@walkeros/core 3.0.2 → 3.1.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.
- package/dist/dev.d.mts +329 -12
- package/dist/dev.d.ts +329 -12
- package/dist/dev.js +1 -1
- package/dist/dev.js.map +1 -1
- package/dist/dev.mjs +1 -1
- package/dist/dev.mjs.map +1 -1
- package/dist/index.d.mts +161 -87
- package/dist/index.d.ts +161 -87
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/collector.ts","../src/types/context.ts","../src/types/destination.ts","../src/types/elb.ts","../src/types/flow.ts","../src/types/hooks.ts","../src/types/logger.ts","../src/types/mapping.ts","../src/types/on.ts","../src/types/transformer.ts","../src/types/request.ts","../src/types/source.ts","../src/types/store.ts","../src/types/lifecycle.ts","../src/types/walkeros.ts","../src/types/simulation.ts","../src/types/matcher.ts","../src/types/hint.ts","../src/types/storage.ts","../src/branch.ts","../src/anonymizeIP.ts","../src/throwError.ts","../src/contract.ts","../src/flow.ts","../src/assign.ts","../src/is.ts","../src/clone.ts","../src/byPath.ts","../src/castValue.ts","../src/consent.ts","../src/createDestination.ts","../src/eventGenerator.ts","../src/getId.ts","../src/getMarketingParameters.ts","../src/invocations.ts","../src/logger.ts","../src/property.ts","../src/tryCatch.ts","../src/mapping.ts","../src/mockEnv.ts","../src/mockLogger.ts","../src/request.ts","../src/send.ts","../src/trim.ts","../src/useHooks.ts","../src/userAgent.ts","../src/wrapInlineCode.ts","../src/cdn.ts","../src/mcpHelpers.ts","../src/respond.ts","../src/matcher.ts"],"sourcesContent":["import type {\n Source,\n Destination,\n Store,\n Elb as ElbTypes,\n Hooks,\n Logger,\n On,\n Transformer,\n WalkerOS,\n Mapping,\n} from '.';\n\n/**\n * Core collector configuration interface\n */\nexport interface Config {\n /** Whether to run collector automatically */\n run?: boolean;\n /** Version for event tagging */\n tagging: number;\n /** Static global properties even on a new run */\n globalsStatic: WalkerOS.Properties;\n /** Static session data even on a new run */\n sessionStatic: Partial<SessionData>;\n /** Logger configuration */\n logger?: Logger.Config;\n}\n\n/**\n * Initialization configuration that extends Config with initial state\n */\nexport interface InitConfig extends Partial<Config> {\n /** Initial consent state */\n consent?: WalkerOS.Consent;\n /** Initial user data */\n user?: WalkerOS.User;\n /** Initial global properties */\n globals?: WalkerOS.Properties;\n /** Source configurations */\n sources?: Source.InitSources;\n /** Destination configurations */\n destinations?: Destination.InitDestinations;\n /** Transformer configurations */\n transformers?: Transformer.InitTransformers;\n /** Store configurations */\n stores?: Store.InitStores;\n /** Initial custom properties */\n custom?: WalkerOS.Properties;\n}\n\nexport interface SessionData extends WalkerOS.Properties {\n isStart: boolean;\n storage: boolean;\n id?: string;\n start?: number;\n marketing?: true;\n updated?: number;\n isNew?: boolean;\n device?: string;\n count?: number;\n runs?: number;\n}\n\nexport interface Status {\n startedAt: number;\n in: number;\n out: number;\n failed: number;\n sources: Record<string, SourceStatus>;\n destinations: Record<string, DestinationStatus>;\n}\n\nexport interface SourceStatus {\n count: number;\n lastAt?: number;\n duration: number;\n}\n\nexport interface DestinationStatus {\n count: number;\n failed: number;\n lastAt?: number;\n duration: number;\n}\n\nexport interface Sources {\n [id: string]: Source.Instance;\n}\n\nexport interface Destinations {\n [id: string]: Destination.Instance;\n}\n\nexport interface Transformers {\n [id: string]: Transformer.Instance;\n}\n\nexport interface Stores {\n [id: string]: Store.Instance;\n}\n\nexport type CommandType =\n | 'action'\n | 'config'\n | 'consent'\n | 'context'\n | 'destination'\n | 'elb'\n | 'globals'\n | 'hook'\n | 'init'\n | 'link'\n | 'run'\n | 'user'\n | 'walker'\n | string;\n\n/**\n * Options passed to collector.push() from sources.\n * NOT a Context - just push metadata.\n */\nexport interface PushOptions {\n id?: string;\n ingest?: unknown;\n respond?: import('../respond').RespondFn;\n mapping?: Mapping.Config;\n preChain?: string[];\n}\n\n/**\n * Push function signature - handles events only\n */\nexport interface PushFn {\n (\n event: WalkerOS.DeepPartialEvent,\n options?: PushOptions,\n ): Promise<ElbTypes.PushResult>;\n}\n\n/**\n * Command function signature - handles walker commands only\n */\nexport interface CommandFn {\n (command: 'config', config: Partial<Config>): Promise<ElbTypes.PushResult>;\n (command: 'consent', consent: WalkerOS.Consent): Promise<ElbTypes.PushResult>;\n <T extends Destination.Types>(\n command: 'destination',\n destination: Destination.Init<T> | Destination.Instance<T>,\n config?: Destination.Config<T>,\n ): Promise<ElbTypes.PushResult>;\n <K extends keyof Hooks.Functions>(\n command: 'hook',\n name: K,\n hookFn: Hooks.Functions[K],\n ): Promise<ElbTypes.PushResult>;\n (\n command: 'on',\n type: On.Types,\n rules: WalkerOS.SingleOrArray<On.Options>,\n ): Promise<ElbTypes.PushResult>;\n (command: 'user', user: WalkerOS.User): Promise<ElbTypes.PushResult>;\n (\n command: 'run',\n runState?: {\n consent?: WalkerOS.Consent;\n user?: WalkerOS.User;\n globals?: WalkerOS.Properties;\n custom?: WalkerOS.Properties;\n },\n ): Promise<ElbTypes.PushResult>;\n (\n command: string,\n data?: unknown,\n options?: unknown,\n ): Promise<ElbTypes.PushResult>;\n}\n\n// Main Collector interface\nexport interface Instance {\n push: PushFn;\n command: CommandFn;\n allowed: boolean;\n config: Config;\n consent: WalkerOS.Consent;\n count: number;\n custom: WalkerOS.Properties;\n sources: Sources;\n destinations: Destinations;\n transformers: Transformers;\n stores: Stores;\n globals: WalkerOS.Properties;\n group: string;\n hooks: Hooks.Functions;\n logger: Logger.Instance;\n on: On.OnConfig;\n queue: WalkerOS.Events;\n round: number;\n session: undefined | SessionData;\n status: Status;\n timing: number;\n user: WalkerOS.User;\n version: string;\n pending: {\n sources: Source.InitSources;\n destinations: Destination.InitDestinations;\n };\n}\n","import type { Collector, Logger } from '.';\n\n/**\n * Base context interface for walkerOS stages.\n * Sources, Transformers, and Destinations extend this.\n */\nexport interface Base<C = unknown, E = unknown> {\n collector: Collector.Instance;\n logger: Logger.Instance;\n config: C;\n env: E;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n Collector,\n Logger,\n Mapping as WalkerOSMapping,\n On,\n WalkerOS,\n Context as BaseContext,\n} from '.';\nimport type { DestroyFn } from './lifecycle';\n\n/**\n * Base environment requirements interface for walkerOS destinations\n *\n * This defines the core interface that destinations can use to declare\n * their runtime environment requirements. Platform-specific extensions\n * should extend this interface.\n */\nexport interface BaseEnv {\n /**\n * Generic global properties that destinations may require\n * Platform-specific implementations can extend this interface\n */\n [key: string]: unknown;\n}\n\n/**\n * Type bundle for destination generics.\n * Groups Settings, InitSettings, Mapping, and Env into a single type parameter.\n */\nexport interface Types<S = unknown, M = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n mapping: M;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n mapping: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n config: Config<T>;\n queuePush?: WalkerOS.Events;\n queueOn?: Array<{ type: On.Types; data?: unknown }>;\n dlq?: DLQ;\n batches?: BatchRegistry<Mapping<T>>;\n type?: string;\n env?: Env<T>;\n init?: InitFn<T>;\n push: PushFn<T>;\n pushBatch?: PushBatchFn<T>;\n on?: On.OnFn;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport interface Config<T extends TypesGeneric = Types> {\n /** Required consent states to push events; queues events when not granted. */\n consent?: WalkerOS.Consent;\n /** Implementation-specific configuration passed to the init function. */\n settings?: InitSettings<T>;\n /** Global data transformation applied to all events; result passed as context.data to push. */\n data?: WalkerOSMapping.Value | WalkerOSMapping.Values;\n /** Runtime dependencies merged from code and config env; extensible per destination. */\n env?: Env<T>;\n /** Destination identifier; auto-generated if not provided. */\n id?: string;\n /** Whether the destination has been initialized; prevents re-initialization. */\n init?: boolean;\n /** Whether to load external scripts (e.g., gtag.js); destination-specific behavior. */\n loadScript?: boolean;\n /** Logger configuration (level, handler) to override the collector's defaults. */\n logger?: Logger.Config;\n /** Entity-action rules to filter, rename, transform, and batch events for this destination. */\n mapping?: WalkerOSMapping.Rules<WalkerOSMapping.Rule<Mapping<T>>>;\n /** Pre-processing rules applied to all events before mapping; modifies events in-place. */\n policy?: Policy;\n /** Whether to queue events when consent is not granted; defaults to true. */\n queue?: boolean;\n /** Defer destination initialization until these collector events fire (e.g., `['consent']`). */\n require?: string[];\n /** Transformer chain to run after collector processing but before this destination. */\n before?: string | string[];\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n Types<\n Partial<Settings<T>> | Settings<T>,\n Partial<Mapping<T>> | Mapping<T>,\n Env<T>\n >\n>;\n\nexport interface Policy {\n [key: string]: WalkerOSMapping.Value;\n}\n\nexport type Code<T extends TypesGeneric = Types> = Instance<T>;\n\nexport type Init<T extends TypesGeneric = Types> = {\n code: Code<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n before?: string | string[];\n};\n\nexport interface InitDestinations {\n [key: string]: Init<any>;\n}\n\nexport interface Destinations {\n [key: string]: Instance;\n}\n\n/**\n * Context provided to destination functions.\n * Extends base context with destination-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n data?: Data;\n}\n\nexport interface PushContext<\n T extends TypesGeneric = Types,\n> extends Context<T> {\n ingest?: unknown;\n rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport interface PushBatchContext<\n T extends TypesGeneric = Types,\n> extends Context<T> {\n ingest?: unknown;\n rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type PushFn<T extends TypesGeneric = Types> = (\n event: WalkerOS.Event,\n context: PushContext<T>,\n) => WalkerOS.PromiseOrValue<void | unknown>;\n\nexport type PushBatchFn<T extends TypesGeneric = Types> = (\n batch: Batch<Mapping<T>>,\n context: PushBatchContext<T>,\n) => void;\n\nexport type PushEvent<Mapping = unknown> = {\n event: WalkerOS.Event;\n mapping?: WalkerOSMapping.Rule<Mapping>;\n};\nexport type PushEvents<Mapping = unknown> = Array<PushEvent<Mapping>>;\n\nexport interface Batch<Mapping> {\n key: string;\n events: WalkerOS.Events;\n data: Array<Data>;\n mapping?: WalkerOSMapping.Rule<Mapping>;\n}\n\nexport interface BatchRegistry<Mapping> {\n [mappingKey: string]: {\n batched: Batch<Mapping>;\n batchFn: () => void;\n };\n}\n\nexport type Data =\n | WalkerOS.Property\n | undefined\n | Array<WalkerOS.Property | undefined>;\n\nexport interface Ref {\n type: string; // Destination type (\"gtag\", \"meta\", \"bigquery\")\n data?: unknown; // Response from push()\n error?: unknown; // Error if failed\n}\n\nexport type Push = {\n queuePush?: WalkerOS.Events;\n error?: unknown;\n};\n\nexport type DLQ = Array<[WalkerOS.Event, unknown]>;\n","import type { Destination, Hooks, On, WalkerOS } from '.';\n\n// Event signatures only\nexport interface EventFn<R = Promise<PushResult>> {\n (partialEvent: WalkerOS.DeepPartialEvent): R;\n (event: string): R;\n (event: string, data: WalkerOS.Properties): R;\n}\n\n// Complete function interface - can be extended by other interfaces\nexport interface Fn<R = Promise<PushResult>, Config = unknown>\n extends EventFn<R>, WalkerCommands<R, Config> {\n // Interface intentionally empty - combines EventFn and WalkerCommands\n}\n\n// Walker commands (clear, predefined list)\nexport interface WalkerCommands<R = Promise<PushResult>, Config = unknown> {\n (event: 'walker config', config: Partial<Config>): R;\n (event: 'walker consent', consent: WalkerOS.Consent): R;\n <T extends Destination.Types>(\n event: 'walker destination',\n destination: Destination.Init<T> | Destination.Instance<T>,\n config?: Destination.Config<T>,\n ): R;\n <K extends keyof Hooks.Functions>(\n event: 'walker hook',\n name: K,\n hookFn: Hooks.Functions[K],\n ): R;\n (\n event: 'walker on',\n type: On.Types,\n rules: WalkerOS.SingleOrArray<On.Options>,\n ): R;\n (event: 'walker user', user: WalkerOS.User): R;\n (\n event: 'walker run',\n runState: {\n consent?: WalkerOS.Consent;\n user?: WalkerOS.User;\n globals?: WalkerOS.Properties;\n custom?: WalkerOS.Properties;\n },\n ): R;\n}\n\nexport type Event<R = Promise<PushResult>> = (\n partialEvent: WalkerOS.DeepPartialEvent,\n) => R;\n\n// Simplified push data types for core collector\nexport type PushData<Config = unknown> =\n | WalkerOS.DeepPartial<Config>\n | WalkerOS.Consent\n | WalkerOS.User\n | WalkerOS.Properties;\n\nexport interface PushResult {\n ok: boolean;\n event?: WalkerOS.Event;\n done?: Record<string, Destination.Ref>;\n queued?: Record<string, Destination.Ref>;\n failed?: Record<string, Destination.Ref>;\n}\n\n// Simplified Layer type for core collector\nexport type Layer = Array<IArguments | WalkerOS.DeepPartialEvent | unknown[]>;\n","/**\n * Flow Configuration System\n *\n * Core types for walkerOS unified configuration.\n * Platform-agnostic, runtime-focused.\n *\n * The Flow system enables \"one config to rule them all\" - a single\n * walkeros.config.json file that manages multiple flows\n * (web_prod, web_stage, server_prod, etc.) with shared configuration,\n * variables, and reusable definitions.\n *\n * ## Connection Rules\n *\n * Sources use `next` to connect to transformers (pre-collector chain).\n * Sources cannot have `before`.\n *\n * Destinations use `before` to connect to transformers (post-collector chain).\n * Destinations cannot have `next`.\n *\n * Transformers use `next` to chain to other transformers. The same transformer\n * pool is shared by both pre-collector and post-collector chains.\n *\n * The collector is implicit — it is never referenced directly in connections.\n * It sits between the source chain and the destination chain automatically.\n *\n * Circular `next` references are safely handled at runtime by `walkChain()`\n * in the collector module (visited-set detection).\n *\n * ```\n * Source → [next → Transformer chain] → Collector → [before → Transformer chain] → Destination\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { Source, Destination, Collector } from '.';\n\n/**\n * JSON Schema object for contract entry validation.\n * Standard JSON Schema with description/examples annotations.\n * Compatible with AJV for runtime validation.\n */\nexport type ContractSchema = Record<string, unknown>;\n\n/**\n * Contract action entries keyed by action name.\n * Each value is a JSON Schema describing the expected WalkerOS.Event shape.\n * Use \"*\" as wildcard for all actions of an entity.\n */\nexport type ContractActions = Record<string, ContractSchema>;\n\n/**\n * Entity-action event map used inside contracts.\n * Keyed by entity name, each value is an action map.\n * Use \"*\" as wildcard for all entities or all actions.\n */\nexport type ContractEvents = Record<string, ContractActions>;\n\n/**\n * A single named contract entry.\n *\n * All sections are optional. Sections mirror WalkerOS.Event fields:\n * globals, context, custom, user, consent.\n * Entity-action schemas live under `events`.\n *\n * Use `extends` to inherit from another named contract (additive merge).\n */\nexport interface ContractEntry {\n /** Inherit from another named contract (additive merge). */\n extends?: string;\n\n /** Contract version number (syncs to event.version.tagging). */\n tagging?: number;\n\n /** Human-readable description of the contract. */\n description?: string;\n\n /** JSON Schema for event.globals. */\n globals?: ContractSchema;\n\n /** JSON Schema for event.context. */\n context?: ContractSchema;\n\n /** JSON Schema for event.custom. */\n custom?: ContractSchema;\n\n /** JSON Schema for event.user. */\n user?: ContractSchema;\n\n /** JSON Schema for event.consent. */\n consent?: ContractSchema;\n\n /** Entity-action event schemas. */\n events?: ContractEvents;\n}\n\n/**\n * Named contract map.\n * Each key is a contract name, each value is a contract entry.\n *\n * Example:\n * ```json\n * {\n * \"default\": { \"globals\": { ... }, \"consent\": { ... } },\n * \"web\": { \"extends\": \"default\", \"events\": { ... } },\n * \"server\": { \"extends\": \"default\", \"events\": { ... } }\n * }\n * ```\n */\nexport type Contract = Record<string, ContractEntry>;\n\n/**\n * Primitive value types for variables\n */\nexport type Primitive = string | number | boolean;\n\n/**\n * Variables record type for interpolation.\n * Used at Config, Settings, Source, and Destination levels.\n */\nexport type Variables = Record<string, Primitive>;\n\n/**\n * Definitions record type for reusable configurations.\n * Used at Config, Settings, Source, and Destination levels.\n */\nexport type Definitions = Record<string, unknown>;\n\n/**\n * Inline code definition for sources/destinations/transformers.\n * Used instead of package when defining inline functions.\n */\nexport interface InlineCode {\n push: string; // \"$code:...\" function (required)\n type?: string; // Optional instance type identifier\n init?: string; // Optional \"$code:...\" init function\n}\n\n/**\n * Packages configuration for build.\n */\nexport type Packages = Record<\n string,\n {\n version?: string;\n imports?: string[];\n path?: string; // Local path to package directory (takes precedence over version)\n }\n>;\n\n/**\n * Web platform configuration.\n *\n * @remarks\n * Presence of this key indicates web platform (browser-based tracking).\n * Builds to IIFE format, ES2020 target, browser platform.\n */\nexport interface Web {\n /**\n * Window property name for collector instance.\n * @default \"collector\"\n */\n windowCollector?: string;\n\n /**\n * Window property name for elb function.\n * @default \"elb\"\n */\n windowElb?: string;\n}\n\n/**\n * Server platform configuration.\n *\n * @remarks\n * Presence of this key indicates server platform (Node.js).\n * Builds to ESM format, Node18 target, node platform.\n * Reserved for future server-specific options.\n */\nexport interface Server {\n // Reserved for future server-specific options\n}\n\n/**\n * Complete multi-flow configuration.\n * Root type for walkeros.config.json files.\n *\n * @remarks\n * If only one flow exists, it's auto-selected without --flow flag.\n * Convention: use \"default\" as the flow name for single-flow configs.\n *\n * @example\n * ```json\n * {\n * \"version\": 3,\n * \"$schema\": \"https://walkeros.io/schema/flow/v3.json\",\n * \"variables\": { \"CURRENCY\": \"USD\" },\n * \"flows\": {\n * \"default\": { \"web\": {}, ... }\n * }\n * }\n * ```\n */\nexport interface Config {\n /**\n * Configuration schema version.\n */\n version: 3;\n\n /**\n * JSON Schema reference for IDE validation.\n * @example \"https://walkeros.io/schema/flow/v1.json\"\n */\n $schema?: string;\n\n /**\n * Folders to include in the bundle output.\n * These folders are copied to dist/ during bundle, making them available\n * at runtime for both local and Docker execution.\n *\n * @remarks\n * Use for credential files, configuration, or other runtime assets.\n * Paths are relative to the config file location.\n * Default: `[\"./shared\"]` if the folder exists, otherwise `[]`.\n *\n * @example\n * ```json\n * {\n * \"include\": [\"./credentials\", \"./config\"]\n * }\n * ```\n */\n include?: string[];\n\n /**\n * Data contract definition (version 2+).\n * Entity → action keyed JSON Schema with additive inheritance.\n */\n contract?: Contract;\n\n /**\n * Shared variables for interpolation.\n * Resolution: destination/source > Settings > Config level\n * Syntax: $var.name\n */\n variables?: Variables;\n\n /**\n * Reusable configuration definitions.\n * Syntax: $def.name\n */\n definitions?: Definitions;\n\n /**\n * Named flow configurations.\n * If only one flow exists, it's auto-selected.\n */\n flows: Record<string, Settings>;\n}\n\n/**\n * Single flow configuration.\n * Represents one deployment target (e.g., web_prod, server_stage).\n *\n * @remarks\n * Platform is determined by presence of `web` or `server` key.\n * Exactly one must be present.\n *\n * Variables/definitions cascade: source/destination > settings > config\n */\nexport interface Settings {\n /**\n * Web platform configuration.\n * Presence indicates web platform (browser-based tracking).\n * Mutually exclusive with `server`.\n */\n web?: Web;\n\n /**\n * Server platform configuration.\n * Presence indicates server platform (Node.js).\n * Mutually exclusive with `web`.\n */\n server?: Server;\n\n /**\n * Store configurations (key-value storage).\n *\n * @remarks\n * Stores provide key-value storage consumed by sources, transformers,\n * and destinations via env injection. Referenced using $store:storeId\n * prefix in env values.\n *\n * Key = unique store identifier (arbitrary)\n * Value = store reference with package and config\n */\n stores?: Record<string, StoreReference>;\n\n /**\n * Source configurations (data capture).\n *\n * @remarks\n * Sources capture events from various origins:\n * - Browser DOM interactions (clicks, page views)\n * - DataLayer pushes\n * - HTTP requests (server-side)\n * - Cloud function triggers\n *\n * Key = unique source identifier (arbitrary)\n * Value = source reference with package and config\n *\n * @example\n * ```json\n * {\n * \"sources\": {\n * \"browser\": {\n * \"package\": \"@walkeros/web-source-browser\",\n * \"config\": {\n * \"settings\": {\n * \"pageview\": true,\n * \"session\": true\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n sources?: Record<string, SourceReference>;\n\n /**\n * Destination configurations (data output).\n *\n * @remarks\n * Destinations send processed events to external services:\n * - Google Analytics (gtag)\n * - Meta Pixel (fbq)\n * - Custom APIs\n * - Data warehouses\n *\n * Key = unique destination identifier (arbitrary)\n * Value = destination reference with package and config\n *\n * @example\n * ```json\n * {\n * \"destinations\": {\n * \"gtag\": {\n * \"package\": \"@walkeros/web-destination-gtag\",\n * \"config\": {\n * \"settings\": {\n * \"ga4\": { \"measurementId\": \"G-XXXXXXXXXX\" }\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n destinations?: Record<string, DestinationReference>;\n\n /**\n * Transformer configurations (event transformation).\n *\n * @remarks\n * Transformers transform events in the pipeline:\n * - Pre-collector: Between sources and collector\n * - Post-collector: Between collector and destinations\n *\n * Key = unique transformer identifier (referenced by source.next or destination.before)\n * Value = transformer reference with package and config\n *\n * @example\n * ```json\n * {\n * \"transformers\": {\n * \"enrich\": {\n * \"package\": \"@walkeros/transformer-enricher\",\n * \"config\": { \"apiUrl\": \"https://api.example.com\" },\n * \"next\": \"validate\"\n * },\n * \"validate\": {\n * \"package\": \"@walkeros/transformer-validator\"\n * }\n * }\n * }\n * ```\n */\n transformers?: Record<string, TransformerReference>;\n\n /**\n * Collector configuration (event processing).\n *\n * @remarks\n * The collector is the central event processing engine.\n * Configuration includes:\n * - Consent management\n * - Global properties\n * - User identification\n * - Processing rules\n *\n * @see {@link Collector.InitConfig} for complete options\n *\n * @example\n * ```json\n * {\n * \"collector\": {\n * \"run\": true,\n * \"tagging\": 1,\n * \"consent\": {\n * \"functional\": true,\n * \"marketing\": false\n * },\n * \"globals\": {\n * \"currency\": \"USD\",\n * \"environment\": \"production\"\n * }\n * }\n * }\n * ```\n */\n collector?: Collector.InitConfig;\n\n /**\n * NPM packages to bundle.\n */\n packages?: Packages;\n\n /**\n * Flow-level variables.\n * Override Config.variables, overridden by source/destination variables.\n */\n variables?: Variables;\n\n /**\n * Flow-level definitions.\n * Extend Config.definitions, overridden by source/destination definitions.\n */\n definitions?: Definitions;\n}\n\n/**\n * Named example pair for a step.\n * `in` is the input to the step, `out` is the expected output.\n * `out: false` indicates the step filters/drops this event.\n */\nexport interface StepExample {\n description?: string;\n in?: unknown;\n mapping?: unknown;\n out?: unknown;\n}\n\n/**\n * Named step examples keyed by scenario name.\n */\nexport type StepExamples = Record<string, StepExample>;\n\n/**\n * Source reference with inline package syntax.\n *\n * @remarks\n * References a source package and provides configuration.\n * The package is automatically downloaded and imported during build.\n * Alternatively, use `code: true` for inline code execution.\n */\nexport interface SourceReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Formats:\n * - `\"@walkeros/web-source-browser\"` - Latest version\n * - `\"@walkeros/web-source-browser@2.0.0\"` - Specific version\n * - `\"@walkeros/web-source-browser@^2.0.0\"` - Semver range\n *\n * The CLI will:\n * 1. Parse the package reference\n * 2. Download from npm\n * 3. Auto-detect default or named export\n * 4. Generate import statement\n *\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/web-source-browser@latest\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code source.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"logger\",\n * \"push\": \"$code:(event) => console.log(event)\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Source-specific configuration.\n *\n * @remarks\n * Structure depends on the source package.\n * Passed to the source's initialization function.\n *\n * @example\n * ```json\n * {\n * \"config\": {\n * \"settings\": {\n * \"pageview\": true,\n * \"session\": true,\n * \"elb\": \"elb\",\n * \"prefix\": \"data-elb\"\n * }\n * }\n * }\n * ```\n */\n config?: unknown;\n\n /**\n * Source environment configuration.\n *\n * @remarks\n * Environment-specific settings for the source.\n * Merged with default source environment.\n */\n env?: unknown;\n\n /**\n * Mark as primary source (provides main ELB).\n *\n * @remarks\n * The primary source's ELB function is returned by `startFlow()`.\n * Only one source should be marked as primary per flow.\n *\n * @default false\n */\n primary?: boolean;\n\n /**\n * Source-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Source-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * First transformer in pre-collector chain.\n *\n * @remarks\n * Name of the transformer to execute after this source captures an event.\n * Creates a pre-collector transformer chain. Chain ends at the collector.\n * If omitted, events route directly to the collector.\n * Can be an array for explicit chain control (bypasses transformer.next resolution).\n */\n next?: string | string[];\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n\n/**\n * Transformer reference with inline package syntax.\n *\n * @remarks\n * References a transformer package and provides configuration.\n * Transformers transform events in the pipeline between sources and destinations.\n * Alternatively, use `code: true` for inline code execution.\n */\nexport interface TransformerReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Same format as SourceReference.package\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/transformer-enricher@1.0.0\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code transformer.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"enricher\",\n * \"push\": \"$code:(event) => ({ ...event, data: { enriched: true } })\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Transformer-specific configuration.\n *\n * @remarks\n * Structure depends on the transformer package.\n * Passed to the transformer's initialization function.\n */\n config?: unknown;\n\n /**\n * Transformer environment configuration.\n *\n * @remarks\n * Environment-specific settings for the transformer.\n * Merged with default transformer environment.\n */\n env?: unknown;\n\n /**\n * Next transformer in chain.\n *\n * @remarks\n * Name of the next transformer to execute after this one.\n * When used in a pre-collector chain (source.next), terminates at the collector.\n * When used in a post-collector chain (destination.before), terminates at the destination.\n * If omitted, the chain ends and control passes to the next pipeline stage.\n * Array values define an explicit chain (no walking). Circular references\n * are safely detected at runtime by `walkChain()`.\n */\n next?: string | string[];\n\n /**\n * Transformer-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Transformer-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n\n/**\n * Store reference with inline package syntax.\n *\n * @remarks\n * References a store package and provides configuration.\n * Stores provide key-value storage consumed by other components via env.\n * Unlike sources/transformers/destinations, stores have no chain properties\n * (no `next` or `before`) — they are passive infrastructure.\n */\nexport interface StoreReference {\n /**\n * Package specifier with optional version.\n * Optional when `code` is provided for inline code.\n */\n package?: string;\n\n /**\n * Resolved import variable name or inline code definition.\n */\n code?: string | InlineCode;\n\n /**\n * Store-specific configuration.\n */\n config?: unknown;\n\n /**\n * Store environment configuration.\n */\n env?: unknown;\n\n /**\n * Store-level variables (highest priority in cascade).\n */\n variables?: Variables;\n\n /**\n * Store-level definitions (highest priority in cascade).\n */\n definitions?: Definitions;\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution.\n */\n examples?: StepExamples;\n}\n\n/**\n * Destination reference with inline package syntax.\n *\n * @remarks\n * References a destination package and provides configuration.\n * Structure mirrors SourceReference for consistency.\n */\nexport interface DestinationReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Same format as SourceReference.package\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/web-destination-gtag@2.0.0\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code destination.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"logger\",\n * \"push\": \"$code:(event) => console.log('Event:', event.name)\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Destination-specific configuration.\n *\n * @remarks\n * Structure depends on the destination package.\n * Typically includes:\n * - settings: API keys, IDs, endpoints\n * - mapping: Event transformation rules\n * - consent: Required consent states\n * - policy: Processing rules\n *\n * @example\n * ```json\n * {\n * \"config\": {\n * \"settings\": {\n * \"ga4\": {\n * \"measurementId\": \"G-XXXXXXXXXX\"\n * }\n * },\n * \"mapping\": {\n * \"page\": {\n * \"view\": {\n * \"name\": \"page_view\",\n * \"data\": { ... }\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n config?: unknown;\n\n /**\n * Destination environment configuration.\n *\n * @remarks\n * Environment-specific settings for the destination.\n * Merged with default destination environment.\n */\n env?: unknown;\n\n /**\n * Destination-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Destination-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * First transformer in post-collector chain.\n *\n * @remarks\n * Name of the transformer to execute before sending events to this destination.\n * Creates a post-collector transformer chain. Chain ends at this destination.\n * If omitted, events are sent directly from the collector.\n * Can be an array for explicit chain control (bypasses transformer.next resolution).\n */\n before?: string | string[];\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n","// Define a generic type for functions with specific parameters and return type\nexport type AnyFunction<P extends unknown[] = never[], R = unknown> = (\n ...args: P\n) => R;\n\n// Define a generic type for a dictionary of functions\nexport type Functions = {\n [key: string]: AnyFunction;\n};\n\n// Define a parameter interface to wrap the function and its result\ninterface Parameter<P extends unknown[], R> {\n fn: (...args: P) => R;\n result?: R;\n}\n\n// Define the HookFn type using generics for better type safety\nexport type HookFn<T extends AnyFunction> = (\n params: Parameter<Parameters<T>, ReturnType<T>>,\n ...args: Parameters<T>\n) => ReturnType<T>;\n","/**\n * Log levels from most to least severe\n */\nexport enum Level {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n}\n\n/**\n * Normalized error context extracted from Error objects\n */\nexport interface ErrorContext {\n message: string;\n name: string;\n stack?: string;\n cause?: unknown;\n}\n\n/**\n * Context passed to log handlers\n * If an Error was passed, it's normalized into the error property\n */\nexport interface LogContext {\n [key: string]: unknown;\n error?: ErrorContext;\n}\n\n/**\n * Log message function signature\n * Accepts string or Error as message, with optional context\n */\nexport type LogFn = (\n message: string | Error,\n context?: unknown | Error,\n) => void;\n\n/**\n * Throw function signature - logs error then throws\n * Returns never as it always throws\n */\nexport type ThrowFn = (message: string | Error, context?: unknown) => never;\n\n/**\n * Default handler function (passed to custom handlers for chaining)\n */\nexport type DefaultHandler = (\n level: Level,\n message: string,\n context: LogContext,\n scope: string[],\n) => void;\n\n/**\n * Custom log handler function\n * Receives originalHandler to allow middleware-style chaining\n */\nexport type Handler = (\n level: Level,\n message: string,\n context: LogContext,\n scope: string[],\n originalHandler: DefaultHandler,\n) => void;\n\n/**\n * Logger instance with scoping support\n * All logs automatically include trace path from scoping\n */\nexport interface Instance {\n /**\n * Log an error message (always visible unless silenced)\n */\n error: LogFn;\n\n /**\n * Log a warning (degraded state, config issues, transient failures)\n */\n warn: LogFn;\n\n /**\n * Log an informational message\n */\n info: LogFn;\n\n /**\n * Log a debug message\n */\n debug: LogFn;\n\n /**\n * Log an error message and throw an Error\n * Combines logging and throwing in one call\n */\n throw: ThrowFn;\n\n /**\n * Output structured JSON data\n */\n json: (data: unknown) => void;\n\n /**\n * Create a scoped child logger with automatic trace path\n * @param name - Scope name (e.g., destination type, destination key)\n * @returns A new logger instance with the scope applied\n */\n scope: (name: string) => Instance;\n}\n\n/**\n * Logger configuration options\n */\nexport interface Config {\n /**\n * Minimum log level to display\n * @default Level.ERROR\n */\n level?: Level | keyof typeof Level;\n\n /**\n * Custom log handler function\n * Receives originalHandler to preserve default behavior\n */\n handler?: Handler;\n\n /** Custom handler for json() output. Default: console.log(JSON.stringify(data, null, 2)) */\n jsonHandler?: (data: unknown) => void;\n}\n\n/**\n * Internal config with resolved values and scope\n */\nexport interface InternalConfig {\n level: Level;\n handler?: Handler;\n jsonHandler?: (data: unknown) => void;\n scope: string[];\n}\n\n/**\n * Logger factory function type\n */\nexport type Factory = (config?: Config) => Instance;\n","import type { Collector, Destination, WalkerOS } from '.';\n\n/**\n * Shared mapping configuration interface.\n * Used by both Source.Config and Destination.Config.\n */\nexport interface Config<T = unknown> {\n consent?: WalkerOS.Consent; // Required consent to process events\n data?: Value | Values; // Global data transformation\n mapping?: Rules<Rule<T>>; // Event-specific mapping rules\n policy?: Policy; // Pre-processing rules\n}\n\nexport interface Policy {\n [key: string]: Value;\n}\n\nexport interface Rules<T = Rule> {\n [entity: string]: Record<string, T | Array<T>> | undefined;\n}\n\nexport interface Rule<Settings = unknown> {\n batch?: number; // Bundle events for batch processing\n batchFn?: (\n destination: Destination.Instance,\n collector: Collector.Instance,\n ) => void;\n batched?: Destination.Batch<Settings>; // Batch of events to be processed\n condition?: Condition; // Added condition\n consent?: WalkerOS.Consent; // Required consent states process the event\n settings?: Settings; // Arbitrary but protected configurations for custom event config\n data?: Data; // Mapping of event data\n ignore?: boolean; // Choose to no process an event when set to true\n name?: string; // Use a custom event name\n policy?: Policy; // Event-level policy applied after config-level policy\n}\n\nexport interface Result {\n eventMapping?: Rule;\n mappingKey?: string;\n}\n\nexport type Data = Value | Values;\nexport type Value = ValueType | Array<ValueType>;\nexport type Values = Array<Value>;\nexport type ValueType = string | ValueConfig;\n\nexport interface ValueConfig {\n condition?: Condition;\n consent?: WalkerOS.Consent;\n fn?: Fn;\n key?: string;\n loop?: Loop;\n map?: Map;\n set?: Value[];\n validate?: Validate;\n value?: WalkerOS.PropertyType;\n}\n\nexport type Condition = (\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping?: Value,\n collector?: Collector.Instance,\n) => WalkerOS.PromiseOrValue<boolean>;\n\nexport type Fn = (\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping: Value,\n options: Options,\n) => WalkerOS.PromiseOrValue<WalkerOS.Property | unknown>;\n\nexport type Loop = [Value, Value];\n\nexport type Map = { [key: string]: Value };\n\nexport interface Options {\n consent?: WalkerOS.Consent;\n collector?: Collector.Instance;\n props?: unknown;\n}\n\nexport type Validate = (value?: unknown) => WalkerOS.PromiseOrValue<boolean>;\n","import type { Collector, Destination, WalkerOS } from './';\n\n// collector state for the on actions\nexport type Config = {\n config?: Array<GenericConfig>;\n consent?: Array<ConsentConfig>;\n custom?: Array<GenericConfig>;\n globals?: Array<GenericConfig>;\n ready?: Array<ReadyConfig>;\n run?: Array<RunConfig>;\n session?: Array<SessionConfig>;\n user?: Array<UserConfig>;\n};\n\n// On types — allow arbitrary string events via `(string & {})`\nexport type Types = keyof Config | (string & {});\n\n// Map each event type to its expected context type\nexport interface EventContextMap {\n config: Partial<Collector.Config>;\n consent: WalkerOS.Consent;\n custom: WalkerOS.Properties;\n globals: WalkerOS.Properties;\n ready: undefined;\n run: undefined;\n session: Collector.SessionData;\n user: WalkerOS.User;\n}\n\n// Extract the context type for a specific event\nexport type EventContext<T extends keyof EventContextMap> = EventContextMap[T];\n\n// Union of all possible context types\nexport type AnyEventContext = EventContextMap[keyof EventContextMap];\n\n// Legacy context interface (can be removed in future)\nexport interface Context {\n consent?: WalkerOS.Consent;\n session?: unknown;\n}\n\n// Parameters for the onAction function calls\nexport type Options =\n | ConsentConfig\n | GenericConfig\n | ReadyConfig\n | RunConfig\n | SessionConfig\n | UserConfig;\n\n// Consent\nexport interface ConsentConfig {\n [key: string]: ConsentFn;\n}\nexport type ConsentFn = (\n collector: Collector.Instance,\n consent: WalkerOS.Consent,\n) => void;\n\n// Generic (config, custom, globals)\nexport type GenericConfig = GenericFn;\nexport type GenericFn = (collector: Collector.Instance, data: unknown) => void;\n\n// Ready\nexport type ReadyConfig = ReadyFn;\nexport type ReadyFn = (collector: Collector.Instance) => void;\n\n// Run\nexport type RunConfig = RunFn;\nexport type RunFn = (collector: Collector.Instance) => void;\n\n// Session\nexport type SessionConfig = SessionFn;\nexport type SessionFn = (\n collector: Collector.Instance,\n session?: unknown,\n) => void;\n\n// User\nexport type UserConfig = UserFn;\nexport type UserFn = (\n collector: Collector.Instance,\n user: WalkerOS.User,\n) => void;\n\nexport interface OnConfig {\n config?: GenericConfig[];\n consent?: ConsentConfig[];\n custom?: GenericConfig[];\n globals?: GenericConfig[];\n ready?: ReadyConfig[];\n run?: RunConfig[];\n session?: SessionConfig[];\n user?: UserConfig[];\n [key: string]:\n | ConsentConfig[]\n | GenericConfig[]\n | ReadyConfig[]\n | RunConfig[]\n | SessionConfig[]\n | UserConfig[]\n | undefined;\n}\n\n// Destination on function type with automatic type inference\nexport type OnFn<T extends Destination.TypesGeneric = Destination.Types> = (\n type: Types,\n context: Destination.Context<T>,\n) => WalkerOS.PromiseOrValue<void>;\n\n// Runtime-compatible version for internal usage\nexport type OnFnRuntime = (\n type: Types,\n context: Destination.Context,\n) => WalkerOS.PromiseOrValue<void>;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Collector, Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn } from './lifecycle';\n\nexport type Next = string | string[];\n\n/**\n * Base environment interface for walkerOS transformers.\n *\n * Minimal like Destination - just an extensible object.\n * Transformers receive dependencies through context, not env.\n */\nexport interface BaseEnv {\n [key: string]: unknown;\n}\n\n/**\n * Type bundle for transformer generics.\n * Groups Settings, InitSettings, and Env into a single type parameter.\n * Follows the Source/Destination pattern.\n *\n * @template S - Settings configuration type\n * @template E - Environment type\n * @template I - InitSettings configuration type (user input)\n */\nexport interface Types<S = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access.\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle.\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance.\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\n/**\n * Transformer configuration.\n */\nexport interface Config<T extends TypesGeneric = Types> {\n settings?: InitSettings<T>;\n env?: Env<T>;\n id?: string;\n logger?: Logger.Config;\n next?: Next; // Graph wiring to next transformer\n init?: boolean; // Track init state (like Destination)\n}\n\n/**\n * Context provided to transformer functions.\n * Extends base context with transformer-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n ingest?: unknown;\n}\n\n/**\n * Unified result type for transformer functions.\n * Replaces the old union return type with a structured object.\n *\n * @field event - Modified event to continue with\n * @field respond - Wrapped respond function for downstream transformers\n * @field next - Branch to a different chain (replaces BranchResult)\n */\nexport interface Result {\n event?: WalkerOS.DeepPartialEvent;\n respond?: import('../respond').RespondFn;\n next?: Next;\n}\n\n/**\n * The main transformer function.\n * Uses DeepPartialEvent for consistency across pre/post collector.\n *\n * @param event - The event to process\n * @param context - Transformer context with collector, config, env, logger\n * @returns Result - structured result with event, respond, next\n * @returns void - continue with current event unchanged (passthrough)\n * @returns false - stop chain, cancel further processing\n */\nexport type Fn<T extends TypesGeneric = Types> = (\n event: WalkerOS.DeepPartialEvent,\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<Result | false | void>;\n\n/**\n * Optional initialization function.\n * Called once before first push.\n *\n * @param context - Transformer context\n * @returns void - initialization successful\n * @returns false - initialization failed, skip this transformer\n * @returns Config<T> - return updated config\n */\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\n/**\n * Transformer instance returned by Init function.\n */\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n push: Fn<T>; // Named \"push\" for consistency with Source/Destination\n init?: InitFn<T>; // Optional, called once before first push\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\n/**\n * Transformer initialization function.\n * Creates a transformer instance from context.\n */\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\n/**\n * Configuration for initializing a transformer.\n * Used in collector registration.\n */\nexport type InitTransformer<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n next?: Next;\n};\n\n/**\n * Transformers configuration for collector.\n * Maps transformer IDs to their initialization configurations.\n */\nexport interface InitTransformers {\n [transformerId: string]: InitTransformer<any>;\n}\n\n/**\n * Active transformer instances registry.\n */\nexport interface Transformers {\n [transformerId: string]: Instance;\n}\n","export interface Context {\n city?: string;\n country?: string;\n encoding?: string;\n hash?: string;\n ip?: string;\n language?: string;\n origin?: string;\n region?: string;\n userAgent?: string;\n [key: string]: string | undefined;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n Elb,\n On,\n Logger,\n Mapping as WalkerOSMapping,\n Collector,\n Context as BaseContext,\n} from './index';\nimport type { DestroyFn } from './lifecycle';\nimport type { Next } from './transformer';\n\n/**\n * Base Env interface for dependency injection into sources.\n *\n * Sources receive all their dependencies through this environment object,\n * making them platform-agnostic and easily testable.\n */\nexport interface BaseEnv {\n [key: string]: unknown;\n push: Collector.PushFn;\n command: Collector.CommandFn;\n sources?: Collector.Sources;\n elb: Elb.Fn;\n logger: Logger.Instance;\n}\n\n/**\n * Type bundle for source generics.\n * Groups Settings, Mapping, Push, Env, and InitSettings into a single type parameter.\n *\n * @template S - Settings configuration type\n * @template M - Mapping configuration type\n * @template P - Push function signature (flexible to support HTTP handlers, etc.)\n * @template E - Environment dependencies type\n * @template I - InitSettings configuration type (user input)\n */\nexport interface Types<\n S = unknown,\n M = unknown,\n P = Elb.Fn,\n E = BaseEnv,\n I = S,\n> {\n settings: S;\n initSettings: I;\n mapping: M;\n push: P;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n mapping: any;\n push: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Push<T extends TypesGeneric = Types> = T['push'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<\n T extends TypesGeneric = Types,\n> extends WalkerOSMapping.Config<Mapping<T>> {\n /** Implementation-specific configuration passed to the init function. */\n settings?: InitSettings<T>;\n /** Runtime dependencies injected by the collector (push, command, logger, etc.). */\n env?: Env<T>;\n /** Source identifier; defaults to the InitSources object key. */\n id?: string;\n /** Logger configuration (level, handler) to override the collector's defaults. */\n logger?: Logger.Config;\n /** Mark as primary source; its push function becomes the exported `elb` from startFlow. */\n primary?: boolean;\n /** Defer source initialization until these collector events fire (e.g., `['consent']`). */\n require?: string[];\n /**\n * Ingest metadata extraction mapping.\n * Extracts values from raw request objects (Express req, Lambda event, etc.)\n * using walkerOS mapping syntax. Extracted data flows to transformers/destinations.\n *\n * @example\n * ingest: {\n * ip: 'req.ip',\n * ua: 'req.headers.user-agent',\n * origin: 'req.headers.origin'\n * }\n */\n ingest?: WalkerOSMapping.Data;\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n Types<\n Partial<Settings<T>> | Settings<T>,\n Partial<Mapping<T>> | Mapping<T>,\n Push<T>,\n Env<T>\n >\n>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n push: Push<T>;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n on?(\n event: On.Types,\n context?: unknown,\n ): void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Context provided to source init function.\n * Extends base context with source-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Partial<Config<T>>, Env<T>> {\n id: string;\n /**\n * Sets ingest metadata for the current request.\n * Extracts values from the raw request using config.ingest mapping.\n * The extracted data is passed through to transformers and destinations.\n *\n * @param value - Raw request object (Express req, Lambda event, etc.)\n */\n setIngest: (value: unknown) => Promise<void>;\n /** Sets respond function for the current request. Called by source per-request. */\n setRespond: (fn: import('../respond').RespondFn | undefined) => void;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitSource<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n primary?: boolean;\n next?: Next;\n};\n\n/**\n * Sources configuration for collector.\n * Maps source IDs to their initialization configurations.\n */\nexport interface InitSources {\n [sourceId: string]: InitSource<any>;\n}\n\n/**\n * Renderer hint for source simulation UI.\n * - 'browser': Source needs a real DOM (iframe with live preview)\n * - 'codebox': Source uses a JSON/code editor (default)\n */\nexport type Renderer = 'browser' | 'codebox';\n\n/**\n * Minimal environment contract for source simulation.\n * Both JSDOM and iframe satisfy this interface.\n */\nexport interface SimulationEnv {\n window: Window & typeof globalThis;\n document: Document;\n localStorage: Storage;\n [key: string]: unknown;\n}\n\n/**\n * Setup function for source simulation.\n * Runs BEFORE startFlow() to prepare the environment\n * (dataLayer arrays, localStorage, window globals).\n *\n * Return void for sources that need no post-init action.\n * Return a () => void trigger for sources that dispatch\n * events AFTER startFlow() (e.g., usercentrics CustomEvent).\n */\nexport type SetupFn = (\n input: unknown,\n env: SimulationEnv,\n) => void | (() => void);\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn } from './lifecycle';\n\nexport interface BaseEnv {\n [key: string]: unknown;\n}\n\nexport interface Types<S = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n env: E;\n}\n\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n env: any;\n};\n\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<T extends TypesGeneric = Types> {\n settings?: InitSettings<T>;\n env?: Env<T>;\n id?: string;\n logger?: Logger.Config;\n}\n\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n}\n\nexport type GetFn<T = unknown> = (\n key: string,\n) => T | undefined | Promise<T | undefined>;\n\nexport type SetFn<T = unknown> = (\n key: string,\n value: T,\n ttl?: number,\n) => void | Promise<void>;\n\nexport type DeleteFn = (key: string) => void | Promise<void>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n get: GetFn;\n set: SetFn;\n delete: DeleteFn;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type InitStore<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n};\n\nexport interface InitStores {\n [storeId: string]: InitStore<any>;\n}\n\nexport interface Stores {\n [storeId: string]: Instance;\n}\n","// packages/core/src/types/lifecycle.ts\nimport type { Logger, WalkerOS } from '.';\n\n/**\n * Context provided to the destroy() lifecycle method.\n *\n * A subset of the init context — config, env, logger, and id.\n * Does NOT include collector or event data. Destroy should only\n * clean up resources, not interact with the event pipeline.\n */\nexport interface DestroyContext<C = unknown, E = unknown> {\n /** Step instance ID. */\n id: string;\n /** Step configuration (contains settings with SDK clients, etc.). */\n config: C;\n /** Runtime environment/dependencies (DB clients, auth clients, etc.). */\n env: E;\n /** Scoped logger for this step instance. */\n logger: Logger.Instance;\n}\n\n/**\n * Destroy function signature for step lifecycle cleanup.\n *\n * Implementations should be idempotent — calling destroy() twice must not throw.\n * Used for closing connections, clearing timers, releasing SDK clients.\n */\nexport type DestroyFn<C = unknown, E = unknown> = (\n context: DestroyContext<C, E>,\n) => WalkerOS.PromiseOrValue<void>;\n","import type { Elb as ElbTypes } from '.';\n\nexport type AnyObject<T = unknown> = Record<string, T>;\nexport type Elb = ElbTypes.Fn;\nexport type AnyFunction = (...args: unknown[]) => unknown;\nexport type SingleOrArray<T> = T | Array<T>;\n\nexport type Events = Array<Event>;\nexport type PartialEvent = Partial<Event>;\nexport type DeepPartialEvent = DeepPartial<Event>;\nexport interface Event {\n name: string;\n data: Properties;\n context: OrderedProperties;\n globals: Properties;\n custom: Properties;\n user: User;\n nested: Entities;\n consent: Consent;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n group: string;\n count: number;\n version: Version;\n source: Source;\n}\n\nexport interface Consent {\n [name: string]: boolean; // name of consent group or tool\n}\n\nexport interface User extends Properties {\n // IDs\n id?: string;\n device?: string;\n session?: string;\n hash?: string;\n // User related\n address?: string;\n email?: string;\n phone?: string;\n userAgent?: string;\n browser?: string;\n browserVersion?: string;\n deviceType?: string;\n language?: string;\n country?: string;\n region?: string;\n city?: string;\n zip?: string;\n timezone?: string;\n os?: string;\n osVersion?: string;\n screenSize?: string;\n ip?: string;\n internal?: boolean;\n}\n\nexport interface Version extends Properties {\n source: string;\n tagging: number;\n}\n\nexport interface Source extends Properties {\n type: SourceType;\n id: string; // https://github.com/elbwalker/walkerOS\n previous_id: string; // https://www.elbwalker.com/\n}\n\nexport type SourceType = 'web' | 'server' | 'app' | 'other' | string;\n\nexport type PropertyType =\n | boolean\n | string\n | number\n | { [key: string]: Property };\n\nexport type Property = PropertyType | Array<PropertyType>;\n\nexport interface Properties {\n [key: string]: Property | undefined;\n}\nexport interface OrderedProperties {\n [key: string]: [Property, number] | undefined;\n}\n\nexport type Entities = Array<Entity>;\nexport interface Entity {\n entity: string;\n data: Properties;\n nested: Entities;\n context: OrderedProperties;\n}\n\nexport type ConsentHandler = Record<string, AnyFunction>;\nexport type ActionHandler = AnyFunction;\n\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type PromiseOrValue<T> = T | Promise<T>;\n","import type { WalkerOS } from '.';\n\n/**\n * A recorded function call made during simulation.\n * Captures what a destination called on its env (e.g., window.gtag).\n */\nexport interface Call {\n /** Dot-path of the function called: \"window.gtag\", \"dataLayer.push\" */\n fn: string;\n /** Arguments passed to the function */\n args: unknown[];\n /** Unix timestamp in ms */\n ts: number;\n}\n\n/**\n * Result of simulating a single step.\n * Same shape for source, transformer, and destination.\n */\nexport interface Result {\n /** Which step type was simulated */\n step: 'source' | 'transformer' | 'destination';\n /** Step name, e.g. \"gtag\", \"dataLayer\", \"enricher\" */\n name: string;\n /**\n * Output events:\n * - source: captured pre-collector events\n * - transformer: [transformed event] or [] if filtered\n * - destination: [] (destinations don't produce events)\n */\n events: WalkerOS.DeepPartialEvent[];\n /** Intercepted env calls. Populated for destinations, empty [] for others. */\n calls: Call[];\n /** Execution time in ms */\n duration: number;\n /** Error if the step threw */\n error?: Error;\n}\n","export type MatchExpression =\n | MatchCondition\n | { and: MatchExpression[] }\n | { or: MatchExpression[] };\n\nexport interface MatchCondition {\n key: string;\n operator: MatchOperator;\n value: string;\n not?: boolean;\n}\n\nexport type MatchOperator =\n | 'eq'\n | 'contains'\n | 'prefix'\n | 'suffix'\n | 'regex'\n | 'gt'\n | 'lt'\n | 'exists';\n\n// Compiled matcher (internal)\nexport type CompiledMatcher = (ingest: Record<string, unknown>) => boolean;\n","export interface Code {\n lang?: string;\n code: string;\n}\n\nexport interface Hint {\n text: string;\n code?: Array<Code>;\n}\n\nexport type Hints = Record<string, Hint>;\n","export type StorageType = 'local' | 'session' | 'cookie';\n\nexport const Storage = {\n Local: 'local' as const,\n Session: 'session' as const,\n Cookie: 'cookie' as const,\n} as const;\n\nexport const Const = {\n Utils: {\n Storage,\n },\n} as const;\n","import type { Transformer, WalkerOS } from './types';\n\n/**\n * Creates a TransformerResult for dynamic chain routing.\n * Use this in transformer push functions to redirect the chain.\n */\nexport function branch(\n event: WalkerOS.DeepPartialEvent,\n next: Transformer.Next,\n): Transformer.Result {\n return { event, next };\n}\n","/**\n * Anonymizes an IPv4 address by setting the last octet to 0.\n *\n * @param ip The IP address to anonymize.\n * @returns The anonymized IP address or an empty string if the IP is invalid.\n */\nexport function anonymizeIP(ip: string): string {\n const ipv4Pattern = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\n\n if (!ipv4Pattern.test(ip)) return '';\n\n return ip.replace(/\\.\\d+$/, '.0'); // Set the last octet to 0\n}\n","/**\n * Throws an error.\n *\n * @param error The error to throw.\n */\nexport function throwError(error: unknown): never {\n throw new Error(String(error));\n}\n","import type { Flow } from './types';\nimport { throwError } from './throwError';\n\n/** Section keys that map to WalkerOS.Event fields. */\nconst SECTION_KEYS = [\n 'globals',\n 'context',\n 'custom',\n 'user',\n 'consent',\n] as const;\n\n/** Annotation keys to strip from AJV-compatible schemas. */\nconst ANNOTATION_KEYS = new Set([\n 'description',\n 'examples',\n 'title',\n '$comment',\n]);\n\n/**\n * Resolve all named contracts: process extends chains, expand wildcards,\n * strip annotations from event schemas.\n *\n * Returns a fully resolved map where each contract entry has inherited\n * properties merged in and wildcards expanded into concrete actions.\n */\nexport function resolveContracts(\n contracts: Flow.Contract,\n): Record<string, Flow.ContractEntry> {\n const resolved: Record<string, Flow.ContractEntry> = {};\n const resolving = new Set<string>(); // Circular detection\n\n function resolve(name: string): Flow.ContractEntry {\n if (resolved[name]) return resolved[name];\n\n if (resolving.has(name)) {\n throwError(\n `Circular extends chain detected: ${[...resolving, name].join(' → ')}`,\n );\n }\n\n const entry = contracts[name];\n if (!entry) {\n throwError(`Contract \"${name}\" not found`);\n }\n\n resolving.add(name);\n\n let result: Flow.ContractEntry = {};\n\n // 1. Resolve parent first (if extends)\n if (entry.extends) {\n const parent = resolve(entry.extends);\n result = mergeContractEntries(parent, entry);\n } else {\n result = { ...entry };\n }\n\n // Remove extends from resolved entry\n delete result.extends;\n\n // 2. Expand wildcards in events\n if (result.events) {\n result.events = expandWildcards(result.events);\n }\n\n // 3. Strip annotations from event schemas (not from section schemas)\n if (result.events) {\n const stripped: Flow.ContractEvents = {};\n for (const [entity, actions] of Object.entries(result.events)) {\n stripped[entity] = {};\n for (const [action, schema] of Object.entries(actions)) {\n stripped[entity][action] = stripAnnotations(schema);\n }\n }\n result.events = stripped;\n }\n\n resolving.delete(name);\n resolved[name] = result;\n return result;\n }\n\n // Resolve all contracts\n for (const name of Object.keys(contracts)) {\n resolve(name);\n }\n\n return resolved;\n}\n\n/**\n * Merge two contract entries additively.\n * Sections merge via mergeContractSchemas.\n * Events merge at the entity-action level.\n * Metadata: child wins for scalars.\n */\nfunction mergeContractEntries(\n parent: Flow.ContractEntry,\n child: Flow.ContractEntry,\n): Flow.ContractEntry {\n const result: Flow.ContractEntry = {};\n\n // Merge metadata (child wins)\n if (parent.tagging !== undefined || child.tagging !== undefined) {\n result.tagging = child.tagging ?? parent.tagging;\n }\n if (parent.description !== undefined || child.description !== undefined) {\n result.description = child.description ?? parent.description;\n }\n\n // Merge sections additively\n for (const key of SECTION_KEYS) {\n const p = parent[key];\n const c = child[key];\n if (p && c) {\n result[key] = mergeContractSchemas(\n p as Record<string, unknown>,\n c as Record<string, unknown>,\n );\n } else if (p || c) {\n result[key] = { ...((p || c) as Record<string, unknown>) };\n }\n }\n\n // Merge events\n if (parent.events || child.events) {\n const merged: Flow.ContractEvents = {};\n const allEntities = new Set([\n ...Object.keys(parent.events || {}),\n ...Object.keys(child.events || {}),\n ]);\n\n for (const entity of allEntities) {\n const pActions = parent.events?.[entity] || {};\n const cActions = child.events?.[entity] || {};\n const allActions = new Set([\n ...Object.keys(pActions),\n ...Object.keys(cActions),\n ]);\n\n merged[entity] = {};\n for (const action of allActions) {\n const pSchema = pActions[action];\n const cSchema = cActions[action];\n if (pSchema && cSchema) {\n merged[entity][action] = mergeContractSchemas(\n pSchema as Record<string, unknown>,\n cSchema as Record<string, unknown>,\n );\n } else {\n merged[entity][action] = {\n ...((pSchema || cSchema) as Record<string, unknown>),\n };\n }\n }\n }\n\n result.events = merged;\n }\n\n return result;\n}\n\n/**\n * Expand wildcards in an events map.\n * Merges *.* into all concrete actions, *.action into matching actions,\n * entity.* into all actions of that entity.\n */\nfunction expandWildcards(events: Flow.ContractEvents): Flow.ContractEvents {\n const result: Flow.ContractEvents = {};\n\n // For each concrete entity-action pair, merge all matching wildcard levels\n for (const entity of Object.keys(events)) {\n if (entity === '*') continue;\n result[entity] = {};\n\n for (const action of Object.keys(events[entity] || {})) {\n let merged: Record<string, unknown> = {};\n\n // Level 1: *.*\n const globalWild = events['*']?.['*'];\n if (globalWild)\n merged = mergeContractSchemas(\n merged,\n globalWild as Record<string, unknown>,\n );\n\n // Level 2: *.action\n const actionWild = events['*']?.[action];\n if (actionWild && action !== '*')\n merged = mergeContractSchemas(\n merged,\n actionWild as Record<string, unknown>,\n );\n\n // Level 3: entity.*\n const entityWild = events[entity]?.['*'];\n if (entityWild && action !== '*')\n merged = mergeContractSchemas(\n merged,\n entityWild as Record<string, unknown>,\n );\n\n // Level 4: entity.action\n const exact = events[entity]?.[action];\n if (exact)\n merged = mergeContractSchemas(merged, exact as Record<string, unknown>);\n\n result[entity][action] = merged;\n }\n }\n\n // Preserve * entries for reference\n if (events['*']) {\n result['*'] = { ...events['*'] };\n }\n\n return result;\n}\n\n/**\n * Deep merge two JSON Schema objects with additive semantics.\n * - `required` arrays: union (deduplicated)\n * - `properties`: deep merge (child wins on conflict for scalars)\n * - Scalars: child overrides parent\n */\nexport function mergeContractSchemas(\n parent: Record<string, unknown>,\n child: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...parent };\n\n for (const key of Object.keys(child)) {\n const parentVal = parent[key];\n const childVal = child[key];\n\n if (\n key === 'required' &&\n Array.isArray(parentVal) &&\n Array.isArray(childVal)\n ) {\n result[key] = [...new Set([...parentVal, ...childVal])];\n } else if (isPlainObject(parentVal) && isPlainObject(childVal)) {\n result[key] = mergeContractSchemas(\n parentVal as Record<string, unknown>,\n childVal as Record<string, unknown>,\n );\n } else {\n result[key] = childVal;\n }\n }\n\n return result;\n}\n\n/**\n * Strip annotation-only keys from a schema (deep).\n */\nfunction stripAnnotations(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema)) {\n if (ANNOTATION_KEYS.has(key)) continue;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = stripAnnotations(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Flow Configuration Utilities\n *\n * Functions for resolving and processing Flow configurations.\n *\n * @packageDocumentation\n */\n\nimport type { Flow } from './types';\nimport { resolveContracts } from './contract';\nimport { throwError } from './throwError';\n\n/**\n * Merge variables with cascade priority.\n * Later arguments have higher priority.\n */\nfunction mergeVariables(\n ...sources: (Flow.Variables | undefined)[]\n): Flow.Variables {\n const result: Flow.Variables = {};\n for (const source of sources) {\n if (source) {\n Object.assign(result, source);\n }\n }\n return result;\n}\n\n/**\n * Merge definitions with cascade priority.\n * Later arguments have higher priority.\n */\nfunction mergeDefinitions(\n ...sources: (Flow.Definitions | undefined)[]\n): Flow.Definitions {\n const result: Flow.Definitions = {};\n for (const source of sources) {\n if (source) {\n Object.assign(result, source);\n }\n }\n return result;\n}\n\n/** Sentinel prefix for deferred $env resolution. Shared with CLI bundler. */\nexport const ENV_MARKER_PREFIX = '__WALKEROS_ENV:';\n\nexport interface ResolveOptions {\n deferred?: boolean;\n}\n\n/**\n * Walk a dot-separated path into a value.\n * Throws if any intermediate segment is missing or not an object.\n */\nexport function walkPath(\n value: unknown,\n path: string,\n refPrefix: string,\n): unknown {\n const segments = path.split('.');\n let current = value;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n const visited = segments.slice(0, i).join('.');\n throwError(\n `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n );\n }\n const obj = current as Record<string, unknown>;\n if (!(segment in obj)) {\n const visited = segments.slice(0, i).join('.');\n throwError(\n `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n );\n }\n current = obj[segment];\n }\n\n return current;\n}\n\n/**\n * Resolve all dynamic patterns in a value.\n *\n * Patterns:\n * - $def.name → Look up definitions[name], replace entire value with definition content\n * - $def.name.path → Look up definitions[name], then walk dot-separated path\n * - $var.name → Look up variables[name]\n * - $env.NAME or $env.NAME:default → Look up process.env[NAME]\n */\nfunction resolvePatterns(\n value: unknown,\n variables: Flow.Variables,\n definitions: Flow.Definitions,\n options?: ResolveOptions,\n resolvedContracts?: Record<string, Flow.ContractEntry>,\n): unknown {\n if (typeof value === 'string') {\n // Check if entire string is a $def reference with optional deep path\n const defMatch = value.match(\n /^\\$def\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.(.+))?$/,\n );\n if (defMatch) {\n const defName = defMatch[1];\n const path = defMatch[2]; // e.g., \"nested.deep\" or undefined\n\n if (definitions[defName] === undefined) {\n throwError(`Definition \"${defName}\" not found`);\n }\n\n // Resolve the definition content recursively first\n let resolved = resolvePatterns(\n definitions[defName],\n variables,\n definitions,\n options,\n resolvedContracts,\n );\n\n // Walk deep path if present\n if (path) {\n resolved = walkPath(resolved, path, `$def.${defName}`);\n }\n\n return resolved;\n }\n\n // Check if entire string is a $contract reference with path\n const contractMatch = value.match(\n /^\\$contract\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.(.+))?$/,\n );\n if (contractMatch && resolvedContracts) {\n const contractName = contractMatch[1];\n const path = contractMatch[2];\n\n if (!(contractName in resolvedContracts)) {\n throwError(`Contract \"${contractName}\" not found`);\n }\n\n let resolved: unknown = resolvedContracts[contractName];\n\n if (path) {\n resolved = walkPath(resolved, path, `$contract.${contractName}`);\n }\n\n return resolved;\n }\n\n // Replace $var.name patterns (inline substitution)\n let result = value.replace(\n /\\$var\\.([a-zA-Z_][a-zA-Z0-9_]*)/g,\n (match, name) => {\n if (variables[name] !== undefined) {\n return String(variables[name]);\n }\n throwError(`Variable \"${name}\" not found`);\n },\n );\n\n // Replace $env.NAME or $env.NAME:default patterns\n result = result.replace(\n /\\$env\\.([a-zA-Z_][a-zA-Z0-9_]*)(?::([^\"}\\s]*))?/g,\n (match, name, defaultValue) => {\n if (options?.deferred) {\n return defaultValue !== undefined\n ? `${ENV_MARKER_PREFIX}${name}:${defaultValue}`\n : `${ENV_MARKER_PREFIX}${name}`;\n }\n if (\n typeof process !== 'undefined' &&\n process.env?.[name] !== undefined\n ) {\n return process.env[name]!;\n }\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n throwError(\n `Environment variable \"${name}\" not found and no default provided`,\n );\n },\n );\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) =>\n resolvePatterns(item, variables, definitions, options, resolvedContracts),\n );\n }\n\n if (value !== null && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = resolvePatterns(\n val,\n variables,\n definitions,\n options,\n resolvedContracts,\n );\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Convert package name to valid JavaScript variable name.\n * Used for deterministic default import naming.\n * @example\n * packageNameToVariable('@walkeros/server-destination-api')\n * // → '_walkerosServerDestinationApi'\n */\nexport function packageNameToVariable(packageName: string): string {\n const hasScope = packageName.startsWith('@');\n const normalized = packageName\n .replace('@', '')\n .replace(/[/-]/g, '_')\n .split('_')\n .filter((part) => part.length > 0)\n .map((part, i) =>\n i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1),\n )\n .join('');\n\n return hasScope ? '_' + normalized : normalized;\n}\n\n/**\n * Resolve code from package reference.\n * Preserves explicit code fields, or auto-generates from package name.\n */\nfunction resolveCodeFromPackage(\n packageName: string | undefined,\n existingCode: string | Flow.InlineCode | undefined,\n packages: Flow.Packages | undefined,\n): string | Flow.InlineCode | undefined {\n // Preserve explicit code first (including InlineCode objects)\n if (existingCode) return existingCode;\n\n // Auto-generate code from package name if package exists\n if (!packageName || !packages) return undefined;\n\n const pkgConfig = packages[packageName];\n if (!pkgConfig) return undefined;\n\n return packageNameToVariable(packageName);\n}\n\n/**\n * Get resolved flow settings for a named flow.\n *\n * @param config - The complete Flow.Config configuration\n * @param flowName - Flow name (auto-selected if only one exists)\n * @returns Resolved Settings with $var, $env, and $def patterns resolved\n * @throws Error if flow selection is required but not specified, or flow not found\n *\n * @example\n * ```typescript\n * import { getFlowSettings } from '@walkeros/core';\n *\n * const config = JSON.parse(fs.readFileSync('walkeros.config.json', 'utf8'));\n *\n * // Auto-select if only one flow\n * const settings = getFlowSettings(config);\n *\n * // Or specify flow\n * const prodSettings = getFlowSettings(config, 'production');\n * ```\n */\nexport function getFlowSettings(\n config: Flow.Config,\n flowName?: string,\n options?: ResolveOptions,\n): Flow.Settings {\n const flowNames = Object.keys(config.flows);\n\n // Auto-select if only one flow\n if (!flowName) {\n if (flowNames.length === 1) {\n flowName = flowNames[0];\n } else {\n throwError(\n `Multiple flows found (${flowNames.join(', ')}). Please specify a flow.`,\n );\n }\n }\n\n // Check flow exists\n const settings = config.flows[flowName];\n if (!settings) {\n throwError(\n `Flow \"${flowName}\" not found. Available: ${flowNames.join(', ')}`,\n );\n }\n\n // Deep clone to avoid mutations\n const result = JSON.parse(JSON.stringify(settings)) as Flow.Settings;\n\n // Pre-process contracts: resolve $def inside contracts, then extends + wildcards\n let resolvedContracts: Record<string, Flow.ContractEntry> | undefined;\n if (config.contract) {\n // Two-pass: resolve $def/$var/$env inside contract first\n const vars = mergeVariables(config.variables, settings.variables);\n const defs = mergeDefinitions(config.definitions, settings.definitions);\n const resolvedContractInput = resolvePatterns(\n config.contract,\n vars,\n defs,\n options,\n ) as Flow.Contract;\n\n resolvedContracts = resolveContracts(resolvedContractInput);\n }\n\n // Process sources with variable and definition cascade\n if (result.sources) {\n for (const [name, source] of Object.entries(result.sources)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n source.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n source.definitions,\n );\n\n const processedConfig = resolvePatterns(\n source.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n source.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n // Resolve code from package reference\n const resolvedCode = resolveCodeFromPackage(\n source.package,\n source.code,\n result.packages,\n );\n\n // Exclude deprecated code: true, only keep valid string or InlineCode\n const validCode =\n typeof source.code === 'string' || typeof source.code === 'object'\n ? source.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.sources[name] = {\n package: source.package,\n config: processedConfig,\n env: processedEnv,\n primary: source.primary,\n variables: source.variables,\n definitions: source.definitions,\n next: source.next,\n code: finalCode,\n } as Flow.SourceReference;\n }\n }\n\n // Process destinations with variable and definition cascade\n if (result.destinations) {\n for (const [name, dest] of Object.entries(result.destinations)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n dest.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n dest.definitions,\n );\n\n const processedConfig = resolvePatterns(\n dest.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n dest.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n // Resolve code from package reference\n const resolvedCode = resolveCodeFromPackage(\n dest.package,\n dest.code,\n result.packages,\n );\n\n // Exclude deprecated code: true, only keep valid string or InlineCode\n const validCode =\n typeof dest.code === 'string' || typeof dest.code === 'object'\n ? dest.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.destinations[name] = {\n package: dest.package,\n config: processedConfig,\n env: processedEnv,\n variables: dest.variables,\n definitions: dest.definitions,\n before: dest.before,\n code: finalCode,\n } as Flow.DestinationReference;\n }\n }\n\n // Process stores with variable and definition cascade\n if (result.stores) {\n for (const [name, store] of Object.entries(result.stores)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n store.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n store.definitions,\n );\n\n const processedConfig = resolvePatterns(\n store.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n store.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const resolvedCode = resolveCodeFromPackage(\n store.package,\n store.code,\n result.packages,\n );\n\n const validCode =\n typeof store.code === 'string' || typeof store.code === 'object'\n ? store.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.stores[name] = {\n package: store.package,\n config: processedConfig,\n env: processedEnv,\n variables: store.variables,\n definitions: store.definitions,\n code: finalCode,\n } as Flow.StoreReference;\n }\n }\n\n // Process transformers with variable and definition cascade\n if (result.transformers) {\n for (const [name, transformer] of Object.entries(result.transformers)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n transformer.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n transformer.definitions,\n );\n\n const processedConfig = resolvePatterns(\n transformer.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n transformer.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const resolvedCode = resolveCodeFromPackage(\n transformer.package,\n transformer.code,\n result.packages,\n );\n\n const validCode =\n typeof transformer.code === 'string' ||\n typeof transformer.code === 'object'\n ? transformer.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.transformers[name] = {\n package: transformer.package,\n config: processedConfig,\n env: processedEnv,\n variables: transformer.variables,\n definitions: transformer.definitions,\n next: transformer.next,\n code: finalCode,\n } as Flow.TransformerReference;\n }\n }\n\n // Process collector config\n if (result.collector) {\n const vars = mergeVariables(config.variables, settings.variables);\n const defs = mergeDefinitions(config.definitions, settings.definitions);\n\n const processedCollector = resolvePatterns(\n result.collector,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n result.collector = processedCollector as typeof result.collector;\n }\n\n return result;\n}\n\n/**\n * Get platform from settings (web or server).\n *\n * @param settings - Flow settings\n * @returns \"web\" or \"server\"\n * @throws Error if neither web nor server is present\n *\n * @example\n * ```typescript\n * import { getPlatform } from '@walkeros/core';\n *\n * const platform = getPlatform(settings);\n * // Returns \"web\" or \"server\"\n * ```\n */\nexport function getPlatform(settings: Flow.Settings): 'web' | 'server' {\n if (settings.web !== undefined) return 'web';\n if (settings.server !== undefined) return 'server';\n throwError('Settings must have web or server key');\n}\n","/**\n * @interface Assign\n * @description Options for the assign function.\n * @property merge - Merge array properties instead of overriding them.\n * @property shallow - Create a shallow copy instead of updating the target object.\n * @property extend - Extend the target with new properties instead of only updating existing ones.\n */\ninterface Assign {\n merge?: boolean;\n shallow?: boolean;\n extend?: boolean;\n}\n\nconst defaultOptions: Assign = {\n merge: true,\n shallow: true,\n extend: true,\n};\n\n/**\n * Merges objects with advanced options.\n *\n * @template T, U\n * @param target - The target object to merge into.\n * @param obj - The source object to merge from.\n * @param options - Options for merging.\n * @returns The merged object.\n */\nexport function assign<T extends object, U extends object>(\n target: T,\n obj: U = {} as U,\n options: Assign = {},\n): T & U {\n options = { ...defaultOptions, ...options };\n\n const finalObj = Object.entries(obj).reduce((acc, [key, sourceProp]) => {\n const targetProp = target[key as keyof typeof target];\n\n // Only merge arrays\n if (\n options.merge &&\n Array.isArray(targetProp) &&\n Array.isArray(sourceProp)\n ) {\n acc[key as keyof typeof acc] = sourceProp.reduce(\n (acc, item) => {\n // Remove duplicates\n return acc.includes(item) ? acc : [...acc, item];\n },\n [...targetProp],\n );\n } else if (options.extend || key in target) {\n // Extend the target with new properties or update existing ones\n acc[key as keyof typeof acc] = sourceProp;\n }\n\n return acc;\n }, {} as U);\n\n // Handle shallow or deep copy based on options\n if (options.shallow) {\n return { ...target, ...finalObj };\n } else {\n Object.assign(target, finalObj);\n return target as T & U;\n }\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if a value is an arguments object.\n *\n * @param value The value to check.\n * @returns True if the value is an arguments object, false otherwise.\n */\nexport function isArguments(value: unknown): value is IArguments {\n return Object.prototype.toString.call(value) === '[object Arguments]';\n}\n\n/**\n * Checks if a value is an array.\n *\n * @param value The value to check.\n * @returns True if the value is an array, false otherwise.\n */\nexport function isArray<T>(value: unknown): value is T[] {\n return Array.isArray(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value The value to check.\n * @returns True if the value is a boolean, false otherwise.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === 'boolean';\n}\n\n/**\n * Checks if an entity is a walker command.\n *\n * @param entity The entity to check.\n * @returns True if the entity is a walker command, false otherwise.\n */\nexport function isCommand(entity: string) {\n return entity === 'walker';\n}\n\n/**\n * Checks if a value is defined.\n *\n * @param value The value to check.\n * @returns True if the value is defined, false otherwise.\n */\nexport function isDefined<T>(val: T | undefined): val is T {\n return typeof val !== 'undefined';\n}\n\n/**\n * Checks if a value is an element or the document.\n *\n * @param elem The value to check.\n * @returns True if the value is an element or the document, false otherwise.\n */\nexport function isElementOrDocument(elem: unknown): elem is Element {\n return elem === document || elem instanceof Element;\n}\n\n/**\n * Checks if a value is a function.\n *\n * @param value The value to check.\n * @returns True if the value is a function, false otherwise.\n */\nexport function isFunction(value: unknown): value is Function {\n return typeof value === 'function';\n}\n\n/**\n * Checks if a value is a number.\n *\n * @param value The value to check.\n * @returns True if the value is a number, false otherwise.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === 'number' && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is an object.\n *\n * @param value The value to check.\n * @returns True if the value is an object, false otherwise.\n */\nexport function isObject(value: unknown): value is WalkerOS.AnyObject {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isArray(value) &&\n Object.prototype.toString.call(value) === '[object Object]'\n );\n}\n\n/**\n * Checks if two variables have the same type.\n *\n * @param variable The first variable.\n * @param type The second variable.\n * @returns True if the variables have the same type, false otherwise.\n */\nexport function isSameType<T>(\n variable: unknown,\n type: T,\n): variable is typeof type {\n return typeof variable === typeof type;\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value The value to check.\n * @returns True if the value is a string, false otherwise.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n","/**\n * Creates a deep clone of a value.\n * Supports primitive values, objects, arrays, dates, and regular expressions.\n * Handles circular references.\n *\n * @template T\n * @param org - The value to clone.\n * @param visited - A map of visited objects to handle circular references.\n * @returns The cloned value.\n */\nexport function clone<T>(\n org: T,\n visited: WeakMap<object, unknown> = new WeakMap(),\n): T {\n // Handle primitive values and functions directly\n if (typeof org !== 'object' || org === null) return org;\n\n // Check for circular references\n if (visited.has(org)) return visited.get(org) as T;\n\n // Allow list of clonable types\n const type = Object.prototype.toString.call(org);\n if (type === '[object Object]') {\n const clonedObj = {} as Record<string | symbol, unknown>;\n visited.set(org as object, clonedObj); // Remember the reference\n\n for (const key in org as Record<string | symbol, unknown>) {\n if (Object.prototype.hasOwnProperty.call(org, key)) {\n clonedObj[key] = clone(\n (org as Record<string | symbol, unknown>)[key],\n visited,\n );\n }\n }\n return clonedObj as T;\n }\n\n if (type === '[object Array]') {\n const clonedArray = [] as unknown[];\n visited.set(org as object, clonedArray); // Remember the reference\n\n (org as unknown[]).forEach((item) => {\n clonedArray.push(clone(item, visited));\n });\n\n return clonedArray as T;\n }\n\n if (type === '[object Date]') {\n return new Date((org as unknown as Date).getTime()) as T;\n }\n\n if (type === '[object RegExp]') {\n const reg = org as unknown as RegExp;\n return new RegExp(reg.source, reg.flags) as T;\n }\n\n // Skip cloning for unsupported types and return reference\n return org;\n}\n","import type { WalkerOS } from './types';\nimport { isArray, isDefined, isObject } from './is';\nimport { clone } from './clone';\n\n/**\n * Gets a value from an object by a dot-notation string.\n * Supports wildcards for arrays.\n *\n * @example\n * getByPath({ data: { id: 1 } }, \"data.id\") // Returns 1\n *\n * @param event - The object to get the value from.\n * @param key - The dot-notation string.\n * @param defaultValue - The default value to return if the key is not found.\n * @returns The value from the object or the default value.\n */\nexport function getByPath(\n event: unknown,\n key: string = '',\n defaultValue?: unknown,\n): unknown {\n const keys = key.split('.');\n let values: unknown = event;\n\n for (let index = 0; index < keys.length; index++) {\n const k = keys[index];\n\n if (k === '*' && isArray(values)) {\n const remainingKeys = keys.slice(index + 1).join('.');\n const result: unknown[] = [];\n\n for (const item of values) {\n const value = getByPath(item, remainingKeys, defaultValue);\n result.push(value);\n }\n\n return result;\n }\n\n values =\n values instanceof Object ? values[k as keyof typeof values] : undefined;\n\n if (values === undefined) break;\n }\n\n return isDefined(values) ? values : defaultValue;\n}\n\n/**\n * Sets a value in an object by a dot-notation string.\n *\n * @param obj - The object to set the value in.\n * @param key - The dot-notation string.\n * @param value - The value to set.\n * @returns A new object with the updated value.\n */\nexport function setByPath<T = unknown>(obj: T, key: string, value: unknown): T {\n if (!isObject(obj)) return obj;\n\n const clonedObj = clone(obj);\n const keys = key.split('.');\n let current: WalkerOS.AnyObject = clonedObj;\n\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i] as keyof typeof current;\n\n // Set the value if it's the last key\n if (i === keys.length - 1) {\n current[k] = value;\n } else {\n // Traverse to the next level\n if (\n !(k in current) ||\n typeof current[k] !== 'object' ||\n current[k] === null\n ) {\n current[k] = {};\n }\n\n // Move deeper into the object\n current = current[k] as WalkerOS.AnyObject;\n }\n }\n\n return clonedObj as T;\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Casts a value to a specific type.\n *\n * @param value The value to cast.\n * @returns The casted value.\n */\nexport function castValue(value: unknown): WalkerOS.PropertyType {\n if (value === 'true') return true;\n if (value === 'false') return false;\n\n const number = Number(value); // Converts \"\" to 0\n if (value == number && value !== '') return number;\n\n return String(value);\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if the required consent is granted.\n *\n * @param required - The required consent states.\n * @param state - The current consent states.\n * @param individual - Individual consent states to prioritize.\n * @returns The granted consent states or false if not granted.\n */\nexport function getGrantedConsent(\n required: WalkerOS.Consent | undefined,\n state: WalkerOS.Consent = {},\n individual: WalkerOS.Consent = {},\n): false | WalkerOS.Consent {\n // Merge state and individual, prioritizing individual states\n const states: WalkerOS.Consent = { ...state, ...individual };\n\n const grantedStates: WalkerOS.Consent = {};\n let hasRequiredConsent = !required || Object.keys(required).length === 0;\n\n Object.keys(states).forEach((name) => {\n if (states[name]) {\n // consent granted\n grantedStates[name] = true;\n\n // Check if it's required and granted consent\n if (required && required[name]) hasRequiredConsent = true;\n }\n });\n\n return hasRequiredConsent ? grantedStates : false;\n}\n","import type { Destination } from './types';\nimport type { TypesOf, Config } from './types/destination';\nimport { assign } from './assign';\n\n/**\n * Creates a new destination instance by merging a base destination with additional configuration.\n *\n * This utility enables elegant destination configuration while avoiding config side-effects\n * that could occur when reusing destination objects across multiple collector instances.\n *\n * @param baseDestination - The base destination to extend\n * @param config - Additional configuration to merge with the base destination's config\n * @returns A new destination instance with merged configuration\n *\n * @example\n * ```typescript\n * // Types are inferred automatically from destinationGtag\n * elb('walker destination', createDestination(destinationGtag, {\n * settings: { ga4: { measurementId: 'G-123' } }\n * }));\n * ```\n */\nexport function createDestination<I extends Destination.Instance>(\n baseDestination: I,\n config: Partial<Config<TypesOf<I>>>,\n): I {\n // Create a shallow copy of the base destination to avoid mutations\n const newDestination = { ...baseDestination };\n\n // Deep merge the config, handling nested objects like settings and mapping\n newDestination.config = assign(baseDestination.config, config, {\n shallow: true, // Create new object, don't mutate original\n merge: true, // Merge arrays\n extend: true, // Allow new properties\n });\n\n // Handle nested settings merging if both have settings\n if (baseDestination.config.settings && config.settings) {\n newDestination.config.settings = assign(\n baseDestination.config.settings as object,\n config.settings as object,\n { shallow: true, merge: true, extend: true },\n ) as typeof newDestination.config.settings;\n }\n\n // Handle nested mapping merging if both have mapping\n if (baseDestination.config.mapping && config.mapping) {\n newDestination.config.mapping = assign(\n baseDestination.config.mapping as object,\n config.mapping as object,\n { shallow: true, merge: true, extend: true },\n ) as typeof newDestination.config.mapping;\n }\n\n return newDestination;\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\n\ndeclare const __VERSION__: string;\n\n/**\n * Creates a complete event with default values.\n * Used for testing and debugging.\n *\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function createEvent(\n props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n const group = props.group || 'gr0up';\n const count = props.count || 1;\n const id = `${timestamp}-${group}-${count}`;\n\n const defaultEvent: WalkerOS.Event = {\n name: 'entity action',\n data: {\n string: 'foo',\n number: 1,\n boolean: true,\n array: [0, 'text', false],\n not: undefined,\n },\n context: { dev: ['test', 1] },\n globals: { lang: 'elb' },\n custom: { completely: 'random' },\n user: { id: 'us3r', device: 'c00k13', session: 's3ss10n' },\n nested: [\n {\n entity: 'child',\n data: { is: 'subordinated' },\n nested: [],\n context: { element: ['child', 0] },\n },\n ],\n consent: { functional: true },\n id,\n trigger: 'test',\n entity: 'entity',\n action: 'action',\n timestamp,\n timing: 3.14,\n group,\n count,\n version: {\n source: __VERSION__,\n tagging: 1,\n },\n source: {\n type: 'web',\n id: 'https://localhost:80',\n previous_id: 'http://remotehost:9001',\n },\n };\n\n // Note: Always prefer the props over the defaults\n\n // Merge properties\n const event = assign(defaultEvent, props, { merge: false });\n\n // Update conditions\n\n // Entity and action from event\n if (props.name) {\n const [entity, action] = props.name.split(' ') ?? [];\n\n if (entity && action) {\n event.entity = entity;\n event.action = action;\n }\n }\n\n return event;\n}\n\n/**\n * Creates a complete event with default values based on the event name.\n * Used for testing and debugging.\n *\n * @param name - The name of the event to create.\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function getEvent(\n name: string = 'entity action',\n props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n\n const quantity = 2;\n const product1 = {\n data: {\n id: 'ers',\n name: 'Everyday Ruck Snack',\n color: 'black',\n size: 'l',\n price: 420,\n },\n };\n const product2 = {\n data: {\n id: 'cc',\n name: 'Cool Cap',\n size: 'one size',\n price: 42,\n },\n };\n\n const defaultEvents: Record<string, WalkerOS.PartialEvent> = {\n 'cart view': {\n data: {\n currency: 'EUR',\n value: product1.data.price * quantity,\n },\n context: { shopping: ['cart', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n data: { ...product1.data, quantity },\n context: { shopping: ['cart', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'checkout view': {\n data: {\n step: 'payment',\n currency: 'EUR',\n value: product1.data.price + product2.data.price,\n },\n context: { shopping: ['checkout', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n ...product1,\n context: { shopping: ['checkout', 0] },\n nested: [],\n },\n {\n entity: 'product',\n ...product2,\n context: { shopping: ['checkout', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'order complete': {\n data: {\n id: '0rd3r1d',\n currency: 'EUR',\n shipping: 5.22,\n taxes: 73.76,\n total: 555,\n },\n context: { shopping: ['complete', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n ...product1,\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n {\n entity: 'product',\n ...product2,\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n {\n entity: 'gift',\n data: {\n name: 'Surprise',\n },\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'page view': {\n data: {\n domain: 'www.example.com',\n title: 'walkerOS documentation',\n referrer: 'https://www.walkeros.io/',\n search: '?foo=bar',\n hash: '#hash',\n id: '/docs/',\n },\n globals: { pagegroup: 'docs' },\n trigger: 'load',\n },\n 'product add': {\n ...product1,\n context: { shopping: ['intent', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'click',\n },\n 'product view': {\n ...product1,\n context: { shopping: ['detail', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'load',\n },\n 'product visible': {\n data: { ...product1.data, position: 3, promo: true },\n context: { shopping: ['discover', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'load',\n },\n 'promotion visible': {\n data: {\n name: 'Setting up tracking easily',\n position: 'hero',\n },\n context: { ab_test: ['engagement', 0] },\n globals: { pagegroup: 'homepage' },\n trigger: 'visible',\n },\n 'session start': {\n data: {\n id: 's3ss10n',\n start: timestamp,\n isNew: true,\n count: 1,\n runs: 1,\n isStart: true,\n storage: true,\n referrer: '',\n device: 'c00k13',\n },\n user: {\n id: 'us3r',\n device: 'c00k13',\n session: 's3ss10n',\n hash: 'h4sh',\n address: 'street number',\n email: 'user@example.com',\n phone: '+49 123 456 789',\n userAgent: 'Mozilla...',\n browser: 'Chrome',\n browserVersion: '90',\n deviceType: 'desktop',\n language: 'de-DE',\n country: 'DE',\n region: 'HH',\n city: 'Hamburg',\n zip: '20354',\n timezone: 'Berlin',\n os: 'walkerOS',\n osVersion: '1.0',\n screenSize: '1337x420',\n ip: '127.0.0.0',\n internal: true,\n custom: 'value',\n },\n },\n };\n\n return createEvent({ ...defaultEvents[name], ...props, name: name });\n}\n","/**\n * Generates a random string of a given length.\n *\n * @param length - The length of the random string.\n * @returns The random string.\n */\nexport function getId(length = 6): string {\n let str = '';\n for (let l = 36; str.length < length; )\n str += ((Math.random() * l) | 0).toString(l);\n return str;\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\n\nexport interface MarketingParameters {\n [key: string]: string;\n}\n\n/**\n * Extracts marketing parameters from a URL.\n *\n * @param url - The URL to extract the parameters from.\n * @param custom - Custom marketing parameters to extract.\n * @returns The extracted marketing parameters.\n */\nexport function getMarketingParameters(\n url: URL,\n custom: MarketingParameters = {},\n): WalkerOS.Properties {\n const clickId = 'clickId';\n const data: WalkerOS.Properties = {};\n const parameters: MarketingParameters = {\n utm_campaign: 'campaign',\n utm_content: 'content',\n utm_medium: 'medium',\n utm_source: 'source',\n utm_term: 'term',\n dclid: clickId,\n fbclid: clickId,\n gclid: clickId,\n msclkid: clickId,\n ttclid: clickId,\n twclid: clickId,\n igshid: clickId,\n sclid: clickId,\n };\n\n Object.entries(assign(parameters, custom)).forEach(([key, name]) => {\n const param = url.searchParams.get(key); // Search for the parameter in the URL\n if (param) {\n if (name === clickId) {\n name = key;\n data[clickId] = key; // Reference the clickId parameter\n }\n\n data[name] = param;\n }\n });\n\n return data;\n}\n","/**\n * Creates a debounced function that delays invoking `fn` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `fn` invocations and a `flush` method to immediately invoke them.\n *\n * @template P, R\n * @param fn The function to debounce.\n * @param wait The number of milliseconds to delay.\n * @param immediate Trigger the function on the leading edge, instead of the trailing.\n * @returns The new debounced function.\n */\nexport function debounce<P extends unknown[], R>(\n fn: (...args: P) => R,\n wait = 1000,\n immediate = false,\n) {\n let timer: number | NodeJS.Timeout | null = null;\n let result: R;\n let hasCalledImmediately = false;\n\n return (...args: P): Promise<R> => {\n // Return value as promise\n return new Promise((resolve) => {\n const callNow = immediate && !hasCalledImmediately;\n\n // abort previous invocation\n if (timer) clearTimeout(timer);\n\n timer = setTimeout(() => {\n timer = null;\n if (!immediate || hasCalledImmediately) {\n result = fn(...args);\n resolve(result);\n }\n }, wait);\n\n if (callNow) {\n hasCalledImmediately = true;\n result = fn(...args);\n resolve(result);\n }\n });\n };\n}\n\n/**\n * Creates a throttled function that only invokes `fn` at most once per\n * every `delay` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `fn` invocations and a `flush` method to\n * immediately invoke them.\n *\n * @template P, R\n * @param fn The function to throttle.\n * @param delay The number of milliseconds to throttle invocations to.\n * @returns The new throttled function.\n */\n\ntype Timeout = ReturnType<typeof setTimeout>;\nexport function throttle<P extends unknown[], R>(\n fn: (...args: P) => R | undefined,\n delay = 1000,\n): (...args: P) => R | undefined {\n let isBlocked: Timeout | null = null;\n\n return function (...args: P): R | undefined {\n // Skip since function is still blocked by previous call\n if (isBlocked !== null) return;\n\n // Set a blocking timeout\n isBlocked = setTimeout(() => {\n // Unblock function\n isBlocked = null;\n }, delay) as Timeout;\n\n // Call the function\n return fn(...args);\n };\n}\n","import type {\n Config,\n DefaultHandler,\n ErrorContext,\n Handler,\n Instance,\n InternalConfig,\n LogContext,\n} from './types/logger';\nimport { Level } from './types/logger';\n\n/**\n * Normalize an Error object into ErrorContext\n */\nfunction normalizeError(err: Error): ErrorContext {\n return {\n message: err.message,\n name: err.name,\n stack: err.stack,\n cause: (err as Error & { cause?: unknown }).cause,\n };\n}\n\n/**\n * Normalize message and context parameters\n * Handles Error objects passed as message or context\n */\nfunction normalizeParams(\n message: string | Error,\n context?: unknown | Error,\n): { message: string; context: LogContext } {\n let normalizedMessage: string;\n let normalizedContext: LogContext = {};\n\n // Handle message\n if (message instanceof Error) {\n normalizedMessage = message.message;\n normalizedContext.error = normalizeError(message);\n } else {\n normalizedMessage = message;\n }\n\n // Handle context\n if (context !== undefined) {\n if (context instanceof Error) {\n normalizedContext.error = normalizeError(context);\n } else if (typeof context === 'object' && context !== null) {\n normalizedContext = { ...normalizedContext, ...(context as object) };\n // If context has an error property that's an Error, normalize it\n if (\n 'error' in normalizedContext &&\n normalizedContext.error instanceof Error\n ) {\n normalizedContext.error = normalizeError(\n normalizedContext.error as unknown as Error,\n );\n }\n } else {\n normalizedContext.value = context;\n }\n }\n\n return { message: normalizedMessage, context: normalizedContext };\n}\n\n/**\n * Default console-based log handler\n */\nconst defaultHandler: DefaultHandler = (level, message, context, scope) => {\n const levelName = Level[level];\n const scopePath = scope.length > 0 ? ` [${scope.join(':')}]` : '';\n const prefix = `${levelName}${scopePath}`;\n\n const hasContext = Object.keys(context).length > 0;\n\n const consoleFn =\n level === Level.ERROR\n ? console.error\n : level === Level.WARN\n ? console.warn\n : console.log;\n\n if (hasContext) {\n consoleFn(prefix, message, context);\n } else {\n consoleFn(prefix, message);\n }\n};\n\n/**\n * Normalize log level from string or enum to enum value\n */\nfunction normalizeLevel(level: Level | keyof typeof Level): Level {\n if (typeof level === 'string') {\n return Level[level as keyof typeof Level];\n }\n return level;\n}\n\n/**\n * Create a logger instance\n *\n * @param config - Logger configuration\n * @returns Logger instance with all log methods and scoping support\n *\n * @example\n * ```typescript\n * // Basic usage\n * const logger = createLogger({ level: 'DEBUG' });\n * logger.info('Hello world');\n *\n * // With scoping\n * const destLogger = logger.scope('gtag').scope('myInstance');\n * destLogger.debug('Processing event'); // DEBUG [gtag:myInstance] Processing event\n *\n * // With custom handler\n * const logger = createLogger({\n * handler: (level, message, context, scope, originalHandler) => {\n * // Custom logic (e.g., send to Sentry)\n * originalHandler(level, message, context, scope);\n * }\n * });\n * ```\n *\n * // TODO: Consider compile-time stripping of debug logs in production builds\n * // e.g., if (__DEV__) { logger.debug(...) }\n */\nexport function createLogger(config: Config = {}): Instance {\n const level =\n config.level !== undefined ? normalizeLevel(config.level) : Level.ERROR;\n const customHandler = config.handler;\n const jsonHandler = config.jsonHandler;\n const scope: string[] = [];\n\n return createLoggerInternal({\n level,\n handler: customHandler,\n jsonHandler,\n scope,\n });\n}\n\n/**\n * Internal logger creation with resolved config\n */\nfunction createLoggerInternal(config: InternalConfig): Instance {\n const { level, handler, jsonHandler, scope } = config;\n\n /**\n * Internal log function that checks level and delegates to handler\n */\n const log = (\n logLevel: Level,\n message: string | Error,\n context?: unknown | Error,\n ): void => {\n if (logLevel <= level) {\n const normalized = normalizeParams(message, context);\n\n if (handler) {\n // Custom handler with access to default handler\n handler(\n logLevel,\n normalized.message,\n normalized.context,\n scope,\n defaultHandler,\n );\n } else {\n defaultHandler(logLevel, normalized.message, normalized.context, scope);\n }\n }\n };\n\n /**\n * Log and throw - combines logging and throwing\n */\n const logAndThrow = (message: string | Error, context?: unknown): never => {\n // Always log errors regardless of level\n const normalized = normalizeParams(message, context);\n\n if (handler) {\n handler(\n Level.ERROR,\n normalized.message,\n normalized.context,\n scope,\n defaultHandler,\n );\n } else {\n defaultHandler(\n Level.ERROR,\n normalized.message,\n normalized.context,\n scope,\n );\n }\n\n // Throw with the message\n throw new Error(normalized.message);\n };\n\n return {\n error: (message, context) => log(Level.ERROR, message, context),\n warn: (message, context) => log(Level.WARN, message, context),\n info: (message, context) => log(Level.INFO, message, context),\n debug: (message, context) => log(Level.DEBUG, message, context),\n throw: logAndThrow,\n json: (data: unknown) => {\n if (jsonHandler) {\n jsonHandler(data);\n } else {\n // eslint-disable-next-line no-console\n console.log(JSON.stringify(data, null, 2));\n }\n },\n scope: (name: string) =>\n createLoggerInternal({\n level,\n handler,\n jsonHandler,\n scope: [...scope, name],\n }),\n };\n}\n\n// Re-export Level enum for convenience\nexport { Level };\n","import type { WalkerOS } from './types';\nimport {\n isArguments,\n isArray,\n isBoolean,\n isDefined,\n isNumber,\n isObject,\n isString,\n} from './is';\n\n/**\n * Checks if a value is a valid property type.\n *\n * @param value The value to check.\n * @returns True if the value is a valid property type, false otherwise.\n */\nexport function isPropertyType(value: unknown): value is WalkerOS.PropertyType {\n return (\n isBoolean(value) ||\n isString(value) ||\n isNumber(value) ||\n !isDefined(value) ||\n (isArray(value) && value.every(isPropertyType)) ||\n (isObject(value) && Object.values(value).every(isPropertyType))\n );\n}\n\n/**\n * Filters a value to only include valid property types.\n *\n * @param value The value to filter.\n * @returns The filtered value or undefined.\n */\nexport function filterValues(value: unknown): WalkerOS.Property | undefined {\n if (isBoolean(value) || isString(value) || isNumber(value)) return value;\n\n if (isArguments(value)) return filterValues(Array.from(value));\n\n if (isArray(value)) {\n return value\n .map((item) => filterValues(item))\n .filter((item): item is WalkerOS.PropertyType => item !== undefined);\n }\n\n if (isObject(value)) {\n return Object.entries(value).reduce<Record<string, WalkerOS.Property>>(\n (acc, [key, val]) => {\n const filteredValue = filterValues(val);\n if (filteredValue !== undefined) acc[key] = filteredValue;\n return acc;\n },\n {},\n );\n }\n\n return;\n}\n\n/**\n * Casts a value to a valid property type.\n *\n * @param value The value to cast.\n * @returns The casted value or undefined.\n */\nexport function castToProperty(value: unknown): WalkerOS.Property | undefined {\n return isPropertyType(value) ? value : undefined;\n}\n","/**\n * A utility function that wraps a function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatch<P extends unknown[], R, S>(\n fn: (...args: P) => R | undefined,\n onError: (err: unknown) => S,\n onFinally?: () => void,\n): (...args: P) => R | S;\nexport function tryCatch<P extends unknown[], R>(\n fn: (...args: P) => R | undefined,\n onError?: undefined,\n onFinally?: () => void,\n): (...args: P) => R | undefined;\n// Implementation\nexport function tryCatch<P extends unknown[], R, S>(\n fn: (...args: P) => R | undefined,\n onError?: (err: unknown) => S,\n onFinally?: () => void,\n): (...args: P) => R | S | undefined {\n return function (...args: P): R | S | undefined {\n try {\n return fn(...args);\n } catch (err) {\n if (!onError) return;\n return onError(err);\n } finally {\n onFinally?.();\n }\n };\n}\n\n/**\n * A utility function that wraps an async function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The async function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped async function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatchAsync<P extends unknown[], R, S>(\n fn: (...args: P) => R,\n onError: (err: unknown) => S,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S>;\nexport function tryCatchAsync<P extends unknown[], R>(\n fn: (...args: P) => R,\n onError?: undefined,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | undefined>;\n// Implementation\nexport function tryCatchAsync<P extends unknown[], R, S>(\n fn: (...args: P) => R,\n onError?: (err: unknown) => S,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S | undefined> {\n return async function (...args: P): Promise<R | S | undefined> {\n try {\n return await fn(...args);\n } catch (err) {\n if (!onError) return;\n return await onError(err);\n } finally {\n await onFinally?.();\n }\n };\n}\n","import type { Mapping, WalkerOS, Collector } from './types';\nimport { getByPath, setByPath } from './byPath';\nimport { isArray, isDefined, isString, isObject } from './is';\nimport { castToProperty } from './property';\nimport { tryCatchAsync } from './tryCatch';\nimport { getGrantedConsent } from './consent';\nimport { assign } from './assign';\n\n/**\n * Gets the mapping for an event.\n *\n * @param event The event to get the mapping for (can be partial or full).\n * @param mapping The mapping rules.\n * @returns The mapping result.\n */\nexport async function getMappingEvent(\n event: WalkerOS.DeepPartialEvent | WalkerOS.PartialEvent | WalkerOS.Event,\n mapping?: Mapping.Rules,\n): Promise<Mapping.Result> {\n const [entity, action] = (event.name || '').split(' ');\n if (!mapping || !entity || !action) return {};\n\n let eventMapping: Mapping.Rule | undefined;\n let mappingKey = '';\n let entityKey = entity;\n let actionKey = action;\n\n const resolveEventMapping = (\n eventMapping?: Mapping.Rule | Mapping.Rule[],\n ) => {\n if (!eventMapping) return;\n eventMapping = isArray(eventMapping) ? eventMapping : [eventMapping];\n\n return eventMapping.find(\n (eventMapping) =>\n !eventMapping.condition || eventMapping.condition(event),\n );\n };\n\n if (!mapping[entityKey]) entityKey = '*';\n const entityMapping = mapping[entityKey];\n\n if (entityMapping) {\n if (!entityMapping[actionKey]) actionKey = '*';\n eventMapping = resolveEventMapping(entityMapping[actionKey]);\n }\n\n // Fallback to * *\n if (!eventMapping) {\n entityKey = '*';\n actionKey = '*';\n eventMapping = resolveEventMapping(mapping[entityKey]?.[actionKey]);\n }\n\n if (eventMapping) mappingKey = `${entityKey} ${actionKey}`;\n\n return { eventMapping, mappingKey };\n}\n\n/**\n * Gets a value from a mapping.\n *\n * @param value The value to get the mapping from.\n * @param data The mapping data.\n * @param options The mapping options.\n * @returns The mapped value.\n */\nexport async function getMappingValue(\n value: WalkerOS.DeepPartialEvent | unknown | undefined,\n data: Mapping.Data = {},\n options: Mapping.Options = {},\n): Promise<WalkerOS.Property | undefined> {\n if (!isDefined(value)) return;\n\n // Get consent state in priority order: value.consent > options.consent > collector?.consent\n const consentState =\n ((isObject(value) && value.consent) as WalkerOS.Consent) ||\n options.consent ||\n options.collector?.consent;\n\n const mappings = isArray(data) ? data : [data];\n\n for (const mapping of mappings) {\n const result = await tryCatchAsync(processMappingValue)(value, mapping, {\n ...options,\n consent: consentState,\n });\n if (isDefined(result)) return result;\n }\n\n return;\n}\n\nasync function processMappingValue(\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping: Mapping.Value,\n options: Mapping.Options = {},\n): Promise<WalkerOS.Property | undefined> {\n const { collector, consent: consentState } = options;\n\n // Ensure mapping is an array for uniform processing\n const mappings = isArray(mapping) ? mapping : [mapping];\n\n // Loop over each mapping and return the first valid result\n return mappings.reduce(\n async (accPromise, mappingItem) => {\n const acc = await accPromise;\n if (acc) return acc; // A valid result was already found\n\n const mapping = isString(mappingItem)\n ? { key: mappingItem }\n : mappingItem;\n\n if (!Object.keys(mapping).length) return;\n\n const {\n condition,\n consent,\n fn,\n key,\n loop,\n map,\n set,\n validate,\n value: staticValue,\n } = mapping;\n\n // Check if this mapping should be used\n if (\n condition &&\n !(await tryCatchAsync(condition)(value, mappingItem, collector))\n )\n return;\n\n // Check if consent is required and granted\n if (consent && !getGrantedConsent(consent, consentState))\n return staticValue;\n\n let mappingValue: unknown = isDefined(staticValue) ? staticValue : value;\n\n // Use a custom function to get the value\n if (fn) {\n mappingValue = await tryCatchAsync(fn)(value, mappingItem, options);\n }\n\n // Get dynamic value from the event\n if (key) {\n mappingValue = getByPath(value, key, staticValue);\n }\n\n if (loop) {\n const [scope, itemMapping] = loop;\n\n const data =\n scope === 'this'\n ? [value]\n : await getMappingValue(value, scope, options);\n\n if (isArray(data)) {\n mappingValue = (\n await Promise.all(\n data.map((item) => getMappingValue(item, itemMapping, options)),\n )\n ).filter(isDefined);\n }\n } else if (map) {\n mappingValue = await Object.entries(map).reduce(\n async (mappedObjPromise, [mapKey, mapValue]) => {\n const mappedObj = await mappedObjPromise;\n const result = await getMappingValue(value, mapValue, options);\n if (isDefined(result)) mappedObj[mapKey] = result;\n return mappedObj;\n },\n Promise.resolve({} as WalkerOS.AnyObject),\n );\n } else if (set) {\n mappingValue = await Promise.all(\n set.map((item) => processMappingValue(value, item, options)),\n );\n }\n\n // Validate the value\n if (validate && !(await tryCatchAsync(validate)(mappingValue)))\n mappingValue = undefined;\n\n const property = castToProperty(mappingValue);\n\n // Finally, check and convert the type\n return isDefined(property) ? property : castToProperty(staticValue); // Always use value as a fallback\n },\n Promise.resolve(undefined as WalkerOS.Property | undefined),\n );\n}\n\n/**\n * Processes an event through mapping configuration.\n *\n * This is the unified mapping logic used by both sources and destinations.\n * It applies transformations in this order:\n * 1. Config-level policy - modifies the event itself (global rules)\n * 2. Mapping rules - finds matching rule based on entity-action\n * 3. Event-level policy - modifies the event based on specific mapping rule\n * 4. Data transformation - creates context data\n * 5. Ignore check and name override\n *\n * Sources can pass partial events, destinations pass full events.\n * getMappingValue works with both partial and full events.\n *\n * @param event - The event to process (can be partial or full, will be mutated by policies)\n * @param config - Mapping configuration (mapping, data, policy, consent)\n * @param collector - Collector instance for context\n * @returns Object with transformed event, data, mapping rule, and ignore flag\n */\nexport async function processEventMapping<\n T extends WalkerOS.DeepPartialEvent | WalkerOS.Event,\n>(\n event: T,\n config: Mapping.Config,\n collector: Collector.Instance,\n): Promise<{\n event: T;\n data?: WalkerOS.Property;\n mapping?: Mapping.Rule;\n mappingKey?: string;\n ignore: boolean;\n}> {\n // Step 1: Apply config-level policy (modifies event)\n if (config.policy) {\n await Promise.all(\n Object.entries(config.policy).map(async ([key, mapping]) => {\n const value = await getMappingValue(event, mapping, { collector });\n event = setByPath(event, key, value);\n }),\n );\n }\n\n // Step 2: Get event mapping rule\n const { eventMapping, mappingKey } = await getMappingEvent(\n event,\n config.mapping,\n );\n\n // Step 2.5: Apply event-level policy (modifies event)\n if (eventMapping?.policy) {\n await Promise.all(\n Object.entries(eventMapping.policy).map(async ([key, mapping]) => {\n const value = await getMappingValue(event, mapping, { collector });\n event = setByPath(event, key, value);\n }),\n );\n }\n\n // Step 3: Transform global data\n let data =\n config.data && (await getMappingValue(event, config.data, { collector }));\n\n if (eventMapping) {\n // Check if event should be ignored\n if (eventMapping.ignore) {\n return { event, data, mapping: eventMapping, mappingKey, ignore: true };\n }\n\n // Override event name if specified\n if (eventMapping.name) event.name = eventMapping.name;\n\n // Transform event-specific data\n if (eventMapping.data) {\n const dataEvent =\n eventMapping.data &&\n (await getMappingValue(event, eventMapping.data, { collector }));\n data =\n isObject(data) && isObject(dataEvent) // Only merge objects\n ? assign(data, dataEvent)\n : dataEvent;\n }\n }\n\n return { event, data, mapping: eventMapping, mappingKey, ignore: false };\n}\n","/**\n * Environment mocking utilities for walkerOS destinations\n *\n * Provides standardized tools for intercepting function calls in environment objects,\n * enabling consistent testing patterns across all destinations.\n */\n\ntype InterceptorFn = (\n path: string[],\n args: unknown[],\n original?: Function,\n) => unknown;\n\n/**\n * Creates a proxied environment that intercepts function calls\n *\n * Uses Proxy to wrap environment objects and capture all function calls,\n * allowing for call recording, mocking, or simulation.\n *\n * @param env - The environment object to wrap\n * @param interceptor - Function called for each intercepted call\n * @returns Proxied environment with interceptor applied\n *\n * @example\n * ```typescript\n * const calls: Array<{ path: string[]; args: unknown[] }> = [];\n *\n * const testEnv = mockEnv(env.push, (path, args) => {\n * calls.push({ path, args });\n * });\n *\n * // Use testEnv with destination\n * await destination.push(event, { env: testEnv });\n *\n * // Analyze captured calls\n * expect(calls).toContainEqual({\n * path: ['window', 'gtag'],\n * args: ['event', 'purchase', { value: 99.99 }]\n * });\n * ```\n */\nexport function mockEnv<T extends object>(\n env: T,\n interceptor: InterceptorFn,\n): T {\n const createProxy = (obj: object, path: string[] = []): object => {\n return new Proxy(obj, {\n get(target, prop: string) {\n const value = (target as Record<string, unknown>)[prop];\n const currentPath = [...path, prop];\n\n if (typeof value === 'function') {\n return (...args: unknown[]) => {\n return interceptor(currentPath, args, value);\n };\n }\n\n if (value && typeof value === 'object') {\n return createProxy(value as object, currentPath);\n }\n\n return value;\n },\n });\n };\n\n return createProxy(env) as T;\n}\n\n/**\n * Traverses environment object and replaces values using a replacer function\n *\n * Alternative to mockEnv for environments where Proxy is not suitable.\n * Performs deep traversal and allows value transformation at each level.\n *\n * @param env - The environment object to traverse\n * @param replacer - Function to transform values during traversal\n * @returns New environment object with transformed values\n *\n * @example\n * ```typescript\n * const recordedCalls: APICall[] = [];\n *\n * const recordingEnv = traverseEnv(originalEnv, (value, path) => {\n * if (typeof value === 'function') {\n * return (...args: unknown[]) => {\n * recordedCalls.push({\n * path: path.join('.'),\n * args: structuredClone(args)\n * });\n * return value(...args);\n * };\n * }\n * return value;\n * });\n * ```\n */\nexport function traverseEnv<T extends object>(\n env: T,\n replacer: (value: unknown, path: string[]) => unknown,\n): T {\n const traverse = (obj: unknown, path: string[] = []): unknown => {\n if (!obj || typeof obj !== 'object') return obj;\n\n const result: Record<string, unknown> | unknown[] = Array.isArray(obj)\n ? []\n : {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n if (Array.isArray(result)) {\n result[Number(key)] = replacer(value, currentPath);\n } else {\n (result as Record<string, unknown>)[key] = replacer(value, currentPath);\n }\n\n if (value && typeof value === 'object' && typeof value !== 'function') {\n if (Array.isArray(result)) {\n result[Number(key)] = traverse(value, currentPath);\n } else {\n (result as Record<string, unknown>)[key] = traverse(\n value,\n currentPath,\n );\n }\n }\n }\n\n return result;\n };\n\n return traverse(env) as T;\n}\n","import type { Instance } from './types/logger';\n\n/**\n * Mock logger instance for testing\n * Includes all logger methods as jest.fn() plus tracking of scoped loggers\n * Extends Instance to ensure type compatibility\n */\nexport interface MockLogger extends Instance {\n error: jest.Mock;\n warn: jest.Mock;\n info: jest.Mock;\n debug: jest.Mock;\n throw: jest.Mock<never, [string | Error, unknown?]>;\n json: jest.Mock;\n scope: jest.Mock<MockLogger, [string]>;\n\n /**\n * Array of all scoped loggers created by this logger\n * Useful for asserting on scoped logger calls in tests\n */\n scopedLoggers: MockLogger[];\n}\n\n/**\n * Create a mock logger for testing\n * All methods are jest.fn() that can be used for assertions\n *\n * @example\n * ```typescript\n * const mockLogger = createMockLogger();\n *\n * // Use in code under test\n * someFunction(mockLogger);\n *\n * // Assert on calls\n * expect(mockLogger.error).toHaveBeenCalledWith('error message');\n *\n * // Assert on scoped logger\n * const scoped = mockLogger.scopedLoggers[0];\n * expect(scoped.debug).toHaveBeenCalledWith('debug in scope');\n * ```\n */\nexport function createMockLogger(): MockLogger {\n const scopedLoggers: MockLogger[] = [];\n\n const mockThrow = jest.fn((message: string | Error): never => {\n const msg = message instanceof Error ? message.message : message;\n throw new Error(msg);\n }) as jest.Mock<never, [string | Error, unknown?]>;\n\n const mockScope = jest.fn((_name: string): MockLogger => {\n const scoped = createMockLogger();\n scopedLoggers.push(scoped);\n return scoped;\n }) as jest.Mock<MockLogger, [string]>;\n\n const mockLogger: MockLogger = {\n error: jest.fn(),\n warn: jest.fn(),\n info: jest.fn(),\n debug: jest.fn(),\n throw: mockThrow,\n json: jest.fn(),\n scope: mockScope,\n scopedLoggers,\n };\n\n return mockLogger;\n}\n","import type { WalkerOS } from './types';\nimport { tryCatch } from './tryCatch';\nimport { castValue } from './castValue';\nimport { isArray, isObject } from './is';\n\n/**\n * Converts a request string to a data object.\n *\n * @param parameter The request string to convert.\n * @returns The data object or undefined.\n */\nexport function requestToData(\n parameter: unknown,\n): WalkerOS.AnyObject | undefined {\n const str = String(parameter);\n const queryString = str.split('?')[1] || str;\n\n return tryCatch(() => {\n const params = new URLSearchParams(queryString);\n const result: WalkerOS.AnyObject = {};\n\n params.forEach((value, key) => {\n const keys = key.split(/[[\\]]+/).filter(Boolean);\n let current: unknown = result;\n\n keys.forEach((k, i) => {\n const isLast = i === keys.length - 1;\n\n if (isArray(current)) {\n const index = parseInt(k, 10);\n if (isLast) {\n (current as Array<unknown>)[index] = castValue(value);\n } else {\n (current as Array<unknown>)[index] =\n (current as Array<unknown>)[index] ||\n (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n current = (current as Array<unknown>)[index];\n }\n } else if (isObject(current)) {\n if (isLast) {\n (current as WalkerOS.AnyObject)[k] = castValue(value);\n } else {\n (current as WalkerOS.AnyObject)[k] =\n (current as WalkerOS.AnyObject)[k] ||\n (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n current = (current as WalkerOS.AnyObject)[k];\n }\n }\n });\n });\n\n return result;\n })();\n}\n\n/**\n * Converts a data object to a request string.\n *\n * @param data The data object to convert.\n * @returns The request string.\n */\nexport function requestToParameter(\n data: WalkerOS.AnyObject | WalkerOS.PropertyType,\n): string {\n if (!data) return '';\n\n const params: string[] = [];\n const encode = encodeURIComponent;\n\n function addParam(key: string, value: unknown) {\n if (value === undefined || value === null) return;\n\n if (isArray(value)) {\n value.forEach((item, index) => addParam(`${key}[${index}]`, item));\n } else if (isObject(value)) {\n Object.entries(value).forEach(([subKey, subValue]) =>\n addParam(`${key}[${subKey}]`, subValue),\n );\n } else {\n params.push(`${encode(key)}=${encode(String(value))}`);\n }\n }\n\n if (typeof data === 'object') {\n Object.entries(data).forEach(([key, value]) => addParam(key, value));\n } else {\n return encode(data);\n }\n\n return params.join('&');\n}\n","import type { SendDataValue, SendHeaders } from './types/send';\nimport { isSameType } from './is';\nimport { assign } from './assign';\n\nexport type { SendDataValue, SendHeaders, SendResponse } from './types/send';\n\n/**\n * Transforms data to a string.\n *\n * @param data The data to transform.\n * @returns The transformed data.\n */\nexport function transformData(data?: SendDataValue): string | undefined {\n if (data === undefined) return data;\n\n return isSameType(data, '' as string) ? data : JSON.stringify(data);\n}\n\n/**\n * Gets the headers for a request.\n *\n * @param headers The headers to merge with the default headers.\n * @returns The merged headers.\n */\nexport function getHeaders(headers: SendHeaders = {}): SendHeaders {\n return assign(\n {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n headers,\n );\n}\n","/**\n * Trims quotes and whitespaces from a string.\n *\n * @param str The string to trim.\n * @returns The trimmed string.\n */\nexport function trim(str: string): string {\n // Remove quotes and whitespaces\n return str ? str.trim().replace(/^'|'$/g, '').trim() : '';\n}\n","import type { Hooks } from './types';\n\n/**\n * A utility function that wraps a function with hooks.\n *\n * @template P, R\n * @param fn The function to wrap.\n * @param name The name of the function.\n * @param hooks The hooks to use.\n * @returns The wrapped function.\n */\nexport function useHooks<P extends unknown[], R>(\n fn: (...args: P) => R,\n name: string,\n hooks: Hooks.Functions,\n): (...args: P) => R {\n return function (...args: P): R {\n let result: R;\n const preHook = ('pre' + name) as keyof Hooks.Functions;\n const postHook = ('post' + name) as keyof Hooks.Functions;\n const preHookFn = hooks[preHook] as unknown as Hooks.HookFn<typeof fn>;\n const postHookFn = hooks[postHook] as unknown as Hooks.HookFn<typeof fn>;\n\n if (preHookFn) {\n // Call the original function within the preHook\n result = preHookFn({ fn }, ...args);\n } else {\n // Regular function call\n result = fn(...args);\n }\n\n if (postHookFn) {\n // Call the post-hook function with fn, result, and the original args\n result = postHookFn({ fn, result }, ...args);\n }\n\n return result;\n };\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Parses a user agent string to extract browser, OS, and device information.\n *\n * @param userAgent The user agent string to parse.\n * @returns An object containing the parsed user agent information.\n */\nexport function parseUserAgent(userAgent?: string): WalkerOS.User {\n if (!userAgent) return {};\n\n return {\n userAgent,\n browser: getBrowser(userAgent),\n browserVersion: getBrowserVersion(userAgent),\n os: getOS(userAgent),\n osVersion: getOSVersion(userAgent),\n deviceType: getDeviceType(userAgent),\n };\n}\n\n/**\n * Gets the browser name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser name or undefined.\n */\nexport function getBrowser(userAgent: string): string | undefined {\n const browsers = [\n { name: 'Edge', substr: 'Edg' },\n { name: 'Chrome', substr: 'Chrome' },\n { name: 'Safari', substr: 'Safari', exclude: 'Chrome' },\n { name: 'Firefox', substr: 'Firefox' },\n { name: 'IE', substr: 'MSIE' },\n { name: 'IE', substr: 'Trident' },\n ];\n\n for (const browser of browsers) {\n if (\n userAgent.includes(browser.substr) &&\n (!browser.exclude || !userAgent.includes(browser.exclude))\n ) {\n return browser.name;\n }\n }\n\n return;\n}\n\n/**\n * Gets the browser version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser version or undefined.\n */\nexport function getBrowserVersion(userAgent: string): string | undefined {\n const rules = [\n /Edg\\/([0-9]+)/, // Edge\n /Chrome\\/([0-9]+)/, // Chrome\n /Version\\/([0-9]+).*Safari/, // Safari\n /Firefox\\/([0-9]+)/, // Firefox\n /MSIE ([0-9]+)/, // IE 10 and older\n /rv:([0-9]+).*Trident/, // IE 11\n ];\n\n for (const regex of rules) {\n const match = userAgent.match(regex);\n if (match) {\n return match[1];\n }\n }\n\n return;\n}\n\n/**\n * Gets the OS name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS name or undefined.\n */\nexport function getOS(userAgent: string): string | undefined {\n const osList = [\n { name: 'Windows', substr: 'Windows NT' },\n { name: 'macOS', substr: 'Mac OS X' },\n { name: 'Android', substr: 'Android' },\n { name: 'iOS', substr: 'iPhone OS' },\n { name: 'Linux', substr: 'Linux' },\n ];\n\n for (const os of osList) {\n if (userAgent.includes(os.substr)) {\n return os.name;\n }\n }\n\n return;\n}\n\n/**\n * Gets the OS version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS version or undefined.\n */\nexport function getOSVersion(userAgent: string): string | undefined {\n const osVersionRegex = /(?:Windows NT|Mac OS X|Android|iPhone OS) ([0-9._]+)/;\n const match = userAgent.match(osVersionRegex);\n return match ? match[1].replace(/_/g, '.') : undefined;\n}\n\n/**\n * Gets the device type from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The device type or undefined.\n */\nexport function getDeviceType(userAgent: string): string | undefined {\n let deviceType = 'Desktop';\n\n if (/Tablet|iPad/i.test(userAgent)) {\n deviceType = 'Tablet';\n } else if (\n /Mobi|Android|iPhone|iPod|BlackBerry|Opera Mini|IEMobile|WPDesktop/i.test(\n userAgent,\n )\n ) {\n deviceType = 'Mobile';\n }\n\n return deviceType;\n}\n","/**\n * Inline Code Wrapping Utilities\n *\n * Converts inline code strings to executable functions.\n * Used for mapping properties: condition, fn, validate.\n *\n * @packageDocumentation\n */\n\nimport type { Mapping } from './types';\n\n/**\n * Detect if code has explicit return statement.\n */\nfunction hasReturn(code: string): boolean {\n return /\\breturn\\b/.test(code);\n}\n\n/**\n * Wrap code with function body.\n * If code has no return, auto-wrap with return.\n */\nfunction wrapCode(code: string): string {\n return hasReturn(code) ? code : `return ${code}`;\n}\n\n/**\n * Wrap inline code string as Condition function.\n *\n * @param code - Inline code string\n * @returns Condition function matching Mapping.Condition signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The event or partial event being processed\n * - `mapping` - Current mapping configuration\n * - `collector` - Collector instance\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapCondition('value.data.total > 100');\n * fn(event, mapping, collector); // returns boolean\n *\n * // Multi-statement (explicit return)\n * const fn = wrapCondition('const threshold = 100; return value.data.total > threshold');\n * ```\n */\nexport function wrapCondition(code: string): Mapping.Condition {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function(\n 'value',\n 'mapping',\n 'collector',\n body,\n ) as Mapping.Condition;\n}\n\n/**\n * Wrap inline code string as Fn function.\n *\n * @param code - Inline code string\n * @returns Fn function matching Mapping.Fn signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The event or partial event being processed\n * - `mapping` - Current mapping configuration\n * - `options` - Options object with consent and collector\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapFn('value.user.email.split(\"@\")[1]');\n * fn(event, mapping, options); // returns domain\n *\n * // Multi-statement (explicit return)\n * const fn = wrapFn('const parts = value.user.email.split(\"@\"); return parts[1].toUpperCase()');\n * ```\n */\nexport function wrapFn(code: string): Mapping.Fn {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function('value', 'mapping', 'options', body) as Mapping.Fn;\n}\n\n/**\n * Wrap inline code string as Validate function.\n *\n * @param code - Inline code string\n * @returns Validate function matching Mapping.Validate signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The current value being validated\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapValidate('value && value.length > 0');\n * fn('hello'); // returns true\n *\n * // Multi-statement (explicit return)\n * const fn = wrapValidate('if (!value) return false; return value.length > 0');\n * ```\n */\nexport function wrapValidate(code: string): Mapping.Validate {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function('value', body) as Mapping.Validate;\n}\n","const JSDELIVR_BASE = 'https://cdn.jsdelivr.net/npm';\nconst DEFAULT_SCHEMA_PATH = 'dist/walkerOS.json';\n\nexport interface ExampleSummary {\n name: string;\n description?: string;\n}\n\nexport interface WalkerOSPackageMeta {\n packageName: string;\n version: string;\n description?: string;\n type?: string;\n platform?: string;\n}\n\nexport interface WalkerOSPackageInfo {\n packageName: string;\n version: string;\n type?: string;\n platform?: string;\n schemas: Record<string, unknown>;\n examples: Record<string, unknown>;\n hints?: Record<string, unknown>;\n}\n\nexport interface WalkerOSPackage extends WalkerOSPackageInfo {\n description?: string;\n docs?: string;\n source?: string;\n hintKeys: string[];\n exampleSummaries: ExampleSummary[];\n}\n\nexport async function fetchPackage(\n packageName: string,\n options?: { version?: string; timeout?: number },\n): Promise<WalkerOSPackage> {\n const ver = options?.version || 'latest';\n const base = `${JSDELIVR_BASE}/${packageName}@${ver}`;\n const controller = new AbortController();\n const timeoutMs = options?.timeout || 10000;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n // Fetch package.json\n const pkgRes = await fetch(`${base}/package.json`, {\n signal: controller.signal,\n });\n if (!pkgRes.ok) {\n throw new Error(\n `Package \"${packageName}\" not found on npm (HTTP ${pkgRes.status})`,\n );\n }\n const pkg = (await pkgRes.json()) as Record<string, unknown>;\n\n // Fetch walkerOS.json\n const schemaRes = await fetch(`${base}/${DEFAULT_SCHEMA_PATH}`, {\n signal: controller.signal,\n });\n if (!schemaRes.ok) {\n throw new Error(\n `walkerOS.json not found at ${DEFAULT_SCHEMA_PATH} (HTTP ${schemaRes.status}). ` +\n `This package may not support the walkerOS.json convention yet.`,\n );\n }\n const walkerOSJson = (await schemaRes.json()) as Record<string, unknown>;\n const meta = (walkerOSJson.$meta as Record<string, unknown>) || {};\n\n const schemas = (walkerOSJson.schemas as Record<string, unknown>) || {};\n const examples = (walkerOSJson.examples as Record<string, unknown>) || {};\n const hints = walkerOSJson.hints as Record<string, unknown> | undefined;\n\n // Extract hint keys\n const hintKeys = hints ? Object.keys(hints) : [];\n\n // Extract example summaries from step examples\n const exampleSummaries: ExampleSummary[] = [];\n const stepExamples = (examples.step || {}) as Record<string, unknown>;\n for (const [name, example] of Object.entries(stepExamples)) {\n const ex = example as Record<string, unknown> | undefined;\n const summary: ExampleSummary = { name };\n if (ex?.description) summary.description = ex.description as string;\n exampleSummaries.push(summary);\n }\n\n const docs = meta.docs as string | undefined;\n const source = meta.source as string | undefined;\n\n return {\n packageName,\n version: (pkg.version as string) || ver,\n description: pkg.description as string | undefined,\n type: meta.type as string | undefined,\n platform: meta.platform as string | undefined,\n schemas,\n examples,\n ...(docs ? { docs } : {}),\n ...(source ? { source } : {}),\n ...(hints && Object.keys(hints).length > 0 ? { hints } : {}),\n hintKeys,\n exampleSummaries,\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * @deprecated Use fetchPackage instead.\n * Still used by: entry.ts (validator), package-schemas.ts (MCP resource).\n */\nexport async function fetchPackageSchema(\n packageName: string,\n options?: { version?: string; timeout?: number },\n): Promise<WalkerOSPackageInfo> {\n const pkg = await fetchPackage(packageName, options);\n return {\n packageName: pkg.packageName,\n version: pkg.version,\n type: pkg.type,\n platform: pkg.platform,\n schemas: pkg.schemas,\n examples: pkg.examples,\n ...(pkg.hints ? { hints: pkg.hints } : {}),\n };\n}\n","export function mcpResult(\n result: unknown,\n summary?: string,\n hints?: { next?: string[]; warnings?: string[] },\n) {\n const enriched = hints\n ? { ...(result as Record<string, unknown>), _hints: hints }\n : result;\n return {\n content: [\n {\n type: 'text' as const,\n text: summary ?? JSON.stringify(enriched, null, 2),\n },\n ],\n structuredContent: enriched as Record<string, unknown>,\n };\n}\n\nexport function mcpError(error: unknown, hint?: string) {\n let message: string;\n let path: string | undefined;\n\n if (error instanceof Error) {\n message = error.message;\n } else if (typeof error === 'string') {\n message = error;\n } else if (\n error &&\n typeof error === 'object' &&\n 'issues' in error &&\n Array.isArray((error as { issues: unknown[] }).issues)\n ) {\n const issues = (\n error as { issues: Array<{ path?: unknown[]; message: string }> }\n ).issues;\n message = issues.map((i) => i.message).join('; ');\n path = issues[0]?.path?.join('.') || undefined;\n } else if (error && typeof error === 'object' && 'message' in error) {\n message = String((error as { message: unknown }).message);\n } else {\n message = 'Unknown error';\n }\n\n const structured: Record<string, unknown> = { error: message };\n if (hint) structured.hint = hint;\n if (path) structured.path = path;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(structured),\n },\n ],\n structuredContent: structured,\n isError: true as const,\n };\n}\n","/**\n * Options for responding to an HTTP request.\n * Same interface for web and server — sources implement the handler.\n */\nexport interface RespondOptions {\n /** Response body. Objects are JSON-serialized by source. */\n body?: unknown;\n /** HTTP status code (default: 200). Server-only, ignored by web sources. */\n status?: number;\n /** HTTP response headers. Server-only, ignored by web sources. */\n headers?: Record<string, string>;\n}\n\n/**\n * Standardized response function available on env for every step.\n * Idempotent: first call wins, subsequent calls are no-ops.\n * Created by sources via createRespond(), consumed by any step.\n */\nexport type RespondFn = (options?: RespondOptions) => void;\n\n/**\n * Creates an idempotent respond function.\n * The sender callback is source-specific (Express wraps res, Fetch wraps Response, etc.).\n *\n * @param sender - Platform-specific function that actually sends the response\n * @returns Idempotent respond function (first call wins)\n */\nexport function createRespond(\n sender: (options: RespondOptions) => void,\n): RespondFn {\n let called = false;\n return (options: RespondOptions = {}) => {\n if (called) return;\n called = true;\n sender(options);\n };\n}\n","import type {\n MatchExpression,\n MatchCondition,\n MatchOperator,\n CompiledMatcher,\n} from './types/matcher';\n\n/**\n * Compiles a match expression into a closure for fast runtime evaluation.\n * Regex patterns are compiled once. Numeric comparisons are parsed once.\n * Runtime evaluation is pure function calls with short-circuit logic.\n */\nexport function compileMatcher(expr: MatchExpression | '*'): CompiledMatcher {\n if (expr === '*') return () => true;\n\n if ('and' in expr) {\n const fns = expr.and.map(compileMatcher);\n return (ingest) => fns.every((fn) => fn(ingest));\n }\n\n if ('or' in expr) {\n const fns = expr.or.map(compileMatcher);\n return (ingest) => fns.some((fn) => fn(ingest));\n }\n\n // Leaf condition\n return compileCondition(expr);\n}\n\nfunction compileCondition(condition: MatchCondition): CompiledMatcher {\n const { key, operator, value, not } = condition;\n const test = compileOperator(operator, value);\n\n return (ingest) => {\n const raw = ingest[key];\n const result = test(raw);\n return not ? !result : result;\n };\n}\n\nfunction compileOperator(\n operator: MatchOperator,\n value: string,\n): (input: unknown) => boolean {\n switch (operator) {\n case 'eq':\n return (input) => String(input ?? '') === value;\n case 'contains':\n return (input) => String(input ?? '').includes(value);\n case 'prefix':\n return (input) => String(input ?? '').startsWith(value);\n case 'suffix':\n return (input) => String(input ?? '').endsWith(value);\n case 'regex': {\n const re = new RegExp(value);\n return (input) => re.test(String(input ?? ''));\n }\n case 'gt': {\n const num = Number(value);\n return (input) => Number(input) > num;\n }\n case 'lt': {\n const num = Number(value);\n return (input) => Number(input) < num;\n }\n case 'exists':\n return (input) => input !== undefined && input !== null;\n }\n}\n"],"mappings":";;;;;;;AAAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;AAAA;AAAA;AAAA;AAGO,IAAK,QAAL,kBAAKA,WAAL;AACL,EAAAA,cAAA,WAAQ,KAAR;AACA,EAAAA,cAAA,UAAO,KAAP;AACA,EAAAA,cAAA,UAAO,KAAP;AACA,EAAAA,cAAA,WAAQ,KAAR;AAJU,SAAAA;AAAA,GAAA;;;ACHZ;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACEO,IAAM,UAAU;AAAA,EACrB,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AACV;AAEO,IAAM,QAAQ;AAAA,EACnB,OAAO;AAAA,IACL;AAAA,EACF;AACF;;;ACNO,SAAS,OACd,OACA,MACoB;AACpB,SAAO,EAAE,OAAO,KAAK;AACvB;;;ACLO,SAAS,YAAY,IAAoB;AAC9C,QAAM,cAAc;AAEpB,MAAI,CAAC,YAAY,KAAK,EAAE,EAAG,QAAO;AAElC,SAAO,GAAG,QAAQ,UAAU,IAAI;AAClC;;;ACPO,SAAS,WAAW,OAAuB;AAChD,QAAM,IAAI,MAAM,OAAO,KAAK,CAAC;AAC/B;;;ACHA,IAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;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AAS,EAAE,EAAE,WAAW,KAAK;AAAA,IACxD,KAAK;AACH,aAAO,CAAC,UAAU,OAAO,SAAS,EAAE,EAAE,SAAS,KAAK;AAAA,IACtD,KAAK,SAAS;AACZ,YAAM,KAAK,IAAI,OAAO,KAAK;AAC3B,aAAO,CAAC,UAAU,GAAG,KAAK,OAAO,SAAS,EAAE,CAAC;AAAA,IAC/C;AAAA,IACA,KAAK,MAAM;AACT,YAAM,MAAM,OAAO,KAAK;AACxB,aAAO,CAAC,UAAU,OAAO,KAAK,IAAI;AAAA,IACpC;AAAA,IACA,KAAK,MAAM;AACT,YAAM,MAAM,OAAO,KAAK;AACxB,aAAO,CAAC,UAAU,OAAO,KAAK,IAAI;AAAA,IACpC;AAAA,IACA,KAAK;AACH,aAAO,CAAC,UAAU,UAAU,UAAa,UAAU;AAAA,EACvD;AACF;","names":["Level","acc","eventMapping","mapping"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/collector.ts","../src/types/context.ts","../src/types/destination.ts","../src/types/elb.ts","../src/types/flow.ts","../src/types/hooks.ts","../src/types/logger.ts","../src/types/mapping.ts","../src/types/on.ts","../src/types/transformer.ts","../src/types/request.ts","../src/types/source.ts","../src/types/store.ts","../src/types/trigger.ts","../src/types/lifecycle.ts","../src/types/walkeros.ts","../src/types/simulation.ts","../src/types/matcher.ts","../src/types/hint.ts","../src/types/storage.ts","../src/branch.ts","../src/anonymizeIP.ts","../src/throwError.ts","../src/contract.ts","../src/flow.ts","../src/assign.ts","../src/is.ts","../src/clone.ts","../src/byPath.ts","../src/castValue.ts","../src/consent.ts","../src/createDestination.ts","../src/eventGenerator.ts","../src/getId.ts","../src/getMarketingParameters.ts","../src/invocations.ts","../src/logger.ts","../src/property.ts","../src/tryCatch.ts","../src/mapping.ts","../src/mockEnv.ts","../src/mockLogger.ts","../src/request.ts","../src/send.ts","../src/trim.ts","../src/useHooks.ts","../src/userAgent.ts","../src/wrapInlineCode.ts","../src/cdn.ts","../src/mcpHelpers.ts","../src/respond.ts","../src/matcher.ts","../src/schemas/validation.ts","../src/schemas/primitives.ts","../src/schemas/utilities.ts","../src/schemas/patterns.ts","../src/schemas/walkeros.ts","../src/schemas/mapping.ts","../src/schemas/destination.ts","../src/schemas/collector.ts","../src/schemas/source.ts","../src/schemas/flow.ts","../src/schemas/hint.ts","../src/merge-config-schema.ts"],"sourcesContent":["import type {\n Source,\n Destination,\n Store,\n Elb as ElbTypes,\n Hooks,\n Logger,\n On,\n Transformer,\n WalkerOS,\n Mapping,\n} from '.';\n\n/**\n * Core collector configuration interface\n */\nexport interface Config {\n /** Whether to run collector automatically */\n run?: boolean;\n /** Version for event tagging */\n tagging: number;\n /** Static global properties even on a new run */\n globalsStatic: WalkerOS.Properties;\n /** Static session data even on a new run */\n sessionStatic: Partial<SessionData>;\n /** Logger configuration */\n logger?: Logger.Config;\n}\n\n/**\n * Initialization configuration that extends Config with initial state\n */\nexport interface InitConfig extends Partial<Config> {\n /** Initial consent state */\n consent?: WalkerOS.Consent;\n /** Initial user data */\n user?: WalkerOS.User;\n /** Initial global properties */\n globals?: WalkerOS.Properties;\n /** Source configurations */\n sources?: Source.InitSources;\n /** Destination configurations */\n destinations?: Destination.InitDestinations;\n /** Transformer configurations */\n transformers?: Transformer.InitTransformers;\n /** Store configurations */\n stores?: Store.InitStores;\n /** Initial custom properties */\n custom?: WalkerOS.Properties;\n}\n\nexport interface SessionData extends WalkerOS.Properties {\n isStart: boolean;\n storage: boolean;\n id?: string;\n start?: number;\n marketing?: true;\n updated?: number;\n isNew?: boolean;\n device?: string;\n count?: number;\n runs?: number;\n}\n\nexport interface Status {\n startedAt: number;\n in: number;\n out: number;\n failed: number;\n sources: Record<string, SourceStatus>;\n destinations: Record<string, DestinationStatus>;\n}\n\nexport interface SourceStatus {\n count: number;\n lastAt?: number;\n duration: number;\n}\n\nexport interface DestinationStatus {\n count: number;\n failed: number;\n lastAt?: number;\n duration: number;\n}\n\nexport interface Sources {\n [id: string]: Source.Instance;\n}\n\nexport interface Destinations {\n [id: string]: Destination.Instance;\n}\n\nexport interface Transformers {\n [id: string]: Transformer.Instance;\n}\n\nexport interface Stores {\n [id: string]: Store.Instance;\n}\n\nexport type CommandType =\n | 'action'\n | 'config'\n | 'consent'\n | 'context'\n | 'destination'\n | 'elb'\n | 'globals'\n | 'hook'\n | 'init'\n | 'link'\n | 'run'\n | 'user'\n | 'walker'\n | string;\n\n/**\n * Options passed to collector.push() from sources.\n * NOT a Context - just push metadata.\n */\nexport interface PushOptions {\n id?: string;\n ingest?: unknown;\n respond?: import('../respond').RespondFn;\n mapping?: Mapping.Config;\n preChain?: string[];\n}\n\n/**\n * Push function signature - handles events only\n */\nexport interface PushFn {\n (\n event: WalkerOS.DeepPartialEvent,\n options?: PushOptions,\n ): Promise<ElbTypes.PushResult>;\n}\n\n/**\n * Command function signature - handles walker commands only\n */\nexport interface CommandFn {\n (command: 'config', config: Partial<Config>): Promise<ElbTypes.PushResult>;\n (command: 'consent', consent: WalkerOS.Consent): Promise<ElbTypes.PushResult>;\n <T extends Destination.Types>(\n command: 'destination',\n destination: Destination.Init<T> | Destination.Instance<T>,\n config?: Destination.Config<T>,\n ): Promise<ElbTypes.PushResult>;\n <K extends keyof Hooks.Functions>(\n command: 'hook',\n name: K,\n hookFn: Hooks.Functions[K],\n ): Promise<ElbTypes.PushResult>;\n (\n command: 'on',\n type: On.Types,\n rules: WalkerOS.SingleOrArray<On.Options>,\n ): Promise<ElbTypes.PushResult>;\n (command: 'user', user: WalkerOS.User): Promise<ElbTypes.PushResult>;\n (\n command: 'run',\n runState?: {\n consent?: WalkerOS.Consent;\n user?: WalkerOS.User;\n globals?: WalkerOS.Properties;\n custom?: WalkerOS.Properties;\n },\n ): Promise<ElbTypes.PushResult>;\n (\n command: string,\n data?: unknown,\n options?: unknown,\n ): Promise<ElbTypes.PushResult>;\n}\n\n// Main Collector interface\nexport interface Instance {\n push: PushFn;\n command: CommandFn;\n allowed: boolean;\n config: Config;\n consent: WalkerOS.Consent;\n count: number;\n custom: WalkerOS.Properties;\n sources: Sources;\n destinations: Destinations;\n transformers: Transformers;\n stores: Stores;\n globals: WalkerOS.Properties;\n group: string;\n hooks: Hooks.Functions;\n logger: Logger.Instance;\n on: On.OnConfig;\n queue: WalkerOS.Events;\n round: number;\n session: undefined | SessionData;\n status: Status;\n timing: number;\n user: WalkerOS.User;\n version: string;\n pending: {\n sources: Source.InitSources;\n destinations: Destination.InitDestinations;\n };\n}\n","import type { Collector, Logger } from '.';\n\n/**\n * Base context interface for walkerOS stages.\n * Sources, Transformers, and Destinations extend this.\n */\nexport interface Base<C = unknown, E = unknown> {\n collector: Collector.Instance;\n logger: Logger.Instance;\n config: C;\n env: E;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n Collector,\n Logger,\n Mapping as WalkerOSMapping,\n On,\n WalkerOS,\n Context as BaseContext,\n} from '.';\nimport type { DestroyFn } from './lifecycle';\n\n/**\n * Base environment requirements interface for walkerOS destinations\n *\n * This defines the core interface that destinations can use to declare\n * their runtime environment requirements. Platform-specific extensions\n * should extend this interface.\n */\nexport interface BaseEnv {\n /**\n * Generic global properties that destinations may require\n * Platform-specific implementations can extend this interface\n */\n [key: string]: unknown;\n}\n\n/**\n * Type bundle for destination generics.\n * Groups Settings, InitSettings, Mapping, and Env into a single type parameter.\n */\nexport interface Types<S = unknown, M = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n mapping: M;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n mapping: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n config: Config<T>;\n queuePush?: WalkerOS.Events;\n queueOn?: Array<{ type: On.Types; data?: unknown }>;\n dlq?: DLQ;\n batches?: BatchRegistry<Mapping<T>>;\n type?: string;\n env?: Env<T>;\n init?: InitFn<T>;\n push: PushFn<T>;\n pushBatch?: PushBatchFn<T>;\n on?: On.OnFn;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport interface Config<T extends TypesGeneric = Types> {\n /** Required consent states to push events; queues events when not granted. */\n consent?: WalkerOS.Consent;\n /** Implementation-specific configuration passed to the init function. */\n settings?: InitSettings<T>;\n /** Global data transformation applied to all events; result passed as context.data to push. */\n data?: WalkerOSMapping.Value | WalkerOSMapping.Values;\n /** Runtime dependencies merged from code and config env; extensible per destination. */\n env?: Env<T>;\n /** Destination identifier; auto-generated if not provided. */\n id?: string;\n /** Whether the destination has been initialized; prevents re-initialization. */\n init?: boolean;\n /** Whether to load external scripts (e.g., gtag.js); destination-specific behavior. */\n loadScript?: boolean;\n /** Logger configuration (level, handler) to override the collector's defaults. */\n logger?: Logger.Config;\n /** Entity-action rules to filter, rename, transform, and batch events for this destination. */\n mapping?: WalkerOSMapping.Rules<WalkerOSMapping.Rule<Mapping<T>>>;\n /** Pre-processing rules applied to all events before mapping; modifies events in-place. */\n policy?: Policy;\n /** Whether to queue events when consent is not granted; defaults to true. */\n queue?: boolean;\n /** Defer destination initialization until these collector events fire (e.g., `['consent']`). */\n require?: string[];\n /** Transformer chain to run after collector processing but before this destination. */\n before?: string | string[];\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n Types<\n Partial<Settings<T>> | Settings<T>,\n Partial<Mapping<T>> | Mapping<T>,\n Env<T>\n >\n>;\n\nexport interface Policy {\n [key: string]: WalkerOSMapping.Value;\n}\n\nexport type Code<T extends TypesGeneric = Types> = Instance<T>;\n\nexport type Init<T extends TypesGeneric = Types> = {\n code: Code<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n before?: string | string[];\n};\n\nexport interface InitDestinations {\n [key: string]: Init<any>;\n}\n\nexport interface Destinations {\n [key: string]: Instance;\n}\n\n/**\n * Context provided to destination functions.\n * Extends base context with destination-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n data?: Data;\n}\n\nexport interface PushContext<\n T extends TypesGeneric = Types,\n> extends Context<T> {\n ingest?: unknown;\n rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport interface PushBatchContext<\n T extends TypesGeneric = Types,\n> extends Context<T> {\n ingest?: unknown;\n rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type PushFn<T extends TypesGeneric = Types> = (\n event: WalkerOS.Event,\n context: PushContext<T>,\n) => WalkerOS.PromiseOrValue<void | unknown>;\n\nexport type PushBatchFn<T extends TypesGeneric = Types> = (\n batch: Batch<Mapping<T>>,\n context: PushBatchContext<T>,\n) => void;\n\nexport type PushEvent<Mapping = unknown> = {\n event: WalkerOS.Event;\n mapping?: WalkerOSMapping.Rule<Mapping>;\n};\nexport type PushEvents<Mapping = unknown> = Array<PushEvent<Mapping>>;\n\nexport interface Batch<Mapping> {\n key: string;\n events: WalkerOS.Events;\n data: Array<Data>;\n mapping?: WalkerOSMapping.Rule<Mapping>;\n}\n\nexport interface BatchRegistry<Mapping> {\n [mappingKey: string]: {\n batched: Batch<Mapping>;\n batchFn: () => void;\n };\n}\n\nexport type Data =\n | WalkerOS.Property\n | undefined\n | Array<WalkerOS.Property | undefined>;\n\nexport interface Ref {\n type: string; // Destination type (\"gtag\", \"meta\", \"bigquery\")\n data?: unknown; // Response from push()\n error?: unknown; // Error if failed\n}\n\nexport type Push = {\n queuePush?: WalkerOS.Events;\n error?: unknown;\n};\n\nexport type DLQ = Array<[WalkerOS.Event, unknown]>;\n","import type { Destination, Hooks, On, WalkerOS } from '.';\n\n// Event signatures only\nexport interface EventFn<R = Promise<PushResult>> {\n (partialEvent: WalkerOS.DeepPartialEvent): R;\n (event: string): R;\n (event: string, data: WalkerOS.Properties): R;\n}\n\n// Complete function interface - can be extended by other interfaces\nexport interface Fn<R = Promise<PushResult>, Config = unknown>\n extends EventFn<R>, WalkerCommands<R, Config> {\n // Interface intentionally empty - combines EventFn and WalkerCommands\n}\n\n// Walker commands (clear, predefined list)\nexport interface WalkerCommands<R = Promise<PushResult>, Config = unknown> {\n (event: 'walker config', config: Partial<Config>): R;\n (event: 'walker consent', consent: WalkerOS.Consent): R;\n <T extends Destination.Types>(\n event: 'walker destination',\n destination: Destination.Init<T> | Destination.Instance<T>,\n config?: Destination.Config<T>,\n ): R;\n <K extends keyof Hooks.Functions>(\n event: 'walker hook',\n name: K,\n hookFn: Hooks.Functions[K],\n ): R;\n (\n event: 'walker on',\n type: On.Types,\n rules: WalkerOS.SingleOrArray<On.Options>,\n ): R;\n (event: 'walker user', user: WalkerOS.User): R;\n (\n event: 'walker run',\n runState: {\n consent?: WalkerOS.Consent;\n user?: WalkerOS.User;\n globals?: WalkerOS.Properties;\n custom?: WalkerOS.Properties;\n },\n ): R;\n}\n\nexport type Event<R = Promise<PushResult>> = (\n partialEvent: WalkerOS.DeepPartialEvent,\n) => R;\n\n// Simplified push data types for core collector\nexport type PushData<Config = unknown> =\n | WalkerOS.DeepPartial<Config>\n | WalkerOS.Consent\n | WalkerOS.User\n | WalkerOS.Properties;\n\nexport interface PushResult {\n ok: boolean;\n event?: WalkerOS.Event;\n done?: Record<string, Destination.Ref>;\n queued?: Record<string, Destination.Ref>;\n failed?: Record<string, Destination.Ref>;\n}\n\n// Simplified Layer type for core collector\nexport type Layer = Array<IArguments | WalkerOS.DeepPartialEvent | unknown[]>;\n","/**\n * Flow Configuration System\n *\n * Core types for walkerOS unified configuration.\n * Platform-agnostic, runtime-focused.\n *\n * The Flow system enables \"one config to rule them all\" - a single\n * walkeros.config.json file that manages multiple flows\n * (web_prod, web_stage, server_prod, etc.) with shared configuration,\n * variables, and reusable definitions.\n *\n * ## Connection Rules\n *\n * Sources use `next` to connect to transformers (pre-collector chain).\n * Sources cannot have `before`.\n *\n * Destinations use `before` to connect to transformers (post-collector chain).\n * Destinations cannot have `next`.\n *\n * Transformers use `next` to chain to other transformers. The same transformer\n * pool is shared by both pre-collector and post-collector chains.\n *\n * The collector is implicit — it is never referenced directly in connections.\n * It sits between the source chain and the destination chain automatically.\n *\n * Circular `next` references are safely handled at runtime by `walkChain()`\n * in the collector module (visited-set detection).\n *\n * ```\n * Source → [next → Transformer chain] → Collector → [before → Transformer chain] → Destination\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { Source, Destination, Collector } from '.';\n\n/**\n * JSON Schema object for contract entry validation.\n * Standard JSON Schema with description/examples annotations.\n * Compatible with AJV for runtime validation.\n */\nexport type ContractSchema = Record<string, unknown>;\n\n/**\n * Contract action entries keyed by action name.\n * Each value is a JSON Schema describing the expected WalkerOS.Event shape.\n * Use \"*\" as wildcard for all actions of an entity.\n */\nexport type ContractActions = Record<string, ContractSchema>;\n\n/**\n * Entity-action event map used inside contracts.\n * Keyed by entity name, each value is an action map.\n * Use \"*\" as wildcard for all entities or all actions.\n */\nexport type ContractEvents = Record<string, ContractActions>;\n\n/**\n * A single named contract entry.\n *\n * All sections are optional. Sections mirror WalkerOS.Event fields:\n * globals, context, custom, user, consent.\n * Entity-action schemas live under `events`.\n *\n * Use `extends` to inherit from another named contract (additive merge).\n */\nexport interface ContractEntry {\n /** Inherit from another named contract (additive merge). */\n extends?: string;\n\n /** Contract version number (syncs to event.version.tagging). */\n tagging?: number;\n\n /** Human-readable description of the contract. */\n description?: string;\n\n /** JSON Schema for event.globals. */\n globals?: ContractSchema;\n\n /** JSON Schema for event.context. */\n context?: ContractSchema;\n\n /** JSON Schema for event.custom. */\n custom?: ContractSchema;\n\n /** JSON Schema for event.user. */\n user?: ContractSchema;\n\n /** JSON Schema for event.consent. */\n consent?: ContractSchema;\n\n /** Entity-action event schemas. */\n events?: ContractEvents;\n}\n\n/**\n * Named contract map.\n * Each key is a contract name, each value is a contract entry.\n *\n * Example:\n * ```json\n * {\n * \"default\": { \"globals\": { ... }, \"consent\": { ... } },\n * \"web\": { \"extends\": \"default\", \"events\": { ... } },\n * \"server\": { \"extends\": \"default\", \"events\": { ... } }\n * }\n * ```\n */\nexport type Contract = Record<string, ContractEntry>;\n\n/**\n * Primitive value types for variables\n */\nexport type Primitive = string | number | boolean;\n\n/**\n * Variables record type for interpolation.\n * Used at Config, Settings, Source, and Destination levels.\n */\nexport type Variables = Record<string, Primitive>;\n\n/**\n * Definitions record type for reusable configurations.\n * Used at Config, Settings, Source, and Destination levels.\n */\nexport type Definitions = Record<string, unknown>;\n\n/**\n * Inline code definition for sources/destinations/transformers.\n * Used instead of package when defining inline functions.\n */\nexport interface InlineCode {\n push: string; // \"$code:...\" function (required)\n type?: string; // Optional instance type identifier\n init?: string; // Optional \"$code:...\" init function\n}\n\n/**\n * Packages configuration for build.\n */\nexport type Packages = Record<\n string,\n {\n version?: string;\n imports?: string[];\n path?: string; // Local path to package directory (takes precedence over version)\n }\n>;\n\n/**\n * Web platform configuration.\n *\n * @remarks\n * Presence of this key indicates web platform (browser-based tracking).\n * Builds to IIFE format, ES2020 target, browser platform.\n */\nexport interface Web {\n /**\n * Window property name for collector instance.\n * @default \"collector\"\n */\n windowCollector?: string;\n\n /**\n * Window property name for elb function.\n * @default \"elb\"\n */\n windowElb?: string;\n}\n\n/**\n * Server platform configuration.\n *\n * @remarks\n * Presence of this key indicates server platform (Node.js).\n * Builds to ESM format, Node18 target, node platform.\n * Reserved for future server-specific options.\n */\nexport interface Server {\n // Reserved for future server-specific options\n}\n\n/**\n * Complete multi-flow configuration.\n * Root type for walkeros.config.json files.\n *\n * @remarks\n * If only one flow exists, it's auto-selected without --flow flag.\n * Convention: use \"default\" as the flow name for single-flow configs.\n *\n * @example\n * ```json\n * {\n * \"version\": 3,\n * \"$schema\": \"https://walkeros.io/schema/flow/v3.json\",\n * \"variables\": { \"CURRENCY\": \"USD\" },\n * \"flows\": {\n * \"default\": { \"web\": {}, ... }\n * }\n * }\n * ```\n */\nexport interface Config {\n /**\n * Configuration schema version.\n */\n version: 3;\n\n /**\n * JSON Schema reference for IDE validation.\n * @example \"https://walkeros.io/schema/flow/v1.json\"\n */\n $schema?: string;\n\n /**\n * Folders to include in the bundle output.\n * These folders are copied to dist/ during bundle, making them available\n * at runtime for both local and Docker execution.\n *\n * @remarks\n * Use for credential files, configuration, or other runtime assets.\n * Paths are relative to the config file location.\n * Default: `[\"./shared\"]` if the folder exists, otherwise `[]`.\n *\n * @example\n * ```json\n * {\n * \"include\": [\"./credentials\", \"./config\"]\n * }\n * ```\n */\n include?: string[];\n\n /**\n * Data contract definition (version 2+).\n * Entity → action keyed JSON Schema with additive inheritance.\n */\n contract?: Contract;\n\n /**\n * Shared variables for interpolation.\n * Resolution: destination/source > Settings > Config level\n * Syntax: $var.name\n */\n variables?: Variables;\n\n /**\n * Reusable configuration definitions.\n * Syntax: $def.name\n */\n definitions?: Definitions;\n\n /**\n * Named flow configurations.\n * If only one flow exists, it's auto-selected.\n */\n flows: Record<string, Settings>;\n}\n\n/**\n * Single flow configuration.\n * Represents one deployment target (e.g., web_prod, server_stage).\n *\n * @remarks\n * Platform is determined by presence of `web` or `server` key.\n * Exactly one must be present.\n *\n * Variables/definitions cascade: source/destination > settings > config\n */\nexport interface Settings {\n /**\n * Web platform configuration.\n * Presence indicates web platform (browser-based tracking).\n * Mutually exclusive with `server`.\n */\n web?: Web;\n\n /**\n * Server platform configuration.\n * Presence indicates server platform (Node.js).\n * Mutually exclusive with `web`.\n */\n server?: Server;\n\n /**\n * Store configurations (key-value storage).\n *\n * @remarks\n * Stores provide key-value storage consumed by sources, transformers,\n * and destinations via env injection. Referenced using $store:storeId\n * prefix in env values.\n *\n * Key = unique store identifier (arbitrary)\n * Value = store reference with package and config\n */\n stores?: Record<string, StoreReference>;\n\n /**\n * Source configurations (data capture).\n *\n * @remarks\n * Sources capture events from various origins:\n * - Browser DOM interactions (clicks, page views)\n * - DataLayer pushes\n * - HTTP requests (server-side)\n * - Cloud function triggers\n *\n * Key = unique source identifier (arbitrary)\n * Value = source reference with package and config\n *\n * @example\n * ```json\n * {\n * \"sources\": {\n * \"browser\": {\n * \"package\": \"@walkeros/web-source-browser\",\n * \"config\": {\n * \"settings\": {\n * \"pageview\": true,\n * \"session\": true\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n sources?: Record<string, SourceReference>;\n\n /**\n * Destination configurations (data output).\n *\n * @remarks\n * Destinations send processed events to external services:\n * - Google Analytics (gtag)\n * - Meta Pixel (fbq)\n * - Custom APIs\n * - Data warehouses\n *\n * Key = unique destination identifier (arbitrary)\n * Value = destination reference with package and config\n *\n * @example\n * ```json\n * {\n * \"destinations\": {\n * \"gtag\": {\n * \"package\": \"@walkeros/web-destination-gtag\",\n * \"config\": {\n * \"settings\": {\n * \"ga4\": { \"measurementId\": \"G-XXXXXXXXXX\" }\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n destinations?: Record<string, DestinationReference>;\n\n /**\n * Transformer configurations (event transformation).\n *\n * @remarks\n * Transformers transform events in the pipeline:\n * - Pre-collector: Between sources and collector\n * - Post-collector: Between collector and destinations\n *\n * Key = unique transformer identifier (referenced by source.next or destination.before)\n * Value = transformer reference with package and config\n *\n * @example\n * ```json\n * {\n * \"transformers\": {\n * \"enrich\": {\n * \"package\": \"@walkeros/transformer-enricher\",\n * \"config\": { \"apiUrl\": \"https://api.example.com\" },\n * \"next\": \"validate\"\n * },\n * \"validate\": {\n * \"package\": \"@walkeros/transformer-validator\"\n * }\n * }\n * }\n * ```\n */\n transformers?: Record<string, TransformerReference>;\n\n /**\n * Collector configuration (event processing).\n *\n * @remarks\n * The collector is the central event processing engine.\n * Configuration includes:\n * - Consent management\n * - Global properties\n * - User identification\n * - Processing rules\n *\n * @see {@link Collector.InitConfig} for complete options\n *\n * @example\n * ```json\n * {\n * \"collector\": {\n * \"run\": true,\n * \"tagging\": 1,\n * \"consent\": {\n * \"functional\": true,\n * \"marketing\": false\n * },\n * \"globals\": {\n * \"currency\": \"USD\",\n * \"environment\": \"production\"\n * }\n * }\n * }\n * ```\n */\n collector?: Collector.InitConfig;\n\n /**\n * NPM packages to bundle.\n */\n packages?: Packages;\n\n /**\n * Flow-level variables.\n * Override Config.variables, overridden by source/destination variables.\n */\n variables?: Variables;\n\n /**\n * Flow-level definitions.\n * Extend Config.definitions, overridden by source/destination definitions.\n */\n definitions?: Definitions;\n}\n\n/**\n * Named example pair for a step.\n * `in` is the input to the step, `out` is the expected output.\n * `out: false` indicates the step filters/drops this event.\n */\nexport interface StepExample {\n description?: string;\n in?: unknown;\n /** Trigger metadata for sources — type and options for the trigger call. */\n trigger?: {\n /** Which mechanism to activate (e.g., 'click', 'POST', 'load'). */\n type?: string;\n /** Mechanism-specific options (e.g., CSS selector, threshold). */\n options?: unknown;\n };\n mapping?: unknown;\n out?: unknown;\n}\n\n/**\n * Named step examples keyed by scenario name.\n */\nexport type StepExamples = Record<string, StepExample>;\n\n/**\n * Source reference with inline package syntax.\n *\n * @remarks\n * References a source package and provides configuration.\n * The package is automatically downloaded and imported during build.\n * Alternatively, use `code: true` for inline code execution.\n */\nexport interface SourceReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Formats:\n * - `\"@walkeros/web-source-browser\"` - Latest version\n * - `\"@walkeros/web-source-browser@2.0.0\"` - Specific version\n * - `\"@walkeros/web-source-browser@^2.0.0\"` - Semver range\n *\n * The CLI will:\n * 1. Parse the package reference\n * 2. Download from npm\n * 3. Auto-detect default or named export\n * 4. Generate import statement\n *\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/web-source-browser@latest\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code source.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"logger\",\n * \"push\": \"$code:(event) => console.log(event)\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Source-specific configuration.\n *\n * @remarks\n * Structure depends on the source package.\n * Passed to the source's initialization function.\n *\n * @example\n * ```json\n * {\n * \"config\": {\n * \"settings\": {\n * \"pageview\": true,\n * \"session\": true,\n * \"elb\": \"elb\",\n * \"prefix\": \"data-elb\"\n * }\n * }\n * }\n * ```\n */\n config?: unknown;\n\n /**\n * Source environment configuration.\n *\n * @remarks\n * Environment-specific settings for the source.\n * Merged with default source environment.\n */\n env?: unknown;\n\n /**\n * Mark as primary source (provides main ELB).\n *\n * @remarks\n * The primary source's ELB function is returned by `startFlow()`.\n * Only one source should be marked as primary per flow.\n *\n * @default false\n */\n primary?: boolean;\n\n /**\n * Source-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Source-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * First transformer in pre-collector chain.\n *\n * @remarks\n * Name of the transformer to execute after this source captures an event.\n * Creates a pre-collector transformer chain. Chain ends at the collector.\n * If omitted, events route directly to the collector.\n * Can be an array for explicit chain control (bypasses transformer.next resolution).\n */\n next?: string | string[];\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n\n/**\n * Transformer reference with inline package syntax.\n *\n * @remarks\n * References a transformer package and provides configuration.\n * Transformers transform events in the pipeline between sources and destinations.\n * Alternatively, use `code: true` for inline code execution.\n */\nexport interface TransformerReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Same format as SourceReference.package\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/transformer-enricher@1.0.0\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code transformer.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"enricher\",\n * \"push\": \"$code:(event) => ({ ...event, data: { enriched: true } })\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Transformer-specific configuration.\n *\n * @remarks\n * Structure depends on the transformer package.\n * Passed to the transformer's initialization function.\n */\n config?: unknown;\n\n /**\n * Transformer environment configuration.\n *\n * @remarks\n * Environment-specific settings for the transformer.\n * Merged with default transformer environment.\n */\n env?: unknown;\n\n /**\n * Next transformer in chain.\n *\n * @remarks\n * Name of the next transformer to execute after this one.\n * When used in a pre-collector chain (source.next), terminates at the collector.\n * When used in a post-collector chain (destination.before), terminates at the destination.\n * If omitted, the chain ends and control passes to the next pipeline stage.\n * Array values define an explicit chain (no walking). Circular references\n * are safely detected at runtime by `walkChain()`.\n */\n next?: string | string[];\n\n /**\n * Transformer-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Transformer-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n\n/**\n * Store reference with inline package syntax.\n *\n * @remarks\n * References a store package and provides configuration.\n * Stores provide key-value storage consumed by other components via env.\n * Unlike sources/transformers/destinations, stores have no chain properties\n * (no `next` or `before`) — they are passive infrastructure.\n */\nexport interface StoreReference {\n /**\n * Package specifier with optional version.\n * Optional when `code` is provided for inline code.\n */\n package?: string;\n\n /**\n * Resolved import variable name or inline code definition.\n */\n code?: string | InlineCode;\n\n /**\n * Store-specific configuration.\n */\n config?: unknown;\n\n /**\n * Store environment configuration.\n */\n env?: unknown;\n\n /**\n * Store-level variables (highest priority in cascade).\n */\n variables?: Variables;\n\n /**\n * Store-level definitions (highest priority in cascade).\n */\n definitions?: Definitions;\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution.\n */\n examples?: StepExamples;\n}\n\n/**\n * Destination reference with inline package syntax.\n *\n * @remarks\n * References a destination package and provides configuration.\n * Structure mirrors SourceReference for consistency.\n */\nexport interface DestinationReference {\n /**\n * Package specifier with optional version.\n *\n * @remarks\n * Same format as SourceReference.package\n * Optional when `code: true` is used for inline code execution.\n *\n * @example\n * \"package\": \"@walkeros/web-destination-gtag@2.0.0\"\n */\n package?: string;\n\n /**\n * Resolved import variable name or built-in code destination.\n *\n * @remarks\n * - String: Auto-resolved from packages[package].imports[0] during getFlowSettings(),\n * or provided explicitly for advanced use cases.\n * - InlineCode: Object with type, push, and optional init for inline code definition.\n *\n * @example\n * // Using inline code object\n * {\n * \"code\": {\n * \"type\": \"logger\",\n * \"push\": \"$code:(event) => console.log('Event:', event.name)\"\n * }\n * }\n */\n code?: string | InlineCode; // string for package import, InlineCode for inline\n\n /**\n * Destination-specific configuration.\n *\n * @remarks\n * Structure depends on the destination package.\n * Typically includes:\n * - settings: API keys, IDs, endpoints\n * - mapping: Event transformation rules\n * - consent: Required consent states\n * - policy: Processing rules\n *\n * @example\n * ```json\n * {\n * \"config\": {\n * \"settings\": {\n * \"ga4\": {\n * \"measurementId\": \"G-XXXXXXXXXX\"\n * }\n * },\n * \"mapping\": {\n * \"page\": {\n * \"view\": {\n * \"name\": \"page_view\",\n * \"data\": { ... }\n * }\n * }\n * }\n * }\n * }\n * ```\n */\n config?: unknown;\n\n /**\n * Destination environment configuration.\n *\n * @remarks\n * Environment-specific settings for the destination.\n * Merged with default destination environment.\n */\n env?: unknown;\n\n /**\n * Destination-level variables (highest priority in cascade).\n * Overrides flow and setup variables.\n */\n variables?: Variables;\n\n /**\n * Destination-level definitions (highest priority in cascade).\n * Overrides flow and setup definitions.\n */\n definitions?: Definitions;\n\n /**\n * First transformer in post-collector chain.\n *\n * @remarks\n * Name of the transformer to execute before sending events to this destination.\n * Creates a post-collector transformer chain. Chain ends at this destination.\n * If omitted, events are sent directly from the collector.\n * Can be an array for explicit chain control (bypasses transformer.next resolution).\n */\n before?: string | string[];\n\n /**\n * Named examples for testing and documentation.\n * Stripped during flow resolution (not included in bundles).\n */\n examples?: StepExamples;\n}\n","// Define a generic type for functions with specific parameters and return type\nexport type AnyFunction<P extends unknown[] = never[], R = unknown> = (\n ...args: P\n) => R;\n\n// Define a generic type for a dictionary of functions\nexport type Functions = {\n [key: string]: AnyFunction;\n};\n\n// Define a parameter interface to wrap the function and its result\ninterface Parameter<P extends unknown[], R> {\n fn: (...args: P) => R;\n result?: R;\n}\n\n// Define the HookFn type using generics for better type safety\nexport type HookFn<T extends AnyFunction> = (\n params: Parameter<Parameters<T>, ReturnType<T>>,\n ...args: Parameters<T>\n) => ReturnType<T>;\n","/**\n * Log levels from most to least severe\n */\nexport enum Level {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n}\n\n/**\n * Normalized error context extracted from Error objects\n */\nexport interface ErrorContext {\n message: string;\n name: string;\n stack?: string;\n cause?: unknown;\n}\n\n/**\n * Context passed to log handlers\n * If an Error was passed, it's normalized into the error property\n */\nexport interface LogContext {\n [key: string]: unknown;\n error?: ErrorContext;\n}\n\n/**\n * Log message function signature\n * Accepts string or Error as message, with optional context\n */\nexport type LogFn = (\n message: string | Error,\n context?: unknown | Error,\n) => void;\n\n/**\n * Throw function signature - logs error then throws\n * Returns never as it always throws\n */\nexport type ThrowFn = (message: string | Error, context?: unknown) => never;\n\n/**\n * Default handler function (passed to custom handlers for chaining)\n */\nexport type DefaultHandler = (\n level: Level,\n message: string,\n context: LogContext,\n scope: string[],\n) => void;\n\n/**\n * Custom log handler function\n * Receives originalHandler to allow middleware-style chaining\n */\nexport type Handler = (\n level: Level,\n message: string,\n context: LogContext,\n scope: string[],\n originalHandler: DefaultHandler,\n) => void;\n\n/**\n * Logger instance with scoping support\n * All logs automatically include trace path from scoping\n */\nexport interface Instance {\n /**\n * Log an error message (always visible unless silenced)\n */\n error: LogFn;\n\n /**\n * Log a warning (degraded state, config issues, transient failures)\n */\n warn: LogFn;\n\n /**\n * Log an informational message\n */\n info: LogFn;\n\n /**\n * Log a debug message\n */\n debug: LogFn;\n\n /**\n * Log an error message and throw an Error\n * Combines logging and throwing in one call\n */\n throw: ThrowFn;\n\n /**\n * Output structured JSON data\n */\n json: (data: unknown) => void;\n\n /**\n * Create a scoped child logger with automatic trace path\n * @param name - Scope name (e.g., destination type, destination key)\n * @returns A new logger instance with the scope applied\n */\n scope: (name: string) => Instance;\n}\n\n/**\n * Logger configuration options\n */\nexport interface Config {\n /**\n * Minimum log level to display\n * @default Level.ERROR\n */\n level?: Level | keyof typeof Level;\n\n /**\n * Custom log handler function\n * Receives originalHandler to preserve default behavior\n */\n handler?: Handler;\n\n /** Custom handler for json() output. Default: console.log(JSON.stringify(data, null, 2)) */\n jsonHandler?: (data: unknown) => void;\n}\n\n/**\n * Internal config with resolved values and scope\n */\nexport interface InternalConfig {\n level: Level;\n handler?: Handler;\n jsonHandler?: (data: unknown) => void;\n scope: string[];\n}\n\n/**\n * Logger factory function type\n */\nexport type Factory = (config?: Config) => Instance;\n","import type { Collector, Destination, WalkerOS } from '.';\n\n/**\n * Shared mapping configuration interface.\n * Used by both Source.Config and Destination.Config.\n */\nexport interface Config<T = unknown> {\n consent?: WalkerOS.Consent; // Required consent to process events\n data?: Value | Values; // Global data transformation\n mapping?: Rules<Rule<T>>; // Event-specific mapping rules\n policy?: Policy; // Pre-processing rules\n}\n\nexport interface Policy {\n [key: string]: Value;\n}\n\nexport interface Rules<T = Rule> {\n [entity: string]: Record<string, T | Array<T>> | undefined;\n}\n\nexport interface Rule<Settings = unknown> {\n batch?: number; // Bundle events for batch processing\n batchFn?: (\n destination: Destination.Instance,\n collector: Collector.Instance,\n ) => void;\n batched?: Destination.Batch<Settings>; // Batch of events to be processed\n condition?: Condition; // Added condition\n consent?: WalkerOS.Consent; // Required consent states process the event\n settings?: Settings; // Arbitrary but protected configurations for custom event config\n data?: Data; // Mapping of event data\n ignore?: boolean; // Choose to no process an event when set to true\n name?: string; // Use a custom event name\n policy?: Policy; // Event-level policy applied after config-level policy\n}\n\nexport interface Result {\n eventMapping?: Rule;\n mappingKey?: string;\n}\n\nexport type Data = Value | Values;\nexport type Value = ValueType | Array<ValueType>;\nexport type Values = Array<Value>;\nexport type ValueType = string | ValueConfig;\n\nexport interface ValueConfig {\n condition?: Condition;\n consent?: WalkerOS.Consent;\n fn?: Fn;\n key?: string;\n loop?: Loop;\n map?: Map;\n set?: Value[];\n validate?: Validate;\n value?: WalkerOS.PropertyType;\n}\n\nexport type Condition = (\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping?: Value,\n collector?: Collector.Instance,\n) => WalkerOS.PromiseOrValue<boolean>;\n\nexport type Fn = (\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping: Value,\n options: Options,\n) => WalkerOS.PromiseOrValue<WalkerOS.Property | unknown>;\n\nexport type Loop = [Value, Value];\n\nexport type Map = { [key: string]: Value };\n\nexport interface Options {\n consent?: WalkerOS.Consent;\n collector?: Collector.Instance;\n props?: unknown;\n}\n\nexport type Validate = (value?: unknown) => WalkerOS.PromiseOrValue<boolean>;\n","import type { Collector, Destination, WalkerOS } from './';\n\n// collector state for the on actions\nexport type Config = {\n config?: Array<GenericConfig>;\n consent?: Array<ConsentConfig>;\n custom?: Array<GenericConfig>;\n globals?: Array<GenericConfig>;\n ready?: Array<ReadyConfig>;\n run?: Array<RunConfig>;\n session?: Array<SessionConfig>;\n user?: Array<UserConfig>;\n};\n\n// On types — allow arbitrary string events via `(string & {})`\nexport type Types = keyof Config | (string & {});\n\n// Map each event type to its expected context type\nexport interface EventContextMap {\n config: Partial<Collector.Config>;\n consent: WalkerOS.Consent;\n custom: WalkerOS.Properties;\n globals: WalkerOS.Properties;\n ready: undefined;\n run: undefined;\n session: Collector.SessionData;\n user: WalkerOS.User;\n}\n\n// Extract the context type for a specific event\nexport type EventContext<T extends keyof EventContextMap> = EventContextMap[T];\n\n// Union of all possible context types\nexport type AnyEventContext = EventContextMap[keyof EventContextMap];\n\n// Legacy context interface (can be removed in future)\nexport interface Context {\n consent?: WalkerOS.Consent;\n session?: unknown;\n}\n\n// Parameters for the onAction function calls\nexport type Options =\n | ConsentConfig\n | GenericConfig\n | ReadyConfig\n | RunConfig\n | SessionConfig\n | UserConfig;\n\n// Consent\nexport interface ConsentConfig {\n [key: string]: ConsentFn;\n}\nexport type ConsentFn = (\n collector: Collector.Instance,\n consent: WalkerOS.Consent,\n) => void;\n\n// Generic (config, custom, globals)\nexport type GenericConfig = GenericFn;\nexport type GenericFn = (collector: Collector.Instance, data: unknown) => void;\n\n// Ready\nexport type ReadyConfig = ReadyFn;\nexport type ReadyFn = (collector: Collector.Instance) => void;\n\n// Run\nexport type RunConfig = RunFn;\nexport type RunFn = (collector: Collector.Instance) => void;\n\n// Session\nexport type SessionConfig = SessionFn;\nexport type SessionFn = (\n collector: Collector.Instance,\n session?: unknown,\n) => void;\n\n// User\nexport type UserConfig = UserFn;\nexport type UserFn = (\n collector: Collector.Instance,\n user: WalkerOS.User,\n) => void;\n\nexport interface OnConfig {\n config?: GenericConfig[];\n consent?: ConsentConfig[];\n custom?: GenericConfig[];\n globals?: GenericConfig[];\n ready?: ReadyConfig[];\n run?: RunConfig[];\n session?: SessionConfig[];\n user?: UserConfig[];\n [key: string]:\n | ConsentConfig[]\n | GenericConfig[]\n | ReadyConfig[]\n | RunConfig[]\n | SessionConfig[]\n | UserConfig[]\n | undefined;\n}\n\n// Destination on function type with automatic type inference\nexport type OnFn<T extends Destination.TypesGeneric = Destination.Types> = (\n type: Types,\n context: Destination.Context<T>,\n) => WalkerOS.PromiseOrValue<void>;\n\n// Runtime-compatible version for internal usage\nexport type OnFnRuntime = (\n type: Types,\n context: Destination.Context,\n) => WalkerOS.PromiseOrValue<void>;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Collector, Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn } from './lifecycle';\n\nexport type Next = string | string[];\n\n/**\n * Base environment interface for walkerOS transformers.\n *\n * Minimal like Destination - just an extensible object.\n * Transformers receive dependencies through context, not env.\n */\nexport interface BaseEnv {\n [key: string]: unknown;\n}\n\n/**\n * Type bundle for transformer generics.\n * Groups Settings, InitSettings, and Env into a single type parameter.\n * Follows the Source/Destination pattern.\n *\n * @template S - Settings configuration type\n * @template E - Environment type\n * @template I - InitSettings configuration type (user input)\n */\nexport interface Types<S = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access.\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle.\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance.\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\n/**\n * Transformer configuration.\n */\nexport interface Config<T extends TypesGeneric = Types> {\n settings?: InitSettings<T>;\n env?: Env<T>;\n id?: string;\n logger?: Logger.Config;\n next?: Next; // Graph wiring to next transformer\n init?: boolean; // Track init state (like Destination)\n}\n\n/**\n * Context provided to transformer functions.\n * Extends base context with transformer-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n ingest?: unknown;\n}\n\n/**\n * Unified result type for transformer functions.\n * Replaces the old union return type with a structured object.\n *\n * @field event - Modified event to continue with\n * @field respond - Wrapped respond function for downstream transformers\n * @field next - Branch to a different chain (replaces BranchResult)\n */\nexport interface Result {\n event?: WalkerOS.DeepPartialEvent;\n respond?: import('../respond').RespondFn;\n next?: Next;\n}\n\n/**\n * The main transformer function.\n * Uses DeepPartialEvent for consistency across pre/post collector.\n *\n * @param event - The event to process\n * @param context - Transformer context with collector, config, env, logger\n * @returns Result - structured result with event, respond, next\n * @returns void - continue with current event unchanged (passthrough)\n * @returns false - stop chain, cancel further processing\n */\nexport type Fn<T extends TypesGeneric = Types> = (\n event: WalkerOS.DeepPartialEvent,\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<Result | false | void>;\n\n/**\n * Optional initialization function.\n * Called once before first push.\n *\n * @param context - Transformer context\n * @returns void - initialization successful\n * @returns false - initialization failed, skip this transformer\n * @returns Config<T> - return updated config\n */\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\n/**\n * Transformer instance returned by Init function.\n */\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n push: Fn<T>; // Named \"push\" for consistency with Source/Destination\n init?: InitFn<T>; // Optional, called once before first push\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\n/**\n * Transformer initialization function.\n * Creates a transformer instance from context.\n */\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\n/**\n * Configuration for initializing a transformer.\n * Used in collector registration.\n */\nexport type InitTransformer<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n next?: Next;\n};\n\n/**\n * Transformers configuration for collector.\n * Maps transformer IDs to their initialization configurations.\n */\nexport interface InitTransformers {\n [transformerId: string]: InitTransformer<any>;\n}\n\n/**\n * Active transformer instances registry.\n */\nexport interface Transformers {\n [transformerId: string]: Instance;\n}\n","export interface Context {\n city?: string;\n country?: string;\n encoding?: string;\n hash?: string;\n ip?: string;\n language?: string;\n origin?: string;\n region?: string;\n userAgent?: string;\n [key: string]: string | undefined;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n Elb,\n On,\n Logger,\n Mapping as WalkerOSMapping,\n Collector,\n Context as BaseContext,\n} from './index';\nimport type { DestroyFn } from './lifecycle';\nimport type { Next } from './transformer';\n\n/**\n * Base Env interface for dependency injection into sources.\n *\n * Sources receive all their dependencies through this environment object,\n * making them platform-agnostic and easily testable.\n */\nexport interface BaseEnv {\n [key: string]: unknown;\n push: Collector.PushFn;\n command: Collector.CommandFn;\n sources?: Collector.Sources;\n elb: Elb.Fn;\n logger: Logger.Instance;\n}\n\n/**\n * Type bundle for source generics.\n * Groups Settings, Mapping, Push, Env, and InitSettings into a single type parameter.\n *\n * @template S - Settings configuration type\n * @template M - Mapping configuration type\n * @template P - Push function signature (flexible to support HTTP handlers, etc.)\n * @template E - Environment dependencies type\n * @template I - InitSettings configuration type (user input)\n */\nexport interface Types<\n S = unknown,\n M = unknown,\n P = Elb.Fn,\n E = BaseEnv,\n I = S,\n> {\n settings: S;\n initSettings: I;\n mapping: M;\n push: P;\n env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n mapping: any;\n push: any;\n env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Push<T extends TypesGeneric = Types> = T['push'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<\n T extends TypesGeneric = Types,\n> extends WalkerOSMapping.Config<Mapping<T>> {\n /** Implementation-specific configuration passed to the init function. */\n settings?: InitSettings<T>;\n /** Runtime dependencies injected by the collector (push, command, logger, etc.). */\n env?: Env<T>;\n /** Source identifier; defaults to the InitSources object key. */\n id?: string;\n /** Logger configuration (level, handler) to override the collector's defaults. */\n logger?: Logger.Config;\n /** Mark as primary source; its push function becomes the exported `elb` from startFlow. */\n primary?: boolean;\n /** Defer source initialization until these collector events fire (e.g., `['consent']`). */\n require?: string[];\n /**\n * Ingest metadata extraction mapping.\n * Extracts values from raw request objects (Express req, Lambda event, etc.)\n * using walkerOS mapping syntax. Extracted data flows to transformers/destinations.\n *\n * @example\n * ingest: {\n * ip: 'req.ip',\n * ua: 'req.headers.user-agent',\n * origin: 'req.headers.origin'\n * }\n */\n ingest?: WalkerOSMapping.Data;\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n Types<\n Partial<Settings<T>> | Settings<T>,\n Partial<Mapping<T>> | Mapping<T>,\n Push<T>,\n Env<T>\n >\n>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n push: Push<T>;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n on?(\n event: On.Types,\n context?: unknown,\n ): void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Context provided to source init function.\n * Extends base context with source-specific properties.\n */\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Partial<Config<T>>, Env<T>> {\n id: string;\n /**\n * Sets ingest metadata for the current request.\n * Extracts values from the raw request using config.ingest mapping.\n * The extracted data is passed through to transformers and destinations.\n *\n * @param value - Raw request object (Express req, Lambda event, etc.)\n */\n setIngest: (value: unknown) => Promise<void>;\n /** Sets respond function for the current request. Called by source per-request. */\n setRespond: (fn: import('../respond').RespondFn | undefined) => void;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitSource<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n primary?: boolean;\n next?: Next;\n};\n\n/**\n * Sources configuration for collector.\n * Maps source IDs to their initialization configurations.\n */\nexport interface InitSources {\n [sourceId: string]: InitSource<any>;\n}\n\n/**\n * Renderer hint for source simulation UI.\n * - 'browser': Source needs a real DOM (iframe with live preview)\n * - 'codebox': Source uses a JSON/code editor (default)\n */\nexport type Renderer = 'browser' | 'codebox';\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn } from './lifecycle';\n\nexport interface BaseEnv {\n [key: string]: unknown;\n}\n\nexport interface Types<S = unknown, E = BaseEnv, I = S> {\n settings: S;\n initSettings: I;\n env: E;\n}\n\nexport type TypesGeneric = {\n settings: any;\n initSettings: any;\n env: any;\n};\n\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<T extends TypesGeneric = Types> {\n settings?: InitSettings<T>;\n env?: Env<T>;\n id?: string;\n logger?: Logger.Config;\n}\n\nexport interface Context<\n T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n id: string;\n}\n\nexport type GetFn<T = unknown> = (\n key: string,\n) => T | undefined | Promise<T | undefined>;\n\nexport type SetFn<T = unknown> = (\n key: string,\n value: T,\n ttl?: number,\n) => void | Promise<void>;\n\nexport type DeleteFn = (key: string) => void | Promise<void>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n type: string;\n config: Config<T>;\n get: GetFn;\n set: SetFn;\n delete: DeleteFn;\n destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type InitStore<T extends TypesGeneric = Types> = {\n code: Init<T>;\n config?: Partial<Config<T>>;\n env?: Partial<Env<T>>;\n};\n\nexport interface InitStores {\n [storeId: string]: InitStore<any>;\n}\n\nexport interface Stores {\n [storeId: string]: Instance;\n}\n","/**\n * Trigger — unified interface for invoking any walkerOS step in simulation\n * and testing. Every package exports a `createTrigger` factory from its\n * examples that conforms to `Trigger.CreateFn`.\n *\n * Usage:\n * const { flow, trigger } = await createTrigger(initConfig);\n * const result = await trigger(type?, options?)(content);\n *\n * @packageDocumentation\n */\n\nimport type { Collector, Elb } from '.';\n\n/** Flow access handle returned by createTrigger. */\nexport interface FlowHandle {\n /** The collector instance created by startFlow. */\n collector: Collector.Instance;\n /** The elb push function for direct event injection. */\n elb: Elb.Fn;\n}\n\n/** What createTrigger returns — a flow handle (lazy) and a trigger function. */\nexport interface Instance<TContent = unknown, TResult = unknown> {\n /** Flow handle — undefined until first trigger() call, then stable. */\n readonly flow: FlowHandle | undefined;\n trigger: Fn<TContent, TResult>;\n}\n\n/**\n * Curried trigger function — always async.\n *\n * First call selects mechanism (type) and configures it (options).\n * Second call fires with content and returns result.\n *\n * @example\n * // Browser source — click trigger\n * trigger('click', 'button.cta')('<button data-elb=\"cta\">Sign Up</button>')\n *\n * // Express source — POST request\n * trigger('POST')({ path: '/collect', body: { name: 'page view' } })\n *\n * // DataLayer — default mechanism\n * trigger()(['event', 'purchase', { value: 25.42 }])\n */\nexport type Fn<TContent = unknown, TResult = unknown> = (\n type?: string,\n options?: unknown,\n) => (content: TContent) => Promise<TResult>;\n\n/**\n * Factory function exported by each package's examples.\n *\n * Receives full Collector.InitConfig. Does NOT call startFlow eagerly —\n * startFlow is deferred to the first trigger() invocation (lazy init).\n * The flow property uses a getter to read the closure variable live.\n * createTrigger itself stays async for consistency (other packages may\n * need await during setup). Config is passed through UNMODIFIED —\n * validation is startFlow's job.\n *\n * @example\n * // Package exports:\n * export const createTrigger: Trigger.CreateFn<HTMLContent, void> = async (config) => {\n * let flow: Trigger.FlowHandle | undefined;\n *\n * const trigger: Trigger.Fn<HTMLContent, void> = (type?, options?) => async (content) => {\n * // Pre-startFlow work (e.g., inject HTML for browser source)\n * // ...\n *\n * // Lazy init — only on first call\n * if (!flow) flow = await startFlow(config);\n *\n * // Post-startFlow work (e.g., dispatch click event)\n * // ...\n * };\n *\n * return {\n * get flow() { return flow; },\n * trigger,\n * };\n * };\n */\nexport type CreateFn<TContent = unknown, TResult = unknown> = (\n config: Collector.InitConfig,\n options?: unknown,\n) => Promise<Instance<TContent, TResult>>;\n","// packages/core/src/types/lifecycle.ts\nimport type { Logger, WalkerOS } from '.';\n\n/**\n * Context provided to the destroy() lifecycle method.\n *\n * A subset of the init context — config, env, logger, and id.\n * Does NOT include collector or event data. Destroy should only\n * clean up resources, not interact with the event pipeline.\n */\nexport interface DestroyContext<C = unknown, E = unknown> {\n /** Step instance ID. */\n id: string;\n /** Step configuration (contains settings with SDK clients, etc.). */\n config: C;\n /** Runtime environment/dependencies (DB clients, auth clients, etc.). */\n env: E;\n /** Scoped logger for this step instance. */\n logger: Logger.Instance;\n}\n\n/**\n * Destroy function signature for step lifecycle cleanup.\n *\n * Implementations should be idempotent — calling destroy() twice must not throw.\n * Used for closing connections, clearing timers, releasing SDK clients.\n */\nexport type DestroyFn<C = unknown, E = unknown> = (\n context: DestroyContext<C, E>,\n) => WalkerOS.PromiseOrValue<void>;\n","import type { Elb as ElbTypes } from '.';\n\nexport type AnyObject<T = unknown> = Record<string, T>;\nexport type Elb = ElbTypes.Fn;\nexport type AnyFunction = (...args: unknown[]) => unknown;\nexport type SingleOrArray<T> = T | Array<T>;\n\nexport type Events = Array<Event>;\nexport type PartialEvent = Partial<Event>;\nexport type DeepPartialEvent = DeepPartial<Event>;\nexport interface Event {\n name: string;\n data: Properties;\n context: OrderedProperties;\n globals: Properties;\n custom: Properties;\n user: User;\n nested: Entities;\n consent: Consent;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n group: string;\n count: number;\n version: Version;\n source: Source;\n}\n\nexport interface Consent {\n [name: string]: boolean; // name of consent group or tool\n}\n\nexport interface User extends Properties {\n // IDs\n id?: string;\n device?: string;\n session?: string;\n hash?: string;\n // User related\n address?: string;\n email?: string;\n phone?: string;\n userAgent?: string;\n browser?: string;\n browserVersion?: string;\n deviceType?: string;\n language?: string;\n country?: string;\n region?: string;\n city?: string;\n zip?: string;\n timezone?: string;\n os?: string;\n osVersion?: string;\n screenSize?: string;\n ip?: string;\n internal?: boolean;\n}\n\nexport interface Version extends Properties {\n source: string;\n tagging: number;\n}\n\nexport interface Source extends Properties {\n type: SourceType;\n id: string; // https://github.com/elbwalker/walkerOS\n previous_id: string; // https://www.elbwalker.com/\n}\n\nexport type SourceType = 'web' | 'server' | 'app' | 'other' | string;\n\nexport type PropertyType =\n | boolean\n | string\n | number\n | { [key: string]: Property };\n\nexport type Property = PropertyType | Array<PropertyType>;\n\nexport interface Properties {\n [key: string]: Property | undefined;\n}\nexport interface OrderedProperties {\n [key: string]: [Property, number] | undefined;\n}\n\nexport type Entities = Array<Entity>;\nexport interface Entity {\n entity: string;\n data: Properties;\n nested: Entities;\n context: OrderedProperties;\n}\n\nexport type ConsentHandler = Record<string, AnyFunction>;\nexport type ActionHandler = AnyFunction;\n\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type PromiseOrValue<T> = T | Promise<T>;\n","import type { WalkerOS } from '.';\n\n/**\n * A recorded function call made during simulation.\n * Captures what a destination called on its env (e.g., window.gtag).\n */\nexport interface Call {\n /** Dot-path of the function called: \"window.gtag\", \"dataLayer.push\" */\n fn: string;\n /** Arguments passed to the function */\n args: unknown[];\n /** Unix timestamp in ms */\n ts: number;\n}\n\n/**\n * Result of simulating a single step.\n * Same shape for source, transformer, and destination.\n */\nexport interface Result {\n /** Which step type was simulated */\n step: 'source' | 'transformer' | 'destination';\n /** Step name, e.g. \"gtag\", \"dataLayer\", \"enricher\" */\n name: string;\n /**\n * Output events:\n * - source: captured pre-collector events\n * - transformer: [transformed event] or [] if filtered\n * - destination: [] (destinations don't produce events)\n */\n events: WalkerOS.DeepPartialEvent[];\n /** Intercepted env calls. Populated for destinations, empty [] for others. */\n calls: Call[];\n /** Execution time in ms */\n duration: number;\n /** Error if the step threw */\n error?: Error;\n}\n","export type MatchExpression =\n | MatchCondition\n | { and: MatchExpression[] }\n | { or: MatchExpression[] };\n\nexport interface MatchCondition {\n key: string;\n operator: MatchOperator;\n value: string;\n not?: boolean;\n}\n\nexport type MatchOperator =\n | 'eq'\n | 'contains'\n | 'prefix'\n | 'suffix'\n | 'regex'\n | 'gt'\n | 'lt'\n | 'exists';\n\n// Compiled matcher (internal)\nexport type CompiledMatcher = (ingest: Record<string, unknown>) => boolean;\n","export interface Code {\n lang?: string;\n code: string;\n}\n\nexport interface Hint {\n text: string;\n code?: Array<Code>;\n}\n\nexport type Hints = Record<string, Hint>;\n","export type StorageType = 'local' | 'session' | 'cookie';\n\nexport const Storage = {\n Local: 'local' as const,\n Session: 'session' as const,\n Cookie: 'cookie' as const,\n} as const;\n\nexport const Const = {\n Utils: {\n Storage,\n },\n} as const;\n","import type { Transformer, WalkerOS } from './types';\n\n/**\n * Creates a TransformerResult for dynamic chain routing.\n * Use this in transformer push functions to redirect the chain.\n */\nexport function branch(\n event: WalkerOS.DeepPartialEvent,\n next: Transformer.Next,\n): Transformer.Result {\n return { event, next };\n}\n","/**\n * Anonymizes an IPv4 address by setting the last octet to 0.\n *\n * @param ip The IP address to anonymize.\n * @returns The anonymized IP address or an empty string if the IP is invalid.\n */\nexport function anonymizeIP(ip: string): string {\n const ipv4Pattern = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\n\n if (!ipv4Pattern.test(ip)) return '';\n\n return ip.replace(/\\.\\d+$/, '.0'); // Set the last octet to 0\n}\n","/**\n * Throws an error.\n *\n * @param error The error to throw.\n */\nexport function throwError(error: unknown): never {\n throw new Error(String(error));\n}\n","import type { Flow } from './types';\nimport { throwError } from './throwError';\n\n/** Section keys that map to WalkerOS.Event fields. */\nconst SECTION_KEYS = [\n 'globals',\n 'context',\n 'custom',\n 'user',\n 'consent',\n] as const;\n\n/** Annotation keys to strip from AJV-compatible schemas. */\nconst ANNOTATION_KEYS = new Set([\n 'description',\n 'examples',\n 'title',\n '$comment',\n]);\n\n/**\n * Resolve all named contracts: process extends chains, expand wildcards,\n * strip annotations from event schemas.\n *\n * Returns a fully resolved map where each contract entry has inherited\n * properties merged in and wildcards expanded into concrete actions.\n */\nexport function resolveContracts(\n contracts: Flow.Contract,\n): Record<string, Flow.ContractEntry> {\n const resolved: Record<string, Flow.ContractEntry> = {};\n const resolving = new Set<string>(); // Circular detection\n\n function resolve(name: string): Flow.ContractEntry {\n if (resolved[name]) return resolved[name];\n\n if (resolving.has(name)) {\n throwError(\n `Circular extends chain detected: ${[...resolving, name].join(' → ')}`,\n );\n }\n\n const entry = contracts[name];\n if (!entry) {\n throwError(`Contract \"${name}\" not found`);\n }\n\n resolving.add(name);\n\n let result: Flow.ContractEntry = {};\n\n // 1. Resolve parent first (if extends)\n if (entry.extends) {\n const parent = resolve(entry.extends);\n result = mergeContractEntries(parent, entry);\n } else {\n result = { ...entry };\n }\n\n // Remove extends from resolved entry\n delete result.extends;\n\n // 2. Expand wildcards in events\n if (result.events) {\n result.events = expandWildcards(result.events);\n }\n\n // 3. Strip annotations from event schemas (not from section schemas)\n if (result.events) {\n const stripped: Flow.ContractEvents = {};\n for (const [entity, actions] of Object.entries(result.events)) {\n stripped[entity] = {};\n for (const [action, schema] of Object.entries(actions)) {\n stripped[entity][action] = stripAnnotations(schema);\n }\n }\n result.events = stripped;\n }\n\n resolving.delete(name);\n resolved[name] = result;\n return result;\n }\n\n // Resolve all contracts\n for (const name of Object.keys(contracts)) {\n resolve(name);\n }\n\n return resolved;\n}\n\n/**\n * Merge two contract entries additively.\n * Sections merge via mergeContractSchemas.\n * Events merge at the entity-action level.\n * Metadata: child wins for scalars.\n */\nfunction mergeContractEntries(\n parent: Flow.ContractEntry,\n child: Flow.ContractEntry,\n): Flow.ContractEntry {\n const result: Flow.ContractEntry = {};\n\n // Merge metadata (child wins)\n if (parent.tagging !== undefined || child.tagging !== undefined) {\n result.tagging = child.tagging ?? parent.tagging;\n }\n if (parent.description !== undefined || child.description !== undefined) {\n result.description = child.description ?? parent.description;\n }\n\n // Merge sections additively\n for (const key of SECTION_KEYS) {\n const p = parent[key];\n const c = child[key];\n if (p && c) {\n result[key] = mergeContractSchemas(\n p as Record<string, unknown>,\n c as Record<string, unknown>,\n );\n } else if (p || c) {\n result[key] = { ...((p || c) as Record<string, unknown>) };\n }\n }\n\n // Merge events\n if (parent.events || child.events) {\n const merged: Flow.ContractEvents = {};\n const allEntities = new Set([\n ...Object.keys(parent.events || {}),\n ...Object.keys(child.events || {}),\n ]);\n\n for (const entity of allEntities) {\n const pActions = parent.events?.[entity] || {};\n const cActions = child.events?.[entity] || {};\n const allActions = new Set([\n ...Object.keys(pActions),\n ...Object.keys(cActions),\n ]);\n\n merged[entity] = {};\n for (const action of allActions) {\n const pSchema = pActions[action];\n const cSchema = cActions[action];\n if (pSchema && cSchema) {\n merged[entity][action] = mergeContractSchemas(\n pSchema as Record<string, unknown>,\n cSchema as Record<string, unknown>,\n );\n } else {\n merged[entity][action] = {\n ...((pSchema || cSchema) as Record<string, unknown>),\n };\n }\n }\n }\n\n result.events = merged;\n }\n\n return result;\n}\n\n/**\n * Expand wildcards in an events map.\n * Merges *.* into all concrete actions, *.action into matching actions,\n * entity.* into all actions of that entity.\n */\nfunction expandWildcards(events: Flow.ContractEvents): Flow.ContractEvents {\n const result: Flow.ContractEvents = {};\n\n // For each concrete entity-action pair, merge all matching wildcard levels\n for (const entity of Object.keys(events)) {\n if (entity === '*') continue;\n result[entity] = {};\n\n for (const action of Object.keys(events[entity] || {})) {\n let merged: Record<string, unknown> = {};\n\n // Level 1: *.*\n const globalWild = events['*']?.['*'];\n if (globalWild)\n merged = mergeContractSchemas(\n merged,\n globalWild as Record<string, unknown>,\n );\n\n // Level 2: *.action\n const actionWild = events['*']?.[action];\n if (actionWild && action !== '*')\n merged = mergeContractSchemas(\n merged,\n actionWild as Record<string, unknown>,\n );\n\n // Level 3: entity.*\n const entityWild = events[entity]?.['*'];\n if (entityWild && action !== '*')\n merged = mergeContractSchemas(\n merged,\n entityWild as Record<string, unknown>,\n );\n\n // Level 4: entity.action\n const exact = events[entity]?.[action];\n if (exact)\n merged = mergeContractSchemas(merged, exact as Record<string, unknown>);\n\n result[entity][action] = merged;\n }\n }\n\n // Preserve * entries for reference\n if (events['*']) {\n result['*'] = { ...events['*'] };\n }\n\n return result;\n}\n\n/**\n * Deep merge two JSON Schema objects with additive semantics.\n * - `required` arrays: union (deduplicated)\n * - `properties`: deep merge (child wins on conflict for scalars)\n * - Scalars: child overrides parent\n */\nexport function mergeContractSchemas(\n parent: Record<string, unknown>,\n child: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...parent };\n\n for (const key of Object.keys(child)) {\n const parentVal = parent[key];\n const childVal = child[key];\n\n if (\n key === 'required' &&\n Array.isArray(parentVal) &&\n Array.isArray(childVal)\n ) {\n result[key] = [...new Set([...parentVal, ...childVal])];\n } else if (isPlainObject(parentVal) && isPlainObject(childVal)) {\n result[key] = mergeContractSchemas(\n parentVal as Record<string, unknown>,\n childVal as Record<string, unknown>,\n );\n } else {\n result[key] = childVal;\n }\n }\n\n return result;\n}\n\n/**\n * Strip annotation-only keys from a schema (deep).\n */\nfunction stripAnnotations(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema)) {\n if (ANNOTATION_KEYS.has(key)) continue;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = stripAnnotations(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * Flow Configuration Utilities\n *\n * Functions for resolving and processing Flow configurations.\n *\n * @packageDocumentation\n */\n\nimport type { Flow } from './types';\nimport { resolveContracts } from './contract';\nimport { throwError } from './throwError';\n\n/**\n * Merge variables with cascade priority.\n * Later arguments have higher priority.\n */\nfunction mergeVariables(\n ...sources: (Flow.Variables | undefined)[]\n): Flow.Variables {\n const result: Flow.Variables = {};\n for (const source of sources) {\n if (source) {\n Object.assign(result, source);\n }\n }\n return result;\n}\n\n/**\n * Merge definitions with cascade priority.\n * Later arguments have higher priority.\n */\nfunction mergeDefinitions(\n ...sources: (Flow.Definitions | undefined)[]\n): Flow.Definitions {\n const result: Flow.Definitions = {};\n for (const source of sources) {\n if (source) {\n Object.assign(result, source);\n }\n }\n return result;\n}\n\n/** Sentinel prefix for deferred $env resolution. Shared with CLI bundler. */\nexport const ENV_MARKER_PREFIX = '__WALKEROS_ENV:';\n\nexport interface ResolveOptions {\n deferred?: boolean;\n}\n\n/**\n * Walk a dot-separated path into a value.\n * Throws if any intermediate segment is missing or not an object.\n */\nexport function walkPath(\n value: unknown,\n path: string,\n refPrefix: string,\n): unknown {\n const segments = path.split('.');\n let current = value;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n const visited = segments.slice(0, i).join('.');\n throwError(\n `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n );\n }\n const obj = current as Record<string, unknown>;\n if (!(segment in obj)) {\n const visited = segments.slice(0, i).join('.');\n throwError(\n `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n );\n }\n current = obj[segment];\n }\n\n return current;\n}\n\n/**\n * Resolve all dynamic patterns in a value.\n *\n * Patterns:\n * - $def.name → Look up definitions[name], replace entire value with definition content\n * - $def.name.path → Look up definitions[name], then walk dot-separated path\n * - $var.name → Look up variables[name]\n * - $env.NAME or $env.NAME:default → Look up process.env[NAME]\n */\nfunction resolvePatterns(\n value: unknown,\n variables: Flow.Variables,\n definitions: Flow.Definitions,\n options?: ResolveOptions,\n resolvedContracts?: Record<string, Flow.ContractEntry>,\n): unknown {\n if (typeof value === 'string') {\n // Check if entire string is a $def reference with optional deep path\n const defMatch = value.match(\n /^\\$def\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.(.+))?$/,\n );\n if (defMatch) {\n const defName = defMatch[1];\n const path = defMatch[2]; // e.g., \"nested.deep\" or undefined\n\n if (definitions[defName] === undefined) {\n throwError(`Definition \"${defName}\" not found`);\n }\n\n // Resolve the definition content recursively first\n let resolved = resolvePatterns(\n definitions[defName],\n variables,\n definitions,\n options,\n resolvedContracts,\n );\n\n // Walk deep path if present\n if (path) {\n resolved = walkPath(resolved, path, `$def.${defName}`);\n }\n\n return resolved;\n }\n\n // Check if entire string is a $contract reference with path\n const contractMatch = value.match(\n /^\\$contract\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.(.+))?$/,\n );\n if (contractMatch && resolvedContracts) {\n const contractName = contractMatch[1];\n const path = contractMatch[2];\n\n if (!(contractName in resolvedContracts)) {\n throwError(`Contract \"${contractName}\" not found`);\n }\n\n let resolved: unknown = resolvedContracts[contractName];\n\n if (path) {\n resolved = walkPath(resolved, path, `$contract.${contractName}`);\n }\n\n return resolved;\n }\n\n // Replace $var.name patterns (inline substitution)\n let result = value.replace(\n /\\$var\\.([a-zA-Z_][a-zA-Z0-9_]*)/g,\n (match, name) => {\n if (variables[name] !== undefined) {\n return String(variables[name]);\n }\n throwError(`Variable \"${name}\" not found`);\n },\n );\n\n // Replace $env.NAME or $env.NAME:default patterns\n result = result.replace(\n /\\$env\\.([a-zA-Z_][a-zA-Z0-9_]*)(?::([^\"}\\s]*))?/g,\n (match, name, defaultValue) => {\n if (options?.deferred) {\n return defaultValue !== undefined\n ? `${ENV_MARKER_PREFIX}${name}:${defaultValue}`\n : `${ENV_MARKER_PREFIX}${name}`;\n }\n if (\n typeof process !== 'undefined' &&\n process.env?.[name] !== undefined\n ) {\n return process.env[name]!;\n }\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n throwError(\n `Environment variable \"${name}\" not found and no default provided`,\n );\n },\n );\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) =>\n resolvePatterns(item, variables, definitions, options, resolvedContracts),\n );\n }\n\n if (value !== null && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = resolvePatterns(\n val,\n variables,\n definitions,\n options,\n resolvedContracts,\n );\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Convert package name to valid JavaScript variable name.\n * Used for deterministic default import naming.\n * @example\n * packageNameToVariable('@walkeros/server-destination-api')\n * // → '_walkerosServerDestinationApi'\n */\nexport function packageNameToVariable(packageName: string): string {\n const hasScope = packageName.startsWith('@');\n const normalized = packageName\n .replace('@', '')\n .replace(/[/-]/g, '_')\n .split('_')\n .filter((part) => part.length > 0)\n .map((part, i) =>\n i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1),\n )\n .join('');\n\n return hasScope ? '_' + normalized : normalized;\n}\n\n/**\n * Resolve code from package reference.\n * Preserves explicit code fields, or auto-generates from package name.\n */\nfunction resolveCodeFromPackage(\n packageName: string | undefined,\n existingCode: string | Flow.InlineCode | undefined,\n packages: Flow.Packages | undefined,\n): string | Flow.InlineCode | undefined {\n // Preserve explicit code first (including InlineCode objects)\n if (existingCode) return existingCode;\n\n // Auto-generate code from package name if package exists\n if (!packageName || !packages) return undefined;\n\n const pkgConfig = packages[packageName];\n if (!pkgConfig) return undefined;\n\n return packageNameToVariable(packageName);\n}\n\n/**\n * Get resolved flow settings for a named flow.\n *\n * @param config - The complete Flow.Config configuration\n * @param flowName - Flow name (auto-selected if only one exists)\n * @returns Resolved Settings with $var, $env, and $def patterns resolved\n * @throws Error if flow selection is required but not specified, or flow not found\n *\n * @example\n * ```typescript\n * import { getFlowSettings } from '@walkeros/core';\n *\n * const config = JSON.parse(fs.readFileSync('walkeros.config.json', 'utf8'));\n *\n * // Auto-select if only one flow\n * const settings = getFlowSettings(config);\n *\n * // Or specify flow\n * const prodSettings = getFlowSettings(config, 'production');\n * ```\n */\nexport function getFlowSettings(\n config: Flow.Config,\n flowName?: string,\n options?: ResolveOptions,\n): Flow.Settings {\n const flowNames = Object.keys(config.flows);\n\n // Auto-select if only one flow\n if (!flowName) {\n if (flowNames.length === 1) {\n flowName = flowNames[0];\n } else {\n throwError(\n `Multiple flows found (${flowNames.join(', ')}). Please specify a flow.`,\n );\n }\n }\n\n // Check flow exists\n const settings = config.flows[flowName];\n if (!settings) {\n throwError(\n `Flow \"${flowName}\" not found. Available: ${flowNames.join(', ')}`,\n );\n }\n\n // Deep clone to avoid mutations\n const result = JSON.parse(JSON.stringify(settings)) as Flow.Settings;\n\n // Pre-process contracts: resolve $def inside contracts, then extends + wildcards\n let resolvedContracts: Record<string, Flow.ContractEntry> | undefined;\n if (config.contract) {\n // Two-pass: resolve $def/$var/$env inside contract first\n const vars = mergeVariables(config.variables, settings.variables);\n const defs = mergeDefinitions(config.definitions, settings.definitions);\n const resolvedContractInput = resolvePatterns(\n config.contract,\n vars,\n defs,\n options,\n ) as Flow.Contract;\n\n resolvedContracts = resolveContracts(resolvedContractInput);\n }\n\n // Process sources with variable and definition cascade\n if (result.sources) {\n for (const [name, source] of Object.entries(result.sources)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n source.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n source.definitions,\n );\n\n const processedConfig = resolvePatterns(\n source.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n source.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n // Resolve code from package reference\n const resolvedCode = resolveCodeFromPackage(\n source.package,\n source.code,\n result.packages,\n );\n\n // Exclude deprecated code: true, only keep valid string or InlineCode\n const validCode =\n typeof source.code === 'string' || typeof source.code === 'object'\n ? source.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.sources[name] = {\n package: source.package,\n config: processedConfig,\n env: processedEnv,\n primary: source.primary,\n variables: source.variables,\n definitions: source.definitions,\n next: source.next,\n code: finalCode,\n } as Flow.SourceReference;\n }\n }\n\n // Process destinations with variable and definition cascade\n if (result.destinations) {\n for (const [name, dest] of Object.entries(result.destinations)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n dest.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n dest.definitions,\n );\n\n const processedConfig = resolvePatterns(\n dest.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n dest.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n // Resolve code from package reference\n const resolvedCode = resolveCodeFromPackage(\n dest.package,\n dest.code,\n result.packages,\n );\n\n // Exclude deprecated code: true, only keep valid string or InlineCode\n const validCode =\n typeof dest.code === 'string' || typeof dest.code === 'object'\n ? dest.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.destinations[name] = {\n package: dest.package,\n config: processedConfig,\n env: processedEnv,\n variables: dest.variables,\n definitions: dest.definitions,\n before: dest.before,\n code: finalCode,\n } as Flow.DestinationReference;\n }\n }\n\n // Process stores with variable and definition cascade\n if (result.stores) {\n for (const [name, store] of Object.entries(result.stores)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n store.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n store.definitions,\n );\n\n const processedConfig = resolvePatterns(\n store.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n store.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const resolvedCode = resolveCodeFromPackage(\n store.package,\n store.code,\n result.packages,\n );\n\n const validCode =\n typeof store.code === 'string' || typeof store.code === 'object'\n ? store.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.stores[name] = {\n package: store.package,\n config: processedConfig,\n env: processedEnv,\n variables: store.variables,\n definitions: store.definitions,\n code: finalCode,\n } as Flow.StoreReference;\n }\n }\n\n // Process transformers with variable and definition cascade\n if (result.transformers) {\n for (const [name, transformer] of Object.entries(result.transformers)) {\n const vars = mergeVariables(\n config.variables,\n settings.variables,\n transformer.variables,\n );\n const defs = mergeDefinitions(\n config.definitions,\n settings.definitions,\n transformer.definitions,\n );\n\n const processedConfig = resolvePatterns(\n transformer.config,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const processedEnv = resolvePatterns(\n transformer.env,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n\n const resolvedCode = resolveCodeFromPackage(\n transformer.package,\n transformer.code,\n result.packages,\n );\n\n const validCode =\n typeof transformer.code === 'string' ||\n typeof transformer.code === 'object'\n ? transformer.code\n : undefined;\n const finalCode = resolvedCode || validCode;\n result.transformers[name] = {\n package: transformer.package,\n config: processedConfig,\n env: processedEnv,\n variables: transformer.variables,\n definitions: transformer.definitions,\n next: transformer.next,\n code: finalCode,\n } as Flow.TransformerReference;\n }\n }\n\n // Process collector config\n if (result.collector) {\n const vars = mergeVariables(config.variables, settings.variables);\n const defs = mergeDefinitions(config.definitions, settings.definitions);\n\n const processedCollector = resolvePatterns(\n result.collector,\n vars,\n defs,\n options,\n resolvedContracts,\n );\n result.collector = processedCollector as typeof result.collector;\n }\n\n return result;\n}\n\n/**\n * Get platform from settings (web or server).\n *\n * @param settings - Flow settings\n * @returns \"web\" or \"server\"\n * @throws Error if neither web nor server is present\n *\n * @example\n * ```typescript\n * import { getPlatform } from '@walkeros/core';\n *\n * const platform = getPlatform(settings);\n * // Returns \"web\" or \"server\"\n * ```\n */\nexport function getPlatform(settings: Flow.Settings): 'web' | 'server' {\n if (settings.web !== undefined) return 'web';\n if (settings.server !== undefined) return 'server';\n throwError('Settings must have web or server key');\n}\n","/**\n * @interface Assign\n * @description Options for the assign function.\n * @property merge - Merge array properties instead of overriding them.\n * @property shallow - Create a shallow copy instead of updating the target object.\n * @property extend - Extend the target with new properties instead of only updating existing ones.\n */\ninterface Assign {\n merge?: boolean;\n shallow?: boolean;\n extend?: boolean;\n}\n\nconst defaultOptions: Assign = {\n merge: true,\n shallow: true,\n extend: true,\n};\n\n/**\n * Merges objects with advanced options.\n *\n * @template T, U\n * @param target - The target object to merge into.\n * @param obj - The source object to merge from.\n * @param options - Options for merging.\n * @returns The merged object.\n */\nexport function assign<T extends object, U extends object>(\n target: T,\n obj: U = {} as U,\n options: Assign = {},\n): T & U {\n options = { ...defaultOptions, ...options };\n\n const finalObj = Object.entries(obj).reduce((acc, [key, sourceProp]) => {\n const targetProp = target[key as keyof typeof target];\n\n // Only merge arrays\n if (\n options.merge &&\n Array.isArray(targetProp) &&\n Array.isArray(sourceProp)\n ) {\n acc[key as keyof typeof acc] = sourceProp.reduce(\n (acc, item) => {\n // Remove duplicates\n return acc.includes(item) ? acc : [...acc, item];\n },\n [...targetProp],\n );\n } else if (options.extend || key in target) {\n // Extend the target with new properties or update existing ones\n acc[key as keyof typeof acc] = sourceProp;\n }\n\n return acc;\n }, {} as U);\n\n // Handle shallow or deep copy based on options\n if (options.shallow) {\n return { ...target, ...finalObj };\n } else {\n Object.assign(target, finalObj);\n return target as T & U;\n }\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if a value is an arguments object.\n *\n * @param value The value to check.\n * @returns True if the value is an arguments object, false otherwise.\n */\nexport function isArguments(value: unknown): value is IArguments {\n return Object.prototype.toString.call(value) === '[object Arguments]';\n}\n\n/**\n * Checks if a value is an array.\n *\n * @param value The value to check.\n * @returns True if the value is an array, false otherwise.\n */\nexport function isArray<T>(value: unknown): value is T[] {\n return Array.isArray(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value The value to check.\n * @returns True if the value is a boolean, false otherwise.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === 'boolean';\n}\n\n/**\n * Checks if an entity is a walker command.\n *\n * @param entity The entity to check.\n * @returns True if the entity is a walker command, false otherwise.\n */\nexport function isCommand(entity: string) {\n return entity === 'walker';\n}\n\n/**\n * Checks if a value is defined.\n *\n * @param value The value to check.\n * @returns True if the value is defined, false otherwise.\n */\nexport function isDefined<T>(val: T | undefined): val is T {\n return typeof val !== 'undefined';\n}\n\n/**\n * Checks if a value is an element or the document.\n *\n * @param elem The value to check.\n * @returns True if the value is an element or the document, false otherwise.\n */\nexport function isElementOrDocument(elem: unknown): elem is Element {\n return elem === document || elem instanceof Element;\n}\n\n/**\n * Checks if a value is a function.\n *\n * @param value The value to check.\n * @returns True if the value is a function, false otherwise.\n */\nexport function isFunction(value: unknown): value is Function {\n return typeof value === 'function';\n}\n\n/**\n * Checks if a value is a number.\n *\n * @param value The value to check.\n * @returns True if the value is a number, false otherwise.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === 'number' && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is an object.\n *\n * @param value The value to check.\n * @returns True if the value is an object, false otherwise.\n */\nexport function isObject(value: unknown): value is WalkerOS.AnyObject {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isArray(value) &&\n Object.prototype.toString.call(value) === '[object Object]'\n );\n}\n\n/**\n * Checks if two variables have the same type.\n *\n * @param variable The first variable.\n * @param type The second variable.\n * @returns True if the variables have the same type, false otherwise.\n */\nexport function isSameType<T>(\n variable: unknown,\n type: T,\n): variable is typeof type {\n return typeof variable === typeof type;\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value The value to check.\n * @returns True if the value is a string, false otherwise.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n","/**\n * Creates a deep clone of a value.\n * Supports primitive values, objects, arrays, dates, and regular expressions.\n * Handles circular references.\n *\n * @template T\n * @param org - The value to clone.\n * @param visited - A map of visited objects to handle circular references.\n * @returns The cloned value.\n */\nexport function clone<T>(\n org: T,\n visited: WeakMap<object, unknown> = new WeakMap(),\n): T {\n // Handle primitive values and functions directly\n if (typeof org !== 'object' || org === null) return org;\n\n // Check for circular references\n if (visited.has(org)) return visited.get(org) as T;\n\n // Allow list of clonable types\n const type = Object.prototype.toString.call(org);\n if (type === '[object Object]') {\n const clonedObj = {} as Record<string | symbol, unknown>;\n visited.set(org as object, clonedObj); // Remember the reference\n\n for (const key in org as Record<string | symbol, unknown>) {\n if (Object.prototype.hasOwnProperty.call(org, key)) {\n clonedObj[key] = clone(\n (org as Record<string | symbol, unknown>)[key],\n visited,\n );\n }\n }\n return clonedObj as T;\n }\n\n if (type === '[object Array]') {\n const clonedArray = [] as unknown[];\n visited.set(org as object, clonedArray); // Remember the reference\n\n (org as unknown[]).forEach((item) => {\n clonedArray.push(clone(item, visited));\n });\n\n return clonedArray as T;\n }\n\n if (type === '[object Date]') {\n return new Date((org as unknown as Date).getTime()) as T;\n }\n\n if (type === '[object RegExp]') {\n const reg = org as unknown as RegExp;\n return new RegExp(reg.source, reg.flags) as T;\n }\n\n // Skip cloning for unsupported types and return reference\n return org;\n}\n","import type { WalkerOS } from './types';\nimport { isArray, isDefined, isObject } from './is';\nimport { clone } from './clone';\n\n/**\n * Gets a value from an object by a dot-notation string.\n * Supports wildcards for arrays.\n *\n * @example\n * getByPath({ data: { id: 1 } }, \"data.id\") // Returns 1\n *\n * @param event - The object to get the value from.\n * @param key - The dot-notation string.\n * @param defaultValue - The default value to return if the key is not found.\n * @returns The value from the object or the default value.\n */\nexport function getByPath(\n event: unknown,\n key: string = '',\n defaultValue?: unknown,\n): unknown {\n const keys = key.split('.');\n let values: unknown = event;\n\n for (let index = 0; index < keys.length; index++) {\n const k = keys[index];\n\n if (k === '*' && isArray(values)) {\n const remainingKeys = keys.slice(index + 1).join('.');\n const result: unknown[] = [];\n\n for (const item of values) {\n const value = getByPath(item, remainingKeys, defaultValue);\n result.push(value);\n }\n\n return result;\n }\n\n values =\n values instanceof Object ? values[k as keyof typeof values] : undefined;\n\n if (values === undefined) break;\n }\n\n return isDefined(values) ? values : defaultValue;\n}\n\n/**\n * Sets a value in an object by a dot-notation string.\n *\n * @param obj - The object to set the value in.\n * @param key - The dot-notation string.\n * @param value - The value to set.\n * @returns A new object with the updated value.\n */\nexport function setByPath<T = unknown>(obj: T, key: string, value: unknown): T {\n if (!isObject(obj)) return obj;\n\n const clonedObj = clone(obj);\n const keys = key.split('.');\n let current: WalkerOS.AnyObject = clonedObj;\n\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i] as keyof typeof current;\n\n // Set the value if it's the last key\n if (i === keys.length - 1) {\n current[k] = value;\n } else {\n // Traverse to the next level\n if (\n !(k in current) ||\n typeof current[k] !== 'object' ||\n current[k] === null\n ) {\n current[k] = {};\n }\n\n // Move deeper into the object\n current = current[k] as WalkerOS.AnyObject;\n }\n }\n\n return clonedObj as T;\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Casts a value to a specific type.\n *\n * @param value The value to cast.\n * @returns The casted value.\n */\nexport function castValue(value: unknown): WalkerOS.PropertyType {\n if (value === 'true') return true;\n if (value === 'false') return false;\n\n const number = Number(value); // Converts \"\" to 0\n if (value == number && value !== '') return number;\n\n return String(value);\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if the required consent is granted.\n *\n * @param required - The required consent states.\n * @param state - The current consent states.\n * @param individual - Individual consent states to prioritize.\n * @returns The granted consent states or false if not granted.\n */\nexport function getGrantedConsent(\n required: WalkerOS.Consent | undefined,\n state: WalkerOS.Consent = {},\n individual: WalkerOS.Consent = {},\n): false | WalkerOS.Consent {\n // Merge state and individual, prioritizing individual states\n const states: WalkerOS.Consent = { ...state, ...individual };\n\n const grantedStates: WalkerOS.Consent = {};\n let hasRequiredConsent = !required || Object.keys(required).length === 0;\n\n Object.keys(states).forEach((name) => {\n if (states[name]) {\n // consent granted\n grantedStates[name] = true;\n\n // Check if it's required and granted consent\n if (required && required[name]) hasRequiredConsent = true;\n }\n });\n\n return hasRequiredConsent ? grantedStates : false;\n}\n","import type { Destination } from './types';\nimport type { TypesOf, Config } from './types/destination';\nimport { assign } from './assign';\n\n/**\n * Creates a new destination instance by merging a base destination with additional configuration.\n *\n * This utility enables elegant destination configuration while avoiding config side-effects\n * that could occur when reusing destination objects across multiple collector instances.\n *\n * @param baseDestination - The base destination to extend\n * @param config - Additional configuration to merge with the base destination's config\n * @returns A new destination instance with merged configuration\n *\n * @example\n * ```typescript\n * // Types are inferred automatically from destinationGtag\n * elb('walker destination', createDestination(destinationGtag, {\n * settings: { ga4: { measurementId: 'G-123' } }\n * }));\n * ```\n */\nexport function createDestination<I extends Destination.Instance>(\n baseDestination: I,\n config: Partial<Config<TypesOf<I>>>,\n): I {\n // Create a shallow copy of the base destination to avoid mutations\n const newDestination = { ...baseDestination };\n\n // Deep merge the config, handling nested objects like settings and mapping\n newDestination.config = assign(baseDestination.config, config, {\n shallow: true, // Create new object, don't mutate original\n merge: true, // Merge arrays\n extend: true, // Allow new properties\n });\n\n // Handle nested settings merging if both have settings\n if (baseDestination.config.settings && config.settings) {\n newDestination.config.settings = assign(\n baseDestination.config.settings as object,\n config.settings as object,\n { shallow: true, merge: true, extend: true },\n ) as typeof newDestination.config.settings;\n }\n\n // Handle nested mapping merging if both have mapping\n if (baseDestination.config.mapping && config.mapping) {\n newDestination.config.mapping = assign(\n baseDestination.config.mapping as object,\n config.mapping as object,\n { shallow: true, merge: true, extend: true },\n ) as typeof newDestination.config.mapping;\n }\n\n return newDestination;\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\n\ndeclare const __VERSION__: string;\n\n/**\n * Creates a complete event with default values.\n * Used for testing and debugging.\n *\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function createEvent(\n props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n const group = props.group || 'gr0up';\n const count = props.count || 1;\n const id = `${timestamp}-${group}-${count}`;\n\n const defaultEvent: WalkerOS.Event = {\n name: 'entity action',\n data: {\n string: 'foo',\n number: 1,\n boolean: true,\n array: [0, 'text', false],\n not: undefined,\n },\n context: { dev: ['test', 1] },\n globals: { lang: 'elb' },\n custom: { completely: 'random' },\n user: { id: 'us3r', device: 'c00k13', session: 's3ss10n' },\n nested: [\n {\n entity: 'child',\n data: { is: 'subordinated' },\n nested: [],\n context: { element: ['child', 0] },\n },\n ],\n consent: { functional: true },\n id,\n trigger: 'test',\n entity: 'entity',\n action: 'action',\n timestamp,\n timing: 3.14,\n group,\n count,\n version: {\n source: __VERSION__,\n tagging: 1,\n },\n source: {\n type: 'web',\n id: 'https://localhost:80',\n previous_id: 'http://remotehost:9001',\n },\n };\n\n // Note: Always prefer the props over the defaults\n\n // Merge properties\n const event = assign(defaultEvent, props, { merge: false });\n\n // Update conditions\n\n // Entity and action from event\n if (props.name) {\n const [entity, action] = props.name.split(' ') ?? [];\n\n if (entity && action) {\n event.entity = entity;\n event.action = action;\n }\n }\n\n return event;\n}\n\n/**\n * Creates a complete event with default values based on the event name.\n * Used for testing and debugging.\n *\n * @param name - The name of the event to create.\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function getEvent(\n name: string = 'entity action',\n props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n\n const quantity = 2;\n const product1 = {\n data: {\n id: 'ers',\n name: 'Everyday Ruck Snack',\n color: 'black',\n size: 'l',\n price: 420,\n },\n };\n const product2 = {\n data: {\n id: 'cc',\n name: 'Cool Cap',\n size: 'one size',\n price: 42,\n },\n };\n\n const defaultEvents: Record<string, WalkerOS.PartialEvent> = {\n 'cart view': {\n data: {\n currency: 'EUR',\n value: product1.data.price * quantity,\n },\n context: { shopping: ['cart', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n data: { ...product1.data, quantity },\n context: { shopping: ['cart', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'checkout view': {\n data: {\n step: 'payment',\n currency: 'EUR',\n value: product1.data.price + product2.data.price,\n },\n context: { shopping: ['checkout', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n ...product1,\n context: { shopping: ['checkout', 0] },\n nested: [],\n },\n {\n entity: 'product',\n ...product2,\n context: { shopping: ['checkout', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'order complete': {\n data: {\n id: '0rd3r1d',\n currency: 'EUR',\n shipping: 5.22,\n taxes: 73.76,\n total: 555,\n },\n context: { shopping: ['complete', 0] },\n globals: { pagegroup: 'shop' },\n nested: [\n {\n entity: 'product',\n ...product1,\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n {\n entity: 'product',\n ...product2,\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n {\n entity: 'gift',\n data: {\n name: 'Surprise',\n },\n context: { shopping: ['complete', 0] },\n nested: [],\n },\n ],\n trigger: 'load',\n },\n 'page view': {\n data: {\n domain: 'www.example.com',\n title: 'walkerOS documentation',\n referrer: 'https://www.walkeros.io/',\n search: '?foo=bar',\n hash: '#hash',\n id: '/docs/',\n },\n globals: { pagegroup: 'docs' },\n trigger: 'load',\n },\n 'product add': {\n ...product1,\n context: { shopping: ['intent', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'click',\n },\n 'product view': {\n ...product1,\n context: { shopping: ['detail', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'load',\n },\n 'product visible': {\n data: { ...product1.data, position: 3, promo: true },\n context: { shopping: ['discover', 0] },\n globals: { pagegroup: 'shop' },\n nested: [],\n trigger: 'load',\n },\n 'promotion visible': {\n data: {\n name: 'Setting up tracking easily',\n position: 'hero',\n },\n context: { ab_test: ['engagement', 0] },\n globals: { pagegroup: 'homepage' },\n trigger: 'visible',\n },\n 'session start': {\n data: {\n id: 's3ss10n',\n start: timestamp,\n isNew: true,\n count: 1,\n runs: 1,\n isStart: true,\n storage: true,\n referrer: '',\n device: 'c00k13',\n },\n user: {\n id: 'us3r',\n device: 'c00k13',\n session: 's3ss10n',\n hash: 'h4sh',\n address: 'street number',\n email: 'user@example.com',\n phone: '+49 123 456 789',\n userAgent: 'Mozilla...',\n browser: 'Chrome',\n browserVersion: '90',\n deviceType: 'desktop',\n language: 'de-DE',\n country: 'DE',\n region: 'HH',\n city: 'Hamburg',\n zip: '20354',\n timezone: 'Berlin',\n os: 'walkerOS',\n osVersion: '1.0',\n screenSize: '1337x420',\n ip: '127.0.0.0',\n internal: true,\n custom: 'value',\n },\n },\n };\n\n return createEvent({ ...defaultEvents[name], ...props, name: name });\n}\n","/**\n * Generates a random string of a given length.\n *\n * @param length - The length of the random string.\n * @returns The random string.\n */\nexport function getId(length = 6): string {\n let str = '';\n for (let l = 36; str.length < length; )\n str += ((Math.random() * l) | 0).toString(l);\n return str;\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\n\nexport interface MarketingParameters {\n [key: string]: string;\n}\n\n/**\n * Extracts marketing parameters from a URL.\n *\n * @param url - The URL to extract the parameters from.\n * @param custom - Custom marketing parameters to extract.\n * @returns The extracted marketing parameters.\n */\nexport function getMarketingParameters(\n url: URL,\n custom: MarketingParameters = {},\n): WalkerOS.Properties {\n const clickId = 'clickId';\n const data: WalkerOS.Properties = {};\n const parameters: MarketingParameters = {\n utm_campaign: 'campaign',\n utm_content: 'content',\n utm_medium: 'medium',\n utm_source: 'source',\n utm_term: 'term',\n dclid: clickId,\n fbclid: clickId,\n gclid: clickId,\n msclkid: clickId,\n ttclid: clickId,\n twclid: clickId,\n igshid: clickId,\n sclid: clickId,\n };\n\n Object.entries(assign(parameters, custom)).forEach(([key, name]) => {\n const param = url.searchParams.get(key); // Search for the parameter in the URL\n if (param) {\n if (name === clickId) {\n name = key;\n data[clickId] = key; // Reference the clickId parameter\n }\n\n data[name] = param;\n }\n });\n\n return data;\n}\n","/**\n * Creates a debounced function that delays invoking `fn` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `fn` invocations and a `flush` method to immediately invoke them.\n *\n * @template P, R\n * @param fn The function to debounce.\n * @param wait The number of milliseconds to delay.\n * @param immediate Trigger the function on the leading edge, instead of the trailing.\n * @returns The new debounced function.\n */\nexport function debounce<P extends unknown[], R>(\n fn: (...args: P) => R,\n wait = 1000,\n immediate = false,\n) {\n let timer: number | NodeJS.Timeout | null = null;\n let result: R;\n let hasCalledImmediately = false;\n\n return (...args: P): Promise<R> => {\n // Return value as promise\n return new Promise((resolve) => {\n const callNow = immediate && !hasCalledImmediately;\n\n // abort previous invocation\n if (timer) clearTimeout(timer);\n\n timer = setTimeout(() => {\n timer = null;\n if (!immediate || hasCalledImmediately) {\n result = fn(...args);\n resolve(result);\n }\n }, wait);\n\n if (callNow) {\n hasCalledImmediately = true;\n result = fn(...args);\n resolve(result);\n }\n });\n };\n}\n\n/**\n * Creates a throttled function that only invokes `fn` at most once per\n * every `delay` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `fn` invocations and a `flush` method to\n * immediately invoke them.\n *\n * @template P, R\n * @param fn The function to throttle.\n * @param delay The number of milliseconds to throttle invocations to.\n * @returns The new throttled function.\n */\n\ntype Timeout = ReturnType<typeof setTimeout>;\nexport function throttle<P extends unknown[], R>(\n fn: (...args: P) => R | undefined,\n delay = 1000,\n): (...args: P) => R | undefined {\n let isBlocked: Timeout | null = null;\n\n return function (...args: P): R | undefined {\n // Skip since function is still blocked by previous call\n if (isBlocked !== null) return;\n\n // Set a blocking timeout\n isBlocked = setTimeout(() => {\n // Unblock function\n isBlocked = null;\n }, delay) as Timeout;\n\n // Call the function\n return fn(...args);\n };\n}\n","import type {\n Config,\n DefaultHandler,\n ErrorContext,\n Handler,\n Instance,\n InternalConfig,\n LogContext,\n} from './types/logger';\nimport { Level } from './types/logger';\n\n/**\n * Normalize an Error object into ErrorContext\n */\nfunction normalizeError(err: Error): ErrorContext {\n return {\n message: err.message,\n name: err.name,\n stack: err.stack,\n cause: (err as Error & { cause?: unknown }).cause,\n };\n}\n\n/**\n * Normalize message and context parameters\n * Handles Error objects passed as message or context\n */\nfunction normalizeParams(\n message: string | Error,\n context?: unknown | Error,\n): { message: string; context: LogContext } {\n let normalizedMessage: string;\n let normalizedContext: LogContext = {};\n\n // Handle message\n if (message instanceof Error) {\n normalizedMessage = message.message;\n normalizedContext.error = normalizeError(message);\n } else {\n normalizedMessage = message;\n }\n\n // Handle context\n if (context !== undefined) {\n if (context instanceof Error) {\n normalizedContext.error = normalizeError(context);\n } else if (typeof context === 'object' && context !== null) {\n normalizedContext = { ...normalizedContext, ...(context as object) };\n // If context has an error property that's an Error, normalize it\n if (\n 'error' in normalizedContext &&\n normalizedContext.error instanceof Error\n ) {\n normalizedContext.error = normalizeError(\n normalizedContext.error as unknown as Error,\n );\n }\n } else {\n normalizedContext.value = context;\n }\n }\n\n return { message: normalizedMessage, context: normalizedContext };\n}\n\n/**\n * Default console-based log handler\n */\nconst defaultHandler: DefaultHandler = (level, message, context, scope) => {\n const levelName = Level[level];\n const scopePath = scope.length > 0 ? ` [${scope.join(':')}]` : '';\n const prefix = `${levelName}${scopePath}`;\n\n const hasContext = Object.keys(context).length > 0;\n\n const consoleFn =\n level === Level.ERROR\n ? console.error\n : level === Level.WARN\n ? console.warn\n : console.log;\n\n if (hasContext) {\n consoleFn(prefix, message, context);\n } else {\n consoleFn(prefix, message);\n }\n};\n\n/**\n * Normalize log level from string or enum to enum value\n */\nfunction normalizeLevel(level: Level | keyof typeof Level): Level {\n if (typeof level === 'string') {\n return Level[level as keyof typeof Level];\n }\n return level;\n}\n\n/**\n * Create a logger instance\n *\n * @param config - Logger configuration\n * @returns Logger instance with all log methods and scoping support\n *\n * @example\n * ```typescript\n * // Basic usage\n * const logger = createLogger({ level: 'DEBUG' });\n * logger.info('Hello world');\n *\n * // With scoping\n * const destLogger = logger.scope('gtag').scope('myInstance');\n * destLogger.debug('Processing event'); // DEBUG [gtag:myInstance] Processing event\n *\n * // With custom handler\n * const logger = createLogger({\n * handler: (level, message, context, scope, originalHandler) => {\n * // Custom logic (e.g., send to Sentry)\n * originalHandler(level, message, context, scope);\n * }\n * });\n * ```\n *\n * // TODO: Consider compile-time stripping of debug logs in production builds\n * // e.g., if (__DEV__) { logger.debug(...) }\n */\nexport function createLogger(config: Config = {}): Instance {\n const level =\n config.level !== undefined ? normalizeLevel(config.level) : Level.ERROR;\n const customHandler = config.handler;\n const jsonHandler = config.jsonHandler;\n const scope: string[] = [];\n\n return createLoggerInternal({\n level,\n handler: customHandler,\n jsonHandler,\n scope,\n });\n}\n\n/**\n * Internal logger creation with resolved config\n */\nfunction createLoggerInternal(config: InternalConfig): Instance {\n const { level, handler, jsonHandler, scope } = config;\n\n /**\n * Internal log function that checks level and delegates to handler\n */\n const log = (\n logLevel: Level,\n message: string | Error,\n context?: unknown | Error,\n ): void => {\n if (logLevel <= level) {\n const normalized = normalizeParams(message, context);\n\n if (handler) {\n // Custom handler with access to default handler\n handler(\n logLevel,\n normalized.message,\n normalized.context,\n scope,\n defaultHandler,\n );\n } else {\n defaultHandler(logLevel, normalized.message, normalized.context, scope);\n }\n }\n };\n\n /**\n * Log and throw - combines logging and throwing\n */\n const logAndThrow = (message: string | Error, context?: unknown): never => {\n // Always log errors regardless of level\n const normalized = normalizeParams(message, context);\n\n if (handler) {\n handler(\n Level.ERROR,\n normalized.message,\n normalized.context,\n scope,\n defaultHandler,\n );\n } else {\n defaultHandler(\n Level.ERROR,\n normalized.message,\n normalized.context,\n scope,\n );\n }\n\n // Throw with the message\n throw new Error(normalized.message);\n };\n\n return {\n error: (message, context) => log(Level.ERROR, message, context),\n warn: (message, context) => log(Level.WARN, message, context),\n info: (message, context) => log(Level.INFO, message, context),\n debug: (message, context) => log(Level.DEBUG, message, context),\n throw: logAndThrow,\n json: (data: unknown) => {\n if (jsonHandler) {\n jsonHandler(data);\n } else {\n // eslint-disable-next-line no-console\n console.log(JSON.stringify(data, null, 2));\n }\n },\n scope: (name: string) =>\n createLoggerInternal({\n level,\n handler,\n jsonHandler,\n scope: [...scope, name],\n }),\n };\n}\n\n// Re-export Level enum for convenience\nexport { Level };\n","import type { WalkerOS } from './types';\nimport {\n isArguments,\n isArray,\n isBoolean,\n isDefined,\n isNumber,\n isObject,\n isString,\n} from './is';\n\n/**\n * Checks if a value is a valid property type.\n *\n * @param value The value to check.\n * @returns True if the value is a valid property type, false otherwise.\n */\nexport function isPropertyType(value: unknown): value is WalkerOS.PropertyType {\n return (\n isBoolean(value) ||\n isString(value) ||\n isNumber(value) ||\n !isDefined(value) ||\n (isArray(value) && value.every(isPropertyType)) ||\n (isObject(value) && Object.values(value).every(isPropertyType))\n );\n}\n\n/**\n * Filters a value to only include valid property types.\n *\n * @param value The value to filter.\n * @returns The filtered value or undefined.\n */\nexport function filterValues(value: unknown): WalkerOS.Property | undefined {\n if (isBoolean(value) || isString(value) || isNumber(value)) return value;\n\n if (isArguments(value)) return filterValues(Array.from(value));\n\n if (isArray(value)) {\n return value\n .map((item) => filterValues(item))\n .filter((item): item is WalkerOS.PropertyType => item !== undefined);\n }\n\n if (isObject(value)) {\n return Object.entries(value).reduce<Record<string, WalkerOS.Property>>(\n (acc, [key, val]) => {\n const filteredValue = filterValues(val);\n if (filteredValue !== undefined) acc[key] = filteredValue;\n return acc;\n },\n {},\n );\n }\n\n return;\n}\n\n/**\n * Casts a value to a valid property type.\n *\n * @param value The value to cast.\n * @returns The casted value or undefined.\n */\nexport function castToProperty(value: unknown): WalkerOS.Property | undefined {\n return isPropertyType(value) ? value : undefined;\n}\n","/**\n * A utility function that wraps a function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatch<P extends unknown[], R, S>(\n fn: (...args: P) => R | undefined,\n onError: (err: unknown) => S,\n onFinally?: () => void,\n): (...args: P) => R | S;\nexport function tryCatch<P extends unknown[], R>(\n fn: (...args: P) => R | undefined,\n onError?: undefined,\n onFinally?: () => void,\n): (...args: P) => R | undefined;\n// Implementation\nexport function tryCatch<P extends unknown[], R, S>(\n fn: (...args: P) => R | undefined,\n onError?: (err: unknown) => S,\n onFinally?: () => void,\n): (...args: P) => R | S | undefined {\n return function (...args: P): R | S | undefined {\n try {\n return fn(...args);\n } catch (err) {\n if (!onError) return;\n return onError(err);\n } finally {\n onFinally?.();\n }\n };\n}\n\n/**\n * A utility function that wraps an async function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The async function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped async function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatchAsync<P extends unknown[], R, S>(\n fn: (...args: P) => R,\n onError: (err: unknown) => S,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S>;\nexport function tryCatchAsync<P extends unknown[], R>(\n fn: (...args: P) => R,\n onError?: undefined,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | undefined>;\n// Implementation\nexport function tryCatchAsync<P extends unknown[], R, S>(\n fn: (...args: P) => R,\n onError?: (err: unknown) => S,\n onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S | undefined> {\n return async function (...args: P): Promise<R | S | undefined> {\n try {\n return await fn(...args);\n } catch (err) {\n if (!onError) return;\n return await onError(err);\n } finally {\n await onFinally?.();\n }\n };\n}\n","import type { Mapping, WalkerOS, Collector } from './types';\nimport { getByPath, setByPath } from './byPath';\nimport { isArray, isDefined, isString, isObject } from './is';\nimport { castToProperty } from './property';\nimport { tryCatchAsync } from './tryCatch';\nimport { getGrantedConsent } from './consent';\nimport { assign } from './assign';\n\n/**\n * Gets the mapping for an event.\n *\n * @param event The event to get the mapping for (can be partial or full).\n * @param mapping The mapping rules.\n * @returns The mapping result.\n */\nexport async function getMappingEvent(\n event: WalkerOS.DeepPartialEvent | WalkerOS.PartialEvent | WalkerOS.Event,\n mapping?: Mapping.Rules,\n): Promise<Mapping.Result> {\n const [entity, action] = (event.name || '').split(' ');\n if (!mapping || !entity || !action) return {};\n\n let eventMapping: Mapping.Rule | undefined;\n let mappingKey = '';\n let entityKey = entity;\n let actionKey = action;\n\n const resolveEventMapping = (\n eventMapping?: Mapping.Rule | Mapping.Rule[],\n ) => {\n if (!eventMapping) return;\n eventMapping = isArray(eventMapping) ? eventMapping : [eventMapping];\n\n return eventMapping.find(\n (eventMapping) =>\n !eventMapping.condition || eventMapping.condition(event),\n );\n };\n\n if (!mapping[entityKey]) entityKey = '*';\n const entityMapping = mapping[entityKey];\n\n if (entityMapping) {\n if (!entityMapping[actionKey]) actionKey = '*';\n eventMapping = resolveEventMapping(entityMapping[actionKey]);\n }\n\n // Fallback to * *\n if (!eventMapping) {\n entityKey = '*';\n actionKey = '*';\n eventMapping = resolveEventMapping(mapping[entityKey]?.[actionKey]);\n }\n\n if (eventMapping) mappingKey = `${entityKey} ${actionKey}`;\n\n return { eventMapping, mappingKey };\n}\n\n/**\n * Gets a value from a mapping.\n *\n * @param value The value to get the mapping from.\n * @param data The mapping data.\n * @param options The mapping options.\n * @returns The mapped value.\n */\nexport async function getMappingValue(\n value: WalkerOS.DeepPartialEvent | unknown | undefined,\n data: Mapping.Data = {},\n options: Mapping.Options = {},\n): Promise<WalkerOS.Property | undefined> {\n if (!isDefined(value)) return;\n\n // Get consent state in priority order: value.consent > options.consent > collector?.consent\n const consentState =\n ((isObject(value) && value.consent) as WalkerOS.Consent) ||\n options.consent ||\n options.collector?.consent;\n\n const mappings = isArray(data) ? data : [data];\n\n for (const mapping of mappings) {\n const result = await tryCatchAsync(processMappingValue)(value, mapping, {\n ...options,\n consent: consentState,\n });\n if (isDefined(result)) return result;\n }\n\n return;\n}\n\nasync function processMappingValue(\n value: WalkerOS.DeepPartialEvent | unknown,\n mapping: Mapping.Value,\n options: Mapping.Options = {},\n): Promise<WalkerOS.Property | undefined> {\n const { collector, consent: consentState } = options;\n\n // Ensure mapping is an array for uniform processing\n const mappings = isArray(mapping) ? mapping : [mapping];\n\n // Loop over each mapping and return the first valid result\n return mappings.reduce(\n async (accPromise, mappingItem) => {\n const acc = await accPromise;\n if (acc) return acc; // A valid result was already found\n\n const mapping = isString(mappingItem)\n ? { key: mappingItem }\n : mappingItem;\n\n if (!Object.keys(mapping).length) return;\n\n const {\n condition,\n consent,\n fn,\n key,\n loop,\n map,\n set,\n validate,\n value: staticValue,\n } = mapping;\n\n // Check if this mapping should be used\n if (\n condition &&\n !(await tryCatchAsync(condition)(value, mappingItem, collector))\n )\n return;\n\n // Check if consent is required and granted\n if (consent && !getGrantedConsent(consent, consentState))\n return staticValue;\n\n let mappingValue: unknown = isDefined(staticValue) ? staticValue : value;\n\n // Use a custom function to get the value\n if (fn) {\n mappingValue = await tryCatchAsync(fn)(value, mappingItem, options);\n }\n\n // Get dynamic value from the event\n if (key) {\n mappingValue = getByPath(value, key, staticValue);\n }\n\n if (loop) {\n const [scope, itemMapping] = loop;\n\n const data =\n scope === 'this'\n ? [value]\n : await getMappingValue(value, scope, options);\n\n if (isArray(data)) {\n mappingValue = (\n await Promise.all(\n data.map((item) => getMappingValue(item, itemMapping, options)),\n )\n ).filter(isDefined);\n }\n } else if (map) {\n mappingValue = await Object.entries(map).reduce(\n async (mappedObjPromise, [mapKey, mapValue]) => {\n const mappedObj = await mappedObjPromise;\n const result = await getMappingValue(value, mapValue, options);\n if (isDefined(result)) mappedObj[mapKey] = result;\n return mappedObj;\n },\n Promise.resolve({} as WalkerOS.AnyObject),\n );\n } else if (set) {\n mappingValue = await Promise.all(\n set.map((item) => processMappingValue(value, item, options)),\n );\n }\n\n // Validate the value\n if (validate && !(await tryCatchAsync(validate)(mappingValue)))\n mappingValue = undefined;\n\n const property = castToProperty(mappingValue);\n\n // Finally, check and convert the type\n return isDefined(property) ? property : castToProperty(staticValue); // Always use value as a fallback\n },\n Promise.resolve(undefined as WalkerOS.Property | undefined),\n );\n}\n\n/**\n * Processes an event through mapping configuration.\n *\n * This is the unified mapping logic used by both sources and destinations.\n * It applies transformations in this order:\n * 1. Config-level policy - modifies the event itself (global rules)\n * 2. Mapping rules - finds matching rule based on entity-action\n * 3. Event-level policy - modifies the event based on specific mapping rule\n * 4. Data transformation - creates context data\n * 5. Ignore check and name override\n *\n * Sources can pass partial events, destinations pass full events.\n * getMappingValue works with both partial and full events.\n *\n * @param event - The event to process (can be partial or full, will be mutated by policies)\n * @param config - Mapping configuration (mapping, data, policy, consent)\n * @param collector - Collector instance for context\n * @returns Object with transformed event, data, mapping rule, and ignore flag\n */\nexport async function processEventMapping<\n T extends WalkerOS.DeepPartialEvent | WalkerOS.Event,\n>(\n event: T,\n config: Mapping.Config,\n collector: Collector.Instance,\n): Promise<{\n event: T;\n data?: WalkerOS.Property;\n mapping?: Mapping.Rule;\n mappingKey?: string;\n ignore: boolean;\n}> {\n // Step 1: Apply config-level policy (modifies event)\n if (config.policy) {\n await Promise.all(\n Object.entries(config.policy).map(async ([key, mapping]) => {\n const value = await getMappingValue(event, mapping, { collector });\n event = setByPath(event, key, value);\n }),\n );\n }\n\n // Step 2: Get event mapping rule\n const { eventMapping, mappingKey } = await getMappingEvent(\n event,\n config.mapping,\n );\n\n // Step 2.5: Apply event-level policy (modifies event)\n if (eventMapping?.policy) {\n await Promise.all(\n Object.entries(eventMapping.policy).map(async ([key, mapping]) => {\n const value = await getMappingValue(event, mapping, { collector });\n event = setByPath(event, key, value);\n }),\n );\n }\n\n // Step 3: Transform global data\n let data =\n config.data && (await getMappingValue(event, config.data, { collector }));\n\n if (eventMapping) {\n // Check if event should be ignored\n if (eventMapping.ignore) {\n return { event, data, mapping: eventMapping, mappingKey, ignore: true };\n }\n\n // Override event name if specified\n if (eventMapping.name) event.name = eventMapping.name;\n\n // Transform event-specific data\n if (eventMapping.data) {\n const dataEvent =\n eventMapping.data &&\n (await getMappingValue(event, eventMapping.data, { collector }));\n data =\n isObject(data) && isObject(dataEvent) // Only merge objects\n ? assign(data, dataEvent)\n : dataEvent;\n }\n }\n\n return { event, data, mapping: eventMapping, mappingKey, ignore: false };\n}\n","/**\n * Environment mocking utilities for walkerOS destinations\n *\n * Provides standardized tools for intercepting function calls in environment objects,\n * enabling consistent testing patterns across all destinations.\n */\n\ntype InterceptorFn = (\n path: string[],\n args: unknown[],\n original?: Function,\n) => unknown;\n\n/**\n * Creates a proxied environment that intercepts function calls\n *\n * Uses Proxy to wrap environment objects and capture all function calls,\n * allowing for call recording, mocking, or simulation.\n *\n * @param env - The environment object to wrap\n * @param interceptor - Function called for each intercepted call\n * @returns Proxied environment with interceptor applied\n *\n * @example\n * ```typescript\n * const calls: Array<{ path: string[]; args: unknown[] }> = [];\n *\n * const testEnv = mockEnv(env.push, (path, args) => {\n * calls.push({ path, args });\n * });\n *\n * // Use testEnv with destination\n * await destination.push(event, { env: testEnv });\n *\n * // Analyze captured calls\n * expect(calls).toContainEqual({\n * path: ['window', 'gtag'],\n * args: ['event', 'purchase', { value: 99.99 }]\n * });\n * ```\n */\nexport function mockEnv<T extends object>(\n env: T,\n interceptor: InterceptorFn,\n): T {\n const createProxy = (obj: object, path: string[] = []): object => {\n return new Proxy(obj, {\n get(target, prop: string) {\n const value = (target as Record<string, unknown>)[prop];\n const currentPath = [...path, prop];\n\n if (typeof value === 'function') {\n return (...args: unknown[]) => {\n return interceptor(currentPath, args, value);\n };\n }\n\n if (value && typeof value === 'object') {\n return createProxy(value as object, currentPath);\n }\n\n return value;\n },\n });\n };\n\n return createProxy(env) as T;\n}\n\n/**\n * Traverses environment object and replaces values using a replacer function\n *\n * Alternative to mockEnv for environments where Proxy is not suitable.\n * Performs deep traversal and allows value transformation at each level.\n *\n * @param env - The environment object to traverse\n * @param replacer - Function to transform values during traversal\n * @returns New environment object with transformed values\n *\n * @example\n * ```typescript\n * const recordedCalls: APICall[] = [];\n *\n * const recordingEnv = traverseEnv(originalEnv, (value, path) => {\n * if (typeof value === 'function') {\n * return (...args: unknown[]) => {\n * recordedCalls.push({\n * path: path.join('.'),\n * args: structuredClone(args)\n * });\n * return value(...args);\n * };\n * }\n * return value;\n * });\n * ```\n */\nexport function traverseEnv<T extends object>(\n env: T,\n replacer: (value: unknown, path: string[]) => unknown,\n): T {\n const traverse = (obj: unknown, path: string[] = []): unknown => {\n if (!obj || typeof obj !== 'object') return obj;\n\n const result: Record<string, unknown> | unknown[] = Array.isArray(obj)\n ? []\n : {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n if (Array.isArray(result)) {\n result[Number(key)] = replacer(value, currentPath);\n } else {\n (result as Record<string, unknown>)[key] = replacer(value, currentPath);\n }\n\n if (value && typeof value === 'object' && typeof value !== 'function') {\n if (Array.isArray(result)) {\n result[Number(key)] = traverse(value, currentPath);\n } else {\n (result as Record<string, unknown>)[key] = traverse(\n value,\n currentPath,\n );\n }\n }\n }\n\n return result;\n };\n\n return traverse(env) as T;\n}\n","import type { Instance } from './types/logger';\n\n/**\n * Mock logger instance for testing\n * Includes all logger methods as jest.fn() plus tracking of scoped loggers\n * Extends Instance to ensure type compatibility\n */\nexport interface MockLogger extends Instance {\n error: jest.Mock;\n warn: jest.Mock;\n info: jest.Mock;\n debug: jest.Mock;\n throw: jest.Mock<never, [string | Error, unknown?]>;\n json: jest.Mock;\n scope: jest.Mock<MockLogger, [string]>;\n\n /**\n * Array of all scoped loggers created by this logger\n * Useful for asserting on scoped logger calls in tests\n */\n scopedLoggers: MockLogger[];\n}\n\n/**\n * Create a mock logger for testing\n * All methods are jest.fn() that can be used for assertions\n *\n * @example\n * ```typescript\n * const mockLogger = createMockLogger();\n *\n * // Use in code under test\n * someFunction(mockLogger);\n *\n * // Assert on calls\n * expect(mockLogger.error).toHaveBeenCalledWith('error message');\n *\n * // Assert on scoped logger\n * const scoped = mockLogger.scopedLoggers[0];\n * expect(scoped.debug).toHaveBeenCalledWith('debug in scope');\n * ```\n */\nexport function createMockLogger(): MockLogger {\n const scopedLoggers: MockLogger[] = [];\n\n const mockThrow = jest.fn((message: string | Error): never => {\n const msg = message instanceof Error ? message.message : message;\n throw new Error(msg);\n }) as jest.Mock<never, [string | Error, unknown?]>;\n\n const mockScope = jest.fn((_name: string): MockLogger => {\n const scoped = createMockLogger();\n scopedLoggers.push(scoped);\n return scoped;\n }) as jest.Mock<MockLogger, [string]>;\n\n const mockLogger: MockLogger = {\n error: jest.fn(),\n warn: jest.fn(),\n info: jest.fn(),\n debug: jest.fn(),\n throw: mockThrow,\n json: jest.fn(),\n scope: mockScope,\n scopedLoggers,\n };\n\n return mockLogger;\n}\n","import type { WalkerOS } from './types';\nimport { tryCatch } from './tryCatch';\nimport { castValue } from './castValue';\nimport { isArray, isObject } from './is';\n\n/**\n * Converts a request string to a data object.\n *\n * @param parameter The request string to convert.\n * @returns The data object or undefined.\n */\nexport function requestToData(\n parameter: unknown,\n): WalkerOS.AnyObject | undefined {\n const str = String(parameter);\n const queryString = str.split('?')[1] || str;\n\n return tryCatch(() => {\n const params = new URLSearchParams(queryString);\n const result: WalkerOS.AnyObject = {};\n\n params.forEach((value, key) => {\n const keys = key.split(/[[\\]]+/).filter(Boolean);\n let current: unknown = result;\n\n keys.forEach((k, i) => {\n const isLast = i === keys.length - 1;\n\n if (isArray(current)) {\n const index = parseInt(k, 10);\n if (isLast) {\n (current as Array<unknown>)[index] = castValue(value);\n } else {\n (current as Array<unknown>)[index] =\n (current as Array<unknown>)[index] ||\n (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n current = (current as Array<unknown>)[index];\n }\n } else if (isObject(current)) {\n if (isLast) {\n (current as WalkerOS.AnyObject)[k] = castValue(value);\n } else {\n (current as WalkerOS.AnyObject)[k] =\n (current as WalkerOS.AnyObject)[k] ||\n (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n current = (current as WalkerOS.AnyObject)[k];\n }\n }\n });\n });\n\n return result;\n })();\n}\n\n/**\n * Converts a data object to a request string.\n *\n * @param data The data object to convert.\n * @returns The request string.\n */\nexport function requestToParameter(\n data: WalkerOS.AnyObject | WalkerOS.PropertyType,\n): string {\n if (!data) return '';\n\n const params: string[] = [];\n const encode = encodeURIComponent;\n\n function addParam(key: string, value: unknown) {\n if (value === undefined || value === null) return;\n\n if (isArray(value)) {\n value.forEach((item, index) => addParam(`${key}[${index}]`, item));\n } else if (isObject(value)) {\n Object.entries(value).forEach(([subKey, subValue]) =>\n addParam(`${key}[${subKey}]`, subValue),\n );\n } else {\n params.push(`${encode(key)}=${encode(String(value))}`);\n }\n }\n\n if (typeof data === 'object') {\n Object.entries(data).forEach(([key, value]) => addParam(key, value));\n } else {\n return encode(data);\n }\n\n return params.join('&');\n}\n","import type { SendDataValue, SendHeaders } from './types/send';\nimport { isSameType } from './is';\nimport { assign } from './assign';\n\nexport type { SendDataValue, SendHeaders, SendResponse } from './types/send';\n\n/**\n * Transforms data to a string.\n *\n * @param data The data to transform.\n * @returns The transformed data.\n */\nexport function transformData(data?: SendDataValue): string | undefined {\n if (data === undefined) return data;\n\n return isSameType(data, '' as string) ? data : JSON.stringify(data);\n}\n\n/**\n * Gets the headers for a request.\n *\n * @param headers The headers to merge with the default headers.\n * @returns The merged headers.\n */\nexport function getHeaders(headers: SendHeaders = {}): SendHeaders {\n return assign(\n {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n headers,\n );\n}\n","/**\n * Trims quotes and whitespaces from a string.\n *\n * @param str The string to trim.\n * @returns The trimmed string.\n */\nexport function trim(str: string): string {\n // Remove quotes and whitespaces\n return str ? str.trim().replace(/^'|'$/g, '').trim() : '';\n}\n","import type { Hooks } from './types';\n\n/**\n * A utility function that wraps a function with hooks.\n *\n * @template P, R\n * @param fn The function to wrap.\n * @param name The name of the function.\n * @param hooks The hooks to use.\n * @returns The wrapped function.\n */\nexport function useHooks<P extends unknown[], R>(\n fn: (...args: P) => R,\n name: string,\n hooks: Hooks.Functions,\n): (...args: P) => R {\n return function (...args: P): R {\n let result: R;\n const preHook = ('pre' + name) as keyof Hooks.Functions;\n const postHook = ('post' + name) as keyof Hooks.Functions;\n const preHookFn = hooks[preHook] as unknown as Hooks.HookFn<typeof fn>;\n const postHookFn = hooks[postHook] as unknown as Hooks.HookFn<typeof fn>;\n\n if (preHookFn) {\n // Call the original function within the preHook\n result = preHookFn({ fn }, ...args);\n } else {\n // Regular function call\n result = fn(...args);\n }\n\n if (postHookFn) {\n // Call the post-hook function with fn, result, and the original args\n result = postHookFn({ fn, result }, ...args);\n }\n\n return result;\n };\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Parses a user agent string to extract browser, OS, and device information.\n *\n * @param userAgent The user agent string to parse.\n * @returns An object containing the parsed user agent information.\n */\nexport function parseUserAgent(userAgent?: string): WalkerOS.User {\n if (!userAgent) return {};\n\n return {\n userAgent,\n browser: getBrowser(userAgent),\n browserVersion: getBrowserVersion(userAgent),\n os: getOS(userAgent),\n osVersion: getOSVersion(userAgent),\n deviceType: getDeviceType(userAgent),\n };\n}\n\n/**\n * Gets the browser name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser name or undefined.\n */\nexport function getBrowser(userAgent: string): string | undefined {\n const browsers = [\n { name: 'Edge', substr: 'Edg' },\n { name: 'Chrome', substr: 'Chrome' },\n { name: 'Safari', substr: 'Safari', exclude: 'Chrome' },\n { name: 'Firefox', substr: 'Firefox' },\n { name: 'IE', substr: 'MSIE' },\n { name: 'IE', substr: 'Trident' },\n ];\n\n for (const browser of browsers) {\n if (\n userAgent.includes(browser.substr) &&\n (!browser.exclude || !userAgent.includes(browser.exclude))\n ) {\n return browser.name;\n }\n }\n\n return;\n}\n\n/**\n * Gets the browser version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser version or undefined.\n */\nexport function getBrowserVersion(userAgent: string): string | undefined {\n const rules = [\n /Edg\\/([0-9]+)/, // Edge\n /Chrome\\/([0-9]+)/, // Chrome\n /Version\\/([0-9]+).*Safari/, // Safari\n /Firefox\\/([0-9]+)/, // Firefox\n /MSIE ([0-9]+)/, // IE 10 and older\n /rv:([0-9]+).*Trident/, // IE 11\n ];\n\n for (const regex of rules) {\n const match = userAgent.match(regex);\n if (match) {\n return match[1];\n }\n }\n\n return;\n}\n\n/**\n * Gets the OS name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS name or undefined.\n */\nexport function getOS(userAgent: string): string | undefined {\n const osList = [\n { name: 'Windows', substr: 'Windows NT' },\n { name: 'macOS', substr: 'Mac OS X' },\n { name: 'Android', substr: 'Android' },\n { name: 'iOS', substr: 'iPhone OS' },\n { name: 'Linux', substr: 'Linux' },\n ];\n\n for (const os of osList) {\n if (userAgent.includes(os.substr)) {\n return os.name;\n }\n }\n\n return;\n}\n\n/**\n * Gets the OS version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS version or undefined.\n */\nexport function getOSVersion(userAgent: string): string | undefined {\n const osVersionRegex = /(?:Windows NT|Mac OS X|Android|iPhone OS) ([0-9._]+)/;\n const match = userAgent.match(osVersionRegex);\n return match ? match[1].replace(/_/g, '.') : undefined;\n}\n\n/**\n * Gets the device type from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The device type or undefined.\n */\nexport function getDeviceType(userAgent: string): string | undefined {\n let deviceType = 'Desktop';\n\n if (/Tablet|iPad/i.test(userAgent)) {\n deviceType = 'Tablet';\n } else if (\n /Mobi|Android|iPhone|iPod|BlackBerry|Opera Mini|IEMobile|WPDesktop/i.test(\n userAgent,\n )\n ) {\n deviceType = 'Mobile';\n }\n\n return deviceType;\n}\n","/**\n * Inline Code Wrapping Utilities\n *\n * Converts inline code strings to executable functions.\n * Used for mapping properties: condition, fn, validate.\n *\n * @packageDocumentation\n */\n\nimport type { Mapping } from './types';\n\n/**\n * Detect if code has explicit return statement.\n */\nfunction hasReturn(code: string): boolean {\n return /\\breturn\\b/.test(code);\n}\n\n/**\n * Wrap code with function body.\n * If code has no return, auto-wrap with return.\n */\nfunction wrapCode(code: string): string {\n return hasReturn(code) ? code : `return ${code}`;\n}\n\n/**\n * Wrap inline code string as Condition function.\n *\n * @param code - Inline code string\n * @returns Condition function matching Mapping.Condition signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The event or partial event being processed\n * - `mapping` - Current mapping configuration\n * - `collector` - Collector instance\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapCondition('value.data.total > 100');\n * fn(event, mapping, collector); // returns boolean\n *\n * // Multi-statement (explicit return)\n * const fn = wrapCondition('const threshold = 100; return value.data.total > threshold');\n * ```\n */\nexport function wrapCondition(code: string): Mapping.Condition {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function(\n 'value',\n 'mapping',\n 'collector',\n body,\n ) as Mapping.Condition;\n}\n\n/**\n * Wrap inline code string as Fn function.\n *\n * @param code - Inline code string\n * @returns Fn function matching Mapping.Fn signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The event or partial event being processed\n * - `mapping` - Current mapping configuration\n * - `options` - Options object with consent and collector\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapFn('value.user.email.split(\"@\")[1]');\n * fn(event, mapping, options); // returns domain\n *\n * // Multi-statement (explicit return)\n * const fn = wrapFn('const parts = value.user.email.split(\"@\"); return parts[1].toUpperCase()');\n * ```\n */\nexport function wrapFn(code: string): Mapping.Fn {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function('value', 'mapping', 'options', body) as Mapping.Fn;\n}\n\n/**\n * Wrap inline code string as Validate function.\n *\n * @param code - Inline code string\n * @returns Validate function matching Mapping.Validate signature\n *\n * @remarks\n * Available parameters in code:\n * - `value` - The current value being validated\n *\n * If code has no explicit return, it's auto-wrapped with `return`.\n *\n * @example\n * ```typescript\n * // One-liner (auto-wrapped)\n * const fn = wrapValidate('value && value.length > 0');\n * fn('hello'); // returns true\n *\n * // Multi-statement (explicit return)\n * const fn = wrapValidate('if (!value) return false; return value.length > 0');\n * ```\n */\nexport function wrapValidate(code: string): Mapping.Validate {\n const body = wrapCode(code);\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function('value', body) as Mapping.Validate;\n}\n","const JSDELIVR_BASE = 'https://cdn.jsdelivr.net/npm';\nconst DEFAULT_SCHEMA_PATH = 'dist/walkerOS.json';\n\nfunction parsePlatform(value: unknown): string | string[] | undefined {\n if (typeof value === 'string') return value;\n if (Array.isArray(value) && value.every((v) => typeof v === 'string'))\n return value as string[];\n return undefined;\n}\n\nexport interface ExampleSummary {\n name: string;\n description?: string;\n}\n\nexport interface WalkerOSPackageMeta {\n packageName: string;\n version: string;\n description?: string;\n type?: string;\n platform?: string | string[];\n}\n\nexport interface WalkerOSPackageInfo {\n packageName: string;\n version: string;\n type?: string;\n platform?: string | string[];\n schemas: Record<string, unknown>;\n examples: Record<string, unknown>;\n hints?: Record<string, unknown>;\n}\n\nexport interface WalkerOSPackage extends WalkerOSPackageInfo {\n description?: string;\n docs?: string;\n source?: string;\n hintKeys: string[];\n exampleSummaries: ExampleSummary[];\n}\n\nexport async function fetchPackage(\n packageName: string,\n options?: { version?: string; timeout?: number },\n): Promise<WalkerOSPackage> {\n const ver = options?.version || 'latest';\n const base = `${JSDELIVR_BASE}/${packageName}@${ver}`;\n const controller = new AbortController();\n const timeoutMs = options?.timeout || 10000;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n // Fetch package.json\n const pkgRes = await fetch(`${base}/package.json`, {\n signal: controller.signal,\n });\n if (!pkgRes.ok) {\n throw new Error(\n `Package \"${packageName}\" not found on npm (HTTP ${pkgRes.status})`,\n );\n }\n const pkg = (await pkgRes.json()) as Record<string, unknown>;\n\n // Fetch walkerOS.json\n const schemaRes = await fetch(`${base}/${DEFAULT_SCHEMA_PATH}`, {\n signal: controller.signal,\n });\n if (!schemaRes.ok) {\n throw new Error(\n `walkerOS.json not found at ${DEFAULT_SCHEMA_PATH} (HTTP ${schemaRes.status}). ` +\n `This package may not support the walkerOS.json convention yet.`,\n );\n }\n const walkerOSJson = (await schemaRes.json()) as Record<string, unknown>;\n const meta = (walkerOSJson.$meta as Record<string, unknown>) || {};\n\n const schemas = (walkerOSJson.schemas as Record<string, unknown>) || {};\n const examples = (walkerOSJson.examples as Record<string, unknown>) || {};\n const hints = walkerOSJson.hints as Record<string, unknown> | undefined;\n\n // Extract hint keys\n const hintKeys = hints ? Object.keys(hints) : [];\n\n // Extract example summaries from step examples\n const exampleSummaries: ExampleSummary[] = [];\n const stepExamples = (examples.step || {}) as Record<string, unknown>;\n for (const [name, example] of Object.entries(stepExamples)) {\n const ex = example as Record<string, unknown> | undefined;\n const summary: ExampleSummary = { name };\n if (typeof ex?.description === 'string')\n summary.description = ex.description;\n exampleSummaries.push(summary);\n }\n\n const docs = typeof meta.docs === 'string' ? meta.docs : undefined;\n const source = typeof meta.source === 'string' ? meta.source : undefined;\n\n return {\n packageName,\n version: typeof pkg.version === 'string' ? pkg.version : ver,\n description:\n typeof pkg.description === 'string' ? pkg.description : undefined,\n type: typeof meta.type === 'string' ? meta.type : undefined,\n platform: parsePlatform(meta.platform),\n schemas,\n examples,\n ...(docs ? { docs } : {}),\n ...(source ? { source } : {}),\n ...(hints && Object.keys(hints).length > 0 ? { hints } : {}),\n hintKeys,\n exampleSummaries,\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * @deprecated Use fetchPackage instead.\n * Still used by: entry.ts (validator), package-schemas.ts (MCP resource).\n */\nexport async function fetchPackageSchema(\n packageName: string,\n options?: { version?: string; timeout?: number },\n): Promise<WalkerOSPackageInfo> {\n const pkg = await fetchPackage(packageName, options);\n return {\n packageName: pkg.packageName,\n version: pkg.version,\n type: pkg.type,\n platform: pkg.platform,\n schemas: pkg.schemas,\n examples: pkg.examples,\n ...(pkg.hints ? { hints: pkg.hints } : {}),\n };\n}\n","export function mcpResult(\n result: unknown,\n summary?: string,\n hints?: { next?: string[]; warnings?: string[] },\n) {\n const enriched = hints\n ? { ...(result as Record<string, unknown>), _hints: hints }\n : result;\n return {\n content: [\n {\n type: 'text' as const,\n text: summary ?? JSON.stringify(enriched, null, 2),\n },\n ],\n structuredContent: enriched as Record<string, unknown>,\n };\n}\n\nexport function mcpError(error: unknown, hint?: string) {\n let message: string;\n let path: string | undefined;\n let code: string | undefined;\n let details: unknown[] | undefined;\n\n if (error instanceof Error) {\n message = error.message;\n // Detect ApiError (has code and/or details properties)\n const err = error as Error & { code?: string; details?: unknown[] };\n if (err.code) code = err.code;\n if (Array.isArray(err.details)) details = err.details;\n } else if (typeof error === 'string') {\n message = error;\n } else if (\n error &&\n typeof error === 'object' &&\n 'issues' in error &&\n Array.isArray((error as { issues: unknown[] }).issues)\n ) {\n const issues = (\n error as { issues: Array<{ path?: unknown[]; message: string }> }\n ).issues;\n message = issues.map((i) => i.message).join('; ');\n path = issues[0]?.path?.join('.') || undefined;\n } else if (error && typeof error === 'object' && 'message' in error) {\n message = String((error as { message: unknown }).message);\n } else {\n message = 'Unknown error';\n }\n\n const structured: Record<string, unknown> = { error: message };\n if (hint) structured.hint = hint;\n if (path) structured.path = path;\n if (code) structured.code = code;\n if (details) structured.details = details;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(structured),\n },\n ],\n structuredContent: structured,\n isError: true as const,\n };\n}\n","/**\n * Options for responding to an HTTP request.\n * Same interface for web and server — sources implement the handler.\n */\nexport interface RespondOptions {\n /** Response body. Objects are JSON-serialized by source. */\n body?: unknown;\n /** HTTP status code (default: 200). Server-only, ignored by web sources. */\n status?: number;\n /** HTTP response headers. Server-only, ignored by web sources. */\n headers?: Record<string, string>;\n}\n\n/**\n * Standardized response function available on env for every step.\n * Idempotent: first call wins, subsequent calls are no-ops.\n * Created by sources via createRespond(), consumed by any step.\n */\nexport type RespondFn = (options?: RespondOptions) => void;\n\n/**\n * Creates an idempotent respond function.\n * The sender callback is source-specific (Express wraps res, Fetch wraps Response, etc.).\n *\n * @param sender - Platform-specific function that actually sends the response\n * @returns Idempotent respond function (first call wins)\n */\nexport function createRespond(\n sender: (options: RespondOptions) => void,\n): RespondFn {\n let called = false;\n return (options: RespondOptions = {}) => {\n if (called) return;\n called = true;\n sender(options);\n };\n}\n","import type {\n MatchExpression,\n MatchCondition,\n MatchOperator,\n CompiledMatcher,\n} from './types/matcher';\n\n/**\n * Compiles a match expression into a closure for fast runtime evaluation.\n * Regex patterns are compiled once. Numeric comparisons are parsed once.\n * Runtime evaluation is pure function calls with short-circuit logic.\n */\nexport function compileMatcher(expr: MatchExpression | '*'): CompiledMatcher {\n if (expr === '*') return () => true;\n\n if ('and' in expr) {\n const fns = expr.and.map(compileMatcher);\n return (ingest) => fns.every((fn) => fn(ingest));\n }\n\n if ('or' in expr) {\n const fns = expr.or.map(compileMatcher);\n return (ingest) => fns.some((fn) => fn(ingest));\n }\n\n // Leaf condition\n return compileCondition(expr);\n}\n\nfunction compileCondition(condition: MatchCondition): CompiledMatcher {\n const { key, operator, value, not } = condition;\n const test = compileOperator(operator, value);\n\n return (ingest) => {\n const raw = ingest[key];\n const result = test(raw);\n return not ? !result : result;\n };\n}\n\nfunction compileOperator(\n operator: MatchOperator,\n value: string,\n): (input: unknown) => boolean {\n switch (operator) {\n case 'eq':\n return (input) => String(input ?? '') === value;\n case 'contains':\n return (input) => String(input ?? '').includes(value);\n case 'prefix':\n return (input) => String(input ?? '').startsWith(value);\n case 'suffix':\n return (input) => String(input ?? '').endsWith(value);\n case 'regex': {\n const re = new RegExp(value);\n return (input) => re.test(String(input ?? ''));\n }\n case 'gt': {\n const num = Number(value);\n return (input) => Number(input) > num;\n }\n case 'lt': {\n const num = Number(value);\n return (input) => Number(input) < num;\n }\n case 'exists':\n return (input) => input !== undefined && input !== null;\n }\n}\n","/**\n * Central validation module\n * Single source of truth for validation library access\n *\n * All schema files should import from this module instead of directly\n * from zod to ensure consistent usage and easy maintenance.\n */\n\nimport { z } from 'zod';\n\n// Re-export validation tools for schema files\nexport { z };\nexport type { z as zod } from 'zod';\n\n/**\n * Standard JSON Schema conversion with consistent project defaults\n *\n * Uses Zod 4 native toJSONSchema() method for JSON Schema generation.\n * All walkerOS schemas use JSON Schema Draft 7 format.\n *\n * @param schema - Zod schema to convert\n * @param _name - Schema name (ignored in Zod 4, kept for API compatibility)\n * @param target - JSON Schema target version (default: 'draft-7')\n * @returns JSON Schema object\n */\nexport function toJsonSchema(\n schema: z.ZodTypeAny,\n _name?: string,\n target: 'draft-7' | 'draft-2020-12' | 'openapi-3.0' = 'draft-7',\n) {\n return z.toJSONSchema(schema, {\n target,\n });\n}\n","import { z } from './validation';\n\n/**\n * Primitive Schema Definitions\n *\n * Reusable primitive schemas following DRY principle.\n * These are the building blocks used throughout all schemas to ensure consistency.\n *\n * Benefits:\n * - Single source of truth for common patterns\n * - Consistent descriptions across all schemas\n * - Easier maintenance and updates\n * - Better IntelliSense/autocomplete\n */\n\n// ========================================\n// Basic Primitives\n// ========================================\n\n/**\n * Required string field\n * Used for required text fields throughout schemas\n */\nexport const RequiredString = z.string();\n\n/**\n * Required number field\n * Used for required numeric fields throughout schemas\n */\nexport const RequiredNumber = z.number();\n\n/**\n * Required boolean field\n * Used for required flag fields throughout schemas\n */\nexport const RequiredBoolean = z.boolean();\n\n// ========================================\n// Semantic Primitives\n// ========================================\n\n/**\n * Identifier - Required unique string identifier\n * Used for entity IDs, session IDs, etc.\n */\nexport const Identifier = z.string().min(1);\n\n/**\n * Timestamp - Unix timestamp in milliseconds\n * Used for event timestamps, session timestamps, etc.\n */\nexport const Timestamp = z.number().int().positive();\n\n/**\n * Counter - Sequential counter (non-negative integer)\n * Used for event counts, session counts, etc.\n */\nexport const Counter = z.number().int().nonnegative();\n\n/**\n * TaggingVersion - Version number for event tagging\n * Standardized description used in both Version and Config schemas\n */\nexport const TaggingVersion = z.number().describe('Tagging version number');\n\n// ========================================\n// Primitive Value Unions\n// ========================================\n\n/**\n * PrimitiveValue - Basic primitive types\n * Union of string, number, and boolean\n * Used in Property definitions and value transformations\n */\nexport const PrimitiveValue = z.union([z.string(), z.number(), z.boolean()]);\n\n/**\n * OptionalPrimitiveValue - Optional primitive value\n */\nexport const OptionalPrimitiveValue = PrimitiveValue.optional();\n","import { z, toJsonSchema } from './validation';\n\n/**\n * Utility Schemas\n *\n * Mirrors: types/storage.ts, types/handler.ts, and other utility types\n * Purpose: Runtime validation and JSON Schema generation for utility types\n *\n * Small, standalone schemas for utility types used throughout walkerOS:\n * - Storage types\n * - Handler functions\n * - Error/log management\n */\n\n// ========================================\n// Storage Schemas\n// ========================================\n\n/**\n * StorageType - Storage mechanism identifier\n *\n * Standard storage types:\n * - local: localStorage (persistent)\n * - session: sessionStorage (session-scoped)\n * - cookie: document.cookie (configurable expiry)\n *\n * Used for session persistence and user tracking\n */\nexport const StorageTypeSchema = z\n .enum(['local', 'session', 'cookie'])\n .describe('Storage mechanism: local, session, or cookie');\n\n/**\n * Storage - Storage type constants\n * Provides const values for type-safe storage type references\n */\nexport const StorageSchema = z\n .object({\n Local: z.literal('local'),\n Session: z.literal('session'),\n Cookie: z.literal('cookie'),\n })\n .describe('Storage type constants for type-safe references');\n\n// ========================================\n// Handler Schemas\n// ========================================\n\n/**\n * Error - Error handler function type\n *\n * Signature: (error: unknown, state?: unknown) => void\n *\n * Called when errors occur during:\n * - Event processing\n * - Destination push operations\n * - Source event handling\n * - Mapping transformations\n *\n * Parameters:\n * - error: The error that occurred\n * - state: Optional state information for debugging\n *\n * Note: Function schemas use z.unknown() as functions aren't serializable\n */\nexport const ErrorHandlerSchema = z\n .any()\n .describe('Error handler function: (error, state?) => void');\n\n/**\n * Log - Log handler function type\n *\n * Signature: (message: string, verbose?: boolean) => void\n *\n * Called for logging during:\n * - Event processing\n * - Configuration updates\n * - Debugging (when verbose enabled)\n *\n * Parameters:\n * - message: Log message\n * - verbose: Whether this is a verbose-only log\n *\n * Note: Function schemas use z.unknown() as functions aren't serializable\n */\nexport const LogHandlerSchema = z\n .any()\n .describe('Log handler function: (message, verbose?) => void');\n\n/**\n * Handler - Combined handler interface\n * Groups Error and Log handlers\n */\nexport const HandlerSchema = z\n .object({\n Error: ErrorHandlerSchema.describe('Error handler function'),\n Log: LogHandlerSchema.describe('Log handler function'),\n })\n .describe('Handler interface with error and log functions');\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const storageTypeJsonSchema = toJsonSchema(\n StorageTypeSchema,\n 'StorageType',\n);\n\nexport const storageJsonSchema = toJsonSchema(StorageSchema, 'Storage');\n\nexport const errorHandlerJsonSchema = toJsonSchema(\n ErrorHandlerSchema,\n 'ErrorHandler',\n);\n\nexport const logHandlerJsonSchema = toJsonSchema(\n LogHandlerSchema,\n 'LogHandler',\n);\n\nexport const handlerJsonSchema = toJsonSchema(HandlerSchema, 'Handler');\n","import { z } from './validation';\nimport {} from './primitives';\nimport { ErrorHandlerSchema, LogHandlerSchema } from './utilities';\n\n/**\n * Common Schema Patterns\n *\n * Reusable schema patterns that appear across multiple domain schemas.\n * These patterns combine primitives into commonly used configurations.\n *\n * Benefits:\n * - DRY principle for complex patterns\n * - Consistent configuration interfaces\n * - Single source of truth for common configs\n * - Easier to maintain and update patterns globally\n */\n\n// ========================================\n// Handler Patterns\n// ========================================\n\n/**\n * HandlersConfig - Error and log handler configuration\n * Used in: Destination.Config, Collector.Config, Source.Config\n */\nexport const HandlersConfig = z\n .object({\n onError: ErrorHandlerSchema.optional().describe(\n 'Error handler function: (error, state?) => void',\n ),\n onLog: LogHandlerSchema.optional().describe(\n 'Log handler function: (message, verbose?) => void',\n ),\n })\n .partial();\n\n// ========================================\n// Configuration Patterns\n// ========================================\n\n/**\n * VerboseConfig - Verbose logging configuration\n * Used in: Destination.Config, Collector.Config\n */\nexport const VerboseConfig = z\n .object({\n verbose: z\n .boolean()\n .describe('Enable verbose logging for debugging')\n .optional(),\n })\n .partial();\n\n/**\n * QueueConfig - Event queueing configuration\n * Used in: Destination.Config\n */\nexport const QueueConfig = z\n .object({\n queue: z\n .boolean()\n .describe('Whether to queue events when consent is not granted')\n .optional(),\n })\n .partial();\n\n/**\n * IdConfig - ID configuration pattern\n * Used in: Destination.Config, Source.Config\n */\nexport const IdConfig = z.object({}).partial();\n\n/**\n * InitConfig - Initialization configuration pattern\n * Used in: Destination.Config\n */\nexport const InitConfig = z\n .object({\n init: z.boolean().describe('Whether to initialize immediately').optional(),\n loadScript: z\n .boolean()\n .describe('Whether to load external script (for web destinations)')\n .optional(),\n })\n .partial();\n\n/**\n * PrimaryConfig - Primary flag configuration\n * Used in: Source.Config, Source.InitSource\n */\nexport const PrimaryConfig = z\n .object({\n primary: z\n .boolean()\n .describe('Mark as primary (only one can be primary)')\n .optional(),\n })\n .partial();\n\n// ========================================\n// Generic Configuration Patterns\n// ========================================\n\n/**\n * GenericSettingsConfig - Generic settings configuration\n * Used in: Destination.Config, Source.Config, Collector runtime\n * Settings are implementation-specific and can't be validated generically\n */\nexport const GenericSettingsConfig = z\n .object({\n settings: z\n .any()\n .optional()\n .describe('Implementation-specific configuration'),\n })\n .partial();\n\n/**\n * GenericEnvConfig - Generic environment configuration\n * Used in: Destination.Config, Source.Config, Source.BaseEnv\n * Environment is platform-specific and can't be validated generically\n */\nexport const GenericEnvConfig = z\n .object({\n env: z\n .any()\n .optional()\n .describe('Environment dependencies (platform-specific)'),\n })\n .partial();\n\n// ========================================\n// Mapping Patterns\n// ========================================\n\n/**\n * DataTransformationConfig - Data transformation configuration\n * Used in: Destination.Config, Mapping.Config, Mapping.Rule\n *\n * Note: This creates a forward reference to ValueSchema/ValuesSchema\n * Import from mapping.ts to avoid circular dependencies\n */\nexport function createDataTransformationConfig(\n ValueSchema: z.ZodTypeAny,\n ValuesSchema: z.ZodTypeAny,\n) {\n return z\n .object({\n data: z\n .union([ValueSchema, ValuesSchema])\n .optional()\n .describe('Data transformation rules'),\n })\n .partial();\n}\n\n/**\n * MappingRulesConfig - Mapping rules configuration\n * Used in: Destination.Config, Source.Config (via Mapping.Config)\n *\n * Note: This creates a forward reference to RulesSchema\n * Import from mapping.ts to avoid circular dependencies\n */\nexport function createMappingRulesConfig(RulesSchema: z.ZodTypeAny) {\n return z\n .object({\n mapping: RulesSchema.optional().describe('Event mapping rules'),\n })\n .partial();\n}\n\n/**\n * PolicyConfig - Policy rules configuration\n * Used in: Destination.Config, Mapping.Config, Mapping.Rule\n *\n * Note: This creates a forward reference to PolicySchema\n * Import from mapping.ts to avoid circular dependencies\n */\nexport function createPolicyConfig(PolicySchema: z.ZodTypeAny) {\n return z\n .object({\n policy: PolicySchema.optional().describe('Pre-processing policy rules'),\n })\n .partial();\n}\n\n/**\n * ConsentConfig - Consent requirements configuration\n * Used in: Destination.Config, Mapping.Config, Mapping.Rule, Event\n *\n * Note: This creates a forward reference to ConsentSchema\n * Import from walkeros.ts to avoid circular dependencies\n */\nexport function createConsentConfig(ConsentSchema: z.ZodTypeAny) {\n return z\n .object({\n consent: ConsentSchema.optional().describe('Required consent states'),\n })\n .partial();\n}\n\n// ========================================\n// Instance Patterns\n// ========================================\n\n/**\n * RuntimeInstanceConfig - Runtime instance configuration\n * Used in: Destination.Instance, Source.Instance, Collector.Instance\n *\n * Common fields for runtime instances:\n * - type: Instance type identifier\n * - config: Configuration object\n * - Functions (push, init, etc.) are instance-specific\n */\nexport const RuntimeInstanceConfig = z\n .object({\n type: z.string().optional().describe('Instance type identifier'),\n config: z.unknown().describe('Instance configuration'),\n })\n .partial();\n\n// ========================================\n// Context Patterns\n// ========================================\n\n/**\n * BaseContextConfig - Base context configuration\n * Used in: Destination.Context, Source contexts\n *\n * Common fields for contexts:\n * - collector: Collector instance (runtime)\n * - config: Configuration\n * - env: Environment dependencies\n */\nexport const BaseContextConfig = z\n .object({\n collector: z.unknown().describe('Collector instance (runtime object)'),\n config: z.unknown().describe('Configuration'),\n env: z.unknown().describe('Environment dependencies'),\n })\n .partial();\n\n// ========================================\n// Batch Patterns\n// ========================================\n\n/**\n * BatchConfig - Batch processing configuration\n * Used in: Mapping.Rule\n */\nexport const BatchConfig = z\n .object({\n batch: z\n .number()\n .optional()\n .describe('Batch size: bundle N events for batch processing'),\n batched: z.unknown().optional().describe('Batch of events to be processed'),\n })\n .partial();\n\n// ========================================\n// Processing Patterns\n// ========================================\n\n/**\n * ProcessingControlConfig - Processing control flags\n * Used in: Mapping.Rule\n */\nexport const ProcessingControlConfig = z\n .object({\n ignore: z.boolean().describe('Set to true to skip processing').optional(),\n condition: z\n .string()\n .optional()\n .describe('Condition function: return true to process'),\n })\n .partial();\n\n// ========================================\n// Collection Patterns\n// ========================================\n\n/**\n * SourcesMapConfig - Sources collection pattern\n * Used in: Collector.Instance\n */\nexport const SourcesMapConfig = z\n .object({\n sources: z\n .record(z.string(), z.unknown())\n .describe('Map of source instances'),\n })\n .partial();\n\n/**\n * DestinationsMapConfig - Destinations collection pattern\n * Used in: Collector.Instance\n */\nexport const DestinationsMapConfig = z\n .object({\n destinations: z\n .record(z.string(), z.unknown())\n .describe('Map of destination instances'),\n })\n .partial();\n","import { z, toJsonSchema } from './validation';\nimport {\n RequiredString,\n RequiredNumber,\n Identifier,\n Timestamp,\n Counter,\n TaggingVersion,\n} from './primitives';\n\n/**\n * Core walkerOS Event Model Schemas\n *\n * Mirrors: types/walkeros.ts\n * Purpose: Runtime validation and JSON Schema generation for MCP tools, Explorer UI, and API boundaries\n *\n * These schemas provide:\n * 1. Runtime validation for event data\n * 2. JSON Schema generation for RJSF/Explorer\n * 3. Type documentation via .describe()\n * 4. Compile-time type checking (schemas mirror TypeScript types)\n *\n * Note: TypeScript types in types/walkeros.ts remain the source of truth for development.\n * These Zod schemas are for validation and JSON Schema generation at runtime boundaries.\n */\n\n// ========================================\n// Base Property Types (Recursive)\n// ========================================\n\n/**\n * PropertyType - Base property value types\n * Can be primitive (boolean, string, number) or nested object with Property values\n */\nexport const PropertyTypeSchema: z.ZodTypeAny = z.lazy(() =>\n z.union([\n z.boolean(),\n z.string(),\n z.number(),\n z.record(z.string(), PropertySchema),\n ]),\n);\n\n/**\n * Property - PropertyType or array of PropertyType\n * Recursive structure allows nested objects and arrays\n */\nexport const PropertySchema: z.ZodTypeAny = z.lazy(() =>\n z.union([PropertyTypeSchema, z.array(PropertyTypeSchema)]),\n);\n\n/**\n * Properties - Record of string keys to Property values\n * Used throughout event structure (data, globals, custom, etc.)\n */\nexport const PropertiesSchema = z\n .record(z.string(), PropertySchema.optional())\n .describe('Flexible property collection with optional values');\n\n/**\n * OrderedProperties - Record with [value, order] tuples\n * Used for context data where order matters\n */\nexport const OrderedPropertiesSchema = z\n .record(z.string(), z.tuple([PropertySchema, z.number()]).optional())\n .describe(\n 'Ordered properties with [value, order] tuples for priority control',\n );\n\n// ========================================\n// Enums & Union Types\n// ========================================\n\n/**\n * SourceType - Event source identifier\n * Standard types: web, server, app, other\n * Extensible: allows custom string values\n */\nexport const SourceTypeSchema = z\n .union([z.enum(['web', 'server', 'app', 'other']), z.string()])\n .describe('Source type: web, server, app, other, or custom');\n\n// ========================================\n// Event Sub-Types\n// ========================================\n\n/**\n * Consent - Consent state mapping\n * Maps consent group names to boolean states\n * Used in Event and Destination/Source configs\n */\nexport const ConsentSchema = z\n .record(z.string(), z.boolean())\n .describe('Consent requirement mapping (group name → state)');\n\n/**\n * User - User identification and attributes\n * Extends Properties with specific optional fields\n * Contains IDs, demographics, device info, and location data\n */\nexport const UserSchema = PropertiesSchema.and(\n z.object({\n // IDs\n id: z.string().optional().describe('User identifier'),\n device: z.string().optional().describe('Device identifier'),\n session: z.string().optional().describe('Session identifier'),\n hash: z.string().optional().describe('Hashed identifier'),\n // User attributes\n address: z.string().optional().describe('User address'),\n email: z.string().email().optional().describe('User email address'),\n phone: z.string().optional().describe('User phone number'),\n // Technical attributes\n userAgent: z.string().optional().describe('Browser user agent string'),\n browser: z.string().optional().describe('Browser name'),\n browserVersion: z.string().optional().describe('Browser version'),\n deviceType: z\n .string()\n .optional()\n .describe('Device type (mobile, desktop, tablet)'),\n os: z.string().optional().describe('Operating system'),\n osVersion: z.string().optional().describe('Operating system version'),\n screenSize: z.string().optional().describe('Screen dimensions'),\n // Location attributes\n language: z.string().optional().describe('User language'),\n country: z.string().optional().describe('User country'),\n region: z.string().optional().describe('User region/state'),\n city: z.string().optional().describe('User city'),\n zip: z.string().optional().describe('User postal code'),\n timezone: z.string().optional().describe('User timezone'),\n ip: z.string().optional().describe('User IP address'),\n // Flags\n internal: z\n .boolean()\n .optional()\n .describe('Internal user flag (employee, test user)'),\n }),\n).describe('User identification and properties');\n\n/**\n * Version - Walker version information\n * Tracks source implementation and tagging version\n */\nexport const VersionSchema = PropertiesSchema.and(\n z.object({\n source: RequiredString.describe(\n 'Walker implementation version (e.g., \"2.0.0\")',\n ),\n tagging: TaggingVersion,\n }),\n).describe('Walker version information');\n\n/**\n * Source - Event source information\n * Identifies where the event originated\n */\nexport const SourceSchema = PropertiesSchema.and(\n z.object({\n type: SourceTypeSchema.describe('Source type identifier'),\n id: RequiredString.describe('Source identifier (typically URL on web)'),\n previous_id: RequiredString.describe(\n 'Previous source identifier (typically referrer on web)',\n ),\n }),\n).describe('Event source information');\n\n/**\n * Entity - Nested entity structure\n * Allows events to contain related entities with their own data and context\n * Recursive: entities can contain nested entities\n */\nexport const EntitySchema: z.ZodTypeAny = z\n .lazy(() =>\n z.object({\n entity: z.string().describe('Entity name'),\n data: PropertiesSchema.describe('Entity-specific properties'),\n nested: z.array(EntitySchema).describe('Nested child entities'),\n context: OrderedPropertiesSchema.describe('Entity context data'),\n }),\n )\n .describe('Nested entity structure with recursive nesting support');\n\n/**\n * Entities - Array of Entity objects\n */\nexport const EntitiesSchema = z\n .array(EntitySchema)\n .describe('Array of nested entities');\n\n// ========================================\n// Main Event Schema\n// ========================================\n\n/**\n * Event - Complete walkerOS event structure\n *\n * Core fields:\n * - name: Event identifier in \"entity action\" format (e.g., \"page view\")\n * - data: Event-specific properties\n * - context: Ordered context properties\n * - globals: Global properties shared across events\n * - custom: Custom properties specific to implementation\n * - user: User identification and attributes\n * - nested: Related entities\n * - consent: Consent states at event time\n *\n * System-generated fields:\n * - id: Unique event identifier\n * - timestamp: Event creation time (milliseconds since epoch)\n * - entity: Parsed entity name from event.name\n * - action: Parsed action name from event.name\n * - trigger: Event trigger identifier\n * - timing: Event processing timing information\n * - group: Event grouping identifier\n * - count: Event count in session\n * - version: Walker version information\n * - source: Event source information\n */\nexport const EventSchema = z\n .object({\n // Core event identification\n name: z\n .string()\n .describe(\n 'Event name in \"entity action\" format (e.g., \"page view\", \"product add\")',\n ),\n\n // Event data\n data: PropertiesSchema.describe('Event-specific properties'),\n context: OrderedPropertiesSchema.describe(\n 'Ordered context properties with priorities',\n ),\n globals: PropertiesSchema.describe(\n 'Global properties shared across events',\n ),\n custom: PropertiesSchema.describe(\n 'Custom implementation-specific properties',\n ),\n\n // Related data\n user: UserSchema.describe('User identification and attributes'),\n nested: EntitiesSchema.describe('Related nested entities'),\n consent: ConsentSchema.describe('Consent states at event time'),\n\n // System-generated fields\n id: Identifier.describe('Unique event identifier (timestamp-based)'),\n trigger: RequiredString.describe('Event trigger identifier'),\n entity: RequiredString.describe('Parsed entity from event name'),\n action: RequiredString.describe('Parsed action from event name'),\n timestamp: Timestamp.describe('Unix timestamp in milliseconds since epoch'),\n timing: RequiredNumber.describe('Event processing timing information'),\n group: RequiredString.describe('Event grouping identifier'),\n count: Counter.describe('Event count in session'),\n\n // Version & source tracking\n version: VersionSchema.describe('Walker version information'),\n source: SourceSchema.describe('Event source information'),\n })\n .describe('Complete walkerOS event structure');\n\n/**\n * PartialEvent - Event with all fields optional\n * Used for event creation where not all fields are provided\n */\nexport const PartialEventSchema = EventSchema.partial().describe(\n 'Partial event structure with all fields optional',\n);\n\n/**\n * DeepPartialEvent - Event with all fields optional\n * Used for event updates and patches\n *\n * Note: While the TypeScript type uses DeepPartial<Event> for compile-time validation,\n * the Zod schema uses .partial() which makes top-level fields optional. This is\n * sufficient for runtime validation as deeply nested partial objects are rarely\n * provided (users typically omit entire objects rather than providing partial nested data).\n * Zod 4 deliberately removed .deepPartial() due to internal type complexity issues.\n */\nexport const DeepPartialEventSchema: z.ZodTypeAny =\n EventSchema.partial().describe(\n 'Partial event structure with all top-level fields optional',\n );\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const eventJsonSchema = toJsonSchema(EventSchema, 'Event');\n\nexport const partialEventJsonSchema = toJsonSchema(\n PartialEventSchema,\n 'PartialEvent',\n);\n\nexport const userJsonSchema = toJsonSchema(UserSchema, 'User');\n\nexport const propertiesJsonSchema = toJsonSchema(\n PropertiesSchema,\n 'Properties',\n);\n\nexport const orderedPropertiesJsonSchema = toJsonSchema(\n OrderedPropertiesSchema,\n 'OrderedProperties',\n);\n\nexport const entityJsonSchema = toJsonSchema(EntitySchema, 'Entity');\n\nexport const sourceTypeJsonSchema = toJsonSchema(\n SourceTypeSchema,\n 'SourceType',\n);\n\nexport const consentJsonSchema = toJsonSchema(ConsentSchema, 'Consent');\n","import { z, toJsonSchema } from './validation';\nimport { ConsentSchema } from './walkeros';\n\n/**\n * Mapping System Schemas\n *\n * Mirrors: types/mapping.ts\n * Purpose: Runtime validation and JSON Schema generation for event transformation rules\n *\n * The mapping system allows flexible transformation of events as they flow through\n * the collector to destinations. This includes:\n * - Value extraction and transformation\n * - Conditional logic\n * - Data mapping and restructuring\n * - Array processing (loops)\n * - Consent-based filtering\n *\n * Key Features:\n * - Recursive value definitions (Value → ValueConfig → Value)\n * - Loop vs Set distinction via JSON Schema (minItems/maxItems)\n * - Lazy evaluation for circular dependencies\n * - Function serialization support (functions as strings)\n */\n\n// ========================================\n// Recursive Value Schemas\n// ========================================\n\n// Forward declaration for circular dependency\nlet ValueConfigSchemaLazy: z.ZodTypeAny;\n\n/**\n * Value - Core value type for mapping transformations\n *\n * Can be:\n * - Primitive: string, number, boolean\n * - ValueConfig: Complex transformation object\n * - Array: Multiple values/configs\n *\n * Recursive structure allows nested transformations\n */\nexport const ValueSchema: z.ZodTypeAny = z.lazy(() =>\n z.union([\n z.string().describe('String value or property path (e.g., \"data.id\")'),\n z.number().describe('Numeric value'),\n z.boolean().describe('Boolean value'),\n z.lazy(() => ValueConfigSchemaLazy),\n z.array(ValueSchema).describe('Array of values'),\n ]),\n);\n\n/**\n * Values - Array of Value objects\n * Used for multiple data transformations\n */\nexport const ValuesSchema = z\n .array(ValueSchema)\n .describe('Array of transformation values');\n\n/**\n * Loop - Tuple for array processing\n * Format: [source, transform]\n *\n * IMPORTANT: z.tuple() generates JSON Schema with minItems/maxItems = 2\n * This is how Explorer distinguishes Loop from Set\n *\n * Example: ['nested', { map: { id: 'data.id' } }]\n * Means: Iterate over event.nested array, transform each item\n */\nconst LoopSchema: z.ZodTypeAny = z.lazy(() =>\n z\n .tuple([ValueSchema, ValueSchema])\n .describe(\n 'Loop transformation: [source, transform] tuple for array processing',\n ),\n);\n\n/**\n * Set - Array of values for selection/combination\n * Format: [value1, value2, ...]\n *\n * IMPORTANT: z.array() generates JSON Schema without minItems/maxItems\n * This distinguishes Set from Loop\n *\n * Example: ['data.firstName', ' ', 'data.lastName']\n * Means: Combine multiple values\n */\nconst SetSchema: z.ZodTypeAny = z.lazy(() =>\n z\n .array(ValueSchema)\n .describe('Set: Array of values for selection or combination'),\n);\n\n/**\n * Map - Object mapping for data transformation\n * Format: { outputKey: value, ... }\n *\n * Example: { item_id: 'data.id', item_name: 'data.name' }\n * Means: Transform event data to destination format\n */\nconst MapSchema: z.ZodTypeAny = z.lazy(() =>\n z\n .record(z.string(), ValueSchema)\n .describe('Map: Object mapping keys to transformation values'),\n);\n\n/**\n * ValueConfig - Configuration object for value transformations\n *\n * Supports multiple transformation strategies:\n * - key: Extract property from event (e.g., \"data.id\")\n * - value: Static primitive value\n * - fn: Custom transformation function (as string)\n * - map: Object mapping for structured output\n * - loop: Array iteration and transformation\n * - set: Value combination/selection\n * - consent: Consent-based filtering\n * - condition: Conditional transformation\n * - validate: Value validation\n *\n * At least one property must be present.\n */\nValueConfigSchemaLazy = z\n .object({\n key: z\n .string()\n .optional()\n .describe(\n 'Property path to extract from event (e.g., \"data.id\", \"user.email\")',\n ),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('Static primitive value'),\n fn: z\n .string()\n .optional()\n .describe('Custom transformation function as string (serialized)'),\n map: MapSchema.optional().describe(\n 'Object mapping: transform event data to structured output',\n ),\n loop: LoopSchema.optional().describe(\n 'Loop transformation: [source, transform] for array processing',\n ),\n set: SetSchema.optional().describe(\n 'Set of values: combine or select from multiple values',\n ),\n consent: ConsentSchema.optional().describe(\n 'Required consent states to include this value',\n ),\n condition: z\n .string()\n .optional()\n .describe('Condition function as string: return true to include value'),\n validate: z\n .string()\n .optional()\n .describe('Validation function as string: return true if value is valid'),\n })\n .refine((data) => Object.keys(data).length > 0, {\n message: 'ValueConfig must have at least one property',\n })\n .describe('Value transformation configuration with multiple strategies');\n\n// Export with original name for backward compatibility\nexport const ValueConfigSchema = ValueConfigSchemaLazy;\n\n// Re-export for use in other schemas\nexport { LoopSchema, SetSchema, MapSchema };\n\n// ========================================\n// Policy Schema\n// ========================================\n\n/**\n * Policy - Pre-processing rules\n * Applied before event mapping\n * Maps policy keys to transformation values\n *\n * Example: { 'consent.marketing': true }\n * Means: Only process events with marketing consent\n */\nexport const PolicySchema = z\n .record(z.string(), ValueSchema)\n .describe('Policy rules for event pre-processing (key → value mapping)');\n\n// ========================================\n// Mapping Rule Schemas\n// ========================================\n\n/**\n * Rule - Event-specific mapping configuration\n *\n * Defines how to transform events for a specific entity-action combination\n * Can include:\n * - Batching configuration\n * - Conditional processing\n * - Consent requirements\n * - Custom settings\n * - Data transformation\n * - Event naming\n * - Policy overrides\n */\nexport const RuleSchema = z\n .object({\n batch: z\n .number()\n .optional()\n .describe('Batch size: bundle N events for batch processing'),\n // Note: batchFn and batched are runtime functions, not serializable\n condition: z\n .string()\n .optional()\n .describe('Condition function as string: return true to process event'),\n consent: ConsentSchema.optional().describe(\n 'Required consent states to process this event',\n ),\n settings: z\n .any()\n .optional()\n .describe('Destination-specific settings for this event mapping'),\n data: z\n .union([ValueSchema, ValuesSchema])\n .optional()\n .describe('Data transformation rules for event'),\n ignore: z\n .boolean()\n .optional()\n .describe('Set to true to skip processing this event'),\n name: z\n .string()\n .optional()\n .describe(\n 'Custom event name override (e.g., \"view_item\" for \"product view\")',\n ),\n policy: PolicySchema.optional().describe(\n 'Event-level policy overrides (applied after config-level policy)',\n ),\n })\n .describe('Mapping rule for specific entity-action combination');\n\n/**\n * Rules - Nested mapping rules structure\n * Format: { entity: { action: Rule | Rule[], ... }, ... }\n *\n * Supports:\n * - Specific entity-action mappings\n * - Wildcard patterns (entity: *, action: *)\n * - Multiple rules per entity-action (array)\n *\n * Example:\n * {\n * product: {\n * view: { name: 'view_item' },\n * add: { name: 'add_to_cart' }\n * },\n * page: {\n * '*': { name: 'page_interaction' }\n * }\n * }\n */\nexport const RulesSchema = z\n .record(\n z.string(),\n z.record(z.string(), z.union([RuleSchema, z.array(RuleSchema)])).optional(),\n )\n .describe(\n 'Event mapping rules: entity → action → Rule. Keys match event name split by space. Use \"*\" as wildcard for entity or action. Priority: exact > entity wildcard > action wildcard > global wildcard (*→*).',\n );\n\n/**\n * Config - Shared mapping configuration\n * Used by both Source.Config and Destination.Config\n *\n * Provides:\n * - Consent requirements\n * - Global data transformations\n * - Entity-action mapping rules\n * - Pre-processing policies\n */\nexport const ConfigSchema = z\n .object({\n consent: ConsentSchema.optional().describe(\n 'Required consent states to process any events',\n ),\n data: z\n .union([ValueSchema, ValuesSchema])\n .optional()\n .describe('Global data transformation applied to all events'),\n mapping: RulesSchema.optional().describe(\n 'Entity-action specific mapping rules',\n ),\n policy: PolicySchema.optional().describe(\n 'Pre-processing policy rules applied before mapping',\n ),\n })\n .describe('Shared mapping configuration for sources and destinations');\n\n/**\n * Result - Mapping resolution result\n * Contains the resolved mapping rule and key used\n */\nexport const ResultSchema = z\n .object({\n eventMapping: RuleSchema.optional().describe(\n 'Resolved mapping rule for event',\n ),\n mappingKey: z\n .string()\n .optional()\n .describe('Mapping key used (e.g., \"product.view\")'),\n })\n .describe('Mapping resolution result');\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const valueJsonSchema = toJsonSchema(ValueSchema, 'Value');\n\nexport const valueConfigJsonSchema = toJsonSchema(\n ValueConfigSchema,\n 'ValueConfig',\n);\n\nexport const loopJsonSchema = toJsonSchema(LoopSchema, 'Loop');\n\nexport const setJsonSchema = toJsonSchema(SetSchema, 'Set');\n\nexport const mapJsonSchema = toJsonSchema(MapSchema, 'Map');\n\nexport const policyJsonSchema = toJsonSchema(PolicySchema, 'Policy');\n\nexport const ruleJsonSchema = toJsonSchema(RuleSchema, 'Rule');\n\nexport const rulesJsonSchema = toJsonSchema(RulesSchema, 'Rules');\n\nexport const configJsonSchema = toJsonSchema(ConfigSchema, 'MappingConfig');\n","import { z, toJsonSchema } from './validation';\nimport { ConsentSchema, EventSchema } from './walkeros';\nimport {\n ValueSchema,\n ValuesSchema,\n RuleSchema,\n RulesSchema,\n PolicySchema,\n} from './mapping';\nimport { Identifier } from './primitives';\nimport { ErrorHandlerSchema, LogHandlerSchema } from './utilities';\n\n/**\n * Destination Schemas\n *\n * Mirrors: types/destination.ts\n * Purpose: Runtime validation and JSON Schema generation for destination configurations\n *\n * Destinations are the endpoints where processed events are sent (analytics tools,\n * marketing platforms, data warehouses, etc.). This file defines schemas for:\n * - Destination configuration\n * - Type bundles for generic constraints\n * - Push contexts\n * - Batching structures\n */\n\n// ========================================\n// Configuration Schemas\n// ========================================\n\n/**\n * Config - Destination configuration\n *\n * Defines how a destination processes events:\n * - Consent requirements\n * - Settings (destination-specific)\n * - Data transformations\n * - Environment dependencies\n * - Initialization options\n * - Mapping rules\n * - Processing policies\n * - Queueing behavior\n * - Logging verbosity\n * - Error/log handlers\n *\n * Generic note: settings, env, and mapping can have destination-specific types\n * but for schema validation we use z.unknown() to allow flexibility\n */\nexport const ConfigSchema = z\n .object({\n consent: ConsentSchema.optional().describe(\n 'Required consent states to send events to this destination',\n ),\n settings: z\n .any()\n .describe('Implementation-specific configuration')\n .optional(),\n data: z\n .union([ValueSchema, ValuesSchema])\n .optional()\n .describe(\n 'Global data transformation applied to all events for this destination',\n ),\n env: z\n .any()\n .describe('Environment dependencies (platform-specific)')\n .optional(),\n id: Identifier.describe(\n 'Destination instance identifier (defaults to destination key)',\n ).optional(),\n init: z.boolean().describe('Whether to initialize immediately').optional(),\n loadScript: z\n .boolean()\n .describe('Whether to load external script (for web destinations)')\n .optional(),\n mapping: RulesSchema.optional().describe(\n 'Entity-action specific mapping rules for this destination',\n ),\n policy: PolicySchema.optional().describe(\n 'Pre-processing policy rules applied before event mapping',\n ),\n queue: z\n .boolean()\n .describe('Whether to queue events when consent is not granted')\n .optional(),\n require: z\n .array(z.string())\n .optional()\n .describe(\n 'Defer destination initialization until these collector events fire (e.g., [\"consent\"])',\n ),\n logger: z\n .object({\n level: z\n .union([z.number(), z.enum(['ERROR', 'WARN', 'INFO', 'DEBUG'])])\n .optional()\n .describe('Minimum log level (default: ERROR)'),\n handler: z.any().optional().describe('Custom log handler function'),\n })\n .optional()\n .describe(\n 'Logger configuration (level, handler) to override the collector defaults',\n ),\n // Handler functions\n onError: ErrorHandlerSchema.optional(),\n onLog: LogHandlerSchema.optional(),\n })\n .describe('Destination configuration');\n\n/**\n * PartialConfig - Config with all fields optional\n * Used for config updates and overrides\n *\n * Note: All fields in ConfigSchema are already optional (.optional() on each field).\n * Using .partial() ensures the schema itself makes all fields optional at the type level.\n */\nexport const PartialConfigSchema = ConfigSchema.partial().describe(\n 'Partial destination configuration with all fields optional',\n);\n\n/**\n * Policy - Processing policy rules\n * Maps policy keys to transformation values\n * Applied before event mapping\n */\nexport const DestinationPolicySchema = PolicySchema.describe(\n 'Destination policy rules for event pre-processing',\n);\n\n// ========================================\n// Context Schemas\n// ========================================\n\n/**\n * Context - Base destination context\n * Passed to init and push functions\n * Contains collector instance, config, data, and environment\n *\n * Note: collector is runtime instance, not easily serializable\n */\nexport const ContextSchema = z\n .object({\n collector: z.unknown().describe('Collector instance (runtime object)'),\n config: ConfigSchema.describe('Destination configuration'),\n data: z\n .union([\n z.unknown(), // WalkerOS.Property\n z.array(z.unknown()),\n ])\n .optional()\n .describe('Transformed event data'),\n env: z.unknown().describe('Environment dependencies'),\n })\n .describe('Destination context for init and push functions');\n\n/**\n * PushContext - Context for push function\n * Extends Context with mapping rule information\n */\nexport const PushContextSchema = ContextSchema.extend({\n mapping: RuleSchema.optional().describe(\n 'Resolved mapping rule for this specific event',\n ),\n}).describe('Push context with event-specific mapping');\n\n/**\n * PushBatchContext - Context for pushBatch function\n * Same as PushContext but for batch processing\n */\nexport const PushBatchContextSchema = PushContextSchema.describe(\n 'Batch push context with event-specific mapping',\n);\n\n// ========================================\n// Batch Processing Schemas\n// ========================================\n\n/**\n * PushEvent - Single event with mapping in a batch\n */\nexport const PushEventSchema = z\n .object({\n event: EventSchema.describe('The event to process'),\n mapping: RuleSchema.optional().describe('Mapping rule for this event'),\n })\n .describe('Event with optional mapping for batch processing');\n\n/**\n * PushEvents - Array of PushEvent\n */\nexport const PushEventsSchema = z\n .array(PushEventSchema)\n .describe('Array of events with mappings');\n\n/**\n * Batch - Batched events for processing\n * Groups events by mapping key for efficient batch sends\n */\nexport const BatchSchema = z\n .object({\n key: z\n .string()\n .describe('Batch key (usually mapping key like \"product.view\")'),\n events: z.array(EventSchema).describe('Array of events in batch'),\n data: z\n .array(\n z\n .union([\n z.unknown(), // WalkerOS.Property\n z.array(z.unknown()),\n ])\n .optional(),\n )\n .describe('Transformed data for each event'),\n mapping: RuleSchema.optional().describe('Shared mapping rule for batch'),\n })\n .describe('Batch of events grouped by mapping key');\n\n/**\n * Data - Transformed event data types\n * Can be single property, undefined, or array of properties\n */\nexport const DataSchema = z\n .union([\n z.unknown(), // WalkerOS.Property\n z.array(z.unknown()),\n ])\n .optional()\n .describe('Transformed event data (Property, undefined, or array)');\n\n// ========================================\n// Instance Schemas\n// ========================================\n\n/**\n * Instance - Destination instance (runtime object)\n *\n * Note: This schema is primarily for documentation\n * Runtime functions (init, push, pushBatch) cannot be validated\n * Use z.unknown() for function fields\n */\nexport const InstanceSchema = z\n .object({\n config: ConfigSchema.describe('Destination configuration'),\n queue: z\n .array(EventSchema)\n .optional()\n .describe('Queued events awaiting consent'),\n dlq: z\n .array(z.tuple([EventSchema, z.unknown()]))\n .optional()\n .describe('Dead letter queue (failed events with errors)'),\n type: z.string().optional().describe('Destination type identifier'),\n env: z.unknown().optional().describe('Environment dependencies'),\n // Functions - not validated, use z.unknown()\n init: z.unknown().optional().describe('Initialization function'),\n push: z.unknown().describe('Push function for single events'),\n pushBatch: z.unknown().optional().describe('Batch push function'),\n on: z.unknown().optional().describe('Event lifecycle hook function'),\n })\n .describe('Destination instance (runtime object with functions)');\n\n/**\n * Init - Initialization config\n * Contains destination code and configuration\n */\nexport const InitSchema = z\n .object({\n code: InstanceSchema.describe('Destination instance with implementation'),\n config: PartialConfigSchema.optional().describe(\n 'Partial configuration overrides',\n ),\n env: z.unknown().optional().describe('Partial environment overrides'),\n })\n .describe('Destination initialization configuration');\n\n/**\n * InitDestinations - Map of destination IDs to Init configs\n */\nexport const InitDestinationsSchema = z\n .record(z.string(), InitSchema)\n .describe('Map of destination IDs to initialization configurations');\n\n/**\n * Destinations - Map of destination IDs to instances\n */\nexport const DestinationsSchema = z\n .record(z.string(), InstanceSchema)\n .describe('Map of destination IDs to runtime instances');\n\n// ========================================\n// Result Schemas\n// ========================================\n\n/**\n * Ref - Destination reference\n * Contains destination type and optional response data or error\n */\nexport const RefSchema = z\n .object({\n type: z.string().describe('Destination type (\"gtag\", \"meta\", \"bigquery\")'),\n data: z.unknown().optional().describe('Response from push()'),\n error: z.unknown().optional().describe('Error if failed'),\n })\n .describe('Destination reference with type and response data');\n\n/**\n * Push - Push operation result\n */\nexport const PushResultSchema = z\n .object({\n queue: z\n .array(EventSchema)\n .optional()\n .describe('Events queued (awaiting consent)'),\n error: z.unknown().optional().describe('Error if push failed'),\n })\n .describe('Push operation result');\n\n/**\n * Result - Overall processing result\n * Note: This type has been removed from types/destination.ts\n * Results are now part of Elb.PushResult with Record<string, Ref> structure\n */\nexport const ResultSchema = z\n .object({\n ok: z.boolean().describe('True if nothing failed'),\n event: z.unknown().optional().describe('The processed event'),\n done: z\n .record(z.string(), RefSchema)\n .optional()\n .describe('Destinations that processed successfully'),\n queued: z\n .record(z.string(), RefSchema)\n .optional()\n .describe('Destinations that queued events'),\n failed: z\n .record(z.string(), RefSchema)\n .optional()\n .describe('Destinations that failed to process'),\n })\n .describe('Push result with destination outcomes');\n\n/**\n * DLQ - Dead Letter Queue\n * Array of failed events with their errors\n */\nexport const DLQSchema = z\n .array(z.tuple([EventSchema, z.unknown()]))\n .describe('Dead letter queue: [(event, error), ...]');\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const configJsonSchema = toJsonSchema(ConfigSchema, 'DestinationConfig');\n\nexport const partialConfigJsonSchema = toJsonSchema(\n PartialConfigSchema,\n 'PartialDestinationConfig',\n);\n\nexport const contextJsonSchema = toJsonSchema(\n ContextSchema,\n 'DestinationContext',\n);\n\nexport const pushContextJsonSchema = toJsonSchema(\n PushContextSchema,\n 'PushContext',\n);\n\nexport const batchJsonSchema = toJsonSchema(BatchSchema, 'Batch');\n\nexport const instanceJsonSchema = toJsonSchema(\n InstanceSchema,\n 'DestinationInstance',\n);\n\nexport const resultJsonSchema = toJsonSchema(ResultSchema, 'DestinationResult');\n","import { z, toJsonSchema } from './validation';\nimport {\n ConsentSchema,\n UserSchema,\n PropertiesSchema,\n EventSchema,\n} from './walkeros';\nimport { ConfigSchema as MappingConfigSchema } from './mapping';\nimport {\n RequiredBoolean,\n RequiredNumber,\n Identifier,\n Timestamp,\n Counter,\n TaggingVersion,\n} from './primitives';\nimport { ErrorHandlerSchema, LogHandlerSchema } from './utilities';\n\n/**\n * Collector Schemas\n *\n * Mirrors: types/collector.ts\n * Purpose: Runtime validation and JSON Schema generation for collector configurations\n *\n * The collector is the central event processing engine in walkerOS:\n * - Receives events from sources\n * - Processes events with consent and context\n * - Routes events to destinations\n * - Manages session state and globals\n * - Handles lifecycle hooks\n *\n * This file defines schemas for collector configuration, commands, and state management.\n */\n\n// ========================================\n// Command Type Schema\n// ========================================\n\n/**\n * CommandType - Walker command identifiers\n *\n * Standard commands:\n * - action: TODO - need documentation\n * - config: Update collector configuration\n * - consent: Update consent state\n * - context: TODO - need documentation\n * - destination: Add/update destination\n * - elb: TODO - need documentation\n * - globals: Update global properties\n * - hook: Register lifecycle hook\n * - init: Initialize collector\n * - link: TODO - need documentation\n * - run: Start/restart collector with state\n * - user: Update user data\n * - walker: TODO - need documentation\n *\n * Extensible: allows custom command strings\n */\nexport const CommandTypeSchema = z\n .union([\n z.enum([\n 'action',\n 'config',\n 'consent',\n 'context',\n 'destination',\n 'elb',\n 'globals',\n 'hook',\n 'init',\n 'link',\n 'run',\n 'user',\n 'walker',\n ]),\n z.string(), // Allow custom commands\n ])\n .describe(\n 'Collector command type: standard commands or custom string for extensions',\n );\n\n// ========================================\n// Configuration Schemas\n// ========================================\n\n/**\n * Config - Core collector configuration\n *\n * Controls collector behavior:\n * - run: Auto-run on initialization\n * - tagging: Version number for event tagging\n * - globalsStatic: Static globals (persist across runs)\n * - sessionStatic: Static session data (persist across runs)\n * - verbose: Enable verbose logging\n * - onError: Error handler\n * - onLog: Log handler\n */\nexport const ConfigSchema = z\n .object({\n run: z\n .boolean()\n .describe('Whether to run collector automatically on initialization')\n .optional(),\n tagging: TaggingVersion,\n globalsStatic: PropertiesSchema.describe(\n 'Static global properties that persist across collector runs',\n ),\n sessionStatic: z\n .record(z.string(), z.unknown())\n .describe('Static session data that persists across collector runs'),\n verbose: z.boolean().describe('Enable verbose logging for debugging'),\n // Function handlers\n onError: ErrorHandlerSchema.optional(),\n onLog: LogHandlerSchema.optional(),\n })\n .describe('Core collector configuration');\n\n/**\n * SessionData - Session state management\n *\n * Tracks session-level information:\n * - IDs and lifecycle\n * - Storage state\n * - Marketing tracking\n * - Timestamps\n * - Counters\n *\n * Extends Properties to allow custom session data\n */\nexport const SessionDataSchema = PropertiesSchema.and(\n z.object({\n isStart: z.boolean().describe('Whether this is a new session start'),\n storage: z.boolean().describe('Whether storage is available'),\n id: Identifier.describe('Session identifier').optional(),\n start: Timestamp.describe('Session start timestamp').optional(),\n marketing: z\n .literal(true)\n .optional()\n .describe('Marketing attribution flag'),\n updated: Timestamp.describe('Last update timestamp').optional(),\n isNew: z.boolean().describe('Whether this is a new session').optional(),\n device: Identifier.describe('Device identifier').optional(),\n count: Counter.describe('Event count in session').optional(),\n runs: Counter.describe('Number of runs').optional(),\n }),\n).describe('Session state and tracking data');\n\n/**\n * InitConfig - Initialization configuration\n *\n * Extends Config with initial state:\n * - Initial consent\n * - Initial user data\n * - Initial globals\n * - Source configurations\n * - Destination configurations\n * - Initial custom properties\n */\nexport const InitConfigSchema = ConfigSchema.partial()\n .extend({\n consent: ConsentSchema.optional().describe('Initial consent state'),\n user: UserSchema.optional().describe('Initial user data'),\n globals: PropertiesSchema.optional().describe('Initial global properties'),\n // Sources and destinations are complex runtime objects\n sources: z.unknown().optional().describe('Source configurations'),\n destinations: z.unknown().optional().describe('Destination configurations'),\n custom: PropertiesSchema.optional().describe(\n 'Initial custom implementation-specific properties',\n ),\n })\n .describe('Collector initialization configuration with initial state');\n\n// ========================================\n// Context Schemas\n// ========================================\n\n/**\n * PushContext - Context for collector.push\n *\n * Provides source-level mapping configuration\n * Applied before destination-specific mappings\n */\nexport const PushContextSchema = z\n .object({\n mapping: MappingConfigSchema.optional().describe(\n 'Source-level mapping configuration',\n ),\n })\n .describe('Push context with optional source mapping');\n\n// ========================================\n// Collection Schemas\n// ========================================\n\n/**\n * Sources - Map of source IDs to instances\n */\nexport const SourcesSchema = z\n .record(z.string(), z.unknown())\n .describe('Map of source IDs to source instances');\n\n/**\n * Destinations - Map of destination IDs to instances\n */\nexport const DestinationsSchema = z\n .record(z.string(), z.unknown())\n .describe('Map of destination IDs to destination instances');\n\n// ========================================\n// Instance Schema\n// ========================================\n\n/**\n * Instance - Collector instance (runtime object)\n *\n * The main collector interface with all state and methods\n *\n * State:\n * - config: Current configuration\n * - consent: Current consent state\n * - user: Current user data\n * - globals: Current global properties\n * - custom: Custom properties\n * - session: Session state\n * - sources: Registered sources\n * - destinations: Registered destinations\n * - hooks: Lifecycle hooks\n * - on: Event lifecycle config\n * - queue: Queued events\n *\n * Flags:\n * - allowed: Processing allowed\n * - count: Event count\n * - round: Collector run count\n * - timing: Processing timing\n * - group: Event grouping ID\n *\n * Methods (not validated):\n * - push: Process events\n * - command: Execute commands\n */\nexport const InstanceSchema = z\n .object({\n // Methods (functions - not validated)\n push: z.unknown().describe('Push function for processing events'),\n command: z.unknown().describe('Command function for walker commands'),\n // State\n allowed: z.boolean().describe('Whether event processing is allowed'),\n config: ConfigSchema.describe('Current collector configuration'),\n consent: ConsentSchema.describe('Current consent state'),\n count: z.number().describe('Event count (increments with each event)'),\n custom: PropertiesSchema.describe(\n 'Custom implementation-specific properties',\n ),\n sources: SourcesSchema.describe('Registered source instances'),\n destinations: DestinationsSchema.describe(\n 'Registered destination instances',\n ),\n globals: PropertiesSchema.describe('Current global properties'),\n group: z.string().describe('Event grouping identifier'),\n hooks: z.unknown().describe('Lifecycle hook functions'),\n on: z.unknown().describe('Event lifecycle configuration'),\n queue: z.array(EventSchema).describe('Queued events awaiting processing'),\n round: z\n .number()\n .describe('Collector run count (increments with each run)'),\n session: z.union([SessionDataSchema]).describe('Current session state'),\n timing: z.number().describe('Event processing timing information'),\n user: UserSchema.describe('Current user data'),\n version: z.string().describe('Walker implementation version'),\n })\n .describe('Collector instance with state and methods');\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const commandTypeJsonSchema = toJsonSchema(\n CommandTypeSchema,\n 'CommandType',\n);\n\nexport const configJsonSchema = toJsonSchema(ConfigSchema, 'CollectorConfig');\n\nexport const sessionDataJsonSchema = toJsonSchema(\n SessionDataSchema,\n 'SessionData',\n);\n\nexport const initConfigJsonSchema = toJsonSchema(\n InitConfigSchema,\n 'InitConfig',\n);\n\nexport const pushContextJsonSchema = toJsonSchema(\n PushContextSchema,\n 'CollectorPushContext',\n);\n\nexport const instanceJsonSchema = toJsonSchema(\n InstanceSchema,\n 'CollectorInstance',\n);\n","import { z, toJsonSchema } from './validation';\nimport {\n ConfigSchema as MappingConfigSchema,\n ValueSchema,\n ValuesSchema,\n} from './mapping';\nimport { Identifier } from './primitives';\nimport { ErrorHandlerSchema } from './utilities';\n\n/**\n * Source Schemas\n *\n * Mirrors: types/source.ts\n * Purpose: Runtime validation and JSON Schema generation for source configurations\n *\n * Sources are the entry points where events enter walkerOS:\n * - Browser sources (DOM events, dataLayer)\n * - Server sources (HTTP handlers, cloud functions)\n * - App sources (mobile, desktop)\n *\n * Sources are platform-agnostic through dependency injection via BaseEnv.\n * All platform-specific dependencies (DOM, HTTP, etc.) are provided through\n * the env object, making sources testable and portable.\n *\n * Key concept: Source.push IS the handler - no wrappers needed\n * Example: http('handler', source.push) for direct deployment\n */\n\n// ========================================\n// Environment Schema\n// ========================================\n\n/**\n * BaseEnv - Base environment interface for dependency injection\n *\n * Sources receive all dependencies through this environment object:\n * - push: Collector push function\n * - command: Collector command function\n * - sources: Other registered sources\n * - elb: Public API function (alias for collector.push)\n *\n * Platform-specific sources extend this with their requirements\n * (e.g., window, document, fetch, req, res)\n *\n * This makes sources:\n * - Platform-agnostic (no direct dependencies)\n * - Testable (mock env for tests)\n * - Composable (share env between sources)\n */\nexport const BaseEnvSchema = z\n .object({\n push: z.unknown().describe('Collector push function'),\n command: z.unknown().describe('Collector command function'),\n sources: z\n .unknown()\n .optional()\n .describe('Map of registered source instances'),\n elb: z.unknown().describe('Public API function (alias for collector.push)'),\n })\n .catchall(z.unknown())\n .describe(\n 'Base environment for dependency injection - platform-specific sources extend this',\n );\n\n// ========================================\n// Configuration Schema\n// ========================================\n\n/**\n * Config - Source configuration\n *\n * Extends Mapping.Config with source-specific options:\n * - consent: Required consent to process events\n * - data: Global data transformations\n * - mapping: Entity-action mapping rules\n * - policy: Pre-processing policies\n * - settings: Source-specific settings\n * - env: Environment dependencies\n * - id: Source identifier\n * - onError: Error handler\n * - primary: Primary source flag (only one can be primary)\n *\n * Generic note: settings, env, and mapping can have source-specific types\n */\nexport const ConfigSchema = MappingConfigSchema.extend({\n settings: z\n .any()\n .describe('Implementation-specific configuration')\n .optional(),\n env: BaseEnvSchema.optional().describe(\n 'Environment dependencies (platform-specific)',\n ),\n id: Identifier.describe(\n 'Source identifier (defaults to source key)',\n ).optional(),\n onError: ErrorHandlerSchema.optional(),\n primary: z\n .boolean()\n .describe('Mark as primary (only one can be primary)')\n .optional(),\n require: z\n .array(z.string())\n .optional()\n .describe(\n 'Defer source initialization until these collector events fire (e.g., [\"consent\"])',\n ),\n logger: z\n .object({\n level: z\n .union([z.number(), z.enum(['ERROR', 'WARN', 'INFO', 'DEBUG'])])\n .optional()\n .describe('Minimum log level (default: ERROR)'),\n handler: z.any().optional().describe('Custom log handler function'),\n })\n .optional()\n .describe(\n 'Logger configuration (level, handler) to override the collector defaults',\n ),\n ingest: z\n .union([ValueSchema, ValuesSchema])\n .optional()\n .describe(\n 'Ingest metadata extraction mapping. Extracts values from raw request objects (Express req, Lambda event) using mapping syntax.',\n ),\n}).describe('Source configuration with mapping and environment');\n\n/**\n * PartialConfig - Config with all fields optional\n * Used for config updates and overrides\n *\n * Note: ConfigSchema extends MappingConfigSchema with mostly optional fields.\n * Using .partial() ensures all fields are optional for config updates.\n */\nexport const PartialConfigSchema = ConfigSchema.partial().describe(\n 'Partial source configuration with all fields optional',\n);\n\n// ========================================\n// Instance Schema\n// ========================================\n\n/**\n * Instance - Source instance (runtime object)\n *\n * Contains:\n * - type: Source type identifier\n * - config: Current configuration\n * - push: Push function (THE HANDLER)\n * - destroy: Cleanup function\n * - on: Lifecycle hook function\n *\n * Key concept: push IS the handler\n * The push function signature is flexible to support different platforms:\n * - Browser: push(event, data) => Promise<void>\n * - HTTP: push(req, res) => Promise<void>\n * - Cloud: push(event, context) => Promise<void>\n *\n * This flexibility allows direct deployment without wrappers:\n * - http.createServer(source.push)\n * - functions.https.onRequest(source.push)\n * - addEventListener('click', source.push)\n */\nexport const InstanceSchema = z\n .object({\n type: z\n .string()\n .describe('Source type identifier (e.g., \"browser\", \"dataLayer\")'),\n config: ConfigSchema.describe('Current source configuration'),\n // Push function - flexible signature, not validated\n push: z\n .any()\n .describe(\n 'Push function - THE HANDLER (flexible signature for platform compatibility)',\n ),\n // Optional lifecycle methods\n destroy: z\n .any()\n .optional()\n .describe('Cleanup function called when source is removed'),\n on: z\n .unknown()\n .optional()\n .describe('Lifecycle hook function for event types'),\n })\n .describe('Source instance with push handler and lifecycle methods');\n\n// ========================================\n// Initialization Schemas\n// ========================================\n\n/**\n * Init - Source initialization function\n *\n * Factory function that creates a source instance:\n * (config, env) => Instance | Promise<Instance>\n *\n * Receives:\n * - config: Partial configuration\n * - env: Environment dependencies\n *\n * Returns:\n * - Source instance with push function\n *\n * The init function sets up the source (e.g., attach DOM listeners,\n * start HTTP server, subscribe to events) and returns the instance.\n */\nexport const InitSchema = z\n .any()\n .describe(\n 'Source initialization function: (config, env) => Instance | Promise<Instance>',\n );\n\n/**\n * InitSource - Initialization configuration\n *\n * Contains:\n * - code: Init function\n * - config: Partial config overrides\n * - env: Partial env overrides\n * - primary: Primary source flag\n */\nexport const InitSourceSchema = z\n .object({\n code: InitSchema.describe('Source initialization function'),\n config: PartialConfigSchema.optional().describe(\n 'Partial configuration overrides',\n ),\n env: BaseEnvSchema.partial()\n .optional()\n .describe('Partial environment overrides'),\n primary: z\n .boolean()\n .optional()\n .describe('Mark as primary source (only one can be primary)'),\n })\n .describe('Source initialization configuration');\n\n/**\n * InitSources - Map of source IDs to init configs\n */\nexport const InitSourcesSchema = z\n .record(z.string(), InitSourceSchema)\n .describe('Map of source IDs to initialization configurations');\n\n// ========================================\n// JSON Schema Exports (for Explorer/RJSF/MCP)\n// ========================================\n\nexport const baseEnvJsonSchema = toJsonSchema(BaseEnvSchema, 'SourceBaseEnv');\n\nexport const configJsonSchema = toJsonSchema(ConfigSchema, 'SourceConfig');\n\nexport const partialConfigJsonSchema = toJsonSchema(\n PartialConfigSchema,\n 'PartialSourceConfig',\n);\n\nexport const instanceJsonSchema = toJsonSchema(\n InstanceSchema,\n 'SourceInstance',\n);\n\nexport const initSourceJsonSchema = toJsonSchema(\n InitSourceSchema,\n 'InitSource',\n);\n\nexport const initSourcesJsonSchema = toJsonSchema(\n InitSourcesSchema,\n 'InitSources',\n);\n","/**\n * Flow Configuration System - Zod Schemas\n *\n * Mirrors: types/flow.ts\n * Purpose: Runtime validation and JSON Schema generation for Flow configurations\n *\n * The Flow system provides unified configuration across all walkerOS flows.\n * These schemas enable:\n * - Runtime validation of config files\n * - Clear error messages for configuration issues\n * - JSON Schema generation for IDE support\n * - Type-safe parsing with Zod\n *\n * SCHEMA SYNC: Run `npx tsx scripts/generate-flow-schema.ts` from the repo root\n * to regenerate website/static/schema/flow/v1.json and v2.json.\n *\n * @packageDocumentation\n */\n\nimport { z, toJsonSchema } from './validation';\n\n// ========================================\n// Primitive Type Schemas\n// ========================================\n\n/**\n * Primitive value schema for variables.\n *\n * @remarks\n * Variables can be strings, numbers, or booleans.\n * Used in Setup.variables and Config.env.\n */\nexport const PrimitiveSchema = z\n .union([z.string(), z.number(), z.boolean()])\n .describe('Primitive value: string, number, or boolean');\n\n// ========================================\n// Shared Type Schemas\n// ========================================\n\n/**\n * Variables schema for interpolation.\n */\nexport const VariablesSchema = z\n .record(z.string(), PrimitiveSchema)\n .describe('Variables for interpolation');\n\n/**\n * Definitions schema for reusable configurations.\n */\nexport const DefinitionsSchema = z\n .record(z.string(), z.unknown())\n .describe('Reusable configuration definitions');\n\n/**\n * Packages schema for build configuration.\n */\nconst npmPackageNamePattern =\n /^(@[a-z0-9\\-~][a-z0-9\\-._~]*\\/)?[a-z0-9\\-~][a-z0-9\\-._~]*$/;\n\nexport const PackagesSchema = z\n .record(\n z.string().regex(npmPackageNamePattern, 'Invalid npm package name'),\n z.object({\n version: z.string().optional(),\n imports: z.array(z.string()).optional(),\n path: z.string().optional(), // Local path (takes precedence over version)\n }),\n )\n .describe('NPM packages to bundle');\n\n// ========================================\n// Platform Configuration Schemas\n// ========================================\n\n/**\n * Web platform configuration schema.\n */\nexport const WebSchema = z\n .object({\n windowCollector: z\n .string()\n .default('collector')\n .optional()\n .describe(\n 'Window property name for the collector instance (default: \"collector\")',\n ),\n windowElb: z\n .string()\n .default('elb')\n .optional()\n .describe(\n 'Window property name for the elb command queue (default: \"elb\")',\n ),\n })\n .describe('Web platform configuration');\n\n/**\n * Server platform configuration schema.\n */\nexport const ServerSchema = z\n .object({})\n .passthrough()\n .describe('Server platform configuration (reserved for future options)');\n\n// ========================================\n// Inline Code Schema\n// ========================================\n\n/**\n * Inline code schema for embedding JavaScript functions in JSON configs.\n *\n * @remarks\n * Enables custom sources, transformers, and destinations without npm packages.\n * The `push` function is required; `type` and `init` are optional.\n *\n * @example\n * ```json\n * {\n * \"code\": {\n * \"type\": \"enricher\",\n * \"push\": \"$code:(event) => ({ ...event, data: { ...event.data, enriched: true } })\"\n * }\n * }\n * ```\n */\nexport const InlineCodeSchema = z\n .object({\n push: z\n .string()\n .min(1, 'Push function cannot be empty')\n .describe(\n 'JavaScript function for processing events. Must start with \"$code:\" prefix. Example: \"$code:(event) => { console.log(event); }\"',\n ),\n type: z\n .string()\n .optional()\n .describe('Optional type identifier for the inline instance'),\n init: z\n .string()\n .optional()\n .describe(\n 'Optional initialization function. Use $code: prefix for inline JavaScript.',\n ),\n })\n .describe('Inline code for custom sources/transformers/destinations');\n\n// ========================================\n// Step Example Schemas\n// ========================================\n\n/**\n * Step example schema — a named { in, out } pair.\n */\nexport const StepExampleSchema = z\n .object({\n description: z.string().optional().describe('Human-readable description'),\n in: z.unknown().optional().describe('Input to the step'),\n trigger: z\n .object({\n type: z\n .string()\n .optional()\n .describe('Trigger mechanism (e.g., click, POST, load)'),\n options: z.unknown().optional().describe('Mechanism-specific options'),\n })\n .optional()\n .describe('Source trigger metadata'),\n mapping: z.unknown().optional().describe('Mapping configuration'),\n out: z.unknown().optional().describe('Expected output from the step'),\n })\n .describe('Named example with input/output pair');\n\n/**\n * Step examples record — keyed by scenario name.\n */\nexport const StepExamplesSchema = z\n .record(z.string(), StepExampleSchema)\n .describe('Named step examples for testing and documentation');\n\n// ========================================\n// Source Reference Schema\n// ========================================\n\n/**\n * Source reference schema.\n *\n * @remarks\n * Defines how to reference and configure a source package.\n * Sources capture events from various origins (browser, HTTP, etc.).\n * Either `package` (npm package) or `code` (inline object) must be provided, but not both.\n */\nexport const SourceReferenceSchema = z\n .object({\n package: z\n .string()\n .min(1, 'Package name cannot be empty')\n .optional()\n .describe(\n 'Package specifier with optional version (e.g., \"@walkeros/web-source-browser@2.0.0\")',\n ),\n code: z\n .union([z.string(), InlineCodeSchema])\n .optional()\n .describe(\n 'Either a named export string (e.g., \"sourceExpress\") or an inline code object with push function',\n ),\n config: z\n .unknown()\n .optional()\n .describe('Source-specific configuration object'),\n env: z.unknown().optional().describe('Source environment configuration'),\n primary: z\n .boolean()\n .optional()\n .describe(\n 'Mark as primary source (provides main elb). Only one source should be primary.',\n ),\n variables: VariablesSchema.optional().describe(\n 'Source-level variables (highest priority in cascade)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Source-level definitions (highest priority in cascade)',\n ),\n next: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Pre-collector transformer chain. Name of the first transformer to run after this source captures an event. If omitted, events go directly to the collector. Can be an array for explicit chain control.',\n ),\n examples: StepExamplesSchema.optional().describe(\n 'Named step examples for testing and documentation (stripped during bundling)',\n ),\n })\n .describe('Source package reference with configuration');\n\n// ========================================\n// Transformer Reference Schema\n// ========================================\n\n/**\n * Transformer reference schema.\n *\n * @remarks\n * Defines how to reference and configure a transformer package.\n * Transformers transform events in the pipeline between sources and destinations.\n */\nexport const TransformerReferenceSchema = z\n .object({\n package: z\n .string()\n .min(1, 'Package name cannot be empty')\n .optional()\n .describe(\n 'Package specifier with optional version (e.g., \"@walkeros/transformer-enricher@1.0.0\")',\n ),\n code: z\n .union([z.string(), InlineCodeSchema])\n .optional()\n .describe(\n 'Either a named export string (e.g., \"transformerEnricher\") or an inline code object with push function',\n ),\n config: z\n .unknown()\n .optional()\n .describe('Transformer-specific configuration object'),\n env: z\n .unknown()\n .optional()\n .describe('Transformer environment configuration'),\n next: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Next transformer in chain. If omitted: pre-collector routes to collector, post-collector routes to destination.',\n ),\n variables: VariablesSchema.optional().describe(\n 'Transformer-level variables (highest priority in cascade)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Transformer-level definitions (highest priority in cascade)',\n ),\n examples: StepExamplesSchema.optional().describe(\n 'Named step examples for testing and documentation (stripped during bundling)',\n ),\n })\n .describe('Transformer package reference with configuration');\n\n// ========================================\n// Destination Reference Schema\n// ========================================\n\n/**\n * Destination reference schema.\n *\n * @remarks\n * Defines how to reference and configure a destination package.\n * Destinations send processed events to external services.\n */\nexport const DestinationReferenceSchema = z\n .object({\n package: z\n .string()\n .min(1, 'Package name cannot be empty')\n .optional()\n .describe(\n 'Package specifier with optional version (e.g., \"@walkeros/web-destination-gtag@2.0.0\")',\n ),\n code: z\n .union([z.string(), InlineCodeSchema])\n .optional()\n .describe(\n 'Either a named export string (e.g., \"destinationAnalytics\") or an inline code object with push function',\n ),\n config: z\n .unknown()\n .optional()\n .describe('Destination-specific configuration object'),\n env: z\n .unknown()\n .optional()\n .describe('Destination environment configuration'),\n variables: VariablesSchema.optional().describe(\n 'Destination-level variables (highest priority in cascade)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Destination-level definitions (highest priority in cascade)',\n ),\n before: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Post-collector transformer chain. Name of the first transformer to run before sending events to this destination. If omitted, events come directly from the collector. Can be an array for explicit chain control.',\n ),\n examples: StepExamplesSchema.optional().describe(\n 'Named step examples for testing and documentation (stripped during bundling)',\n ),\n })\n .describe('Destination package reference with configuration');\n\n/**\n * Store package reference.\n *\n * @remarks\n * Stores are passive key-value infrastructure — no chain properties (next/before).\n * Consumed by other components via `$store:storeId` env wiring.\n */\nexport const StoreReferenceSchema = z\n .object({\n package: z\n .string()\n .min(1, 'Package name cannot be empty')\n .optional()\n .describe('Store package specifier with optional version'),\n code: z\n .union([z.string(), InlineCodeSchema])\n .optional()\n .describe('Named export string or inline code definition'),\n config: z\n .unknown()\n .optional()\n .describe('Store-specific configuration object'),\n env: z.unknown().optional().describe('Store environment configuration'),\n variables: VariablesSchema.optional().describe(\n 'Store-level variables (highest priority in cascade)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Store-level definitions (highest priority in cascade)',\n ),\n examples: StepExamplesSchema.optional().describe(\n 'Named step examples for testing and documentation (stripped during bundling)',\n ),\n })\n .describe('Store package reference with configuration');\n\n// ========================================\n// Contract Schemas\n// ========================================\n\n/**\n * Contract schema entry — a JSON Schema object.\n * Passthrough to allow any valid JSON Schema keywords.\n */\nexport const ContractSchemaEntry = z\n .record(z.string(), z.unknown())\n .describe(\n 'JSON Schema object for event validation with description/examples annotations',\n );\n\n/**\n * Contract actions — keyed by action name (or \"*\" wildcard).\n */\nexport const ContractActionsSchema = z\n .record(z.string(), ContractSchemaEntry)\n .describe('Action-level contract entries');\n\n/**\n * Contract events map — entity → action keyed.\n */\nexport const ContractEventsSchema = z\n .record(z.string(), ContractActionsSchema)\n .describe('Entity-action event schemas');\n\n/**\n * Single named contract entry.\n */\nexport const ContractEntrySchema = z\n .object({\n extends: z\n .string()\n .optional()\n .describe('Inherit from another named contract'),\n tagging: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Contract version number'),\n description: z.string().optional().describe('Human-readable description'),\n globals: ContractSchemaEntry.optional().describe(\n 'JSON Schema for event.globals',\n ),\n context: ContractSchemaEntry.optional().describe(\n 'JSON Schema for event.context',\n ),\n custom: ContractSchemaEntry.optional().describe(\n 'JSON Schema for event.custom',\n ),\n user: ContractSchemaEntry.optional().describe('JSON Schema for event.user'),\n consent: ContractSchemaEntry.optional().describe(\n 'JSON Schema for event.consent',\n ),\n events: ContractEventsSchema.optional().describe(\n 'Entity-action event schemas',\n ),\n })\n .describe('Named contract entry with optional sections and events');\n\n/**\n * Named contract map.\n */\nexport const ContractSchema = z\n .record(z.string(), ContractEntrySchema)\n .describe('Named contracts with optional extends inheritance');\n\n// ========================================\n// Flow Settings Schema (Single Flow)\n// ========================================\n\n/**\n * Single flow settings schema.\n *\n * @remarks\n * Represents a single deployment target (e.g., web_prod, server_stage).\n * Platform is determined by presence of `web` or `server` key.\n * Exactly one must be present.\n */\nexport const SettingsSchema = z\n .object({\n web: WebSchema.optional().describe(\n 'Web platform configuration (browser-based tracking). Mutually exclusive with server.',\n ),\n server: ServerSchema.optional().describe(\n 'Server platform configuration (Node.js). Mutually exclusive with web.',\n ),\n sources: z\n .record(z.string(), SourceReferenceSchema)\n .optional()\n .describe(\n 'Source configurations (data capture) keyed by unique identifier',\n ),\n destinations: z\n .record(z.string(), DestinationReferenceSchema)\n .optional()\n .describe(\n 'Destination configurations (data output) keyed by unique identifier',\n ),\n transformers: z\n .record(z.string(), TransformerReferenceSchema)\n .optional()\n .describe(\n 'Transformer configurations (event transformation) keyed by unique identifier',\n ),\n stores: z\n .record(z.string(), StoreReferenceSchema)\n .optional()\n .describe(\n 'Store configurations (key-value storage) keyed by unique identifier',\n ),\n collector: z\n .unknown()\n .optional()\n .describe(\n 'Collector configuration for event processing (uses Collector.InitConfig)',\n ),\n packages: PackagesSchema.optional().describe('NPM packages to bundle'),\n variables: VariablesSchema.optional().describe(\n 'Flow-level variables (override Config.variables, overridden by source/destination variables)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Flow-level definitions (extend Config.definitions, overridden by source/destination definitions)',\n ),\n })\n .refine(\n (data) => {\n const hasWeb = data.web !== undefined;\n const hasServer = data.server !== undefined;\n return (hasWeb || hasServer) && !(hasWeb && hasServer);\n },\n {\n message: 'Exactly one of \"web\" or \"server\" must be present',\n },\n )\n .describe('Single flow settings for one deployment target');\n\n// ========================================\n// Flow Config Schema (Root Configuration)\n// ========================================\n\n/**\n * Flow config schema - root configuration.\n *\n * @remarks\n * This is the complete schema for walkeros.config.json files.\n * Contains multiple named flows with shared variables and definitions.\n */\nconst ConfigBaseSchema = z.object({\n $schema: z\n .string()\n .url('Schema URL must be a valid URL')\n .optional()\n .describe(\n 'JSON Schema reference for IDE validation (e.g., \"https://walkeros.io/schema/flow/v2.json\")',\n ),\n include: z\n .array(z.string())\n .optional()\n .describe('Folders to include in the bundle output'),\n variables: VariablesSchema.optional().describe(\n 'Shared variables for interpolation across all flows (use $var.name syntax)',\n ),\n definitions: DefinitionsSchema.optional().describe(\n 'Reusable configuration definitions (use $def.name syntax)',\n ),\n flows: z\n .record(z.string(), SettingsSchema)\n .refine((flows) => Object.keys(flows).length > 0, {\n message: 'At least one flow is required',\n })\n .describe(\n 'Named flow configurations (e.g., production, staging, development)',\n ),\n});\n\nexport const ConfigSchema = ConfigBaseSchema.extend({\n version: z.literal(3).describe('Configuration schema version'),\n contract: ContractSchema.optional().describe(\n 'Named contracts with extends inheritance and dot-path references',\n ),\n}).describe('walkerOS flow configuration (walkeros.config.json)');\n\n// ========================================\n// Helper Functions\n// ========================================\n\n/**\n * Parse and validate Flow.Config configuration.\n *\n * @param data - Raw JSON data from config file\n * @returns Validated Flow.Config object\n * @throws ZodError if validation fails with detailed error messages\n *\n * @example\n * ```typescript\n * import { parseConfig } from '@walkeros/core/dev';\n * import { readFileSync } from 'fs';\n *\n * const raw = JSON.parse(readFileSync('walkeros.config.json', 'utf8'));\n * const config = parseConfig(raw);\n * console.log(`Found ${Object.keys(config.flows).length} flows`);\n * ```\n */\nexport function parseConfig(data: unknown): z.infer<typeof ConfigSchema> {\n return ConfigSchema.parse(data);\n}\n\n/**\n * Safely parse Flow.Config configuration without throwing.\n *\n * @param data - Raw JSON data from config file\n * @returns Success result with data or error result with issues\n *\n * @example\n * ```typescript\n * import { safeParseConfig } from '@walkeros/core/dev';\n *\n * const result = safeParseConfig(rawData);\n * if (result.success) {\n * console.log('Valid config:', result.data);\n * } else {\n * console.error('Validation errors:', result.error.issues);\n * }\n * ```\n */\nexport function safeParseConfig(data: unknown) {\n return ConfigSchema.safeParse(data);\n}\n\n/**\n * Parse and validate Flow.Settings (single flow).\n *\n * @param data - Raw JSON data for single flow\n * @returns Validated Flow.Settings object\n * @throws ZodError if validation fails\n *\n * @example\n * ```typescript\n * import { parseSettings } from '@walkeros/core/dev';\n *\n * const flowSettings = parseSettings(rawFlowData);\n * console.log(`Platform: ${flowSettings.web ? 'web' : 'server'}`);\n * ```\n */\nexport function parseSettings(data: unknown): z.infer<typeof SettingsSchema> {\n return SettingsSchema.parse(data);\n}\n\n/**\n * Safely parse Flow.Settings without throwing.\n *\n * @param data - Raw JSON data for single flow\n * @returns Success result with data or error result with issues\n */\nexport function safeParseSettings(data: unknown) {\n return SettingsSchema.safeParse(data);\n}\n\n// ========================================\n// JSON Schema Generation\n// ========================================\n\n/**\n * Generate JSON Schema for Flow.Config.\n *\n * @remarks\n * Used for IDE validation and autocomplete.\n * Hosted at https://walkeros.io/schema/flow/v3.json\n *\n * @returns JSON Schema (Draft 7) representation of ConfigSchema\n */\nexport const configJsonSchema = z.toJSONSchema(ConfigSchema, {\n target: 'draft-7',\n});\n\n/**\n * Generate JSON Schema for Flow.Settings.\n *\n * @remarks\n * Used for validating individual flow settings.\n *\n * @returns JSON Schema (Draft 7) representation of SettingsSchema\n */\nexport const settingsJsonSchema = toJsonSchema(SettingsSchema, 'FlowSettings');\n\n/**\n * Generate JSON Schema for SourceReference.\n *\n * @remarks\n * Used for validating source package references.\n *\n * @returns JSON Schema (Draft 7) representation of SourceReferenceSchema\n */\nexport const sourceReferenceJsonSchema = toJsonSchema(\n SourceReferenceSchema,\n 'SourceReference',\n);\n\n/**\n * Generate JSON Schema for DestinationReference.\n *\n * @remarks\n * Used for validating destination package references.\n *\n * @returns JSON Schema (Draft 7) representation of DestinationReferenceSchema\n */\nexport const destinationReferenceJsonSchema = toJsonSchema(\n DestinationReferenceSchema,\n 'DestinationReference',\n);\n\n/**\n * Generate JSON Schema for TransformerReference.\n *\n * @remarks\n * Used for validating transformer package references.\n *\n * @returns JSON Schema (Draft 7) representation of TransformerReferenceSchema\n */\nexport const transformerReferenceJsonSchema = toJsonSchema(\n TransformerReferenceSchema,\n 'TransformerReference',\n);\n\n/**\n * Generate JSON Schema for StoreReference.\n *\n * @remarks\n * Used for validating store package references.\n *\n * @returns JSON Schema (Draft 7) representation of StoreReferenceSchema\n */\nexport const storeReferenceJsonSchema = toJsonSchema(\n StoreReferenceSchema,\n 'StoreReference',\n);\n\n/**\n * Generate JSON Schema for ContractEntry.\n *\n * @remarks\n * Used for validating individual contract entries.\n *\n * @returns JSON Schema (Draft 7) representation of ContractEntrySchema\n */\nexport const contractEntryJsonSchema = toJsonSchema(\n ContractEntrySchema,\n 'ContractEntry',\n);\n\n/**\n * Generate JSON Schema for Contract.\n *\n * @remarks\n * Used for validating named contract maps.\n *\n * @returns JSON Schema (Draft 7) representation of ContractSchema\n */\nexport const contractJsonSchema = toJsonSchema(ContractSchema, 'Contract');\n","import { z } from 'zod';\n\nexport const CodeSchema = z.object({\n lang: z\n .string()\n .optional()\n .describe('Language identifier (e.g. json, sql, bash, typescript)'),\n code: z.string().describe('Code snippet'),\n});\n\nexport const HintSchema = z.object({\n text: z\n .string()\n .describe('Short actionable hint text focused on walkerOS usage'),\n code: z.array(CodeSchema).optional().describe('Optional code snippets'),\n});\n\nexport const HintsSchema = z\n .record(z.string(), HintSchema)\n .describe(\n 'Keyed hints for AI consumption — lightweight context beyond schemas and examples',\n );\n","import { SourceSchemas, DestinationSchemas } from './schemas';\n\ntype PackageType = 'source' | 'destination' | 'transformer' | 'store';\n\ninterface PackageSchemas {\n settings?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n// Fields to exclude from merged config (runtime-only, not flow.json-relevant)\nconst RUNTIME_ONLY_FIELDS = new Set(['env', 'onError', 'onLog', 'primary']);\n\n// Base config schemas by type\nconst BASE_SCHEMAS: Partial<Record<PackageType, Record<string, unknown>>> = {\n source: SourceSchemas.configJsonSchema,\n destination: DestinationSchemas.configJsonSchema,\n};\n\nexport function mergeConfigSchema(\n type: PackageType,\n packageSchemas: PackageSchemas,\n): Record<string, unknown> {\n const baseSchema = BASE_SCHEMAS[type];\n\n if (!baseSchema || !baseSchema.properties) {\n const result: Record<string, unknown> = {\n type: 'object',\n properties: {\n settings: packageSchemas.settings\n ? stripDollarSchema(packageSchemas.settings)\n : { description: 'Implementation-specific configuration' },\n },\n };\n return result;\n }\n\n const merged = JSON.parse(JSON.stringify(baseSchema)) as Record<\n string,\n unknown\n >;\n const props = merged.properties as Record<string, unknown>;\n\n for (const field of RUNTIME_ONLY_FIELDS) {\n delete props[field];\n }\n\n if (packageSchemas.settings) {\n props.settings = stripDollarSchema(packageSchemas.settings);\n }\n\n return merged;\n}\n\nfunction stripDollarSchema(\n schema: Record<string, unknown>,\n): Record<string, unknown> {\n const { $schema, ...rest } = schema;\n return rest;\n}\n"],"mappings":";;;;;;;AAAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;AAAA;AAAA;AAAA;AAGO,IAAK,QAAL,kBAAKA,WAAL;AACL,EAAAA,cAAA,WAAQ,KAAR;AACA,EAAAA,cAAA,UAAO,KAAP;AACA,EAAAA,cAAA,UAAO,KAAP;AACA,EAAAA,cAAA,WAAQ,KAAR;AAJU,SAAAA;AAAA,GAAA;;;ACHZ;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACEO,IAAM,UAAU;AAAA,EACrB,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AACV;AAEO,IAAM,QAAQ;AAAA,EACnB,OAAO;AAAA,IACL;A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AE,SAAS,GAAG,KAAK,IAAI;AAC7B,SAAO;AACT;","names":["Level","acc","eventMapping","mapping","destination_exports","ConfigSchema","ResultSchema","configJsonSchema","ConfigSchema","ResultSchema","configJsonSchema","ConfigSchema","PushContextSchema","DestinationsSchema","InstanceSchema","configJsonSchema","pushContextJsonSchema","instanceJsonSchema","source_exports","ConfigSchema","InitSchema","InstanceSchema","PartialConfigSchema","configJsonSchema","instanceJsonSchema","partialConfigJsonSchema","ConfigSchema","PartialConfigSchema","InstanceSchema","InitSchema","configJsonSchema","partialConfigJsonSchema","instanceJsonSchema","ConfigSchema","configJsonSchema","ConfigSchema","z","source_exports","destination_exports"]}
|