@fire-spark/analytics-server 0.0.0-stage → 0.26.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/meta.js ADDED
@@ -0,0 +1,498 @@
1
+ import { n as appContextOf } from "./app-DlzC8Iq0.js";
2
+ import { a as stringifyJson, f as withProviderRetry, i as decimalText, l as postJson, n as compact, o as AnalyticsServerConfigError, r as decimalNumber } from "./json-D5hsBi3M.js";
3
+ import { n as testCodeFor } from "./provider-DIOneNqa.js";
4
+ import { providerEventName, sha256Hex } from "@fire-spark/analytics";
5
+ import { Big } from "big.js";
6
+ //#region src/meta.shared.ts
7
+ const META_PROVIDER = "meta";
8
+ const META_MAX_BATCH = 1e3;
9
+ /** Pixel and dataset ids are numeric. */
10
+ const META_NUMERIC_ID = /^\d{1,32}$/;
11
+ const GRAPH_VERSION = /^v\d{1,3}\.0$/;
12
+ const GRAPH_BASE = "https://graph.facebook.com";
13
+ /** Graph errors worth retrying: 1, 2 unknown/service; 4, 17, 32, 613 limits. */
14
+ const RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
15
+ 4,
16
+ 17,
17
+ 32,
18
+ 613
19
+ ]);
20
+ const TRANSIENT_CODES = /* @__PURE__ */ new Set([1, 2]);
21
+ const ZERO = new Big(0);
22
+ const list = (value) => {
23
+ return value ? [value] : void 0;
24
+ };
25
+ const contentsOf = (event) => {
26
+ return (event.items ?? []).map((item) => {
27
+ return compact({
28
+ id: item.id,
29
+ quantity: decimalNumber(item.quantity),
30
+ item_price: decimalNumber(item.price)
31
+ });
32
+ });
33
+ };
34
+ /** Sum of item quantities (an item without one counts as 1), unrounded. */
35
+ const numItemsOf = (event) => {
36
+ const items = event.items ?? [];
37
+ if (items.length === 0) return void 0;
38
+ const add = (sum, quantity) => sum.plus(quantity ?? "1");
39
+ return decimalNumber(items.reduce((sum, item) => add(sum, item.quantity), ZERO).toFixed());
40
+ };
41
+ const processingOptionsOf = (dpo) => {
42
+ if (!dpo) return {};
43
+ const d1 = { data_processing_options: [...dpo.options] };
44
+ const d2 = { data_processing_options_country: dpo.country };
45
+ const d3 = { data_processing_options_state: dpo.state };
46
+ return compact({
47
+ ...d1,
48
+ ...d2,
49
+ ...d3
50
+ });
51
+ };
52
+ const recordOf = (value) => {
53
+ return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
54
+ };
55
+ const textOf = (value) => {
56
+ return typeof value === "string" && value ? value : void 0;
57
+ };
58
+ const failed = (reason, retryable) => {
59
+ return {
60
+ outcome: "failed",
61
+ reason,
62
+ retryable
63
+ };
64
+ };
65
+ const classifyError = (status, error) => {
66
+ const code = typeof error.code === "number" ? error.code : void 0;
67
+ if (code === 190) return failed("auth", false);
68
+ if (code !== void 0 && code >= 200 && code <= 299) return failed("auth", false);
69
+ if (code === 100) return failed("invalid_payload", false);
70
+ if (code !== void 0 && RATE_LIMIT_CODES.has(code)) return failed("rate_limited", true);
71
+ if (code !== void 0 && TRANSIENT_CODES.has(code)) return failed("upstream_error", true);
72
+ if (error.is_transient === true) return failed("upstream_error", true);
73
+ if (status >= 500) return failed("upstream_error", true);
74
+ if (status === 429) return failed("rate_limited", true);
75
+ if (status === 401 || status === 403) return failed("auth", false);
76
+ return failed("invalid_payload", false);
77
+ };
78
+ /** Meta response → outcome, per the retry matrix. */
79
+ const classifyMetaReply = (reply, expected) => {
80
+ const body = recordOf(reply.body);
81
+ const error = recordOf(body.error);
82
+ const hasError = Object.keys(error).length > 0;
83
+ const traceId = textOf(error.fbtrace_id) ?? textOf(body.fbtrace_id);
84
+ const base = {
85
+ httpStatus: reply.status,
86
+ traceId
87
+ };
88
+ if (reply.status === 200 && !hasError) {
89
+ if (body.events_received === expected) return {
90
+ ...base,
91
+ outcome: "sent",
92
+ retryable: false
93
+ };
94
+ return {
95
+ ...base,
96
+ ...failed("upstream_error", false)
97
+ };
98
+ }
99
+ const code = typeof error.code === "number" ? error.code : void 0;
100
+ const outcome = classifyError(reply.status, error);
101
+ return {
102
+ ...base,
103
+ ...outcome,
104
+ providerCode: code
105
+ };
106
+ };
107
+ /** Checks the token and Graph version; returns the version to use. */
108
+ const assertMetaCredentials = (factory, options) => {
109
+ if (typeof options.accessToken !== "string" || !options.accessToken.trim()) throw new AnalyticsServerConfigError("META_ACCESS_TOKEN_REQUIRED", `${factory}: accessToken is required`);
110
+ const version = options.graphVersion ?? "v27.0";
111
+ if (!GRAPH_VERSION.test(version)) throw new AnalyticsServerConfigError("META_GRAPH_VERSION_INVALID", `${factory}: graphVersion must look like v27.0`);
112
+ return version;
113
+ };
114
+ /** `POST /{version}/{id}/events`. */
115
+ const metaEventsUrl = (version, id) => {
116
+ return `${GRAPH_BASE}/${version}/${id}/events`;
117
+ };
118
+ /** A `skipped` result for one event. */
119
+ const metaSkipped = (event, reason) => {
120
+ const b1 = {
121
+ provider: META_PROVIDER,
122
+ eventIds: [event.event_id]
123
+ };
124
+ const b2 = {
125
+ outcome: "skipped",
126
+ reason,
127
+ retryable: false
128
+ };
129
+ return {
130
+ ...b1,
131
+ ...b2,
132
+ attempts: 0
133
+ };
134
+ };
135
+ /**
136
+ * Posts one serialized batch with the shared retry policy and checks that
137
+ * Meta received every event. The body holds the token; never log it.
138
+ */
139
+ const sendMetaBatch = async (ctx, url, body, events) => {
140
+ const final = await withProviderRetry(ctx, async (signal) => {
141
+ const reply = await postJson(ctx, {
142
+ url,
143
+ body
144
+ }, signal);
145
+ return classifyMetaReply(reply, events.length);
146
+ });
147
+ const eventIds = events.map((event) => event.event_id);
148
+ return {
149
+ provider: META_PROVIDER,
150
+ eventIds,
151
+ ...final
152
+ };
153
+ };
154
+ //#endregion
155
+ //#region src/meta.app.ts
156
+ const PROVIDER$1 = META_PROVIDER;
157
+ const FACTORY = "metaAppConversionsApi";
158
+ /**
159
+ * Contract name → Meta app event name. The Facebook SDK logs a purchase
160
+ * as `fb_mobile_purchase`; the server copy must share that name to dedup.
161
+ */
162
+ const META_APP_EVENT_NAMES = { purchase: "fb_mobile_purchase" };
163
+ const text = (value) => {
164
+ return value === void 0 ? "" : String(value);
165
+ };
166
+ /** BCP 47 `es-EC` → Meta's `es_EC`. */
167
+ const localeOf = (locale) => {
168
+ return locale ? locale.replace(/-/g, "_") : "";
169
+ };
170
+ /** The 16 `extinfo` strings, positions fixed by Meta. */
171
+ const extinfoOf = (app) => {
172
+ const e1 = [
173
+ app.platform === "ios" ? "i2" : "a2",
174
+ app.id,
175
+ text(app.version),
176
+ text(app.build)
177
+ ];
178
+ const e2 = [
179
+ app.os_version,
180
+ text(app.device_model),
181
+ localeOf(app.locale)
182
+ ];
183
+ const e3 = [
184
+ "",
185
+ "",
186
+ text(app.screen_width),
187
+ text(app.screen_height)
188
+ ];
189
+ const e4 = [
190
+ text(app.screen_density),
191
+ "",
192
+ "",
193
+ "",
194
+ text(app.timezone)
195
+ ];
196
+ return [
197
+ ...e1,
198
+ ...e2,
199
+ ...e3,
200
+ ...e4
201
+ ];
202
+ };
203
+ /**
204
+ * `advertiser_tracking_enabled`: iOS needs ATT `authorized`; Android needs
205
+ * the device flag and an advertising id (Android rule unverified by Meta).
206
+ */
207
+ const advertiserTrackingOf = (app) => {
208
+ if (app.platform === "ios") return app.att_status === "authorized" && app.advertiser_tracking;
209
+ return app.advertiser_tracking && !!app.ad_id;
210
+ };
211
+ const flag = (value) => value ? 1 : 0;
212
+ const appDataOf = (event, app) => {
213
+ const ios = app.platform === "ios";
214
+ const allowed = !ios || app.att_status === "authorized";
215
+ const a1 = { advertiser_tracking_enabled: flag(advertiserTrackingOf(app)) };
216
+ const a2 = { application_tracking_enabled: flag(event.consent.ads) };
217
+ const a3 = { vendor_id: ios && allowed ? app.vendor_id : void 0 };
218
+ const a4 = { install_referrer: ios ? void 0 : app.install_referrer };
219
+ return compact({
220
+ ...a1,
221
+ ...a2,
222
+ ...a3,
223
+ ...a4,
224
+ extinfo: extinfoOf(app)
225
+ });
226
+ };
227
+ const userDataOf$1 = async (event, app) => {
228
+ const { user } = event;
229
+ const country = user.country_code?.toLowerCase();
230
+ const hashedCountry = country ? await sha256Hex(country) : void 0;
231
+ const u1 = {
232
+ anon_id: app.install_id,
233
+ madid: app.ad_id
234
+ };
235
+ const u2 = { client_ip_address: event.ipAddress };
236
+ const u3 = { em: list(user.email_sha256) };
237
+ const u4 = { ph: list(user.phone_digits_sha256) };
238
+ const u5 = { external_id: list(user.external_id_sha256) };
239
+ const u6 = { fn: list(user.first_name_sha256) };
240
+ const u7 = { ln: list(user.last_name_sha256) };
241
+ const u8 = { country: list(hashedCountry) };
242
+ return compact({
243
+ ...u1,
244
+ ...u2,
245
+ ...u3,
246
+ ...u4,
247
+ ...u5,
248
+ ...u6,
249
+ ...u7,
250
+ ...u8
251
+ });
252
+ };
253
+ /** Whole units; a fractional quantity (for example `"1.5"` kg) is `false`. */
254
+ const isWhole = (quantity) => {
255
+ if (quantity === void 0) return true;
256
+ try {
257
+ return new Big(quantity).mod(1).eq(0);
258
+ } catch {
259
+ return false;
260
+ }
261
+ };
262
+ /**
263
+ * `contents[].quantity` and `num_items` are integers for Meta, so a
264
+ * fractional quantity drops both rather than rounding; `value` keeps the
265
+ * exact total.
266
+ */
267
+ const customDataOf$1 = (event) => {
268
+ const items = event.items ?? [];
269
+ const whole = items.every((item) => isWhole(item.quantity));
270
+ const priced = items.length > 0 && whole;
271
+ const c1 = {
272
+ currency: event.currency,
273
+ value: decimalNumber(event.value)
274
+ };
275
+ const c2 = { order_id: event.order_id };
276
+ const c3 = { content_type: priced ? "product" : void 0 };
277
+ const c4 = { contents: priced ? contentsOf(event) : void 0 };
278
+ const c5 = { num_items: priced ? numItemsOf(event) : void 0 };
279
+ return compact({
280
+ ...c1,
281
+ ...c2,
282
+ ...c3,
283
+ ...c4,
284
+ ...c5
285
+ });
286
+ };
287
+ const eventNamesOf = (options) => {
288
+ const names = {
289
+ ...META_APP_EVENT_NAMES,
290
+ ...options.eventNames
291
+ };
292
+ return (name) => {
293
+ return Object.hasOwn(names, name) ? names[name] || void 0 : void 0;
294
+ };
295
+ };
296
+ /** One Conversions API app event (`action_source: "app"`). */
297
+ const metaAppEventOf = async (event, options) => {
298
+ const app = appContextOf(event);
299
+ if (!app) return void 0;
300
+ const e1 = {
301
+ event_name: eventNamesOf(options)(event.name),
302
+ event_time: Math.floor(event.timestamp / 1e3)
303
+ };
304
+ const e2 = {
305
+ event_id: event.event_id,
306
+ action_source: "app"
307
+ };
308
+ const e3 = { app_data: appDataOf(event, app) };
309
+ const e4 = { user_data: await userDataOf$1(event, app) };
310
+ const e5 = { custom_data: customDataOf$1(event) };
311
+ const e6 = processingOptionsOf(options.dataProcessingOptions);
312
+ return compact({
313
+ ...e1,
314
+ ...e2,
315
+ ...e3,
316
+ ...e4,
317
+ ...e5,
318
+ ...e6
319
+ });
320
+ };
321
+ const hasIdentifier = (event, app) => {
322
+ const { user } = event;
323
+ const ids = [
324
+ app.install_id,
325
+ app.ad_id,
326
+ user.email_sha256
327
+ ];
328
+ const more = [user.phone_digits_sha256, user.external_id_sha256];
329
+ return [...ids, ...more].some((id) => !!id);
330
+ };
331
+ const assertOptions$1 = (options) => {
332
+ if (!META_NUMERIC_ID.test(String(options.datasetId ?? ""))) throw new AnalyticsServerConfigError("META_DATASET_ID_INVALID", `${FACTORY}: datasetId must be the numeric dataset id`);
333
+ return assertMetaCredentials(FACTORY, options);
334
+ };
335
+ /**
336
+ * Meta Conversions API destination for app events (React Native), sent
337
+ * to the dataset linked to the app. Use it with `createAppTrackingHandler`.
338
+ * The token travels in the JSON body, never in the URL, and is never
339
+ * logged.
340
+ */
341
+ const metaAppConversionsApi = (options) => {
342
+ const url = metaEventsUrl(assertOptions$1(options), String(options.datasetId));
343
+ const accessToken = options.accessToken.trim();
344
+ const nameOf = eventNamesOf(options);
345
+ const prepare = (events) => {
346
+ const ready = [];
347
+ const skipped = [];
348
+ for (const event of events) {
349
+ const app = appContextOf(event);
350
+ if (!app) skipped.push(metaSkipped(event, "app_context_missing"));
351
+ else if (!nameOf(event.name)) skipped.push(metaSkipped(event, "not_mapped"));
352
+ else if (!hasIdentifier(event, app)) skipped.push(metaSkipped(event, "no_identifier"));
353
+ else ready.push(event);
354
+ }
355
+ return {
356
+ ready,
357
+ skipped
358
+ };
359
+ };
360
+ const send = async (events, ctx) => {
361
+ const mapped = events.map((event) => metaAppEventOf(event, options));
362
+ const data = await Promise.all(mapped);
363
+ const test_event_code = testCodeFor(PROVIDER$1, options, ctx);
364
+ const body = stringifyJson(compact({
365
+ access_token: accessToken,
366
+ test_event_code,
367
+ data
368
+ }));
369
+ return sendMetaBatch(ctx, url, body, events);
370
+ };
371
+ return {
372
+ id: PROVIDER$1,
373
+ maxBatchSize: META_MAX_BATCH,
374
+ runtimes: ["react-native"],
375
+ prepare,
376
+ send
377
+ };
378
+ };
379
+ //#endregion
380
+ //#region src/meta.ts
381
+ const PROVIDER = META_PROVIDER;
382
+ const customDataOf = (event) => {
383
+ const items = event.items ?? [];
384
+ const priced = items.length > 0;
385
+ const c1 = {
386
+ currency: event.currency,
387
+ value: decimalText(event.value)
388
+ };
389
+ const c2 = { order_id: event.order_id };
390
+ const c3 = { content_type: priced ? "product" : void 0 };
391
+ const c4 = { content_ids: items.map((item) => item.id) };
392
+ const c5 = {
393
+ contents: contentsOf(event),
394
+ num_items: numItemsOf(event)
395
+ };
396
+ return compact({
397
+ ...c1,
398
+ ...c2,
399
+ ...c3,
400
+ ...c4,
401
+ ...c5
402
+ });
403
+ };
404
+ const userDataOf = async (event) => {
405
+ const { user, click_ids: clickIds } = event;
406
+ const country = user.country_code?.toLowerCase();
407
+ const hashedCountry = country ? await sha256Hex(country) : void 0;
408
+ const u1 = { em: list(user.email_sha256) };
409
+ const u2 = { ph: list(user.phone_digits_sha256) };
410
+ const u3 = { fn: list(user.first_name_sha256) };
411
+ const u4 = { ln: list(user.last_name_sha256) };
412
+ const u5 = { external_id: list(user.external_id_sha256) };
413
+ const u6 = { country: list(hashedCountry) };
414
+ const u7 = { client_ip_address: event.ipAddress };
415
+ const u8 = { client_user_agent: event.userAgent };
416
+ const u9 = {
417
+ fbp: clickIds.fbp,
418
+ fbc: clickIds.fbc
419
+ };
420
+ return compact({
421
+ ...u1,
422
+ ...u2,
423
+ ...u3,
424
+ ...u4,
425
+ ...u5,
426
+ ...u6,
427
+ ...u7,
428
+ ...u8,
429
+ ...u9
430
+ });
431
+ };
432
+ /** One Conversions API server event. `event_name` is the pixel's name. */
433
+ const metaEventOf = async (event, options) => {
434
+ const e1 = {
435
+ event_name: providerEventName(PROVIDER, event.name),
436
+ event_time: Math.floor(event.timestamp / 1e3)
437
+ };
438
+ const e2 = {
439
+ event_id: event.event_id,
440
+ action_source: "website"
441
+ };
442
+ const e3 = { event_source_url: event.source_url };
443
+ const e4 = { referrer_url: event.referrer_url };
444
+ const e5 = { user_data: await userDataOf(event) };
445
+ const e6 = { custom_data: customDataOf(event) };
446
+ const e7 = processingOptionsOf(options.dataProcessingOptions);
447
+ return compact({
448
+ ...e1,
449
+ ...e2,
450
+ ...e3,
451
+ ...e4,
452
+ ...e5,
453
+ ...e6,
454
+ ...e7
455
+ });
456
+ };
457
+ const assertOptions = (options) => {
458
+ if (!META_NUMERIC_ID.test(String(options.pixelId ?? ""))) throw new AnalyticsServerConfigError("META_PIXEL_ID_INVALID", "metaConversionsApi: pixelId must be the numeric pixel id");
459
+ return assertMetaCredentials("metaConversionsApi", options);
460
+ };
461
+ const prepare = (events) => {
462
+ const ready = [];
463
+ const skipped = [];
464
+ for (const event of events) if (!providerEventName(PROVIDER, event.name)) skipped.push(metaSkipped(event, "not_mapped"));
465
+ else if (!event.userAgent) skipped.push(metaSkipped(event, "no_identifier"));
466
+ else ready.push(event);
467
+ return {
468
+ ready,
469
+ skipped
470
+ };
471
+ };
472
+ /**
473
+ * Meta Conversions API destination for web events. The token travels in
474
+ * the JSON body, never in the URL, and is never logged.
475
+ */
476
+ const metaConversionsApi = (options) => {
477
+ const url = metaEventsUrl(assertOptions(options), String(options.pixelId));
478
+ const accessToken = options.accessToken.trim();
479
+ const send = async (events, ctx) => {
480
+ const body = stringifyJson({
481
+ ...compact({
482
+ data: await Promise.all(events.map((e) => metaEventOf(e, options))),
483
+ test_event_code: testCodeFor(PROVIDER, options, ctx)
484
+ }),
485
+ access_token: accessToken
486
+ });
487
+ return sendMetaBatch(ctx, url, body, events);
488
+ };
489
+ return {
490
+ id: PROVIDER,
491
+ maxBatchSize: META_MAX_BATCH,
492
+ runtimes: ["web"],
493
+ prepare,
494
+ send
495
+ };
496
+ };
497
+ //#endregion
498
+ export { classifyMetaReply, metaAppConversionsApi, metaAppEventOf, metaConversionsApi, metaEventOf };
@@ -0,0 +1,22 @@
1
+ //#region src/provider.ts
2
+ /**
3
+ * The test event code to send. In production it is dropped (with a
4
+ * warning) unless `allowTestInProduction` is set, so a code left in the
5
+ * production env cannot hide real conversions in Test Events.
6
+ */
7
+ const testCodeFor = (provider, options, ctx) => {
8
+ const code = options.testEventCode?.trim();
9
+ if (!code) return void 0;
10
+ if (!ctx.isProduction || options.allowTestInProduction) return code;
11
+ const p1 = `${provider} test event code ignored in production`;
12
+ ctx.report({
13
+ level: "warning",
14
+ source: "config",
15
+ provider,
16
+ message: p1
17
+ });
18
+ };
19
+ /** Typed identity helper for a custom destination. */
20
+ const defineServerProvider = (provider) => provider;
21
+ //#endregion
22
+ export { testCodeFor as n, defineServerProvider as t };