@walkeros/collector 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
- import { WalkerOS, Collector, Elb, Mapping, Destination, On, Source, Transformer } from '@walkeros/core';
1
+ import * as _walkeros_core from '@walkeros/core';
2
+ import { Collector, WalkerOS, Elb, Mapping, Destination, On, Source, Transformer, Simulation } from '@walkeros/core';
2
3
 
3
4
  interface RunState {
4
5
  consent?: WalkerOS.Consent;
@@ -7,7 +8,7 @@ interface RunState {
7
8
  custom?: WalkerOS.Properties;
8
9
  }
9
10
  type HandleCommandFn<T extends Collector.Instance> = (collector: T, action: string, data?: unknown, options?: unknown) => Promise<Elb.PushResult>;
10
- type CommandTypes = 'Action' | 'Actions' | 'Config' | 'Consent' | 'Context' | 'Custom' | 'Destination' | 'Elb' | 'Globals' | 'Hook' | 'Init' | 'Link' | 'On' | 'Prefix' | 'Ready' | 'Run' | 'Session' | 'User' | 'Walker';
11
+ type CommandTypes = 'Action' | 'Actions' | 'Config' | 'Consent' | 'Context' | 'Custom' | 'Destination' | 'Elb' | 'Globals' | 'Hook' | 'Init' | 'Link' | 'On' | 'Prefix' | 'Ready' | 'Run' | 'Session' | 'Shutdown' | 'User' | 'Walker';
11
12
  type StorageType = 'cookie' | 'local' | 'session';
12
13
  interface CreateCollector {
13
14
  collector: Collector.Instance;
@@ -106,6 +107,7 @@ declare function addDestination(collector: Collector.Instance, data: Destination
106
107
  declare function pushToDestinations(collector: Collector.Instance, event?: WalkerOS.Event, meta?: {
107
108
  id?: string;
108
109
  ingest?: unknown;
110
+ respond?: _walkeros_core.RespondFn;
109
111
  }, destinations?: Collector.Destinations): Promise<Elb.PushResult>;
110
112
  /**
111
113
  * Initializes a destination.
@@ -129,7 +131,7 @@ declare function destinationInit<Destination extends Destination.Instance>(colle
129
131
  * @param ingest - Optional ingest metadata (frozen, same reference).
130
132
  * @returns Whether the event was pushed successfully.
131
133
  */
132
- declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown): Promise<unknown>;
134
+ declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown, respond?: _walkeros_core.RespondFn): Promise<unknown>;
133
135
  /**
134
136
  * Creates a standardized result object for push operations.
135
137
  *
@@ -218,40 +220,6 @@ declare function initSource(collector: Collector.Instance, sourceId: string, sou
218
220
  */
219
221
  declare function initSources(collector: Collector.Instance, sources?: Source.InitSources): Promise<Collector.Sources>;
220
222
 
221
- /**
222
- * @module transformer
223
- *
224
- * Transformer Chain Utilities
225
- * ==========================
226
- *
227
- * This module provides the unified implementation for transformer chains in walkerOS.
228
- * Chains are used at two points in the data flow:
229
- *
230
- * 1. Pre-collector chains (source.next):
231
- * Source → [Transformer Chain] → Collector
232
- * Events are processed before the collector sees them.
233
- *
234
- * 2. Post-collector chains (destination.before):
235
- * Collector → [Transformer Chain] → Destination
236
- * Events are processed before reaching specific destinations.
237
- *
238
- * Key Functions:
239
- * - extractTransformerNextMap(): Extracts next links from transformer instances
240
- * - extractChainProperty(): Unified extraction of chain properties from definitions
241
- * - walkChain(): Resolves chain IDs from starting point
242
- * - runTransformerChain(): Executes a chain of transformers on an event
243
- *
244
- * Chain Resolution:
245
- * - String start: Walk transformer.next links until chain ends
246
- * - Array start: Use array directly (explicit chain, ignores transformer.next)
247
- *
248
- * Chain Termination:
249
- * - Transformer returns false → chain stops, event is dropped
250
- * - Transformer throws error → chain stops, event is dropped
251
- * - Transformer returns void → continue with unchanged event
252
- * - Transformer returns event → continue with modified event
253
- */
254
-
255
223
  /**
256
224
  * Extracts transformer next configuration for chain walking.
257
225
  * Maps transformer instances to their config.next values.
@@ -293,4 +261,54 @@ declare function walkChain(startId: string | string[] | undefined, transformers?
293
261
  next?: string | string[];
294
262
  }>): string[];
295
263
 
296
- export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, startFlow, walkChain };
264
+ interface SimulateSource {
265
+ step: 'source';
266
+ name: string;
267
+ code: Source.Init;
268
+ config?: Partial<Source.Config>;
269
+ setup?: Source.SetupFn;
270
+ input?: unknown;
271
+ env: Source.SimulationEnv;
272
+ consent?: WalkerOS.Consent;
273
+ }
274
+ interface SimulateTransformer {
275
+ step: 'transformer';
276
+ name: string;
277
+ code: Transformer.Init;
278
+ event: WalkerOS.DeepPartialEvent;
279
+ config?: Partial<Transformer.Config>;
280
+ }
281
+ interface SimulateDestination {
282
+ step: 'destination';
283
+ name: string;
284
+ code: Destination.Instance;
285
+ event: WalkerOS.DeepPartialEvent;
286
+ config?: Partial<Destination.Config>;
287
+ consent?: WalkerOS.Consent;
288
+ /** Mock env objects (window, document, fetch, etc.) */
289
+ env?: Record<string, unknown>;
290
+ /** Dot-paths within env to wrap with call recording, e.g. ["window.gtag"] */
291
+ track?: string[];
292
+ }
293
+ type SimulateParams = SimulateSource | SimulateTransformer | SimulateDestination;
294
+
295
+ declare function simulate(params: SimulateParams): Promise<Simulation.Result>;
296
+
297
+ interface WrapResult {
298
+ /** Env with tracked paths wrapped by recording functions */
299
+ wrappedEnv: Record<string, unknown>;
300
+ /** Mutable array — calls are pushed here during step execution */
301
+ calls: Simulation.Call[];
302
+ }
303
+ /**
304
+ * Wrap tracked paths in a destination env with recording wrappers.
305
+ *
306
+ * The env object must include a `simulation: string[]` declaring which
307
+ * dot-paths to intercept. Returns a cloned env (without `simulation`)
308
+ * where those paths record every call into the `calls` array.
309
+ */
310
+ declare function wrapEnv(env: Record<string, unknown> & {
311
+ simulation: string[];
312
+ }): WrapResult;
313
+
314
+ export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type SimulateDestination, type SimulateParams, type SimulateSource, type SimulateTransformer, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, simulate, startFlow, walkChain, wrapEnv };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { WalkerOS, Collector, Elb, Mapping, Destination, On, Source, Transformer } from '@walkeros/core';
1
+ import * as _walkeros_core from '@walkeros/core';
2
+ import { Collector, WalkerOS, Elb, Mapping, Destination, On, Source, Transformer, Simulation } from '@walkeros/core';
2
3
 
