@walkeros/collector 4.2.0 → 4.3.0-next-1781171238534
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/CHANGELOG.md +7 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e={},t={Action:"action",Actions:"actions",Config:"config",Consent:"consent",Context:"context",Custom:"custom",Destination:"destination",Elb:"elb",Globals:"globals",Hook:"hook",Init:"init",Link:"link",On:"on",Prefix:"data-elb",Ready:"ready",Run:"run",Scoped:"_",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"},n={Commands:t,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};import{assign as o}from"@walkeros/core";function s(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=o(e.consent,n),{update:n}}import{assign as r,createLogger as a}from"@walkeros/core";import{assign as i,buildCacheContext as c,clone as u,compileCache as d,checkCache as l,storeCache as f,createIngest as p,debounce as g,emitStep as m,getId as h,getGrantedConsent as y,getNextSteps as w,isDefined as v,isFunction as b,isObject as k,processEventMapping as C,stepId as I,tryCatchAsync as q,useHooks as S,compileState as x,applyState as O}from"@walkeros/core";import{emitStep as j}from"@walkeros/core";function D(e,t){const n=e.status.startedAt;return{flowId:"default",stepId:t.stepId,stepType:t.stepType,phase:t.phase,eventId:t.eventId,timestamp:new Date(t.now).toISOString(),elapsedMs:t.now-n}}import{isArray as A,FatalError as $}from"@walkeros/core";import{tryCatch as E,tryCatchAsync as M}from"@walkeros/core";import{createIngest as T,FatalError as _,getMappingValue as P,tryCatchAsync as z,getNextSteps as B,compileCache as H,checkCache as R,storeCache as F,applyUpdate as G,buildCacheContext as K,compileState as U,applyState as W}from"@walkeros/core";import{createIngest as V,emitStep as N,FatalError as L,isObject as Y,stepId as J,tryCatchAsync as Q,useHooks as X,getNextSteps as Z,compileCache as ee,checkCache as te,storeCache as ne,buildCacheContext as oe,validateStepEntry as se,processEventMapping as re,compileState as ae,applyState as ie}from"@walkeros/core";function ce(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function ue(e,t){return e?t.stores[e]:t.stores.__cache}function de(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)?t[n]={next:e}:t[n]={}}return t}function le(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function fe(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function pe(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:V(n),config:t.config,env:ye(t.config.env)};s.debug("init");const a=await X(t.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===a)return!1;t.config={...a||t.config,env:a?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function ge(e,t,n,o,s,r){const a=t.type||"unknown",i=e.logger.scope(`transformer:${a}`),c={collector:e,logger:i,id:n,ingest:s,config:t.config,env:{...ye(t.config.env),...r?{respond:r}:{}}};i.debug("push",{event:o.name});const u="string"==typeof o.id?o.id:"",d=Date.now(),l=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"in",eventId:u,now:d});N(e,l);try{const s=await X(t.push,"TransformerPush",e.hooks,e.logger)(o,c),r=Date.now(),a=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"out",eventId:u,now:r});return a.durationMs=r-d,a.outEvent=s,N(e,a),i.debug("push done"),s}catch(t){const o=Date.now(),s=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"error",eventId:u,now:o});throw s.durationMs=o-d,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},N(e,s),t}}function me(e,t){return e?{...e,_meta:{...e._meta,path:[...e._meta.path]}}:V(t)}async function he(e,t,n,o,s,r,a){s||(s=V(n[0]??"chain")),a&&s._meta&&(s._meta.chainPath=a);let i=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};s&&s._meta&&(s._meta.hops++,s._meta.path.push(o));if(!await Q(pe,t=>{if(t instanceof L)throw t;return e.status.failed++,e.logger.scope(`transformer:${r.type||"unknown"}`).error("transformer init failed",{transformer:o,error:t}),!1})(e,r,o))return{event:null,respond:c};if(a&&void 0!==r.config?.chainMocks?.[a]){const t=r.config.chainMocks[a];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:a}),i=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),i=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,d=u?ee(u):void 0,l=d?ce(d,e):void 0,f=r.config?.state?ae(r.config.state):void 0,p=f?.filter(e=>"get"===e.mode),g=f?.filter(e=>"set"===e.mode),m=async t=>g&&0!==g.length?ie(g,t=>ue(t,e),t,e):t;let h;if(d&&l){const e=oe(s,i),t=await te(d,l,e);if("HIT"===t?.status&&t.value){if(i=t.value,d.stop)return{event:i,respond:c,stopped:!0};continue}"MISS"===t?.status&&(h={key:t.key,ttl:t.rule.ttl})}const y=r.config.before;if(y){const n=Z(y,oe(s,i));if(1===n.length){const o=fe(n[0],de(t));if(o.length>0){const n=await he(e,t,o,i,s,c,a);if(null===n.event)return{event:null,respond:n.respond??c};if(n.stopped)return{event:Array.isArray(n.event)?n.event[0]:n.event,respond:n.respond??c,stopped:!0};n.respond&&(c=n.respond),i=Array.isArray(n.event)?n.event[0]:n.event}}else n.length>1&&await Promise.all(n.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),i,me(s,n),void 0,a)))}p&&p.length>0&&(i=await ie(p,t=>ue(t,e),i,e));const w=await Q(ge,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,i,s,c);if(!1===w)return{event:null,respond:c};if(Array.isArray(w)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(w.map(async n=>{const o=await m(n.event||i),u=me(s,"unknown");if(n.next){const s=Z(n.next,oe(u,o));if(0===s.length)return{event:o,respond:c};if(1===s.length){const n=fe(s[0],de(t));return n.length>0?he(e,t,n,o,u,c,a):{event:o,respond:c}}return(await Promise.all(s.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),o,me(u,n),void 0,a)))).map(e=>({event:e.event,respond:void 0}))}return r.length>0?he(e,t,r,o,u,c,a):{event:o,respond:c}}));let d=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(d=t.respond),null===t.event)continue;Array.isArray(t.event)?l.push(...t.event):l.push(t.event)}else l.push(e);return 0===l.length?{event:null,respond:d}:1===l.length?{event:l[0],respond:d}:{event:l,respond:d}}if(w&&"object"==typeof w){const{event:n,respond:o,next:r}=w;if(o&&(c=o),void 0!==r){const o=await m(n||i),u=Z(r,oe(s,o));if(0===u.length){i=o;continue}if(1===u.length){const n=fe(u[0],de(t));return n.length>0?he(e,t,n,o,s,c,a):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}return await Promise.all(u.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),o,me(s,n),void 0,a))),{event:null,respond:void 0}}n&&(i=n)}g&&g.length>0&&(i=await ie(g,t=>ue(t,e),i,e)),h&&l&&ne(l,h.key,i,h.ttl);const v=r.config.next,b="string"==typeof v||Array.isArray(v)&&v.every(e=>"string"==typeof e),k=void 0!==v&&!b;if((!w||"object"==typeof w&&!w.next)&&k){const n=Z(r.config.next,oe(s,i));if(1===n.length){const o=fe(n[0],de(t));return o.length>0?he(e,t,o,i,s,c,a):{event:i,respond:c}}return n.length>1?(await Promise.all(n.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),i,me(s,n),void 0,a))),{event:null,respond:void 0}):{event:i,respond:c}}}return{event:i,respond:c}}function ye(e){return e&&Y(e)?e:{}}function we(e){return"string"==typeof e||!(!Array.isArray(e)||!e.every(e=>"string"==typeof e))}async function ve(e,t,n){if(!t.on||!t.queueOn?.length)return;const o=t.queueOn;t.queueOn=[];const s=n||t.config?.id||"unknown";for(const{type:n,data:r}of o)De(n)&&!Te(e,t,n)||(await z(t.on,t=>{if(t instanceof _)throw t;e.status.failed++,e.logger.scope("source").error("source on flush failed",{sourceId:s,type:n,error:t})})(n,r),De(n)&&Me(e,t,n))}function be(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ke(e,t,n){const{code:o,config:s={},env:r={},primary:a,next:i,before:c,cache:u}=n,d=s.state??n.state,l=d?U(d):void 0,f=u,p=f?H({...f,stop:f.stop??!0}):void 0,g=we(i)?fe(i,de(e.transformers)):void 0,m=we(c)?fe(c,de(e.transformers)):void 0,h=r.push,y=h??e.push,w=Boolean(h),v=async(n,o,r)=>{let a;const u=m??(void 0!==c?(()=>{const t=B(c,K(r.ingest));if(0===t.length)return[];return fe(1===t.length?t[0]:t,de(e.transformers))})():[]);let d=[n];if(u.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await he(e,e.transformers,u,n,r.ingest,r.respond,`source.${t}.before`);if(null===o.event)return{ok:!0};if(o.stopped)return o.respond&&(r.respond=o.respond),{ok:!0};o.respond&&(r.respond=o.respond),d=Array.isArray(o.event)?o.event:[o.event]}if(p){const t=ce(p,e);if(t){const n=K(r.ingest),o=await R(p,t,n);if(o){if("HIT"===o.status&&void 0!==o.value&&p.stop){let t=o.value;return o.rule.update&&(t=await G(t,o.rule.update,{...n,cache:{status:"HIT"}},e)),r.respond?.(t),{ok:!0}}if("MISS"===o.status&&p.stop&&r.respond){const s=r.respond,i=o.rule.update,c={...n,cache:{status:"MISS"}},u=o.key,d=o.rule.ttl,l=n=>{F(t,u,n,d),i?a=(async()=>{const t=await G(n,i,c,e);s(t)})():s(n)};r.respond=l}"MISS"!==o.status||p.stop||F(t,o.key,!0,o.rule.ttl)}}}const f=g?{kind:"single",preChain:g}:void 0!==i?(()=>{const t=B(i,K(r.ingest));return 0===t.length?{kind:"single",preChain:[]}:1===t.length?{kind:"single",preChain:fe(t[0],de(e.transformers))}:{kind:"many",branches:t.map(t=>fe(t,de(e.transformers)))}})():{kind:"single",preChain:[]};!w&&l&&l.length>0&&(d=await Promise.all(d.map(t=>W(l,t=>ue(t,e),t,e))));let h={ok:!0};for(const n of d)"many"===f.kind?(await Promise.all(f.branches.map((a,i)=>z(async()=>w?y(n):y(n,{...o,id:t,ingest:me(r.ingest,`${t}.${i}`),respond:void 0,mapping:s,preChain:a}),t=>(e.logger.scope("source:many").error(`many branch ${i} failed`,{error:t}),{ok:!0}))())),h={ok:!0}):h=w?await y(n):await y(n,{...o,id:t,ingest:r.ingest,respond:r.respond,mapping:s,preChain:f.preChain});return a&&await a,h},b=async n=>{const o=T(t);if(!s.ingest||void 0===n)return o;const r=await P(n,s.ingest,{collector:e});return{...o,...r,_meta:o._meta}},k=e.logger.scope("source").scope(t),C={command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:k,...r,push:async(e,n={})=>{const o={ingest:T(t),respond:void 0};return v(e,n,o)}},I={collector:e,logger:k,id:t,config:s,env:C,withScope:async(e,t,n)=>{const o={ingest:await b(e),respond:t};return n({...C,push:(e,t={})=>v(e,t,o),ingest:o.ingest,respond:o.respond})}},q=await z(o,n=>{if(n instanceof _)throw n;e.status.failed++,e.logger.scope("source").error("source factory failed",{sourceId:t,error:n})})(I);if(!q)return;const S=q.type||"unknown",x=e.logger.scope(S).scope(t);return C.logger=x,a&&(q.config={...q.config,primary:a}),q}async function Ce(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const t=await ke(e,o,s);if(!t)continue;const r=s.config?.require;t.config={...t.config,init:!1,...r?{require:[...r]}:{}},n[o]=t}Object.assign(e.sources,n);for(const t of Object.keys(n)){const n=e.sources[t];let o=!1;n.init&&await z(n.init.bind(n),n=>{if(n instanceof _)throw n;o=!0,e.status.failed++,e.logger.scope("source").error("source init failed",{sourceId:t,error:n})})(),o||(n.config.init=!0,be(n)&&await ve(e,n,t))}return await Ie(e),n}async function Ie(e){for(const[t,n]of Object.entries(e.sources)){if(be(n))continue;const o=n.config.require;if(!o?.length)continue;const s=o.filter(t=>!$e(e,t));s.length!==o.length&&(n.config.require=s,be(n)&&await ve(e,n,t))}for(const[t,n]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const o=n.config?.require;if(!o)continue;const s=o.filter(t=>!$e(e,t));if(n.config&&(n.config.require=s),s.length>0)continue;delete e.pending.destinations[t];const r=at(n);!1!==r.config.queue&&(r.queuePush=[...e.queue]),e.destinations[t]=r}}function qe(e){if("object"!=typeof e||null===e)return!1;if(!("logger"in e))return!1;const t=e.logger;return"object"==typeof t&&null!==t&&("scope"in t&&"function"==typeof t.scope)}var Se=!1;function xe(){Se||(Se=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("walkerOS: ignored an on-dispatch call with a non-collector argument"))}function Oe(e,t,n,o){if(n instanceof $)throw n;e.logger.scope("on").error("on callback failed",{kind:t,...o,error:n})}var je=[n.Commands.Consent,n.Commands.User,n.Commands.Globals,n.Commands.Custom];function De(e){return je.includes(e)}function Ae(e,t){switch(t){case n.Commands.Consent:return Object.keys(e.consent).length>0;case n.Commands.User:return Object.keys(e.user).length>0;case n.Commands.Globals:return Object.keys(e.globals).length>0;case n.Commands.Custom:return Object.keys(e.custom).length>0;default:return!1}}function $e(e,t){switch(t){case n.Commands.Consent:case n.Commands.User:case n.Commands.Globals:case n.Commands.Custom:return Ae(e,t);case n.Commands.Run:case n.Commands.Ready:return!0===e.allowed;default:return e.seenEvents.has(String(t))}}function Ee(e,t){return e.cellVersion[String(t)]??0}function Me(e,t,n){let o=e.delivery.get(t);o||(o={},e.delivery.set(t,o)),o[String(n)]=Ee(e,n)}function Te(e,t,n){return e.allowed&&Ee(e,n)>function(e,t,n){const o=e.delivery.get(t),s=o?.[String(n)];return void 0===s?-1:s}(e,t,n)}function _e(e){return e.cascade?()=>{}:(e.cascade={counts:new WeakMap},()=>{e.cascade=void 0})}function Pe(e,t,n){const o=e.cascade;if(!o)return!0;let s=o.counts.get(t);s||(s={},o.counts.set(t,s));const r=String(n),a=(s[r]||0)+1;return s[r]=a,a<=8||(9===a&&e.logger.error("state delivery did not converge",{type:r}),!1)}function ze(e,t){return{collector:e,logger:e.logger.scope("on").scope(String(t))}}async function Be(e,t,n){if(!qe(e))return void xe();const o=e.on,s=o[t]||[],r=A(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,Re(e,t,r)}function He(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",a=e.logger.scope(r).scope("on").scope(o),i={collector:e,logger:a,id:n,config:t.config,data:s,env:ct(t.env,t.config.env)};E(t.on,t=>Oe(e,"destination",t,{destId:n,type:o}))(o,i)}function Re(e,t,o,s){if(!qe(e))return void xe();const r=Fe(e,t,s);if(o.length)switch(t){case n.Commands.Consent:!function(e,t,o){const s=o||e.consent,r=ze(e,n.Commands.Consent);t.forEach(t=>{Te(e,t,n.Commands.Consent)&&Pe(e,t,n.Commands.Consent)&&(Object.keys(s).filter(e=>e in t).forEach(n=>{E(t[n],t=>Oe(e,"consent",t,{key:n}))(s,r)}),Me(e,t,n.Commands.Consent))})}(e,o,s);break;case n.Commands.Ready:!function(e,t){if(!e.allowed)return;const o=ze(e,n.Commands.Ready);t.forEach(t=>{E(t,t=>Oe(e,"ready",t))(void 0,o)})}(e,o);break;case n.Commands.Run:!function(e,t){if(!e.allowed)return;const o=ze(e,n.Commands.Run);t.forEach(t=>{E(t,t=>Oe(e,"run",t))(void 0,o)})}(e,o);break;case n.Commands.Session:!function(e,t){if(!e.session)return;const o=ze(e,n.Commands.Session);t.forEach(t=>{E(t,t=>Oe(e,"session",t))(e.session,o)})}(e,o);break;default:{const n=ze(e,t),s=De(t);o.forEach(o=>{"function"==typeof o&&(s&&!Te(e,o,t)||s&&!Pe(e,o,t)||(E(o,n=>Oe(e,"generic",n,{type:t}))(r,n),s&&Me(e,o,t)))});break}}}function Fe(e,t,o){switch(t){case n.Commands.Consent:return o||e.consent;case n.Commands.Session:return e.session;case n.Commands.User:return o||e.user;case n.Commands.Custom:return o||e.custom;case n.Commands.Globals:return o||e.globals;case n.Commands.Config:return o||e.config;default:return}}async function Ge(e,t,n,o,s){if(!t.on)return!1;if(De(o)&&!Te(e,t,o))return!1;if(De(o)&&!Pe(e,t,o))return!1;const r=await M(t.on,t=>Oe(e,"source",t,{sourceId:n,type:o}))(o,s);return De(o)&&Me(e,t,o),!1===r}async function Ke(e){if(qe(e))for(const t of je){if(!Ae(e,t))continue;const n=Fe(e,t);Re(e,t,e.on[t]||[]);for(const[o,s]of Object.entries(e.sources))be(s)&&await Ge(e,s,o,t,n)}else xe()}async function Ue(e,t,n,o){if(!qe(e))return xe(),!0;e.seenEvents.add(String(t));let s=n||[];n||(s=e.on[t]||[]);const r=Fe(e,t,o);let a=!1;for(const[n,o]of Object.entries(e.sources)){if(o.config.require?.length){const e=o.config.require.indexOf(t);-1!==e&&o.config.require.splice(e,1)}if(o.on)if(be(o)){await Ge(e,o,n,t,r)&&(a=!0)}else o.queueOn=o.queueOn||[],o.queueOn.push({type:t,data:r})}Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:r});He(e,o,n,t,r)}});for(const[t,n]of Object.entries(e.sources))be(n)&&n.queueOn?.length&&await ve(e,n,t);const i=Object.values(e.sources).some(e=>!be(e)&&e.config.require?.length);return(Object.keys(e.pending.destinations).length>0||i)&&await Ie(e),Re(e,t,s,o),!a}function We(e,t,n,o){if(!Number.isFinite(n.max)||n.max<=0)throw new Error(`pushBounded: max must be > 0 (got ${n.max})`);if("dropNewest"===(n.onOverflow??"dropOldest"))return e.length>=n.max?(o&&o([t]),{appended:!1,dropped:1}):(e.push(t),{appended:!0,dropped:0});const s=[];for(;e.length>=n.max;)s.push(e.shift());return e.push(t),s.length>0&&o&&o(s),{appended:!0,dropped:s.length}}var Ve=new WeakMap;function Ne(e,t,n,o){Ve.get(e)||(Ve.set(e,!0),t.warn(n,o))}function Le(e){Ve.delete(e)}var Ye=Object.freeze({batched:!0});function Je(e){return e===Ye}function Qe(e){return void 0===e?{}:"number"==typeof e?{wait:e}:{wait:e.wait,size:e.size,age:e.age}}function Xe(e,t){return e.status.destinations[t]||(e.status.destinations[t]={count:0,failed:0,duration:0,queuePushSize:0,dlqSize:0}),e.status.destinations[t]}function Ze(e,t,n,o){e.dropped[t]||(e.dropped[t]={});const s=e.dropped[t];return s[n]=(s[n]??0)+o,s[n]}function et(e,t,n){if(!e)return[];if(Array.isArray(e)&&e.every(e=>"string"==typeof e))return fe(e,t);if("string"==typeof e)return fe(e,t);const o=w(e,c(n));return 0===o.length?[]:1===o.length?fe(o[0],t):fe(o,t)}async function tt(e,t){const{code:n,config:o={},env:s={},before:r,next:a,cache:i,state:c}=t;if(!b(n.push))return rt({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=o||{init:!1};let d=r?{...u,before:r}:{...u};a&&(d={...d,next:a}),i&&(d={...d,cache:i}),void 0!==c&&void 0===d.state&&(d={...d,state:c});let l=d.id;if(!l)do{l=h(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[l]||e.pending.destinations[l]);if(d.require?.length){e.pending.destinations[l]=t,await Ie(e);const n=e.destinations[l];return n?nt(e,void 0,{},{[l]:n}):rt({ok:!0})}const f={...n,config:d,env:ct(n.env,s)};return e.destinations[l]=f,!1!==f.config.queue&&(f.queuePush=[...e.queue]),nt(e,void 0,{},{[l]:f})}async function nt(e,t,n={},o){const{allowed:s,consent:r,globals:a,user:g}=e;if(!s)return rt({ok:!1});if(t){const n=e.config.queueMax;if(void 0===n)throw new Error("Collector.Config.queueMax is undefined; defaults must be seeded by collector()");const o=We(e.queue,t,{max:n});if(o.dropped>0){const t=Ze(e.status,I("collector"),"queue",o.dropped);Ne(e.queue,e.logger,"collector.queue overflow; oldest events dropped",{buffer:"queue",cap:n,droppedCount:t})}else e.queue.length<n&&Le(e.queue);e.status.in++}o||(o=e.destinations);const h=e.transformers?de(e.transformers):{},w=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let w=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],t&&w.push(u(t));const v=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:p("unknown");if(!w.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!w.length&&s.queueOn?.length){let t=!1;try{t=await ot(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}return{id:o,destination:s,skipped:!t}}const b=[],k=w.filter(t=>{const n=y(s.config.consent,r,t.consent);if(n)return t.consent=n,b.push(t),!1;const a=D(e,{stepId:I("destination",o),stepType:"destination",phase:"skip",eventId:"string"==typeof t.id?t.id:"",now:Date.now()});return a.skipReason="consent",r&&(a.consent={...r}),s.config.consent&&(a.meta={required:{...s.config.consent}}),m(e,a),!0});if(k.length>0){const t=s.queuePush,n=s.config.id||o,r={max:s.config.queueMax??1e3};let a=0;for(const e of k){a+=We(t,e,r).dropped}if(a>0){Xe(e,n);const o=Ze(e.status,I("destination",n),"queue",a);Ne(t,e.logger.scope(s.type||"unknown"),"destination.queuePush overflow; oldest events dropped",{buffer:"queuePush",destination:n,cap:r.max,droppedCount:o})}else t.length<r.max&&Le(t)}if(!b.length)return{id:o,destination:s,queue:w};let C,S,j=!1;try{j=await ot(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}if(!j)return{id:o,destination:s,queue:w};s.dlq||(s.dlq=[]);const A=et(s.config.before,h,v),$=s.config.next,E=s.config?.cache,M=E?d(E):void 0,T=M?ce(M,e):void 0,_=s.config?.state?x(s.config.state):void 0,P=_?.filter(e=>"get"===e.mode),z=_?.filter(e=>"set"===e.mode);let B=0,H=0;return await Promise.all(b.map(async t=>{let r;if(t.globals=i(a,t.globals),t.user=i(g,t.user),M?.stop&&T){const e=c(v,t),n=await l(M,T,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let u=t,d=n.respond;if(A.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await he(e,e.transformers,A,t,v,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(d=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(M&&!M.stop&&T){const e=c(v,u),n=await l(M,T,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}P&&P.length>0&&u&&(u=await O(P,t=>ue(t,e),u,e));const p=Date.now();let m=!1;const y=await q(st,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:u.name}),C=t,m=!0;const r=s.dlq,a=s.config.id||o,i={max:s.config.dlqMax??100},c=We(r,[u,t],i);if(c.dropped>0){Xe(e,a);const t=Ze(e.status,I("destination",a),"dlq",c.dropped);Ne(r,e.logger.scope(s.type||"unknown"),"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:a,cap:i.max,droppedCount:t})}else r.length<i.max&&Le(r)})(e,s,o,u,v,d);if(B+=Date.now()-p,r&&T&&void 0===s.config.mock&&f(T,r.key,y??!0,r.ttl),!m&&!Je(y)&&z&&z.length>0&&u&&(u=await O(z,t=>ue(t,e),u,e)),void 0===y||Je(y)||(S=y),Je(y)&&H++,!m&&$){void 0!==y&&(v._response=y);const t=et($,h,v);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await he(e,e.transformers,t,u,v,d,`destination.${o}.next`);n.respond&&(d=n.respond)}}return t})),{id:o,destination:s,error:C,response:S,totalDuration:B,batchedCount:H,allowedCount:b.length}})),v={},b={},k={};for(const t of w){if(t.skipped)continue;const n=t.destination,o={type:n.type||"unknown",data:t.response};Xe(e,t.id);const s=e.status.destinations[t.id],r=Date.now();if(s.queuePushSize=n.queuePush?.length??0,s.dlqSize=n.dlq?.length??0,t.error)o.error=t.error,k[t.id]=o,s.failed++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.failed++;else if(t.queue&&t.queue.length)b[t.id]=o;else{const n=t.batchedCount??0,a=t.allowedCount??0;(Math.max(0,a-n)>0||0===a)&&(v[t.id]=o,s.count++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.out++)}}return rt({event:t,...Object.keys(v).length&&{done:v},...Object.keys(b).length&&{queued:b},...Object.keys(k).length&&{failed:k}})}async function ot(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:ct(t.env,t.config.env)};s.debug("init");const a=Date.now();let i;m(e,D(e,{stepId:I("destination",n),stepType:"destination",phase:"init",eventId:"",now:a}));try{i=await S(t.init,"DestinationInit",e.hooks,e.logger)(r)}catch(t){const o=Date.now(),s=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});throw s.durationMs=o-a,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},m(e,s),t}if(!1===i)return i;if(t.config={...i||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)He(e,t,n,s,r)}s.debug("init done")}return!0}async function st(e,t,n,o,s,r){const{config:a}=t,i=await C(o,a,e);if(i.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),d={collector:e,logger:u,id:n,config:a,data:i.data,rule:i.mapping,ingest:s,env:{...ct(t.env,a.env),...r?{respond:r}:{}}};if(void 0!==a.mock)return u.debug("mock",{event:i.event.name}),a.mock;const l=i.mapping,f=void 0!==l?.batch,p=f?i.mappingKey||"* *":" batch-all";if((f||void 0!==a.batch)&&t.pushBatch&&void 0===a.mock){if(t.batches=t.batches||{},!t.batches[p]){const o={key:p,entries:[],events:[],data:[]},s=Qe(l?.batch),r=Qe(a.batch),i=s.wait??r.wait??3e4,c=s.size??r.size??1e3,d=s.age??r.age??3e4,h=ct(t.env,a.env),y=g(async()=>{const o=t.batches[p],s=o.batched;if(0===s.entries.length)return;const r={key:s.key,entries:s.entries,events:s.events,data:s.data};s.entries=[],s.events=[],s.data=[];const i=r.entries[0],c={collector:e,logger:u,id:n,config:a,data:void 0,rule:o.isDefault?void 0:i.rule,ingest:i.ingest,env:{...h,...i.respond?{respond:i.respond}:{}}};u.debug("push batch",{events:r.entries.length});const d=t.config.id||n,l=Xe(e,d),f=Date.now(),g=D(e,{stepId:I("destination",n),stepType:"destination",phase:"flush",eventId:"",now:f});g.batch={size:r.entries.length,index:0},m(e,g);const y=n=>{const o=t.dlq=t.dlq||[],s={max:t.config.dlqMax??100};let r=0;for(const e of n){r+=We(o,e,s).dropped}if(r>0){const t=Ze(e.status,I("destination",d),"dlq",r);Ne(o,u,"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:d,cap:s.max,droppedCount:t})}else o.length<s.max&&Le(o);l.failed+=n.length,l.dlqSize=o.length,e.status.failed+=n.length};let w=r.entries.length;const v=await q(S(t.pushBatch,"DestinationPushBatch",e.hooks,e.logger),t=>{w=0;const o=Date.now(),s=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});s.durationMs=o-f,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},s.batch={size:r.entries.length,index:0},m(e,s),y(r.entries.map(e=>[e.event,t])),u.error("Push batch failed",{error:t instanceof Error?t.message:String(t),entries:r.entries.length})})(r,c);if(k(b=v)&&Array.isArray(b.failed)&&v.failed.length>0){const e=[],t=new Set;for(const n of v.failed){const o=r.entries[n.index];o&&!t.has(n.index)&&(t.add(n.index),e.push([o.event,n.error??new Error(`Push batch entry ${n.index} failed (no per-row error provided)`)]))}e.length>0&&(y(e),w=Math.max(0,r.entries.length-e.length),u.error("Push batch partial failure",{failed:e.length,delivered:w,entries:r.entries.length}))}var b;u.debug("push batch done"),l.inFlightBatch=Math.max(0,(l.inFlightBatch??0)-r.entries.length),w>0&&(l.count+=w,l.lastAt=Date.now(),e.status.out+=w)},{wait:i,size:c,age:d});t.batches[p]={batched:o,isDefault:!f,batchFn:()=>{y()},flush:async()=>{await y.flush()}}}const o=t.batches[p];o.batched.entries.push({event:i.event,ingest:s,respond:r,rule:l,data:i.data}),o.batched.events.push(i.event),v(i.data)&&o.batched.data.push(i.data);const c=t.config.id||n,d=Xe(e,c);return d.inFlightBatch=(d.inFlightBatch??0)+1,o.batchFn(),Ye}{u.debug("push",{event:i.event.name});const o="string"==typeof i.event.id?i.event.id:"",s=Date.now(),r=D(e,{stepId:I("destination",n),stepType:"destination",phase:"in",eventId:o,now:s});i.mappingKey&&(r.mappingKey=i.mappingKey),i.event.consent&&(r.consent={...i.event.consent}),m(e,r);try{const r=await S(t.push,"DestinationPush",e.hooks,e.logger)(i.event,d),a=Date.now(),c=D(e,{stepId:I("destination",n),stepType:"destination",phase:"out",eventId:o,now:a});return c.durationMs=a-s,c.outEvent=r,i.mappingKey&&(c.mappingKey=i.mappingKey),m(e,c),u.debug("push done"),r}catch(t){const r=Date.now(),a=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:o,now:r});throw a.durationMs=r-s,a.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},i.mappingKey&&(a.mappingKey=i.mappingKey),m(e,a),t}}}function rt(e){return{ok:!e?.failed,...e}}function at(e){const{code:t,config:n={},env:o={},cache:s,state:r}=e,{config:a}=le(e,"before"),{config:i}=le({...e,config:a},"next"),c={...t.config,...n,...i};s&&(c.cache=s),void 0!==r&&void 0===c.state&&(c.state=r);const u=ct(t.env,o);return{...t,config:c,env:u}}async function it(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=at(s);return n}function ct(e,t){return e||t?t?e&&k(e)&&k(t)?{...e,...t}:t:e:{}}import{assign as ut,getSpanId as dt,isFunction as lt,isString as ft}from"@walkeros/core";import{isObject as pt}from"@walkeros/core";var gt=5e3;async function mt(e){const t=e.logger;await ht(e.sources,"source",t),await async function(e,t){const n=Object.entries(e).flatMap(([e,n])=>{const o=n.batches;if(!o)return[];const s=t.scope(n.type||"destination");return Object.values(o).map(async t=>{let n;try{await Promise.race([t.flush(),new Promise((t,o)=>{n=setTimeout(()=>o(new Error(`destination '${e}' batch flush timed out`)),gt)})])}catch(t){s.error(`destination '${e}' batch flush failed: ${t}`)}finally{n&&clearTimeout(n)}})});await Promise.allSettled(n)}(e.destinations,t),await ht(e.destinations,"destination",t),await ht(e.transformers,"transformer",t),await ht(e.stores,"store",t)}async function ht(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",a=n.scope(r),i={id:e,config:o.config,env:o.env??{},logger:a};let c;try{await Promise.race([s(i),new Promise((n,o)=>{c=setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),gt)})])}catch(n){a.error(`${t} '${e}' destroy failed: ${n}`)}finally{c&&clearTimeout(c)}});await Promise.allSettled(o)}function yt(e,t){e.stateVersion++,e.cellVersion[t]=e.stateVersion}async function wt(e,t,o){let r,a,i=!1;const c=_e(e);try{return await async function(){switch(t){case n.Commands.Config:pt(o)&&(ut(e.config,o,{shallow:!1}),a=o,i=!0);break;case n.Commands.Consent:if(pt(o)){const{update:t}=s(e,o);yt(e,n.Commands.Consent),a=t,i=!0}break;case n.Commands.Custom:pt(o)&&(e.custom=ut(e.custom,o),yt(e,n.Commands.Custom),a=o,i=!0);break;case n.Commands.Destination:pt(o)&&"code"in o&&pt(o.code)&&(r=await tt(e,o));break;case n.Commands.Globals:pt(o)&&(e.globals=ut(e.globals,o),yt(e,n.Commands.Globals),a=o,i=!0);break;case n.Commands.Hook:if(pt(o)&&ft(o.name)&<(o.fn)){const{name:t,fn:n}=o;e.hooks[t]=n,a=o,i=!0}break;case n.Commands.On:if(pt(o)&&ft(o.type)){const{type:t,rules:n}=o;await Be(e,t,n)}break;case n.Commands.Ready:i=!0;break;case n.Commands.Run:r=await Ct(e,o),i=!0;break;case n.Commands.Session:i=!0;break;case n.Commands.Shutdown:e.hasShutdown||(e.hasShutdown=!0,await mt(e));break;case n.Commands.User:pt(o)&&(ut(e.user,o,{shallow:!1}),yt(e,n.Commands.User),a=o,i=!0)}i&&(await Ue(e,t,void 0,a),r=await nt(e));return r||rt({ok:!0})}()}finally{c()}}function vt(e,t){return{timing:Math.round((Date.now()-e.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.2.0"},...t}}function bt(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${n} ${o}`,data:a={},context:i={},globals:c=e.globals,custom:u={},user:d=e.user,nested:l=[],consent:f=e.consent,id:p=dt(),trigger:g="",entity:m=n,action:h=o,timing:y=0,source:w={type:"collector",schema:"4"}}=t;return{name:r,data:a,context:i,globals:c,custom:u,user:d,nested:l,consent:f,id:p,trigger:g,entity:m,action:h,timestamp:s,timing:y,source:w}}function kt(e,t){return bt(e,vt(e,t))}async function Ct(e,t){e.allowed=!0,e.timing=Date.now(),t&&(t.consent&&(e.consent=ut(e.consent,t.consent),yt(e,n.Commands.Consent)),t.user&&(e.user=ut(e.user,t.user),yt(e,n.Commands.User)),t.globals&&(e.globals=ut(e.config.globalsStatic||{},t.globals),yt(e,n.Commands.Globals)),t.custom&&(e.custom=ut(e.custom,t.custom),yt(e,n.Commands.Custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++,await Ie(e),await Ke(e);return await nt(e)}import{createIngest as It,emitStep as qt,FatalError as St,getGrantedConsent as xt,processEventMapping as Ot,tryCatchAsync as jt,useHooks as Dt}from"@walkeros/core";function At(e,t){const n=Dt(async(n,o={})=>await jt(async()=>{const s=Date.now(),{id:r,ingest:a,respond:i,mapping:c,preChain:u,include:d,exclude:l}=o;let f=i,p=n;const g=d||l?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,d,l):void 0,m=a??It(r||"unknown");if(c){const t=await Ot(p,c,e);if(t.ignore)return rt({ok:!0});if(c.consent){if(!xt(c.consent,e.consent,t.event.consent))return rt({ok:!0})}p=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await he(e,e.transformers,u,p,m,f,r?`source.${r}.next`:void 0);if(null===n.event)return rt({ok:!0});if(n.stopped)return n.respond&&(f=n.respond),rt({ok:!0});if(n.respond&&(f=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=bt(e,o);return nt(e,s,{id:r,ingest:m,respond:f},g)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??rt({ok:!0})}p=n.event}const h=kt(e,p),y=await nt(e,h,{id:r,ingest:m,respond:f},g);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return y},t=>{if(t instanceof St)throw t;return e.status.failed++,e.logger.error("push failed",{event:n,ingest:o.ingest,error:t}),rt({ok:!1})})(),"Push",e.hooks,e.logger);return async(t,o)=>{const s="string"==typeof t.id?t.id:"",r=Date.now();qt(e,D(e,{stepId:"collector.push",stepType:"collector",phase:"in",eventId:s,now:r}));try{const a=await n(t,o),i=Date.now(),c=D(e,{stepId:"collector.push",stepType:"collector",phase:"out",eventId:s,now:i});return c.durationMs=i-r,c.outEvent=a,qt(e,c),a}catch(t){const n=Date.now(),o=D(e,{stepId:"collector.push",stepType:"collector",phase:"error",eventId:s,now:n});throw o.durationMs=n-r,o.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},qt(e,o),t}}}import{FatalError as $t,useHooks as Et,tryCatchAsync as Mt}from"@walkeros/core";import{emitStep as Tt,useHooks as _t}from"@walkeros/core";function Pt(e={}){const t=e.maxEntries??1e4,n=e.lowWaterMark??.8,o=e.sweepIntervalMs??6e4,s=Math.floor(t*n),r=new Map,a={hits:0,misses:0,populates:0,writes:0,deletes:0,evictions_entries:0,evictions_ttl:0};let i;o>0&&(i=setInterval(function(){const e=Date.now();let t=0;for(const[n,o]of r)void 0!==o.expires&&o.expires<=e&&(r.delete(n),t++);a.evictions_ttl+=t},o),i&&"function"==typeof i.unref&&i.unref());return{type:"memory",config:{},get(e){const t=r.get(e);if(t)return void 0!==t.expires&&t.expires<=Date.now()?(r.delete(e),a.evictions_ttl++,void a.misses++):(r.delete(e),r.set(e,t),a.hits++,t.value);a.misses++},set(e,n,o){const i=!r.has(e);i||r.delete(e),r.set(e,{value:n,expires:void 0!==o?Date.now()+o:void 0}),a.writes++,i&&a.populates++,r.size>t&&function(){if(r.size<=t)return;const e=r.size-s;let n=0;for(const t of r.keys()){if(n>=e)break;r.delete(t),n++}a.evictions_entries+=n}()},delete(e){r.delete(e)&&a.deletes++},get counters(){return{...a}},destroy(){void 0!==i&&(clearInterval(i),i=void 0),r.clear()}}}import{compileMatcher as zt,emitStep as Bt,readCacheEnvelope as Ht,wrapCacheEnvelope as Rt}from"@walkeros/core";function Ft(e,t){const{cacheConfig:n,cacheStore:o,namespace:s,logger:r,storeId:a,collector:i}=t,c=(e,t)=>{if(!i)return;const n=D(i,{stepId:`store.${a}`,stepType:"store",phase:"in",eventId:"",now:Date.now()});n.meta={op:"cache",cached:"hit"===t,status:t,key:e},Bt(i,n)},u={hits:0,misses:0,populates:0,writes:0,deletes:0,inflight_dedups:0},d=n.rules.map(e=>({match:e.match?zt(e.match):()=>!0,ttl:e.ttl})),l=e=>`${s}:${e}`;function f(e,t){const n=void 0===t?{key:e}:{key:e,value:t};return d.find(e=>e.match(n))}const p=new Map;return{type:e.type,config:e.config,setup:e.setup,get counters(){return{...u}},async get(t){const n=l(t),s=await o.get(n),r=Ht(s);if(void 0!==r){if(!("expired"in r))return u.hits++,c(t,"hit"),r.value;try{await o.delete(n)}catch(e){g("delete",t,e)}}const a=p.get(n);if(a)return u.inflight_dedups++,c(t,"hit"),a;u.misses++,c(t,"miss");const i=(async()=>{try{const s=await e.get(t);if(void 0===s)return;const r=f(t,s);if(r)try{const e=1e3*r.ttl;await o.set(n,Rt(s,e),e),u.populates++}catch(e){g("set",t,e)}return s}finally{p.delete(n)}})();return p.set(n,i),i},async set(t,n,s){u.writes++,await e.set(t,n,s);const r=f(t,n);if(r)try{const e=1e3*r.ttl;await o.set(l(t),Rt(n,e),e)}catch(e){g("set",t,e)}},async delete(t){u.deletes++,await e.delete(t);try{await o.delete(l(t))}catch(e){g("delete",t,e)}}};function g(e,t,n){const o=`store-cache(${a}): cache ${e} failed for "${t}"; backing succeeded, continuing`;r?r.warn(o,{error:n}):console.warn(o,n)}}function Gt(e,t,n){const o=`store.${n}`,s=_t(t.get,"StoreGet",e.hooks,e.logger),r=_t(t.set,"StoreSet",e.hooks,e.logger),a=_t(t.delete,"StoreDelete",e.hooks,e.logger);t.get=async t=>{const n=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});r.meta={op:"get",key:t},Tt(e,r);try{const r=await s(t),a=Date.now(),i=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:a});return i.durationMs=a-n,i.meta={op:"get",key:t},Tt(e,i),r}catch(s){const r=Date.now(),a=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw a.durationMs=r-n,a.meta={op:"get",key:t},a.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},Tt(e,a),s}},t.set=async(t,n,s)=>{const a=Date.now(),i=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:a});i.meta={op:"set",key:t},Tt(e,i);try{await r(t,n,s);const i=Date.now(),c=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:i});c.durationMs=i-a,c.meta={op:"set",key:t},Tt(e,c)}catch(n){const s=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:s});throw r.durationMs=s-a,r.meta={op:"set",key:t},r.error=n instanceof Error?{name:n.name,message:n.message}:{message:String(n)},Tt(e,r),n}},t.delete=async t=>{const n=Date.now(),s=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});s.meta={op:"delete",key:t},Tt(e,s);try{await a(t);const s=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:s});r.durationMs=s-n,r.meta={op:"delete",key:t},Tt(e,r)}catch(s){const r=Date.now(),a=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw a.durationMs=r-n,a.meta={op:"delete",key:t},a.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},Tt(e,a),s}}}async function Kt(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:a={}}=s,i=e.logger.scope("store").scope(o),c={collector:e,logger:i,id:o,config:r,env:a},u=await t(c);n[o]=u}const o=t,s=function(e){const t={};for(const n of Object.keys(e))t[n]="WHITE";const n=[],o=[];function s(r){const a=t[r];if("BLACK"===a)return;if("GRAY"===a){const e=o.indexOf(r),t=o.slice(-1===e?0:e).concat(r).join(" -> ");throw new Error(`Cycle in cache.store chain: ${t}`)}t[r]="GRAY",o.push(r);const i=e[r].cache?.store;if(void 0!==i){if(!(i in e))throw new Error(`Store "${r}" cache.store references "${i}", which is not declared in flow.stores`);s(i)}o.pop(),t[r]="BLACK",n.push(r)}for(const n of Object.keys(e))"WHITE"===t[n]&&s(n);return n}(o);for(const t of s){const s=o[t].cache;if(!s)continue;let r,a;void 0!==s.store?(r=n[s.store],a=s.store):(n.__cache||(n.__cache=Pt()),r=n.__cache,a="__cache");const i=s.namespace??t;e.logger.scope("store-cache").scope(t).info(`store "${t}" caches with namespace "${i}:" via ${a}`),n[t]=Ft(n[t],{storeId:t,cacheConfig:s,cacheStore:r,namespace:i,logger:e.logger.scope("store-cache").scope(t),collector:e})}for(const[t,o]of Object.entries(n))"__cache"!==t&&Gt(e,o,t);return n}async function Ut(e){const t=r({globalsStatic:{},sessionStatic:{},run:!0,queueMax:1e3},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=a(n),s={...t.globalsStatic,...e.globals},i={allowed:!1,config:t,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},observers:new Set,logger:o,on:{},queue:[],round:0,stateVersion:0,cellVersion:{},delivery:new WeakMap,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{},dropped:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},hasShutdown:!1,seenEvents:new Set,push:void 0,command:void 0};i.push=At(i,e=>vt(i,e)),i.command=function(e,t){return Et(async(n,o,s)=>await Mt(async()=>await t(e,n,o,s),t=>{if(t instanceof $t)throw t;return e.status.failed++,e.logger.error("command failed",{command:n,data:o,error:t}),rt({ok:!1})})(),"Command",e.hooks,e.logger)}(i,wt);const c=e.stores||{};return i.stores=await Kt(i,c),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(c,i.stores,e),i.stores.__cache||(i.stores.__cache=Pt()),i.destinations=await it(i,e.destinations||{}),i.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,a=se(s,"Transformer");if(!a.ok){e.logger.warn(`Transformer ${o} invalid (${a.code}): ${a.reason}. Skipping.`);continue}const{config:i}=le(s,"before"),{config:c}=le({...s,config:i},"next"),u=Object.keys(r).length>0?{...c,env:r}:c,{cache:d}=s,l=d?{...u,cache:d}:u,f=s.config?.state??s.state,p=void 0!==f&&void 0===l.state?{...l,state:f}:l,g=e.logger.scope("transformer").scope(o),m={collector:e,logger:g,id:o,ingest:V(o),config:p,env:r},h=t??(e=>{const t=s.mapping;if(t){const n=[];if(void 0!==t.data&&n.push("data"),t.mapping)for(const[e,o]of Object.entries(t.mapping))if("object"==typeof o&&null!==o)for(const[t,s]of Object.entries(o)){if("object"!=typeof s||null===s)continue;const o=s;void 0!==o.data&&n.push(`mapping[${e}][${t}].data`),void 0!==o.silent&&n.push(`mapping[${e}][${t}].silent`)}return n.length>0&&e.collector.logger.warn(`Transformer ${o}: \`${n.join(", ")}\` ignored at transformer position (only event-mutating fields apply).`),{type:"pass",config:e.config,push:async n=>{const o=await re(n,t,e.collector);return!o.ignore&&{event:o.event}}}}return{type:"pass",config:e.config,push:e=>({event:e})}}),y=await h(m);void 0!==s.before&&void 0===y.config?.before&&(y.config={...y.config??{},before:s.before}),void 0!==s.next&&void 0===y.config?.next&&(y.config={...y.config??{},next:s.next}),void 0!==f&&void 0===y.config?.state&&(y.config={...y.config??{},state:f}),n[o]=y}return n}(i,e.transformers||{}),i}async function Wt(e){e=e||{};const t=await Ut(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r)=>{if("string"==typeof e&&e.startsWith("walker ")){const n=e.replace("walker ","");return o.command(n,t)}let a;if("string"==typeof e)a={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(a.data=t);else{if(!e||"object"!=typeof e)return rt({ok:!1});a=e,t&&"object"==typeof t&&!Array.isArray(t)&&(a.data={...a.data||{},...t})}return n&&"object"==typeof n&&(a.context=n),s&&Array.isArray(s)&&(a.nested=s),r&&"object"==typeof r&&(a.custom=r),o.push(a)}});var o;t.sources.elb=n,await Ce(t,e.sources||{});const{consent:s,user:r,globals:a,custom:i}=e;s&&await t.command("consent",s),r&&await t.command("user",r),a&&await t.command("globals",a),i&&await t.command("custom",i),t.config.run&&await t.command("run");let c=n.push;const u=Object.values(t.sources).filter(e=>"elb"!==e.type),d=u.find(e=>e.config.primary);return d?c=d.push:u.length>0&&(c=u[0].push),{collector:t,elb:c}}function Vt(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Vt);const t={};for(const[n,o]of Object.entries(e))t[n]="function"==typeof o?o:Vt(o);return t}function Nt(e){const t=[],{simulation:n,...o}=e,s=Vt(o);for(const e of n){const n=e.startsWith("call:")?e.slice(5):e,o=n.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const a=o[o.length-1];if(null==r||!(a in r))continue;const i=r[a];"function"==typeof i&&(r[a]=function(...e){return t.push({fn:n,args:e,ts:Date.now()}),i.apply(this,e)})}return{wrappedEnv:s,calls:t}}export{e as Code,t as Commands,n as Const,tt as addDestination,He as callDestinationOn,wt as commonHandleCommand,bt as createEvent,At as createPush,rt as createPushResult,ot as destinationInit,st as destinationPush,kt as enrichEvent,_e as enterCascade,de as extractTransformerNextMap,Re as fireCallbacks,ve as flushSourceQueueOn,ce as getCacheStore,it as initDestinations,ke as initSource,Ce as initSources,$e as isRequireSatisfied,be as isSourceStarted,De as isStateDelivery,Ae as isStatePresent,ct as mergeEnvironments,Be as on,Ue as onApply,vt as prepareEvent,s as processConsent,nt as pushToDestinations,Ke as redeliverStateAtRun,at as registerDestination,Ct as runCollector,he as runTransformerChain,Me as setMark,Te as shouldDeliver,Wt as startFlow,pe as transformerInit,ge as transformerPush,fe as walkChain,Nt as wrapEnv};//# sourceMappingURL=index.mjs.map
|
|
1
|
+
var e={},t={Action:"action",Actions:"actions",Config:"config",Consent:"consent",Context:"context",Custom:"custom",Destination:"destination",Elb:"elb",Globals:"globals",Hook:"hook",Init:"init",Link:"link",On:"on",Prefix:"data-elb",Ready:"ready",Run:"run",Scoped:"_",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"},n={Commands:t,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};import{assign as o}from"@walkeros/core";function s(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=o(e.consent,n),{update:n}}import{assign as r,createLogger as a}from"@walkeros/core";import{assign as i,buildCacheContext as c,clone as u,compileCache as d,checkCache as l,storeCache as f,createIngest as p,debounce as g,emitStep as m,getId as h,getGrantedConsent as y,getNextSteps as w,isDefined as v,isFunction as b,isObject as k,processEventMapping as C,stepId as I,tryCatchAsync as q,useHooks as S,compileState as x,applyState as O}from"@walkeros/core";import{emitStep as j}from"@walkeros/core";function D(e,t){const n=e.status.startedAt;return{flowId:"default",stepId:t.stepId,stepType:t.stepType,phase:t.phase,eventId:t.eventId,timestamp:new Date(t.now).toISOString(),elapsedMs:t.now-n}}import{isArray as A,FatalError as $}from"@walkeros/core";import{tryCatch as E,tryCatchAsync as M}from"@walkeros/core";import{createIngest as T,FatalError as _,getMappingValue as P,tryCatchAsync as z,getNextSteps as B,compileCache as H,checkCache as R,storeCache as F,applyUpdate as G,buildCacheContext as K,compileState as U,applyState as W}from"@walkeros/core";import{createIngest as V,emitStep as N,FatalError as L,isObject as Y,stepId as J,tryCatchAsync as Q,useHooks as X,getNextSteps as Z,compileCache as ee,checkCache as te,storeCache as ne,buildCacheContext as oe,validateStepEntry as se,processEventMapping as re,compileState as ae,applyState as ie}from"@walkeros/core";function ce(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function ue(e,t){return e?t.stores[e]:t.stores.__cache}function de(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)?t[n]={next:e}:t[n]={}}return t}function le(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function fe(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function pe(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:V(n),config:t.config,env:ye(t.config.env)};s.debug("init");const a=await X(t.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===a)return!1;t.config={...a||t.config,env:a?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function ge(e,t,n,o,s,r){const a=t.type||"unknown",i=e.logger.scope(`transformer:${a}`),c={collector:e,logger:i,id:n,ingest:s,config:t.config,env:{...ye(t.config.env),...r?{respond:r}:{}}};i.debug("push",{event:o.name});const u="string"==typeof o.id?o.id:"",d=Date.now(),l=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"in",eventId:u,now:d});N(e,l);try{const s=await X(t.push,"TransformerPush",e.hooks,e.logger)(o,c),r=Date.now(),a=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"out",eventId:u,now:r});return a.durationMs=r-d,a.outEvent=s,N(e,a),i.debug("push done"),s}catch(t){const o=Date.now(),s=D(e,{stepId:J("transformer",n),stepType:"transformer",phase:"error",eventId:u,now:o});throw s.durationMs=o-d,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},N(e,s),t}}function me(e,t){return e?{...e,_meta:{...e._meta,path:[...e._meta.path]}}:V(t)}async function he(e,t,n,o,s,r,a){s||(s=V(n[0]??"chain")),a&&s._meta&&(s._meta.chainPath=a);let i=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};s&&s._meta&&(s._meta.hops++,s._meta.path.push(o));if(!await Q(pe,t=>{if(t instanceof L)throw t;return e.status.failed++,e.logger.scope(`transformer:${r.type||"unknown"}`).error("transformer init failed",{transformer:o,error:t}),!1})(e,r,o))return{event:null,respond:c};if(a&&void 0!==r.config?.chainMocks?.[a]){const t=r.config.chainMocks[a];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:a}),i=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),i=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,d=u?ee(u):void 0,l=d?ce(d,e):void 0,f=r.config?.state?ae(r.config.state):void 0,p=f?.filter(e=>"get"===e.mode),g=f?.filter(e=>"set"===e.mode),m=async t=>g&&0!==g.length?ie(g,t=>ue(t,e),t,e):t;let h;if(d&&l){const e=oe(s,i),t=await te(d,l,e);if("HIT"===t?.status&&t.value){if(i=t.value,d.stop)return{event:i,respond:c,stopped:!0};continue}"MISS"===t?.status&&(h={key:t.key,ttl:t.rule.ttl})}const y=r.config.before;if(y){const n=Z(y,oe(s,i));if(1===n.length){const o=fe(n[0],de(t));if(o.length>0){const n=await he(e,t,o,i,s,c,a);if(null===n.event)return{event:null,respond:n.respond??c};if(n.stopped)return{event:Array.isArray(n.event)?n.event[0]:n.event,respond:n.respond??c,stopped:!0};n.respond&&(c=n.respond),i=Array.isArray(n.event)?n.event[0]:n.event}}else n.length>1&&await Promise.all(n.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),i,me(s,n),void 0,a)))}p&&p.length>0&&(i=await ie(p,t=>ue(t,e),i,e));const w=await Q(ge,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,i,s,c);if(!1===w)return{event:null,respond:c};if(Array.isArray(w)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(w.map(async n=>{const o=await m(n.event||i),u=me(s,"unknown");if(n.next){const s=Z(n.next,oe(u,o));if(0===s.length)return{event:o,respond:c};if(1===s.length){const n=fe(s[0],de(t));return n.length>0?he(e,t,n,o,u,c,a):{event:o,respond:c}}return(await Promise.all(s.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),o,me(u,n),void 0,a)))).map(e=>({event:e.event,respond:void 0}))}return r.length>0?he(e,t,r,o,u,c,a):{event:o,respond:c}}));let d=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(d=t.respond),null===t.event)continue;Array.isArray(t.event)?l.push(...t.event):l.push(t.event)}else l.push(e);return 0===l.length?{event:null,respond:d}:1===l.length?{event:l[0],respond:d}:{event:l,respond:d}}if(w&&"object"==typeof w){const{event:n,respond:o,next:r}=w;if(o&&(c=o),void 0!==r){const o=await m(n||i),u=Z(r,oe(s,o));if(0===u.length){i=o;continue}if(1===u.length){const n=fe(u[0],de(t));return n.length>0?he(e,t,n,o,s,c,a):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}return await Promise.all(u.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),o,me(s,n),void 0,a))),{event:null,respond:void 0}}n&&(i=n)}g&&g.length>0&&(i=await ie(g,t=>ue(t,e),i,e)),h&&l&&ne(l,h.key,i,h.ttl);const v=r.config.next,b="string"==typeof v||Array.isArray(v)&&v.every(e=>"string"==typeof e),k=void 0!==v&&!b;if((!w||"object"==typeof w&&!w.next)&&k){const n=Z(r.config.next,oe(s,i));if(1===n.length){const o=fe(n[0],de(t));return o.length>0?he(e,t,o,i,s,c,a):{event:i,respond:c}}return n.length>1?(await Promise.all(n.map(n=>Q(he,t=>(e.logger.scope("transformer:many").error(`many branch ${n} failed`,{error:t}),{event:null,respond:void 0}))(e,t,fe(n,de(t)),i,me(s,n),void 0,a))),{event:null,respond:void 0}):{event:i,respond:c}}}return{event:i,respond:c}}function ye(e){return e&&Y(e)?e:{}}function we(e){return"string"==typeof e||!(!Array.isArray(e)||!e.every(e=>"string"==typeof e))}async function ve(e,t,n){if(!t.on||!t.queueOn?.length)return;const o=t.queueOn;t.queueOn=[];const s=n||t.config?.id||"unknown";for(const{type:n,data:r}of o)De(n)&&!Te(e,t,n)||(await z(t.on,t=>{if(t instanceof _)throw t;e.status.failed++,e.logger.scope("source").error("source on flush failed",{sourceId:s,type:n,error:t})})(n,r),De(n)&&Me(e,t,n))}function be(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ke(e,t,n){const{code:o,config:s={},env:r={},primary:a,next:i,before:c,cache:u}=n,d=s.state??n.state,l=d?U(d):void 0,f=u,p=f?H({...f,stop:f.stop??!0}):void 0,g=we(i)?fe(i,de(e.transformers)):void 0,m=we(c)?fe(c,de(e.transformers)):void 0,h=r.push,y=h??e.push,w=Boolean(h),v=async(n,o,r)=>{let a;const u=m??(void 0!==c?(()=>{const t=B(c,K(r.ingest));if(0===t.length)return[];return fe(1===t.length?t[0]:t,de(e.transformers))})():[]);let d=[n];if(u.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await he(e,e.transformers,u,n,r.ingest,r.respond,`source.${t}.before`);if(null===o.event)return{ok:!0};if(o.stopped)return o.respond&&(r.respond=o.respond),{ok:!0};o.respond&&(r.respond=o.respond),d=Array.isArray(o.event)?o.event:[o.event]}if(p){const t=ce(p,e);if(t){const n=K(r.ingest),o=await R(p,t,n);if(o){if("HIT"===o.status&&void 0!==o.value&&p.stop){let t=o.value;return o.rule.update&&(t=await G(t,o.rule.update,{...n,cache:{status:"HIT"}},e)),r.respond?.(t),{ok:!0}}if("MISS"===o.status&&p.stop&&r.respond){const s=r.respond,i=o.rule.update,c={...n,cache:{status:"MISS"}},u=o.key,d=o.rule.ttl,l=n=>{F(t,u,n,d),i?a=(async()=>{const t=await G(n,i,c,e);s(t)})():s(n)};r.respond=l}"MISS"!==o.status||p.stop||F(t,o.key,!0,o.rule.ttl)}}}const f=g?{kind:"single",preChain:g}:void 0!==i?(()=>{const t=B(i,K(r.ingest));return 0===t.length?{kind:"single",preChain:[]}:1===t.length?{kind:"single",preChain:fe(t[0],de(e.transformers))}:{kind:"many",branches:t.map(t=>fe(t,de(e.transformers)))}})():{kind:"single",preChain:[]};!w&&l&&l.length>0&&(d=await Promise.all(d.map(t=>W(l,t=>ue(t,e),t,e))));let h={ok:!0};for(const n of d)"many"===f.kind?(await Promise.all(f.branches.map((a,i)=>z(async()=>w?y(n):y(n,{...o,id:t,ingest:me(r.ingest,`${t}.${i}`),respond:void 0,mapping:s,preChain:a}),t=>(e.logger.scope("source:many").error(`many branch ${i} failed`,{error:t}),{ok:!0}))())),h={ok:!0}):h=w?await y(n):await y(n,{...o,id:t,ingest:r.ingest,respond:r.respond,mapping:s,preChain:f.preChain});return a&&await a,h},b=async n=>{const o=T(t);if(!s.ingest||void 0===n)return o;const r=await P(n,s.ingest,{collector:e});return{...o,...r,_meta:o._meta}},k=e.logger.scope("source").scope(t),C={command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:k,...r,push:async(e,n={})=>{const o={ingest:T(t),respond:void 0};return v(e,n,o)}},I={collector:e,logger:k,id:t,config:s,env:C,withScope:async(e,t,n)=>{const o={ingest:await b(e),respond:t};return n({...C,push:(e,t={})=>v(e,t,o),ingest:o.ingest,respond:o.respond})}},q=await z(o,n=>{if(n instanceof _)throw n;e.status.failed++,e.logger.scope("source").error("source factory failed",{sourceId:t,error:n})})(I);if(!q)return;const S=q.type||"unknown",x=e.logger.scope(S).scope(t);return C.logger=x,a&&(q.config={...q.config,primary:a}),q}async function Ce(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const t=await ke(e,o,s);if(!t)continue;const r=s.config?.require;t.config={...t.config,init:!1,...r?{require:[...r]}:{}},n[o]=t}Object.assign(e.sources,n);for(const t of Object.keys(n)){const n=e.sources[t];let o=!1;n.init&&await z(n.init.bind(n),n=>{if(n instanceof _)throw n;o=!0,e.status.failed++,e.logger.scope("source").error("source init failed",{sourceId:t,error:n})})(),o||(n.config.init=!0,be(n)&&await ve(e,n,t))}return await Ie(e),n}async function Ie(e){for(const[t,n]of Object.entries(e.sources)){if(be(n))continue;const o=n.config.require;if(!o?.length)continue;const s=o.filter(t=>!$e(e,t));s.length!==o.length&&(n.config.require=s,be(n)&&await ve(e,n,t))}for(const[t,n]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const o=n.config?.require;if(!o)continue;const s=o.filter(t=>!$e(e,t));if(n.config&&(n.config.require=s),s.length>0)continue;delete e.pending.destinations[t];const r=at(n);!1!==r.config.queue&&(r.queuePush=[...e.queue]),e.destinations[t]=r}}function qe(e){if("object"!=typeof e||null===e)return!1;if(!("logger"in e))return!1;const t=e.logger;return"object"==typeof t&&null!==t&&("scope"in t&&"function"==typeof t.scope)}var Se=!1;function xe(){Se||(Se=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("walkerOS: ignored an on-dispatch call with a non-collector argument"))}function Oe(e,t,n,o){if(n instanceof $)throw n;e.logger.scope("on").error("on callback failed",{kind:t,...o,error:n})}var je=[n.Commands.Consent,n.Commands.User,n.Commands.Globals,n.Commands.Custom];function De(e){return je.includes(e)}function Ae(e,t){switch(t){case n.Commands.Consent:return Object.keys(e.consent).length>0;case n.Commands.User:return Object.keys(e.user).length>0;case n.Commands.Globals:return Object.keys(e.globals).length>0;case n.Commands.Custom:return Object.keys(e.custom).length>0;default:return!1}}function $e(e,t){switch(t){case n.Commands.Consent:case n.Commands.User:case n.Commands.Globals:case n.Commands.Custom:return Ae(e,t);case n.Commands.Run:case n.Commands.Ready:return!0===e.allowed;default:return e.seenEvents.has(String(t))}}function Ee(e,t){return e.cellVersion[String(t)]??0}function Me(e,t,n){let o=e.delivery.get(t);o||(o={},e.delivery.set(t,o)),o[String(n)]=Ee(e,n)}function Te(e,t,n){return e.allowed&&Ee(e,n)>function(e,t,n){const o=e.delivery.get(t),s=o?.[String(n)];return void 0===s?-1:s}(e,t,n)}function _e(e){return e.cascade?()=>{}:(e.cascade={counts:new WeakMap},()=>{e.cascade=void 0})}function Pe(e,t,n){const o=e.cascade;if(!o)return!0;let s=o.counts.get(t);s||(s={},o.counts.set(t,s));const r=String(n),a=(s[r]||0)+1;return s[r]=a,a<=8||(9===a&&e.logger.error("state delivery did not converge",{type:r}),!1)}function ze(e,t){return{collector:e,logger:e.logger.scope("on").scope(String(t))}}async function Be(e,t,n){if(!qe(e))return void xe();const o=e.on,s=o[t]||[],r=A(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,Re(e,t,r)}function He(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",a=e.logger.scope(r).scope("on").scope(o),i={collector:e,logger:a,id:n,config:t.config,data:s,env:ct(t.env,t.config.env)};E(t.on,t=>Oe(e,"destination",t,{destId:n,type:o}))(o,i)}function Re(e,t,o,s){if(!qe(e))return void xe();const r=Fe(e,t,s);if(o.length)switch(t){case n.Commands.Consent:!function(e,t,o){const s=o||e.consent,r=ze(e,n.Commands.Consent);t.forEach(t=>{Te(e,t,n.Commands.Consent)&&Pe(e,t,n.Commands.Consent)&&(Object.keys(s).filter(e=>e in t).forEach(n=>{E(t[n],t=>Oe(e,"consent",t,{key:n}))(s,r)}),Me(e,t,n.Commands.Consent))})}(e,o,s);break;case n.Commands.Ready:!function(e,t){if(!e.allowed)return;const o=ze(e,n.Commands.Ready);t.forEach(t=>{E(t,t=>Oe(e,"ready",t))(void 0,o)})}(e,o);break;case n.Commands.Run:!function(e,t){if(!e.allowed)return;const o=ze(e,n.Commands.Run);t.forEach(t=>{E(t,t=>Oe(e,"run",t))(void 0,o)})}(e,o);break;case n.Commands.Session:!function(e,t){if(!e.session)return;const o=ze(e,n.Commands.Session);t.forEach(t=>{E(t,t=>Oe(e,"session",t))(e.session,o)})}(e,o);break;default:{const n=ze(e,t),s=De(t);o.forEach(o=>{"function"==typeof o&&(s&&!Te(e,o,t)||s&&!Pe(e,o,t)||(E(o,n=>Oe(e,"generic",n,{type:t}))(r,n),s&&Me(e,o,t)))});break}}}function Fe(e,t,o){switch(t){case n.Commands.Consent:return o||e.consent;case n.Commands.Session:return e.session;case n.Commands.User:return o||e.user;case n.Commands.Custom:return o||e.custom;case n.Commands.Globals:return o||e.globals;case n.Commands.Config:return o||e.config;default:return}}async function Ge(e,t,n,o,s){if(!t.on)return!1;if(De(o)&&!Te(e,t,o))return!1;if(De(o)&&!Pe(e,t,o))return!1;const r=await M(t.on,t=>Oe(e,"source",t,{sourceId:n,type:o}))(o,s);return De(o)&&Me(e,t,o),!1===r}async function Ke(e){if(qe(e))for(const t of je){if(!Ae(e,t))continue;const n=Fe(e,t);Re(e,t,e.on[t]||[]);for(const[o,s]of Object.entries(e.sources))be(s)&&await Ge(e,s,o,t,n)}else xe()}async function Ue(e,t,n,o){if(!qe(e))return xe(),!0;e.seenEvents.add(String(t));let s=n||[];n||(s=e.on[t]||[]);const r=Fe(e,t,o);let a=!1;for(const[n,o]of Object.entries(e.sources)){if(o.config.require?.length){const e=o.config.require.indexOf(t);-1!==e&&o.config.require.splice(e,1)}if(o.on)if(be(o)){await Ge(e,o,n,t,r)&&(a=!0)}else o.queueOn=o.queueOn||[],o.queueOn.push({type:t,data:r})}Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:r});He(e,o,n,t,r)}});for(const[t,n]of Object.entries(e.sources))be(n)&&n.queueOn?.length&&await ve(e,n,t);const i=Object.values(e.sources).some(e=>!be(e)&&e.config.require?.length);return(Object.keys(e.pending.destinations).length>0||i)&&await Ie(e),Re(e,t,s,o),!a}function We(e,t,n,o){if(!Number.isFinite(n.max)||n.max<=0)throw new Error(`pushBounded: max must be > 0 (got ${n.max})`);if("dropNewest"===(n.onOverflow??"dropOldest"))return e.length>=n.max?(o&&o([t]),{appended:!1,dropped:1}):(e.push(t),{appended:!0,dropped:0});const s=[];for(;e.length>=n.max;)s.push(e.shift());return e.push(t),s.length>0&&o&&o(s),{appended:!0,dropped:s.length}}var Ve=new WeakMap;function Ne(e,t,n,o){Ve.get(e)||(Ve.set(e,!0),t.warn(n,o))}function Le(e){Ve.delete(e)}var Ye=Object.freeze({batched:!0});function Je(e){return e===Ye}function Qe(e){return void 0===e?{}:"number"==typeof e?{wait:e}:{wait:e.wait,size:e.size,age:e.age}}function Xe(e,t){return e.status.destinations[t]||(e.status.destinations[t]={count:0,failed:0,duration:0,queuePushSize:0,dlqSize:0}),e.status.destinations[t]}function Ze(e,t,n,o){e.dropped[t]||(e.dropped[t]={});const s=e.dropped[t];return s[n]=(s[n]??0)+o,s[n]}function et(e,t,n){if(!e)return[];if(Array.isArray(e)&&e.every(e=>"string"==typeof e))return fe(e,t);if("string"==typeof e)return fe(e,t);const o=w(e,c(n));return 0===o.length?[]:1===o.length?fe(o[0],t):fe(o,t)}async function tt(e,t){const{code:n,config:o={},env:s={},before:r,next:a,cache:i,state:c}=t;if(!b(n.push))return rt({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=o||{init:!1};let d=r?{...u,before:r}:{...u};a&&(d={...d,next:a}),i&&(d={...d,cache:i}),void 0!==c&&void 0===d.state&&(d={...d,state:c});let l=d.id;if(!l)do{l=h(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[l]||e.pending.destinations[l]);if(d.require?.length){e.pending.destinations[l]=t,await Ie(e);const n=e.destinations[l];return n?nt(e,void 0,{},{[l]:n}):rt({ok:!0})}const f={...n,config:d,env:ct(n.env,s)};return e.destinations[l]=f,!1!==f.config.queue&&(f.queuePush=[...e.queue]),nt(e,void 0,{},{[l]:f})}async function nt(e,t,n={},o){const{allowed:s,consent:r,globals:a,user:g}=e;if(!s)return rt({ok:!1});if(t){const n=e.config.queueMax;if(void 0===n)throw new Error("Collector.Config.queueMax is undefined; defaults must be seeded by collector()");const o=We(e.queue,t,{max:n});if(o.dropped>0){const t=Ze(e.status,I("collector"),"queue",o.dropped);Ne(e.queue,e.logger,"collector.queue overflow; oldest events dropped",{buffer:"queue",cap:n,droppedCount:t})}else e.queue.length<n&&Le(e.queue);e.status.in++}o||(o=e.destinations);const h=e.transformers?de(e.transformers):{},w=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let w=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],t&&w.push(u(t));const v=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:p("unknown");if(!w.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!w.length&&s.queueOn?.length){let t=!1;try{t=await ot(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}return{id:o,destination:s,skipped:!t}}const b=[],k=w.filter(t=>{const n=y(s.config.consent,r,t.consent);if(n)return t.consent=n,b.push(t),!1;const a=D(e,{stepId:I("destination",o),stepType:"destination",phase:"skip",eventId:"string"==typeof t.id?t.id:"",now:Date.now()});return a.skipReason="consent",r&&(a.consent={...r}),s.config.consent&&(a.meta={required:{...s.config.consent}}),m(e,a),!0});if(k.length>0){const t=s.queuePush,n=s.config.id||o,r={max:s.config.queueMax??1e3};let a=0;for(const e of k){a+=We(t,e,r).dropped}if(a>0){Xe(e,n);const o=Ze(e.status,I("destination",n),"queue",a);Ne(t,e.logger.scope(s.type||"unknown"),"destination.queuePush overflow; oldest events dropped",{buffer:"queuePush",destination:n,cap:r.max,droppedCount:o})}else t.length<r.max&&Le(t)}if(!b.length)return{id:o,destination:s,queue:w};let C,S,j=!1;try{j=await ot(e,s,o)}catch(t){e.status.failed++;const n=s.type||"unknown";e.logger.scope(n).error("destination init failed",{error:t instanceof Error?t.message:String(t)})}if(!j)return{id:o,destination:s,queue:w};s.dlq||(s.dlq=[]);const A=et(s.config.before,h,v),$=s.config.next,E=s.config?.cache,M=E?d(E):void 0,T=M?ce(M,e):void 0,_=s.config?.state?x(s.config.state):void 0,P=_?.filter(e=>"get"===e.mode),z=_?.filter(e=>"set"===e.mode);let B=0,H=0;return await Promise.all(b.map(async t=>{let r;if(t.globals=i(a,t.globals),t.user=i(g,t.user),M?.stop&&T){const e=c(v,t),n=await l(M,T,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let u=t,d=n.respond;if(A.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await he(e,e.transformers,A,t,v,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(d=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(M&&!M.stop&&T){const e=c(v,u),n=await l(M,T,e);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}P&&P.length>0&&u&&(u=await O(P,t=>ue(t,e),u,e));const p=Date.now();let m=!1;const y=await q(st,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:u.name}),C=t,m=!0;const r=s.dlq,a=s.config.id||o,i={max:s.config.dlqMax??100},c=We(r,[u,t],i);if(c.dropped>0){Xe(e,a);const t=Ze(e.status,I("destination",a),"dlq",c.dropped);Ne(r,e.logger.scope(s.type||"unknown"),"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:a,cap:i.max,droppedCount:t})}else r.length<i.max&&Le(r)})(e,s,o,u,v,d);if(B+=Date.now()-p,r&&T&&void 0===s.config.mock&&f(T,r.key,y??!0,r.ttl),!m&&!Je(y)&&z&&z.length>0&&u&&(u=await O(z,t=>ue(t,e),u,e)),void 0===y||Je(y)||(S=y),Je(y)&&H++,!m&&$){void 0!==y&&(v._response=y);const t=et($,h,v);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await he(e,e.transformers,t,u,v,d,`destination.${o}.next`);n.respond&&(d=n.respond)}}return t})),{id:o,destination:s,error:C,response:S,totalDuration:B,batchedCount:H,allowedCount:b.length}})),v={},b={},k={};for(const t of w){if(t.skipped)continue;const n=t.destination,o={type:n.type||"unknown",data:t.response};Xe(e,t.id);const s=e.status.destinations[t.id],r=Date.now();if(s.queuePushSize=n.queuePush?.length??0,s.dlqSize=n.dlq?.length??0,t.error)o.error=t.error,k[t.id]=o,s.failed++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.failed++;else if(t.queue&&t.queue.length)b[t.id]=o;else{const n=t.batchedCount??0,a=t.allowedCount??0;(Math.max(0,a-n)>0||0===a)&&(v[t.id]=o,s.count++,s.lastAt=r,s.duration+=t.totalDuration||0,e.status.out++)}}return rt({event:t,...Object.keys(v).length&&{done:v},...Object.keys(b).length&&{queued:b},...Object.keys(k).length&&{failed:k}})}async function ot(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:ct(t.env,t.config.env)};s.debug("init");const a=Date.now();let i;m(e,D(e,{stepId:I("destination",n),stepType:"destination",phase:"init",eventId:"",now:a}));try{i=await S(t.init,"DestinationInit",e.hooks,e.logger)(r)}catch(t){const o=Date.now(),s=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});throw s.durationMs=o-a,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},m(e,s),t}if(!1===i)return i;if(t.config={...i||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)He(e,t,n,s,r)}s.debug("init done")}return!0}async function st(e,t,n,o,s,r){const{config:a}=t,i=await C(o,a,e);if(i.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),d={collector:e,logger:u,id:n,config:a,data:i.data,rule:i.mapping,ingest:s,env:{...ct(t.env,a.env),...r?{respond:r}:{}}};if(void 0!==a.mock)return u.debug("mock",{event:i.event.name}),a.mock;const l=i.mapping,f=void 0!==l?.batch,p=f?i.mappingKey||"* *":" batch-all";if((f||void 0!==a.batch)&&t.pushBatch&&void 0===a.mock){if(t.batches=t.batches||{},!t.batches[p]){const o={key:p,entries:[],events:[],data:[]},s=Qe(l?.batch),r=Qe(a.batch),i=s.wait??r.wait??3e4,c=s.size??r.size??1e3,d=s.age??r.age??3e4,h=ct(t.env,a.env),y=g(async()=>{const o=t.batches[p],s=o.batched;if(0===s.entries.length)return;const r={key:s.key,entries:s.entries,events:s.events,data:s.data};s.entries=[],s.events=[],s.data=[];const i=r.entries[0],c={collector:e,logger:u,id:n,config:a,data:void 0,rule:o.isDefault?void 0:i.rule,ingest:i.ingest,env:{...h,...i.respond?{respond:i.respond}:{}}};u.debug("push batch",{events:r.entries.length});const d=t.config.id||n,l=Xe(e,d),f=Date.now(),g=D(e,{stepId:I("destination",n),stepType:"destination",phase:"flush",eventId:"",now:f});g.batch={size:r.entries.length,index:0},m(e,g);const y=n=>{const o=t.dlq=t.dlq||[],s={max:t.config.dlqMax??100};let r=0;for(const e of n){r+=We(o,e,s).dropped}if(r>0){const t=Ze(e.status,I("destination",d),"dlq",r);Ne(o,u,"destination.dlq overflow; oldest entries dropped",{buffer:"dlq",destination:d,cap:s.max,droppedCount:t})}else o.length<s.max&&Le(o);l.failed+=n.length,l.dlqSize=o.length,e.status.failed+=n.length};let w=r.entries.length;const v=await q(S(t.pushBatch,"DestinationPushBatch",e.hooks,e.logger),t=>{w=0;const o=Date.now(),s=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:"",now:o});s.durationMs=o-f,s.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},s.batch={size:r.entries.length,index:0},m(e,s),y(r.entries.map(e=>[e.event,t])),u.error("Push batch failed",{error:t instanceof Error?t.message:String(t),entries:r.entries.length})})(r,c);if(k(b=v)&&Array.isArray(b.failed)&&v.failed.length>0){const e=[],t=new Set;for(const n of v.failed){const o=r.entries[n.index];o&&!t.has(n.index)&&(t.add(n.index),e.push([o.event,n.error??new Error(`Push batch entry ${n.index} failed (no per-row error provided)`)]))}e.length>0&&(y(e),w=Math.max(0,r.entries.length-e.length),u.error("Push batch partial failure",{failed:e.length,delivered:w,entries:r.entries.length}))}var b;u.debug("push batch done"),l.inFlightBatch=Math.max(0,(l.inFlightBatch??0)-r.entries.length),w>0&&(l.count+=w,l.lastAt=Date.now(),e.status.out+=w)},{wait:i,size:c,age:d});t.batches[p]={batched:o,isDefault:!f,batchFn:()=>{y()},flush:async()=>{await y.flush()}}}const o=t.batches[p];o.batched.entries.push({event:i.event,ingest:s,respond:r,rule:l,data:i.data}),o.batched.events.push(i.event),v(i.data)&&o.batched.data.push(i.data);const c=t.config.id||n,d=Xe(e,c);return d.inFlightBatch=(d.inFlightBatch??0)+1,o.batchFn(),Ye}{u.debug("push",{event:i.event.name});const o="string"==typeof i.event.id?i.event.id:"",s=Date.now(),r=D(e,{stepId:I("destination",n),stepType:"destination",phase:"in",eventId:o,now:s});i.mappingKey&&(r.mappingKey=i.mappingKey),i.event.consent&&(r.consent={...i.event.consent}),m(e,r);try{const r=await S(t.push,"DestinationPush",e.hooks,e.logger)(i.event,d),a=Date.now(),c=D(e,{stepId:I("destination",n),stepType:"destination",phase:"out",eventId:o,now:a});return c.durationMs=a-s,c.outEvent=r,i.mappingKey&&(c.mappingKey=i.mappingKey),m(e,c),u.debug("push done"),r}catch(t){const r=Date.now(),a=D(e,{stepId:I("destination",n),stepType:"destination",phase:"error",eventId:o,now:r});throw a.durationMs=r-s,a.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},i.mappingKey&&(a.mappingKey=i.mappingKey),m(e,a),t}}}function rt(e){return{ok:!e?.failed,...e}}function at(e){const{code:t,config:n={},env:o={},cache:s,state:r}=e,{config:a}=le(e,"before"),{config:i}=le({...e,config:a},"next"),c={...t.config,...n,...i};s&&(c.cache=s),void 0!==r&&void 0===c.state&&(c.state=r);const u=ct(t.env,o);return{...t,config:c,env:u}}async function it(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=at(s);return n}function ct(e,t){return e||t?t?e&&k(e)&&k(t)?{...e,...t}:t:e:{}}import{assign as ut,getSpanId as dt,isFunction as lt,isString as ft}from"@walkeros/core";import{isObject as pt}from"@walkeros/core";var gt=5e3;async function mt(e){const t=e.logger;await ht(e.sources,"source",t),await async function(e,t){const n=Object.entries(e).flatMap(([e,n])=>{const o=n.batches;if(!o)return[];const s=t.scope(n.type||"destination");return Object.values(o).map(async t=>{let n;try{await Promise.race([t.flush(),new Promise((t,o)=>{n=setTimeout(()=>o(new Error(`destination '${e}' batch flush timed out`)),gt)})])}catch(t){s.error(`destination '${e}' batch flush failed: ${t}`)}finally{n&&clearTimeout(n)}})});await Promise.allSettled(n)}(e.destinations,t),await ht(e.destinations,"destination",t),await ht(e.transformers,"transformer",t),await ht(e.stores,"store",t)}async function ht(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",a=n.scope(r),i={id:e,config:o.config,env:o.env??{},logger:a};let c;try{await Promise.race([s(i),new Promise((n,o)=>{c=setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),gt)})])}catch(n){a.error(`${t} '${e}' destroy failed: ${n}`)}finally{c&&clearTimeout(c)}});await Promise.allSettled(o)}function yt(e,t){e.stateVersion++,e.cellVersion[t]=e.stateVersion}async function wt(e,t,o){let r,a,i=!1;const c=_e(e);try{return await async function(){switch(t){case n.Commands.Config:pt(o)&&(ut(e.config,o,{shallow:!1}),a=o,i=!0);break;case n.Commands.Consent:if(pt(o)){const{update:t}=s(e,o);yt(e,n.Commands.Consent),a=t,i=!0}break;case n.Commands.Custom:pt(o)&&(e.custom=ut(e.custom,o),yt(e,n.Commands.Custom),a=o,i=!0);break;case n.Commands.Destination:pt(o)&&"code"in o&&pt(o.code)&&(r=await tt(e,o));break;case n.Commands.Globals:pt(o)&&(e.globals=ut(e.globals,o),yt(e,n.Commands.Globals),a=o,i=!0);break;case n.Commands.Hook:if(pt(o)&&ft(o.name)&<(o.fn)){const{name:t,fn:n}=o;e.hooks[t]=n,a=o,i=!0}break;case n.Commands.On:if(pt(o)&&ft(o.type)){const{type:t,rules:n}=o;await Be(e,t,n)}break;case n.Commands.Ready:i=!0;break;case n.Commands.Run:r=await Ct(e,o),i=!0;break;case n.Commands.Session:i=!0;break;case n.Commands.Shutdown:e.hasShutdown||(e.hasShutdown=!0,await mt(e));break;case n.Commands.User:pt(o)&&(ut(e.user,o,{shallow:!1}),yt(e,n.Commands.User),a=o,i=!0)}i&&(await Ue(e,t,void 0,a),r=await nt(e));return r||rt({ok:!0})}()}finally{c()}}function vt(e,t){return{timing:Math.round((Date.now()-e.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.3.0-next-1781171238534"},...t}}function bt(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${n} ${o}`,data:a={},context:i={},globals:c=e.globals,custom:u={},user:d=e.user,nested:l=[],consent:f=e.consent,id:p=dt(),trigger:g="",entity:m=n,action:h=o,timing:y=0,source:w={type:"collector",schema:"4"}}=t;return{name:r,data:a,context:i,globals:c,custom:u,user:d,nested:l,consent:f,id:p,trigger:g,entity:m,action:h,timestamp:s,timing:y,source:w}}function kt(e,t){return bt(e,vt(e,t))}async function Ct(e,t){e.allowed=!0,e.timing=Date.now(),t&&(t.consent&&(e.consent=ut(e.consent,t.consent),yt(e,n.Commands.Consent)),t.user&&(e.user=ut(e.user,t.user),yt(e,n.Commands.User)),t.globals&&(e.globals=ut(e.config.globalsStatic||{},t.globals),yt(e,n.Commands.Globals)),t.custom&&(e.custom=ut(e.custom,t.custom),yt(e,n.Commands.Custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++,await Ie(e),await Ke(e);return await nt(e)}import{createIngest as It,emitStep as qt,FatalError as St,getGrantedConsent as xt,processEventMapping as Ot,tryCatchAsync as jt,useHooks as Dt}from"@walkeros/core";function At(e,t){const n=Dt(async(n,o={})=>await jt(async()=>{const s=Date.now(),{id:r,ingest:a,respond:i,mapping:c,preChain:u,include:d,exclude:l}=o;let f=i,p=n;const g=d||l?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,d,l):void 0,m=a??It(r||"unknown");if(c){const t=await Ot(p,c,e);if(t.ignore)return rt({ok:!0});if(c.consent){if(!xt(c.consent,e.consent,t.event.consent))return rt({ok:!0})}p=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await he(e,e.transformers,u,p,m,f,r?`source.${r}.next`:void 0);if(null===n.event)return rt({ok:!0});if(n.stopped)return n.respond&&(f=n.respond),rt({ok:!0});if(n.respond&&(f=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=bt(e,o);return nt(e,s,{id:r,ingest:m,respond:f},g)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??rt({ok:!0})}p=n.event}const h=kt(e,p),y=await nt(e,h,{id:r,ingest:m,respond:f},g);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return y},t=>{if(t instanceof St)throw t;return e.status.failed++,e.logger.error("push failed",{event:n,ingest:o.ingest,error:t}),rt({ok:!1})})(),"Push",e.hooks,e.logger);return async(t,o)=>{const s="string"==typeof t.id?t.id:"",r=Date.now();qt(e,D(e,{stepId:"collector.push",stepType:"collector",phase:"in",eventId:s,now:r}));try{const a=await n(t,o),i=Date.now(),c=D(e,{stepId:"collector.push",stepType:"collector",phase:"out",eventId:s,now:i});return c.durationMs=i-r,c.outEvent=a,qt(e,c),a}catch(t){const n=Date.now(),o=D(e,{stepId:"collector.push",stepType:"collector",phase:"error",eventId:s,now:n});throw o.durationMs=n-r,o.error=t instanceof Error?{name:t.name,message:t.message}:{message:String(t)},qt(e,o),t}}}import{FatalError as $t,useHooks as Et,tryCatchAsync as Mt}from"@walkeros/core";import{emitStep as Tt,useHooks as _t}from"@walkeros/core";function Pt(e={}){const t=e.maxEntries??1e4,n=e.lowWaterMark??.8,o=e.sweepIntervalMs??6e4,s=Math.floor(t*n),r=new Map,a={hits:0,misses:0,populates:0,writes:0,deletes:0,evictions_entries:0,evictions_ttl:0};let i;o>0&&(i=setInterval(function(){const e=Date.now();let t=0;for(const[n,o]of r)void 0!==o.expires&&o.expires<=e&&(r.delete(n),t++);a.evictions_ttl+=t},o),i&&"function"==typeof i.unref&&i.unref());return{type:"memory",config:{},get(e){const t=r.get(e);if(t)return void 0!==t.expires&&t.expires<=Date.now()?(r.delete(e),a.evictions_ttl++,void a.misses++):(r.delete(e),r.set(e,t),a.hits++,t.value);a.misses++},set(e,n,o){const i=!r.has(e);i||r.delete(e),r.set(e,{value:n,expires:void 0!==o?Date.now()+o:void 0}),a.writes++,i&&a.populates++,r.size>t&&function(){if(r.size<=t)return;const e=r.size-s;let n=0;for(const t of r.keys()){if(n>=e)break;r.delete(t),n++}a.evictions_entries+=n}()},delete(e){r.delete(e)&&a.deletes++},get counters(){return{...a}},destroy(){void 0!==i&&(clearInterval(i),i=void 0),r.clear()}}}import{compileMatcher as zt,emitStep as Bt,readCacheEnvelope as Ht,wrapCacheEnvelope as Rt}from"@walkeros/core";function Ft(e,t){const{cacheConfig:n,cacheStore:o,namespace:s,logger:r,storeId:a,collector:i}=t,c=(e,t)=>{if(!i)return;const n=D(i,{stepId:`store.${a}`,stepType:"store",phase:"in",eventId:"",now:Date.now()});n.meta={op:"cache",cached:"hit"===t,status:t,key:e},Bt(i,n)},u={hits:0,misses:0,populates:0,writes:0,deletes:0,inflight_dedups:0},d=n.rules.map(e=>({match:e.match?zt(e.match):()=>!0,ttl:e.ttl})),l=e=>`${s}:${e}`;function f(e,t){const n=void 0===t?{key:e}:{key:e,value:t};return d.find(e=>e.match(n))}const p=new Map;return{type:e.type,config:e.config,setup:e.setup,get counters(){return{...u}},async get(t){const n=l(t),s=await o.get(n),r=Ht(s);if(void 0!==r){if(!("expired"in r))return u.hits++,c(t,"hit"),r.value;try{await o.delete(n)}catch(e){g("delete",t,e)}}const a=p.get(n);if(a)return u.inflight_dedups++,c(t,"hit"),a;u.misses++,c(t,"miss");const i=(async()=>{try{const s=await e.get(t);if(void 0===s)return;const r=f(t,s);if(r)try{const e=1e3*r.ttl;await o.set(n,Rt(s,e),e),u.populates++}catch(e){g("set",t,e)}return s}finally{p.delete(n)}})();return p.set(n,i),i},async set(t,n,s){u.writes++,await e.set(t,n,s);const r=f(t,n);if(r)try{const e=1e3*r.ttl;await o.set(l(t),Rt(n,e),e)}catch(e){g("set",t,e)}},async delete(t){u.deletes++,await e.delete(t);try{await o.delete(l(t))}catch(e){g("delete",t,e)}}};function g(e,t,n){const o=`store-cache(${a}): cache ${e} failed for "${t}"; backing succeeded, continuing`;r?r.warn(o,{error:n}):console.warn(o,n)}}function Gt(e,t,n){const o=`store.${n}`,s=_t(t.get,"StoreGet",e.hooks,e.logger),r=_t(t.set,"StoreSet",e.hooks,e.logger),a=_t(t.delete,"StoreDelete",e.hooks,e.logger);t.get=async t=>{const n=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});r.meta={op:"get",key:t},Tt(e,r);try{const r=await s(t),a=Date.now(),i=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:a});return i.durationMs=a-n,i.meta={op:"get",key:t},Tt(e,i),r}catch(s){const r=Date.now(),a=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw a.durationMs=r-n,a.meta={op:"get",key:t},a.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},Tt(e,a),s}},t.set=async(t,n,s)=>{const a=Date.now(),i=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:a});i.meta={op:"set",key:t},Tt(e,i);try{await r(t,n,s);const i=Date.now(),c=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:i});c.durationMs=i-a,c.meta={op:"set",key:t},Tt(e,c)}catch(n){const s=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:s});throw r.durationMs=s-a,r.meta={op:"set",key:t},r.error=n instanceof Error?{name:n.name,message:n.message}:{message:String(n)},Tt(e,r),n}},t.delete=async t=>{const n=Date.now(),s=D(e,{stepId:o,stepType:"store",phase:"in",eventId:"",now:n});s.meta={op:"delete",key:t},Tt(e,s);try{await a(t);const s=Date.now(),r=D(e,{stepId:o,stepType:"store",phase:"out",eventId:"",now:s});r.durationMs=s-n,r.meta={op:"delete",key:t},Tt(e,r)}catch(s){const r=Date.now(),a=D(e,{stepId:o,stepType:"store",phase:"error",eventId:"",now:r});throw a.durationMs=r-n,a.meta={op:"delete",key:t},a.error=s instanceof Error?{name:s.name,message:s.message}:{message:String(s)},Tt(e,a),s}}}async function Kt(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:a={}}=s,i=e.logger.scope("store").scope(o),c={collector:e,logger:i,id:o,config:r,env:a},u=await t(c);n[o]=u}const o=t,s=function(e){const t={};for(const n of Object.keys(e))t[n]="WHITE";const n=[],o=[];function s(r){const a=t[r];if("BLACK"===a)return;if("GRAY"===a){const e=o.indexOf(r),t=o.slice(-1===e?0:e).concat(r).join(" -> ");throw new Error(`Cycle in cache.store chain: ${t}`)}t[r]="GRAY",o.push(r);const i=e[r].cache?.store;if(void 0!==i){if(!(i in e))throw new Error(`Store "${r}" cache.store references "${i}", which is not declared in flow.stores`);s(i)}o.pop(),t[r]="BLACK",n.push(r)}for(const n of Object.keys(e))"WHITE"===t[n]&&s(n);return n}(o);for(const t of s){const s=o[t].cache;if(!s)continue;let r,a;void 0!==s.store?(r=n[s.store],a=s.store):(n.__cache||(n.__cache=Pt()),r=n.__cache,a="__cache");const i=s.namespace??t;e.logger.scope("store-cache").scope(t).info(`store "${t}" caches with namespace "${i}:" via ${a}`),n[t]=Ft(n[t],{storeId:t,cacheConfig:s,cacheStore:r,namespace:i,logger:e.logger.scope("store-cache").scope(t),collector:e})}for(const[t,o]of Object.entries(n))"__cache"!==t&&Gt(e,o,t);return n}async function Ut(e){const t=r({globalsStatic:{},sessionStatic:{},run:!0,queueMax:1e3},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=a(n),s={...t.globalsStatic,...e.globals},i={allowed:!1,config:t,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},observers:new Set,logger:o,on:{},queue:[],round:0,stateVersion:0,cellVersion:{},delivery:new WeakMap,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{},dropped:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},hasShutdown:!1,seenEvents:new Set,push:void 0,command:void 0};i.push=At(i,e=>vt(i,e)),i.command=function(e,t){return Et(async(n,o,s)=>await Mt(async()=>await t(e,n,o,s),t=>{if(t instanceof $t)throw t;return e.status.failed++,e.logger.error("command failed",{command:n,data:o,error:t}),rt({ok:!1})})(),"Command",e.hooks,e.logger)}(i,wt);const c=e.stores||{};return i.stores=await Kt(i,c),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(c,i.stores,e),i.stores.__cache||(i.stores.__cache=Pt()),i.destinations=await it(i,e.destinations||{}),i.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,a=se(s,"Transformer");if(!a.ok){e.logger.warn(`Transformer ${o} invalid (${a.code}): ${a.reason}. Skipping.`);continue}const{config:i}=le(s,"before"),{config:c}=le({...s,config:i},"next"),u=Object.keys(r).length>0?{...c,env:r}:c,{cache:d}=s,l=d?{...u,cache:d}:u,f=s.config?.state??s.state,p=void 0!==f&&void 0===l.state?{...l,state:f}:l,g=e.logger.scope("transformer").scope(o),m={collector:e,logger:g,id:o,ingest:V(o),config:p,env:r},h=t??(e=>{const t=s.mapping;if(t){const n=[];if(void 0!==t.data&&n.push("data"),t.mapping)for(const[e,o]of Object.entries(t.mapping))if("object"==typeof o&&null!==o)for(const[t,s]of Object.entries(o)){if("object"!=typeof s||null===s)continue;const o=s;void 0!==o.data&&n.push(`mapping[${e}][${t}].data`),void 0!==o.silent&&n.push(`mapping[${e}][${t}].silent`)}return n.length>0&&e.collector.logger.warn(`Transformer ${o}: \`${n.join(", ")}\` ignored at transformer position (only event-mutating fields apply).`),{type:"pass",config:e.config,push:async n=>{const o=await re(n,t,e.collector);return!o.ignore&&{event:o.event}}}}return{type:"pass",config:e.config,push:e=>({event:e})}}),y=await h(m);void 0!==s.before&&void 0===y.config?.before&&(y.config={...y.config??{},before:s.before}),void 0!==s.next&&void 0===y.config?.next&&(y.config={...y.config??{},next:s.next}),void 0!==f&&void 0===y.config?.state&&(y.config={...y.config??{},state:f}),n[o]=y}return n}(i,e.transformers||{}),i}async function Wt(e){e=e||{};const t=await Ut(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r)=>{if("string"==typeof e&&e.startsWith("walker ")){const n=e.replace("walker ","");return o.command(n,t)}let a;if("string"==typeof e)a={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(a.data=t);else{if(!e||"object"!=typeof e)return rt({ok:!1});a=e,t&&"object"==typeof t&&!Array.isArray(t)&&(a.data={...a.data||{},...t})}return n&&"object"==typeof n&&(a.context=n),s&&Array.isArray(s)&&(a.nested=s),r&&"object"==typeof r&&(a.custom=r),o.push(a)}});var o;t.sources.elb=n,await Ce(t,e.sources||{});const{consent:s,user:r,globals:a,custom:i}=e;s&&await t.command("consent",s),r&&await t.command("user",r),a&&await t.command("globals",a),i&&await t.command("custom",i),t.config.run&&await t.command("run");let c=n.push;const u=Object.values(t.sources).filter(e=>"elb"!==e.type),d=u.find(e=>e.config.primary);return d?c=d.push:u.length>0&&(c=u[0].push),{collector:t,elb:c}}function Vt(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Vt);const t={};for(const[n,o]of Object.entries(e))t[n]="function"==typeof o?o:Vt(o);return t}function Nt(e){const t=[],{simulation:n,...o}=e,s=Vt(o);for(const e of n){const n=e.startsWith("call:")?e.slice(5):e,o=n.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const a=o[o.length-1];if(null==r||!(a in r))continue;const i=r[a];"function"==typeof i&&(r[a]=function(...e){return t.push({fn:n,args:e,ts:Date.now()}),i.apply(this,e)})}return{wrappedEnv:s,calls:t}}export{e as Code,t as Commands,n as Const,tt as addDestination,He as callDestinationOn,wt as commonHandleCommand,bt as createEvent,At as createPush,rt as createPushResult,ot as destinationInit,st as destinationPush,kt as enrichEvent,_e as enterCascade,de as extractTransformerNextMap,Re as fireCallbacks,ve as flushSourceQueueOn,ce as getCacheStore,it as initDestinations,ke as initSource,Ce as initSources,$e as isRequireSatisfied,be as isSourceStarted,De as isStateDelivery,Ae as isStatePresent,ct as mergeEnvironments,Be as on,Ue as onApply,vt as prepareEvent,s as processConsent,nt as pushToDestinations,Ke as redeliverStateAtRun,at as registerDestination,Ct as runCollector,he as runTransformerChain,Me as setMark,Te as shouldDeliver,Wt as startFlow,pe as transformerInit,ge as transformerPush,fe as walkChain,Nt as wrapEnv};//# sourceMappingURL=index.mjs.map
|