@walkeros/core 4.7.0-next-1790722899482 → 4.7.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.mjs CHANGED
@@ -1 +1 @@
1
- var e=Object.defineProperty,t=(t,n)=>{for(var i in n)e(t,i,{get:n[i],enumerable:!0})},n={};t(n,{BaseContextConfig:()=>F,CacheRuleSchema:()=>Ke,CacheSchema:()=>Qe,CacheSchemas:()=>Be,ClickIdEntrySchema:()=>si,CodeSchema:()=>ii,CollectorSchemas:()=>Dt,ConsentSchema:()=>Z,ContractActionsSchema:()=>Rn,ContractRuleSchema:()=>Mn,ContractSchema:()=>Fn,ContractSchemaEntry:()=>Tn,Counter:()=>d,CredentialsSchema:()=>ci,DeepPartialEventSchema:()=>ne,DestinationSchemas:()=>Te,DestinationsMapConfig:()=>L,EntitiesSchema:()=>X,EntitySchema:()=>Y,EventCacheRuleSchema:()=>He,EventCacheSchema:()=>Ve,EventSchema:()=>ee,FlowBundlePackageSchema:()=>Sn,FlowBundleSchema:()=>wn,FlowCodeSchema:()=>kn,FlowConfigSchema:()=>Nn,FlowDestinationSchema:()=>In,FlowJsonSchema:()=>qn,FlowSchema:()=>Ln,FlowSchemas:()=>hn,FlowSourceSchema:()=>$n,FlowStoreSchema:()=>An,FlowTransformerSchema:()=>Dn,GenericEnvConfig:()=>I,GenericSettingsConfig:()=>D,HandlersConfig:()=>x,HintSchema:()=>oi,HintsSchema:()=>ri,IdConfig:()=>O,Identifier:()=>c,InitConfig:()=>P,LoggerConfigSchema:()=>ot,LoggerHandlerSchema:()=>it,LoopSchema:()=>me,MapSchema:()=>he,MappingResultSchema:()=>Ce,MappingSchemas:()=>pe,MatchExpressionSchema:()=>Fe,MatcherSchemas:()=>Re,OptionalPrimitiveValue:()=>u,OrderedPropertiesSchema:()=>H,PartialEventSchema:()=>te,PolicySchema:()=>ve,PrimaryConfig:()=>$,PrimitiveValue:()=>p,ProcessingControlConfig:()=>z,PropertiesSchema:()=>B,PropertySchema:()=>U,PropertyTypeSchema:()=>W,QueueConfig:()=>E,RequiredBoolean:()=>a,RequiredNumber:()=>s,RequiredString:()=>r,RouteSchema:()=>Ue,RuleSchema:()=>Se,RulesSchema:()=>we,RuntimeInstanceConfig:()=>M,ServiceAccountSchema:()=>ai,SetSchema:()=>ge,SourceSchema:()=>Q,SourceSchemas:()=>Bt,SourceTypeSchema:()=>V,SourcesMapConfig:()=>N,StateSchema:()=>nt,StoreCacheRuleSchema:()=>Ze,StoreCacheSchema:()=>Ge,StoreSchemas:()=>pn,Timestamp:()=>l,TransformerSchemas:()=>sn,UserSchema:()=>G,UtilitySchemas:()=>f,ValidateEventsSchema:()=>On,ValueConfigSchema:()=>be,ValueSchema:()=>ue,ValuesSchema:()=>fe,VerboseConfig:()=>j,WalkerOSSchemas:()=>q,configJsonSchema:()=>Hn,consentJsonSchema:()=>de,contractJsonSchema:()=>ei,contractRuleJsonSchema:()=>Xn,createArraySchema:()=>Eo,createConsentConfig:()=>J,createDataTransformationConfig:()=>A,createEnumSchema:()=>Oo,createMappingRulesConfig:()=>T,createObjectSchema:()=>xo,createPolicyConfig:()=>R,createTupleSchema:()=>Po,credentialsJsonSchema:()=>li,destinationJsonSchema:()=>Kn,entityJsonSchema:()=>ce,eventJsonSchema:()=>ie,flowConfigJsonSchema:()=>Zn,flowJsonSchema:()=>Vn,loopJsonSchema:()=>Ee,mapJsonSchema:()=>Pe,orderedPropertiesJsonSchema:()=>ae,parseConfig:()=>_n,parseFlow:()=>Un,partialEventJsonSchema:()=>oe,policyJsonSchema:()=>$e,propertiesJsonSchema:()=>se,ruleJsonSchema:()=>De,rulesJsonSchema:()=>Ie,safeParseConfig:()=>Wn,safeParseFlow:()=>Bn,setJsonSchema:()=>Oe,sourceJsonSchema:()=>Gn,sourceTypeJsonSchema:()=>le,storeJsonSchema:()=>Yn,transformerJsonSchema:()=>Qn,userJsonSchema:()=>re,validateEventsJsonSchema:()=>ti,validateFlowConfig:()=>Ui,valueConfigJsonSchema:()=>je,valueJsonSchema:()=>xe,z:()=>i,zodToSchema:()=>$o});import{z as i}from"zod";function o(e,t,n="draft-7"){return i.toJSONSchema(e,{target:n})}var r=i.string(),s=i.number(),a=i.boolean(),c=i.string().min(1),l=i.number().int().positive(),d=i.number().int().nonnegative(),p=i.union([i.string(),i.number(),i.boolean()]),u=p.optional(),f={};t(f,{ErrorHandlerSchema:()=>h,HandlerSchema:()=>v,LogHandlerSchema:()=>b,StorageSchema:()=>g,StorageTypeSchema:()=>m,errorHandlerJsonSchema:()=>w,handlerJsonSchema:()=>C,logHandlerJsonSchema:()=>k,storageJsonSchema:()=>S,storageTypeJsonSchema:()=>y});var m=i.enum(["local","session","cookie"]).meta({id:"StorageType",title:"Storage.Type",description:"Storage mechanism: local, session, or cookie."}).describe("Storage mechanism: local, session, or cookie"),g=i.object({Local:i.literal("local"),Session:i.literal("session"),Cookie:i.literal("cookie")}).meta({id:"StorageConstants",title:"Storage",description:"Storage type constants for type-safe references."}).describe("Storage type constants for type-safe references"),h=i.unknown().meta({id:"ErrorHandler",title:"Error.Handler",description:"Error handler function: (error, state?) => void."}).describe("Error handler function: (error, state?) => void"),b=i.unknown().meta({id:"LogHandler",title:"Log.Handler",description:"Log handler function: (message, verbose?) => void."}).describe("Log handler function: (message, verbose?) => void"),v=i.object({Error:h.describe("Error handler function"),Log:b.describe("Log handler function")}).meta({id:"Handler",title:"Handler",description:"Handler interface with error and log functions."}).describe("Handler interface with error and log functions"),y=o(m),S=o(g),w=o(h),k=o(b),C=o(v),x=i.object({onError:h.optional().describe("Error handler function: (error, state?) => void"),onLog:b.optional().describe("Log handler function: (message, verbose?) => void")}).partial(),j=i.object({verbose:i.boolean().describe("Enable verbose logging for debugging").optional()}).partial(),E=i.object({queue:i.boolean().describe("Whether a destination added later receives events pushed earlier in the current run (default true). Consent-denied events are queued regardless.").optional()}).partial(),O=i.object({}).partial(),P=i.object({init:i.boolean().describe("Whether to initialize immediately").optional(),loadScript:i.boolean().describe("Whether to load external script (for web destinations)").optional()}).partial(),$=i.object({primary:i.boolean().describe("Mark as primary (only one can be primary)").optional()}).partial(),D=i.object({settings:i.any().optional().describe("Implementation-specific configuration")}).partial(),I=i.object({env:i.any().optional().describe("Environment dependencies (platform-specific)")}).partial();function A(e,t){return i.object({data:i.union([e,t]).optional().describe("Data transformation rules")}).partial()}function T(e){return i.object({mapping:e.optional().describe("Event mapping rules")}).partial()}function R(e){return i.object({policy:e.optional().describe("Pre-processing policy rules")}).partial()}function J(e){return i.object({consent:e.optional().describe("Required consent states")}).partial()}var M=i.object({type:i.string().optional().describe("Instance type identifier"),config:i.unknown().describe("Instance configuration")}).partial(),F=i.object({collector:i.unknown().describe("Collector instance (runtime object)"),config:i.unknown().describe("Configuration"),env:i.unknown().describe("Environment dependencies")}).partial(),z=i.object({ignore:i.boolean().describe("Set to true to skip processing").optional(),condition:i.string().optional().describe("Condition function: return true to process")}).partial(),N=i.object({sources:i.record(i.string(),i.unknown()).describe("Map of source instances")}).partial(),L=i.object({destinations:i.record(i.string(),i.unknown()).describe("Map of destination instances")}).partial(),q={};t(q,{ConsentSchema:()=>Z,DeepPartialEventSchema:()=>ne,EntitiesSchema:()=>X,EntitySchema:()=>Y,EventSchema:()=>ee,OrderedPropertiesSchema:()=>H,PartialEventSchema:()=>te,PropertiesSchema:()=>B,PropertySchema:()=>U,PropertyTypeSchema:()=>W,SourceFieldsSchema:()=>K,SourceSchema:()=>Q,SourceTypeSchema:()=>V,UserSchema:()=>G,consentJsonSchema:()=>de,entityJsonSchema:()=>ce,eventJsonSchema:()=>ie,orderedPropertiesJsonSchema:()=>ae,partialEventJsonSchema:()=>oe,propertiesJsonSchema:()=>se,sourceTypeJsonSchema:()=>le,userJsonSchema:()=>re});var _,W=i.lazy(()=>i.union([i.boolean(),i.string(),i.number(),i.record(i.string(),U)])).meta({id:"WalkerOSPropertyType",title:"WalkerOS.PropertyType",description:"Base property value types (boolean, string, number, or nested Property record)."}),U=i.lazy(()=>i.union([W,i.array(W)])).meta({id:"WalkerOSProperty",title:"WalkerOS.Property",description:"PropertyType or an array of PropertyType. Recursive structure for nested objects and arrays."}),B=i.record(i.string(),U.optional()).meta({id:"WalkerOSProperties",title:"WalkerOS.Properties",description:"Flexible property collection with optional values."}).describe("Flexible property collection with optional values"),H=i.record(i.string(),i.tuple([U,i.number()]).optional()).meta({id:"WalkerOSOrderedProperties",title:"WalkerOS.OrderedProperties",description:"Ordered properties with [value, order] tuples for priority control."}).describe("Ordered properties with [value, order] tuples for priority control"),V=i.union([i.enum(["web","server","app","other"]),i.string()]).meta({id:"WalkerOSSourceType",title:"WalkerOS.SourceType",description:"Source type identifier. Standard: web, server, app, other. Extensible to custom strings."}).describe("Source type: web, server, app, other, or custom"),Z=i.record(i.string(),i.boolean()).meta({id:"WalkerOSConsent",title:"WalkerOS.Consent",description:"Consent state mapping. Keys are consent groups (e.g. marketing, functional), values are booleans for granted/denied."}).describe("Consent requirement mapping (group name to state)"),G=B.and(i.object({id:i.string().optional().describe("User identifier"),device:i.string().optional().describe("Device identifier"),session:i.string().optional().describe("Session identifier"),hash:i.string().optional().describe("Hashed identifier"),address:i.string().optional().describe("User address"),email:i.string().email().optional().describe("User email address"),phone:i.string().optional().describe("User phone number"),userAgent:i.string().optional().describe("Browser user agent string"),browser:i.string().optional().describe("Browser name"),browserVersion:i.string().optional().describe("Browser version"),deviceType:i.string().optional().describe("Device type (mobile, desktop, tablet)"),os:i.string().optional().describe("Operating system"),osVersion:i.string().optional().describe("Operating system version"),screenSize:i.string().optional().describe("Screen dimensions"),language:i.string().optional().describe("User language"),country:i.string().optional().describe("User country"),region:i.string().optional().describe("User region/state"),city:i.string().optional().describe("User city"),zip:i.string().optional().describe("User postal code"),timezone:i.string().optional().describe("User timezone"),ip:i.string().optional().describe("User IP address"),internal:i.boolean().optional().describe("Internal user flag (employee, test user)")})).meta({id:"WalkerOSUser",title:"WalkerOS.User",description:"User identification and attributes."}).describe("User identification and properties"),K=i.object({type:i.string().describe("Source kind (browser, dataLayer, gtag, ...)"),platform:i.string().optional().describe("Runtime platform (web, server, app, ios, android, terminal, ...)"),version:i.string().optional().describe("Deployment version of the source emitter"),schema:i.string().optional().describe('Event model spec version (collector defaults to "4")'),count:i.number().int().nonnegative().optional().describe("Emission sequence per run"),trace:i.string().optional().describe("Trace id shared by every event of a run (W3C trace-id shape)"),release:i.record(i.string(),i.string()).optional().describe("Per-flow config release map, keyed by flow name; accumulates across walkerOS crossings"),url:i.string().optional(),referrer:i.string().optional(),tool:i.string().optional(),command:i.string().optional()}),Q=B.and(K).meta({id:"WalkerOSSource",title:"WalkerOS.Source",description:"Event source information (origin of the event)."}).describe("Event source information"),Y=i.lazy(()=>i.object({entity:i.string().describe("Entity name"),data:B.describe("Entity-specific properties"),nested:i.array(Y).optional().describe("Nested child entities"),context:H.optional().describe("Entity context data")})).meta({id:"WalkerOSEntity",title:"WalkerOS.Entity",description:"Nested entity structure with recursive nesting support."}).describe("Nested entity structure with recursive nesting support"),X=i.array(Y).meta({id:"WalkerOSEntities",title:"WalkerOS.Entities",description:"Array of nested entities."}).describe("Array of nested entities"),ee=i.object({name:i.string().describe('Event name in "entity action" format (e.g., "page view", "product add")'),data:B.describe("Event-specific properties"),context:H.describe("Ordered context properties with priorities"),globals:B.describe("Global properties shared across events"),custom:B.describe("Custom implementation-specific properties"),user:G.describe("User identification and attributes"),nested:X.describe("Related nested entities"),consent:Z.describe("Consent states at event time"),id:c.describe("W3C span_id, 16 lowercase hex characters"),trigger:r.describe("Event trigger identifier"),entity:r.describe("Parsed entity from event name"),action:r.describe("Parsed action from event name"),timestamp:l.describe("Unix timestamp in milliseconds since epoch"),timing:s.describe("Event processing timing information"),source:Q.describe("Event source information")}).meta({id:"WalkerOSEvent",title:"WalkerOS.Event",description:"Complete walkerOS event structure."}).describe("Complete walkerOS event structure"),te=ee.partial().meta({id:"WalkerOSPartialEvent",title:"WalkerOS.PartialEvent",description:"Partial event structure with all fields optional."}).describe("Partial event structure with all fields optional"),ne=ee.partial().meta({id:"WalkerOSDeepPartialEvent",title:"WalkerOS.DeepPartialEvent",description:"Partial event structure with all top-level fields optional."}).describe("Partial event structure with all top-level fields optional"),ie=o(ee),oe=o(te),re=o(G),se=o(B),ae=o(H),ce=o(Y),le=o(V),de=o(Z),pe={};t(pe,{ConfigSchema:()=>ke,LoopSchema:()=>me,MapSchema:()=>he,PolicySchema:()=>ve,ResultSchema:()=>Ce,RulePatchSchema:()=>ye,RuleSchema:()=>Se,RulesSchema:()=>we,SetSchema:()=>ge,ValueConfigSchema:()=>be,ValueSchema:()=>ue,ValuesSchema:()=>fe,configJsonSchema:()=>Ae,loopJsonSchema:()=>Ee,mapJsonSchema:()=>Pe,policyJsonSchema:()=>$e,ruleJsonSchema:()=>De,rulesJsonSchema:()=>Ie,setJsonSchema:()=>Oe,valueConfigJsonSchema:()=>je,valueJsonSchema:()=>xe});var ue=i.lazy(()=>i.union([i.string().describe('String value or property path (e.g., "data.id")'),i.number().describe("Numeric value"),i.boolean().describe("Boolean value"),i.lazy(()=>_),i.array(ue).describe("Array of values")])).meta({id:"MappingValue",title:"Mapping.Value",description:"Polymorphic transform primitive used in every mapping field. A string path, constant, operator object (map/loop/set/condition/consent), or array of values."}),fe=i.array(ue).meta({id:"MappingValues",title:"Mapping.Values",description:"Array of transformation values."}).describe("Array of transformation values"),me=i.lazy(()=>i.tuple([ue,ue]).describe("Loop transformation: [source, transform] tuple for array processing")).meta({id:"MappingLoop",title:"Mapping.Loop",description:"Loop tuple [source, transform] for iterating and transforming arrays.",minItems:2,maxItems:2}),ge=i.lazy(()=>i.array(ue).describe("Set: Array of values for selection or combination")).meta({id:"MappingSet",title:"Mapping.Set",description:"Set: array of values for selection or combination."}),he=i.lazy(()=>i.record(i.string(),ue).describe("Map: Object mapping keys to transformation values")).meta({id:"MappingMap",title:"Mapping.Map",description:"Map: object mapping keys to transformation values."}),be=_=i.object({key:i.string().optional().describe('Property path to extract from event (e.g., "data.id", "user.email")'),value:i.union([i.string(),i.number(),i.boolean()]).optional().describe("Static primitive value"),fn:i.string().optional().describe("Custom transformation function as string (serialized)"),map:he.optional().describe("Object mapping: transform event data to structured output"),loop:me.optional().describe("Loop transformation: [source, transform] for array processing"),set:ge.optional().describe("Set of values: combine or select from multiple values"),consent:Z.optional().describe("Required consent states to include this value"),condition:i.string().optional().describe("Condition function as string: return true to include value"),validate:i.string().optional().describe("Validation function as string: return true if value is valid")}).refine(e=>Object.keys(e).length>0,{message:"ValueConfig must have at least one property"}).meta({id:"MappingValueConfig",title:"Mapping.ValueConfig",description:"Object-form value transformation with map/loop/set/condition/consent etc."}).describe("Value transformation configuration with multiple strategies"),ve=i.record(i.string(),ue).meta({id:"MappingPolicy",title:"Mapping.Policy",description:"Policy rules for event pre-processing (key → value transformation)."}).describe("Policy rules for event pre-processing (key → value mapping)"),ye=i.object({name:i.string().nullable().optional(),data:i.union([ue,fe]).nullable().optional(),settings:i.unknown().nullable().optional(),condition:i.string().nullable().optional(),consent:Z.nullable().optional(),policy:ve.nullable().optional(),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).nullable().optional(),include:i.array(i.string()).nullable().optional(),ignore:i.boolean().nullable().optional(),silent:i.boolean().nullable().optional()}).meta({id:"MappingRulePatch",title:"Mapping.RulePatch",description:"Partial rule deep-merged onto a package-shipped default; a null value clears the inherited field."}).describe("Partial rule for `extend`; null clears an inherited field"),Se=i.object({name:i.string().optional().describe('Custom event name override (e.g., "view_item" for "product view")'),data:i.union([ue,fe]).optional().describe("Data transformation rules for event"),settings:i.unknown().optional().describe("Destination-specific settings for this event mapping"),condition:i.string().optional().describe("Condition function as string: return true to process event"),consent:Z.optional().describe("Required consent states to process this event"),policy:ve.optional().describe("Event-level policy overrides (applied after config-level policy)"),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).optional().describe("Batch scheduling: bare number is the debounce wait window (legacy); object form supports wait/size/age."),include:i.array(i.string()).optional().describe('Event sections (e.g. ["context", "globals"]) flattened into context.data'),ignore:i.boolean().optional().describe("Skip the event entirely. No push, no side effects. Use for suppression."),silent:i.boolean().optional().describe("Run side effects (settings.identify, ...) but suppress the destination default push call."),extend:ye.optional().describe("Merge mode: a partial rule deep-merged onto the package-shipped default at this key (instead of replacing it). A null value clears an inherited field."),remove:i.array(i.string()).optional().describe("Dotted paths stripped from the produced data payload after evaluation (applied last).")}).meta({id:"MappingRule",title:"Mapping.Rule",description:"Configuration for transforming a single event at one stage of the flow (source or destination)."}).describe("Mapping rule for specific entity-action combination"),we=i.record(i.string(),i.record(i.string(),i.union([Se,i.array(Se)])).optional()).meta({id:"MappingRules",title:"Mapping.Rules",description:'Event mapping rules tree: entity → action → Rule (or Rule[]). Use "*" as wildcard for entity or action.'}).describe('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 (*→*).'),ke=i.object({consent:Z.optional().describe("Required consent states to process any events"),data:i.union([ue,fe]).optional().describe("Global data transformation applied to all events"),include:i.array(i.string()).optional().describe("Event sections to flatten into context.data"),mapping:we.optional().describe("Entity-action specific mapping rules"),policy:ve.optional().describe("Pre-processing policy rules applied before mapping")}).meta({id:"MappingConfig",title:"Mapping.Config",description:"Shared mapping configuration (consent, data, include, mapping, policy)."}).describe("Shared mapping configuration for sources and destinations"),Ce=i.object({eventMapping:Se.optional().describe("Resolved mapping rule for event"),mappingKey:i.string().optional().describe('Mapping key used (e.g., "product.view")')}).meta({id:"MappingResult",title:"Mapping.Result",description:"Mapping resolution result (matched rule + key)."}).describe("Mapping resolution result"),xe=o(ue),je=o(be),Ee=o(me),Oe=o(ge),Pe=o(he),$e=o(ve),De=o(Se),Ie=o(we),Ae=o(ke),Te={};t(Te,{BatchSchema:()=>ft,ConfigSchema:()=>rt,ContextSchema:()=>ct,DLQSchema:()=>kt,DataSchema:()=>mt,DestinationPolicySchema:()=>at,DestinationsSchema:()=>vt,InitDestinationsSchema:()=>bt,InitSchema:()=>ht,InstanceSchema:()=>gt,PartialConfigSchema:()=>st,PushBatchContextSchema:()=>dt,PushContextSchema:()=>lt,PushEventSchema:()=>pt,PushEventsSchema:()=>ut,PushResultSchema:()=>St,RefSchema:()=>yt,ResultSchema:()=>wt,batchJsonSchema:()=>Ot,configJsonSchema:()=>Ct,contextJsonSchema:()=>jt,instanceJsonSchema:()=>Pt,partialConfigJsonSchema:()=>xt,pushContextJsonSchema:()=>Et,resultJsonSchema:()=>$t});var Re={};t(Re,{MatchExpressionSchema:()=>Fe,RouteSchema:()=>Ue});var Je=i.enum(["eq","contains","prefix","suffix","regex","gt","lt","exists"]).meta({id:"MatcherOperator",title:"Matcher.Operator",description:"Supported operators for a match condition."}),Me=i.object({key:i.string(),operator:Je,value:i.string(),not:i.boolean().optional()}).meta({id:"MatcherCondition",title:"Matcher.Condition",description:"Single match condition (key, operator, value, optional not)."}),Fe=i.union([Me,i.object({and:i.array(i.lazy(()=>Fe))}),i.object({or:i.array(i.lazy(()=>Fe))})]).meta({id:"MatcherExpression",title:"Matcher.Expression",description:"Boolean expression tree of match conditions (leaf, and, or)."}),ze=i.strictObject({match:Fe.optional(),next:i.lazy(()=>Ue)}),Ne=i.strictObject({match:Fe.optional(),one:i.array(i.lazy(()=>Ue))}),Le=i.strictObject({match:Fe.optional(),many:i.array(i.lazy(()=>Ue))}),qe=i.strictObject({match:Fe.optional(),stop:i.literal(!0)}),_e=i.strictObject({match:Fe}),We=i.union([ze,Ne,Le,qe,_e]),Ue=i.union([i.string(),i.array(i.lazy(()=>Ue)),We]).meta({id:"Route",title:"Route",description:"Recursive route: string ID, sequence of routes, or a RouteConfig (next/one/many/stop/gate). Valid in every chain field."}),Be={};t(Be,{CacheRuleSchema:()=>Ke,CacheSchema:()=>Qe,EventCacheRuleSchema:()=>He,EventCacheSchema:()=>Ve,StoreCacheRuleSchema:()=>Ze,StoreCacheSchema:()=>Ge});var He=i.object({match:Fe.optional().describe("Optional match expression — omit for always-match."),key:i.array(i.string()).min(1).describe("Dot-path fields used to build the cache key"),ttl:i.number().positive().describe("Time-to-live in seconds"),update:i.record(i.string(),ue).optional().describe("Response mutations applied on cache hit (key → Value mapping)")}).meta({id:"EventCacheRule",title:"EventCache.Rule",description:"Single event-cache rule: when it applies (match), what event fields it keys off, TTL, and optional response mutations on hit."}),Ve=i.object({stop:i.boolean().optional().describe("Stop the chain on cache HIT (default: false). When true, skip remaining steps and return cached value."),store:i.string().optional().describe("Store ID for persistent caching (references a configured store)"),namespace:i.string().optional().describe("Optional key prefix. Omit to write keys directly to the store. Same store + same key + same namespace = same cache entry."),rules:i.array(He).min(1).describe("Cache rules — at least one required")}).meta({id:"EventCacheConfig",title:"EventCache.Config",description:"Top-level cache configuration for an event-context pipeline step (source / transformer / destination)."}),Ze=i.strictObject({match:Fe.optional().describe("Optional match expression evaluated against `{ key, value? }`. Omit for always-match."),ttl:i.number().positive().describe("Time-to-live in seconds")}).meta({id:"StoreCacheRule",title:"StoreCache.Rule",description:"Single store-cache rule: optional match against `{ key, value? }` and a TTL. No `key` (caller provides it) and no `update` (no event to mutate)."}),Ge=i.strictObject({store:i.string().optional().describe("Store ID for persistent caching (references a configured store)"),namespace:i.string().min(1).optional().describe("Optional key prefix. Omit to default to the host store id. Empty string is rejected."),rules:i.array(Ze).min(1).describe("Cache rules — at least one required")}).meta({id:"StoreCacheConfig",title:"StoreCache.Config",description:"Top-level cache configuration for a store wrapper. No `stop` (always falls through on miss); namespace defaults to the host store id."}),Ke=He,Qe=Ve,Ye=/^(event|ingest)(\..+)?$/,Xe=/^(event|ingest)\..+$/;function et(e){return"string"==typeof e?[e]:Array.isArray(e)?e.flatMap(et):"object"==typeof e&&null!==e&&"key"in e&&"string"==typeof e.key?[e.key]:[]}function tt(e,t,n,i){for(const o of et(e))i.test(o)||n.addIssue({code:"custom",message:`State paths resolve against { event, ingest }: "${o}" needs an "event." or "ingest." prefix.`,path:[t]})}var nt=i.object({mode:i.enum(["get","set"]).describe("Direction: 'get' reads from the store, 'set' writes to it"),store:i.string().optional().describe("Store id; defaults to the in-memory __cache store when omitted"),key:ue.describe("Resolves against { event, ingest } to the store key. Paths need an event. or ingest. prefix"),value:ue.optional().describe("set: resolves against { event, ingest } to the payload to store. get: its path is the write target, event. onto the event or ingest. into the ingest.")}).superRefine((e,t)=>{if(tt(e.key,"key",t,Xe),void 0!==e.value){if(tt(e.value,"value",t,"get"===e.mode?Xe:Ye),"get"===e.mode){const n=e.value;let i;if("string"==typeof n)i=n;else if("object"==typeof n&&null!==n&&!Array.isArray(n)&&"key"in n&&"string"==typeof n.key){if(["value","fn","map","loop","set"].filter(e=>e in n).length>0)return void t.addIssue({code:"custom",message:'For mode "get", `value` may only provide a `key` path.',path:["value"]});i=n.key}if(void 0===i)return void t.addIssue({code:"custom",message:'For mode "get", `value` must be a bare string path or a ValueConfig with a `key` (no value/fn/map/loop/set).',path:["value"]});i.includes("*")&&t.addIssue({code:"custom",message:'For mode "get", the `value` path may not contain `*`.',path:["value"]})}}else t.addIssue({code:"custom",message:`\`value\` is required for mode "${e.mode}".`,path:["value"]})}).meta({id:"StateConfig",title:"State.Config",description:"Declarative store operation: stash (set) or fetch (get) a value against a store. key names the store slot, value the event or ingest side, mode the direction. Paths resolve against { event, ingest }."}),it=i.any().meta({id:"LoggerHandler",title:"Logger.Handler",description:"Custom log handler function (level, ...args) => void"}),ot=i.object({level:i.union([i.number(),i.enum(["ERROR","WARN","INFO","DEBUG"])]).optional().describe("Minimum log level (default: ERROR)"),handler:it.optional().describe("Custom log handler function")}).meta({id:"LoggerConfig",title:"Logger.Config",description:"Logger configuration (level, handler) to override the collector defaults"}),rt=i.object({consent:Z.optional().describe("Required consent states to send events to this destination"),settings:i.any().meta({id:"DestinationSettings",title:"Destination.Settings",description:"Implementation-specific configuration (destination-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.any().meta({id:"DestinationCredentials",title:"Destination.Credentials",description:"Optional credentials slot (destination-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (destination-defined shape)").optional(),data:i.union([ue,fe]).optional().describe("Global data transformation applied to all events for this destination"),include:i.array(i.string()).optional().describe("Event sections to flatten into context.data"),env:i.any().meta({id:"DestinationEnv",title:"Destination.Env",description:"Environment dependencies (destination-defined shape) — platform, SDK, or mock hook."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Destination instance identifier (defaults to destination key)").optional(),init:i.boolean().describe("Whether to initialize immediately").optional(),loadScript:i.boolean().describe("Whether to load external script (for web destinations)").optional(),mapping:we.optional().describe("Entity-action specific mapping rules for this destination"),policy:ve.optional().describe("Pre-processing policy rules applied before event mapping"),queue:i.boolean().describe("Whether a destination added later receives events pushed earlier in the current run (default true). Consent-denied events are queued regardless.").optional(),require:i.array(i.string()).optional().describe('Defer destination initialization until these collector events fire (e.g., ["consent"])'),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during destination registration (boolean enables defaults, object configures specifics)"),before:Ue.optional().describe("Transformer chain run for this destination only, before it receives the event."),next:Ue.optional().describe("Post-push transformer chain. Runs after destination push completes; push response is available at ingest._response."),cache:Ve.optional().describe("Cache configuration for deduplication; skip push on cache HIT"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this destination"),disabled:i.boolean().describe("Completely skip this destination (no init, no push, no queue)").optional(),mock:i.unknown().meta({id:"DestinationMock",title:"Destination.Mock",description:"Return this value instead of calling push(). Dev/testing only."}).optional().describe("Return this value instead of calling push(). Dev/testing only."),queueMax:i.number().optional().describe("Maximum consent-denied events retained in queuePush for this destination. FIFO drop on overflow. Default 1000."),dlqMax:i.number().optional().describe("Maximum failed-push entries retained in dlq for this destination. FIFO drop on overflow. Default 100."),timeout:i.number().optional().describe("Per-destination delivery timeout in ms (default 10000); a delivery that does not settle in this window is routed to the DLQ like a thrown push."),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).optional().describe("Enables batching for all of this destination's events into one shared default buffer; a mapping rule's own batch splits that entity-action into its own buffer and overrides per field. Bare number is the debounce wait window; object form supports wait (debounce ms), size (count cap, default 1000), age (max ms since first entry, default 30000)."),breaker:i.union([i.number(),i.object({threshold:i.number().optional(),cooldown:i.number().optional()})]).optional().describe("Per-destination circuit breaker (presence-gated). After threshold consecutive transport failures the breaker opens and events are skipped until cooldown ms elapse, then one probe is admitted; success closes it, failure re-opens it. Partial-batch row failures are breaker-neutral. Bare number is the threshold; object form supports threshold (default 5) and cooldown (default 30000ms).")}).meta({id:"DestinationConfig",title:"Destination.Config",description:"Destination configuration: consent, settings, data, env, mapping rules, policy, queue, logger, before/next chains, cache."}).describe("Destination configuration"),st=rt.partial().meta({id:"DestinationPartialConfig",title:"Destination.PartialConfig",description:"Partial destination configuration with all fields optional."}).describe("Partial destination configuration with all fields optional"),at=ve.describe("Destination policy rules for event pre-processing"),ct=i.object({collector:i.unknown().meta({id:"DestinationContextCollector",title:"Collector.Instance",description:"Collector instance handed to the destination (runtime object)."}).describe("Collector instance (runtime object)"),config:rt.describe("Destination configuration"),data:i.union([i.unknown(),i.array(i.unknown())]).optional().describe("Transformed event data"),env:i.unknown().meta({id:"DestinationContextEnv",title:"Destination.Env",description:"Environment dependencies (destination-defined shape)."}).describe("Environment dependencies")}).meta({id:"DestinationContext",title:"Destination.Context",description:"Destination context passed to init and push functions."}).describe("Destination context for init and push functions"),lt=ct.extend({mapping:Se.optional().describe("Resolved mapping rule for this specific event")}).meta({id:"DestinationPushContext",title:"Destination.PushContext",description:"Destination context for push() with the resolved event mapping rule."}).describe("Push context with event-specific mapping"),dt=lt.describe("Batch push context with event-specific mapping"),pt=i.object({event:ee.describe("The event to process"),mapping:Se.optional().describe("Mapping rule for this event")}).meta({id:"DestinationPushEvent",title:"Destination.PushEvent",description:"Single event paired with its resolved mapping rule (batch element)."}).describe("Event with optional mapping for batch processing"),ut=i.array(pt).meta({id:"DestinationPushEvents",title:"Destination.PushEvents",description:"Array of events with mappings (batch input)."}).describe("Array of events with mappings"),ft=i.object({key:i.string().describe('Batch key (usually mapping key like "product.view")'),events:i.array(ee).describe("Array of events in batch"),data:i.array(i.union([i.unknown(),i.array(i.unknown())]).optional()).describe("Transformed data for each event"),mapping:Se.optional().describe("Shared mapping rule for batch")}).meta({id:"DestinationBatch",title:"Destination.Batch",description:"Batch of events grouped by mapping key for batch delivery."}).describe("Batch of events grouped by mapping key"),mt=i.union([i.unknown(),i.array(i.unknown())]).meta({id:"DestinationData",title:"Destination.Data",description:"Transformed event data delivered to the destination (Property, undefined, or array)."}).optional().describe("Transformed event data (Property, undefined, or array)"),gt=i.object({config:rt.describe("Destination configuration"),queue:i.array(ee).optional().describe("Queued events awaiting consent"),dlq:i.array(i.tuple([ee,i.unknown()])).optional().describe("Dead letter queue (failed events with errors)"),type:i.string().optional().describe("Destination type identifier"),env:i.unknown().optional().describe("Environment dependencies"),init:i.unknown().optional().describe("Initialization function"),push:i.unknown().describe("Push function for single events"),pushBatch:i.unknown().optional().describe("Batch push function"),on:i.unknown().optional().describe("Event lifecycle hook function")}).meta({id:"DestinationInstance",title:"Destination.Instance",description:"Destination instance (runtime object with init/push/pushBatch/on)."}).describe("Destination instance (runtime object with functions)"),ht=i.object({code:gt.describe("Destination instance with implementation"),config:st.optional().describe("Partial configuration overrides"),env:i.unknown().optional().describe("Partial environment overrides")}).meta({id:"DestinationInit",title:"Destination.Init",description:"Destination initialization bundle (instance code + config + env)."}).describe("Destination initialization configuration"),bt=i.record(i.string(),ht).meta({id:"DestinationInitDestinations",title:"Destination.InitDestinations",description:"Map of destination IDs to initialization configurations."}).describe("Map of destination IDs to initialization configurations"),vt=i.record(i.string(),gt).meta({id:"DestinationDestinations",title:"Destination.Destinations",description:"Map of destination IDs to runtime destination instances."}).describe("Map of destination IDs to runtime instances"),yt=i.object({type:i.string().describe('Destination type ("gtag", "meta", "bigquery")'),data:i.unknown().optional().describe("Response from push()"),error:i.unknown().optional().describe("Error if failed")}).meta({id:"DestinationRef",title:"Destination.Ref",description:"Reference to a destination outcome (type + response data or error)."}).describe("Destination reference with type and response data"),St=i.object({queue:i.array(ee).optional().describe("Events queued (awaiting consent)"),error:i.unknown().optional().describe("Error if push failed")}).meta({id:"DestinationPushResult",title:"Destination.PushResult",description:"Result of a single destination push (queued events, optional error)."}).describe("Push operation result"),wt=i.object({ok:i.boolean().describe("True if nothing failed"),event:i.unknown().optional().describe("The processed event"),done:i.record(i.string(),yt).optional().describe("Destinations that processed successfully"),queued:i.record(i.string(),yt).optional().describe("Destinations that queued events"),failed:i.record(i.string(),yt).optional().describe("Destinations that failed to process")}).meta({id:"DestinationResult",title:"Destination.Result",description:"Overall push result aggregated across all destinations (done/queued/failed maps)."}).describe("Push result with destination outcomes"),kt=i.array(i.tuple([ee,i.unknown()])).meta({id:"DestinationDLQ",title:"Destination.DLQ",description:"Dead-letter queue: list of [event, error] tuples."}).describe("Dead letter queue: [(event, error), ...]"),Ct=o(rt),xt=o(st),jt=o(ct),Et=o(lt),Ot=o(ft),Pt=o(gt),$t=o(wt),Dt={};t(Dt,{CommandTypeSchema:()=>It,ConfigSchema:()=>At,DestinationsSchema:()=>Ft,InitConfigSchema:()=>Rt,InstanceSchema:()=>zt,PushContextSchema:()=>Jt,SessionDataSchema:()=>Tt,SourcesSchema:()=>Mt,commandTypeJsonSchema:()=>Nt,configJsonSchema:()=>Lt,initConfigJsonSchema:()=>_t,instanceJsonSchema:()=>Ut,pushContextJsonSchema:()=>Wt,sessionDataJsonSchema:()=>qt});var It=i.union([i.enum(["action","config","consent","context","destination","elb","globals","hook","init","link","run","user","walker"]),i.string()]).meta({id:"CollectorCommandType",title:"Collector.CommandType",description:"Collector command type identifier (standard or extension string)."}).describe("Collector command type: standard commands or custom string for extensions"),At=i.object({run:i.boolean().describe("Whether to run collector automatically on initialization").optional(),globalsStatic:B.describe("Static global properties that persist across collector runs"),sessionStatic:i.record(i.string(),i.unknown()).meta({id:"CollectorSessionStatic",title:"Collector.SessionStatic",description:"Static session data that persists across collector runs."}).describe("Static session data that persists across collector runs"),logger:ot.optional().describe("Logger configuration (level, handler)"),queueMax:i.number().optional().describe("Maximum events retained in collector.queue (late-registration replay). FIFO drop on overflow. Default 1000."),name:i.string().optional().describe("Flow name; keys this flow's entry in event.source.release and the observer flowId."),release:i.string().optional().describe("Config release id stamped into event.source.release for this flow."),next:Ue.optional().describe("Collector chain: runs once per completed event before the destination fan-out. A stop drops the event for every destination.")}).meta({id:"CollectorConfig",title:"Collector.Config",description:"Core collector configuration (globals/session statics, logger, buffer bounds)."}).describe("Core collector configuration"),Tt=B.and(i.object({isStart:i.boolean().describe("Whether this is a new session start"),storage:i.boolean().describe("Whether storage is available"),id:c.describe("Session identifier").optional(),start:l.describe("Session start timestamp").optional(),marketing:i.literal(!0).optional().describe("Marketing attribution flag"),updated:l.describe("Last update timestamp").optional(),isNew:i.boolean().describe("Whether this is a new session").optional(),device:c.describe("Device identifier").optional(),count:d.describe("Event count in session").optional(),runs:d.describe("Number of runs").optional()})).meta({id:"CollectorSessionData",title:"Collector.SessionData",description:"Session state and tracking data."}).describe("Session state and tracking data"),Rt=At.partial().extend({consent:Z.optional().describe("Initial consent state"),user:G.optional().describe("Initial user data"),globals:B.optional().describe("Initial global properties"),sources:i.unknown().meta({id:"CollectorInitSources",title:"Source.InitSources",description:"Source configurations map (id → InitSource)."}).optional().describe("Source configurations"),destinations:i.unknown().meta({id:"CollectorInitDestinations",title:"Destination.InitDestinations",description:"Destination configurations map (id → Init)."}).optional().describe("Destination configurations"),transformers:i.unknown().meta({id:"CollectorInitTransformers",title:"Transformer.Configs",description:"Transformer configurations map (id → Config)."}).optional().describe("Transformer configurations"),stores:i.unknown().meta({id:"CollectorInitStores",title:"Store.Configs",description:"Store configurations map (id → Config)."}).optional().describe("Store configurations"),custom:B.optional().describe("Initial custom implementation-specific properties"),hooks:i.unknown().meta({id:"CollectorHooks",title:"Collector.Hooks",description:"Pipeline observation hooks."}).optional().describe("Pipeline observation hooks"),observe:i.union([i.object({url:i.string().describe("Observer base URL"),binding:i.string().describe("Public project binding the web credential must match")}),i.object({url:i.string().describe("Observer base URL"),sessionId:i.string().describe("Session id the runtime posts under"),token:i.string().describe("Ingest bearer token"),level:i.enum(["off","standard","trace"]).optional().describe("Telemetry level"),sample:i.number().optional().describe("Deterministic sample fraction in [0, 1]")})]).meta({id:"CollectorObserve",title:"Observe",description:"Observation session connect config: web arm (url + binding) or server arm (url + sessionId + token)."}).optional().describe("Observation session connect config"),observers:i.unknown().meta({id:"CollectorObservers",title:"Collector.Observers",description:"Caller-supplied advisory observer functions (runtime objects)."}).optional().describe("Caller-supplied advisory observer functions")}).meta({id:"CollectorInitConfig",title:"Collector.InitConfig",description:"Collector initialization configuration with initial state (consent, user, globals, components, hooks)."}).describe("Collector initialization configuration with initial state"),Jt=i.object({mapping:ke.optional().describe("Source-level mapping configuration")}).meta({id:"CollectorPushContext",title:"Collector.PushContext",description:"Push context with optional source-level mapping."}).describe("Push context with optional source mapping"),Mt=i.record(i.string(),i.unknown()).meta({id:"CollectorSources",title:"Collector.Sources",description:"Map of source IDs to runtime source instances."}).describe("Map of source IDs to source instances"),Ft=i.record(i.string(),i.unknown()).meta({id:"CollectorDestinations",title:"Collector.Destinations",description:"Map of destination IDs to runtime destination instances."}).describe("Map of destination IDs to destination instances"),zt=i.object({push:i.unknown().describe("Push function for processing events"),command:i.unknown().describe("Command function for walker commands"),allowed:i.boolean().describe("Whether event processing is allowed"),config:At.describe("Current collector configuration"),consent:Z.describe("Current consent state"),custom:B.describe("Custom implementation-specific properties"),sources:Mt.describe("Registered source instances"),destinations:Ft.describe("Registered destination instances"),globals:B.describe("Current global properties"),hooks:i.unknown().describe("Lifecycle hook functions"),on:i.unknown().describe("Event lifecycle configuration"),queue:i.array(ee).describe("Queued events awaiting processing"),round:i.number().describe("Collector run count (increments with each run)"),session:i.union([Tt]).describe("Current session state"),timing:i.number().describe("Event processing timing information"),user:G.describe("Current user data")}).meta({id:"CollectorInstance",title:"Collector.Instance",description:"Collector instance (runtime object with push/command + full state and component maps)."}).describe("Collector instance with state and methods"),Nt=o(It),Lt=o(At),qt=o(Tt),_t=o(Rt),Wt=o(Jt),Ut=o(zt),Bt={};t(Bt,{BaseEnvSchema:()=>Ht,ConfigSchema:()=>Vt,InitSchema:()=>Kt,InitSourceSchema:()=>Qt,InitSourcesSchema:()=>Yt,InstanceSchema:()=>Gt,PartialConfigSchema:()=>Zt,baseEnvJsonSchema:()=>Xt,configJsonSchema:()=>en,initSourceJsonSchema:()=>on,initSourcesJsonSchema:()=>rn,instanceJsonSchema:()=>nn,partialConfigJsonSchema:()=>tn});var Ht=i.object({push:i.unknown().meta({id:"SourcePushFn",title:"Source.PushFn",description:"Collector push function passed to the source via dependency injection."}).describe("Collector push function"),command:i.unknown().meta({id:"SourceCommandFn",title:"Source.CommandFn",description:"Collector command function passed to the source."}).describe("Collector command function"),sources:i.unknown().optional().describe("Map of registered source instances"),elb:i.unknown().meta({id:"ElbFn",title:"Elb.Fn",description:"Public `elb(...)` API function alias for collector.push."}).describe("Public API function (alias for collector.push)")}).catchall(i.unknown()).meta({id:"SourceBaseEnv",title:"Source.BaseEnv",description:"Base environment for source dependency injection; platform-specific sources extend this."}).describe("Base environment for dependency injection - platform-specific sources extend this"),Vt=ke.extend({settings:i.any().meta({id:"SourceSettings",title:"Source.Settings",description:"Implementation-specific configuration (source-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.any().meta({id:"SourceCredentials",title:"Source.Credentials",description:"Optional credentials slot (source-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (source-defined shape)").optional(),env:Ht.optional().describe("Environment dependencies (platform-specific)"),id:c.describe("Source identifier (defaults to source key)").optional(),primary:i.boolean().describe("Mark as primary (only one can be primary)").optional(),require:i.array(i.string()).optional().describe('Defer source initialization until these collector events fire (e.g., ["consent"])'),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),async:i.union([i.boolean(),i.record(i.string(),i.boolean())]).optional().describe('Respond-first acknowledgement for response-producing server sources. When true the source responds 2xx ("accepted") before the event is delivered; when false it waits for delivery to settle and the response reflects the outcome. A record configures this per source-defined key: the express source keys it by HTTP method (GET/POST) and defaults to { GET: false, POST: true }. Browser/dataLayer sources have no HTTP response to defer and ignore it. A 2xx means accepted, not delivered. Defaults are per source type.'),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during source registration (boolean enables defaults, object configures specifics)"),ingest:i.union([ue,fe]).optional().describe("Ingest metadata extraction mapping. Extracts values from raw request objects (Express req, Lambda event) using mapping syntax."),disabled:i.boolean().describe("Completely skip this source (no init, no event capture)").optional(),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this source"),init:i.boolean().optional().describe("Init lifecycle flag set by collector to true after Instance.init() runs")}).meta({id:"SourceConfig",title:"Source.Config",description:"Source configuration with mapping, environment, and lifecycle hooks."}).describe("Source configuration with mapping and environment"),Zt=Vt.partial().meta({id:"SourcePartialConfig",title:"Source.PartialConfig",description:"Partial source configuration with all fields optional."}).describe("Partial source configuration with all fields optional"),Gt=i.object({type:i.string().describe('Source type identifier (e.g., "browser", "dataLayer")'),config:Vt.describe("Current source configuration"),push:i.any().meta({id:"SourceInstancePushFn",title:"Source.PushFn",description:"Push function — THE HANDLER (flexible signature for platform compatibility)."}).describe("Push function - THE HANDLER (flexible signature for platform compatibility)"),destroy:i.any().meta({id:"SourceDestroyFn",title:"Source.DestroyFn",description:"Cleanup function called when the source is removed."}).optional().describe("Cleanup function called when source is removed"),on:i.unknown().optional().describe("Lifecycle hook function for event types")}).meta({id:"SourceInstance",title:"Source.Instance",description:"Source instance (runtime object with push handler and lifecycle methods)."}).describe("Source instance with push handler and lifecycle methods"),Kt=i.any().meta({id:"SourceInit",title:"Source.Init",description:"Source initialization function: (config, env) => Instance | Promise<Instance>."}).describe("Source initialization function: (config, env) => Instance | Promise<Instance>"),Qt=i.object({code:Kt.describe("Source initialization function"),config:Zt.optional().describe("Partial configuration overrides"),env:Ht.partial().optional().describe("Partial environment overrides"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this source"),primary:i.boolean().optional().describe("Mark as primary source (only one can be primary)")}).meta({id:"SourceInitSource",title:"Source.InitSource",description:"Source initialization bundle (init function + config + env + primary flag)."}).describe("Source initialization configuration"),Yt=i.record(i.string(),Qt).meta({id:"SourceInitSources",title:"Source.InitSources",description:"Map of source IDs to initialization configurations."}).describe("Map of source IDs to initialization configurations"),Xt=o(Ht),en=o(Vt),tn=o(Zt),nn=o(Gt),on=o(Qt),rn=o(Yt),sn={};t(sn,{ConfigSchema:()=>an,PartialConfigSchema:()=>cn,configJsonSchema:()=>ln,partialConfigJsonSchema:()=>dn});var an=i.object({settings:i.any().meta({id:"TransformerSettings",title:"Transformer.Settings",description:"Implementation-specific configuration (transformer-defined shape)."}).describe("Implementation-specific configuration").optional(),env:i.any().meta({id:"TransformerEnv",title:"Transformer.Env",description:"Environment dependencies (transformer-defined shape)."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Transformer instance identifier (defaults to transformer key)").optional(),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),before:Ue.optional().describe("Pre-transformer chain that runs before this transformer pushes"),next:Ue.optional().describe("Graph wiring to the next transformer in the chain"),cache:Ve.optional().describe("Step-level cache configuration for this transformer"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this transformer"),init:i.boolean().describe("Whether to initialize immediately").optional(),disabled:i.boolean().describe("Completely skip this transformer in chains").optional(),mock:i.unknown().meta({id:"TransformerMock",title:"Transformer.Mock",description:"Return this value instead of calling push(). Dev/testing only."}).optional().describe("Return this value instead of calling push(). Global mock for all chains. Dev/testing only."),chainMocks:i.record(i.string(),i.unknown().meta({id:"TransformerChainMock",title:"Transformer.ChainMock",description:"Chain-path-specific mock value. Dev/testing only."})).optional().describe("Path-specific mock values keyed by chain path. Takes precedence over global mock. Dev/testing only."),mapping:ke.optional().describe("Declarative event-to-event mapping applied when this transformer step has no code. At this position, only event-mutating fields apply (policy, mapping[].policy, mapping[].name, mapping[].ignore, mapping[].consent, include); vendor-payload fields are ignored.")}).strict().meta({id:"TransformerConfig",title:"Transformer.Config",description:"Transformer configuration (settings, env, chain wiring, cache, mocks)."}).describe("Transformer configuration"),cn=an.partial().meta({id:"TransformerPartialConfig",title:"Transformer.PartialConfig",description:"Partial transformer configuration with all fields optional."}).describe("Partial transformer configuration with all fields optional"),ln=o(an),dn=o(cn),pn={};t(pn,{ConfigSchema:()=>un,PartialConfigSchema:()=>fn,configJsonSchema:()=>mn,partialConfigJsonSchema:()=>gn});var un=i.object({settings:i.unknown().meta({id:"StoreSettings",title:"Store.Settings",description:"Implementation-specific configuration (store-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.unknown().meta({id:"StoreCredentials",title:"Store.Credentials",description:"Optional credentials slot (store-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (store-defined shape)").optional(),env:i.unknown().meta({id:"StoreEnv",title:"Store.Env",description:"Environment dependencies (store-defined shape)."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Store instance identifier (defaults to store key)").optional(),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during store registration (boolean enables defaults, object configures specifics)"),file:i.boolean().optional().describe("Persist values as raw bytes (byte-exact), bypassing the structured codec. Default false (structured). Set true only on byte-native stores for asset serving; sheets rejects it.")}).meta({id:"StoreConfig",title:"Store.Config",description:"Store configuration (settings, env, logger): key-value infrastructure component."}).describe("Store configuration"),fn=un.partial().meta({id:"StorePartialConfig",title:"Store.PartialConfig",description:"Partial store configuration with all fields optional."}).describe("Partial store configuration with all fields optional"),mn=o(un),gn=o(fn),hn={};t(hn,{BundlePackageSchema:()=>Sn,BundleSchema:()=>wn,CodeSchema:()=>kn,ConfigSchema:()=>Nn,ContractActionsSchema:()=>Rn,ContractEventsSchema:()=>Jn,ContractRuleSchema:()=>Mn,ContractSchema:()=>Fn,ContractSchemaEntry:()=>Tn,DestinationSchema:()=>In,FlowSchema:()=>Ln,JsonSchema:()=>qn,JsonSchemaSchema:()=>En,ObserveSchema:()=>zn,SettingsSchema:()=>vn,SourceSchema:()=>$n,StepExampleSchema:()=>xn,StepExamplesSchema:()=>jn,StoreSchema:()=>An,TransformerSchema:()=>Dn,TriggerDescriptorSchema:()=>Cn,ValidateEventsSchema:()=>On,VariablesSchema:()=>bn,configJsonSchema:()=>Hn,contractJsonSchema:()=>ei,contractRuleJsonSchema:()=>Xn,destinationJsonSchema:()=>Kn,flowConfigJsonSchema:()=>Zn,flowJsonSchema:()=>Vn,parseConfig:()=>_n,parseFlow:()=>Un,safeParseConfig:()=>Wn,safeParseFlow:()=>Bn,sourceJsonSchema:()=>Gn,storeJsonSchema:()=>Yn,transformerJsonSchema:()=>Qn,validateEventsJsonSchema:()=>ti});var bn=i.record(i.string(),i.unknown()).meta({id:"FlowVariables",title:"Flow.Variables",description:"Reusable values referenced via $var.name (with optional deep paths). Whole-string refs preserve native type; inline interpolation requires scalars."}),vn=i.record(i.string(),i.unknown()).meta({id:"FlowSettings",title:"Flow.Settings",description:"Free-form key-value settings consumed by the platform runtime."}).describe("Free-form platform settings bag"),yn=/^(@[a-z0-9\-~][a-z0-9\-._~]*\/)?[a-z0-9\-~][a-z0-9\-._~]*$/,Sn=i.object({version:i.string().optional(),imports:i.array(i.string()).optional(),path:i.string().optional()}).meta({id:"FlowBundlePackage",title:"Flow.BundlePackage",description:"Per-package bundle spec (version / imports / local path)."}),wn=i.object({packages:i.record(i.string().regex(yn,"Invalid npm package name"),Sn).optional().describe("NPM packages to bundle, keyed by package name"),overrides:i.record(i.string().regex(yn,"Invalid npm package name"),i.string().min(1,"Override version cannot be empty")).optional().describe("Transitive dependency version pins"),traceInclude:i.array(i.string()).optional().describe("Extra paths or globs the bundler must include in the trace output (server flows only)"),env:i.record(i.string(),i.string()).optional().describe("Declared build-time values for web $env references (inlined into public bundles, never secrets)")}).strict().meta({id:"FlowBundle",title:"Flow.Bundle",description:"Bundle configuration (packages + overrides + traceInclude + env)."}).describe("Bundle configuration (packages + overrides + traceInclude + env)"),kn=i.object({push:i.string().min(1,"Push function cannot be empty").describe('JavaScript function for processing events. Must start with "$code:" prefix.'),type:i.string().optional().describe("Optional type identifier for the inline instance"),init:i.string().optional().describe("Optional initialization function. Use $code: prefix for inline JavaScript.")}).meta({id:"FlowCode",title:"Flow.Code",description:"Inline code block (object form) for custom sources / transformers / destinations / stores. Use `import` on the step to select a named export from a package."}).describe("Inline code for custom components (object form)"),Cn=i.object({type:i.string().optional().describe("Trigger mechanism (e.g., click, POST, load)"),options:i.unknown().optional().describe("Mechanism-specific options")}).meta({id:"TriggerDescriptor",title:"Trigger.Descriptor",description:"Source trigger metadata (mechanism + options) used by step examples."}),xn=i.object({title:i.string().optional().describe("Human-readable title (overrides default heading)"),description:i.string().optional().describe("Human-readable description"),public:i.boolean().optional().describe("Whether this example is shown in docs/UI/MCP default output (default: true). Set false for test-only fixtures."),in:i.unknown().optional().describe("Input to the step"),trigger:Cn.optional().describe("Source trigger metadata"),mapping:i.unknown().optional().describe("Mapping configuration"),out:i.unknown().optional().describe("Expected output from the step"),command:i.enum(["config","consent","user","run"]).optional().describe("Invoke elb('walker <command>', in) instead of pushing in as an event")}).meta({id:"FlowStepExample",title:"Flow.StepExample",description:"Named example with input/output pair used for step testing."}).describe("Named example with input/output pair"),jn=i.record(i.string(),xn).meta({id:"FlowStepExamples",title:"Flow.StepExamples",description:"Named step examples keyed by scenario name."}).describe("Named step examples for testing and documentation"),En=i.record(i.string(),i.unknown()).meta({id:"JsonSchema",title:"JsonSchema",description:"Structural JSON Schema fragment (Record<string, unknown>)"}),On=i.record(i.string(),i.record(i.string(),En)).meta({id:"ValidateEvents",title:"ValidateEvents",description:"Entity-action keyed JSON Schemas"}).describe("Entity-action keyed JSON Schemas");function Pn(e,t){void 0!==e.import&&(void 0!==e.code&&t.addIssue({code:"custom",message:"`import` cannot be combined with inline `code`",path:["import"]}),void 0===e.package&&t.addIssue({code:"custom",message:"`import` requires `package`",path:["import"]}))}var $n=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/web-source-browser@2.0.0")'),code:kn.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during source registration (boolean enables defaults, object configures specifics)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set, run before the collector receives the event. Takes precedence over a step-level state.")}).meta({id:"FlowSourceConfig",title:"Source.Config",description:"Source-specific configuration object (Source.Config)."}).optional().describe("Source-specific configuration object"),env:i.unknown().meta({id:"FlowSourceEnv",title:"Source.BaseEnv",description:"Source environment configuration (Source.BaseEnv overrides)."}).optional().describe("Source environment configuration"),primary:i.boolean().optional().describe("Mark as primary source (provides main elb). Only one source should be primary."),variables:bn.optional().describe("Source-level variables (highest priority in cascade)"),next:Ue.optional().describe("Pre-collector transformer chain. String, string[], or Route[] for conditional routing on ingest and event data."),before:Ue.optional().describe("Pre-source transformer chain (consent-exempt). Handles transport-level preprocessing."),examples:jn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ve.optional().describe("Cache configuration for this source (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this source. Paths resolve against { event, ingest }.")}).strict().meta({id:"FlowSource",title:"Flow.Source",description:"Source package reference with configuration, env, chains, and examples."}).describe("Source package reference with configuration").superRefine(Pn),Dn=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/transformer-enricher@1.0.0")'),code:kn.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.unknown().meta({id:"FlowTransformerConfig",title:"Transformer.Config",description:"Transformer-specific configuration object."}).optional().describe("Transformer-specific configuration object"),env:i.unknown().meta({id:"FlowTransformerEnv",title:"Transformer.Env",description:"Transformer environment configuration."}).optional().describe("Transformer environment configuration"),before:Ue.optional().describe("Pre-transformer chain. Runs before this transformer push function."),next:Ue.optional().describe("Next transformer in chain. String, string[], or Route[] for conditional routing."),variables:bn.optional().describe("Transformer-level variables (highest priority in cascade)"),examples:jn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ve.optional().describe("Cache configuration for this transformer (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this transformer. Paths resolve against { event, ingest }."),mapping:i.unknown().optional().describe("Event mapping for a code-free transformer. The collector applies it to the event; a rule with ignore: true drops it.")}).meta({id:"FlowTransformer",title:"Flow.Transformer",description:"Transformer package reference with configuration, env, chains, and cache."}).describe("Transformer package reference with configuration").superRefine(Pn),In=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/web-destination-gtag@2.0.0")'),code:kn.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during destination registration (boolean enables defaults, object configures specifics)")}).meta({id:"FlowDestinationConfig",title:"Destination.Config",description:"Destination-specific configuration object."}).optional().describe("Destination-specific configuration object"),env:i.unknown().meta({id:"FlowDestinationEnv",title:"Destination.Env",description:"Destination environment configuration."}).optional().describe("Destination environment configuration"),variables:bn.optional().describe("Destination-level variables (highest priority in cascade)"),before:Ue.optional().describe("Transformer chain run for this destination only, before it receives the event. String, string[], or a Route for conditional routing."),next:Ue.optional().describe("Post-push transformer chain. Push response available at context.ingest._response."),examples:jn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ve.optional().describe("Cache configuration for this destination (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this destination. Paths resolve against { event, ingest }.")}).meta({id:"FlowDestination",title:"Flow.Destination",description:"Destination package reference with configuration, env, chains, and cache."}).describe("Destination package reference with configuration").superRefine(Pn),An=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe("Store package specifier with optional version"),code:kn.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during store registration (boolean enables defaults, object configures specifics)")}).meta({id:"FlowStoreConfig",title:"Store.Config",description:"Store-specific configuration object."}).optional().describe("Store-specific configuration object"),env:i.unknown().meta({id:"FlowStoreEnv",title:"Store.Env",description:"Store environment configuration."}).optional().describe("Store environment configuration"),cache:Ge.optional().describe("Cache configuration for this store (TTL-only rules, optional recursive `cache.store`)"),variables:bn.optional().describe("Store-level variables (highest priority in cascade)"),examples:jn.optional().describe("Named step examples for testing and documentation (stripped during bundling)")}).meta({id:"FlowStore",title:"Flow.Store",description:"Store package reference with configuration, env, cache, and examples."}).describe("Store package reference with configuration").superRefine(Pn),Tn=i.record(i.string(),i.unknown()).meta({id:"FlowContractSchemaEntry",title:"Flow.ContractSchemaEntry",description:"JSON Schema object for event validation with description/examples annotations."}).describe("JSON Schema object for event validation with description/examples annotations"),Rn=i.record(i.string(),Tn).meta({id:"FlowContractActions",title:"Flow.ContractActions",description:"Action-level contract entries keyed by action name."}).describe("Action-level contract entries"),Jn=i.record(i.string(),Rn).meta({id:"FlowContractEvents",title:"Flow.ContractEvents",description:"Entity-action event schemas (entity → action → schema)."}).describe("Entity-action event schemas"),Mn=i.object({extend:i.string().optional(),tagging:i.number().optional(),description:i.string().optional(),events:On.optional(),schema:En.optional()}).meta({id:"ContractRule",title:"Flow.ContractRule",description:"Named contract entry"}),Fn=i.record(i.string(),Mn).meta({id:"FlowContract",title:"Flow.Contract",description:"Named contracts map with optional extend inheritance."}).describe("Named contracts with optional extend inheritance"),zn=i.object({level:i.enum(["off","standard","trace"]).optional().describe("Managed-telemetry verbosity. 'off' disables telemetry entirely, 'standard' emits structural records, 'trace' emits full payloads."),sample:i.number().min(0).max(1).optional().describe("Deterministic sample fraction in [0, 1]. Defaults to 1."),url:i.string().min(1).optional().describe("Observer base URL for the web connect form. Public, safe to commit. Paired with binding."),binding:i.string().min(1).optional().describe("Public project binding a web observe credential must match. Paired with url; public, safe to commit.")}).meta({id:"FlowObserve",title:"Flow.Observe",description:"Observability configuration: public web connect pair (url + binding) and managed-telemetry knobs (level + sample)."}).describe("Observability configuration block"),Nn=i.object({platform:i.enum(["web","server"]).describe("Platform identity for this flow. Drives bundle target/format."),url:i.string().min(1).optional().describe("Public URL where this flow is reachable (for cross-flow $flow.X.url references)."),settings:vn.optional().describe("Free-form key-value settings consumed by the platform runtime."),bundle:wn.optional().describe("Bundle configuration: NPM packages, transitive dependency overrides."),observe:zn.optional().describe("Observability configuration: public web connect pair, managed-telemetry level and sample.")}).meta({id:"FlowConfig",title:"Flow.Config",description:"Per-flow configuration block: platform identity, optional public URL, settings, bundle, observe."}).describe("Per-flow configuration block"),Ln=i.object({config:Nn.optional().describe("Per-flow configuration: platform, url, settings, bundle."),sources:i.record(i.string(),$n).optional().describe("Source configurations (data capture) keyed by unique identifier"),destinations:i.record(i.string(),In).optional().describe("Destination configurations (data output) keyed by unique identifier"),transformers:i.record(i.string(),Dn).optional().describe("Transformer configurations (event transformation) keyed by unique identifier"),stores:i.record(i.string(),An).optional().describe("Store configurations (key-value storage) keyed by unique identifier"),collector:i.looseObject({next:Ue.optional().describe("Collector chain: runs once per completed event before the destination fan-out. A stop drops the event for every destination.")}).meta({id:"FlowCollector",title:"Collector.InitConfig",description:"Collector configuration for event processing (Collector.InitConfig)."}).optional().describe("Collector configuration for event processing (uses Collector.InitConfig)"),variables:bn.optional().describe("Flow-level variables (override root variables, overridden by source/destination variables)")}).meta({id:"Flow",title:"Flow",description:"Single flow definition (one deployment target): config, sources, destinations, transformers, stores, collector."}).describe("Single flow definition for one deployment target"),qn=i.object({version:i.literal(4).describe("Configuration schema version (v4, current)."),$schema:i.string().url("Schema URL must be a valid URL").optional().describe('JSON Schema reference for IDE validation (e.g., "https://walkeros.io/schema/flow/v4.json")'),include:i.array(i.string()).optional().describe("Folders to include in the bundle output"),variables:bn.optional().describe("Shared variables for interpolation across all flows (use $var.name syntax, deep paths supported)"),contract:Fn.optional().describe("Named contracts with extend inheritance and dot-path references"),flows:i.record(i.string(),Ln).refine(e=>Object.keys(e).length>0,{message:"At least one flow is required"}).describe("Named flow configurations (e.g., production, staging, development)")}).meta({id:"FlowJson",title:"Flow.Json",description:"walkerOS root configuration (walkeros.config.json) v4: version, variables, contract, named flows."}).describe("walkerOS root configuration (walkeros.config.json)");function _n(e){return qn.parse(e)}function Wn(e){return qn.safeParse(e)}function Un(e){return Ln.parse(e)}function Bn(e){return Ln.safeParse(e)}var Hn=i.toJSONSchema(qn,{target:"draft-7"}),Vn=o(Ln),Zn=o(Nn),Gn=o($n),Kn=o(In),Qn=o(Dn),Yn=o(An),Xn=o(Mn),ei=o(Fn),ti=o(On);import{z as ni}from"zod";var ii=ni.object({lang:ni.string().optional().describe("Language identifier (e.g. json, sql, bash, typescript)"),code:ni.string().describe("Code snippet")}),oi=ni.object({text:ni.string().describe("Short actionable hint text focused on walkerOS usage"),code:ni.array(ii).optional().describe("Optional code snippets")}),ri=ni.record(ni.string(),oi).describe("Keyed hints for AI consumption — lightweight context beyond schemas and examples"),si=i.object({param:i.string().describe("Lowercase URL parameter name. Match is case-insensitive on lookup."),platform:i.string().describe("Canonical platform identifier (lowercase, kebab-case).")}),ai=i.object({client_email:i.string().describe("Service account client email"),private_key:i.string().describe("Service account private key (PEM)"),project_id:i.string().optional().describe("GCP project id (derived from environment when omitted)")}).meta({id:"ServiceAccount",title:"ServiceAccount",description:"Google-style service account credentials (client_email, private_key, optional project_id)."}).describe("Google-style service account credentials"),ci=i.union([i.string(),ai]).meta({id:"Credentials",title:"Credentials",description:"Service account credentials: a JSON string (back it with a managed secret via $secret.NAME) or a parsed service account object."}).describe("Service account credentials: a JSON string (back it with a managed secret via $secret.NAME) or a parsed object"),li=o(ci);function di(e){return Array.isArray(e)}function pi(e){return"object"==typeof e&&null!==e&&!di(e)&&"[object Object]"===Object.prototype.toString.call(e)}function ui(e,t="",n){const i=t.split(".");let o=e;for(let e=0;e<i.length;e++){const t=i[e];if("*"===t&&di(o)){const t=i.slice(e+1).join("."),r=[];for(const e of o){const i=ui(e,t,n);r.push(i)}return r}if(o=pi(o)||di(o)?o[t]:void 0,void 0===o)break}return void 0!==o?o:n}function fi(e){if(void 0===e||"*"===e)return()=>!0;if("and"in e){const t=e.and.map(fi);return e=>t.every(t=>t(e))}if("or"in e){const t=e.or.map(fi);return e=>t.some(t=>t(e))}return function(e){const{key:t,operator:n,value:i,not:o}=e,r=function(e,t){switch(e){case"eq":return e=>String(e??"")===t;case"contains":return e=>String(e??"").includes(t);case"prefix":return e=>String(e??"").startsWith(t);case"suffix":return e=>String(e??"").endsWith(t);case"regex":{const e=new RegExp(t);return t=>e.test(String(t??""))}case"gt":{const e=Number(t);return t=>Number(t)>e}case"lt":{const e=Number(t);return t=>Number(t)<e}case"exists":return e=>null!=e}}(n,i);return e=>{const n=ui(e,t),i=r(n);return o?!i:i}}(e)}function mi(e){return Array.isArray(e)&&e.length>0&&e.every(e=>function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&("match"in e||"next"in e||"one"in e||"many"in e||"stop"in e)}(e))}var gi=()=>!0;function hi(e,t){return{kind:t?"sequence":"next",path:e}}function bi(e,t){return t?{...e,outer:t}:e}function vi(e,t,n,i){return bi(n?{kind:e,path:t,match:n}:{kind:e,path:t,catchAll:!0},i)}function yi(e,t,n,i){return 0===e.length?{type:"chain",value:[],label:bi({kind:n,path:t},i)}:{type:n,routes:Si(e,t,n,i)}}function Si(e,t,n,i){return e.map((e,o)=>{const r=[...t,o];if("string"==typeof e||Array.isArray(e)){const t=vi(n,r,void 0,i);return{match:gi,next:ki(e,r,t)??{type:"chain",value:[],label:t}}}const s=vi(n,r,e.match,i);return{match:e.match?fi(e.match):gi,source:e.match,next:wi(e,r,s,!1,!0)??{type:"chain",value:[],label:s}}})}function wi(e,t,n,i,o){const r=o?void 0:e.match,s=r?bi({kind:"next",path:t,match:r},n):n??hi(t,i),a=r?s:n;let c;return!0===e.stop?c={type:"stop",label:s}:void 0!==e.one?c=yi(e.one,[...t,"one"],"one",a):void 0!==e.many?c=yi(e.many,[...t,"many"],"many",a):void 0!==e.next&&(c=ki(e.next,[...t,"next"],a)),r?{type:"gate",match:fi(r),source:r,next:c??{type:"chain",value:[],label:s}}:void 0===c&&e.match?{type:"chain",value:[],label:s}:c}function ki(e,t=[],n,i=!1){if(null!=e){if("string"==typeof e)return{type:"static",value:e,label:n??hi(t,i)};if(Array.isArray(e)){if(0===e.length)return;if(mi(e))return{type:"one",routes:Si(e,t,"one",n)};const o=[];for(const t of e)"string"==typeof t&&o.push(t);if(o.length===e.length)return{type:"chain",value:o,label:n??hi(t,i)};const r=[];if(e.forEach((e,i)=>{const o=ki(e,[...t,i],n,!0);void 0!==o&&r.push(o)}),0===r.length)return;return{type:"sequence",value:r}}return wi(e,t,n,i,!1)}}var Ci=new WeakMap;function xi(e,t,n){return n?{type:"continuation",segments:e,at:t,tail:n}:{type:"continuation",segments:e,at:t}}function ji(e){if(null==e)return;if(function(e){return"object"==typeof e&&!Array.isArray(e)&&"type"in e&&"continuation"===e.type}(e))return e;const t=function(e){if(null==e)return;if("object"!=typeof e)return ki(e);const t=Ci.get(e);if(t)return t;const n=ki(e);return n&&Ci.set(e,n),n}(e);return t?xi([t],0,void 0):void 0}function Ei(e,t,n){const i=[];let o=e;for(;o;){if(o.at>=o.segments.length){o=o.tail;continue}const e=o.segments[o.at],r=xi(o.segments,o.at+1,o.tail);if("static"===e.type){i.push(e.value),n&&n(e),o=r;continue}if("chain"===e.type){i.push(...e.value),n&&n(e),o=r;continue}if("sequence"===e.type){o=xi(e.value,0,r);continue}if(i.length>0)return{ids:i,then:o};if("stop"===e.type)return n&&n(e),{ids:[],stop:!0};if("gate"===e.type){o=t.gate(e)?xi([e.next],0,r):r;continue}if("one"===e.type){const n=e.routes.length>0?t.one(e.routes):-1;o=n>=0?xi([e.routes[n].next],0,r):r;continue}const s=e.routes.length>0?t.many(e.routes):[];if(0!==s.length){if(1!==s.length)return{ids:[],forks:s.map(t=>xi([e.routes[t].next],0,r))};o=xi([e.routes[s[0]].next],0,r)}else o=r}return{ids:i}}function Oi(e,t){return Ei(ji(e),function(e){return{gate:t=>t.match(e),one:t=>t.findIndex(t=>t.match(e)),many:t=>{const n=[];return t.forEach((t,i)=>{t.match(e)&&n.push(i)}),n}}}(t))}function Pi(e){return null==e?[]:[{route:e,ancestry:[]}]}function $i(e,t,n){if(e.at>=e.ids.length)return{rest:t};const i=e.ids[e.at],o=e.at+1<e.ids.length?[{ids:e.ids,at:e.at+1,ancestry:e.ancestry},...t]:t;if(e.ancestry.includes(i))return{rest:o};const r=[...e.ancestry,i],s=n[i],a=s?s.config.next:void 0;return{id:i,ancestry:r,rest:void 0===a?o:[{route:a,ancestry:r},...o]}}function Di(e,t,n){if(e.stop)return t.length>0?{kind:"stop",owner:t[t.length-1]}:{kind:"stop"};if(e.forks)return{kind:"fork",branches:e.forks.map(e=>[{route:e,ancestry:t},...n])};const i=[];return e.ids.length>0&&i.push({ids:e.ids,at:0,ancestry:t}),e.then&&i.push({route:e.then,ancestry:t}),{kind:"stack",stack:[...i,...n]}}function Ii(e,t,n){let i=e;for(;i.length>0;){const[e,...o]=i;if("ids"in e){const t=$i(e,o,n);if(void 0!==t.id)return{kind:"run",id:t.id,rest:t.rest,ancestry:t.ancestry};i=t.rest;continue}const r=Di(Oi(e.route,t),e.ancestry,o);if("stack"!==r.kind)return r;i=r.stack}return{kind:"done"}}function Ai(e,t={}){const n=[],i=new Map,o=new Set,r=new WeakMap,s=new WeakMap;let a=0;const c=e=>{let t=s.get(e);return void 0===t&&(t=++a,s.set(e,t)),t},l=e=>e.length>0?e[e.length-1]:void 0,d=(e,t,o,r,s)=>{const a=void 0===s,c=`${e??""}|${o}|${r??""}|${s??""}`,l=i.get(c);if(l)return l;const d={targets:[],kind:t.kind,path:t.path};return void 0!==e&&(d.from=e),t.match&&(d.match=t.match),t.catchAll&&(d.catchAll=!0),a&&(d.stop=!0),void 0!==r&&(d.owner=r),t.outer&&(d.via=function(e){const t=[];for(let n=e.outer;n;n=n.outer){const e={kind:n.kind,path:n.path};n.match&&(e.match=n.match),n.catchAll&&(e.catchAll=!0),t.unshift(e)}return t}(t)),i.set(c,d),n.push(d),d},p=e=>{const t=e.ancestry.join(",");if("ids"in e){const n=r.get(e.ids)??[];return`i${e.ids.join(",")}#${n.map(c).join(",")}@${e.at}/${t}`}const n=e.route;if("string"==typeof n)return`s${n}/${t}`;let i="",o=ji(n);for(;o;)i+=`${c(o.segments)}@${o.at};`,o=o.tail;return`r${i}/${t}`},u=(e,n,i)=>{const s=`${n??""}|${i?`${c(i.node)}:${i.position}`:""}|${e.map(p).join("|")}`;if(o.has(s))return;if(o.add(s),0===e.length)return;const[a,...f]=e;if("ids"in a){const e=$i(a,f,t);if(void 0===e.id)return void u(e.rest,n,i);const o=(r.get(a.ids)??[])[a.at];if(!o)return;let s;if(i&&i.source===o&&i.node.targets[i.position]===n){const t=i.position+1;i.node.targets.length===t&&i.node.targets.push(e.id),s={node:i.node,source:o,position:t}}else{const t=d(n,o.label,c(o),l(a.ancestry),e.id);0===t.targets.length&&t.targets.push(e.id),s={node:t,source:o,position:0}}return void u(e.rest,e.id,s)}const m=l(a.ancestry);for(const e of function(e){const t=[],n=i=>{let o=0;const r=[],s=e=>{let t=0;return o<i.length?t=i[o]:r.push(e),o++,t},a=e=>e.some(e=>void 0===e.source),c=[],l=Ei(e,{gate:()=>0===s(2),one:e=>{const t=e.map((e,t)=>t);return a(e)||t.push(-1),t[s(t.length)]},many:e=>{const t=e.map((e,t)=>t);return a(e)||0===s(2)?t:[]}},e=>c.push(e));t.push({steps:l,visited:c});for(let e=0;e<r.length;e++)for(let t=1;t<r[e];t++){const o=i.slice();for(let t=0;t<e;t++)o.push(0);o.push(t),n(o)}};return n([]),t}(ji(a.route))){const{steps:t}=e,i=[];let o=n;for(const t of e.visited)if("stop"!==t.type)if("static"===t.type)i.push(t),o=t.value;else if(0===t.value.length)d(o,t.label,c(t),m,"");else{for(let e=0;e<t.value.length;e++)i.push(t);o=t.value[t.value.length-1]}else d(n,t.label,c(t),m,void 0);t.ids.length>0&&r.set(t.ids,i);const s=Di(t,a.ancestry,f);if("stop"!==s.kind)if("fork"!==s.kind)u(s.stack,n,void 0);else for(const e of s.branches)u(e,n,void 0)}};return u(Pi(e),void 0,void 0),n}function Ti(e){throw new Error(String(e))}var Ri=new Set(["description","examples","title","$comment"]),Ji=new Set(["additionalItems","additionalProperties","contains","contentSchema","else","if","items","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"]),Mi=new Set(["allOf","anyOf","items","oneOf","prefixItems"]),Fi=new Set(["properties","patternProperties","dependentSchemas","dependentRequired","dependencies","$defs","definitions"]);function zi(e,t){const n=!1!==t?.stripAnnotations,i={},o=new Set;function r(t){if(i[t])return i[t];o.has(t)&&Ti(`Circular extend chain detected: ${[...o,t].join(" → ")}`);const s=e[t];s||Ti(`Contract "${t}" not found`),o.add(t);let a={};if(s.extend){a=function(e,t){const n={};void 0===e.tagging&&void 0===t.tagging||(n.tagging=t.tagging??e.tagging);void 0===e.description&&void 0===t.description||(n.description=t.description??e.description);e.schema&&t.schema?n.schema=Ni(e.schema,t.schema):(e.schema||t.schema)&&(n.schema={...e.schema||t.schema});if(e.events||t.events){const i={},o=new Set([...Object.keys(e.events||{}),...Object.keys(t.events||{})]);for(const n of o){const o=e.events?.[n]||{},r=t.events?.[n]||{},s=new Set([...Object.keys(o),...Object.keys(r)]);i[n]={};for(const e of s){const t=o[e],s=r[e];i[n][e]=t&&s?Ni(t,s):{...t||s}}}n.events=i}return n}(r(s.extend),s)}else a={...s};if(delete a.extend,a.events&&(a.events=function(e){const t={};for(const n of Object.keys(e))if("*"!==n){t[n]={};for(const i of Object.keys(e[n]||{})){let o={};const r=e["*"]?.["*"];r&&(o=Ni(o,r));const s=e["*"]?.[i];s&&"*"!==i&&(o=Ni(o,s));const a=e[n]?.["*"];a&&"*"!==i&&(o=Ni(o,a));const c=e[n]?.[i];c&&(o=Ni(o,c)),t[n][i]=o}}e["*"]&&(t["*"]={...e["*"]});return t}(a.events)),a.events&&n){const e={};for(const[t,n]of Object.entries(a.events)){e[t]={};for(const[i,o]of Object.entries(n))e[t][i]=Li(o)}a.events=e}return o.delete(t),i[t]=a,a}for(const t of Object.keys(e))r(t);return i}function Ni(e,t){const n={...e};for(const i of Object.keys(t)){const o=e[i],r=t[i];"required"===i&&Array.isArray(o)&&Array.isArray(r)?n[i]=[...new Set([...o,...r])]:_i(o)&&_i(r)?n[i]=Ni(o,r):n[i]=r}return n}function Li(e){const t={};for(const[n,i]of Object.entries(e))Ri.has(n)||(Fi.has(n)&&_i(i)?t[n]=qi(i):Mi.has(n)&&Array.isArray(i)?t[n]=i.map(e=>_i(e)?Li(e):e):Ji.has(n)&&_i(i)?t[n]=Li(i):t[n]=i);return t}function qi(e){const t={};for(const[n,i]of Object.entries(e))t[n]=_i(i)?Li(i):i;return t}function _i(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Wi="$code:";function Ui(e,t){let n;try{n=JSON.parse(e)}catch(t){const{line:n,column:i}=function(e,t){if(e instanceof SyntaxError){const n=e.message.match(/position\s+(\d+)/);if(n){return co(t,parseInt(n[1],10))}const i=e.message.match(/line\s+(\d+)\s+column\s+(\d+)/);if(i)return{line:parseInt(i[1],10),column:parseInt(i[2],10)}}return{line:1,column:1}}(t,e);return{valid:!1,errors:[{message:t instanceof Error?t.message:"Invalid JSON",severity:"error",line:n,column:i}],warnings:[]}}const i=[],o=[],r=qn.safeParse(n);if(!r.success)for(const t of r.error.issues){const n=t.path.join("."),o=po(e,t.path);i.push({message:t.message,severity:"error",path:n||"root",...o})}const s=function(e){if(!(wo(e)&&"version"in e&&"flows"in e&&wo(e.flows)))return;const t={},n=[],i=[],o=[],r=[],s=[],a=[];let c;const l=Object.keys(e.flows);ko(t,e.variables),function(e,t){if(!wo(t))return;let n;try{n=zi(t,{stripAnnotations:!1})}catch{return}for(const t of Object.values(n)){const n=t.events;if(wo(n))for(const[t,i]of Object.entries(n)){if(!wo(i))continue;let n=e.find(e=>e.entity===t);n||(n={entity:t,actions:[],properties:{}},e.push(n)),n.properties||(n.properties={});for(const[e,t]of Object.entries(i))n.actions.includes(e)||n.actions.push(e),n.properties[e]=Co(t)}}}(a,e.contract);for(const a of Object.values(e.flows))if(wo(a)){if(!c){const e=a.config;!wo(e)||"web"!==e.platform&&"server"!==e.platform||(c=e.platform)}ko(t,a.variables);for(const e of["sources","destinations","transformers"]){const r="sources"===e?"source":"destinations"===e?"destination":"transformer",l="sources"===e?n:"destinations"===e?i:o;if(wo(a[e]))for(const[n,i]of Object.entries(a[e]))l.push(n),wo(i)&&(ko(t,i.variables),"string"==typeof i.package&&s.push({package:i.package,shortName:n,type:r,platform:c||"web"}))}if(wo(a.stores))for(const[e,n]of Object.entries(a.stores))r.push(e),wo(n)&&ko(t,n.variables)}const d={variables:t,stepNames:{sources:n,destinations:i,transformers:o,stores:r},flowNames:l};c&&(d.platform=c);s.length>0&&(d.packages=s);a.length>0&&(d.contract=a);return d}(n);return s&&(t?.secrets&&(s.secrets=t.secrets),function(e,t,n,i,o){(function(e,t,n){let i;Zi.lastIndex=0;for(;null!==(i=Zi.exec(e));){const t=i[0],o=i[1],r=i[2],s=lo(e,i.index,t.length);n.push({message:`Malformed reference "${t}", use a dot, not a colon: "$${o}.${r}".`,severity:"warning",path:t,...s})}})(e,0,o),function(e,t,n){if(!t.variables)return;const i=/\$var\.(\w+)/g;let o;for(;null!==(o=i.exec(e));)if(!(o[1]in t.variables)){const i=lo(e,o.index,o[0].length);n.push({message:`Unknown variable "$var.${o[1]}". Defined: ${Object.keys(t.variables).join(", ")||"none"}`,severity:"warning",path:`$var.${o[1]}`,...i})}}(e,n,o),function(e,t,n){const i=t.stepNames?.stores??[];let o;Bi.lastIndex=0;for(;null!==(o=Bi.exec(e));)if(!i.includes(o[1])){const t=lo(e,o.index,o[0].length);n.push({message:`Unknown store "$store.${o[1]}". Defined: ${i.join(", ")||"none"}`,severity:"warning",path:`$store.${o[1]}`,...t})}}(e,n,o),function(e,t,n){let i;Hi.lastIndex=0;for(;null!==(i=Hi.exec(e));){const t=i[0],o=i[1],r=i[2],s=lo(e,i.index,t.length);r?n.push({message:`Malformed $env reference "${t}". Use ":" for default values, not "=" (e.g., "$env.${o}:fallback").`,severity:"warning",path:t,...s}):/^[A-Z][A-Z0-9_]*$/.test(o)||n.push({message:`$env.${o} should use UPPER_SNAKE_CASE by convention (e.g., $env.${o.toUpperCase()}).`,severity:"warning",path:t,...s})}}(e,0,o),function(e,t,n){const i=t.flowNames??[];if(0===i.length)return;let o;Vi.lastIndex=0;for(;null!==(o=Vi.exec(e));){const t=o[0],r=o[1];if(!i.includes(r)){const s=lo(e,o.index,t.length);n.push({message:`Unknown flow "$flow.${r}". Defined: ${i.join(", ")}`,severity:"warning",path:t,...s})}}}(e,n,o),function(e,t,n,i,o){const r=n.secrets;if(!wo(t)||!wo(t.flows))return;for(const[n,s]of Object.entries(t.flows)){if(!wo(s))continue;const t=s.config,a=!wo(t)||"web"!==t.platform&&"server"!==t.platform?void 0:t.platform;eo(s,["flows",n],(t,n)=>{if(Xi(n))return;let s;for(Gi.lastIndex=0;null!==(s=Gi.exec(t));){const t=s[0],n=s[1],c=e.indexOf(t),l=-1===c?{line:1,column:1}:lo(e,c,t.length);"web"!==a?r&&!r.includes(n)&&o.push({message:`Unknown secret "$secret.${n}"; not in the project's registered secrets.`,severity:"warning",path:t,...l}):i.push({message:`Secret "$secret.${n}" cannot be used in a web flow: secrets are never sent to the browser; use a server flow.`,severity:"error",path:t,...l})}})}}(e,t,n,i,o),function(e,t,n){eo(t,[],(t,i)=>{if(!t.startsWith(Wi)&&!Xi(i))for(const{prefix:o,regex:r,grammar:s}of Ki){if(!t.includes(o))continue;const a=o.slice(0,-1);let c;if(t.startsWith(o)){if(r.test(t))continue;c=`"${t}" does not match the ${a}.NAME grammar (${s}); it would not resolve. To build a longer string, compose with $var or $env.`}else c=`"${t}" uses ${o} inline. ${o} references resolve only as the whole value; it would ship as literal text. Use the reference as the entire value, or compose strings with $var or $env.`;const l=JSON.stringify(t),d=e.indexOf(l);n.push({message:c,severity:"warning",path:i.join("."),...-1===d?{line:1,column:1}:lo(e,d,l.length)})}})}(e,t,o)}(e,n,s,i,o)),function(e,t,n){if(!wo(t)||!wo(t.flows))return;for(const i of Object.values(t.flows)){if(!wo(i))continue;const t=wo(i.stores)?i.stores:void 0;t&&ro(e,t,n),t&&wo(i.transformers)&&so(e,i.transformers,t,n)}}(e,n,o),function(e,t,n){if(!wo(t)||!wo(t.flows))return;const i=(t,i,o)=>{n.push({message:o,severity:"error",path:i.join("."),...ao(e,t)})},o=(e,t)=>{e.startsWith("ingest.")&&i(e,t,`Mapping values resolve against the event, so "${e}" never resolves here. Copy it onto the event in an earlier step, then map the event path.`)},r=(e,t)=>(n,o)=>{e.test(n)||i(n,o,`Cache keys and route matchers resolve against { event, ingest }: "${n}" needs an ${t} prefix.`)},s=r(uo,'"event." or "ingest."'),a=r(fo,'"event.", "ingest." or "cache."');for(const[e,n]of Object.entries(t.flows))if(wo(n)){for(const t of mo){const i=n[t];if(wo(i))for(const[n,r]of Object.entries(i)){if(!wo(r))continue;const i=["flows",e,t,n];yo(r.before,[...i,"before"],s),yo(r.next,[...i,"next"],s),vo(r.cache,[...i,"cache"],s,a),"transformers"!==t&&wo(r.config)&&bo(r.config,[...i,"config"],o)}}wo(n.collector)&&yo(n.collector.next,["flows",e,"collector","next"],s)}}(e,n,i),{valid:0===i.length,errors:i,warnings:o,context:s}}var Bi=/\$store\.([a-zA-Z_][a-zA-Z0-9_]*)/g,Hi=/\$env\.([A-Za-z_]\w*)(=[^"}\s]*)?/g,Vi=/\$flow\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.([a-zA-Z0-9_.]+))?/g,Zi=/\$(var|store|flow|secret):([a-zA-Z_][a-zA-Z0-9_]*)/g,Gi=/\$secret\.([A-Za-z0-9_]+)/g;var Ki=[{prefix:"$flow.",regex:/^\$flow\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.([a-zA-Z0-9_.]+))?$/,grammar:"a flow name, then an optional dot path of letters, digits and _"},{prefix:"$store.",regex:/^\$store\.([a-zA-Z_][a-zA-Z0-9_]*)$/,grammar:"one store id of letters, digits and _, no path"},{prefix:"$secret.",regex:/^\$secret\.([A-Z0-9_]+)$/,grammar:"uppercase letters, digits and _"},{prefix:"$contract.",regex:/^\$contract\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.(.+))?$/,grammar:"a contract name, then an optional dot path"}],Qi=["title","description"],Yi=["sources","transformers","destinations","stores"];function Xi(e){const t=e[e.length-1];return"$comment"===t||("contract"===e[0]||(!("flows"!==e[0]||!Yi.includes(e[2])||"config"!==e[4]||"settings"!==e[5]||"contract"!==e[6])||!!Qi.includes(t)&&(1===e.length||"flows"===e[0]&&(3===e.length||!!Yi.includes(e[2])&&(5===e.length||7===e.length&&"examples"===e[4])))))}function eo(e,t,n){if("string"!=typeof e){if(Array.isArray(e))e.forEach((e,i)=>eo(e,[...t,String(i)],n));else if(wo(e))for(const[i,o]of Object.entries(e))eo(o,[...t,i],n)}else n(e,t)}var to=["@walkeros/server-store-fs","@walkeros/server-store-s3","@walkeros/server-store-gcs"],no="@walkeros/server-transformer-file",io=/^\$store\.([a-zA-Z_][a-zA-Z0-9_]*)$/;function oo(e){return wo(e.config)&&!0===e.config.file}function ro(e,t,n){for(const[i,o]of Object.entries(t))wo(o)&&oo(o)&&void 0!==o.cache&&n.push({message:`Store "${i}" sets file: true and cache. The cache holds structured values; caching a byte-serving store offers no benefit. Remove cache or unset file.`,severity:"warning",path:`stores.${i}`,...ao(e,i)})}function so(e,t,n,i){for(const o of Object.values(t)){if(!wo(o))continue;if(o.package!==no)continue;if(!wo(o.env))continue;const t=o.env.store;if("string"!=typeof t)continue;const r=io.exec(t);if(!r)continue;const s=r[1],a=n[s];if(!wo(a))continue;const c=a.package;"string"==typeof c&&to.includes(c)&&(oo(a)||i.push({message:`transformer-file serves byte-exact assets; set config.file: true on store "${s}".`,severity:"warning",path:`stores.${s}`,...ao(e,s)}))}}function ao(e,t){const n=e.indexOf(`"${t}"`);return-1===n?{line:1,column:1}:co(e,n)}function co(e,t){let n=1,i=1;for(let o=0;o<t&&o<e.length;o++)"\n"===e[o]?(n++,i=1):i++;return{line:n,column:i}}function lo(e,t,n){const i=co(e,t),o=co(e,t+n);return{line:i.line,column:i.column,endLine:o.line,endColumn:o.column}}function po(e,t){if(0===t.length)return{line:1,column:1};const n=t[t.length-1];if("string"==typeof n){const t=`"${n}"`,i=e.lastIndexOf(t);if(-1!==i)return co(e,i)}return{line:1,column:1}}var uo=/^(event|ingest)(\..+)?$/,fo=/^(event|ingest|cache)(\..+)?$/,mo=["sources","transformers","destinations"];function go(e,t,n){if("string"!=typeof e){if(Array.isArray(e))e.forEach((e,i)=>go(e,[...t,i],n));else if(wo(e)){if("string"==typeof e.key&&go(e.key,[...t,"key"],n),wo(e.map))for(const[i,o]of Object.entries(e.map))go(o,[...t,"map",i],n);Array.isArray(e.set)&&e.set.forEach((e,i)=>go(e,[...t,"set",i],n)),Array.isArray(e.loop)&&"this"!==e.loop[0]&&go(e.loop[0],[...t,"loop",0],n)}}else e.startsWith("$")||n(e,t)}function ho(e,t,n){if(wo(e))for(const[i,o]of Object.entries(e))go(o,[...t,i],n)}function bo(e,t,n){if(go(e.data,[...t,"data"],n),ho(e.policy,[...t,"policy"],n),wo(e.mapping))for(const[i,o]of Object.entries(e.mapping))if(wo(o))for(const[e,r]of Object.entries(o)){const o=[...t,"mapping",i,e];(Array.isArray(r)?r:[r]).forEach((e,t)=>{if(!wo(e))return;const i=Array.isArray(r)?[...o,t]:o;go(e.data,[...i,"data"],n),ho(e.policy,[...i,"policy"],n),wo(e.extend)&&(go(e.extend.data,[...i,"extend","data"],n),ho(e.extend.policy,[...i,"extend","policy"],n))})}}function vo(e,t,n,i){wo(e)&&Array.isArray(e.rules)&&e.rules.forEach((e,o)=>{if(!wo(e))return;const r=[...t,"rules",o];if(go(e.key,[...r,"key"],n),So(e.match,[...r,"match"],n),wo(e.update))for(const[t,n]of Object.entries(e.update))go(n,[...r,"update",t],i)})}function yo(e,t,n){if(void 0===e||(i=e,!Ue.safeParse(i).success))return;var i;const o=new Set;for(const i of Ai(e))for(const e of[...i.via??[],i]){if(!e.match)continue;const i=e.path.join(".");o.has(i)||(o.add(i),So(e.match,[...t,...e.path,"match"],n))}}function So(e,t,n){wo(e)&&(Array.isArray(e.and)&&e.and.forEach((e,i)=>So(e,[...t,"and",i],n)),Array.isArray(e.or)&&e.or.forEach((e,i)=>So(e,[...t,"or",i],n)),"string"==typeof e.key&&go(e.key,[...t,"key"],n))}function wo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ko(e,t){if(wo(t))for(const[n,i]of Object.entries(t))e[n]=i}function Co(e){const t={};if(!wo(e))return t;const n=wo(e.properties)?e.properties.data:void 0;if(!wo(n))return t;const i=Array.isArray(n.required)?n.required.filter(e=>"string"==typeof e):[],o=n.properties;if(!wo(o))return t;for(const[e,n]of Object.entries(o)){const o={};wo(n)&&("string"==typeof n.type&&(o.type=n.type),"string"==typeof n.description&&(o.description=n.description)),i.includes(e)&&(o.required=!0),t[e]=o}return t}function xo(e,t){const n=[],i={};for(const[t,o]of Object.entries(e)){o.required&&n.push(t);const e={type:o.type};if(o.description&&(e.description=o.description),o.pattern&&(e.pattern=o.pattern),void 0!==o.minLength&&(e.minLength=o.minLength),void 0!==o.maxLength&&(e.maxLength=o.maxLength),void 0!==o.minimum&&(e.minimum=o.minimum),void 0!==o.maximum&&(e.maximum=o.maximum),o.enum&&(e.enum=[...o.enum]),void 0!==o.default&&(e.default=o.default),"object"===o.type&&o.properties){const t={};for(const[e,n]of Object.entries(o.properties))t[e]=jo(n);e.properties=t}"array"===o.type&&o.items&&(e.items=jo(o.items)),i[t]=e}const o={type:"object",properties:i};return t&&(o.title=t),n.length>0&&(o.required=n),o}function jo(e){const t={type:e.type};if(e.description&&(t.description=e.description),e.pattern&&(t.pattern=e.pattern),void 0!==e.minLength&&(t.minLength=e.minLength),void 0!==e.maxLength&&(t.maxLength=e.maxLength),void 0!==e.minimum&&(t.minimum=e.minimum),void 0!==e.maximum&&(t.maximum=e.maximum),e.enum&&(t.enum=[...e.enum]),void 0!==e.default&&(t.default=e.default),"object"===e.type&&e.properties){const n={};for(const[t,i]of Object.entries(e.properties))n[t]=jo(i);t.properties=n}return"array"===e.type&&e.items&&(t.items=jo(e.items)),t}function Eo(e,t){const n={type:"array",items:jo(e)};return void 0!==t?.minItems&&(n.minItems=t.minItems),void 0!==t?.maxItems&&(n.maxItems=t.maxItems),t?.description&&(n.description=t.description),t?.title&&(n.title=t.title),n}function Oo(e,t="string",n){const i={type:t,enum:[...e]};return n?.description&&(i.description=n.description),n?.title&&(i.title=n.title),i}function Po(e,t,n){return Eo({type:"object"},{minItems:2,maxItems:2,description:n||"Tuple with exactly 2 elements [source, transform]"})}function $o(e){const t=i.toJSONSchema(e,{target:"draft-7"});return Do(t),t}function Do(e){const t=e.properties;if(t&&"object"==typeof t){Array.isArray(e.required)&&(e.required=e.required.filter(e=>{const n=t[e];return!(n&&"object"==typeof n&&"default"in n)}));for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&("object"===n.type&&n.properties&&"string"!=typeof n.title&&(n.title=e),Do(n))}}var Io=new Set(["env","onError","onLog","primary"]),Ao={source:Bt.configJsonSchema,destination:Te.configJsonSchema,store:pn.configJsonSchema};function To(e,t){const n=Ro(Ao[e]);if(!n||!n.properties){const e={settings:t.settings?Jo(t.settings):{description:"Implementation-specific configuration"}};t.credentials&&(e.credentials=Jo(t.credentials));return{type:"object",properties:e}}const i=JSON.parse(JSON.stringify(n)),o=i.properties;for(const e of Io)delete o[e];return t.settings&&(o.settings=Jo(t.settings)),t.credentials&&(o.credentials=Jo(t.credentials)),i}function Ro(e){if(!e)return e;if(e.properties)return e;const{ref:t,container:n,containerKey:i}=function(e){const t=e.$defs,n=e.definitions,i=t??n,o=t?"$defs":"definitions";let r;if("string"==typeof e.$ref)r=e.$ref;else if(Array.isArray(e.allOf)){const t=e.allOf[0];t&&"string"==typeof t.$ref&&(r=t.$ref)}return{ref:r,container:i,containerKey:o}}(e);if(!t||!n)return e;const o=t.match(/^#\/(\$defs|definitions)\/(.+)$/);if(!o)return e;const r=n[o[2]];return r&&"object"==typeof r?{...r,[i]:n}:e}function Jo(e){const{$schema:t,...n}=e;return n}function Mo(e){return 0===e.length?"// no output":e.map(Fo).join(";\n\n")}function Fo(e){const[t,...n]=e,i=n.map(zo).join(", ");return"return"===t?i?`return ${i}`:"return":`${t}(${i})`}function zo(e){return void 0===e?"undefined":null===e?"null":"function"==typeof e?"[Function]":JSON.stringify(e,null,2)}var No="call:";function Lo(e){const t=(e.startsWith(No)?e.slice(5):e).split(".");return t.some(e=>""===e)?[]:t}async function qo(e){const t=e.simulation??[];if(0===t.length)return;const n=e.push;if(!n)throw new Error(`simulation declares ${t.join(", ")} but the examples env has no push mock`);const i=[];for(const e of t){const t=Lo(e),o=0===t.length?"malformed path":await Wo(n,t);o&&i.push(`${e} (${o})`)}if(i.length>0)throw new Error(`simulation paths do not resolve against the push mock env: ${i.join(", ")}`)}function _o(e){return"function"==typeof e}async function Wo(e,t){let n,i=e;for(const e of t){if(_o(i)&&!(e in i))try{i=await Uo(i,n)}catch(t){return`calling before "${e}" threw: ${t instanceof Error?t.message:String(t)}`}if("object"!=typeof i&&"function"!=typeof i||null===i||!(e in i))return`"${e}" not found`;n=i,i=Reflect.get(i,e)}return"function"==typeof i?void 0:"leaf is not a function"}async function Uo(e,t){let n;try{n=Reflect.construct(e,[])}catch(i){try{n=Reflect.apply(e,t,[])}catch{throw i}}return await n}var Bo={};t(Bo,{STOP:()=>Ho,eq:()=>Vo,interpret:()=>Qo,makeTransformers:()=>Zo,routeCases:()=>Go,visits:()=>Yo});var Ho="(stop)";function Vo(e,t){return{key:e,operator:"eq",value:t}}function Zo(e={}){const t={};for(const[n,i]of Object.entries(e))t[n]={type:n,config:{next:i},push:()=>{}};return t}var Go=[{name:"static member next is inserted after the member",spec:["bot","validate","session"],nexts:{bot:"foo"},roots:[{ingest:{}}],expected:[[["bot","foo","validate","session"]]]},{name:"member next insertion is recursive and depth first",spec:["bot","validate","session"],nexts:{bot:"foo",foo:"bar"},roots:[{ingest:{}}],expected:[[["bot","foo","bar","validate","session"]]]},{name:"conditional member next inserts only on match",spec:["bot","validate"],nexts:{bot:{match:Vo("ingest.bot","yes"),next:"flag"}},roots:[{ingest:{bot:"yes"}},{ingest:{bot:"no"}}],expected:[[["bot","flag","validate"]],[["bot","validate"]]]},{name:"conditional member next sees what the member wrote",spec:["enrich","out"],nexts:{enrich:{match:Vo("ingest.tier","gold"),next:"vip"}},sets:{enrich:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["enrich","vip","out"]]]},{name:"many forks and each fork finishes the rest of the array",spec:["a",{many:["x","y"]},"z"],roots:[{ingest:{}}],expected:[[["a","x","z"],["a","y","z"]]]},{name:"stop in one fork ends only that copy",spec:["a",{many:[["x",{stop:!0}],"y"]},"z"],roots:[{ingest:{}}],expected:[[["a","x",Ho],["a","y","z"]]]},{name:"fork at depth 2 carries every enclosing continuation",spec:["a",{one:[{match:Vo("ingest.k","1"),next:["b",{many:["c","d"]},"e"]}]},"f"],roots:[{ingest:{k:"1"}},{ingest:{k:"2"}}],expected:[[["a","b","c","e","f"],["a","b","d","e","f"]],[["a","f"]]]},{name:"fork inside a member next continues the enclosing arrays",spec:["a",["b","c"],"d"],nexts:{b:{many:["m1","m2"]}},roots:[{ingest:{}}],expected:[[["a","b","m1","c","d"],["a","b","m2","c","d"]]]},{name:"a step listed twice runs twice",spec:["a","b","a"],roots:[{ingest:{}}],expected:[[["a","b","a"]]]},{name:"member next cycle stops at the guard",spec:["a","x"],nexts:{a:"b",b:"a"},roots:[{ingest:{}}],expected:[[["a","b","x"]]]},{name:"gated stop after a write ends the copy",spec:["a",{match:Vo("ingest.tier","gold"),stop:!0},"b"],sets:{a:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["a",Ho]]]},{name:"gated stop that fails falls through",spec:["a",{match:Vo("ingest.tier","gold"),stop:!0},"b"],roots:[{ingest:{tier:"gold"}},{ingest:{tier:"silver"}}],expected:[[["a",Ho]],[["a","b"]]]},{name:"unconditional stop",spec:["a",{stop:!0},"b"],roots:[{ingest:{}}],expected:[[["a",Ho]]]},{name:"one with a stop entry",spec:{one:[{match:Vo("ingest.x","1"),stop:!0},{next:"b"}]},roots:[{ingest:{x:"1"}},{ingest:{x:"2"}}],expected:[[[Ho]],[["b"]]]},{name:"state get into ingest.tier → next one on ingest.tier",spec:["state",{one:[{match:Vo("ingest.tier","gold"),next:"vip"},{next:"std"}]}],sets:{state:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["state","vip"]]]}];function Ko(e){return{...e,ingest:{...e.ingest}}}function Qo(e,t,n){const i=Zo(e.nexts),o=[],r=(t,s,a)=>{let c=t;const l={ids:[...a.ids],stopped:!1,edges:[...a.edges]};for(let t=0;t<256;t++){const t=Ii(c,s,i);if("done"===t.kind)break;if("stop"===t.kind){l.stopped=!0;break}if("fork"===t.kind){for(const e of t.branches)r(e,Ko(s),l);return}n&&n(t.id);const o=l.ids.length>0?l.ids[l.ids.length-1]:"";l.edges.push(`${o}>${t.id}`),l.ids.push(t.id);const a=e.sets?e.sets[t.id]:void 0;a&&(s.ingest={...s.ingest,...a}),c=t.rest}o.push(l)};return r(Pi(e.spec),Ko(t),{ids:[],stopped:!1,edges:[]}),o}function Yo(e){return e.map(e=>e.stopped?[...e.ids,Ho]:e.ids)}var Xo={Source:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",primary:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",variables:"resolve",examples:"docs"},Transformer:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",mapping:"runtime",variables:"resolve",examples:"docs"},Destination:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",variables:"resolve",examples:"docs"},Store:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",cache:"runtime",variables:"resolve",examples:"docs"}},er=["disabled","id","logger","mock","chainMocks"],tr=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function nr(e,t){const n=function(e){return new Set([...Object.keys(Xo[e]),...er])}(t);for(const i of Object.keys(e))if(!n.has(i))return{ok:!1,code:"UNKNOWN_KEY",key:i,reason:`Unknown key "${i}" on ${t}. Allowed: ${[...n].sort().join(", ")}.`};const i=void 0!==e.package,o=void 0!==e.import,r=void 0!==e.code;return r&&"string"==typeof e.code?{ok:!1,code:"OBSOLETE_CODE_STRING",key:"code",reason:`code: "<name>" is no longer supported. Use import: "${e.code}" with the package field instead.`}:r&&("object"!=typeof e.code&&"function"!=typeof e.code||null===e.code||Array.isArray(e.code))?{ok:!1,code:"INVALID_CODE_SHAPE",key:"code",reason:"code must be an object ({ push, type?, init? }) or a resolved function value."}:r&&i?{ok:!1,code:"CONFLICT",key:"package",reason:"Cannot specify both `code` and `package`. Use one or the other."}:r&&o?{ok:!1,code:"CONFLICT",key:"import",reason:"Cannot specify both `code` and `import`."}:o&&!i?{ok:!1,code:"MISSING_PACKAGE",key:"import",reason:"`import` requires `package` to be set."}:!o||"string"==typeof e.import&&tr.test(e.import)?{ok:!0}:{ok:!1,code:"INVALID_IMPORT",key:"import",reason:`import must match ${tr.source}. Got: ${JSON.stringify(e.import)}.`}}function ir(e){return function(e){return pi(e)&&"push"in e}(e)||"string"==typeof e}function or(e,t,n){if("Transformer"===e){const e=nr({...n},"Transformer");if(!e.ok)throw new Error(`Transformer "${t}": ${e.reason??"invalid entry."}`);return}const i=!!n.package,o=ir(n.code);if(i&&o)throw new Error(`${e} "${t}": Cannot specify both package and code. Use one or the other.`);if(!i&&!o)throw new Error(`${e} "${t}": Must specify either package or code.`)}var rr=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/;function sr(e,t){for(const n of Object.keys(e))if(!rr.test(n))throw new Error(`Invalid ${t} name "${n}": must be a valid JavaScript identifier (use camelCase, e.g., "${n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}")`)}function ar(e,t){const n=[];function i(e,t){if("string"==typeof e&&e.startsWith("$store."))n.push({ref:e.slice(7),location:t});else if(null!==e&&"object"==typeof e)for(const[n,o]of Object.entries(e))i(o,`${t}.${n}`)}const o={sources:e.sources||{},destinations:e.destinations||{},transformers:e.transformers||{}};for(const[e,t]of Object.entries(o))for(const[n,o]of Object.entries(t))i(o,`${e}.${n}`);const r=n.filter(({ref:e})=>!t.has(e));if(r.length>0){const e=t.size>0?`Available stores: ${Array.from(t).join(", ")}`:"No stores defined",n=r.map(({ref:e,location:t})=>`"$store.${e}" in ${t} (store "${e}" not found)`).join("; ");throw new Error(`Invalid store references: ${n}. ${e}`)}}var cr=["sources","destinations","transformers","stores"],lr={sources:"Source",destinations:"Destination",transformers:"Transformer",stores:"Store"};function dr(e,t){switch(t){case"sources":return e.sources;case"destinations":return e.destinations;case"transformers":return e.transformers;case"stores":return e.stores}}function pr(e){return"string"==typeof e||pi(e)&&"push"in e}function ur(e){return e instanceof Error?e.message:String(e)}function fr(e){const t=[],n={},i=e.flows,o=pi(i)?Object.keys(i):[];if(n.flowNames=o,n.flowCount=o.length,!pi(i)||0===o.length)return t.push({path:"flows",message:"At least one flow is required",code:"EMPTY_FLOWS"}),{valid:!1,type:"flow",errors:t,warnings:[],details:n};for(const[e,n]of Object.entries(i)){for(const i of cr){const o=dr(n,i);if(o)try{sr(o,i)}catch(n){t.push({path:`flows.${e}.${i}`,message:ur(n),code:"INVALID_COMPONENT_NAME"})}}for(const i of cr){const o=dr(n,i);if(!o)continue;const r=lr[i];if("Transformer"!==r)for(const[n,s]of Object.entries(o))if("Store"!==r||s.package||pr(s.code))try{or(r,n,s)}catch(o){t.push({path:`flows.${e}.${i}.${n}`,message:ur(o),code:"INVALID_REFERENCE"})}}const i=n.transformers;if(i)for(const[n,o]of Object.entries(i)){const i=nr({...o},"Transformer");i.ok||t.push({path:`flows.${e}.transformers.${n}`,message:i.reason||"Invalid transformer entry.",code:i.code})}const o=new Set(Object.keys(n.stores||{}));try{ar(n,o)}catch(n){t.push({path:`flows.${e}`,message:ur(n),code:"STORE_REFERENCE_NOT_FOUND"})}}return{valid:0===t.length,type:"flow",errors:t,warnings:[],details:n}}export{si as ClickIdEntrySchema,qo as expectSimulationResolves,Mo as formatOut,To as mergeConfigSchema,Ro as resolveBaseSchema,Bo as routeCases,n as schemas,sr as validateComponentNames,fr as validateFlowStructure,or as validateReference,ar as validateStoreReferences,i as z,$o as zodToSchema};//# sourceMappingURL=dev.mjs.map
1
+ var e=Object.defineProperty,t=(t,n)=>{for(var i in n)e(t,i,{get:n[i],enumerable:!0})},n={};t(n,{BaseContextConfig:()=>F,CacheRuleSchema:()=>Ke,CacheSchema:()=>Qe,CacheSchemas:()=>Be,ClickIdEntrySchema:()=>di,CodeSchema:()=>ai,CollectorSchemas:()=>Dt,ConsentSchema:()=>V,ContractActionsSchema:()=>Nn,ContractRuleSchema:()=>Ln,ContractSchema:()=>_n,ContractSchemaEntry:()=>Fn,Counter:()=>d,CredentialsSchema:()=>ui,DeepPartialEventSchema:()=>ne,DestinationSchemas:()=>Te,DestinationsMapConfig:()=>L,EntitiesSchema:()=>X,EntitySchema:()=>Y,EventCacheRuleSchema:()=>He,EventCacheSchema:()=>Ze,EventSchema:()=>ee,FlowBundlePackageSchema:()=>xn,FlowBundleSchema:()=>jn,FlowCodeSchema:()=>En,FlowConfigSchema:()=>Wn,FlowDestinationSchema:()=>Jn,FlowJsonSchema:()=>Bn,FlowSchema:()=>Un,FlowSchemas:()=>hn,FlowSourceSchema:()=>Tn,FlowStoreSchema:()=>Mn,FlowTransformerSchema:()=>Rn,GenericEnvConfig:()=>I,GenericSettingsConfig:()=>D,HandlersConfig:()=>x,HintSchema:()=>ci,HintsSchema:()=>li,IdConfig:()=>O,Identifier:()=>c,InitConfig:()=>$,LoggerConfigSchema:()=>ot,LoggerHandlerSchema:()=>it,LoopSchema:()=>me,MapSchema:()=>he,MappingResultSchema:()=>Ce,MappingSchemas:()=>pe,MatchExpressionSchema:()=>Fe,MatcherSchemas:()=>Re,OptionalPrimitiveValue:()=>u,OrderedPropertiesSchema:()=>H,PartialEventSchema:()=>te,PolicySchema:()=>ve,PrimaryConfig:()=>P,PrimitiveValue:()=>p,ProcessingControlConfig:()=>N,PropertiesSchema:()=>B,PropertySchema:()=>U,PropertyTypeSchema:()=>W,QueueConfig:()=>E,RequiredBoolean:()=>a,RequiredNumber:()=>s,RequiredString:()=>r,RouteSchema:()=>Ue,RuleSchema:()=>Se,RulesSchema:()=>we,RuntimeInstanceConfig:()=>M,ServiceAccountSchema:()=>pi,SetSchema:()=>ge,SourceSchema:()=>Q,SourceSchemas:()=>Bt,SourceTypeSchema:()=>Z,SourcesMapConfig:()=>z,StateSchema:()=>nt,StoreCacheRuleSchema:()=>Ve,StoreCacheSchema:()=>Ge,StoreSchemas:()=>pn,Timestamp:()=>l,TransformerSchemas:()=>sn,UserSchema:()=>G,UtilitySchemas:()=>f,ValidateEventsSchema:()=>In,ValueConfigSchema:()=>be,ValueSchema:()=>ue,ValuesSchema:()=>fe,VerboseConfig:()=>j,WalkerOSSchemas:()=>_,configJsonSchema:()=>Kn,consentJsonSchema:()=>de,contractJsonSchema:()=>oi,contractRuleJsonSchema:()=>ii,createArraySchema:()=>To,createConsentConfig:()=>J,createDataTransformationConfig:()=>A,createEnumSchema:()=>Ro,createMappingRulesConfig:()=>T,createObjectSchema:()=>Io,createPolicyConfig:()=>R,createTupleSchema:()=>Jo,credentialsJsonSchema:()=>fi,destinationJsonSchema:()=>ei,entityJsonSchema:()=>ce,eventJsonSchema:()=>ie,flowConfigJsonSchema:()=>Yn,flowJsonSchema:()=>Qn,loopJsonSchema:()=>Ee,mapJsonSchema:()=>$e,orderedPropertiesJsonSchema:()=>ae,parseConfig:()=>Hn,parseFlow:()=>Vn,partialEventJsonSchema:()=>oe,policyJsonSchema:()=>Pe,propertiesJsonSchema:()=>se,ruleJsonSchema:()=>De,rulesJsonSchema:()=>Ie,safeParseConfig:()=>Zn,safeParseFlow:()=>Gn,setJsonSchema:()=>Oe,sourceJsonSchema:()=>Xn,sourceTypeJsonSchema:()=>le,storeJsonSchema:()=>ni,transformerJsonSchema:()=>ti,userJsonSchema:()=>re,validateEventsJsonSchema:()=>ri,validateFlowConfig:()=>Vi,valueConfigJsonSchema:()=>je,valueJsonSchema:()=>xe,z:()=>i,zodToSchema:()=>Mo});import{z as i}from"zod";function o(e,t,n="draft-7"){return i.toJSONSchema(e,{target:n})}var r=i.string(),s=i.number(),a=i.boolean(),c=i.string().min(1),l=i.number().int().positive(),d=i.number().int().nonnegative(),p=i.union([i.string(),i.number(),i.boolean()]),u=p.optional(),f={};t(f,{ErrorHandlerSchema:()=>h,HandlerSchema:()=>v,LogHandlerSchema:()=>b,StorageSchema:()=>g,StorageTypeSchema:()=>m,errorHandlerJsonSchema:()=>w,handlerJsonSchema:()=>C,logHandlerJsonSchema:()=>k,storageJsonSchema:()=>S,storageTypeJsonSchema:()=>y});var m=i.enum(["local","session","cookie"]).meta({id:"StorageType",title:"Storage.Type",description:"Storage mechanism: local, session, or cookie."}).describe("Storage mechanism: local, session, or cookie"),g=i.object({Local:i.literal("local"),Session:i.literal("session"),Cookie:i.literal("cookie")}).meta({id:"StorageConstants",title:"Storage",description:"Storage type constants for type-safe references."}).describe("Storage type constants for type-safe references"),h=i.unknown().meta({id:"ErrorHandler",title:"Error.Handler",description:"Error handler function: (error, state?) => void."}).describe("Error handler function: (error, state?) => void"),b=i.unknown().meta({id:"LogHandler",title:"Log.Handler",description:"Log handler function: (message, verbose?) => void."}).describe("Log handler function: (message, verbose?) => void"),v=i.object({Error:h.describe("Error handler function"),Log:b.describe("Log handler function")}).meta({id:"Handler",title:"Handler",description:"Handler interface with error and log functions."}).describe("Handler interface with error and log functions"),y=o(m),S=o(g),w=o(h),k=o(b),C=o(v),x=i.object({onError:h.optional().describe("Error handler function: (error, state?) => void"),onLog:b.optional().describe("Log handler function: (message, verbose?) => void")}).partial(),j=i.object({verbose:i.boolean().describe("Enable verbose logging for debugging").optional()}).partial(),E=i.object({queue:i.boolean().describe("Whether a destination added later receives events pushed earlier in the current run (default true). Consent-denied events are queued regardless.").optional()}).partial(),O=i.object({}).partial(),$=i.object({init:i.boolean().describe("Whether to initialize immediately").optional(),loadScript:i.boolean().describe("Whether to load external script (for web destinations)").optional()}).partial(),P=i.object({primary:i.boolean().describe("Mark as primary (only one can be primary)").optional()}).partial(),D=i.object({settings:i.any().optional().describe("Implementation-specific configuration")}).partial(),I=i.object({env:i.any().optional().describe("Environment dependencies (platform-specific)")}).partial();function A(e,t){return i.object({data:i.union([e,t]).optional().describe("Data transformation rules")}).partial()}function T(e){return i.object({mapping:e.optional().describe("Event mapping rules")}).partial()}function R(e){return i.object({policy:e.optional().describe("Pre-processing policy rules")}).partial()}function J(e){return i.object({consent:e.optional().describe("Required consent states")}).partial()}var M=i.object({type:i.string().optional().describe("Instance type identifier"),config:i.unknown().describe("Instance configuration")}).partial(),F=i.object({collector:i.unknown().describe("Collector instance (runtime object)"),config:i.unknown().describe("Configuration"),env:i.unknown().describe("Environment dependencies")}).partial(),N=i.object({ignore:i.boolean().describe("Set to true to skip processing").optional(),condition:i.string().optional().describe("Condition function: return true to process")}).partial(),z=i.object({sources:i.record(i.string(),i.unknown()).describe("Map of source instances")}).partial(),L=i.object({destinations:i.record(i.string(),i.unknown()).describe("Map of destination instances")}).partial(),_={};t(_,{ConsentSchema:()=>V,DeepPartialEventSchema:()=>ne,EntitiesSchema:()=>X,EntitySchema:()=>Y,EventSchema:()=>ee,OrderedPropertiesSchema:()=>H,PartialEventSchema:()=>te,PropertiesSchema:()=>B,PropertySchema:()=>U,PropertyTypeSchema:()=>W,SourceFieldsSchema:()=>K,SourceSchema:()=>Q,SourceTypeSchema:()=>Z,UserSchema:()=>G,consentJsonSchema:()=>de,entityJsonSchema:()=>ce,eventJsonSchema:()=>ie,orderedPropertiesJsonSchema:()=>ae,partialEventJsonSchema:()=>oe,propertiesJsonSchema:()=>se,sourceTypeJsonSchema:()=>le,userJsonSchema:()=>re});var q,W=i.lazy(()=>i.union([i.boolean(),i.string(),i.number(),i.record(i.string(),U)])).meta({id:"WalkerOSPropertyType",title:"WalkerOS.PropertyType",description:"Base property value types (boolean, string, number, or nested Property record)."}),U=i.lazy(()=>i.union([W,i.array(W)])).meta({id:"WalkerOSProperty",title:"WalkerOS.Property",description:"PropertyType or an array of PropertyType. Recursive structure for nested objects and arrays."}),B=i.record(i.string(),U.optional()).meta({id:"WalkerOSProperties",title:"WalkerOS.Properties",description:"Flexible property collection with optional values."}).describe("Flexible property collection with optional values"),H=i.record(i.string(),i.tuple([U,i.number()]).optional()).meta({id:"WalkerOSOrderedProperties",title:"WalkerOS.OrderedProperties",description:"Ordered properties with [value, order] tuples for priority control."}).describe("Ordered properties with [value, order] tuples for priority control"),Z=i.union([i.enum(["web","server","app","other"]),i.string()]).meta({id:"WalkerOSSourceType",title:"WalkerOS.SourceType",description:"Source type identifier. Standard: web, server, app, other. Extensible to custom strings."}).describe("Source type: web, server, app, other, or custom"),V=i.record(i.string(),i.boolean()).meta({id:"WalkerOSConsent",title:"WalkerOS.Consent",description:"Consent state mapping. Keys are consent groups (e.g. marketing, functional), values are booleans for granted/denied."}).describe("Consent requirement mapping (group name to state)"),G=B.and(i.object({id:i.string().optional().describe("User identifier"),device:i.string().optional().describe("Device identifier"),session:i.string().optional().describe("Session identifier"),hash:i.string().optional().describe("Hashed identifier"),address:i.string().optional().describe("User address"),email:i.string().email().optional().describe("User email address"),phone:i.string().optional().describe("User phone number"),userAgent:i.string().optional().describe("Browser user agent string"),browser:i.string().optional().describe("Browser name"),browserVersion:i.string().optional().describe("Browser version"),deviceType:i.string().optional().describe("Device type (mobile, desktop, tablet)"),os:i.string().optional().describe("Operating system"),osVersion:i.string().optional().describe("Operating system version"),screenSize:i.string().optional().describe("Screen dimensions"),language:i.string().optional().describe("User language"),country:i.string().optional().describe("User country"),region:i.string().optional().describe("User region/state"),city:i.string().optional().describe("User city"),zip:i.string().optional().describe("User postal code"),timezone:i.string().optional().describe("User timezone"),ip:i.string().optional().describe("User IP address"),internal:i.boolean().optional().describe("Internal user flag (employee, test user)")})).meta({id:"WalkerOSUser",title:"WalkerOS.User",description:"User identification and attributes."}).describe("User identification and properties"),K=i.object({type:i.string().describe("Source kind (browser, dataLayer, gtag, ...)"),platform:i.string().optional().describe("Runtime platform (web, server, app, ios, android, terminal, ...)"),version:i.string().optional().describe("Deployment version of the source emitter"),schema:i.string().optional().describe('Event model spec version (collector defaults to "4")'),count:i.number().int().nonnegative().optional().describe("Emission sequence per run"),trace:i.string().optional().describe("Trace id shared by every event of a run (W3C trace-id shape)"),release:i.record(i.string(),i.string()).optional().describe("Per-flow config release map, keyed by flow name; accumulates across walkerOS crossings"),url:i.string().optional(),referrer:i.string().optional(),tool:i.string().optional(),command:i.string().optional()}),Q=B.and(K).meta({id:"WalkerOSSource",title:"WalkerOS.Source",description:"Event source information (origin of the event)."}).describe("Event source information"),Y=i.lazy(()=>i.object({entity:i.string().describe("Entity name"),data:B.describe("Entity-specific properties"),nested:i.array(Y).optional().describe("Nested child entities"),context:H.optional().describe("Entity context data")})).meta({id:"WalkerOSEntity",title:"WalkerOS.Entity",description:"Nested entity structure with recursive nesting support."}).describe("Nested entity structure with recursive nesting support"),X=i.array(Y).meta({id:"WalkerOSEntities",title:"WalkerOS.Entities",description:"Array of nested entities."}).describe("Array of nested entities"),ee=i.object({name:i.string().describe('Event name in "entity action" format (e.g., "page view", "product add")'),data:B.describe("Event-specific properties"),context:H.describe("Ordered context properties with priorities"),globals:B.describe("Global properties shared across events"),custom:B.describe("Custom implementation-specific properties"),user:G.describe("User identification and attributes"),nested:X.describe("Related nested entities"),consent:V.describe("Consent states at event time"),id:c.describe("W3C span_id, 16 lowercase hex characters"),trigger:r.describe("Event trigger identifier"),entity:r.describe("Parsed entity from event name"),action:r.describe("Parsed action from event name"),timestamp:l.describe("Unix timestamp in milliseconds since epoch"),timing:s.describe("Event processing timing information"),source:Q.describe("Event source information")}).meta({id:"WalkerOSEvent",title:"WalkerOS.Event",description:"Complete walkerOS event structure."}).describe("Complete walkerOS event structure"),te=ee.partial().meta({id:"WalkerOSPartialEvent",title:"WalkerOS.PartialEvent",description:"Partial event structure with all fields optional."}).describe("Partial event structure with all fields optional"),ne=ee.partial().meta({id:"WalkerOSDeepPartialEvent",title:"WalkerOS.DeepPartialEvent",description:"Partial event structure with all top-level fields optional."}).describe("Partial event structure with all top-level fields optional"),ie=o(ee),oe=o(te),re=o(G),se=o(B),ae=o(H),ce=o(Y),le=o(Z),de=o(V),pe={};t(pe,{ConfigSchema:()=>ke,LoopSchema:()=>me,MapSchema:()=>he,PolicySchema:()=>ve,ResultSchema:()=>Ce,RulePatchSchema:()=>ye,RuleSchema:()=>Se,RulesSchema:()=>we,SetSchema:()=>ge,ValueConfigSchema:()=>be,ValueSchema:()=>ue,ValuesSchema:()=>fe,configJsonSchema:()=>Ae,loopJsonSchema:()=>Ee,mapJsonSchema:()=>$e,policyJsonSchema:()=>Pe,ruleJsonSchema:()=>De,rulesJsonSchema:()=>Ie,setJsonSchema:()=>Oe,valueConfigJsonSchema:()=>je,valueJsonSchema:()=>xe});var ue=i.lazy(()=>i.union([i.string().describe('String value or property path (e.g., "data.id")'),i.number().describe("Numeric value"),i.boolean().describe("Boolean value"),i.lazy(()=>q),i.array(ue).describe("Array of values")])).meta({id:"MappingValue",title:"Mapping.Value",description:"Polymorphic transform primitive used in every mapping field. A string path, constant, operator object (map/loop/set/condition/consent), or array of values."}),fe=i.array(ue).meta({id:"MappingValues",title:"Mapping.Values",description:"Array of transformation values."}).describe("Array of transformation values"),me=i.lazy(()=>i.tuple([ue,ue]).describe("Loop transformation: [source, transform] tuple for array processing")).meta({id:"MappingLoop",title:"Mapping.Loop",description:"Loop tuple [source, transform] for iterating and transforming arrays.",minItems:2,maxItems:2}),ge=i.lazy(()=>i.array(ue).describe("Set: Array of values for selection or combination")).meta({id:"MappingSet",title:"Mapping.Set",description:"Set: array of values for selection or combination."}),he=i.lazy(()=>i.record(i.string(),ue).describe("Map: Object mapping keys to transformation values")).meta({id:"MappingMap",title:"Mapping.Map",description:"Map: object mapping keys to transformation values."}),be=q=i.object({key:i.string().optional().describe('Property path to extract from event (e.g., "data.id", "user.email")'),value:i.union([i.string(),i.number(),i.boolean()]).optional().describe("Static primitive value"),fn:i.string().optional().describe("Custom transformation function as string (serialized)"),map:he.optional().describe("Object mapping: transform event data to structured output"),loop:me.optional().describe("Loop transformation: [source, transform] for array processing"),set:ge.optional().describe("Set of values: combine or select from multiple values"),consent:V.optional().describe("Required consent states to include this value"),condition:i.string().optional().describe("Condition function as string: return true to include value"),validate:i.string().optional().describe("Validation function as string: return true if value is valid")}).refine(e=>Object.keys(e).length>0,{message:"ValueConfig must have at least one property"}).meta({id:"MappingValueConfig",title:"Mapping.ValueConfig",description:"Object-form value transformation with map/loop/set/condition/consent etc."}).describe("Value transformation configuration with multiple strategies"),ve=i.record(i.string(),ue).meta({id:"MappingPolicy",title:"Mapping.Policy",description:"Policy rules for event pre-processing (key → value transformation)."}).describe("Policy rules for event pre-processing (key → value mapping)"),ye=i.object({name:i.string().nullable().optional(),data:i.union([ue,fe]).nullable().optional(),settings:i.unknown().nullable().optional(),condition:i.string().nullable().optional(),consent:V.nullable().optional(),policy:ve.nullable().optional(),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).nullable().optional(),include:i.array(i.string()).nullable().optional(),ignore:i.boolean().nullable().optional(),silent:i.boolean().nullable().optional()}).meta({id:"MappingRulePatch",title:"Mapping.RulePatch",description:"Partial rule deep-merged onto a package-shipped default; a null value clears the inherited field."}).describe("Partial rule for `extend`; null clears an inherited field"),Se=i.object({name:i.string().optional().describe('Custom event name override (e.g., "view_item" for "product view")'),data:i.union([ue,fe]).optional().describe("Data transformation rules for event"),settings:i.unknown().optional().describe("Destination-specific settings for this event mapping"),condition:i.string().optional().describe("Condition function as string: return true to process event"),consent:V.optional().describe("Required consent states to process this event"),policy:ve.optional().describe("Event-level policy overrides (applied after config-level policy)"),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).optional().describe("Batch scheduling: bare number is the debounce wait window (legacy); object form supports wait/size/age."),include:i.array(i.string()).optional().describe('Event sections (e.g. ["context", "globals"]) flattened into context.data'),ignore:i.boolean().optional().describe("Skip the event entirely. No push, no side effects. Use for suppression."),silent:i.boolean().optional().describe("Run side effects (settings.identify, ...) but suppress the destination default push call."),extend:ye.optional().describe("Merge mode: a partial rule deep-merged onto the package-shipped default at this key (instead of replacing it). A null value clears an inherited field."),remove:i.array(i.string()).optional().describe("Dotted paths stripped from the produced data payload after evaluation (applied last).")}).meta({id:"MappingRule",title:"Mapping.Rule",description:"Configuration for transforming a single event at one stage of the flow (source or destination)."}).describe("Mapping rule for specific entity-action combination"),we=i.record(i.string(),i.record(i.string(),i.union([Se,i.array(Se)])).optional()).meta({id:"MappingRules",title:"Mapping.Rules",description:'Event mapping rules tree: entity → action → Rule (or Rule[]). Use "*" as wildcard for entity or action.'}).describe('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 (*→*).'),ke=i.object({consent:V.optional().describe("Required consent states to process any events"),data:i.union([ue,fe]).optional().describe("Global data transformation applied to all events"),include:i.array(i.string()).optional().describe("Event sections to flatten into context.data"),mapping:we.optional().describe("Entity-action specific mapping rules"),policy:ve.optional().describe("Pre-processing policy rules applied before mapping")}).meta({id:"MappingConfig",title:"Mapping.Config",description:"Shared mapping configuration (consent, data, include, mapping, policy)."}).describe("Shared mapping configuration for sources and destinations"),Ce=i.object({eventMapping:Se.optional().describe("Resolved mapping rule for event"),mappingKey:i.string().optional().describe('Mapping key used (e.g., "product.view")')}).meta({id:"MappingResult",title:"Mapping.Result",description:"Mapping resolution result (matched rule + key)."}).describe("Mapping resolution result"),xe=o(ue),je=o(be),Ee=o(me),Oe=o(ge),$e=o(he),Pe=o(ve),De=o(Se),Ie=o(we),Ae=o(ke),Te={};t(Te,{BatchSchema:()=>ft,ConfigSchema:()=>rt,ContextSchema:()=>ct,DLQSchema:()=>kt,DataSchema:()=>mt,DestinationPolicySchema:()=>at,DestinationsSchema:()=>vt,InitDestinationsSchema:()=>bt,InitSchema:()=>ht,InstanceSchema:()=>gt,PartialConfigSchema:()=>st,PushBatchContextSchema:()=>dt,PushContextSchema:()=>lt,PushEventSchema:()=>pt,PushEventsSchema:()=>ut,PushResultSchema:()=>St,RefSchema:()=>yt,ResultSchema:()=>wt,batchJsonSchema:()=>Ot,configJsonSchema:()=>Ct,contextJsonSchema:()=>jt,instanceJsonSchema:()=>$t,partialConfigJsonSchema:()=>xt,pushContextJsonSchema:()=>Et,resultJsonSchema:()=>Pt});var Re={};t(Re,{MatchExpressionSchema:()=>Fe,RouteSchema:()=>Ue});var Je=i.enum(["eq","contains","prefix","suffix","regex","gt","lt","exists"]).meta({id:"MatcherOperator",title:"Matcher.Operator",description:"Supported operators for a match condition."}),Me=i.object({key:i.string(),operator:Je,value:i.string(),not:i.boolean().optional()}).meta({id:"MatcherCondition",title:"Matcher.Condition",description:"Single match condition (key, operator, value, optional not)."}),Fe=i.union([Me,i.object({and:i.array(i.lazy(()=>Fe))}),i.object({or:i.array(i.lazy(()=>Fe))})]).meta({id:"MatcherExpression",title:"Matcher.Expression",description:"Boolean expression tree of match conditions (leaf, and, or)."}),Ne=i.strictObject({match:Fe.optional(),next:i.lazy(()=>Ue)}),ze=i.strictObject({match:Fe.optional(),one:i.array(i.lazy(()=>Ue))}),Le=i.strictObject({match:Fe.optional(),many:i.array(i.lazy(()=>Ue))}),_e=i.strictObject({match:Fe.optional(),stop:i.literal(!0)}),qe=i.strictObject({match:Fe}),We=i.union([Ne,ze,Le,_e,qe]),Ue=i.union([i.string(),i.array(i.lazy(()=>Ue)),We]).meta({id:"Route",title:"Route",description:"Recursive route: string ID, sequence of routes, or a RouteConfig (next/one/many/stop/gate). Valid in every chain field."}),Be={};t(Be,{CacheRuleSchema:()=>Ke,CacheSchema:()=>Qe,EventCacheRuleSchema:()=>He,EventCacheSchema:()=>Ze,StoreCacheRuleSchema:()=>Ve,StoreCacheSchema:()=>Ge});var He=i.object({match:Fe.optional().describe("Optional match expression — omit for always-match."),key:i.array(i.string()).min(1).describe("Dot-path fields used to build the cache key"),ttl:i.number().positive().describe("Time-to-live in seconds"),update:i.record(i.string(),ue).optional().describe("Response mutations applied on cache hit (key → Value mapping)")}).meta({id:"EventCacheRule",title:"EventCache.Rule",description:"Single event-cache rule: when it applies (match), what event fields it keys off, TTL, and optional response mutations on hit."}),Ze=i.object({stop:i.boolean().optional().describe("Stop the chain on cache HIT (default: false). When true, skip remaining steps and return cached value."),store:i.string().optional().describe("Store ID for persistent caching (references a configured store)"),namespace:i.string().optional().describe("Optional key prefix. Omit to write keys directly to the store. Same store + same key + same namespace = same cache entry."),rules:i.array(He).min(1).describe("Cache rules — at least one required")}).meta({id:"EventCacheConfig",title:"EventCache.Config",description:"Top-level cache configuration for an event-context pipeline step (source / transformer / destination)."}),Ve=i.strictObject({match:Fe.optional().describe("Optional match expression evaluated against `{ key, value? }`. Omit for always-match."),ttl:i.number().positive().describe("Time-to-live in seconds")}).meta({id:"StoreCacheRule",title:"StoreCache.Rule",description:"Single store-cache rule: optional match against `{ key, value? }` and a TTL. No `key` (caller provides it) and no `update` (no event to mutate)."}),Ge=i.strictObject({store:i.string().optional().describe("Store ID for persistent caching (references a configured store)"),namespace:i.string().min(1).optional().describe("Optional key prefix. Omit to default to the host store id. Empty string is rejected."),rules:i.array(Ve).min(1).describe("Cache rules — at least one required")}).meta({id:"StoreCacheConfig",title:"StoreCache.Config",description:"Top-level cache configuration for a store wrapper. No `stop` (always falls through on miss); namespace defaults to the host store id."}),Ke=He,Qe=Ze,Ye=/^(event|ingest)(\..+)?$/,Xe=/^(event|ingest)\..+$/;function et(e){return"string"==typeof e?[e]:Array.isArray(e)?e.flatMap(et):"object"==typeof e&&null!==e&&"key"in e&&"string"==typeof e.key?[e.key]:[]}function tt(e,t,n,i){for(const o of et(e))i.test(o)||n.addIssue({code:"custom",message:`State paths resolve against { event, ingest }: "${o}" needs an "event." or "ingest." prefix.`,path:[t]})}var nt=i.object({mode:i.enum(["get","set"]).describe("Direction: 'get' reads from the store, 'set' writes to it"),store:i.string().optional().describe("Store id; defaults to the in-memory __cache store when omitted"),key:ue.describe("Resolves against { event, ingest } to the store key. Paths need an event. or ingest. prefix"),value:ue.optional().describe("set: resolves against { event, ingest } to the payload to store. get: its path is the write target, event. onto the event or ingest. into the ingest."),mapping:ue.optional().describe("Shapes the value read (get) or the payload (set). Paths are relative to that value. The result merges into the target.")}).superRefine((e,t)=>{if(tt(e.key,"key",t,Xe),void 0!==e.value){if(tt(e.value,"value",t,"get"===e.mode?Xe:Ye),"get"===e.mode){const n=e.value;let i;if("string"==typeof n)i=n;else if("object"==typeof n&&null!==n&&!Array.isArray(n)&&"key"in n&&"string"==typeof n.key){if(["value","fn","map","loop","set"].filter(e=>e in n).length>0)return void t.addIssue({code:"custom",message:'For mode "get", `value` may only provide a `key` path.',path:["value"]});i=n.key}if(void 0===i)return void t.addIssue({code:"custom",message:'For mode "get", `value` must be a bare string path or a ValueConfig with a `key` (no value/fn/map/loop/set).',path:["value"]});i.includes("*")&&t.addIssue({code:"custom",message:'For mode "get", the `value` path may not contain `*`.',path:["value"]})}}else t.addIssue({code:"custom",message:`\`value\` is required for mode "${e.mode}".`,path:["value"]})}).meta({id:"StateConfig",title:"State.Config",description:"Declarative store operation: stash (set) or fetch (get) a value against a store. key names the store slot, value the event or ingest side, mode the direction. Paths resolve against { event, ingest }."}),it=i.any().meta({id:"LoggerHandler",title:"Logger.Handler",description:"Custom log handler function (level, ...args) => void"}),ot=i.object({level:i.union([i.number(),i.enum(["ERROR","WARN","INFO","DEBUG"])]).optional().describe("Minimum log level (default: ERROR)"),handler:it.optional().describe("Custom log handler function")}).meta({id:"LoggerConfig",title:"Logger.Config",description:"Logger configuration (level, handler) to override the collector defaults"}),rt=i.object({consent:V.optional().describe("Required consent states to send events to this destination"),settings:i.any().meta({id:"DestinationSettings",title:"Destination.Settings",description:"Implementation-specific configuration (destination-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.any().meta({id:"DestinationCredentials",title:"Destination.Credentials",description:"Optional credentials slot (destination-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (destination-defined shape)").optional(),data:i.union([ue,fe]).optional().describe("Global data transformation applied to all events for this destination"),include:i.array(i.string()).optional().describe("Event sections to flatten into context.data"),env:i.any().meta({id:"DestinationEnv",title:"Destination.Env",description:"Environment dependencies (destination-defined shape) — platform, SDK, or mock hook."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Destination instance identifier (defaults to destination key)").optional(),init:i.boolean().describe("Whether to initialize immediately").optional(),loadScript:i.boolean().describe("Whether to load external script (for web destinations)").optional(),mapping:we.optional().describe("Entity-action specific mapping rules for this destination"),policy:ve.optional().describe("Pre-processing policy rules applied before event mapping"),queue:i.boolean().describe("Whether a destination added later receives events pushed earlier in the current run (default true). Consent-denied events are queued regardless.").optional(),require:i.array(i.string()).optional().describe('Defer destination initialization until these collector events fire (e.g., ["consent"])'),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during destination registration (boolean enables defaults, object configures specifics)"),before:Ue.optional().describe("Transformer chain run for this destination only, before it receives the event."),next:Ue.optional().describe("Post-push transformer chain. Runs after destination push completes; push response is available at ingest._response."),cache:Ze.optional().describe("Cache configuration for deduplication; skip push on cache HIT"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this destination"),disabled:i.boolean().describe("Completely skip this destination (no init, no push, no queue)").optional(),mock:i.unknown().meta({id:"DestinationMock",title:"Destination.Mock",description:"Return this value instead of calling push(). Dev/testing only."}).optional().describe("Return this value instead of calling push(). Dev/testing only."),queueMax:i.number().optional().describe("Maximum consent-denied events retained in queuePush for this destination. FIFO drop on overflow. Default 1000."),dlqMax:i.number().optional().describe("Maximum failed-push entries retained in dlq for this destination. FIFO drop on overflow. Default 100."),timeout:i.number().optional().describe("Per-destination delivery timeout in ms (default 10000); a delivery that does not settle in this window is routed to the DLQ like a thrown push."),batch:i.union([i.number(),i.object({wait:i.number().optional(),size:i.number().optional(),age:i.number().optional()})]).optional().describe("Enables batching for all of this destination's events into one shared default buffer; a mapping rule's own batch splits that entity-action into its own buffer and overrides per field. Bare number is the debounce wait window; object form supports wait (debounce ms), size (count cap, default 1000), age (max ms since first entry, default 30000)."),breaker:i.union([i.number(),i.object({threshold:i.number().optional(),cooldown:i.number().optional()})]).optional().describe("Per-destination circuit breaker (presence-gated). After threshold consecutive transport failures the breaker opens and events are skipped until cooldown ms elapse, then one probe is admitted; success closes it, failure re-opens it. Partial-batch row failures are breaker-neutral. Bare number is the threshold; object form supports threshold (default 5) and cooldown (default 30000ms).")}).meta({id:"DestinationConfig",title:"Destination.Config",description:"Destination configuration: consent, settings, data, env, mapping rules, policy, queue, logger, before/next chains, cache."}).describe("Destination configuration"),st=rt.partial().meta({id:"DestinationPartialConfig",title:"Destination.PartialConfig",description:"Partial destination configuration with all fields optional."}).describe("Partial destination configuration with all fields optional"),at=ve.describe("Destination policy rules for event pre-processing"),ct=i.object({collector:i.unknown().meta({id:"DestinationContextCollector",title:"Collector.Instance",description:"Collector instance handed to the destination (runtime object)."}).describe("Collector instance (runtime object)"),config:rt.describe("Destination configuration"),data:i.union([i.unknown(),i.array(i.unknown())]).optional().describe("Transformed event data"),env:i.unknown().meta({id:"DestinationContextEnv",title:"Destination.Env",description:"Environment dependencies (destination-defined shape)."}).describe("Environment dependencies")}).meta({id:"DestinationContext",title:"Destination.Context",description:"Destination context passed to init and push functions."}).describe("Destination context for init and push functions"),lt=ct.extend({mapping:Se.optional().describe("Resolved mapping rule for this specific event")}).meta({id:"DestinationPushContext",title:"Destination.PushContext",description:"Destination context for push() with the resolved event mapping rule."}).describe("Push context with event-specific mapping"),dt=lt.describe("Batch push context with event-specific mapping"),pt=i.object({event:ee.describe("The event to process"),mapping:Se.optional().describe("Mapping rule for this event")}).meta({id:"DestinationPushEvent",title:"Destination.PushEvent",description:"Single event paired with its resolved mapping rule (batch element)."}).describe("Event with optional mapping for batch processing"),ut=i.array(pt).meta({id:"DestinationPushEvents",title:"Destination.PushEvents",description:"Array of events with mappings (batch input)."}).describe("Array of events with mappings"),ft=i.object({key:i.string().describe('Batch key (usually mapping key like "product.view")'),events:i.array(ee).describe("Array of events in batch"),data:i.array(i.union([i.unknown(),i.array(i.unknown())]).optional()).describe("Transformed data for each event"),mapping:Se.optional().describe("Shared mapping rule for batch")}).meta({id:"DestinationBatch",title:"Destination.Batch",description:"Batch of events grouped by mapping key for batch delivery."}).describe("Batch of events grouped by mapping key"),mt=i.union([i.unknown(),i.array(i.unknown())]).meta({id:"DestinationData",title:"Destination.Data",description:"Transformed event data delivered to the destination (Property, undefined, or array)."}).optional().describe("Transformed event data (Property, undefined, or array)"),gt=i.object({config:rt.describe("Destination configuration"),queue:i.array(ee).optional().describe("Queued events awaiting consent"),dlq:i.array(i.tuple([ee,i.unknown()])).optional().describe("Dead letter queue (failed events with errors)"),type:i.string().optional().describe("Destination type identifier"),env:i.unknown().optional().describe("Environment dependencies"),init:i.unknown().optional().describe("Initialization function"),push:i.unknown().describe("Push function for single events"),pushBatch:i.unknown().optional().describe("Batch push function"),on:i.unknown().optional().describe("Event lifecycle hook function")}).meta({id:"DestinationInstance",title:"Destination.Instance",description:"Destination instance (runtime object with init/push/pushBatch/on)."}).describe("Destination instance (runtime object with functions)"),ht=i.object({code:gt.describe("Destination instance with implementation"),config:st.optional().describe("Partial configuration overrides"),env:i.unknown().optional().describe("Partial environment overrides")}).meta({id:"DestinationInit",title:"Destination.Init",description:"Destination initialization bundle (instance code + config + env)."}).describe("Destination initialization configuration"),bt=i.record(i.string(),ht).meta({id:"DestinationInitDestinations",title:"Destination.InitDestinations",description:"Map of destination IDs to initialization configurations."}).describe("Map of destination IDs to initialization configurations"),vt=i.record(i.string(),gt).meta({id:"DestinationDestinations",title:"Destination.Destinations",description:"Map of destination IDs to runtime destination instances."}).describe("Map of destination IDs to runtime instances"),yt=i.object({type:i.string().describe('Destination type ("gtag", "meta", "bigquery")'),data:i.unknown().optional().describe("Response from push()"),error:i.unknown().optional().describe("Error if failed")}).meta({id:"DestinationRef",title:"Destination.Ref",description:"Reference to a destination outcome (type + response data or error)."}).describe("Destination reference with type and response data"),St=i.object({queue:i.array(ee).optional().describe("Events queued (awaiting consent)"),error:i.unknown().optional().describe("Error if push failed")}).meta({id:"DestinationPushResult",title:"Destination.PushResult",description:"Result of a single destination push (queued events, optional error)."}).describe("Push operation result"),wt=i.object({ok:i.boolean().describe("True if nothing failed"),event:i.unknown().optional().describe("The processed event"),done:i.record(i.string(),yt).optional().describe("Destinations that processed successfully"),queued:i.record(i.string(),yt).optional().describe("Destinations that queued events"),failed:i.record(i.string(),yt).optional().describe("Destinations that failed to process")}).meta({id:"DestinationResult",title:"Destination.Result",description:"Overall push result aggregated across all destinations (done/queued/failed maps)."}).describe("Push result with destination outcomes"),kt=i.array(i.tuple([ee,i.unknown()])).meta({id:"DestinationDLQ",title:"Destination.DLQ",description:"Dead-letter queue: list of [event, error] tuples."}).describe("Dead letter queue: [(event, error), ...]"),Ct=o(rt),xt=o(st),jt=o(ct),Et=o(lt),Ot=o(ft),$t=o(gt),Pt=o(wt),Dt={};t(Dt,{CommandTypeSchema:()=>It,ConfigSchema:()=>At,DestinationsSchema:()=>Ft,InitConfigSchema:()=>Rt,InstanceSchema:()=>Nt,PushContextSchema:()=>Jt,SessionDataSchema:()=>Tt,SourcesSchema:()=>Mt,commandTypeJsonSchema:()=>zt,configJsonSchema:()=>Lt,initConfigJsonSchema:()=>qt,instanceJsonSchema:()=>Ut,pushContextJsonSchema:()=>Wt,sessionDataJsonSchema:()=>_t});var It=i.union([i.enum(["action","config","consent","context","destination","elb","globals","hook","init","link","run","user","walker"]),i.string()]).meta({id:"CollectorCommandType",title:"Collector.CommandType",description:"Collector command type identifier (standard or extension string)."}).describe("Collector command type: standard commands or custom string for extensions"),At=i.object({run:i.boolean().describe("Whether to run collector automatically on initialization").optional(),globalsStatic:B.describe("Static global properties that persist across collector runs"),sessionStatic:i.record(i.string(),i.unknown()).meta({id:"CollectorSessionStatic",title:"Collector.SessionStatic",description:"Static session data that persists across collector runs."}).describe("Static session data that persists across collector runs"),logger:ot.optional().describe("Logger configuration (level, handler)"),queueMax:i.number().optional().describe("Maximum events retained in collector.queue (late-registration replay). FIFO drop on overflow. Default 1000."),name:i.string().optional().describe("Flow name; keys this flow's entry in event.source.release and the observer flowId."),release:i.string().optional().describe("Config release id stamped into event.source.release for this flow."),next:Ue.optional().describe("Collector chain: runs once per completed event before the destination fan-out. A stop drops the event for every destination.")}).meta({id:"CollectorConfig",title:"Collector.Config",description:"Core collector configuration (globals/session statics, logger, buffer bounds)."}).describe("Core collector configuration"),Tt=B.and(i.object({isStart:i.boolean().describe("Whether this is a new session start"),storage:i.boolean().describe("Whether storage is available"),id:c.describe("Session identifier").optional(),start:l.describe("Session start timestamp").optional(),marketing:i.literal(!0).optional().describe("Marketing attribution flag"),updated:l.describe("Last update timestamp").optional(),isNew:i.boolean().describe("Whether this is a new session").optional(),device:c.describe("Device identifier").optional(),count:d.describe("Event count in session").optional(),runs:d.describe("Number of runs").optional()})).meta({id:"CollectorSessionData",title:"Collector.SessionData",description:"Session state and tracking data."}).describe("Session state and tracking data"),Rt=At.partial().extend({consent:V.optional().describe("Initial consent state"),user:G.optional().describe("Initial user data"),globals:B.optional().describe("Initial global properties"),sources:i.unknown().meta({id:"CollectorInitSources",title:"Source.InitSources",description:"Source configurations map (id → InitSource)."}).optional().describe("Source configurations"),destinations:i.unknown().meta({id:"CollectorInitDestinations",title:"Destination.InitDestinations",description:"Destination configurations map (id → Init)."}).optional().describe("Destination configurations"),transformers:i.unknown().meta({id:"CollectorInitTransformers",title:"Transformer.Configs",description:"Transformer configurations map (id → Config)."}).optional().describe("Transformer configurations"),stores:i.unknown().meta({id:"CollectorInitStores",title:"Store.Configs",description:"Store configurations map (id → Config)."}).optional().describe("Store configurations"),custom:B.optional().describe("Initial custom implementation-specific properties"),hooks:i.unknown().meta({id:"CollectorHooks",title:"Collector.Hooks",description:"Pipeline observation hooks."}).optional().describe("Pipeline observation hooks"),observe:i.union([i.object({url:i.string().describe("Observer base URL"),binding:i.string().describe("Public project binding the web credential must match")}),i.object({url:i.string().describe("Observer base URL"),sessionId:i.string().describe("Session id the runtime posts under"),token:i.string().describe("Ingest bearer token"),level:i.enum(["off","standard","trace"]).optional().describe("Telemetry level"),sample:i.number().optional().describe("Deterministic sample fraction in [0, 1]")})]).meta({id:"CollectorObserve",title:"Observe",description:"Observation session connect config: web arm (url + binding) or server arm (url + sessionId + token)."}).optional().describe("Observation session connect config"),observers:i.unknown().meta({id:"CollectorObservers",title:"Collector.Observers",description:"Caller-supplied advisory observer functions (runtime objects)."}).optional().describe("Caller-supplied advisory observer functions")}).meta({id:"CollectorInitConfig",title:"Collector.InitConfig",description:"Collector initialization configuration with initial state (consent, user, globals, components, hooks)."}).describe("Collector initialization configuration with initial state"),Jt=i.object({mapping:ke.optional().describe("Source-level mapping configuration")}).meta({id:"CollectorPushContext",title:"Collector.PushContext",description:"Push context with optional source-level mapping."}).describe("Push context with optional source mapping"),Mt=i.record(i.string(),i.unknown()).meta({id:"CollectorSources",title:"Collector.Sources",description:"Map of source IDs to runtime source instances."}).describe("Map of source IDs to source instances"),Ft=i.record(i.string(),i.unknown()).meta({id:"CollectorDestinations",title:"Collector.Destinations",description:"Map of destination IDs to runtime destination instances."}).describe("Map of destination IDs to destination instances"),Nt=i.object({push:i.unknown().describe("Push function for processing events"),command:i.unknown().describe("Command function for walker commands"),allowed:i.boolean().describe("Whether event processing is allowed"),config:At.describe("Current collector configuration"),consent:V.describe("Current consent state"),custom:B.describe("Custom implementation-specific properties"),sources:Mt.describe("Registered source instances"),destinations:Ft.describe("Registered destination instances"),globals:B.describe("Current global properties"),hooks:i.unknown().describe("Lifecycle hook functions"),on:i.unknown().describe("Event lifecycle configuration"),queue:i.array(ee).describe("Queued events awaiting processing"),round:i.number().describe("Collector run count (increments with each run)"),session:i.union([Tt]).describe("Current session state"),timing:i.number().describe("Event processing timing information"),user:G.describe("Current user data")}).meta({id:"CollectorInstance",title:"Collector.Instance",description:"Collector instance (runtime object with push/command + full state and component maps)."}).describe("Collector instance with state and methods"),zt=o(It),Lt=o(At),_t=o(Tt),qt=o(Rt),Wt=o(Jt),Ut=o(Nt),Bt={};t(Bt,{BaseEnvSchema:()=>Ht,ConfigSchema:()=>Zt,InitSchema:()=>Kt,InitSourceSchema:()=>Qt,InitSourcesSchema:()=>Yt,InstanceSchema:()=>Gt,PartialConfigSchema:()=>Vt,baseEnvJsonSchema:()=>Xt,configJsonSchema:()=>en,initSourceJsonSchema:()=>on,initSourcesJsonSchema:()=>rn,instanceJsonSchema:()=>nn,partialConfigJsonSchema:()=>tn});var Ht=i.object({push:i.unknown().meta({id:"SourcePushFn",title:"Source.PushFn",description:"Collector push function passed to the source via dependency injection."}).describe("Collector push function"),command:i.unknown().meta({id:"SourceCommandFn",title:"Source.CommandFn",description:"Collector command function passed to the source."}).describe("Collector command function"),sources:i.unknown().optional().describe("Map of registered source instances"),elb:i.unknown().meta({id:"ElbFn",title:"Elb.Fn",description:"Public `elb(...)` API function alias for collector.push."}).describe("Public API function (alias for collector.push)")}).catchall(i.unknown()).meta({id:"SourceBaseEnv",title:"Source.BaseEnv",description:"Base environment for source dependency injection; platform-specific sources extend this."}).describe("Base environment for dependency injection - platform-specific sources extend this"),Zt=ke.extend({settings:i.any().meta({id:"SourceSettings",title:"Source.Settings",description:"Implementation-specific configuration (source-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.any().meta({id:"SourceCredentials",title:"Source.Credentials",description:"Optional credentials slot (source-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (source-defined shape)").optional(),env:Ht.optional().describe("Environment dependencies (platform-specific)"),id:c.describe("Source identifier (defaults to source key)").optional(),primary:i.boolean().describe("Mark as primary (only one can be primary)").optional(),require:i.array(i.string()).optional().describe('Defer source initialization until these collector events fire (e.g., ["consent"])'),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),async:i.union([i.boolean(),i.record(i.string(),i.boolean())]).optional().describe('Respond-first acknowledgement for response-producing server sources. When true the source responds 2xx ("accepted") before the event is delivered; when false it waits for delivery to settle and the response reflects the outcome. A record configures this per source-defined key: the express source keys it by HTTP method (GET/POST) and defaults to { GET: false, POST: true }. Browser/dataLayer sources have no HTTP response to defer and ignore it. A 2xx means accepted, not delivered. Defaults are per source type.'),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during source registration (boolean enables defaults, object configures specifics)"),ingest:i.union([ue,fe]).optional().describe("Ingest metadata extraction mapping. Extracts values from raw request objects (Express req, Lambda event) using mapping syntax."),disabled:i.boolean().describe("Completely skip this source (no init, no event capture)").optional(),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this source"),init:i.boolean().optional().describe("Init lifecycle flag set by collector to true after Instance.init() runs")}).meta({id:"SourceConfig",title:"Source.Config",description:"Source configuration with mapping, environment, and lifecycle hooks."}).describe("Source configuration with mapping and environment"),Vt=Zt.partial().meta({id:"SourcePartialConfig",title:"Source.PartialConfig",description:"Partial source configuration with all fields optional."}).describe("Partial source configuration with all fields optional"),Gt=i.object({type:i.string().describe('Source type identifier (e.g., "browser", "dataLayer")'),config:Zt.describe("Current source configuration"),push:i.any().meta({id:"SourceInstancePushFn",title:"Source.PushFn",description:"Push function — THE HANDLER (flexible signature for platform compatibility)."}).describe("Push function - THE HANDLER (flexible signature for platform compatibility)"),destroy:i.any().meta({id:"SourceDestroyFn",title:"Source.DestroyFn",description:"Cleanup function called when the source is removed."}).optional().describe("Cleanup function called when source is removed"),on:i.unknown().optional().describe("Lifecycle hook function for event types")}).meta({id:"SourceInstance",title:"Source.Instance",description:"Source instance (runtime object with push handler and lifecycle methods)."}).describe("Source instance with push handler and lifecycle methods"),Kt=i.any().meta({id:"SourceInit",title:"Source.Init",description:"Source initialization function: (config, env) => Instance | Promise<Instance>."}).describe("Source initialization function: (config, env) => Instance | Promise<Instance>"),Qt=i.object({code:Kt.describe("Source initialization function"),config:Vt.optional().describe("Partial configuration overrides"),env:Ht.partial().optional().describe("Partial environment overrides"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this source"),primary:i.boolean().optional().describe("Mark as primary source (only one can be primary)")}).meta({id:"SourceInitSource",title:"Source.InitSource",description:"Source initialization bundle (init function + config + env + primary flag)."}).describe("Source initialization configuration"),Yt=i.record(i.string(),Qt).meta({id:"SourceInitSources",title:"Source.InitSources",description:"Map of source IDs to initialization configurations."}).describe("Map of source IDs to initialization configurations"),Xt=o(Ht),en=o(Zt),tn=o(Vt),nn=o(Gt),on=o(Qt),rn=o(Yt),sn={};t(sn,{ConfigSchema:()=>an,PartialConfigSchema:()=>cn,configJsonSchema:()=>ln,partialConfigJsonSchema:()=>dn});var an=i.object({settings:i.any().meta({id:"TransformerSettings",title:"Transformer.Settings",description:"Implementation-specific configuration (transformer-defined shape)."}).describe("Implementation-specific configuration").optional(),env:i.any().meta({id:"TransformerEnv",title:"Transformer.Env",description:"Environment dependencies (transformer-defined shape)."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Transformer instance identifier (defaults to transformer key)").optional(),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),before:Ue.optional().describe("Pre-transformer chain that runs before this transformer pushes"),next:Ue.optional().describe("Graph wiring to the next transformer in the chain"),cache:Ze.optional().describe("Step-level cache configuration for this transformer"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set operations applied around this transformer"),init:i.boolean().describe("Whether to initialize immediately").optional(),disabled:i.boolean().describe("Completely skip this transformer in chains").optional(),mock:i.unknown().meta({id:"TransformerMock",title:"Transformer.Mock",description:"Return this value instead of calling push(). Dev/testing only."}).optional().describe("Return this value instead of calling push(). Global mock for all chains. Dev/testing only."),chainMocks:i.record(i.string(),i.unknown().meta({id:"TransformerChainMock",title:"Transformer.ChainMock",description:"Chain-path-specific mock value. Dev/testing only."})).optional().describe("Path-specific mock values keyed by chain path. Takes precedence over global mock. Dev/testing only."),mapping:ke.optional().describe("Declarative event-to-event mapping applied when this transformer step has no code. At this position, only event-mutating fields apply (policy, mapping[].policy, mapping[].name, mapping[].ignore, mapping[].consent, include); vendor-payload fields are ignored.")}).strict().meta({id:"TransformerConfig",title:"Transformer.Config",description:"Transformer configuration (settings, env, chain wiring, cache, mocks)."}).describe("Transformer configuration"),cn=an.partial().meta({id:"TransformerPartialConfig",title:"Transformer.PartialConfig",description:"Partial transformer configuration with all fields optional."}).describe("Partial transformer configuration with all fields optional"),ln=o(an),dn=o(cn),pn={};t(pn,{ConfigSchema:()=>un,PartialConfigSchema:()=>fn,configJsonSchema:()=>mn,partialConfigJsonSchema:()=>gn});var un=i.object({settings:i.unknown().meta({id:"StoreSettings",title:"Store.Settings",description:"Implementation-specific configuration (store-defined shape)."}).describe("Implementation-specific configuration").optional(),credentials:i.unknown().meta({id:"StoreCredentials",title:"Store.Credentials",description:"Optional credentials slot (store-defined shape); back it with a managed secret via $secret.NAME (credentials use $secret, not $env). The per-package shape is supplied via mergeConfigSchema."}).describe("Optional credentials (store-defined shape)").optional(),env:i.unknown().meta({id:"StoreEnv",title:"Store.Env",description:"Environment dependencies (store-defined shape)."}).describe("Environment dependencies (platform-specific)").optional(),id:c.describe("Store instance identifier (defaults to store key)").optional(),logger:ot.optional().describe("Logger configuration (level, handler) to override the collector defaults"),setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during store registration (boolean enables defaults, object configures specifics)"),file:i.boolean().optional().describe("Persist values as raw bytes (byte-exact), bypassing the structured codec. Default false (structured). Set true only on byte-native stores for asset serving; sheets rejects it.")}).meta({id:"StoreConfig",title:"Store.Config",description:"Store configuration (settings, env, logger): key-value infrastructure component."}).describe("Store configuration"),fn=un.partial().meta({id:"StorePartialConfig",title:"Store.PartialConfig",description:"Partial store configuration with all fields optional."}).describe("Partial store configuration with all fields optional"),mn=o(un),gn=o(fn),hn={};t(hn,{BundlePackageSchema:()=>xn,BundleSchema:()=>jn,CodeSchema:()=>En,ConfigSchema:()=>Wn,ContractActionsSchema:()=>Nn,ContractEventsSchema:()=>zn,ContractRuleSchema:()=>Ln,ContractSchema:()=>_n,ContractSchemaEntry:()=>Fn,DestinationSchema:()=>Jn,FlowSchema:()=>Un,JsonSchema:()=>Bn,JsonSchemaSchema:()=>Dn,ObserveSchema:()=>qn,SettingsSchema:()=>kn,SourceSchema:()=>Tn,StepExampleSchema:()=>$n,StepExamplesSchema:()=>Pn,StoreSchema:()=>Mn,TransformerSchema:()=>Rn,TriggerDescriptorSchema:()=>On,ValidateEventsSchema:()=>In,VariablesSchema:()=>yn,configJsonSchema:()=>Kn,contractJsonSchema:()=>oi,contractRuleJsonSchema:()=>ii,destinationJsonSchema:()=>ei,flowConfigJsonSchema:()=>Yn,flowJsonSchema:()=>Qn,parseConfig:()=>Hn,parseFlow:()=>Vn,safeParseConfig:()=>Zn,safeParseFlow:()=>Gn,sourceJsonSchema:()=>Xn,storeJsonSchema:()=>ni,transformerJsonSchema:()=>ti,validateEventsJsonSchema:()=>ri});var bn=["elb","elbLayer","window","document","location","self","top","parent","frames","globalThis","__proto__","constructor","prototype"],vn=/^[A-Za-z_$][A-Za-z0-9_$]*$/;var yn=i.record(i.string(),i.unknown()).meta({id:"FlowVariables",title:"Flow.Variables",description:"Reusable values referenced via $var.name (with optional deep paths). Whole-string refs preserve native type; inline interpolation requires scalars."}),Sn=/\$(?:var|env)\./,wn=i.string().superRefine((e,t)=>{if(Sn.test(e))return;const n=function(e){return"string"!=typeof e?{ok:!1,reason:"is not a string"}:vn.test(e)?bn.includes(e)?{ok:!1,reason:`is reserved (${bn.join(", ")})`}:{ok:!0,name:e}:{ok:!1,reason:"is not a JavaScript identifier (letters, digits, _ or $, not starting with a digit)"}}(e);n.ok||t.addIssue({code:"custom",message:`windowCollector ${JSON.stringify(e)} ${n.reason}`})}),kn=i.looseObject({windowCollector:wn.optional().describe('Web: global variable name of the collector instance (default: "walkerOS").')}).meta({id:"FlowSettings",title:"Flow.Settings",description:"Free-form key-value settings consumed by the platform runtime."}).describe("Free-form platform settings bag"),Cn=/^(@[a-z0-9\-~][a-z0-9\-._~]*\/)?[a-z0-9\-~][a-z0-9\-._~]*$/,xn=i.object({version:i.string().optional(),imports:i.array(i.string()).optional(),path:i.string().optional()}).meta({id:"FlowBundlePackage",title:"Flow.BundlePackage",description:"Per-package bundle spec (version / imports / local path)."}),jn=i.object({packages:i.record(i.string().regex(Cn,"Invalid npm package name"),xn).optional().describe("NPM packages to bundle, keyed by package name"),overrides:i.record(i.string().regex(Cn,"Invalid npm package name"),i.string().min(1,"Override version cannot be empty")).optional().describe("Transitive dependency version pins"),traceInclude:i.array(i.string()).optional().describe("Extra paths or globs the bundler must include in the trace output (server flows only)"),env:i.record(i.string(),i.string()).optional().describe("Declared build-time values for web $env references (inlined into public bundles, never secrets)")}).strict().meta({id:"FlowBundle",title:"Flow.Bundle",description:"Bundle configuration (packages + overrides + traceInclude + env)."}).describe("Bundle configuration (packages + overrides + traceInclude + env)"),En=i.object({push:i.string().min(1,"Push function cannot be empty").describe('JavaScript function for processing events. Must start with "$code:" prefix.'),type:i.string().optional().describe("Optional type identifier for the inline instance"),init:i.string().optional().describe("Optional initialization function. Use $code: prefix for inline JavaScript.")}).meta({id:"FlowCode",title:"Flow.Code",description:"Inline code block (object form) for custom sources / transformers / destinations / stores. Use `import` on the step to select a named export from a package."}).describe("Inline code for custom components (object form)"),On=i.object({type:i.string().optional().describe("Trigger mechanism (e.g., click, POST, load)"),options:i.unknown().optional().describe("Mechanism-specific options")}).meta({id:"TriggerDescriptor",title:"Trigger.Descriptor",description:"Source trigger metadata (mechanism + options) used by step examples."}),$n=i.object({title:i.string().optional().describe("Human-readable title (overrides default heading)"),description:i.string().optional().describe("Human-readable description"),public:i.boolean().optional().describe("Whether this example is shown in docs/UI/MCP default output (default: true). Set false for test-only fixtures."),in:i.unknown().optional().describe("Input to the step"),trigger:On.optional().describe("Source trigger metadata"),mapping:i.unknown().optional().describe("Mapping configuration"),out:i.unknown().optional().describe("Expected output from the step"),command:i.enum(["config","consent","user","run"]).optional().describe("Invoke elb('walker <command>', in) instead of pushing in as an event")}).meta({id:"FlowStepExample",title:"Flow.StepExample",description:"Named example with input/output pair used for step testing."}).describe("Named example with input/output pair"),Pn=i.record(i.string(),$n).meta({id:"FlowStepExamples",title:"Flow.StepExamples",description:"Named step examples keyed by scenario name."}).describe("Named step examples for testing and documentation"),Dn=i.record(i.string(),i.unknown()).meta({id:"JsonSchema",title:"JsonSchema",description:"Structural JSON Schema fragment (Record<string, unknown>)"}),In=i.record(i.string(),i.record(i.string(),Dn)).meta({id:"ValidateEvents",title:"ValidateEvents",description:"Entity-action keyed JSON Schemas"}).describe("Entity-action keyed JSON Schemas");function An(e,t){void 0!==e.import&&(void 0!==e.code&&t.addIssue({code:"custom",message:"`import` cannot be combined with inline `code`",path:["import"]}),void 0===e.package&&t.addIssue({code:"custom",message:"`import` requires `package`",path:["import"]}))}var Tn=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/web-source-browser@2.0.0")'),code:En.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during source registration (boolean enables defaults, object configures specifics)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set, run before the collector receives the event. Takes precedence over a step-level state.")}).meta({id:"FlowSourceConfig",title:"Source.Config",description:"Source-specific configuration object (Source.Config)."}).optional().describe("Source-specific configuration object"),env:i.unknown().meta({id:"FlowSourceEnv",title:"Source.BaseEnv",description:"Source environment configuration (Source.BaseEnv overrides)."}).optional().describe("Source environment configuration"),primary:i.boolean().optional().describe("Mark as primary source (provides main elb). Only one source should be primary."),variables:yn.optional().describe("Source-level variables (highest priority in cascade)"),next:Ue.optional().describe("Pre-collector transformer chain. String, string[], or Route[] for conditional routing on ingest and event data."),before:Ue.optional().describe("Pre-source transformer chain (consent-exempt). Handles transport-level preprocessing."),examples:Pn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ze.optional().describe("Cache configuration for this source (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this source. Paths resolve against { event, ingest }.")}).strict().meta({id:"FlowSource",title:"Flow.Source",description:"Source package reference with configuration, env, chains, and examples."}).describe("Source package reference with configuration").superRefine(An),Rn=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/transformer-enricher@1.0.0")'),code:En.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.unknown().meta({id:"FlowTransformerConfig",title:"Transformer.Config",description:"Transformer-specific configuration object."}).optional().describe("Transformer-specific configuration object"),env:i.unknown().meta({id:"FlowTransformerEnv",title:"Transformer.Env",description:"Transformer environment configuration."}).optional().describe("Transformer environment configuration"),before:Ue.optional().describe("Pre-transformer chain. Runs before this transformer push function."),next:Ue.optional().describe("Next transformer in chain. String, string[], or Route[] for conditional routing."),variables:yn.optional().describe("Transformer-level variables (highest priority in cascade)"),examples:Pn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ze.optional().describe("Cache configuration for this transformer (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this transformer. Paths resolve against { event, ingest }."),mapping:i.unknown().optional().describe("Event mapping for a code-free transformer. The collector applies it to the event; a rule with ignore: true drops it.")}).meta({id:"FlowTransformer",title:"Flow.Transformer",description:"Transformer package reference with configuration, env, chains, and cache."}).describe("Transformer package reference with configuration").superRefine(An),Jn=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe('Package specifier with optional version (e.g., "@walkeros/web-destination-gtag@2.0.0")'),code:En.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during destination registration (boolean enables defaults, object configures specifics)")}).meta({id:"FlowDestinationConfig",title:"Destination.Config",description:"Destination-specific configuration object."}).optional().describe("Destination-specific configuration object"),env:i.unknown().meta({id:"FlowDestinationEnv",title:"Destination.Env",description:"Destination environment configuration."}).optional().describe("Destination environment configuration"),variables:yn.optional().describe("Destination-level variables (highest priority in cascade)"),before:Ue.optional().describe("Transformer chain run for this destination only, before it receives the event. String, string[], or a Route for conditional routing."),next:Ue.optional().describe("Post-push transformer chain. Push response available at context.ingest._response."),examples:Pn.optional().describe("Named step examples for testing and documentation (stripped during bundling)"),cache:Ze.optional().describe("Cache configuration for this destination (match → key → ttl rules)"),state:i.union([nt,i.array(nt)]).optional().describe("Declarative store get/set for this destination. Paths resolve against { event, ingest }.")}).meta({id:"FlowDestination",title:"Flow.Destination",description:"Destination package reference with configuration, env, chains, and cache."}).describe("Destination package reference with configuration").superRefine(An),Mn=i.object({package:i.string().min(1,"Package name cannot be empty").optional().describe("Store package specifier with optional version"),code:En.optional().describe("Inline code definition (object form). For a named export from a package, use `import` instead."),import:i.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/,"import must be a valid JavaScript identifier").optional().describe("Named export from `package` to import as this step's implementation. Top-level identifier only. Requires `package`. Mutually exclusive with `code`."),config:i.looseObject({setup:i.union([i.boolean(),i.record(i.string(),i.unknown())]).optional().describe("One-time setup options applied during store registration (boolean enables defaults, object configures specifics)")}).meta({id:"FlowStoreConfig",title:"Store.Config",description:"Store-specific configuration object."}).optional().describe("Store-specific configuration object"),env:i.unknown().meta({id:"FlowStoreEnv",title:"Store.Env",description:"Store environment configuration."}).optional().describe("Store environment configuration"),cache:Ge.optional().describe("Cache configuration for this store (TTL-only rules, optional recursive `cache.store`)"),variables:yn.optional().describe("Store-level variables (highest priority in cascade)"),examples:Pn.optional().describe("Named step examples for testing and documentation (stripped during bundling)")}).meta({id:"FlowStore",title:"Flow.Store",description:"Store package reference with configuration, env, cache, and examples."}).describe("Store package reference with configuration").superRefine(An),Fn=i.record(i.string(),i.unknown()).meta({id:"FlowContractSchemaEntry",title:"Flow.ContractSchemaEntry",description:"JSON Schema object for event validation with description/examples annotations."}).describe("JSON Schema object for event validation with description/examples annotations"),Nn=i.record(i.string(),Fn).meta({id:"FlowContractActions",title:"Flow.ContractActions",description:"Action-level contract entries keyed by action name."}).describe("Action-level contract entries"),zn=i.record(i.string(),Nn).meta({id:"FlowContractEvents",title:"Flow.ContractEvents",description:"Entity-action event schemas (entity → action → schema)."}).describe("Entity-action event schemas"),Ln=i.object({extend:i.string().optional(),tagging:i.number().optional(),description:i.string().optional(),events:In.optional(),schema:Dn.optional()}).meta({id:"ContractRule",title:"Flow.ContractRule",description:"Named contract entry"}),_n=i.record(i.string(),Ln).meta({id:"FlowContract",title:"Flow.Contract",description:"Named contracts map with optional extend inheritance."}).describe("Named contracts with optional extend inheritance"),qn=i.object({level:i.enum(["off","standard","trace"]).optional().describe("Managed-telemetry verbosity. 'off' disables telemetry entirely, 'standard' emits structural records, 'trace' emits full payloads."),sample:i.number().min(0).max(1).optional().describe("Deterministic sample fraction in [0, 1]. Defaults to 1."),url:i.string().min(1).optional().describe("Observer base URL for the web connect form. Public, safe to commit. Paired with binding."),binding:i.string().min(1).optional().describe("Public project binding a web observe credential must match. Paired with url; public, safe to commit.")}).meta({id:"FlowObserve",title:"Flow.Observe",description:"Observability configuration: public web connect pair (url + binding) and managed-telemetry knobs (level + sample)."}).describe("Observability configuration block"),Wn=i.object({platform:i.enum(["web","server"]).describe("Platform identity for this flow. Drives bundle target/format."),url:i.string().min(1).optional().describe("Public URL where this flow is reachable (for cross-flow $flow.X.url references)."),settings:kn.optional().describe("Free-form key-value settings consumed by the platform runtime."),bundle:jn.optional().describe("Bundle configuration: NPM packages, transitive dependency overrides."),observe:qn.optional().describe("Observability configuration: public web connect pair, managed-telemetry level and sample.")}).meta({id:"FlowConfig",title:"Flow.Config",description:"Per-flow configuration block: platform identity, optional public URL, settings, bundle, observe."}).describe("Per-flow configuration block"),Un=i.object({config:Wn.optional().describe("Per-flow configuration: platform, url, settings, bundle."),sources:i.record(i.string(),Tn).optional().describe("Source configurations (data capture) keyed by unique identifier"),destinations:i.record(i.string(),Jn).optional().describe("Destination configurations (data output) keyed by unique identifier"),transformers:i.record(i.string(),Rn).optional().describe("Transformer configurations (event transformation) keyed by unique identifier"),stores:i.record(i.string(),Mn).optional().describe("Store configurations (key-value storage) keyed by unique identifier"),collector:i.looseObject({next:Ue.optional().describe("Collector chain: runs once per completed event before the destination fan-out. A stop drops the event for every destination.")}).meta({id:"FlowCollector",title:"Collector.InitConfig",description:"Collector configuration for event processing (Collector.InitConfig)."}).optional().describe("Collector configuration for event processing (uses Collector.InitConfig)"),variables:yn.optional().describe("Flow-level variables (override root variables, overridden by source/destination variables)")}).meta({id:"Flow",title:"Flow",description:"Single flow definition (one deployment target): config, sources, destinations, transformers, stores, collector."}).describe("Single flow definition for one deployment target"),Bn=i.object({version:i.literal(4).describe("Configuration schema version (v4, current)."),$schema:i.string().url("Schema URL must be a valid URL").optional().describe('JSON Schema reference for IDE validation (e.g., "https://walkeros.io/schema/flow/v4.json")'),include:i.array(i.string()).optional().describe("Folders to include in the bundle output"),variables:yn.optional().describe("Shared variables for interpolation across all flows (use $var.name syntax, deep paths supported)"),contract:_n.optional().describe("Named contracts with extend inheritance and dot-path references"),flows:i.record(i.string(),Un).refine(e=>Object.keys(e).length>0,{message:"At least one flow is required"}).describe("Named flow configurations (e.g., production, staging, development)")}).meta({id:"FlowJson",title:"Flow.Json",description:"walkerOS root configuration (walkeros.config.json) v4: version, variables, contract, named flows."}).describe("walkerOS root configuration (walkeros.config.json)");function Hn(e){return Bn.parse(e)}function Zn(e){return Bn.safeParse(e)}function Vn(e){return Un.parse(e)}function Gn(e){return Un.safeParse(e)}var Kn=i.toJSONSchema(Bn,{target:"draft-7"}),Qn=o(Un),Yn=o(Wn),Xn=o(Tn),ei=o(Jn),ti=o(Rn),ni=o(Mn),ii=o(Ln),oi=o(_n),ri=o(In);import{z as si}from"zod";var ai=si.object({lang:si.string().optional().describe("Language identifier (e.g. json, sql, bash, typescript)"),code:si.string().describe("Code snippet")}),ci=si.object({text:si.string().describe("Short actionable hint text focused on walkerOS usage"),code:si.array(ai).optional().describe("Optional code snippets")}),li=si.record(si.string(),ci).describe("Keyed hints for AI consumption — lightweight context beyond schemas and examples"),di=i.object({param:i.string().describe("Lowercase URL parameter name. Match is case-insensitive on lookup."),platform:i.string().describe("Canonical platform identifier (lowercase, kebab-case).")}),pi=i.object({client_email:i.string().describe("Service account client email"),private_key:i.string().describe("Service account private key (PEM)"),project_id:i.string().optional().describe("GCP project id (derived from environment when omitted)")}).meta({id:"ServiceAccount",title:"ServiceAccount",description:"Google-style service account credentials (client_email, private_key, optional project_id)."}).describe("Google-style service account credentials"),ui=i.union([i.string(),pi]).meta({id:"Credentials",title:"Credentials",description:"Service account credentials: a JSON string (back it with a managed secret via $secret.NAME) or a parsed service account object."}).describe("Service account credentials: a JSON string (back it with a managed secret via $secret.NAME) or a parsed object"),fi=o(ui);function mi(e){return Array.isArray(e)}function gi(e){return"object"==typeof e&&null!==e&&!mi(e)&&"[object Object]"===Object.prototype.toString.call(e)}function hi(e,t="",n){const i=t.split(".");let o=e;for(let e=0;e<i.length;e++){const t=i[e];if("*"===t&&mi(o)){const t=i.slice(e+1).join("."),r=[];for(const e of o){const i=hi(e,t,n);r.push(i)}return r}if(o=gi(o)||mi(o)?o[t]:void 0,void 0===o)break}return void 0!==o?o:n}function bi(e){if(void 0===e||"*"===e)return()=>!0;if("and"in e){const t=e.and.map(bi);return e=>t.every(t=>t(e))}if("or"in e){const t=e.or.map(bi);return e=>t.some(t=>t(e))}return function(e){const{key:t,operator:n,value:i,not:o}=e,r=function(e,t){switch(e){case"eq":return e=>String(e??"")===t;case"contains":return e=>String(e??"").includes(t);case"prefix":return e=>String(e??"").startsWith(t);case"suffix":return e=>String(e??"").endsWith(t);case"regex":{const e=new RegExp(t);return t=>e.test(String(t??""))}case"gt":{const e=Number(t);return t=>Number(t)>e}case"lt":{const e=Number(t);return t=>Number(t)<e}case"exists":return e=>null!=e}}(n,i);return e=>{const n=hi(e,t),i=r(n);return o?!i:i}}(e)}function vi(e){return Array.isArray(e)&&e.length>0&&e.every(e=>function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&("match"in e||"next"in e||"one"in e||"many"in e||"stop"in e)}(e))}var yi=()=>!0;function Si(e,t){return{kind:t?"sequence":"next",path:e}}function wi(e,t){return t?{...e,outer:t}:e}function ki(e,t,n,i){return wi(n?{kind:e,path:t,match:n}:{kind:e,path:t,catchAll:!0},i)}function Ci(e,t,n,i){return 0===e.length?{type:"chain",value:[],label:wi({kind:n,path:t},i)}:{type:n,routes:xi(e,t,n,i)}}function xi(e,t,n,i){return e.map((e,o)=>{const r=[...t,o];if("string"==typeof e||Array.isArray(e)){const t=ki(n,r,void 0,i);return{match:yi,next:Ei(e,r,t)??{type:"chain",value:[],label:t}}}const s=ki(n,r,e.match,i);return{match:e.match?bi(e.match):yi,source:e.match,next:ji(e,r,s,!1,!0)??{type:"chain",value:[],label:s}}})}function ji(e,t,n,i,o){const r=o?void 0:e.match,s=r?wi({kind:"next",path:t,match:r},n):n??Si(t,i),a=r?s:n;let c;return!0===e.stop?c={type:"stop",label:s}:void 0!==e.one?c=Ci(e.one,[...t,"one"],"one",a):void 0!==e.many?c=Ci(e.many,[...t,"many"],"many",a):void 0!==e.next&&(c=Ei(e.next,[...t,"next"],a)),r?{type:"gate",match:bi(r),source:r,next:c??{type:"chain",value:[],label:s}}:void 0===c&&e.match?{type:"chain",value:[],label:s}:c}function Ei(e,t=[],n,i=!1){if(null!=e){if("string"==typeof e)return{type:"static",value:e,label:n??Si(t,i)};if(Array.isArray(e)){if(0===e.length)return;if(vi(e))return{type:"one",routes:xi(e,t,"one",n)};const o=[];for(const t of e)"string"==typeof t&&o.push(t);if(o.length===e.length)return{type:"chain",value:o,label:n??Si(t,i)};const r=[];if(e.forEach((e,i)=>{const o=Ei(e,[...t,i],n,!0);void 0!==o&&r.push(o)}),0===r.length)return;return{type:"sequence",value:r}}return ji(e,t,n,i,!1)}}var Oi=new WeakMap;function $i(e,t,n){return n?{type:"continuation",segments:e,at:t,tail:n}:{type:"continuation",segments:e,at:t}}function Pi(e){if(null==e)return;if(function(e){return"object"==typeof e&&!Array.isArray(e)&&"type"in e&&"continuation"===e.type}(e))return e;const t=function(e){if(null==e)return;if("object"!=typeof e)return Ei(e);const t=Oi.get(e);if(t)return t;const n=Ei(e);return n&&Oi.set(e,n),n}(e);return t?$i([t],0,void 0):void 0}function Di(e,t,n){const i=[];let o=e;for(;o;){if(o.at>=o.segments.length){o=o.tail;continue}const e=o.segments[o.at],r=$i(o.segments,o.at+1,o.tail);if("static"===e.type){i.push(e.value),n&&n(e),o=r;continue}if("chain"===e.type){i.push(...e.value),n&&n(e),o=r;continue}if("sequence"===e.type){o=$i(e.value,0,r);continue}if(i.length>0)return{ids:i,then:o};if("stop"===e.type)return n&&n(e),{ids:[],stop:!0};if("gate"===e.type){o=t.gate(e)?$i([e.next],0,r):r;continue}if("one"===e.type){const n=e.routes.length>0?t.one(e.routes):-1;o=n>=0?$i([e.routes[n].next],0,r):r;continue}const s=e.routes.length>0?t.many(e.routes):[];if(0!==s.length){if(1!==s.length)return{ids:[],forks:s.map(t=>$i([e.routes[t].next],0,r))};o=$i([e.routes[s[0]].next],0,r)}else o=r}return{ids:i}}function Ii(e,t){return Di(Pi(e),function(e){return{gate:t=>t.match(e),one:t=>t.findIndex(t=>t.match(e)),many:t=>{const n=[];return t.forEach((t,i)=>{t.match(e)&&n.push(i)}),n}}}(t))}function Ai(e){return null==e?[]:[{route:e,ancestry:[]}]}function Ti(e,t,n){if(e.at>=e.ids.length)return{rest:t};const i=e.ids[e.at],o=e.at+1<e.ids.length?[{ids:e.ids,at:e.at+1,ancestry:e.ancestry},...t]:t;if(e.ancestry.includes(i))return{rest:o};const r=[...e.ancestry,i],s=n[i],a=s?s.config.next:void 0;return{id:i,ancestry:r,rest:void 0===a?o:[{route:a,ancestry:r},...o]}}function Ri(e,t,n){if(e.stop)return t.length>0?{kind:"stop",owner:t[t.length-1]}:{kind:"stop"};if(e.forks)return{kind:"fork",branches:e.forks.map(e=>[{route:e,ancestry:t},...n])};const i=[];return e.ids.length>0&&i.push({ids:e.ids,at:0,ancestry:t}),e.then&&i.push({route:e.then,ancestry:t}),{kind:"stack",stack:[...i,...n]}}function Ji(e,t,n){let i=e;for(;i.length>0;){const[e,...o]=i;if("ids"in e){const t=Ti(e,o,n);if(void 0!==t.id)return{kind:"run",id:t.id,rest:t.rest,ancestry:t.ancestry};i=t.rest;continue}const r=Ri(Ii(e.route,t),e.ancestry,o);if("stack"!==r.kind)return r;i=r.stack}return{kind:"done"}}function Mi(e,t={}){const n=[],i=new Map,o=new Set,r=new WeakMap,s=new WeakMap;let a=0;const c=e=>{let t=s.get(e);return void 0===t&&(t=++a,s.set(e,t)),t},l=e=>e.length>0?e[e.length-1]:void 0,d=(e,t,o,r,s)=>{const a=void 0===s,c=`${e??""}|${o}|${r??""}|${s??""}`,l=i.get(c);if(l)return l;const d={targets:[],kind:t.kind,path:t.path};return void 0!==e&&(d.from=e),t.match&&(d.match=t.match),t.catchAll&&(d.catchAll=!0),a&&(d.stop=!0),void 0!==r&&(d.owner=r),t.outer&&(d.via=function(e){const t=[];for(let n=e.outer;n;n=n.outer){const e={kind:n.kind,path:n.path};n.match&&(e.match=n.match),n.catchAll&&(e.catchAll=!0),t.unshift(e)}return t}(t)),i.set(c,d),n.push(d),d},p=e=>{const t=e.ancestry.join(",");if("ids"in e){const n=r.get(e.ids)??[];return`i${e.ids.join(",")}#${n.map(c).join(",")}@${e.at}/${t}`}const n=e.route;if("string"==typeof n)return`s${n}/${t}`;let i="",o=Pi(n);for(;o;)i+=`${c(o.segments)}@${o.at};`,o=o.tail;return`r${i}/${t}`},u=(e,n,i)=>{const s=`${n??""}|${i?`${c(i.node)}:${i.position}`:""}|${e.map(p).join("|")}`;if(o.has(s))return;if(o.add(s),0===e.length)return;const[a,...f]=e;if("ids"in a){const e=Ti(a,f,t);if(void 0===e.id)return void u(e.rest,n,i);const o=(r.get(a.ids)??[])[a.at];if(!o)return;let s;if(i&&i.source===o&&i.node.targets[i.position]===n){const t=i.position+1;i.node.targets.length===t&&i.node.targets.push(e.id),s={node:i.node,source:o,position:t}}else{const t=d(n,o.label,c(o),l(a.ancestry),e.id);0===t.targets.length&&t.targets.push(e.id),s={node:t,source:o,position:0}}return void u(e.rest,e.id,s)}const m=l(a.ancestry);for(const e of function(e){const t=[],n=i=>{let o=0;const r=[],s=e=>{let t=0;return o<i.length?t=i[o]:r.push(e),o++,t},a=e=>e.some(e=>void 0===e.source),c=[],l=Di(e,{gate:()=>0===s(2),one:e=>{const t=e.map((e,t)=>t);return a(e)||t.push(-1),t[s(t.length)]},many:e=>{const t=e.map((e,t)=>t);return a(e)||0===s(2)?t:[]}},e=>c.push(e));t.push({steps:l,visited:c});for(let e=0;e<r.length;e++)for(let t=1;t<r[e];t++){const o=i.slice();for(let t=0;t<e;t++)o.push(0);o.push(t),n(o)}};return n([]),t}(Pi(a.route))){const{steps:t}=e,i=[];let o=n;for(const t of e.visited)if("stop"!==t.type)if("static"===t.type)i.push(t),o=t.value;else if(0===t.value.length)d(o,t.label,c(t),m,"");else{for(let e=0;e<t.value.length;e++)i.push(t);o=t.value[t.value.length-1]}else d(n,t.label,c(t),m,void 0);t.ids.length>0&&r.set(t.ids,i);const s=Ri(t,a.ancestry,f);if("stop"!==s.kind)if("fork"!==s.kind)u(s.stack,n,void 0);else for(const e of s.branches)u(e,n,void 0)}};return u(Ai(e),void 0,void 0),n}function Fi(e){throw new Error(String(e))}var Ni=new Set(["description","examples","title","$comment"]),zi=new Set(["additionalItems","additionalProperties","contains","contentSchema","else","if","items","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"]),Li=new Set(["allOf","anyOf","items","oneOf","prefixItems"]),_i=new Set(["properties","patternProperties","dependentSchemas","dependentRequired","dependencies","$defs","definitions"]);function qi(e,t){const n=!1!==t?.stripAnnotations,i={},o=new Set;function r(t){if(i[t])return i[t];o.has(t)&&Fi(`Circular extend chain detected: ${[...o,t].join(" → ")}`);const s=e[t];s||Fi(`Contract "${t}" not found`),o.add(t);let a={};if(s.extend){a=function(e,t){const n={};void 0===e.tagging&&void 0===t.tagging||(n.tagging=t.tagging??e.tagging);void 0===e.description&&void 0===t.description||(n.description=t.description??e.description);e.schema&&t.schema?n.schema=Wi(e.schema,t.schema):(e.schema||t.schema)&&(n.schema={...e.schema||t.schema});if(e.events||t.events){const i={},o=new Set([...Object.keys(e.events||{}),...Object.keys(t.events||{})]);for(const n of o){const o=e.events?.[n]||{},r=t.events?.[n]||{},s=new Set([...Object.keys(o),...Object.keys(r)]);i[n]={};for(const e of s){const t=o[e],s=r[e];i[n][e]=t&&s?Wi(t,s):{...t||s}}}n.events=i}return n}(r(s.extend),s)}else a={...s};if(delete a.extend,a.events&&(a.events=function(e){const t={};for(const n of Object.keys(e))if("*"!==n){t[n]={};for(const i of Object.keys(e[n]||{})){let o={};const r=e["*"]?.["*"];r&&(o=Wi(o,r));const s=e["*"]?.[i];s&&"*"!==i&&(o=Wi(o,s));const a=e[n]?.["*"];a&&"*"!==i&&(o=Wi(o,a));const c=e[n]?.[i];c&&(o=Wi(o,c)),t[n][i]=o}}e["*"]&&(t["*"]={...e["*"]});return t}(a.events)),a.events&&n){const e={};for(const[t,n]of Object.entries(a.events)){e[t]={};for(const[i,o]of Object.entries(n))e[t][i]=Ui(o)}a.events=e}return o.delete(t),i[t]=a,a}for(const t of Object.keys(e))r(t);return i}function Wi(e,t){const n={...e};for(const i of Object.keys(t)){const o=e[i],r=t[i];"required"===i&&Array.isArray(o)&&Array.isArray(r)?n[i]=[...new Set([...o,...r])]:Hi(o)&&Hi(r)?n[i]=Wi(o,r):n[i]=r}return n}function Ui(e){const t={};for(const[n,i]of Object.entries(e))Ni.has(n)||(_i.has(n)&&Hi(i)?t[n]=Bi(i):Li.has(n)&&Array.isArray(i)?t[n]=i.map(e=>Hi(e)?Ui(e):e):zi.has(n)&&Hi(i)?t[n]=Ui(i):t[n]=i);return t}function Bi(e){const t={};for(const[n,i]of Object.entries(e))t[n]=Hi(i)?Ui(i):i;return t}function Hi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Zi="$code:";function Vi(e,t){let n;try{n=JSON.parse(e)}catch(t){const{line:n,column:i}=function(e,t){if(e instanceof SyntaxError){const n=e.message.match(/position\s+(\d+)/);if(n){return ho(t,parseInt(n[1],10))}const i=e.message.match(/line\s+(\d+)\s+column\s+(\d+)/);if(i)return{line:parseInt(i[1],10),column:parseInt(i[2],10)}}return{line:1,column:1}}(t,e);return{valid:!1,errors:[{message:t instanceof Error?t.message:"Invalid JSON",severity:"error",line:n,column:i}],warnings:[]}}const i=[],o=[],r=Bn.safeParse(n);if(!r.success)for(const t of r.error.issues){const n=t.path.join("."),o=vo(e,t.path);i.push({message:t.message,severity:"error",path:n||"root",...o})}const s=function(e){if(!($o(e)&&"version"in e&&"flows"in e&&$o(e.flows)))return;const t={},n=[],i=[],o=[],r=[],s=[],a=[];let c;const l=Object.keys(e.flows);Po(t,e.variables),function(e,t){if(!$o(t))return;let n;try{n=qi(t,{stripAnnotations:!1})}catch{return}for(const t of Object.values(n)){const n=t.events;if($o(n))for(const[t,i]of Object.entries(n)){if(!$o(i))continue;let n=e.find(e=>e.entity===t);n||(n={entity:t,actions:[],properties:{}},e.push(n)),n.properties||(n.properties={});for(const[e,t]of Object.entries(i))n.actions.includes(e)||n.actions.push(e),n.properties[e]=Do(t)}}}(a,e.contract);for(const a of Object.values(e.flows))if($o(a)){if(!c){const e=a.config;!$o(e)||"web"!==e.platform&&"server"!==e.platform||(c=e.platform)}Po(t,a.variables);for(const e of["sources","destinations","transformers"]){const r="sources"===e?"source":"destinations"===e?"destination":"transformer",l="sources"===e?n:"destinations"===e?i:o;if($o(a[e]))for(const[n,i]of Object.entries(a[e]))l.push(n),$o(i)&&(Po(t,i.variables),"string"==typeof i.package&&s.push({package:i.package,shortName:n,type:r,platform:c||"web"}))}if($o(a.stores))for(const[e,n]of Object.entries(a.stores))r.push(e),$o(n)&&Po(t,n.variables)}const d={variables:t,stepNames:{sources:n,destinations:i,transformers:o,stores:r},flowNames:l};c&&(d.platform=c);s.length>0&&(d.packages=s);a.length>0&&(d.contract=a);return d}(n);return s&&(t?.secrets&&(s.secrets=t.secrets),function(e,t,n,i,o){const r=function(e,t){const n=function(e){const t=new Map,n=[],i=()=>n.map(e=>"array"===e.kind?String(e.index):e.key??"");let o=0;for(;o<e.length;){const r=e[o],s=n.length>0?n[n.length-1]:void 0;if("{"===r||"["===r)n.push({kind:"{"===r?"object":"array",index:0,expectKey:"{"===r}),o++;else if("}"===r||"]"===r)n.pop(),o++;else if(","===r)"array"===s?.kind?s.index++:s&&(s.expectKey=!0),o++;else if(":"===r)s&&(s.expectKey=!1),o++;else if('"'===r){const n=o;for(o++;o<e.length&&'"'!==e[o];)o+="\\"===e[o]?2:1;if(o++,"object"===s?.kind&&s.expectKey){const t=JSON.parse(e.slice(n,o));s.key="string"==typeof t?t:""}else t.set(no(i()),{start:n,end:o})}else o++}return t}(e),i=[];return ao(t,[],(t,o)=>{if(so(o))return;const r=n.get(no(o));r&&i.push({path:o,raw:e.slice(r.start+1,r.end-1),offset:r.start+1})}),i}(e,t);(function(e,t,n){to(t,Yi,(t,i,o)=>{const r=t[0],s=t[1],a=t[2];n.push({message:`Malformed reference "${r}", use a dot, not a colon: "$${s}.${a}".`,severity:"warning",path:i.path.join("."),...bo(e,o,r.length)})})})(e,r,o),function(e,t,n,i,o){to(n,eo,(n,r,s)=>{const a=function(e,t,n){if("flows"!==t[0]||!$o(e)||!$o(e.flows))return n.variables??{};const i={};Po(i,e.variables);const o=e.flows[t[1]];if(!$o(o))return i;Po(i,o.variables);const r=o[t[2]];if(ro.includes(t[2])&&$o(r)){const e=r[t[3]];$o(e)&&Po(i,e.variables)}return i}(t,r.path,i);n[1]in a||o.push({message:`Unknown variable "$var.${n[1]}". Defined: ${Object.keys(a).join(", ")||"none"}`,severity:"warning",path:r.path.join("."),...bo(e,s,n[0].length)})})}(e,t,r,n,o),function(e,t,n,i,o){to(n,Gi,(n,r,s)=>{const a=function(e,t,n){if("flows"!==t[0]||!$o(e)||!$o(e.flows))return n.stepNames?.stores??[];const i=e.flows[t[1]];return $o(i)&&$o(i.stores)?Object.keys(i.stores):[]}(t,r.path,i);a.includes(n[1])||o.push({message:`Unknown store "$store.${n[1]}". Defined: ${a.join(", ")||"none"}`,severity:"warning",path:r.path.join("."),...bo(e,s,n[0].length)})})}(e,t,r,n,o),function(e,t,n){to(t,Ki,(t,i,o)=>{const r=t[0],s=t[1],a=t[2],c=bo(e,o,r.length),l=i.path.join(".");a?n.push({message:`Malformed $env reference "${r}". Use ":" for default values, not "=" (e.g., "$env.${s}:fallback").`,severity:"warning",path:l,...c}):/^[A-Z][A-Z0-9_]*$/.test(s)||n.push({message:`$env.${s} should use UPPER_SNAKE_CASE by convention (e.g., $env.${s.toUpperCase()}).`,severity:"warning",path:l,...c})})}(e,r,o),function(e,t,n,i){const o=n.flowNames??[];if(0===o.length)return;to(t,Qi,(t,n,r)=>{const s=t[0],a=t[1];o.includes(a)||i.push({message:`Unknown flow "$flow.${a}". Defined: ${o.join(", ")}`,severity:"warning",path:n.path.join("."),...bo(e,r,s.length)})})}(e,r,n,o),function(e,t,n,i,o){const r=n.secrets;if(!$o(t)||!$o(t.flows))return;for(const[n,s]of Object.entries(t.flows)){if(!$o(s))continue;const t=s.config,a=!$o(t)||"web"!==t.platform&&"server"!==t.platform?void 0:t.platform;ao(s,["flows",n],(t,n)=>{if(so(n))return;let s;for(Xi.lastIndex=0;null!==(s=Xi.exec(t));){const t=s[0],n=s[1],c=e.indexOf(t),l=-1===c?{line:1,column:1}:bo(e,c,t.length);"web"!==a?r&&!r.includes(n)&&o.push({message:`Unknown secret "$secret.${n}"; not in the project's registered secrets.`,severity:"warning",path:t,...l}):i.push({message:`Secret "$secret.${n}" cannot be used in a web flow: secrets are never sent to the browser; use a server flow.`,severity:"error",path:t,...l})}})}}(e,t,n,i,o),function(e,t,n){ao(t,[],(t,i)=>{if(!t.startsWith(Zi)&&!so(i))for(const{prefix:o,regex:r,grammar:s}of io){if(!t.includes(o))continue;const a=o.slice(0,-1);let c;if(t.startsWith(o)){if(r.test(t))continue;c=`"${t}" does not match the ${a}.NAME grammar (${s}); it would not resolve. To build a longer string, compose with $var or $env.`}else c=`"${t}" uses ${o} inline. ${o} references resolve only as the whole value; it would ship as literal text. Use the reference as the entire value, or compose strings with $var or $env.`;const l=JSON.stringify(t),d=e.indexOf(l);n.push({message:c,severity:"warning",path:i.join("."),...-1===d?{line:1,column:1}:bo(e,d,l.length)})}})}(e,t,o)}(e,n,s,i,o)),function(e,t,n){if(!$o(t))return;const i=_n.safeParse(t.contract);if(void 0===t.contract||!i.success)return;try{qi(i.data)}catch(t){n.push({message:`Contract does not resolve: ${t instanceof Error?t.message:String(t)}`,severity:"error",path:"contract",...go(e,"contract")})}}(e,n,i),function(e,t,n){if(!$o(t)||!$o(t.flows))return;for(const i of Object.values(t.flows)){if(!$o(i))continue;const t=$o(i.stores)?i.stores:void 0;t&&fo(e,t,n),t&&$o(i.transformers)&&mo(e,i.transformers,t,n)}}(e,n,o),function(e,t,n){if(!$o(t)||!$o(t.flows))return;const i=(t,i,o)=>{n.push({message:o,severity:"error",path:i.join("."),...go(e,t)})},o=(e,t)=>{e.startsWith("ingest.")&&i(e,t,`Mapping values resolve against the event, so "${e}" never resolves here. Copy it onto the event in an earlier step, then map the event path.`)},r=(e,t)=>(n,o)=>{e.test(n)||i(n,o,`Cache keys and route matchers resolve against { event, ingest }: "${n}" needs an ${t} prefix.`)},s=r(yo,'"event." or "ingest."'),a=r(So,'"event.", "ingest." or "cache."');for(const[e,n]of Object.entries(t.flows))if($o(n)){for(const t of wo){const i=n[t];if($o(i))for(const[n,r]of Object.entries(i)){if(!$o(r))continue;const i=["flows",e,t,n];Eo(r.before,[...i,"before"],s),Eo(r.next,[...i,"next"],s),jo(r.cache,[...i,"cache"],s,a),"transformers"!==t&&$o(r.config)&&xo(r.config,[...i,"config"],o)}}$o(n.collector)&&Eo(n.collector.next,["flows",e,"collector","next"],s)}}(e,n,i),{valid:0===i.length,errors:i,warnings:o,context:s}}var Gi=/\$store\.([a-zA-Z_][a-zA-Z0-9_]*)/g,Ki=/\$env\.([A-Za-z_]\w*)(=[^"}\s]*)?/g,Qi=/\$flow\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.([a-zA-Z0-9_.]+))?/g,Yi=/\$(var|store|flow|secret):([a-zA-Z_][a-zA-Z0-9_]*)/g,Xi=/\$secret\.([A-Za-z0-9_]+)/g,eo=/\$var\.(\w+)/g;function to(e,t,n){for(const i of e){let e;for(t.lastIndex=0;null!==(e=t.exec(i.raw));)n(e,i,i.offset+e.index)}}function no(e){return JSON.stringify(e)}var io=[{prefix:"$flow.",regex:/^\$flow\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.([a-zA-Z0-9_.]+))?$/,grammar:"a flow name, then an optional dot path of letters, digits and _"},{prefix:"$store.",regex:/^\$store\.([a-zA-Z_][a-zA-Z0-9_]*)$/,grammar:"one store id of letters, digits and _, no path"},{prefix:"$secret.",regex:/^\$secret\.([A-Z0-9_]+)$/,grammar:"uppercase letters, digits and _"},{prefix:"$contract.",regex:/^\$contract\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\.(.+))?$/,grammar:"a contract name, then an optional dot path"}],oo=["title","description"],ro=["sources","transformers","destinations","stores"];function so(e){const t=e[e.length-1];return"$comment"===t||("contract"===e[0]||(!("flows"!==e[0]||!ro.includes(e[2])||"config"!==e[4]||"settings"!==e[5]||"contract"!==e[6])||!!oo.includes(t)&&(1===e.length||"flows"===e[0]&&(3===e.length||!!ro.includes(e[2])&&(5===e.length||7===e.length&&"examples"===e[4])))))}function ao(e,t,n){if("string"!=typeof e){if(Array.isArray(e))e.forEach((e,i)=>ao(e,[...t,String(i)],n));else if($o(e))for(const[i,o]of Object.entries(e))ao(o,[...t,i],n)}else n(e,t)}var co=["@walkeros/server-store-fs","@walkeros/server-store-s3","@walkeros/server-store-gcs"],lo="@walkeros/server-transformer-file",po=/^\$store\.([a-zA-Z_][a-zA-Z0-9_]*)$/;function uo(e){return $o(e.config)&&!0===e.config.file}function fo(e,t,n){for(const[i,o]of Object.entries(t))$o(o)&&uo(o)&&void 0!==o.cache&&n.push({message:`Store "${i}" sets file: true and cache. The cache holds structured values; caching a byte-serving store offers no benefit. Remove cache or unset file.`,severity:"warning",path:`stores.${i}`,...go(e,i)})}function mo(e,t,n,i){for(const o of Object.values(t)){if(!$o(o))continue;if(o.package!==lo)continue;if(!$o(o.env))continue;const t=o.env.store;if("string"!=typeof t)continue;const r=po.exec(t);if(!r)continue;const s=r[1],a=n[s];if(!$o(a))continue;const c=a.package;"string"==typeof c&&co.includes(c)&&(uo(a)||i.push({message:`transformer-file serves byte-exact assets; set config.file: true on store "${s}".`,severity:"warning",path:`stores.${s}`,...go(e,s)}))}}function go(e,t){const n=e.indexOf(`"${t}"`);return-1===n?{line:1,column:1}:ho(e,n)}function ho(e,t){let n=1,i=1;for(let o=0;o<t&&o<e.length;o++)"\n"===e[o]?(n++,i=1):i++;return{line:n,column:i}}function bo(e,t,n){const i=ho(e,t),o=ho(e,t+n);return{line:i.line,column:i.column,endLine:o.line,endColumn:o.column}}function vo(e,t){if(0===t.length)return{line:1,column:1};const n=t[t.length-1];if("string"==typeof n){const t=`"${n}"`,i=e.lastIndexOf(t);if(-1!==i)return ho(e,i)}return{line:1,column:1}}var yo=/^(event|ingest)(\..+)?$/,So=/^(event|ingest|cache)(\..+)?$/,wo=["sources","transformers","destinations"];function ko(e,t,n){if("string"!=typeof e){if(Array.isArray(e))e.forEach((e,i)=>ko(e,[...t,i],n));else if($o(e)){if("string"==typeof e.key&&ko(e.key,[...t,"key"],n),$o(e.map))for(const[i,o]of Object.entries(e.map))ko(o,[...t,"map",i],n);Array.isArray(e.set)&&e.set.forEach((e,i)=>ko(e,[...t,"set",i],n)),Array.isArray(e.loop)&&"this"!==e.loop[0]&&ko(e.loop[0],[...t,"loop",0],n)}}else e.startsWith("$")||n(e,t)}function Co(e,t,n){if($o(e))for(const[i,o]of Object.entries(e))ko(o,[...t,i],n)}function xo(e,t,n){if(ko(e.data,[...t,"data"],n),Co(e.policy,[...t,"policy"],n),$o(e.mapping))for(const[i,o]of Object.entries(e.mapping))if($o(o))for(const[e,r]of Object.entries(o)){const o=[...t,"mapping",i,e];(Array.isArray(r)?r:[r]).forEach((e,t)=>{if(!$o(e))return;const i=Array.isArray(r)?[...o,t]:o;ko(e.data,[...i,"data"],n),Co(e.policy,[...i,"policy"],n),$o(e.extend)&&(ko(e.extend.data,[...i,"extend","data"],n),Co(e.extend.policy,[...i,"extend","policy"],n))})}}function jo(e,t,n,i){$o(e)&&Array.isArray(e.rules)&&e.rules.forEach((e,o)=>{if(!$o(e))return;const r=[...t,"rules",o];if(ko(e.key,[...r,"key"],n),Oo(e.match,[...r,"match"],n),$o(e.update))for(const[t,n]of Object.entries(e.update))ko(n,[...r,"update",t],i)})}function Eo(e,t,n){if(void 0===e||(i=e,!Ue.safeParse(i).success))return;var i;const o=new Set;for(const i of Mi(e))for(const e of[...i.via??[],i]){if(!e.match)continue;const i=e.path.join(".");o.has(i)||(o.add(i),Oo(e.match,[...t,...e.path,"match"],n))}}function Oo(e,t,n){$o(e)&&(Array.isArray(e.and)&&e.and.forEach((e,i)=>Oo(e,[...t,"and",i],n)),Array.isArray(e.or)&&e.or.forEach((e,i)=>Oo(e,[...t,"or",i],n)),"string"==typeof e.key&&ko(e.key,[...t,"key"],n))}function $o(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Po(e,t){if($o(t))for(const[n,i]of Object.entries(t))e[n]=i}function Do(e){const t={};if(!$o(e))return t;const n=$o(e.properties)?e.properties.data:void 0;if(!$o(n))return t;const i=Array.isArray(n.required)?n.required.filter(e=>"string"==typeof e):[],o=n.properties;if(!$o(o))return t;for(const[e,n]of Object.entries(o)){const o={};$o(n)&&("string"==typeof n.type&&(o.type=n.type),"string"==typeof n.description&&(o.description=n.description)),i.includes(e)&&(o.required=!0),t[e]=o}return t}function Io(e,t){const n=[],i={};for(const[t,o]of Object.entries(e)){o.required&&n.push(t);const e={type:o.type};if(o.description&&(e.description=o.description),o.pattern&&(e.pattern=o.pattern),void 0!==o.minLength&&(e.minLength=o.minLength),void 0!==o.maxLength&&(e.maxLength=o.maxLength),void 0!==o.minimum&&(e.minimum=o.minimum),void 0!==o.maximum&&(e.maximum=o.maximum),o.enum&&(e.enum=[...o.enum]),void 0!==o.default&&(e.default=o.default),"object"===o.type&&o.properties){const t={};for(const[e,n]of Object.entries(o.properties))t[e]=Ao(n);e.properties=t}"array"===o.type&&o.items&&(e.items=Ao(o.items)),i[t]=e}const o={type:"object",properties:i};return t&&(o.title=t),n.length>0&&(o.required=n),o}function Ao(e){const t={type:e.type};if(e.description&&(t.description=e.description),e.pattern&&(t.pattern=e.pattern),void 0!==e.minLength&&(t.minLength=e.minLength),void 0!==e.maxLength&&(t.maxLength=e.maxLength),void 0!==e.minimum&&(t.minimum=e.minimum),void 0!==e.maximum&&(t.maximum=e.maximum),e.enum&&(t.enum=[...e.enum]),void 0!==e.default&&(t.default=e.default),"object"===e.type&&e.properties){const n={};for(const[t,i]of Object.entries(e.properties))n[t]=Ao(i);t.properties=n}return"array"===e.type&&e.items&&(t.items=Ao(e.items)),t}function To(e,t){const n={type:"array",items:Ao(e)};return void 0!==t?.minItems&&(n.minItems=t.minItems),void 0!==t?.maxItems&&(n.maxItems=t.maxItems),t?.description&&(n.description=t.description),t?.title&&(n.title=t.title),n}function Ro(e,t="string",n){const i={type:t,enum:[...e]};return n?.description&&(i.description=n.description),n?.title&&(i.title=n.title),i}function Jo(e,t,n){return To({type:"object"},{minItems:2,maxItems:2,description:n||"Tuple with exactly 2 elements [source, transform]"})}function Mo(e){const t=i.toJSONSchema(e,{target:"draft-7"});return Fo(t),t}function Fo(e){const t=e.properties;if(t&&"object"==typeof t){Array.isArray(e.required)&&(e.required=e.required.filter(e=>{const n=t[e];return!(n&&"object"==typeof n&&"default"in n)}));for(const[e,n]of Object.entries(t))n&&"object"==typeof n&&("object"===n.type&&n.properties&&"string"!=typeof n.title&&(n.title=e),Fo(n))}}var No=new Set(["env","onError","onLog","primary"]),zo={source:Bt.configJsonSchema,destination:Te.configJsonSchema,store:pn.configJsonSchema};function Lo(e,t){const n=_o(zo[e]);if(!n||!n.properties){const e={settings:t.settings?qo(t.settings):{description:"Implementation-specific configuration"}};t.credentials&&(e.credentials=qo(t.credentials));return{type:"object",properties:e}}const i=JSON.parse(JSON.stringify(n)),o=i.properties;for(const e of No)delete o[e];return t.settings&&(o.settings=qo(t.settings)),t.credentials&&(o.credentials=qo(t.credentials)),i}function _o(e){if(!e)return e;if(e.properties)return e;const{ref:t,container:n,containerKey:i}=function(e){const t=e.$defs,n=e.definitions,i=t??n,o=t?"$defs":"definitions";let r;if("string"==typeof e.$ref)r=e.$ref;else if(Array.isArray(e.allOf)){const t=e.allOf[0];t&&"string"==typeof t.$ref&&(r=t.$ref)}return{ref:r,container:i,containerKey:o}}(e);if(!t||!n)return e;const o=t.match(/^#\/(\$defs|definitions)\/(.+)$/);if(!o)return e;const r=n[o[2]];return r&&"object"==typeof r?{...r,[i]:n}:e}function qo(e){const{$schema:t,...n}=e;return n}function Wo(e){return 0===e.length?"// no output":e.map(Uo).join(";\n\n")}function Uo(e){const[t,...n]=e,i=n.map(Bo).join(", ");return"return"===t?i?`return ${i}`:"return":`${t}(${i})`}function Bo(e){return void 0===e?"undefined":null===e?"null":"function"==typeof e?"[Function]":JSON.stringify(e,null,2)}var Ho="call:";function Zo(e){const t=(e.startsWith(Ho)?e.slice(5):e).split(".");return t.some(e=>""===e)?[]:t}async function Vo(e){const t=e.simulation??[];if(0===t.length)return;const n=e.push;if(!n)throw new Error(`simulation declares ${t.join(", ")} but the examples env has no push mock`);const i=[];for(const e of t){const t=Zo(e),o=0===t.length?"malformed path":await Ko(n,t);o&&i.push(`${e} (${o})`)}if(i.length>0)throw new Error(`simulation paths do not resolve against the push mock env: ${i.join(", ")}`)}function Go(e){return"function"==typeof e}async function Ko(e,t){let n,i=e;for(const e of t){if(Go(i)&&!(e in i))try{i=await Qo(i,n)}catch(t){return`calling before "${e}" threw: ${t instanceof Error?t.message:String(t)}`}if("object"!=typeof i&&"function"!=typeof i||null===i||!(e in i))return`"${e}" not found`;n=i,i=Reflect.get(i,e)}return"function"==typeof i?void 0:"leaf is not a function"}async function Qo(e,t){let n;try{n=Reflect.construct(e,[])}catch(i){try{n=Reflect.apply(e,t,[])}catch{throw i}}return await n}var Yo={};t(Yo,{STOP:()=>Xo,eq:()=>er,interpret:()=>or,makeTransformers:()=>tr,routeCases:()=>nr,visits:()=>rr});var Xo="(stop)";function er(e,t){return{key:e,operator:"eq",value:t}}function tr(e={}){const t={};for(const[n,i]of Object.entries(e))t[n]={type:n,config:{next:i},push:()=>{}};return t}var nr=[{name:"static member next is inserted after the member",spec:["bot","validate","session"],nexts:{bot:"foo"},roots:[{ingest:{}}],expected:[[["bot","foo","validate","session"]]]},{name:"member next insertion is recursive and depth first",spec:["bot","validate","session"],nexts:{bot:"foo",foo:"bar"},roots:[{ingest:{}}],expected:[[["bot","foo","bar","validate","session"]]]},{name:"conditional member next inserts only on match",spec:["bot","validate"],nexts:{bot:{match:er("ingest.bot","yes"),next:"flag"}},roots:[{ingest:{bot:"yes"}},{ingest:{bot:"no"}}],expected:[[["bot","flag","validate"]],[["bot","validate"]]]},{name:"conditional member next sees what the member wrote",spec:["enrich","out"],nexts:{enrich:{match:er("ingest.tier","gold"),next:"vip"}},sets:{enrich:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["enrich","vip","out"]]]},{name:"many forks and each fork finishes the rest of the array",spec:["a",{many:["x","y"]},"z"],roots:[{ingest:{}}],expected:[[["a","x","z"],["a","y","z"]]]},{name:"stop in one fork ends only that copy",spec:["a",{many:[["x",{stop:!0}],"y"]},"z"],roots:[{ingest:{}}],expected:[[["a","x",Xo],["a","y","z"]]]},{name:"fork at depth 2 carries every enclosing continuation",spec:["a",{one:[{match:er("ingest.k","1"),next:["b",{many:["c","d"]},"e"]}]},"f"],roots:[{ingest:{k:"1"}},{ingest:{k:"2"}}],expected:[[["a","b","c","e","f"],["a","b","d","e","f"]],[["a","f"]]]},{name:"fork inside a member next continues the enclosing arrays",spec:["a",["b","c"],"d"],nexts:{b:{many:["m1","m2"]}},roots:[{ingest:{}}],expected:[[["a","b","m1","c","d"],["a","b","m2","c","d"]]]},{name:"a step listed twice runs twice",spec:["a","b","a"],roots:[{ingest:{}}],expected:[[["a","b","a"]]]},{name:"member next cycle stops at the guard",spec:["a","x"],nexts:{a:"b",b:"a"},roots:[{ingest:{}}],expected:[[["a","b","x"]]]},{name:"gated stop after a write ends the copy",spec:["a",{match:er("ingest.tier","gold"),stop:!0},"b"],sets:{a:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["a",Xo]]]},{name:"gated stop that fails falls through",spec:["a",{match:er("ingest.tier","gold"),stop:!0},"b"],roots:[{ingest:{tier:"gold"}},{ingest:{tier:"silver"}}],expected:[[["a",Xo]],[["a","b"]]]},{name:"unconditional stop",spec:["a",{stop:!0},"b"],roots:[{ingest:{}}],expected:[[["a",Xo]]]},{name:"one with a stop entry",spec:{one:[{match:er("ingest.x","1"),stop:!0},{next:"b"}]},roots:[{ingest:{x:"1"}},{ingest:{x:"2"}}],expected:[[[Xo]],[["b"]]]},{name:"state get into ingest.tier → next one on ingest.tier",spec:["state",{one:[{match:er("ingest.tier","gold"),next:"vip"},{next:"std"}]}],sets:{state:{tier:"gold"}},roots:[{ingest:{}}],expected:[[["state","vip"]]]}];function ir(e){return{...e,ingest:{...e.ingest}}}function or(e,t,n){const i=tr(e.nexts),o=[],r=(t,s,a)=>{let c=t;const l={ids:[...a.ids],stopped:!1,edges:[...a.edges]};for(let t=0;t<256;t++){const t=Ji(c,s,i);if("done"===t.kind)break;if("stop"===t.kind){l.stopped=!0;break}if("fork"===t.kind){for(const e of t.branches)r(e,ir(s),l);return}n&&n(t.id);const o=l.ids.length>0?l.ids[l.ids.length-1]:"";l.edges.push(`${o}>${t.id}`),l.ids.push(t.id);const a=e.sets?e.sets[t.id]:void 0;a&&(s.ingest={...s.ingest,...a}),c=t.rest}o.push(l)};return r(Ai(e.spec),ir(t),{ids:[],stopped:!1,edges:[]}),o}function rr(e){return e.map(e=>e.stopped?[...e.ids,Xo]:e.ids)}var sr={Source:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",primary:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",variables:"resolve",examples:"docs"},Transformer:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",mapping:"runtime",variables:"resolve",examples:"docs"},Destination:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",before:"runtime",next:"runtime",cache:"runtime",state:"runtime",variables:"resolve",examples:"docs"},Store:{package:"reference",code:"reference",import:"reference",config:"runtime",env:"runtime",cache:"runtime",variables:"resolve",examples:"docs"}},ar=["disabled","id","logger","mock","chainMocks"],cr=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function lr(e,t){const n=function(e){return new Set([...Object.keys(sr[e]),...ar])}(t);for(const i of Object.keys(e))if(!n.has(i))return{ok:!1,code:"UNKNOWN_KEY",key:i,reason:`Unknown key "${i}" on ${t}. Allowed: ${[...n].sort().join(", ")}.`};const i=void 0!==e.package,o=void 0!==e.import,r=void 0!==e.code;return r&&"string"==typeof e.code?{ok:!1,code:"OBSOLETE_CODE_STRING",key:"code",reason:`code: "<name>" is no longer supported. Use import: "${e.code}" with the package field instead.`}:r&&("object"!=typeof e.code&&"function"!=typeof e.code||null===e.code||Array.isArray(e.code))?{ok:!1,code:"INVALID_CODE_SHAPE",key:"code",reason:"code must be an object ({ push, type?, init? }) or a resolved function value."}:r&&i?{ok:!1,code:"CONFLICT",key:"package",reason:"Cannot specify both `code` and `package`. Use one or the other."}:r&&o?{ok:!1,code:"CONFLICT",key:"import",reason:"Cannot specify both `code` and `import`."}:o&&!i?{ok:!1,code:"MISSING_PACKAGE",key:"import",reason:"`import` requires `package` to be set."}:!o||"string"==typeof e.import&&cr.test(e.import)?{ok:!0}:{ok:!1,code:"INVALID_IMPORT",key:"import",reason:`import must match ${cr.source}. Got: ${JSON.stringify(e.import)}.`}}function dr(e){return function(e){return gi(e)&&"push"in e}(e)||"string"==typeof e}function pr(e,t,n){if("Transformer"===e){const e=lr({...n},"Transformer");if(!e.ok)throw new Error(`Transformer "${t}": ${e.reason??"invalid entry."}`);return}const i=!!n.package,o=dr(n.code);if(i&&o)throw new Error(`${e} "${t}": Cannot specify both package and code. Use one or the other.`);if(!i&&!o)throw new Error(`${e} "${t}": Must specify either package or code.`)}var ur=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/;function fr(e,t){for(const n of Object.keys(e))if(!ur.test(n))throw new Error(`Invalid ${t} name "${n}": must be a valid JavaScript identifier (use camelCase, e.g., "${n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}")`)}function mr(e,t){const n=[];function i(e,t){if("string"==typeof e&&e.startsWith("$store."))n.push({ref:e.slice(7),location:t});else if(null!==e&&"object"==typeof e)for(const[n,o]of Object.entries(e))i(o,`${t}.${n}`)}const o={sources:e.sources||{},destinations:e.destinations||{},transformers:e.transformers||{}};for(const[e,t]of Object.entries(o))for(const[n,o]of Object.entries(t))i(o,`${e}.${n}`);const r=n.filter(({ref:e})=>!t.has(e));if(r.length>0){const e=t.size>0?`Available stores: ${Array.from(t).join(", ")}`:"No stores defined",n=r.map(({ref:e,location:t})=>`"$store.${e}" in ${t} (store "${e}" not found)`).join("; ");throw new Error(`Invalid store references: ${n}. ${e}`)}}var gr=["sources","destinations","transformers","stores"],hr={sources:"Source",destinations:"Destination",transformers:"Transformer",stores:"Store"};function br(e,t){switch(t){case"sources":return e.sources;case"destinations":return e.destinations;case"transformers":return e.transformers;case"stores":return e.stores}}function vr(e){return"string"==typeof e||gi(e)&&"push"in e}function yr(e){return e instanceof Error?e.message:String(e)}var Sr=["sources","transformers","destinations"];function wr(e,t){const n=[],i=e.stores||{},o=(e,t)=>{if(!gi(e)||"string"!=typeof e.store)return;const o=e.store;if(o.startsWith("$")||"__cache"===o)return;const r=i[o];r?gi(r.config)&&!0===r.config.file&&n.push({path:t,message:`State cannot use store "${o}": it sets file: true. Handle byte stores in a transformer.`,code:"STATE_STORE_FILE"}):n.push({path:t,message:`State store "${o}" is not declared in flow.stores.`,code:"STATE_STORE_UNKNOWN"})},r=(e,t)=>{Array.isArray(e)?e.forEach((e,n)=>o(e,`${t}.${n}`)):o(e,t)};for(const n of Sr){const i=br(e,n);if(i)for(const[e,o]of Object.entries(i)){const i=`flows.${t}.${n}.${e}`;"state"in o&&r(o.state,`${i}.state`),gi(o.config)&&r(o.config.state,`${i}.config.state`)}}return n}function kr(e){const t=[],n={},i=e.flows,o=gi(i)?Object.keys(i):[];if(n.flowNames=o,n.flowCount=o.length,!gi(i)||0===o.length)return t.push({path:"flows",message:"At least one flow is required",code:"EMPTY_FLOWS"}),{valid:!1,type:"flow",errors:t,warnings:[],details:n};for(const[e,n]of Object.entries(i)){for(const i of gr){const o=br(n,i);if(o)try{fr(o,i)}catch(n){t.push({path:`flows.${e}.${i}`,message:yr(n),code:"INVALID_COMPONENT_NAME"})}}for(const i of gr){const o=br(n,i);if(!o)continue;const r=hr[i];if("Transformer"!==r)for(const[n,s]of Object.entries(o))if("Store"!==r||s.package||vr(s.code))try{pr(r,n,s)}catch(o){t.push({path:`flows.${e}.${i}.${n}`,message:yr(o),code:"INVALID_REFERENCE"})}}const i=n.transformers;if(i)for(const[n,o]of Object.entries(i)){const i=lr({...o},"Transformer");i.ok||t.push({path:`flows.${e}.transformers.${n}`,message:i.reason||"Invalid transformer entry.",code:i.code})}const o=new Set(Object.keys(n.stores||{}));try{mr(n,o)}catch(n){t.push({path:`flows.${e}`,message:yr(n),code:"STORE_REFERENCE_NOT_FOUND"})}t.push(...wr(n,e))}return{valid:0===t.length,type:"flow",errors:t,warnings:[],details:n}}export{di as ClickIdEntrySchema,Vo as expectSimulationResolves,Wo as formatOut,Lo as mergeConfigSchema,_o as resolveBaseSchema,Yo as routeCases,n as schemas,fr as validateComponentNames,kr as validateFlowStructure,pr as validateReference,mr as validateStoreReferences,i as z,Mo as zodToSchema};//# sourceMappingURL=dev.mjs.map