3
4
  interface RunState {
4
5
  consent?: WalkerOS.Consent;
@@ -7,7 +8,7 @@ interface RunState {
7
8
  custom?: WalkerOS.Properties;
8
9
  }
9
10
  type HandleCommandFn<T extends Collector.Instance> = (collector: T, action: string, data?: unknown, options?: unknown) => Promise<Elb.PushResult>;
10
- type CommandTypes = 'Action' | 'Actions' | 'Config' | 'Consent' | 'Context' | 'Custom' | 'Destination' | 'Elb' | 'Globals' | 'Hook' | 'Init' | 'Link' | 'On' | 'Prefix' | 'Ready' | 'Run' | 'Session' | 'User' | 'Walker';
11
+ type CommandTypes = 'Action' | 'Actions' | 'Config' | 'Consent' | 'Context' | 'Custom' | 'Destination' | 'Elb' | 'Globals' | 'Hook' | 'Init' | 'Link' | 'On' | 'Prefix' | 'Ready' | 'Run' | 'Session' | 'Shutdown' | 'User' | 'Walker';
11
12
  type StorageType = 'cookie' | 'local' | 'session';
12
13
  interface CreateCollector {
13
14
  collector: Collector.Instance;
@@ -106,6 +107,7 @@ declare function addDestination(collector: Collector.Instance, data: Destination
106
107
  declare function pushToDestinations(collector: Collector.Instance, event?: WalkerOS.Event, meta?: {
107
108
  id?: string;
108
109
  ingest?: unknown;
110
+ respond?: _walkeros_core.RespondFn;
109
111
  }, destinations?: Collector.Destinations): Promise<Elb.PushResult>;
110
112
  /**
111
113
  * Initializes a destination.
@@ -129,7 +131,7 @@ declare function destinationInit<Destination extends Destination.Instance>(colle
129
131
  * @param ingest - Optional ingest metadata (frozen, same reference).
130
132
  * @returns Whether the event was pushed successfully.
131
133
  */
132
- declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown): Promise<unknown>;
134
+ declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown, respond?: _walkeros_core.RespondFn): Promise<unknown>;
133
135
  /**
134
136
  * Creates a standardized result object for push operations.
135
137
  *
@@ -218,40 +220,6 @@ declare function initSource(collector: Collector.Instance, sourceId: string, sou
218
220
  */
219
221
  declare function initSources(collector: Collector.Instance, sources?: Source.InitSources): Promise<Collector.Sources>;
220
222
 
221
- /**
222
- * @module transformer
223
- *
224
- * Transformer Chain Utilities
225
- * ==========================
226
- *
227
- * This module provides the unified implementation for transformer chains in walkerOS.
228
- * Chains are used at two points in the data flow:
229
- *
230
- * 1. Pre-collector chains (source.next):
231
- * Source → [Transformer Chain] → Collector
232
- * Events are processed before the collector sees them.
233
- *
234
- * 2. Post-collector chains (destination.before):
235
- * Collector → [Transformer Chain] → Destination
236
- * Events are processed before reaching specific destinations.
237
- *
238
- * Key Functions:
239
- * - extractTransformerNextMap(): Extracts next links from transformer instances
240
- * - extractChainProperty(): Unified extraction of chain properties from definitions
241
- * - walkChain(): Resolves chain IDs from starting point
242
- * - runTransformerChain(): Executes a chain of transformers on an event
243
- *
244
- * Chain Resolution:
245
- * - String start: Walk transformer.next links until chain ends
246
- * - Array start: Use array directly (explicit chain, ignores transformer.next)
247
- *
248
- * Chain Termination:
249
- * - Transformer returns false → chain stops, event is dropped
250
- * - Transformer throws error → chain stops, event is dropped
251
- * - Transformer returns void → continue with unchanged event
252
- * - Transformer returns event → continue with modified event
253
- */
254
-
255
223
  /**
256
224
  * Extracts transformer next configuration for chain walking.
257
225
  * Maps transformer instances to their config.next values.
@@ -293,4 +261,54 @@ declare function walkChain(startId: string | string[] | undefined, transformers?
293
261
  next?: string | string[];
294
262
  }>): string[];
295
263
 
296
- export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, startFlow, walkChain };
264
+ interface SimulateSource {
265
+ step: 'source';
266
+ name: string;
267
+ code: Source.Init;
268
+ config?: Partial<Source.Config>;
269
+ setup?: Source.SetupFn;
270
+ input?: unknown;
271
+ env: Source.SimulationEnv;
272
+ consent?: WalkerOS.Consent;
273
+ }
274
+ interface SimulateTransformer {
275
+ step: 'transformer';
276
+ name: string;
277
+ code: Transformer.Init;
278
+ event: WalkerOS.DeepPartialEvent;
279
+ config?: Partial<Transformer.Config>;
280
+ }
281
+ interface SimulateDestination {
282
+ step: 'destination';
283
+ name: string;
284
+ code: Destination.Instance;
285
+ event: WalkerOS.DeepPartialEvent;
286
+ config?: Partial<Destination.Config>;
287
+ consent?: WalkerOS.Consent;
288
+ /** Mock env objects (window, document, fetch, etc.) */
289
+ env?: Record<string, unknown>;
290
+ /** Dot-paths within env to wrap with call recording, e.g. ["window.gtag"] */
291
+ track?: string[];
292
+ }
293
+ type SimulateParams = SimulateSource | SimulateTransformer | SimulateDestination;
294
+
295
+ declare function simulate(params: SimulateParams): Promise<Simulation.Result>;
296
+
297
+ interface WrapResult {
298
+ /** Env with tracked paths wrapped by recording functions */
299
+ wrappedEnv: Record<string, unknown>;
300
+ /** Mutable array — calls are pushed here during step execution */
301
+ calls: Simulation.Call[];
302
+ }
303
+ /**
304
+ * Wrap tracked paths in a destination env with recording wrappers.
305
+ *
306
+ * The env object must include a `simulation: string[]` declaring which
307
+ * dot-paths to intercept. Returns a cloned env (without `simulation`)
308
+ * where those paths record every call into the `calls` array.
309
+ */
310
+ declare function wrapEnv(env: Record<string, unknown> & {
311
+ simulation: string[];
312
+ }): WrapResult;
313
+
314
+ export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type SimulateDestination, type SimulateParams, type SimulateSource, type SimulateTransformer, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, simulate, startFlow, walkChain, wrapEnv };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,n=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var o in t)n(e,o,{get:t[o],enumerable:!0})})(i,{Code:()=>r,Commands:()=>a,Const:()=>c,addDestination:()=>E,callDestinationOn:()=>P,commonHandleCommand:()=>G,createEvent:()=>B,createPush:()=>N,createPushResult:()=>R,destinationInit:()=>$,destinationPush:()=>H,extractTransformerNextMap:()=>y,initDestinations:()=>M,initSource:()=>j,initSources:()=>A,mergeEnvironments:()=>T,on:()=>D,onApply:()=>x,processConsent:()=>l,pushToDestinations:()=>S,registerDestination:()=>I,runCollector:()=>U,startFlow:()=>W,walkChain:()=>k}),module.exports=(e=i,((e,i,r,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of o(i))s.call(e,c)||c===r||n(e,c,{get:()=>i[c],enumerable:!(a=t(i,c))||a.enumerable});return e})(n({},"__esModule",{value:!0}),e));var r={},a={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",User:"user",Walker:"walker"},c={Commands:a,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}},u=require("@walkeros/core");function l(e,n){let t=!1;const o={};return Object.entries(n).forEach(([e,n])=>{const s=!!n;o[e]=s,t=t||s}),e.consent=(0,u.assign)(e.consent,o),{update:o,runQueue:t}}var g=require("@walkeros/core"),f=require("@walkeros/core"),d=require("@walkeros/core"),m=require("@walkeros/core"),h=require("@walkeros/core"),p=require("@walkeros/core");function b(e){return null!=e&&!1!==e&&"object"==typeof e&&!0===e.__branch}function y(e){const n={};for(const[t,o]of Object.entries(e))o.config?.next?n[t]={next:o.config.next}:n[t]={};return n}function w(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 k(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 v(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(`transformer:${o}`),i={collector:e,logger:s,id:t,config:n.config,env:q(n.config.env)};s.debug("init");const r=await(0,p.useHooks)(n.init,"TransformerInit",e.hooks)(i);if(!1===r)return!1;n.config={...r||n.config,init:!0},s.debug("init done")}return!0}async function C(e,n,t,o,s){const i=n.type||"unknown",r=e.logger.scope(`transformer:${i}`),a={collector:e,logger:r,id:t,ingest:s,config:n.config,env:q(n.config.env)};r.debug("push",{event:o.name});const c=await(0,p.useHooks)(n.push,"TransformerPush",e.hooks)(o,a);return r.debug("push done"),c}async function O(e,n,t,o,s){let i=o;for(const o of t){const t=n[o];if(!t){e.logger.info(`Transformer not found: ${o}`);continue}if(!await(0,p.tryCatchAsync)(v)(e,t,o))return e.logger.info(`Transformer init failed: ${o}`),null;const r=await(0,p.tryCatchAsync)(C,n=>(e.logger.scope(`transformer:${t.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,t,o,i,s);if(!1===r)return null;if(b(r)){const t=k(r.next,y(n));return t.length>0?O(e,n,t,r.event,s):(e.logger.info(`Branch target not found: ${JSON.stringify(r.next)}`),null)}void 0!==r&&(i=r)}return i}function q(e){return e&&(0,p.isObject)(e)?e:{}}async function j(e,n,t){const{code:o,config:s={},env:i={},primary:r,next:a}=t;let c;const u=k(a,y(e.transformers)),l=e.logger.scope("source").scope(n),g={push:(t,o={})=>e.push(t,{...o,id:n,ingest:c,mapping:s,preChain:u}),command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:l,...i},f={collector:e,logger:l,id:n,config:s,env:g,setIngest:async n=>{c=s.ingest?await(0,h.getMappingValue)(n,s.ingest,{collector:e}):void 0}},d=await(0,h.tryCatchAsync)(o)(f);if(!d)return;const m=d.type||"unknown",p=e.logger.scope(m).scope(n);return g.logger=p,r&&(d.config={...d.config,primary:r}),d}async function A(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{config:n={}}=s;if(n.require&&n.require.length>0){e.pending.sources[o]=s;continue}const i=await j(e,o,s);i&&(t[o]=i)}return t}async function D(e,n,t){const o=e.on,s=o[n]||[],i=(0,d.isArray)(t)?t:[t];i.forEach(e=>{s.push(e)}),o[n]=s,await x(e,n,i)}function P(e,n,t,o,s){if(!n.on)return;const i=n.type||"unknown",r=e.logger.scope(i).scope("on").scope(o),a={collector:e,logger:r,id:t,config:n.config,data:s,env:T(n.env,n.config.env)};(0,m.tryCatch)(n.on)(o,a)}async function x(e,n,t,o){let s,i=t||[];switch(t||(i=e.on[n]||[]),n){case c.Commands.Consent:s=o||e.consent;break;case c.Commands.Session:s=e.session;break;case c.Commands.User:s=o||e.user;break;case c.Commands.Custom:s=o||e.custom;break;case c.Commands.Globals:s=o||e.globals;break;case c.Commands.Config:s=o||e.config;break;case c.Commands.Ready:case c.Commands.Run:default:s=void 0}let r=!1;for(const t of Object.values(e.sources))if(t.on){!1===await(0,m.tryCatchAsync)(t.on)(n,s)&&(r=!0)}if(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:s});P(e,o,t,n,s)}}),(Object.keys(e.pending.sources).length>0||Object.keys(e.pending.destinations).length>0)&&await async function(e,n){for(const[t,o]of Object.entries(e.pending.sources)){if(!e.pending.sources[t]||e.sources[t])continue;const s=o.config?.require;if(!s)continue;const i=s.indexOf(n);if(-1===i)continue;if(s.splice(i,1),s.length>0)continue;delete e.pending.sources[t];const r=await j(e,t,o);r&&(e.sources[t]=r)}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 i=s.indexOf(n);if(-1===i)continue;if(s.splice(i,1),s.length>0)continue;delete e.pending.destinations[t];const r=I(o);!1!==r.config.queue&&(r.queuePush=[...e.queue]),e.destinations[t]=r}}(e,n),!i.length)return!r;switch(n){case c.Commands.Consent:!function(e,n,t){const o=t||e.consent;n.forEach(n=>{Object.keys(o).filter(e=>e in n).forEach(t=>{(0,m.tryCatch)(n[t])(e,o)})})}(e,i,o);break;case c.Commands.Ready:case c.Commands.Run:!function(e,n){e.allowed&&n.forEach(n=>{(0,m.tryCatch)(n)(e)})}(e,i);break;case c.Commands.Session:!function(e,n){if(!e.session)return;n.forEach(n=>{(0,m.tryCatch)(n)(e,e.session)})}(e,i);break;default:i.forEach(n=>{"function"==typeof n&&(0,m.tryCatch)(n)(e,s)})}return!r}async function E(e,n,t){const{code:o,config:s={},env:i={},before:r}=n;if(!(0,f.isFunction)(o.push))return R({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const a=t||s||{init:!1},c=r?{...a,before:r}:a,u={...o,config:c,env:T(o.env,i)};let l=u.config.id;if(!l)do{l=(0,f.getId)(4)}while(e.destinations[l]);return e.destinations[l]=u,!1!==u.config.queue&&(u.queuePush=[...e.queue]),S(e,void 0,{},{[l]:u})}async function S(e,n,t={},o){const{allowed:s,consent:i,globals:r,user:a}=e;if(!s)return R({ok:!1});n&&(e.queue.push(n),e.status.in++),o||(o=e.destinations);const c=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{let c=(s.queuePush||[]).map(e=>({...e,consent:i}));if(s.queuePush=[],n){const e=(0,f.clone)(n);c.push(e)}if(!c.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!c.length&&s.queueOn?.length){const n=await(0,f.tryCatchAsync)($)(e,s,o);return{id:o,destination:s,skipped:!n}}const u=[],l=c.filter(e=>{const n=(0,f.getGrantedConsent)(s.config.consent,i,e.consent);return!n||(e.consent=n,u.push(e),!1)});if(s.queuePush.push(...l),!u.length)return{id:o,destination:s,queue:c};if(!await(0,f.tryCatchAsync)($)(e,s,o))return{id:o,destination:s,queue:c};let g,d;s.dlq||(s.dlq=[]);const m=function(e,n){const t=e.config.before;return t?k(t,y(n)):[]}(s,e.transformers);let h=0;return await Promise.all(u.map(async n=>{n.globals=(0,f.assign)(r,n.globals),n.user=(0,f.assign)(a,n.user);let i=n;if(m.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await O(e,e.transformers,m,n,t.ingest);if(null===o)return n;i=o}const c=Date.now(),u=await(0,f.tryCatchAsync)(H,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:i.name}),g=n,s.dlq.push([i,n])})(e,s,o,i,t.ingest);return h+=Date.now()-c,void 0!==u&&(d=u),n})),{id:o,destination:s,error:g,response:d,totalDuration:h}})),u={},l={},g={};for(const n of c){if(n.skipped)continue;const t=n.destination,o={type:t.type||"unknown",data:n.response};e.status.destinations[n.id]||(e.status.destinations[n.id]={count:0,failed:0,duration:0});const s=e.status.destinations[n.id],i=Date.now();n.error?(o.error=n.error,g[n.id]=o,s.failed++,s.lastAt=i,s.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?(t.queuePush=(t.queuePush||[]).concat(n.queue),l[n.id]=o):(u[n.id]=o,s.count++,s.lastAt=i,s.duration+=n.totalDuration||0,e.status.out++)}return R({event:n,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(g).length&&{failed:g}})}async function $(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(o),i={collector:e,logger:s,id:t,config:n.config,env:T(n.env,n.config.env)};s.debug("init");const r=await(0,f.useHooks)(n.init,"DestinationInit",e.hooks)(i);if(!1===r)return r;if(n.config={...r||n.config,init:!0},n.queueOn?.length){const o=n.queueOn;n.queueOn=[];for(const{type:s,data:i}of o)P(e,n,t,s,i)}s.debug("init done")}return!0}async function H(e,n,t,o,s){const{config:i}=n,r=await(0,f.processEventMapping)(o,i,e);if(r.ignore)return!1;const a=n.type||"unknown",c=e.logger.scope(a),u={collector:e,logger:c,id:t,config:i,data:r.data,rule:r.mapping,ingest:s,env:T(n.env,i.env)},l=r.mapping,g=r.mappingKey||"* *";if(!l?.batch||!n.pushBatch){c.debug("push",{event:r.event.name});const t=await(0,f.useHooks)(n.push,"DestinationPush",e.hooks)(r.event,u);return c.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[g]){const o={key:g,events:[],data:[]};n.batches[g]={batched:o,batchFn:(0,f.debounce)(()=>{const o=n.batches[g].batched,r={collector:e,logger:c,id:t,config:i,data:void 0,rule:l,ingest:s,env:T(n.env,i.env)};c.debug("push batch",{events:o.events.length}),(0,f.useHooks)(n.pushBatch,"DestinationPushBatch",e.hooks)(o,r),c.debug("push batch done"),o.events=[],o.data=[]},l.batch)}}const o=n.batches[g];o.batched.events.push(r.event),(0,f.isDefined)(r.data)&&o.batched.data.push(r.data),o.batchFn()}return!0}function R(e){return{ok:!e?.failed,...e}}function I(e){const{code:n,config:t={},env:o={}}=e,{config:s}=w(e,"before"),i={...n.config,...t,...s},r=T(n.env,o);return{...n,config:i,env:r}}async function M(e,n={}){const t={};for(const[o,s]of Object.entries(n))s.config?.require?.length?e.pending.destinations[o]=s:t[o]=I(s);return t}function T(e,n){return e||n?n?e&&(0,f.isObject)(e)&&(0,f.isObject)(n)?{...e,...n}:n:e:{}}var _=require("@walkeros/core"),F=require("@walkeros/core");async function G(e,n,t,o){let s,i,r=!1,a=!1;switch(n){case c.Commands.Config:(0,F.isObject)(t)&&((0,_.assign)(e.config,t,{shallow:!1}),i=t,r=!0);break;case c.Commands.Consent:if((0,F.isObject)(t)){const{update:n,runQueue:o}=l(e,t);i=n,r=!0,a=o}break;case c.Commands.Custom:(0,F.isObject)(t)&&(e.custom=(0,_.assign)(e.custom,t),i=t,r=!0);break;case c.Commands.Destination:(0,F.isObject)(t)&&("code"in t&&(0,F.isObject)(t.code)?s=await E(e,t,o):(0,_.isFunction)(t.push)&&(s=await E(e,{code:t},o)));break;case c.Commands.Globals:(0,F.isObject)(t)&&(e.globals=(0,_.assign)(e.globals,t),i=t,r=!0);break;case c.Commands.On:(0,_.isString)(t)&&await D(e,t,o);break;case c.Commands.Ready:r=!0;break;case c.Commands.Run:s=await U(e,t),r=!0;break;case c.Commands.Session:r=!0;break;case c.Commands.User:(0,F.isObject)(t)&&((0,_.assign)(e.user,t,{shallow:!1}),i=t,r=!0)}return r&&await x(e,n,void 0,i),a&&(s=await S(e)),s||R({ok:!0})}function B(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");++e.count;const{timestamp:s=Date.now(),group:i=e.group,count:r=e.count}=n,{name:a=`${t} ${o}`,data:c={},context:u={},globals:l=e.globals,custom:g={},user:f=e.user,nested:d=[],consent:m=e.consent,id:h=`${s}-${i}-${r}`,trigger:p="",entity:b=t,action:y=o,timing:w=0,version:k={source:e.version,tagging:e.config.tagging||0},source:v={type:"collector",id:"",previous_id:""}}=n;return{name:a,data:c,context:u,globals:l,custom:g,user:f,nested:d,consent:m,id:h,trigger:p,entity:b,action:y,timestamp:s,timing:w,group:i,count:r,version:k,source:v}}async function U(e,n){e.allowed=!0,e.count=0,e.group=(0,_.getId)(),e.timing=Date.now(),n&&(n.consent&&(e.consent=(0,_.assign)(e.consent,n.consent)),n.user&&(e.user=(0,_.assign)(e.user,n.user)),n.globals&&(e.globals=(0,_.assign)(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=(0,_.assign)(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await S(e)}var L=require("@walkeros/core");function N(e,n){return(0,L.useHooks)(async(t,o={})=>await(0,L.tryCatchAsync)(async()=>{const s=Date.now(),{id:i,ingest:r,mapping:a,preChain:c}=o;let u=t;const l=r?Object.freeze(r):void 0;if(a){const n=await(0,L.processEventMapping)(u,a,e);if(n.ignore)return R({ok:!0});if(a.consent){if(!(0,L.getGrantedConsent)(a.consent,e.consent,n.event.consent))return R({ok:!0})}u=n.event}if(c?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,c,u,l);if(null===n)return R({ok:!0});u=n}const g=n(u),f=B(e,g),d=await S(e,f,{id:i,ingest:l});if(i){e.status.sources[i]||(e.status.sources[i]={count:0,duration:0});const n=e.status.sources[i];n.count++,n.lastAt=Date.now(),n.duration+=Date.now()-s}return d},()=>R({ok:!1}))(),"Push",e.hooks)}var V=require("@walkeros/core");async function Q(e){const n=(0,g.assign)({globalsStatic:{},sessionStatic:{},tagging:0,run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=(0,g.createLogger)(t),s={...n.globalsStatic,...e.globals},i={allowed:!1,config:n,consent:e.consent||{},count:0,custom:e.custom||{},destinations:{},transformers:{},globals:s,group:"",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||{},version:"2.0.0",sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};return i.push=N(i,e=>({timing:Math.round((Date.now()-i.timing)/10)/100,source:{type:"collector",id:"",previous_id:""},...e})),i.command=function(e,n){return(0,V.useHooks)(async(t,o,s)=>await(0,V.tryCatchAsync)(async()=>await n(e,t,o,s),()=>R({ok:!1}))(),"Command",e.hooks)}(i,G),i.destinations=await M(i,e.destinations||{}),i.transformers=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,env:i={}}=s,{config:r}=w(s,"next"),a=e.logger.scope("transformer").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await n(c);t[o]=u}return t}(i,e.transformers||{}),i}async function W(e){e=e||{};const n=await Q(e),t=(o=n,{type:"elb",config:{},push:async(e,n,t,s,i,r)=>{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 R({ok:!1});a=e,n&&"object"==typeof n&&!Array.isArray(n)&&(a.data={...a.data||{},...n})}return s&&"object"==typeof s&&(a.context=s),i&&Array.isArray(i)&&(a.nested=i),r&&"object"==typeof r&&(a.custom=r),o.push(a)}});var o;n.sources.elb=t;const s=await A(n,e.sources||{});Object.assign(n.sources,s);const{consent:i,user:r,globals:a,custom:c}=e;i&&await n.command("consent",i),r&&await n.command("user",r),a&&Object.assign(n.globals,a),c&&Object.assign(n.custom,c),n.config.run&&await n.command("run");let u=t.push;const l=Object.values(n.sources).filter(e=>"elb"!==e.type),g=l.find(e=>e.config.primary);return g?u=g.push:l.length>0&&(u=l[0].push),{collector:n,elb:u}}//# sourceMappingURL=index.js.map
1
+ "use strict";var n,e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r={};((n,t)=>{for(var o in t)e(n,o,{get:t[o],enumerable:!0})})(r,{Code:()=>i,Commands:()=>a,Const:()=>c,addDestination:()=>x,callDestinationOn:()=>P,commonHandleCommand:()=>B,createEvent:()=>U,createPush:()=>V,createPushResult:()=>H,destinationInit:()=>$,destinationPush:()=>R,extractTransformerNextMap:()=>b,initDestinations:()=>I,initSource:()=>j,initSources:()=>D,mergeEnvironments:()=>M,on:()=>A,onApply:()=>E,processConsent:()=>l,pushToDestinations:()=>S,registerDestination:()=>T,runCollector:()=>J,simulate:()=>Y,startFlow:()=>Q,walkChain:()=>v,wrapEnv:()=>X}),module.exports=(n=r,((n,r,i,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let c of o(r))s.call(n,c)||c===i||e(n,c,{get:()=>r[c],enumerable:!(a=t(r,c))||a.enumerable});return n})(e({},"__esModule",{value:!0}),n));var i={},a={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"},c={Commands:a,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}},u=require("@walkeros/core");function l(n,e){let t=!1;const o={};return Object.entries(e).forEach(([n,e])=>{const s=!!e;o[n]=s,t=t||s}),n.consent=(0,u.assign)(n.consent,o),{update:o,runQueue:t}}var f=require("@walkeros/core"),g=require("@walkeros/core"),d=require("@walkeros/core"),p=require("@walkeros/core"),m=require("@walkeros/core"),h=require("@walkeros/core");function y(n){return null!=n&&!1!==n&&"object"==typeof n&&!0===n.__branch}function b(n){const e={};for(const[t,o]of Object.entries(n))o.config?.next?e[t]={next:o.config.next}:e[t]={};return e}function w(n,e){const t=n.config||{},o=n[e];return void 0!==o?{config:{...t,[e]:o},chainValue:o}:{config:t,chainValue:void 0}}function v(n,e={}){if(!n)return[];if(Array.isArray(n))return n;const t=[],o=new Set;let s=n;for(;s&&e[s]&&!o.has(s);){o.add(s),t.push(s);const n=e[s].next;if(Array.isArray(n)){t.push(...n);break}s=n}return t}async function k(n,e,t){if(e.init&&!e.config.init){const o=e.type||"unknown",s=n.logger.scope(`transformer:${o}`),r={collector:n,logger:s,id:t,config:e.config,env:q(e.config.env)};s.debug("init");const i=await(0,h.useHooks)(e.init,"TransformerInit",n.hooks)(r);if(!1===i)return!1;e.config={...i||e.config,init:!0},s.debug("init done")}return!0}async function C(n,e,t,o,s,r){const i=e.type||"unknown",a=n.logger.scope(`transformer:${i}`),c={collector:n,logger:a,id:t,ingest:s,config:e.config,env:{...q(e.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,h.useHooks)(e.push,"TransformerPush",n.hooks)(o,c);return a.debug("push done"),u}async function O(n,e,t,o,s,r){let i=o;for(const o of t){const t=e[o];if(!t){n.logger.warn(`Transformer not found: ${o}`);continue}if(!await(0,h.tryCatchAsync)(k)(n,t,o))return n.logger.error(`Transformer init failed: ${o}`),null;const a=await(0,h.tryCatchAsync)(C,e=>(n.logger.scope(`transformer:${t.type||"unknown"}`).error("Push failed",{error:e}),!1))(n,t,o,i,s,r);if(!1===a)return null;if(y(a)){const t=v(a.next,b(e));return t.length>0?O(n,e,t,a.event,s,r):(n.logger.warn(`Branch target not found: ${JSON.stringify(a.next)}`),null)}void 0!==a&&(i=a)}return i}function q(n){return n&&(0,h.isObject)(n)?n:{}}async function j(n,e,t){const{code:o,config:s={},env:r={},primary:i,next:a}=t;let c,u;const l=v(a,b(n.transformers)),f=n.logger.scope("source").scope(e),g={push:(t,o={})=>n.push(t,{...o,id:e,ingest:c,respond:u,mapping:s,preChain:l}),command:n.command,sources:n.sources,elb:n.sources.elb.push,logger:f,...r},d={collector:n,logger:f,id:e,config:s,env:g,setIngest:async e=>{c=s.ingest?await(0,m.getMappingValue)(e,s.ingest,{collector:n}):void 0},setRespond:n=>{u=n}},p=await(0,m.tryCatchAsync)(o)(d);if(!p)return;const h=p.type||"unknown",y=n.logger.scope(h).scope(e);return g.logger=y,i&&(p.config={...p.config,primary:i}),p}async function D(n,e={}){const t={};for(const[o,s]of Object.entries(e)){const{config:e={}}=s;if(e.require&&e.require.length>0){n.pending.sources[o]=s;continue}const r=await j(n,o,s);r&&(t[o]=r)}return t}async function A(n,e,t){const o=n.on,s=o[e]||[],r=(0,d.isArray)(t)?t:[t];r.forEach(n=>{s.push(n)}),o[e]=s,await E(n,e,r)}function P(n,e,t,o,s){if(!e.on)return;const r=e.type||"unknown",i=n.logger.scope(r).scope("on").scope(o),a={collector:n,logger:i,id:t,config:e.config,data:s,env:M(e.env,e.config.env)};(0,p.tryCatch)(e.on)(o,a)}async function E(n,e,t,o){let s,r=t||[];switch(t||(r=n.on[e]||[]),e){case c.Commands.Consent:s=o||n.consent;break;case c.Commands.Session:s=n.session;break;case c.Commands.User:s=o||n.user;break;case c.Commands.Custom:s=o||n.custom;break;case c.Commands.Globals:s=o||n.globals;break;case c.Commands.Config:s=o||n.config;break;case c.Commands.Ready:case c.Commands.Run:default:s=void 0}let i=!1;for(const t of Object.values(n.sources))if(t.on){!1===await(0,p.tryCatchAsync)(t.on)(e,s)&&(i=!0)}if(Object.entries(n.destinations).forEach(([t,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:e,data:s});P(n,o,t,e,s)}}),(Object.keys(n.pending.sources).length>0||Object.keys(n.pending.destinations).length>0)&&await async function(n,e){for(const[t,o]of Object.entries(n.pending.sources)){if(!n.pending.sources[t]||n.sources[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(e);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete n.pending.sources[t];const i=await j(n,t,o);i&&(n.sources[t]=i)}for(const[t,o]of Object.entries(n.pending.destinations)){if(!n.pending.destinations[t]||n.destinations[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(e);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete n.pending.destinations[t];const i=T(o);!1!==i.config.queue&&(i.queuePush=[...n.queue]),n.destinations[t]=i}}(n,e),!r.length)return!i;switch(e){case c.Commands.Consent:!function(n,e,t){const o=t||n.consent;e.forEach(e=>{Object.keys(o).filter(n=>n in e).forEach(t=>{(0,p.tryCatch)(e[t])(n,o)})})}(n,r,o);break;case c.Commands.Ready:case c.Commands.Run:!function(n,e){n.allowed&&e.forEach(e=>{(0,p.tryCatch)(e)(n)})}(n,r);break;case c.Commands.Session:!function(n,e){if(!n.session)return;e.forEach(e=>{(0,p.tryCatch)(e)(n,n.session)})}(n,r);break;default:r.forEach(e=>{"function"==typeof e&&(0,p.tryCatch)(e)(n,s)})}return!i}async function x(n,e,t){const{code:o,config:s={},env:r={},before:i}=e;if(!(0,g.isFunction)(o.push))return H({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const a=t||s||{init:!1},c=i?{...a,before:i}:a,u={...o,config:c,env:M(o.env,r)};let l=u.config.id;if(!l)do{l=(0,g.getId)(4)}while(n.destinations[l]);return n.destinations[l]=u,!1!==u.config.queue&&(u.queuePush=[...n.queue]),S(n,void 0,{},{[l]:u})}async function S(n,e,t={},o){const{allowed:s,consent:r,globals:i,user:a}=n;if(!s)return H({ok:!1});e&&(n.queue.push(e),n.status.in++),o||(o=n.destinations);const c=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{let c=(s.queuePush||[]).map(n=>({...n,consent:r}));if(s.queuePush=[],e){const n=(0,g.clone)(e);c.push(n)}if(!c.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!c.length&&s.queueOn?.length){const e=await(0,g.tryCatchAsync)($)(n,s,o);return{id:o,destination:s,skipped:!e}}const u=[],l=c.filter(n=>{const e=(0,g.getGrantedConsent)(s.config.consent,r,n.consent);return!e||(n.consent=e,u.push(n),!1)});if(s.queuePush.push(...l),!u.length)return{id:o,destination:s,queue:c};if(!await(0,g.tryCatchAsync)($)(n,s,o))return{id:o,destination:s,queue:c};let f,d;s.dlq||(s.dlq=[]);const p=function(n,e){const t=n.config.before;return t?v(t,b(e)):[]}(s,n.transformers);let m=0;return await Promise.all(u.map(async e=>{e.globals=(0,g.assign)(i,e.globals),e.user=(0,g.assign)(a,e.user);let r=e;if(p.length>0&&n.transformers&&Object.keys(n.transformers).length>0){const o=await O(n,n.transformers,p,e,t.ingest,t.respond);if(null===o)return e;r=o}const c=Date.now(),u=await(0,g.tryCatchAsync)(R,e=>{const t=s.type||"unknown";n.logger.scope(t).error("Push failed",{error:e,event:r.name}),f=e,s.dlq.push([r,e])})(n,s,o,r,t.ingest,t.respond);return m+=Date.now()-c,void 0!==u&&(d=u),e})),{id:o,destination:s,error:f,response:d,totalDuration:m}})),u={},l={},f={};for(const e of c){if(e.skipped)continue;const t=e.destination,o={type:t.type||"unknown",data:e.response};n.status.destinations[e.id]||(n.status.destinations[e.id]={count:0,failed:0,duration:0});const s=n.status.destinations[e.id],r=Date.now();e.error?(o.error=e.error,f[e.id]=o,s.failed++,s.lastAt=r,s.duration+=e.totalDuration||0,n.status.failed++):e.queue&&e.queue.length?(t.queuePush=(t.queuePush||[]).concat(e.queue),l[e.id]=o):(u[e.id]=o,s.count++,s.lastAt=r,s.duration+=e.totalDuration||0,n.status.out++)}return H({event:e,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(f).length&&{failed:f}})}async function $(n,e,t){if(e.init&&!e.config.init){const o=e.type||"unknown",s=n.logger.scope(o),r={collector:n,logger:s,id:t,config:e.config,env:M(e.env,e.config.env)};s.debug("init");const i=await(0,g.useHooks)(e.init,"DestinationInit",n.hooks)(r);if(!1===i)return i;if(e.config={...i||e.config,init:!0},e.queueOn?.length){const o=e.queueOn;e.queueOn=[];for(const{type:s,data:r}of o)P(n,e,t,s,r)}s.debug("init done")}return!0}async function R(n,e,t,o,s,r){const{config:i}=e,a=await(0,g.processEventMapping)(o,i,n);if(a.ignore)return!1;const c=e.type||"unknown",u=n.logger.scope(c),l={collector:n,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...M(e.env,i.env),...r?{respond:r}:{}}},f=a.mapping,d=a.mappingKey||"* *";if(!f?.batch||!e.pushBatch){u.debug("push",{event:a.event.name});const t=await(0,g.useHooks)(e.push,"DestinationPush",n.hooks)(a.event,l);return u.debug("push done"),t}{if(e.batches=e.batches||{},!e.batches[d]){const o={key:d,events:[],data:[]};e.batches[d]={batched:o,batchFn:(0,g.debounce)(()=>{const o=e.batches[d].batched,a={collector:n,logger:u,id:t,config:i,data:void 0,rule:f,ingest:s,env:{...M(e.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,g.useHooks)(e.pushBatch,"DestinationPushBatch",n.hooks)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},f.batch)}}const o=e.batches[d];o.batched.events.push(a.event),(0,g.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function H(n){return{ok:!n?.failed,...n}}function T(n){const{code:e,config:t={},env:o={}}=n,{config:s}=w(n,"before"),r={...e.config,...t,...s},i=M(e.env,o);return{...e,config:r,env:i}}async function I(n,e={}){const t={};for(const[o,s]of Object.entries(e))s.config?.require?.length?n.pending.destinations[o]=s:t[o]=T(s);return t}function M(n,e){return n||e?e?n&&(0,g.isObject)(n)&&(0,g.isObject)(e)?{...n,...e}:e:n:{}}var _=require("@walkeros/core"),F=require("@walkeros/core"),G=5e3;async function N(n,e,t){const o=Object.entries(n).map(async([n,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=t.scope(r),a={id:n,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((t,o)=>setTimeout(()=>o(new Error(`${e} '${n}' destroy timed out`)),G))])}catch(t){i.error(`${e} '${n}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function B(n,e,t,o){let s,r,i=!1,a=!1;switch(e){case c.Commands.Config:(0,F.isObject)(t)&&((0,_.assign)(n.config,t,{shallow:!1}),r=t,i=!0);break;case c.Commands.Consent:if((0,F.isObject)(t)){const{update:e,runQueue:o}=l(n,t);r=e,i=!0,a=o}break;case c.Commands.Custom:(0,F.isObject)(t)&&(n.custom=(0,_.assign)(n.custom,t),r=t,i=!0);break;case c.Commands.Destination:(0,F.isObject)(t)&&("code"in t&&(0,F.isObject)(t.code)?s=await x(n,t,o):(0,_.isFunction)(t.push)&&(s=await x(n,{code:t},o)));break;case c.Commands.Globals:(0,F.isObject)(t)&&(n.globals=(0,_.assign)(n.globals,t),r=t,i=!0);break;case c.Commands.On:(0,_.isString)(t)&&await A(n,t,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await J(n,t),i=!0;break;case c.Commands.Session:i=!0;break;case c.Commands.Shutdown:await async function(n){const e=n.logger;await N(n.sources,"source",e),await N(n.destinations,"destination",e),await N(n.transformers,"transformer",e)}(n);break;case c.Commands.User:(0,F.isObject)(t)&&((0,_.assign)(n.user,t,{shallow:!1}),r=t,i=!0)}return i&&await E(n,e,void 0,r),a&&(s=await S(n)),s||H({ok:!0})}function U(n,e){if(!e.name)throw new Error("Event name is required");const[t,o]=e.name.split(" ");if(!t||!o)throw new Error("Event name is invalid");++n.count;const{timestamp:s=Date.now(),group:r=n.group,count:i=n.count}=e,{name:a=`${t} ${o}`,data:c={},context:u={},globals:l=n.globals,custom:f={},user:g=n.user,nested:d=[],consent:p=n.consent,id:m=`${s}-${r}-${i}`,trigger:h="",entity:y=t,action:b=o,timing:w=0,version:v={source:n.version,tagging:n.config.tagging||0},source:k={type:"collector",id:"",previous_id:""}}=e;return{name:a,data:c,context:u,globals:l,custom:f,user:g,nested:d,consent:p,id:m,trigger:h,entity:y,action:b,timestamp:s,timing:w,group:r,count:i,version:v,source:k}}async function J(n,e){n.allowed=!0,n.count=0,n.group=(0,_.getId)(),n.timing=Date.now(),e&&(e.consent&&(n.consent=(0,_.assign)(n.consent,e.consent)),e.user&&(n.user=(0,_.assign)(n.user,e.user)),e.globals&&(n.globals=(0,_.assign)(n.config.globalsStatic||{},e.globals)),e.custom&&(n.custom=(0,_.assign)(n.custom,e.custom))),Object.values(n.destinations).forEach(n=>{n.queuePush=[]}),n.queue=[],n.round++;return await S(n)}var L=require("@walkeros/core");function V(n,e){return(0,L.useHooks)(async(t,o={})=>await(0,L.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u}=o;let l=t;const f=i?Object.freeze(i):void 0;if(c){const e=await(0,L.processEventMapping)(l,c,n);if(e.ignore)return H({ok:!0});if(c.consent){if(!(0,L.getGrantedConsent)(c.consent,n.consent,e.event.consent))return H({ok:!0})}l=e.event}if(u?.length&&n.transformers&&Object.keys(n.transformers).length>0){const e=await O(n,n.transformers,u,l,f,a);if(null===e)return H({ok:!0});l=e}const g=e(l),d=U(n,g),p=await S(n,d,{id:r,ingest:f,respond:a});if(r){n.status.sources[r]||(n.status.sources[r]={count:0,duration:0});const e=n.status.sources[r];e.count++,e.lastAt=Date.now(),e.duration+=Date.now()-s}return p},()=>H({ok:!1}))(),"Push",n.hooks)}var W=require("@walkeros/core");async function z(n){const e=(0,f.assign)({globalsStatic:{},sessionStatic:{},tagging:0,run:!0},n,{merge:!1,extend:!1}),t={level:n.logger?.level,handler:n.logger?.handler},o=(0,f.createLogger)(t),s={...e.globalsStatic,...n.globals},r={allowed:!1,config:e,consent:n.consent||{},count:0,custom:n.custom||{},destinations:{},transformers:{},globals:s,group:"",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:n.user||{},version:"2.0.1",sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};return r.push=V(r,n=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",id:"",previous_id:""},...n})),r.command=function(n,e){return(0,W.useHooks)(async(t,o,s)=>await(0,W.tryCatchAsync)(async()=>await e(n,t,o,s),()=>H({ok:!1}))(),"Command",n.hooks)}(r,B),r.destinations=await I(r,n.destinations||{}),r.transformers=await async function(n,e={}){const t={};for(const[o,s]of Object.entries(e)){const{code:e,env:r={}}=s,{config:i}=w(s,"next"),a=n.logger.scope("transformer").scope(o),c={collector:n,logger:a,id:o,config:i,env:r},u=await e(c);t[o]=u}return t}(r,n.transformers||{}),r}async function Q(n){n=n||{};const e=await z(n),t=(o=e,{type:"elb",config:{},push:async(n,e,t,s,r,i)=>{if("string"==typeof n&&n.startsWith("walker ")){const s=n.replace("walker ","");return o.command(s,e,t)}let a;if("string"==typeof n)a={name:n},e&&"object"==typeof e&&!Array.isArray(e)&&(a.data=e);else{if(!n||"object"!=typeof n)return H({ok:!1});a=n,e&&"object"==typeof e&&!Array.isArray(e)&&(a.data={...a.data||{},...e})}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;e.sources.elb=t;const s=await D(e,n.sources||{});Object.assign(e.sources,s);const{consent:r,user:i,globals:a,custom:c}=n;r&&await e.command("consent",r),i&&await e.command("user",i),a&&Object.assign(e.globals,a),c&&Object.assign(e.custom,c),e.config.run&&await e.command("run");let u=t.push;const l=Object.values(e.sources).filter(n=>"elb"!==n.type),f=l.find(n=>n.config.primary);return f?u=f.push:l.length>0&&(u=l[0].push),{collector:e,elb:u}}function K(n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(n))return n.map(K);const e={};for(const[t,o]of Object.entries(n))e[t]="function"==typeof o?o:K(o);return e}function X(n){const e=[],{simulation:t,...o}=n,s=K(o);for(const n of t){const t=n.startsWith("call:")?n.slice(5):n,o=t.split(".");let r=s;for(let n=0;n<o.length-1&&null!=r[o[n]];n++)r=r[o[n]];const i=o[o.length-1];if(null==r||!(i in r))continue;const a=r[i];"function"==typeof a&&(r[i]=function(...n){return e.push({fn:t,args:n,ts:Date.now()}),a.apply(this,n)})}return{wrappedEnv:s,calls:e}}async function Y(n){const e=Date.now();try{switch(n.step){case"transformer":return await async function(n,e){const{code:t,config:o={},event:s}=n,{collector:r}=await Q({transformers:{sim:{code:t,config:o}}}),i=r.transformers?.sim;if(!i)throw new Error("Transformer failed to initialize");const a=await i.push(s,{collector:r,logger:r.logger.scope("transformer").scope("sim"),id:"sim",config:i.config,env:i.config?.env||{}});let c;c=!1===a?[]:null==a?[s]:[a];return{step:"transformer",name:n.name,events:c,calls:[],duration:Date.now()-e}}(n,e);case"source":return await async function(n,e){const{code:t,config:o={},setup:s,input:r,env:i,consent:a}=n,c={functional:!0,marketing:!0,analytics:!0};let u;if(s){const n=s(r,i);"function"==typeof n&&(u=n)}const l=[],{collector:f}=await Q({consent:a||c,sources:{sim:{code:t,config:o,env:i,next:"spy"}},transformers:{spy:{code:()=>({type:"spy",config:{},push:n=>(l.push(JSON.parse(JSON.stringify(n))),n)})}}});u&&u();return{step:"source",name:n.name,events:l,calls:[],duration:Date.now()-e}}(n,e);case"destination":return await async function(n,e){const{code:t,config:o={},event:s,consent:r,env:i,track:a}=n,c={functional:!0,marketing:!0,analytics:!0};let u=[],l=i;if(i&&a&&a.length>0){const n=X({...i,simulation:a});l=n.wrappedEnv,u=n.calls}const f={...o};l&&(f.env=l);const{collector:g}=await Q({consent:r||c,destinations:{sim:{code:t,config:f}}});return await g.push(s),{step:"destination",name:n.name,events:[],calls:u,duration:Date.now()-e}}(n,e)}}catch(t){return{step:n.step,name:n.name,events:[],calls:[],duration:Date.now()-e,error:t instanceof Error?t:new Error(String(t))}}}//# sourceMappingURL=index.js.map