@fire-spark/analytics 0.19.0 → 0.19.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +172 -10
  2. package/dist/index.js +408 -90
  3. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -26,11 +26,20 @@ type AnalyticsScope = {
26
26
  brand_id?: string;
27
27
  fulfillment_id?: string;
28
28
  };
29
- type DestinationProviderId = "ga4" | "meta" | "masivo" | "tiktok";
29
+ declare const BUILTIN_DESTINATION_IDS: readonly ["ga4", "meta", "masivo", "tiktok"];
30
+ type BuiltinDestinationId = (typeof BUILTIN_DESTINATION_IDS)[number];
31
+ /**
32
+ * Built-in ids keep autocomplete. Any other string is a custom destination
33
+ * created with `customAdapter()`.
34
+ */
35
+ type DestinationProviderId = BuiltinDestinationId | (string & {});
30
36
  type AnalyticsRuntime = "web" | "react-native";
37
+ /** Gate declared by a custom destination. */
38
+ type AnalyticsConsentCategory = "analytics" | "ads";
31
39
  /**
32
- * `analytics` gates GA4 and Masivo; `ads` gates Meta and TikTok. Fire Spark
33
- * ingest is first-party and is not gated.
40
+ * `analytics` gates GA4, Masivo and custom destinations that declare
41
+ * `consent: "analytics"`. `ads` gates Meta, TikTok and custom destinations
42
+ * that declare `consent: "ads"`. Fire Spark ingest is not gated.
34
43
  */
