@walkeros/collector 4.0.1 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var e={},n={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",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"},t={Commands:n,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};import{assign as o}from"@walkeros/core";function s(e,n){const t={};return Object.entries(n).forEach(([e,n])=>{t[e]=!!n}),e.consent=o(e.consent,t),{update:t}}import{assign as r,createLogger as i}from"@walkeros/core";import{assign as a,buildCacheContext as c,clone as u,compileCache as f,checkCache as l,storeCache as d,compileNext as g,createIngest as m,debounce as p,getId as h,getGrantedConsent as y,isDefined as b,isFunction as v,isObject as w,isRouteArray as k,processEventMapping as C,resolveNext as O,tryCatchAsync as j,useHooks as q}from"@walkeros/core";import{isArray as x}from"@walkeros/core";import{tryCatch as A,tryCatchAsync as S}from"@walkeros/core";import{createIngest as D,getMappingValue as $,tryCatchAsync as E,compileNext as _,resolveNext as I,isRouteArray as P,compileCache as R,checkCache as M,storeCache as H,applyUpdate as T,buildCacheContext as G}from"@walkeros/core";import{createIngest as B,isObject as N,tryCatchAsync as U,useHooks as F,compileNext as W,resolveNext as z,isRouteArray as L,compileCache as V,checkCache as J,storeCache as K,buildCacheContext as Q}from"@walkeros/core";function X(e,n){return e.storeId&&n.stores[e.storeId]?n.stores[e.storeId]:n.stores.__cache}function Y(e){const n={};for(const[t,o]of Object.entries(e)){const e=o.config?.next;e&&!L(e)?n[t]={next:e}:n[t]={}}return n}function Z(e,n){const t=e.config||{},o=e[n];return void 0!==o?{config:{...t,[n]:o},chainValue:o}:{config:t,chainValue:void 0}}function ee(e,n={}){if(!e)return[];if(Array.isArray(e))return e;const t=[],o=new Set;let s=e;for(;s&&n[s]&&!o.has(s);){o.add(s),t.push(s);const e=n[s].next;if(Array.isArray(e)){t.push(...e);break}s=e}return t}async function ne(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:t,ingest:B(t),config:n.config,env:se(n.config.env)};s.debug("init");const i=await F(n.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;n.config={...i||n.config,env:i?.env||n.config.env,init:!0},s.debug("init done")}return!0}async function te(e,n,t,o,s,r){const i=n.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:t,ingest:s,config:n.config,env:{...se(n.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await F(n.push,"TransformerPush",e.hooks,e.logger)(o,c);return a.debug("push done"),u}async function oe(e,n,t,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of t){const r=n[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 U(ne)(e,r,o))return e.logger.error(`Transformer init failed: ${o}`),{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const n=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=n;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,f=u?V(u):void 0,l=f?X(f,e):void 0;let d;if(f&&l){const e=Q(s,a),n=J(f,l,e,`t:${o}`);if("HIT"===n?.status&&n.value){if(a=n.value,f.full)return{event:a,respond:c};continue}"MISS"===n?.status&&(d={key:n.key,ttl:n.rule.ttl})}const g=r.config.before;if(g){const t=ee("string"==typeof g||Array.isArray(g)&&!L(g)?g:z(W(g),Q(s,a))||void 0,Y(n));if(t.length>0){const o=await oe(e,n,t,a,s,c,i);if(null===o.event)return{event:null,respond:o.respond??c};o.respond&&(c=o.respond),a=Array.isArray(o.event)?o.event[0]:o.event}}const m=await U(te,n=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,r,o,a,s,c);if(!1===m)return{event:null,respond:c};if(Array.isArray(m)){const r=t.slice(t.indexOf(o)+1),u=await Promise.all(m.map(async t=>{const o=t.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:B("unknown");if(t.next){let s=t.next;if(L(t.next)){const e=W(t.next);s=z(e,Q(u,o))}if(s){const t=ee(s,Y(n));if(t.length>0)return oe(e,n,t,o,u,c,i)}return{event:o,respond:c}}return r.length>0?oe(e,n,r,o,u,c,i):{event:o,respond:c}}));let f=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const n=e;if(n.respond&&(f=n.respond),null===n.event)continue;Array.isArray(n.event)?l.push(...n.event):l.push(n.event)}else l.push(e);return 0===l.length?{event:null,respond:f}:1===l.length?{event:l[0],respond:f}:{event:l,respond:f}}if(m&&"object"==typeof m){const{event:t,respond:o,next:r}=m;if(o&&(c=o),r){let o=r;if(L(r)){const e=W(r);if(o=z(e,Q(s,a)),!o){t&&(a=t);continue}}const u=ee(o,Y(n));return u.length>0?oe(e,n,u,t||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}t&&(a=t)}if(d&&l&&K(l,d.key,a,d.ttl),(!m||"object"==typeof m&&!m.next)&&r.config.next&&L(r.config.next)){const t=r.config.next,o=W(t),u=z(o,Q(s,a));if(u){const t=ee(u,Y(n));if(t.length>0)return oe(e,n,t,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function se(e){return e&&N(e)?e:{}}async function re(e,n){if(!n.on||!n.queueOn?.length)return;const t=n.queueOn;n.queueOn=[];for(const{type:e,data:o}of t)await E(n.on)(e,o)}function ie(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ae(e,n,t){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=t;let f,l=D(n);const d=u?R({...u,full:u.full??!0}):void 0,g=_(a),m=!(Array.isArray(a)&&P(a))&&g?ee(I(g),Y(e.transformers)):void 0,p=_(c),h=!(Array.isArray(c)&&P(c))&&p?ee(I(p),Y(e.transformers)):void 0,y=e.logger.scope("source").scope(n),b={push:async(t,o={})=>{let r,i=t;const a=h??(p?ee(I(p,G(l)),Y(e.transformers)):[]);if(a.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await oe(e,e.transformers,a,i,l,f,`source.${n}.before`);if(null===t.event)return{ok:!0};t.respond&&(f=t.respond),i=Array.isArray(t.event)?t.event[0]:t.event}if(d){const t=X(d,e);if(t){const o=G(l),s=M(d,t,o,`s:${n}`);if(s){if("HIT"===s.status&&void 0!==s.value&&d.full){let n=s.value;return s.rule.update&&(n=await T(n,s.rule.update,{...o,cache:{status:"HIT"}},e)),f?.(n),{ok:!0}}if("MISS"===s.status&&d.full&&f){const n=f,i=s.rule.update,a={...o,cache:{status:"MISS"}},c=s.key,u=s.rule.ttl;f=o=>{H(t,c,o,u),i?r=(async()=>{const t=await T(o,i,a,e);n(t)})():n(o)}}"MISS"!==s.status||d.full||H(t,s.key,!0,s.rule.ttl)}}}const c=m??(g?ee(I(g,G(l)),Y(e.transformers)):[]),u=await e.push(i,{...o,id:n,ingest:l,respond:f,mapping:s,preChain:c});return r&&await r,u},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:y,...r},v={collector:e,logger:y,id:n,config:s,env:b,setIngest:async t=>{if(!s.ingest)return void(l=D(n));const o=await $(t,s.ingest,{collector:e}),r=D(n);l={...r,...o,_meta:r._meta}},setRespond:e=>{f=e}},w=await E(o)(v);if(!w)return;const k=w.type||"unknown",C=e.logger.scope(k).scope(n);return b.logger=C,i&&(w.config={...w.config,primary:i}),w}async function ce(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const n=await ae(e,o,s);if(!n)continue;const r=s.config?.require;n.config={...n.config,init:!1,...r?{require:[...r]}:{}},t[o]=n}Object.assign(e.sources,t);for(const n of Object.keys(t)){const t=e.sources[n];t.init&&await E(t.init.bind(t))(),t.config.init=!0,ie(t)&&await re(0,t)}return t}function ue(e,n){return{collector:e,logger:e.logger.scope("on").scope(String(n))}}async function fe(e,n,t){const o=e.on,s=o[n]||[],r=x(t)?t:[t];r.forEach(e=>{s.push(e)}),o[n]=s,de(e,n,r)}function le(e,n,t,o,s){if(!n.on)return;const r=n.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:t,config:n.config,data:s,env:Ce(n.env,n.config.env)};A(n.on)(o,a)}function de(e,n,o,s){let r;switch(n){case t.Commands.Consent:r=s||e.consent;break;case t.Commands.Session:r=e.session;break;case t.Commands.User:r=s||e.user;break;case t.Commands.Custom:r=s||e.custom;break;case t.Commands.Globals:r=s||e.globals;break;case t.Commands.Config:r=s||e.config;break;case t.Commands.Ready:case t.Commands.Run:default:r=void 0}if(o.length)switch(n){case t.Commands.Consent:!function(e,n,o){const s=o||e.consent,r=ue(e,t.Commands.Consent);n.forEach(e=>{Object.keys(s).filter(n=>n in e).forEach(n=>{A(e[n])(s,r)})})}(e,o,s);break;case t.Commands.Ready:!function(e,n){if(!e.allowed)return;const o=ue(e,t.Commands.Ready);n.forEach(e=>{A(e)(void 0,o)})}(e,o);break;case t.Commands.Run:!function(e,n){if(!e.allowed)return;const o=ue(e,t.Commands.Run);n.forEach(e=>{A(e)(void 0,o)})}(e,o);break;case t.Commands.Session:!function(e,n){if(!e.session)return;const o=ue(e,t.Commands.Session);n.forEach(n=>{A(n)(e.session,o)})}(e,o);break;default:{const t=ue(e,n);o.forEach(e=>{"function"==typeof e&&A(e)(r,t)});break}}}async function ge(e,n,o,s){let r,i=o||[];switch(o||(i=e.on[n]||[]),n){case t.Commands.Consent:r=s||e.consent;break;case t.Commands.Session:r=e.session;break;case t.Commands.User:r=s||e.user;break;case t.Commands.Custom:r=s||e.custom;break;case t.Commands.Globals:r=s||e.globals;break;case t.Commands.Config:r=s||e.config;break;case t.Commands.Ready:case t.Commands.Run:default:r=void 0}let a=!1;for(const t of Object.values(e.sources)){if(t.config.require?.length){const e=t.config.require.indexOf(n);-1!==e&&t.config.require.splice(e,1)}if(t.on)if(ie(t)){!1===await S(t.on)(n,r)&&(a=!0)}else t.queueOn=t.queueOn||[],t.queueOn.push({type:n,data:r})}Object.entries(e.destinations).forEach(([t,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:n,data:r});le(e,o,t,n,r)}});for(const n of Object.values(e.sources))ie(n)&&n.queueOn?.length&&await re(0,n);return Object.keys(e.pending.destinations).length>0&&await async function(e,n){for(const[t,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(n);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[t];const i=we(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[t]=i}}(e,n),de(e,n,i,s),!a}function me(e,n,t,o){if(!e)return[];if(n){const e=O(n,c(o));return e?ee(e,Y(t)):[]}return ee(e,Y(t))}async function pe(e,n,t){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=n;if(!v(o.push))return ve({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=t||s||{init:!1};let f=i?{...u,before:i}:{...u};a&&(f={...f,next:a}),c&&(f={...f,cache:c});const l={...o,config:f,env:Ce(o.env,r)};let d=l.config.id;if(!d)do{d=h(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[d]);return e.destinations[d]=l,!1!==l.config.queue&&(l.queuePush=[...e.queue]),he(e,void 0,{},{[d]:l})}async function he(e,n,t={},o){const{allowed:s,consent:r,globals:i,user:p}=e;if(!s)return ve({ok:!1});n&&(e.queue.push(n),e.status.in++),o||(o=e.destinations);const h=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let h=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],n&&h.push(u(n));const b=t.ingest?{...t.ingest,_meta:{...t.ingest._meta,path:[...t.ingest._meta.path]}}:m("unknown");if(!h.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!h.length&&s.queueOn?.length){let n=!1;try{n=await ye(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}return{id:o,destination:s,skipped:!n}}const v=[],w=h.filter(e=>{const n=y(s.config.consent,r,e.consent);return!n||(e.consent=n,v.push(e),!1)});if(s.queuePush.push(...w),!v.length)return{id:o,destination:s,queue:h};let C,O,q=!1;try{q=await ye(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}if(!q)return{id:o,destination:s,queue:h};s.dlq||(s.dlq=[]);const x=s.config.before,A=me(x,x&&k(x)?g(x):void 0,e.transformers,b),S=s.config.next,D=S&&k(S)?g(S):void 0,$=s.config?.cache,E=$?f($):void 0,_=E?X(E,e):void 0;let I=0;return await Promise.all(v.map(async n=>{let r;if(n.globals=a(i,n.globals),n.user=a(p,n.user),E?.full&&_){const e=c(b,n),t=l(E,_,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}let u=n,f=t.respond;if(A.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await oe(e,e.transformers,A,n,b,t.respond,`destination.${o}.before`);if(null===s.event)return n;s.respond&&(f=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(E&&!E.full&&_){const e=c(b,u),t=l(E,_,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}const g=Date.now();let m=!1;const h=await j(be,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:u.name}),C=n,m=!0,s.dlq.push([u,n])})(e,s,o,u,b,f);if(I+=Date.now()-g,r&&_&&void 0===s.config.mock&&d(_,r.key,h??!0,r.ttl),void 0!==h&&(O=h),!m&&S){void 0!==h&&(b._response=h);const n=me(S,D,e.transformers,b);if(n.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await oe(e,e.transformers,n,u,b,f,`destination.${o}.next`);t.respond&&(f=t.respond)}}return n})),{id:o,destination:s,error:C,response:O,totalDuration:I}})),b={},v={},w={};for(const n of h){if(n.skipped)continue;const t={type:n.destination.type||"unknown",data:n.response};e.status.destinations[n.id]||(e.status.destinations[n.id]={count:0,failed:0,duration:0});const o=e.status.destinations[n.id],s=Date.now();n.error?(t.error=n.error,w[n.id]=t,o.failed++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?v[n.id]=t:(b[n.id]=t,o.count++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.out++)}return ve({event:n,...Object.keys(b).length&&{done:b},...Object.keys(v).length&&{queued:v},...Object.keys(w).length&&{failed:w}})}async function ye(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:t,config:n.config,env:Ce(n.env,n.config.env)};s.debug("init");const i=await q(n.init,"DestinationInit",e.hooks,e.logger)(r);if(!1===i)return i;if(n.config={...i||n.config,init:!0},n.queueOn?.length){const o=n.queueOn;n.queueOn=[];for(const{type:s,data:r}of o)le(e,n,t,s,r)}s.debug("init done")}return!0}async function be(e,n,t,o,s,r){const{config:i}=n,a=await C(o,i,e);if(a.ignore)return!1;const c=n.type||"unknown",u=e.logger.scope(c),f={collector:e,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...Ce(n.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const l=a.mapping,d=a.mappingKey||"* *";if(!l?.batch||!n.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const t=await q(n.push,"DestinationPush",e.hooks,e.logger)(a.event,f);return u.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[d]){const o={key:d,events:[],data:[]};n.batches[d]={batched:o,batchFn:p(()=>{const o=n.batches[d].batched,a={collector:e,logger:u,id:t,config:i,data:void 0,rule:l,ingest:s,env:{...Ce(n.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),q(n.pushBatch,"DestinationPushBatch",e.hooks,e.logger)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},l.batch)}}const o=n.batches[d];o.batched.events.push(a.event),b(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function ve(e){return{ok:!e?.failed,...e}}function we(e){const{code:n,config:t={},env:o={},cache:s}=e,{config:r}=Z(e,"before"),{config:i}=Z({...e,config:r},"next"),a={...n.config,...t,...i};s&&(a.cache=s);const c=Ce(n.env,o);return{...n,config:a,env:c}}async function ke(e,n={}){const t={};for(const[o,s]of Object.entries(n))s.config?.require?.length?e.pending.destinations[o]=s:t[o]=we(s);return t}function Ce(e,n){return e||n?n?e&&w(e)&&w(n)?{...e,...n}:n:e:{}}import{assign as Oe,getSpanId as je,isFunction as qe,isString as xe}from"@walkeros/core";import{isObject as Ae}from"@walkeros/core";async function Se(e,n,t){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=t.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((t,o)=>setTimeout(()=>o(new Error(`${n} '${e}' destroy timed out`)),5e3))])}catch(t){i.error(`${n} '${e}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function De(e,n,o,r){let i,a,c=!1;switch(n){case t.Commands.Config:Ae(o)&&(Oe(e.config,o,{shallow:!1}),a=o,c=!0);break;case t.Commands.Consent:if(Ae(o)){const{update:n}=s(e,o);a=n,c=!0}break;case t.Commands.Custom:Ae(o)&&(e.custom=Oe(e.custom,o),a=o,c=!0);break;case t.Commands.Destination:Ae(o)&&("code"in o&&Ae(o.code)?i=await pe(e,o,r):qe(o.push)&&(i=await pe(e,{code:o},r)));break;case t.Commands.Globals:Ae(o)&&(e.globals=Oe(e.globals,o),a=o,c=!0);break;case t.Commands.On:xe(o)&&await fe(e,o,r);break;case t.Commands.Ready:c=!0;break;case t.Commands.Run:i=await Ee(e,o),c=!0;break;case t.Commands.Session:c=!0;break;case t.Commands.Shutdown:await async function(e){const n=e.logger;await Se(e.sources,"source",n),await Se(e.destinations,"destination",n),await Se(e.transformers,"transformer",n),await Se(e.stores,"store",n)}(e);break;case t.Commands.User:Ae(o)&&(Oe(e.user,o,{shallow:!1}),a=o,c=!0)}return c&&(await ge(e,n,void 0,a),i=await he(e)),i||ve({ok:!0})}function $e(e,n){if(!n.name)throw new Error("Event name is required");const[t,o]=n.name.split(" ");if(!t||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${t} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:f=e.user,nested:l=[],consent:d=e.consent,id:g=je(),trigger:m="",entity:p=t,action:h=o,timing:y=0,source:b={type:"collector",schema:"4"}}=n;return{name:r,data:i,context:a,globals:c,custom:u,user:f,nested:l,consent:d,id:g,trigger:m,entity:p,action:h,timestamp:s,timing:y,source:b}}async function Ee(e,n){e.allowed=!0,e.timing=Date.now(),n&&(n.consent&&(e.consent=Oe(e.consent,n.consent)),n.user&&(e.user=Oe(e.user,n.user)),n.globals&&(e.globals=Oe(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=Oe(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await he(e)}import{createIngest as _e,getGrantedConsent as Ie,processEventMapping as Pe,tryCatchAsync as Re,useHooks as Me}from"@walkeros/core";function He(e,n){return Me(async(t,o={})=>await Re(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:f,exclude:l}=o;let d=a,g=t;const m=f||l?function(e,n,t){let o=e;return n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>n.includes(e)))),t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!t.includes(e)))),o}(e.destinations,f,l):void 0,p=i??_e(r||"unknown");if(c){const n=await Pe(g,c,e);if(n.ignore)return ve({ok:!0});if(c.consent){if(!Ie(c.consent,e.consent,n.event.consent))return ve({ok:!0})}g=n.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const t=await oe(e,e.transformers,u,g,p,d,r?`source.${r}.next`:void 0);if(null===t.event)return ve({ok:!0});if(t.respond&&(d=t.respond),Array.isArray(t.event)){const o=await Promise.all(t.event.map(async t=>{const o=n(t),s=$e(e,o);return he(e,s,{id:r,ingest:p,respond:d},m)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count+=t.event.length,n.lastAt=Date.now(),n.duration+=Date.now()-s}return o[0]??ve({ok:!0})}g=t.event}const h=n(g),y=$e(e,h),b=await he(e,y,{id:r,ingest:p,respond:d},m);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count++,n.lastAt=Date.now(),n.duration+=Date.now()-s}return b},()=>ve({ok:!1}))(),"Push",e.hooks,e.logger)}import{useHooks as Te,tryCatchAsync as Ge}from"@walkeros/core";import{useHooks as Be}from"@walkeros/core";async function Ne(e){const n=r({globalsStatic:{},sessionStatic:{},run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=i(t),s={...n.globalsStatic,...e.globals},a={allowed:!1,config:n,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},push:void 0,command:void 0};a.push=He(a,e=>({timing:Math.round((Date.now()-a.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.0.1"},...e})),a.command=function(e,n){return Te(async(t,o,s)=>await Ge(async()=>await n(e,t,o,s),()=>ve({ok:!1}))(),"Command",e.hooks,e.logger)}(a,De);const c=e.stores||{};if(a.stores=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await n(c),f=u.get,l=u.set,d=u.delete;u.get=Be(f,"StoreGet",e.hooks,e.logger),u.set=Be(l,"StoreSet",e.hooks,e.logger),u.delete=Be(d,"StoreDelete",e.hooks,e.logger),t[o]=u}return t}(a,c),function(e,n,t){const o=new Map;for(const[t,s]of Object.entries(e))n[t]&&o.set(s,n[t]);if(0!==o.size)for(const e of[t.transformers,t.destinations,t.sources])if(e)for(const n of Object.values(e))s(n.env);function s(e){if(e)for(const[n,t]of Object.entries(e))if("object"==typeof t&&null!==t){const s=o.get(t);s&&(e[n]=s)}}}(c,a.stores,e),!a.stores.__cache){const e=new Map;a.stores.__cache={type:"memory",config:{},get:n=>{const t=e.get(n);if(t){if(!(t.expires&&Date.now()>t.expires))return t.value;e.delete(n)}},set:(n,t,o)=>{e.set(n,{value:t,expires:o?Date.now()+o:void 0})},delete:n=>{e.delete(n)}}}return a.destinations=await ke(a,e.destinations||{}),a.transformers=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,env:r={}}=s,{config:i}=Z(s,"before"),{config:a}=Z({...s,config:i},"next"),c=Object.keys(r).length>0?{...a,env:r}:a,{cache:u}=s,f=u?{...c,cache:u}:c,l=e.logger.scope("transformer").scope(o),d={collector:e,logger:l,id:o,ingest:B(o),config:f,env:r},g=await n(d);t[o]=g}return t}(a,e.transformers||{}),a}async function Ue(e){e=e||{};const n=await Ne(e),t=(o=n,{type:"elb",config:{},push:async(e,n,t,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,n,t)}let a;if("string"==typeof e)a={name:e},n&&"object"==typeof n&&!Array.isArray(n)&&(a.data=n);else{if(!e||"object"!=typeof e)return ve({ok:!1});a=e,n&&"object"==typeof n&&!Array.isArray(n)&&(a.data={...a.data||{},...n})}return s&&"object"==typeof s&&(a.context=s),r&&Array.isArray(r)&&(a.nested=r),i&&"object"==typeof i&&(a.custom=i),o.push(a)}});var o;n.sources.elb=t,await ce(n,e.sources||{});const{consent:s,user:r,globals:i,custom:a}=e;s&&await n.command("consent",s),r&&await n.command("user",r),i&&Object.assign(n.globals,i),a&&Object.assign(n.custom,a),n.config.run&&await n.command("run");let c=t.push;const u=Object.values(n.sources).filter(e=>"elb"!==e.type),f=u.find(e=>e.config.primary);return f?c=f.push:u.length>0&&(c=u[0].push),{collector:n,elb:c}}function Fe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Fe);const n={};for(const[t,o]of Object.entries(e))n[t]="function"==typeof o?o:Fe(o);return n}function We(e){const n=[],{simulation:t,...o}=e,s=Fe(o);for(const e of t){const t=e.startsWith("call:")?e.slice(5):e,o=t.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const i=o[o.length-1];if(null==r||!(i in r))continue;const a=r[i];"function"==typeof a&&(r[i]=function(...e){return n.push({fn:t,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:n}}export{e as Code,n as Commands,t as Const,pe as addDestination,le as callDestinationOn,De as commonHandleCommand,$e as createEvent,He as createPush,ve as createPushResult,ye as destinationInit,be as destinationPush,Y as extractTransformerNextMap,re as flushSourceQueueOn,X as getCacheStore,ke as initDestinations,ae as initSource,ce as initSources,ie as isSourceStarted,Ce as mergeEnvironments,fe as on,ge as onApply,s as processConsent,he as pushToDestinations,we as registerDestination,Ee as runCollector,oe as runTransformerChain,Ue as startFlow,ne as transformerInit,te as transformerPush,ee as walkChain,We as wrapEnv};//# sourceMappingURL=index.mjs.map
1
+ var e={},n={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",Session:"session",Shutdown:"shutdown",User:"user",Walker:"walker"},t={Commands:n,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};import{assign as o}from"@walkeros/core";function s(e,n){const t={};return Object.entries(n).forEach(([e,n])=>{t[e]=!!n}),e.consent=o(e.consent,t),{update:t}}import{assign as r,createLogger as i}from"@walkeros/core";import{assign as a,buildCacheContext as c,clone as u,compileCache as f,checkCache as l,storeCache as d,compileNext as g,createIngest as m,debounce as p,getId as h,getGrantedConsent as y,isDefined as b,isFunction as v,isObject as w,isRouteArray as k,processEventMapping as C,resolveNext as O,tryCatchAsync as j,useHooks as q}from"@walkeros/core";import{isArray as A}from"@walkeros/core";import{tryCatch as x,tryCatchAsync as S}from"@walkeros/core";import{createIngest as D,getMappingValue as $,tryCatchAsync as E,compileNext as _,resolveNext as I,isRouteArray as P,compileCache as R,checkCache as M,storeCache as H,applyUpdate as T,buildCacheContext as G}from"@walkeros/core";import{createIngest as B,isObject as N,tryCatchAsync as U,useHooks as F,compileNext as W,resolveNext as z,isRouteArray as L,compileCache as V,checkCache as J,storeCache as K,buildCacheContext as Q}from"@walkeros/core";function X(e,n){return e.storeId&&n.stores[e.storeId]?n.stores[e.storeId]:n.stores.__cache}function Y(e){const n={};for(const[t,o]of Object.entries(e)){const e=o.config?.next;e&&!L(e)?n[t]={next:e}:n[t]={}}return n}function Z(e,n){const t=e.config||{},o=e[n];return void 0!==o?{config:{...t,[n]:o},chainValue:o}:{config:t,chainValue:void 0}}function ee(e,n={}){if(!e)return[];if(Array.isArray(e))return e;const t=[],o=new Set;let s=e;for(;s&&n[s]&&!o.has(s);){o.add(s),t.push(s);const e=n[s].next;if(Array.isArray(e)){t.push(...e);break}s=e}return t}async function ne(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:t,ingest:B(t),config:n.config,env:re(n.config.env)};s.debug("init");const i=await F(n.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;n.config={...i||n.config,env:i?.env||n.config.env,init:!0},s.debug("init done")}return!0}async function te(e,n,t,o,s,r){const i=n.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:t,ingest:s,config:n.config,env:{...re(n.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await F(n.push,"TransformerPush",e.hooks,e.logger)(o,c);return a.debug("push done"),u}function oe(e,n){if(e)return"string"==typeof e||Array.isArray(e)&&!L(e)?e:z(W(e),n)??void 0}async function se(e,n,t,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of t){const r=n[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 U(ne)(e,r,o))return e.logger.error(`Transformer init failed: ${o}`),{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const n=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=n;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,f=u?V(u):void 0,l=f?X(f,e):void 0;let d;if(f&&l){const e=Q(s,a),n=J(f,l,e,`t:${o}`);if("HIT"===n?.status&&n.value){if(a=n.value,f.full)return{event:a,respond:c};continue}"MISS"===n?.status&&(d={key:n.key,ttl:n.rule.ttl})}const g=r.config.before;if(g){const t=ee(oe(g,Q(s,a)),Y(n));if(t.length>0){const o=await se(e,n,t,a,s,c,i);if(null===o.event)return{event:null,respond:o.respond??c};o.respond&&(c=o.respond),a=Array.isArray(o.event)?o.event[0]:o.event}}const m=await U(te,n=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,r,o,a,s,c);if(!1===m)return{event:null,respond:c};if(Array.isArray(m)){const r=t.slice(t.indexOf(o)+1),u=await Promise.all(m.map(async t=>{const o=t.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:B("unknown");if(t.next){const s=oe(t.next,Q(u,o));if(s){const t=ee(s,Y(n));if(t.length>0)return se(e,n,t,o,u,c,i)}return{event:o,respond:c}}return r.length>0?se(e,n,r,o,u,c,i):{event:o,respond:c}}));let f=c;const l=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const n=e;if(n.respond&&(f=n.respond),null===n.event)continue;Array.isArray(n.event)?l.push(...n.event):l.push(n.event)}else l.push(e);return 0===l.length?{event:null,respond:f}:1===l.length?{event:l[0],respond:f}:{event:l,respond:f}}if(m&&"object"==typeof m){const{event:t,respond:o,next:r}=m;if(o&&(c=o),r){const o=oe(r,Q(s,a));if(!o){t&&(a=t);continue}const u=ee(o,Y(n));return u.length>0?se(e,n,u,t||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}t&&(a=t)}if(d&&l&&K(l,d.key,a,d.ttl),(!m||"object"==typeof m&&!m.next)&&r.config.next&&L(r.config.next)){const t=r.config.next,o=W(t),u=z(o,Q(s,a));if(u){const t=ee(u,Y(n));if(t.length>0)return se(e,n,t,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function re(e){return e&&N(e)?e:{}}async function ie(e,n){if(!n.on||!n.queueOn?.length)return;const t=n.queueOn;n.queueOn=[];for(const{type:e,data:o}of t)await E(n.on)(e,o)}function ae(e){return Boolean(e.config.init)&&!e.config.require?.length}async function ce(e,n,t){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=t;let f,l=D(n);const d=u?R({...u,full:u.full??!0}):void 0,g=_(a),m=!(Array.isArray(a)&&P(a))&&g?ee(I(g),Y(e.transformers)):void 0,p=_(c),h=!(Array.isArray(c)&&P(c))&&p?ee(I(p),Y(e.transformers)):void 0,y=e.logger.scope("source").scope(n),b={push:async(t,o={})=>{let r,i=t;const a=h??(p?ee(I(p,G(l)),Y(e.transformers)):[]);if(a.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await se(e,e.transformers,a,i,l,f,`source.${n}.before`);if(null===t.event)return{ok:!0};t.respond&&(f=t.respond),i=Array.isArray(t.event)?t.event[0]:t.event}if(d){const t=X(d,e);if(t){const o=G(l),s=M(d,t,o,`s:${n}`);if(s){if("HIT"===s.status&&void 0!==s.value&&d.full){let n=s.value;return s.rule.update&&(n=await T(n,s.rule.update,{...o,cache:{status:"HIT"}},e)),f?.(n),{ok:!0}}if("MISS"===s.status&&d.full&&f){const n=f,i=s.rule.update,a={...o,cache:{status:"MISS"}},c=s.key,u=s.rule.ttl;f=o=>{H(t,c,o,u),i?r=(async()=>{const t=await T(o,i,a,e);n(t)})():n(o)}}"MISS"!==s.status||d.full||H(t,s.key,!0,s.rule.ttl)}}}const c=m??(g?ee(I(g,G(l)),Y(e.transformers)):[]),u=await e.push(i,{...o,id:n,ingest:l,respond:f,mapping:s,preChain:c});return r&&await r,u},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:y,...r},v={collector:e,logger:y,id:n,config:s,env:b,setIngest:async t=>{if(!s.ingest)return void(l=D(n));const o=await $(t,s.ingest,{collector:e}),r=D(n);l={...r,...o,_meta:r._meta}},setRespond:e=>{f=e}},w=await E(o)(v);if(!w)return;const k=w.type||"unknown",C=e.logger.scope(k).scope(n);return b.logger=C,i&&(w.config={...w.config,primary:i}),w}async function ue(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const n=await ce(e,o,s);if(!n)continue;const r=s.config?.require;n.config={...n.config,init:!1,...r?{require:[...r]}:{}},t[o]=n}Object.assign(e.sources,t);for(const n of Object.keys(t)){const t=e.sources[n];t.init&&await E(t.init.bind(t))(),t.config.init=!0,ae(t)&&await ie(0,t)}return t}function fe(e,n){return{collector:e,logger:e.logger.scope("on").scope(String(n))}}async function le(e,n,t){const o=e.on,s=o[n]||[],r=A(t)?t:[t];r.forEach(e=>{s.push(e)}),o[n]=s,ge(e,n,r)}function de(e,n,t,o,s){if(!n.on)return;const r=n.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:t,config:n.config,data:s,env:Oe(n.env,n.config.env)};x(n.on)(o,a)}function ge(e,n,o,s){let r;switch(n){case t.Commands.Consent:r=s||e.consent;break;case t.Commands.Session:r=e.session;break;case t.Commands.User:r=s||e.user;break;case t.Commands.Custom:r=s||e.custom;break;case t.Commands.Globals:r=s||e.globals;break;case t.Commands.Config:r=s||e.config;break;case t.Commands.Ready:case t.Commands.Run:default:r=void 0}if(o.length)switch(n){case t.Commands.Consent:!function(e,n,o){const s=o||e.consent,r=fe(e,t.Commands.Consent);n.forEach(e=>{Object.keys(s).filter(n=>n in e).forEach(n=>{x(e[n])(s,r)})})}(e,o,s);break;case t.Commands.Ready:!function(e,n){if(!e.allowed)return;const o=fe(e,t.Commands.Ready);n.forEach(e=>{x(e)(void 0,o)})}(e,o);break;case t.Commands.Run:!function(e,n){if(!e.allowed)return;const o=fe(e,t.Commands.Run);n.forEach(e=>{x(e)(void 0,o)})}(e,o);break;case t.Commands.Session:!function(e,n){if(!e.session)return;const o=fe(e,t.Commands.Session);n.forEach(n=>{x(n)(e.session,o)})}(e,o);break;default:{const t=fe(e,n);o.forEach(e=>{"function"==typeof e&&x(e)(r,t)});break}}}async function me(e,n,o,s){let r,i=o||[];switch(o||(i=e.on[n]||[]),n){case t.Commands.Consent:r=s||e.consent;break;case t.Commands.Session:r=e.session;break;case t.Commands.User:r=s||e.user;break;case t.Commands.Custom:r=s||e.custom;break;case t.Commands.Globals:r=s||e.globals;break;case t.Commands.Config:r=s||e.config;break;case t.Commands.Ready:case t.Commands.Run:default:r=void 0}let a=!1;for(const t of Object.values(e.sources)){if(t.config.require?.length){const e=t.config.require.indexOf(n);-1!==e&&t.config.require.splice(e,1)}if(t.on)if(ae(t)){!1===await S(t.on)(n,r)&&(a=!0)}else t.queueOn=t.queueOn||[],t.queueOn.push({type:n,data:r})}Object.entries(e.destinations).forEach(([t,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:n,data:r});de(e,o,t,n,r)}});for(const n of Object.values(e.sources))ae(n)&&n.queueOn?.length&&await ie(0,n);return Object.keys(e.pending.destinations).length>0&&await async function(e,n){for(const[t,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(n);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[t];const i=ke(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[t]=i}}(e,n),ge(e,n,i,s),!a}function pe(e,n,t,o){if(!e)return[];if(n){const e=O(n,c(o));return e?ee(e,t):[]}return k(e)?[]:ee(e,t)}async function he(e,n,t){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=n;if(!v(o.push))return we({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=t||s||{init:!1};let f=i?{...u,before:i}:{...u};a&&(f={...f,next:a}),c&&(f={...f,cache:c});const l={...o,config:f,env:Oe(o.env,r)};let d=l.config.id;if(!d)do{d=h(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[d]);return e.destinations[d]=l,!1!==l.config.queue&&(l.queuePush=[...e.queue]),ye(e,void 0,{},{[d]:l})}async function ye(e,n,t={},o){const{allowed:s,consent:r,globals:i,user:p}=e;if(!s)return we({ok:!1});n&&(e.queue.push(n),e.status.in++),o||(o=e.destinations);const h=e.transformers?Y(e.transformers):{},b=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let b=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],n&&b.push(u(n));const v=t.ingest?{...t.ingest,_meta:{...t.ingest._meta,path:[...t.ingest._meta.path]}}:m("unknown");if(!b.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!b.length&&s.queueOn?.length){let n=!1;try{n=await be(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}return{id:o,destination:s,skipped:!n}}const w=[],C=b.filter(e=>{const n=y(s.config.consent,r,e.consent);return!n||(e.consent=n,w.push(e),!1)});if(s.queuePush.push(...C),!w.length)return{id:o,destination:s,queue:b};let O,q,A=!1;try{A=await be(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}if(!A)return{id:o,destination:s,queue:b};s.dlq||(s.dlq=[]);const x=s.config.before,S=pe(x,x&&k(x)?g(x):void 0,h,v),D=s.config.next,$=D&&k(D)?g(D):void 0,E=s.config?.cache,_=E?f(E):void 0,I=_?X(_,e):void 0;let P=0;return await Promise.all(w.map(async n=>{let r;if(n.globals=a(i,n.globals),n.user=a(p,n.user),_?.full&&I){const e=c(v,n),t=l(_,I,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}let u=n,f=t.respond;if(S.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await se(e,e.transformers,S,n,v,t.respond,`destination.${o}.before`);if(null===s.event)return n;s.respond&&(f=s.respond),u=Array.isArray(s.event)?s.event[0]:s.event}if(_&&!_.full&&I){const e=c(v,u),t=l(_,I,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}const g=Date.now();let m=!1;const y=await j(ve,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:u.name}),O=n,m=!0,s.dlq.push([u,n])})(e,s,o,u,v,f);if(P+=Date.now()-g,r&&I&&void 0===s.config.mock&&d(I,r.key,y??!0,r.ttl),void 0!==y&&(q=y),!m&&D){void 0!==y&&(v._response=y);const n=pe(D,$,h,v);if(n.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await se(e,e.transformers,n,u,v,f,`destination.${o}.next`);t.respond&&(f=t.respond)}}return n})),{id:o,destination:s,error:O,response:q,totalDuration:P}})),v={},w={},C={};for(const n of b){if(n.skipped)continue;const t={type:n.destination.type||"unknown",data:n.response};e.status.destinations[n.id]||(e.status.destinations[n.id]={count:0,failed:0,duration:0});const o=e.status.destinations[n.id],s=Date.now();n.error?(t.error=n.error,C[n.id]=t,o.failed++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?w[n.id]=t:(v[n.id]=t,o.count++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.out++)}return we({event:n,...Object.keys(v).length&&{done:v},...Object.keys(w).length&&{queued:w},...Object.keys(C).length&&{failed:C}})}async function be(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:t,config:n.config,env:Oe(n.env,n.config.env)};s.debug("init");const i=await q(n.init,"DestinationInit",e.hooks,e.logger)(r);if(!1===i)return i;if(n.config={...i||n.config,init:!0},n.queueOn?.length){const o=n.queueOn;n.queueOn=[];for(const{type:s,data:r}of o)de(e,n,t,s,r)}s.debug("init done")}return!0}async function ve(e,n,t,o,s,r){const{config:i}=n,a=await C(o,i,e);if(a.ignore)return!1;const c=n.type||"unknown",u=e.logger.scope(c),f={collector:e,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...Oe(n.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const l=a.mapping,d=a.mappingKey||"* *";if(!l?.batch||!n.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const t=await q(n.push,"DestinationPush",e.hooks,e.logger)(a.event,f);return u.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[d]){const o={key:d,events:[],data:[]};n.batches[d]={batched:o,batchFn:p(()=>{const o=n.batches[d].batched,a={collector:e,logger:u,id:t,config:i,data:void 0,rule:l,ingest:s,env:{...Oe(n.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),q(n.pushBatch,"DestinationPushBatch",e.hooks,e.logger)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},l.batch)}}const o=n.batches[d];o.batched.events.push(a.event),b(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function we(e){return{ok:!e?.failed,...e}}function ke(e){const{code:n,config:t={},env:o={},cache:s}=e,{config:r}=Z(e,"before"),{config:i}=Z({...e,config:r},"next"),a={...n.config,...t,...i};s&&(a.cache=s);const c=Oe(n.env,o);return{...n,config:a,env:c}}async function Ce(e,n={}){const t={};for(const[o,s]of Object.entries(n))s.config?.require?.length?e.pending.destinations[o]=s:t[o]=ke(s);return t}function Oe(e,n){return e||n?n?e&&w(e)&&w(n)?{...e,...n}:n:e:{}}import{assign as je,getSpanId as qe,isFunction as Ae,isString as xe}from"@walkeros/core";import{isObject as Se}from"@walkeros/core";async function De(e,n,t){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=t.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((t,o)=>setTimeout(()=>o(new Error(`${n} '${e}' destroy timed out`)),5e3))])}catch(t){i.error(`${n} '${e}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function $e(e,n,o,r){let i,a,c=!1;switch(n){case t.Commands.Config:Se(o)&&(je(e.config,o,{shallow:!1}),a=o,c=!0);break;case t.Commands.Consent:if(Se(o)){const{update:n}=s(e,o);a=n,c=!0}break;case t.Commands.Custom:Se(o)&&(e.custom=je(e.custom,o),a=o,c=!0);break;case t.Commands.Destination:Se(o)&&("code"in o&&Se(o.code)?i=await he(e,o,r):Ae(o.push)&&(i=await he(e,{code:o},r)));break;case t.Commands.Globals:Se(o)&&(e.globals=je(e.globals,o),a=o,c=!0);break;case t.Commands.On:xe(o)&&await le(e,o,r);break;case t.Commands.Ready:c=!0;break;case t.Commands.Run:i=await _e(e,o),c=!0;break;case t.Commands.Session:c=!0;break;case t.Commands.Shutdown:await async function(e){const n=e.logger;await De(e.sources,"source",n),await De(e.destinations,"destination",n),await De(e.transformers,"transformer",n),await De(e.stores,"store",n)}(e);break;case t.Commands.User:Se(o)&&(je(e.user,o,{shallow:!1}),a=o,c=!0)}return c&&(await me(e,n,void 0,a),i=await ye(e)),i||we({ok:!0})}function Ee(e,n){if(!n.name)throw new Error("Event name is required");const[t,o]=n.name.split(" ");if(!t||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${t} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:f=e.user,nested:l=[],consent:d=e.consent,id:g=qe(),trigger:m="",entity:p=t,action:h=o,timing:y=0,source:b={type:"collector",schema:"4"}}=n;return{name:r,data:i,context:a,globals:c,custom:u,user:f,nested:l,consent:d,id:g,trigger:m,entity:p,action:h,timestamp:s,timing:y,source:b}}async function _e(e,n){e.allowed=!0,e.timing=Date.now(),n&&(n.consent&&(e.consent=je(e.consent,n.consent)),n.user&&(e.user=je(e.user,n.user)),n.globals&&(e.globals=je(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=je(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await ye(e)}import{createIngest as Ie,getGrantedConsent as Pe,processEventMapping as Re,tryCatchAsync as Me,useHooks as He}from"@walkeros/core";function Te(e,n){return He(async(t,o={})=>await Me(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:f,exclude:l}=o;let d=a,g=t;const m=f||l?function(e,n,t){let o=e;return n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>n.includes(e)))),t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!t.includes(e)))),o}(e.destinations,f,l):void 0,p=i??Ie(r||"unknown");if(c){const n=await Re(g,c,e);if(n.ignore)return we({ok:!0});if(c.consent){if(!Pe(c.consent,e.consent,n.event.consent))return we({ok:!0})}g=n.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const t=await se(e,e.transformers,u,g,p,d,r?`source.${r}.next`:void 0);if(null===t.event)return we({ok:!0});if(t.respond&&(d=t.respond),Array.isArray(t.event)){const o=await Promise.all(t.event.map(async t=>{const o=n(t),s=Ee(e,o);return ye(e,s,{id:r,ingest:p,respond:d},m)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count+=t.event.length,n.lastAt=Date.now(),n.duration+=Date.now()-s}return o[0]??we({ok:!0})}g=t.event}const h=n(g),y=Ee(e,h),b=await ye(e,y,{id:r,ingest:p,respond:d},m);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count++,n.lastAt=Date.now(),n.duration+=Date.now()-s}return b},()=>we({ok:!1}))(),"Push",e.hooks,e.logger)}import{useHooks as Ge,tryCatchAsync as Be}from"@walkeros/core";import{useHooks as Ne}from"@walkeros/core";async function Ue(e){const n=r({globalsStatic:{},sessionStatic:{},run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=i(t),s={...n.globalsStatic,...e.globals},a={allowed:!1,config:n,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,hooks:e.hooks||{},logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{}},timing:Date.now(),user:e.user||{},sources:{},pending:{destinations:{}},push:void 0,command:void 0};a.push=Te(a,e=>({timing:Math.round((Date.now()-a.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.0.2"},...e})),a.command=function(e,n){return Ge(async(t,o,s)=>await Be(async()=>await n(e,t,o,s),()=>we({ok:!1}))(),"Command",e.hooks,e.logger)}(a,$e);const c=e.stores||{};if(a.stores=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await n(c),f=u.get,l=u.set,d=u.delete;u.get=Ne(f,"StoreGet",e.hooks,e.logger),u.set=Ne(l,"StoreSet",e.hooks,e.logger),u.delete=Ne(d,"StoreDelete",e.hooks,e.logger),t[o]=u}return t}(a,c),function(e,n,t){const o=new Map;for(const[t,s]of Object.entries(e))n[t]&&o.set(s,n[t]);if(0!==o.size)for(const e of[t.transformers,t.destinations,t.sources])if(e)for(const n of Object.values(e))s(n.env);function s(e){if(e)for(const[n,t]of Object.entries(e))if("object"==typeof t&&null!==t){const s=o.get(t);s&&(e[n]=s)}}}(c,a.stores,e),!a.stores.__cache){const e=new Map;a.stores.__cache={type:"memory",config:{},get:n=>{const t=e.get(n);if(t){if(!(t.expires&&Date.now()>t.expires))return t.value;e.delete(n)}},set:(n,t,o)=>{e.set(n,{value:t,expires:o?Date.now()+o:void 0})},delete:n=>{e.delete(n)}}}return a.destinations=await Ce(a,e.destinations||{}),a.transformers=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,env:r={}}=s,{config:i}=Z(s,"before"),{config:a}=Z({...s,config:i},"next"),c=Object.keys(r).length>0?{...a,env:r}:a,{cache:u}=s,f=u?{...c,cache:u}:c,l=e.logger.scope("transformer").scope(o),d={collector:e,logger:l,id:o,ingest:B(o),config:f,env:r},g=await n(d);t[o]=g}return t}(a,e.transformers||{}),a}async function Fe(e){e=e||{};const n=await Ue(e),t=(o=n,{type:"elb",config:{},push:async(e,n,t,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,n,t)}let a;if("string"==typeof e)a={name:e},n&&"object"==typeof n&&!Array.isArray(n)&&(a.data=n);else{if(!e||"object"!=typeof e)return we({ok:!1});a=e,n&&"object"==typeof n&&!Array.isArray(n)&&(a.data={...a.data||{},...n})}return s&&"object"==typeof s&&(a.context=s),r&&Array.isArray(r)&&(a.nested=r),i&&"object"==typeof i&&(a.custom=i),o.push(a)}});var o;n.sources.elb=t,await ue(n,e.sources||{});const{consent:s,user:r,globals:i,custom:a}=e;s&&await n.command("consent",s),r&&await n.command("user",r),i&&Object.assign(n.globals,i),a&&Object.assign(n.custom,a),n.config.run&&await n.command("run");let c=t.push;const u=Object.values(n.sources).filter(e=>"elb"!==e.type),f=u.find(e=>e.config.primary);return f?c=f.push:u.length>0&&(c=u[0].push),{collector:n,elb:c}}function We(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(We);const n={};for(const[t,o]of Object.entries(e))n[t]="function"==typeof o?o:We(o);return n}function ze(e){const n=[],{simulation:t,...o}=e,s=We(o);for(const e of t){const t=e.startsWith("call:")?e.slice(5):e,o=t.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const i=o[o.length-1];if(null==r||!(i in r))continue;const a=r[i];"function"==typeof a&&(r[i]=function(...e){return n.push({fn:t,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:n}}export{e as Code,n as Commands,t as Const,he as addDestination,de as callDestinationOn,$e as commonHandleCommand,Ee as createEvent,Te as createPush,we as createPushResult,be as destinationInit,ve as destinationPush,Y as extractTransformerNextMap,ie as flushSourceQueueOn,X as getCacheStore,Ce as initDestinations,ce as initSource,ue as initSources,ae as isSourceStarted,Oe as mergeEnvironments,le as on,me as onApply,s as processConsent,ye as pushToDestinations,ke as registerDestination,_e as runCollector,se as runTransformerChain,Fe as startFlow,ne as transformerInit,te as transformerPush,ee as walkChain,ze as wrapEnv};//# sourceMappingURL=index.mjs.map