35
44
  type AnalyticsConsent = {
36
45
  analytics: boolean;
@@ -87,15 +96,84 @@ type NormalizedEvent = {
87
96
  type AnalyticsAdapter = {
88
97
  provider: DestinationProviderId;
89
98
  send: (event: NormalizedEvent) => Promise<void> | void;
90
- /** Called by `setUser()`. Ads providers receive the SHA-256 of `id`. */
99
+ /** Called by `setUser()`. Ads destinations receive the SHA-256 of `id`. */
91
100
  setUser?: (user: AnalyticsUser, runtime: AnalyticsRuntime) => Promise<void> | void;
92
101
  /** Called by `setConsent()`, also when consent is revoked. */
93
102
  setConsent?: (consent: AnalyticsConsent, runtime: AnalyticsRuntime) => Promise<void> | void;
94
103
  };
104
+ /** Who and where a custom destination's event happened. */
105
+ interface CustomDestinationIdentity {
106
+ customerId?: string;
107
+ /** SHA-256 of the user id. Set for `consent: "ads"` only. */
108
+ hashedUserId?: string;
109
+ brandId?: string;
110
+ storeId?: string;
111
+ channelId?: string;
112
+ fulfillmentId?: string;
113
+ platform?: string;
114
+ }
115
+ /**
116
+ * Raw tracked event passed to a custom `map`. Catalog renames are not
117
+ * applied. `properties` and `items` are already hashed when `consent` is
118
+ * `"ads"`.
119
+ */
120
+ interface CustomDestinationInput {
121
+ name: string;
122
+ properties: Record<string, unknown>;
123
+ items?: Array<Record<string, unknown>>;
124
+ /** ISO 4217 for this event, or the merchant currency. */
125
+ currency?: string;
126
+ eventId: string;
127
+ /** Unix seconds. */
128
+ eventTime: number;
129
+ runtime: AnalyticsRuntime;
130
+ context: Record<string, unknown>;
131
+ identity: CustomDestinationIdentity;
132
+ /** Ads destinations receive the SHA-256 of `id`. `id: null` clears it. */
133
+ user?: AnalyticsUser;
134
+ }
135
+ /**
136
+ * Money forwarded to a custom destination. `amount` is not rounded: a
137
+ * decimal string keeps every digit, and a finite number is passed through.
138
+ */
139
+ interface CustomRevenue {
140
+ currency: string;
141
+ amount: string | number;
142
+ }
143
+ /** Payload a custom `map` returns and `send` delivers. */
144
+ interface CustomDestinationEvent {
145
+ name: string;
146
+ params: Record<string, unknown>;
147
+ revenue?: CustomRevenue;
148
+ }
149
+ type CustomDestinationMap = (event: CustomDestinationInput) => CustomDestinationEvent | null;
150
+ interface CustomAnalyticsAdapter {
151
+ readonly kind: "custom";
152
+ provider: DestinationProviderId;
153
+ consent: AnalyticsConsentCategory;
154
+ map?: CustomDestinationMap;
155
+ send: (event: CustomDestinationEvent) => Promise<void> | void;
156
+ setUser?: (user: AnalyticsUser, runtime: AnalyticsRuntime) => Promise<void> | void;
157
+ setConsent?: (consent: AnalyticsConsent, runtime: AnalyticsRuntime) => Promise<void> | void;
158
+ }
159
+ type AnalyticsDestination = AnalyticsAdapter | CustomAnalyticsAdapter;
160
+ interface CustomAdapterOptions {
161
+ /** Free-form id. Must not be `ga4`, `meta`, `masivo` or `tiktok`. */
162
+ id: string;
163
+ consent: AnalyticsConsentCategory;
164
+ /**
165
+ * Maps the raw event. Return `null` to drop it. Without `map`, `send`
166
+ * receives the tracked name and properties.
167
+ */
168
+ map?: CustomDestinationMap;
169
+ send: (event: CustomDestinationEvent) => Promise<void> | void;
170
+ setUser?: CustomAnalyticsAdapter["setUser"];
171
+ setConsent?: CustomAnalyticsAdapter["setConsent"];
172
+ }
95
173
  type TrackOptions = {
96
174
  only?: DestinationProviderId[];
97
175
  exclude?: DestinationProviderId[];
98
- extra?: AnalyticsAdapter[];
176
+ extra?: AnalyticsDestination[];
99
177
  variant?: string;
100
178
  };
101
179
  type MenuViewedEvent = {
@@ -176,7 +254,7 @@ type AnalyticsConfigureOptions = {
176
254
  * currency from preferences is used instead.
177
255
  */
178
256
  currency?: string;
179
- adapters?: AnalyticsAdapter[];
257
+ adapters?: AnalyticsDestination[];
180
258
  env?: "production" | "staging";
181
259
  planVersionId?: string;
182
260
  /** Read on every event unless `setConsent()` was called. */
@@ -188,8 +266,9 @@ type AnalyticsConfigureOptions = {
188
266
  /** Recoverable problems. Default `console.warn`. */
189
267
  onWarning?: (issue: AnalyticsIssue) => void;
190
268
  /**
191
- * SHA-256 for PII sent to Meta and TikTok. Defaults to `crypto.subtle`,
192
- * or a built-in implementation when it is missing (Hermes, insecure web).
269
+ * SHA-256 for PII sent to Meta, TikTok and custom `ads` destinations.
270
+ * Defaults to `crypto.subtle`, or a built-in implementation when it is
271
+ * missing (Hermes, insecure web).
193
272
  */
194
273
  hash?: AnalyticsHash;
195
274
  /** Send the queue once it holds this many events. Default 20. */
@@ -218,9 +297,92 @@ declare const isInteractionEventName: (name: string) => name is InteractionEvent
218
297
  /** Sends the default instance queue to Fire Spark. */
219
298
  declare const flush: () => Promise<void>;
220
299
  //#endregion
300
+ //#region src/custom.d.ts
301
+ /**
302
+ * Destination the app owns. The id is any string except `ga4`, `meta`,
303
+ * `masivo` and `tiktok`. A collision or a repeated id is reported with
304
+ * `onWarning` (`source: "configure"`, or `"track"` for `extra`) and that
305
+ * adapter is skipped. `consent` selects the gate. `"ads"` hashes
306
+ * `email`, `phone`, `device_ip`, `ttclid` and the user id the same way
307
+ * Meta and TikTok do. `map` receives the raw tracked event (no catalog
308
+ * rename) and returns the payload `send` delivers, or `null` to drop it.
309
+ * Without `map`, `send` receives the tracked name and properties.
310
+ * `revenue.amount` is forwarded unchanged.
311
+ *
312
+ * The app supplies the native SDK. This package does not include one.
313
+ * Installs, ATT prompts and deep links stay in that SDK and its Expo
314
+ * config plugins.
315
+ *
316
+ * @example Singular-style mapping. The SDK below is the app's own; nothing
317
+ * here imports Singular.
318
+ * ```ts
319
+ * import { customAdapter } from "@fire-spark/analytics";
320
+ * import type { CustomDestinationEvent } from "@fire-spark/analytics";
321
+ * import type { CustomDestinationInput } from "@fire-spark/analytics";
322
+ *
323
+ * type RevenueSdk = {
324
+ * eventWithArgs: (name: string, args: Record<string, unknown>) => void;
325
+ * customRevenueWithArgs: (
326
+ * name: string,
327
+ * currency: string,
328
+ * amount: string | number,
329
+ * args: Record<string, unknown>
330
+ * ) => void;
331
+ * };
332
+ *
333
+ * const SINGULAR_EVENTS: Record<string, string> = {
334
+ * sign_up: "sng_complete_registration",
335
+ * search: "sng_search",
336
+ * product_viewed: "sng_content_view",
337
+ * add_to_cart: "sng_add_to_cart",
338
+ * view_cart: "sng_view_cart",
339
+ * begin_checkout: "sng_checkout_initiated",
340
+ * add_payment_info: "sng_add_payment_info",
341
+ * subscribe: "sng_subscribe"
342
+ * };
343
+ *
344
+ * const singularAdapter = (sdk: RevenueSdk) => {
345
+ * const map = (event: CustomDestinationInput) => {
346
+ * if (event.name === "purchase") {
347
+ * const total = event.properties.total ?? event.properties.value;
348
+ * if (typeof total !== "string" && typeof total !== "number") {
349
+ * return null;
350
+ * }
351
+ * if (!event.currency) return null;
352
+ * const first = event.properties.first_purchase === true;
353
+ * const repeatName = "sng_ecommerce_purchase";
354
+ * const firstName = "sng_ecommerce_firstpurchase";
355
+ * const name = first ? firstName : repeatName;
356
+ * const params = { order_id: event.properties.order_id };
357
+ * const revenue = { currency: event.currency, amount: total };
358
+ * return { name, params, revenue };
359
+ * }
360
+ * const name = SINGULAR_EVENTS[event.name];
361
+ * if (!name) return null;
362
+ * return { name, params: event.properties };
363
+ * };
364
+ * const send = (event: CustomDestinationEvent) => {
365
+ * const revenue = event.revenue;
366
+ * if (!revenue) {
367
+ * sdk.eventWithArgs(event.name, event.params);
368
+ * return;
369
+ * }
370
+ * sdk.customRevenueWithArgs(
371
+ * event.name,
372
+ * revenue.currency,
373
+ * revenue.amount,
374
+ * event.params
375
+ * );
376
+ * };
377
+ * return customAdapter({ id: "singular", consent: "ads", map, send });
378
+ * };
379
+ * ```
380
+ */
381
+ declare const customAdapter: (options: CustomAdapterOptions) => CustomAnalyticsAdapter;
382
+ //#endregion
221
383
  //#region src/version.d.ts
222
384
  /** Kept equal to package.json by `pnpm sdk:release` (see version.test.ts). */
223
- declare const SDK_VERSION = "0.19.0";
385
+ declare const SDK_VERSION = "0.19.2";
224
386
  //#endregion
225
387
  //#region src/compact.d.ts
226
388
  /** Drops `undefined`, `null`, non-finite numbers and functions, deeply. */
@@ -285,4 +447,4 @@ declare const analytics: {
285
447
  setConsent: typeof setConsent;
286
448
  };
287
449
  //#endregion
288
- export { Analytics, type AnalyticsAdapter, type AnalyticsAppState, type AnalyticsConfig, type AnalyticsConfigureOptions, type AnalyticsConsent, type AnalyticsContext, type AnalyticsCustomer, type AnalyticsHash, type AnalyticsIssue, type AnalyticsIssueSource, type AnalyticsPlatform, type AnalyticsRuntime, type AnalyticsSampleOptions, type AnalyticsScope, type AnalyticsStorage, type AnalyticsUser, type DestinationProviderId, FUNNEL_EVENTS, type FunnelEventName, INTERACTION_EVENTS, type InteractionEventName, type NormalizedEvent, SDK_VERSION, type TrackOptions as TrackCallOptions, type TrackOptions, type TrackEvent, analytics, compactPayload, configure, endSession, flush, hasScript, isFunnelEventName, isInteractionEventName, loadScript, reset, setConsent, setUser, track };
450
+ export { Analytics, type AnalyticsAdapter, type AnalyticsAppState, type AnalyticsConfig, type AnalyticsConfigureOptions, type AnalyticsConsent, type AnalyticsConsentCategory, type AnalyticsContext, type AnalyticsCustomer, type AnalyticsDestination, type AnalyticsHash, type AnalyticsIssue, type AnalyticsIssueSource, type AnalyticsPlatform, type AnalyticsRuntime, type AnalyticsSampleOptions, type AnalyticsScope, type AnalyticsStorage, type AnalyticsUser, BUILTIN_DESTINATION_IDS, type BuiltinDestinationId, type CustomAdapterOptions, type CustomAnalyticsAdapter, type CustomDestinationEvent, type CustomDestinationIdentity, type CustomDestinationInput, type CustomDestinationMap, type CustomRevenue, type DestinationProviderId, FUNNEL_EVENTS, type FunnelEventName, INTERACTION_EVENTS, type InteractionEventName, type NormalizedEvent, SDK_VERSION, type TrackOptions as TrackCallOptions, type TrackOptions, type TrackEvent, analytics, compactPayload, configure, customAdapter, endSession, flush, hasScript, isFunnelEventName, isInteractionEventName, loadScript, reset, setConsent, setUser, track };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { StorefrontHttpError, logError, storefrontJson } from "@fire-spark/core";
2
1
  import { Big } from "big.js";
2
+ import { StorefrontHttpError, logError, storefrontJson } from "@fire-spark/core";
3
3
  //#region src/version.ts
4
4
  /** Kept equal to package.json by `pnpm sdk:release` (see version.test.ts). */
5
- const SDK_VERSION = "0.19.0";
5
+ const SDK_VERSION = "0.19.2";
6
6
  const intlContext = () => {
7
7
  try {
8
8
  const options = Intl.DateTimeFormat().resolvedOptions();
@@ -34,6 +34,274 @@ const buildEventContext = (context) => {
34
34
  };
35
35
  };
36
36
  //#endregion
37
+ //#region src/report.ts
38
+ const PREFIX = "[@fire-spark/analytics]";
39
+ const logMasivo = (issue) => {
40
+ try {
41
+ const opts = {
42
+ alias: "masivo.destination",
43
+ detail: issue.event
44
+ };
45
+ const logged = logError(issue.error ?? issue.message, opts);
46
+ Promise.resolve(logged).catch((failure) => {
47
+ console.error(`${PREFIX} Masivo error was not logged`, failure);
48
+ });
49
+ } catch (failure) {
50
+ console.error(`${PREFIX} Masivo error was not logged`, failure);
51
+ }
52
+ };
53
+ const callHook = (hook, issue) => {
54
+ try {
55
+ hook(issue);
56
+ } catch (failure) {
57
+ console.error(`${PREFIX} onError/onWarning threw`, failure);
58
+ }
59
+ };
60
+ /** Never throws: a failing reporter must not break tracking. */
61
+ const report = (rt, issue) => {
62
+ const error = issue.level === "error";
63
+ if (error && issue.provider === "masivo") logMasivo(issue);
64
+ const hook = error ? rt.options?.onError : rt.options?.onWarning;
65
+ if (hook) {
66
+ callHook(hook, issue);
67
+ return;
68
+ }
69
+ const detail = {
70
+ provider: issue.provider,
71
+ event: issue.event
72
+ };
73
+ const args = [
74
+ `${PREFIX} ${issue.message}`,
75
+ detail,
76
+ issue.error
77
+ ];
78
+ if (error) console.error(...args);
79
+ else console.warn(...args);
80
+ };
81
+ const errorMessage = (error) => {
82
+ if (error instanceof Error) return error.message;
83
+ return String(error);
84
+ };
85
+ //#endregion
86
+ //#region src/types.ts
87
+ const FUNNEL_EVENTS = [
88
+ "menu_viewed",
89
+ "product_viewed",
90
+ "add_to_cart",
91
+ "purchase"
92
+ ];
93
+ const INTERACTION_EVENTS = ["product_visited", "category_visited"];
94
+ const BUILTIN_DESTINATION_IDS = [
95
+ "ga4",
96
+ "meta",
97
+ "masivo",
98
+ "tiktok"
99
+ ];
100
+ const isFunnelEventName = (name) => {
101
+ return FUNNEL_EVENTS.includes(name);
102
+ };
103
+ const isInteractionEventName = (name) => {
104
+ return INTERACTION_EVENTS.includes(name);
105
+ };
106
+ //#endregion
107
+ //#region src/custom.ts
108
+ const BUILTIN_IDS = new Set(BUILTIN_DESTINATION_IDS);
109
+ const isBuiltinDestination = (id) => {
110
+ return BUILTIN_IDS.has(id);
111
+ };
112
+ const isCustomAdapter = (adapter) => {
113
+ return "kind" in adapter && adapter.kind === "custom";
114
+ };
115
+ /**
116
+ * Decimal token check. The original string or number is what callers
117
+ * receive; Big.js never rewrites it (no `toFixed`, no `toString`).
118
+ */
119
+ const decimalAmount = (amount) => {
120
+ if (typeof amount === "number") {
121
+ if (!Number.isFinite(amount)) return void 0;
122
+ return amount;
123
+ }
124
+ if (typeof amount !== "string") return void 0;
125
+ const trimmed = amount.trim();
126
+ if (!trimmed) return void 0;
127
+ try {
128
+ new Big(trimmed);
129
+ } catch {
130
+ return;
131
+ }
132
+ return trimmed;
133
+ };
134
+ /** Revenue copied onto the custom event, or `undefined` when it is unusable. */
135
+ const forwardRevenue = (revenue) => {
136
+ if (!revenue) return void 0;
137
+ if (typeof revenue.currency !== "string") return void 0;
138
+ const currency = revenue.currency.trim();
139
+ if (!currency) return void 0;
140
+ const amount = decimalAmount(revenue.amount);
141
+ if (amount === void 0) return void 0;
142
+ return {
143
+ currency,
144
+ amount
145
+ };
146
+ };
147
+ const warn = (rt, source, message, provider) => {
148
+ report(rt, {
149
+ level: "warning",
150
+ source,
151
+ message,
152
+ provider
153
+ });
154
+ };
155
+ /**
156
+ * Drops custom destinations whose id is empty, reserved or repeated, and
157
+ * plain adapters whose id is not a built-in. Built-in adapters are kept,
158
+ * including two adapters that share a built-in id.
159
+ */
160
+ const acceptDestinations = (rt, adapters, source, seen) => {
161
+ const taken = new Set(seen);
162
+ const accepted = [];
163
+ for (const adapter of adapters) {
164
+ if (!isCustomAdapter(adapter)) {
165
+ const id = adapter.provider;
166
+ if (!isBuiltinDestination(id)) {
167
+ const message = `${`Destination "${id}" is not built in.`} Use customAdapter(). Skipped`;
168
+ warn(rt, source, message, id);
169
+ continue;
170
+ }
171
+ taken.add(id);
172
+ accepted.push(adapter);
173
+ continue;
174
+ }
175
+ const id = adapter.provider.trim();
176
+ if (!id) {
177
+ warn(rt, source, "Custom destination id is empty; skipped");
178
+ continue;
179
+ }
180
+ const label = `Custom destination "${id}"`;
181
+ if (isBuiltinDestination(id)) {
182
+ const message = `${label} collides with a built-in id; skipped`;
183
+ warn(rt, source, message, id);
184
+ continue;
185
+ }
186
+ if (taken.has(id)) {
187
+ const message = `${label} is already registered; skipped`;
188
+ warn(rt, source, message, id);
189
+ continue;
190
+ }
191
+ taken.add(id);
192
+ if (adapter.provider === id) {
193
+ accepted.push(adapter);
194
+ continue;
195
+ }
196
+ accepted.push({
197
+ ...adapter,
198
+ provider: id
199
+ });
200
+ }
201
+ return accepted;
202
+ };
203
+ /**
204
+ * Destination the app owns. The id is any string except `ga4`, `meta`,
205
+ * `masivo` and `tiktok`. A collision or a repeated id is reported with
206
+ * `onWarning` (`source: "configure"`, or `"track"` for `extra`) and that
207
+ * adapter is skipped. `consent` selects the gate. `"ads"` hashes
208
+ * `email`, `phone`, `device_ip`, `ttclid` and the user id the same way
209
+ * Meta and TikTok do. `map` receives the raw tracked event (no catalog
210
+ * rename) and returns the payload `send` delivers, or `null` to drop it.
211
+ * Without `map`, `send` receives the tracked name and properties.
212
+ * `revenue.amount` is forwarded unchanged.
213
+ *
214
+ * The app supplies the native SDK. This package does not include one.
215
+ * Installs, ATT prompts and deep links stay in that SDK and its Expo
216
+ * config plugins.
217
+ *
218
+ * @example Singular-style mapping. The SDK below is the app's own; nothing
219
+ * here imports Singular.
220
+ * ```ts
221
+ * import { customAdapter } from "@fire-spark/analytics";
222
+ * import type { CustomDestinationEvent } from "@fire-spark/analytics";
223
+ * import type { CustomDestinationInput } from "@fire-spark/analytics";
224
+ *
225
+ * type RevenueSdk = {
226
+ * eventWithArgs: (name: string, args: Record<string, unknown>) => void;
227
+ * customRevenueWithArgs: (
228
+ * name: string,
229
+ * currency: string,
230
+ * amount: string | number,
231
+ * args: Record<string, unknown>
232
+ * ) => void;
233
+ * };
234
+ *
235
+ * const SINGULAR_EVENTS: Record<string, string> = {
236
+ * sign_up: "sng_complete_registration",
237
+ * search: "sng_search",
238
+ * product_viewed: "sng_content_view",
239
+ * add_to_cart: "sng_add_to_cart",
240
+ * view_cart: "sng_view_cart",
241
+ * begin_checkout: "sng_checkout_initiated",
242
+ * add_payment_info: "sng_add_payment_info",
243
+ * subscribe: "sng_subscribe"
244
+ * };
245
+ *
246
+ * const singularAdapter = (sdk: RevenueSdk) => {
247
+ * const map = (event: CustomDestinationInput) => {
248
+ * if (event.name === "purchase") {
249
+ * const total = event.properties.total ?? event.properties.value;
250
+ * if (typeof total !== "string" && typeof total !== "number") {
251
+ * return null;
252
+ * }
253
+ * if (!event.currency) return null;
254
+ * const first = event.properties.first_purchase === true;
255
+ * const repeatName = "sng_ecommerce_purchase";
256
+ * const firstName = "sng_ecommerce_firstpurchase";
257
+ * const name = first ? firstName : repeatName;
258
+ * const params = { order_id: event.properties.order_id };
259
+ * const revenue = { currency: event.currency, amount: total };
260
+ * return { name, params, revenue };
261
+ * }
262
+ * const name = SINGULAR_EVENTS[event.name];
263
+ * if (!name) return null;
264
+ * return { name, params: event.properties };
265
+ * };
266
+ * const send = (event: CustomDestinationEvent) => {
267
+ * const revenue = event.revenue;
268
+ * if (!revenue) {
269
+ * sdk.eventWithArgs(event.name, event.params);
270
+ * return;
271
+ * }
272
+ * sdk.customRevenueWithArgs(
273
+ * event.name,
274
+ * revenue.currency,
275
+ * revenue.amount,
276
+ * event.params
277
+ * );
278
+ * };
279
+ * return customAdapter({ id: "singular", consent: "ads", map, send });
280
+ * };
281
+ * ```
282
+ */
283
+ const customAdapter = (options) => {
284
+ const b1 = {
285
+ kind: "custom",
286
+ provider: options.id.trim()
287
+ };
288
+ const b2 = {
289
+ consent: options.consent,
290
+ map: options.map
291
+ };
292
+ const b3 = {
293
+ send: options.send,
294
+ setUser: options.setUser
295
+ };
296
+ const b4 = { setConsent: options.setConsent };
297
+ return {
298
+ ...b1,
299
+ ...b2,
300
+ ...b3,
301
+ ...b4
302
+ };
303
+ };
304
+ //#endregion
37
305
  //#region src/sha256.ts
38
306
  const K = [
39
307
  1116352408,
@@ -235,55 +503,6 @@ const hashPiiParams = async (params, hash = defaultHash, onFailure) => {
235
503
  return next;
236
504
  };
237
505
  //#endregion
238
- //#region src/report.ts
239
- const PREFIX = "[@fire-spark/analytics]";
240
- const logMasivo = (issue) => {
241
- try {
242
- const opts = {
243
- alias: "masivo.destination",
244
- detail: issue.event
245
- };
246
- const logged = logError(issue.error ?? issue.message, opts);
247
- Promise.resolve(logged).catch((failure) => {
248
- console.error(`${PREFIX} Masivo error was not logged`, failure);
249
- });
250
- } catch (failure) {
251
- console.error(`${PREFIX} Masivo error was not logged`, failure);
252
- }
253
- };
254
- const callHook = (hook, issue) => {
255
- try {
256
- hook(issue);
257
- } catch (failure) {
258
- console.error(`${PREFIX} onError/onWarning threw`, failure);
259
- }
260
- };
261
- /** Never throws: a failing reporter must not break tracking. */
262
- const report = (rt, issue) => {
263
- const error = issue.level === "error";
264
- if (error && issue.provider === "masivo") logMasivo(issue);
265
- const hook = error ? rt.options?.onError : rt.options?.onWarning;
266
- if (hook) {
267
- callHook(hook, issue);
268
- return;
269
- }
270
- const detail = {
271
- provider: issue.provider,
272
- event: issue.event
273
- };
274
- const args = [
275
- `${PREFIX} ${issue.message}`,
276
- detail,
277
- issue.error
278
- ];
279
- if (error) console.error(...args);
280
- else console.warn(...args);
281
- };
282
- const errorMessage = (error) => {
283
- if (error instanceof Error) return error.message;
284
- return String(error);
285
- };
286
- //#endregion
287
506
  //#region ../../packages/constants/src/tracking-plan-catalog/currency.ts
288
507
  const ISO_4217_CODE = /^[A-Z]{3}$/;
289
508
  const USD_AMOUNT_PARAM_SUFFIX = "_in_usd";
@@ -1291,6 +1510,11 @@ const DEFAULT_CONSENT = {
1291
1510
  const isAdsProvider = (provider) => {
1292
1511
  return ADS_PROVIDERS.has(provider);
1293
1512
  };
1513
+ const categoryOf = (adapter) => {
1514
+ if (isCustomAdapter(adapter)) return adapter.consent;
1515
+ if (isAdsProvider(adapter.provider)) return "ads";
1516
+ return "analytics";
1517
+ };
1294
1518
  const resolveRuntime = (options) => {
1295
1519
  if (options.runtime) return options.runtime;
1296
1520
  return options.platform === "web" ? "web" : "react-native";
@@ -1299,8 +1523,9 @@ const resolveConsent = (rt) => {
1299
1523
  if (rt.consent) return rt.consent;
1300
1524
  return rt.options?.consent?.() ?? DEFAULT_CONSENT;
1301
1525
  };
1302
- const allowed = (provider, consent) => {
1303
- return isAdsProvider(provider) ? consent.ads : consent.analytics;
1526
+ const allowed = (adapter, consent) => {
1527
+ if (categoryOf(adapter) === "ads") return consent.ads;
1528
+ return consent.analytics;
1304
1529
  };
1305
1530
  /**
1306
1531
  * `setUser()` wins; otherwise a signed-in (non-anonymous) customer is the
@@ -1319,7 +1544,8 @@ const resolveMerchantContext = (options) => {
1319
1544
  };
1320
1545
  const resolveAdapters = (rt, opts) => {
1321
1546
  const constructed = rt.options?.adapters ?? [];
1322
- const extra = opts?.extra ?? [];
1547
+ const seen = new Set(constructed.map((adapter) => adapter.provider));
1548
+ const extra = acceptDestinations(rt, opts?.extra ?? [], "track", seen);
1323
1549
  const available = [...constructed, ...extra];
1324
1550
  if (opts?.only) {
1325
1551
  for (const id of opts.only) {
@@ -1354,13 +1580,56 @@ const itemsOf = (params) => {
1354
1580
  return !!row && typeof row === "object" && !Array.isArray(row);
1355
1581
  });
1356
1582
  };
1357
- /** SHA-256 of the user id for ads providers; `null` clears it. */
1358
- const userFor = async (rt, provider, user) => {
1583
+ /** SHA-256 of the user id for ads destinations; `null` clears it. */
1584
+ const userFor = async (rt, category, user) => {
1359
1585
  if (!user) return void 0;
1360
- if (!isAdsProvider(provider)) return user;
1586
+ if (category !== "ads") return user;
1361
1587
  if (typeof user.id !== "string") return { id: user.id };
1362
1588
  return { id: await hashPiiValue(user.id, hashFn(rt)) };
1363
1589
  };
1590
+ const preparedEvent = async (rt, ads, name, properties) => {
1591
+ const raw = properties ?? {};
1592
+ const hash = hashFn(rt);
1593
+ const onFailure = hashFailure(rt, name);
1594
+ const params = ads ? await hashPiiParams(raw, hash, onFailure) : raw;
1595
+ const rows = itemsOf(params);
1596
+ const hashRow = (row) => {
1597
+ return hashPiiParams(row, hash, onFailure);
1598
+ };
1599
+ return {
1600
+ params,
1601
+ items: ads && rows ? await Promise.all(rows.map(hashRow)) : rows
1602
+ };
1603
+ };
1604
+ const copyParams = (params) => {
1605
+ if (!params || Array.isArray(params)) return {};
1606
+ return { ...params };
1607
+ };
1608
+ /** Snapshot so `map` cannot change the queue, user or other destinations. */
1609
+ const copyData = (value) => {
1610
+ if (Array.isArray(value)) return value.map((item) => copyData(item));
1611
+ if (!value || typeof value !== "object") return value;
1612
+ const proto = Object.getPrototypeOf(value);
1613
+ if (proto !== Object.prototype && proto !== null) return value;
1614
+ const record = value;
1615
+ const next = {};
1616
+ for (const key of Object.keys(record)) next[key] = copyData(record[key]);
1617
+ return next;
1618
+ };
1619
+ const copyUser = (user) => {
1620
+ if (!user) return void 0;
1621
+ if (!user.properties) return { id: user.id };
1622
+ return {
1623
+ id: user.id,
1624
+ properties: { ...user.properties }
1625
+ };
1626
+ };
1627
+ const passthrough = (input) => {
1628
+ return {
1629
+ name: input.name,
1630
+ params: { ...input.properties }
1631
+ };
1632
+ };
1364
1633
  const identityOf = (rt, hashedUserId) => {
1365
1634
  const options = rt.options;
1366
1635
  const scope = options?.getScope?.() ?? {};
@@ -1384,23 +1653,17 @@ const identityOf = (rt, hashedUserId) => {
1384
1653
  ...i3
1385
1654
  };
1386
1655
  };
1387
- const sendOne = async (adapter, item, ctx) => {
1656
+ const deliverBuiltin = async (adapter, item, ctx) => {
1657
+ if (!isBuiltinDestination(adapter.provider)) return;
1388
1658
  const { rt, consent } = ctx;
1389
- if (!allowed(adapter.provider, consent)) return;
1390
- const ads = isAdsProvider(adapter.provider);
1391
- const raw = item.event.properties ?? {};
1392
- const hash = hashFn(rt);
1393
- const onFailure = hashFailure(rt, item.event.name);
1394
- const params = ads ? await hashPiiParams(raw, hash, onFailure) : raw;
1395
- const rows = itemsOf(params);
1396
- const hashRow = (row) => {
1397
- return hashPiiParams(row, hash, onFailure);
1398
- };
1399
- const items = ads && rows ? await Promise.all(rows.map(hashRow)) : rows;
1400
- const user = await userFor(rt, adapter.provider, ctx.user);
1659
+ const category = categoryOf(adapter);
1660
+ const ads = category === "ads";
1661
+ const name = item.event.name;
1662
+ const { params, items } = await preparedEvent(rt, ads, name, item.event.properties);
1663
+ const user = await userFor(rt, category, ctx.user);
1401
1664
  const hashedUserId = ads && user?.id ? user.id : void 0;
1402
1665
  const b1 = {
1403
- name: item.event.name,
1666
+ name,
1404
1667
  params,
1405
1668
  items,
1406
1669
  currency: rt.currency
@@ -1450,6 +1713,68 @@ const sendOne = async (adapter, item, ctx) => {
1450
1713
  };
1451
1714
  await adapter.send(normalized);
1452
1715
  };
1716
+ const deliverCustom = async (adapter, item, ctx) => {
1717
+ const { rt } = ctx;
1718
+ const ads = adapter.consent === "ads";
1719
+ const name = item.event.name;
1720
+ const prepared = await preparedEvent(rt, ads, name, item.event.properties);
1721
+ const user = await userFor(rt, adapter.consent, ctx.user);
1722
+ const hashed = ads && user?.id ? user.id : void 0;
1723
+ const base = ads ? copyParams(prepared.params) : prepared.params;
1724
+ if (ads && prepared.items) base.items = prepared.items;
1725
+ const properties = copyData(base);
1726
+ const safeItems = itemsOf(properties);
1727
+ const currency = isoCurrencyCode(properties.currency) ?? rt.currency;
1728
+ const identity = identityOf(rt, hashed);
1729
+ const context = copyData(ctx.context);
1730
+ const safeUser = copyUser(user);
1731
+ const c1 = {
1732
+ name,
1733
+ properties,
1734
+ items: safeItems,
1735
+ currency
1736
+ };
1737
+ const c2 = {
1738
+ eventId: item.eventId,
1739
+ eventTime: Math.floor(item.at / 1e3)
1740
+ };
1741
+ const c3 = {
1742
+ runtime: ctx.runtime,
1743
+ context,
1744
+ identity,
1745
+ user: safeUser
1746
+ };
1747
+ const input = {
1748
+ ...c1,
1749
+ ...c2,
1750
+ ...c3
1751
+ };
1752
+ const mapped = adapter.map ? adapter.map(input) : passthrough(input);
1753
+ if (!mapped) return;
1754
+ const revenue = forwardRevenue(mapped.revenue);
1755
+ if (mapped.revenue && !revenue) report(rt, {
1756
+ level: "warning",
1757
+ source: "destination",
1758
+ message: `${`Custom destination "${adapter.provider}"`} revenue was ignored`,
1759
+ provider: adapter.provider,
1760
+ event: name
1761
+ });
1762
+ const params = copyParams(mapped.params);
1763
+ const event = {
1764
+ name: mapped.name,
1765
+ params
1766
+ };
1767
+ if (revenue) event.revenue = revenue;
1768
+ await adapter.send(event);
1769
+ };
1770
+ const sendOne = async (adapter, item, ctx) => {
1771
+ if (!allowed(adapter, ctx.consent)) return;
1772
+ if (isCustomAdapter(adapter)) {
1773
+ await deliverCustom(adapter, item, ctx);
1774
+ return;
1775
+ }
1776
+ await deliverBuiltin(adapter, item, ctx);
1777
+ };
1453
1778
  const destinationError = (rt, provider, name, error) => {
1454
1779
  report(rt, {
1455
1780
  level: "error",
@@ -1496,9 +1821,9 @@ const pushUser = async (rt) => {
1496
1821
  const consent = resolveConsent(rt);
1497
1822
  const user = resolveUser(rt) ?? { id: null };
1498
1823
  const push = async (adapter) => {
1499
- if (!adapter.setUser || !allowed(adapter.provider, consent)) return;
1824
+ if (!adapter.setUser || !allowed(adapter, consent)) return;
1500
1825
  try {
1501
- const target = await userFor(rt, adapter.provider, user);
1826
+ const target = await userFor(rt, categoryOf(adapter), user);
1502
1827
  await adapter.setUser(target ?? { id: null }, runtimeId);
1503
1828
  } catch (error) {
1504
1829
  destinationError(rt, adapter.provider, "set_user", error);
@@ -1883,21 +2208,6 @@ const scheduleFlush = (rt) => {
1883
2208
  /** Sends the default instance queue to Fire Spark. */
1884
2209
  const flush = () => flushWith(runtime);
1885
2210
  //#endregion
1886
- //#region src/types.ts
1887
- const FUNNEL_EVENTS = [
1888
- "menu_viewed",
1889
- "product_viewed",
1890
- "add_to_cart",
1891
- "purchase"
1892
- ];
1893
- const INTERACTION_EVENTS = ["product_visited", "category_visited"];
1894
- const isFunnelEventName = (name) => {
1895
- return FUNNEL_EVENTS.includes(name);
1896
- };
1897
- const isInteractionEventName = (name) => {
1898
- return INTERACTION_EVENTS.includes(name);
1899
- };
1900
- //#endregion
1901
2211
  //#region src/interactions.ts
1902
2212
  const interactionKey = (name, entityId) => {
1903
2213
  return `${name}:${entityId}`;
@@ -2465,10 +2775,18 @@ const configureWith = async (rt, options) => {
2465
2775
  const channel_id = options.channel_id?.trim() ?? "";
2466
2776
  if (!channel_id) throw new Error("channel_id is required");
2467
2777
  return enqueue(rt, async () => {
2468
- rt.options = {
2778
+ const next = {
2469
2779
  ...options,
2470
2780
  channel_id
2471
2781
  };
2782
+ rt.options = next;
2783
+ if (options.adapters) {
2784
+ const accepted = acceptDestinations(rt, options.adapters, "configure");
2785
+ rt.options = {
2786
+ ...next,
2787
+ adapters: accepted
2788
+ };
2789
+ }
2472
2790
  rt.currency = resolveCurrency(rt, options.currency);
2473
2791
  const ctx = options.context;
2474
2792
  rt.context = buildEventContext(typeof ctx === "function" ? void 0 : ctx);
@@ -2651,4 +2969,4 @@ const analytics = {
2651
2969
  setConsent
2652
2970
  };
2653
2971
  //#endregion
2654
- export { Analytics, FUNNEL_EVENTS, INTERACTION_EVENTS, SDK_VERSION, analytics, compactPayload, configure, endSession, flush, hasScript, isFunnelEventName, isInteractionEventName, loadScript, reset, setConsent, setUser, track };
2972
+ export { Analytics, BUILTIN_DESTINATION_IDS, FUNNEL_EVENTS, INTERACTION_EVENTS, SDK_VERSION, analytics, compactPayload, configure, customAdapter, endSession, flush, hasScript, isFunnelEventName, isInteractionEventName, loadScript, reset, setConsent, setUser, track };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fire-spark/analytics",
3
- "version": "0.19.0",
3
+ "version": "0.19.2",
4
4
  "description": "Fire Spark storefront analytics SDK",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "big.js": "6.2.1",
21
- "@fire-spark/core": "^0.19.0"
21
+ "@fire-spark/core": "^0.19.2"
22
22
  },
23
23
  "devDependencies": {
24
24
  "tsdown": "^0.22.14",