@fire-spark/analytics 0.24.0 → 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.
Files changed (3) hide show
  1. package/dist/index.d.ts +128 -10
  2. package/dist/index.js +780 -100
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1000,7 +1000,7 @@ const transformForProvider = (provider, input) => {
1000
1000
  //#endregion
1001
1001
  //#region src/version.ts
1002
1002
  /** Kept equal to package.json by `pnpm sdk:release` (see version.test.ts). */
1003
- const SDK_VERSION = "0.24.0";
1003
+ const SDK_VERSION = "0.26.0";
1004
1004
  //#endregion
1005
1005
  //#region src/contract.ts
1006
1006
  const TRACKING_CONTRACT_VERSION = 1;
@@ -1183,7 +1183,89 @@ const resolveContractConsent = (consent) => {
1183
1183
  ad_personalization: consent.adPersonalization ?? ads
1184
1184
  };
1185
1185
  };
1186
- const contextOf$2 = (context) => {
1186
+ /** An all-zero UUID: what iOS returns after ATT denial. */
1187
+ const isZeroId = (value) => {
1188
+ return typeof value === "string" && /^[0-]+$/.test(value);
1189
+ };
1190
+ const deviceIdOf$1 = (value) => {
1191
+ const id = textOf(value);
1192
+ return id && !isZeroId(id) ? id : void 0;
1193
+ };
1194
+ /**
1195
+ * Whether app tracking data may leave the device: on iOS only with ATT
1196
+ * `authorized`; on Android always (consent is checked separately).
1197
+ */
1198
+ const appTrackingAllowed = (app) => {
1199
+ return app.platform !== "ios" || app.att_status === "authorized";
1200
+ };
1201
+ /**
1202
+ * Drops `ad_id`, `vendor_id` and the `user` hashes (keeps
1203
+ * `country_code`) when ATT does not allow tracking on iOS.
1204
+ */
1205
+ const withAttPolicy = (event) => {
1206
+ const app = event.context.app;
1207
+ if (!app || appTrackingAllowed(app)) return event;
1208
+ const kept = {
1209
+ ...app,
1210
+ advertiser_tracking: false
1211
+ };
1212
+ delete kept.ad_id;
1213
+ delete kept.vendor_id;
1214
+ const country = event.user.country_code;
1215
+ const user = country ? { country_code: country } : {};
1216
+ const context = {
1217
+ ...event.context,
1218
+ app: kept
1219
+ };
1220
+ return {
1221
+ ...event,
1222
+ user,
1223
+ context
1224
+ };
1225
+ };
1226
+ const appContextOf = (app) => {
1227
+ const a1 = {
1228
+ platform: app.platform,
1229
+ id: app.id,
1230
+ version: app.version
1231
+ };
1232
+ const a2 = {
1233
+ build: app.build,
1234
+ os_version: app.osVersion
1235
+ };
1236
+ const a3 = {
1237
+ device_model: app.deviceModel,
1238
+ locale: app.locale
1239
+ };
1240
+ const a4 = {
1241
+ timezone: app.timezone,
1242
+ screen_width: app.screenWidth
1243
+ };
1244
+ const a5 = { screen_height: app.screenHeight };
1245
+ const a6 = { screen_density: toDecimalString(app.screenDensity) };
1246
+ const a7 = { install_id: app.installId };
1247
+ const a8 = { vendor_id: deviceIdOf$1(app.vendorId) };
1248
+ const a9 = {
1249
+ ad_id: deviceIdOf$1(app.adId),
1250
+ att_status: app.attStatus
1251
+ };
1252
+ const a10 = { advertiser_tracking: app.advertiserTracking };
1253
+ const a11 = { install_referrer: app.installReferrer };
1254
+ return compactPayload$1({
1255
+ ...a1,
1256
+ ...a2,
1257
+ ...a3,
1258
+ ...a4,
1259
+ ...a5,
1260
+ ...a6,
1261
+ ...a7,
1262
+ ...a8,
1263
+ ...a9,
1264
+ ...a10,
1265
+ ...a11
1266
+ });
1267
+ };
1268
+ const contextOf$1 = (context) => {
1187
1269
  const c1 = {
1188
1270
  runtime: context.runtime,
1189
1271
  locale: context.locale
@@ -1194,11 +1276,13 @@ const contextOf$2 = (context) => {
1194
1276
  };
1195
1277
  const c3 = { brand_id: context.brandId };
1196
1278
  const c4 = { fulfillment_id: context.fulfillmentId };
1279
+ const c5 = { app: context.runtime === "react-native" && context.app ? appContextOf(context.app) : void 0 };
1197
1280
  return compactPayload$1({
1198
1281
  ...c1,
1199
1282
  ...c2,
1200
1283
  ...c3,
1201
- ...c4
1284
+ ...c4,
1285
+ ...c5
1202
1286
  });
1203
1287
  };
1204
1288
  const propertiesOf$1 = (params) => {
@@ -1220,15 +1304,17 @@ const buildTrackingEvent = (input) => {
1220
1304
  const own = isoCurrencyCode(params.currency);
1221
1305
  const fallback = isoCurrencyCode(input.currency);
1222
1306
  const currency = priced ? own ?? fallback : void 0;
1307
+ const web = input.context.runtime === "web";
1308
+ const source_url = web ? input.sourceUrl : void 0;
1223
1309
  const e1 = {
1224
1310
  event_id: input.eventId,
1225
1311
  name: input.name
1226
1312
  };
1227
1313
  const e2 = {
1228
1314
  timestamp: input.timestamp,
1229
- source_url: input.sourceUrl
1315
+ source_url
1230
1316
  };
1231
- const e3 = { referrer_url: textOf(input.referrerUrl) };
1317
+ const e3 = { referrer_url: web ? textOf(input.referrerUrl) : void 0 };
1232
1318
  const e4 = {
1233
1319
  properties: propertiesOf$1(params),
1234
1320
  currency,
@@ -1242,8 +1328,8 @@ const buildTrackingEvent = (input) => {
1242
1328
  const e7 = { click_ids: clickIdsOf$1(input.clickIds) };
1243
1329
  const e8 = { consent: resolveContractConsent(input.consent) };
1244
1330
  const e9 = { providers: [...new Set(input.providers)] };
1245
- const e10 = { context: contextOf$2(input.context) };
1246
- return compactPayload$1({
1331
+ const e10 = { context: contextOf$1(input.context) };
1332
+ const event = compactPayload$1({
1247
1333
  ...e1,
1248
1334
  ...e2,
1249
1335
  ...e3,
@@ -1255,6 +1341,7 @@ const buildTrackingEvent = (input) => {
1255
1341
  ...e9,
1256
1342
  ...e10
1257
1343
  });
1344
+ return withAttPolicy(event);
1258
1345
  };
1259
1346
  /** Wraps 1 to 20 events in a contract v1 envelope. */
1260
1347
  const buildTrackingEnvelope = (events, options = {}) => {
@@ -2705,6 +2792,15 @@ const createRuntimeState = () => {
2705
2792
  serverSide: null
2706
2793
  };
2707
2794
  const r10 = { relayBuffer: [] };
2795
+ const r11 = {
2796
+ outbox: null,
2797
+ outboxFlush: null
2798
+ };
2799
+ const r12 = {
2800
+ outboxWrite: Promise.resolve(),
2801
+ relayDisabled: false
2802
+ };
2803
+ const r13 = { relayWarnings: /* @__PURE__ */ new Set() };
2708
2804
  return {
2709
2805
  ...r1,
2710
2806
  ...r2,
@@ -2715,7 +2811,10 @@ const createRuntimeState = () => {
2715
2811
  ...r7,
2716
2812
  ...r8,
2717
2813
  ...r9,
2718
- ...r10
2814
+ ...r10,
2815
+ ...r11,
2816
+ ...r12,
2817
+ ...r13
2719
2818
  };
2720
2819
  };
2721
2820
  /** State behind the module-level `configure`/`track`/`analytics` API. */
@@ -2799,7 +2898,7 @@ const httpOptions = async (rt) => {
2799
2898
  fetchImpl: options.fetchImpl
2800
2899
  };
2801
2900
  };
2802
- const isOnline = async (rt) => {
2901
+ const isOnline$1 = async (rt) => {
2803
2902
  const check = rt.options?.isOnline;
2804
2903
  if (!check) return true;
2805
2904
  return check();
@@ -2886,7 +2985,7 @@ const removeSent = async (rt, chunk) => {
2886
2985
  rt.queue = rt.queue.filter((event) => !ids.has(event.id));
2887
2986
  await persistQueue(rt);
2888
2987
  };
2889
- const sendChunk = async (rt, chunk, keepalive) => {
2988
+ const sendChunk$1 = async (rt, chunk, keepalive) => {
2890
2989
  try {
2891
2990
  await withExponentialRetry(() => postChunk(rt, chunk, keepalive), { shouldRetry: isTransientError });
2892
2991
  await removeSent(rt, chunk);
@@ -2914,7 +3013,7 @@ const sendChunk = async (rt, chunk, keepalive) => {
2914
3013
  const flushOnce = async (rt, keepalive) => {
2915
3014
  clearTimer(rt, "flushTimer");
2916
3015
  if (!rt.options || rt.queue.length === 0) return;
2917
- if (!await isOnline(rt)) {
3016
+ if (!await isOnline$1(rt)) {
2918
3017
  scheduleRetry(rt);
2919
3018
  return;
2920
3019
  }
@@ -2922,7 +3021,7 @@ const flushOnce = async (rt, keepalive) => {
2922
3021
  for (;;) {
2923
3022
  const chunk = nextChunk(rt, keepalive);
2924
3023
  if (chunk.length === 0) break;
2925
- if (!await sendChunk(rt, chunk, keepalive)) {
3024
+ if (!await sendChunk$1(rt, chunk, keepalive)) {
2926
3025
  scheduleRetry(rt);
2927
3026
  return;
2928
3027
  }
@@ -3005,7 +3104,7 @@ const markInteraction = (state, name, entityId) => {
3005
3104
  };
3006
3105
  };
3007
3106
  //#endregion
3008
- //#region src/relay.ts
3107
+ //#region src/relay-shared.ts
3009
3108
  const RELAY_CONTRACT_HEADER = "x-firespark-contract";
3010
3109
  const RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429]);
3011
3110
  /** A relay HTTP response the client should retry with backoff. */
@@ -3024,14 +3123,7 @@ const isRetryableError = (error) => {
3024
3123
  if (error instanceof RelayHttpError) return isRetryableStatus(error.status);
3025
3124
  return true;
3026
3125
  };
3027
- const pageHref = () => {
3028
- const location = globalThis.location;
3029
- return textOf(location?.href);
3030
- };
3031
- const pageReferrer = () => {
3032
- const doc = globalThis.document;
3033
- return textOf(doc?.referrer);
3034
- };
3126
+ /** Raw personal data for `hashUserData()`; never put on the wire. */
3035
3127
  const userInput = (rt, event) => {
3036
3128
  const props = event.event.properties ?? {};
3037
3129
  const b1 = {
@@ -3050,7 +3142,8 @@ const userInput = (rt, event) => {
3050
3142
  ...b5
3051
3143
  };
3052
3144
  };
3053
- const contextOf$1 = (rt) => {
3145
+ /** Channel, store, brand and fulfillment of the event (web context). */
3146
+ const scopeContext = (rt) => {
3054
3147
  const scope = rt.options?.getScope?.() ?? {};
3055
3148
  const channelId = rt.options?.channel_id ?? scope.channel_id ?? "";
3056
3149
  const b1 = {
@@ -3068,6 +3161,371 @@ const contextOf$1 = (rt) => {
3068
3161
  fulfillmentId: scope.fulfillment_id
3069
3162
  };
3070
3163
  };
3164
+ const relayHeaders = (rt) => {
3165
+ const b1 = { "content-type": "application/json" };
3166
+ const b2 = { [RELAY_CONTRACT_HEADER]: "1" };
3167
+ return {
3168
+ ...b1,
3169
+ ...b2,
3170
+ ...rt.serverSide?.headers ?? {}
3171
+ };
3172
+ };
3173
+ const reportRelay = (rt, message, error) => {
3174
+ report(rt, {
3175
+ level: "error",
3176
+ source: "relay",
3177
+ message,
3178
+ error
3179
+ });
3180
+ };
3181
+ /** Reports a relay warning once per session for each `key`. */
3182
+ const warnRelayOnce = (rt, key, message) => {
3183
+ if (rt.relayWarnings.has(key)) return;
3184
+ rt.relayWarnings.add(key);
3185
+ report(rt, {
3186
+ level: "warning",
3187
+ source: "relay",
3188
+ message
3189
+ });
3190
+ };
3191
+ const reportRejected = (rt, body) => {
3192
+ const rejected = body?.rejected;
3193
+ if (!Array.isArray(rejected)) return;
3194
+ for (const entry of rejected) {
3195
+ const reason = textOf(entry?.reason) ?? "rejected";
3196
+ const eventId = textOf(entry?.event_id);
3197
+ const suffix = eventId ? ` (${eventId})` : "";
3198
+ reportRelay(rt, `Relay rejected an event: ${reason}${suffix}`);
3199
+ }
3200
+ };
3201
+ /** Splits per `batchSize` and `RELAY_MAX_BYTES`, keeping the order. */
3202
+ const chunkBy = (items, eventOf, batchSize) => {
3203
+ const chunks = [];
3204
+ let current = [];
3205
+ let bytes = 0;
3206
+ for (const item of items) {
3207
+ const size = JSON.stringify(eventOf(item)).length;
3208
+ const full = current.length >= batchSize || bytes + size > 6e4;
3209
+ if (current.length > 0 && full) {
3210
+ chunks.push(current);
3211
+ current = [];
3212
+ bytes = 0;
3213
+ }
3214
+ current.push(item);
3215
+ bytes += size;
3216
+ }
3217
+ if (current.length > 0) chunks.push(current);
3218
+ return chunks;
3219
+ };
3220
+ const isEntry = (value) => {
3221
+ if (!isRecord(value) || !isRecord(value.event)) return false;
3222
+ const { queued_at, attempts } = value;
3223
+ return typeof queued_at === "number" && typeof attempts === "number";
3224
+ };
3225
+ const parseEntries = (raw) => {
3226
+ if (!raw) return [];
3227
+ try {
3228
+ const parsed = JSON.parse(raw);
3229
+ return Array.isArray(parsed) ? parsed.filter(isEntry) : [];
3230
+ } catch {
3231
+ return [];
3232
+ }
3233
+ };
3234
+ const loadOutbox = async (rt) => {
3235
+ if (rt.outbox) return rt.outbox;
3236
+ const raw = await readStorage(rt, "relay-outbox").catch(() => null);
3237
+ rt.outbox ??= parseEntries(raw);
3238
+ return rt.outbox;
3239
+ };
3240
+ /** Writes the current entries; writes run one after another. */
3241
+ const persistOutbox = (rt) => {
3242
+ const write = async () => {
3243
+ const entries = rt.outbox ?? [];
3244
+ if (entries.length === 0) {
3245
+ await clearStorage(rt, "relay-outbox");
3246
+ return;
3247
+ }
3248
+ await writeStorage(rt, "relay-outbox", JSON.stringify(entries));
3249
+ };
3250
+ const next = rt.outboxWrite.then(write).catch((error) => {
3251
+ report(rt, {
3252
+ level: "warning",
3253
+ source: "relay",
3254
+ message: `Relay outbox not saved: ${errorMessage(error)}`,
3255
+ error
3256
+ });
3257
+ });
3258
+ rt.outboxWrite = next;
3259
+ return next;
3260
+ };
3261
+ const setEntries = (rt, entries) => {
3262
+ rt.outbox = entries;
3263
+ return persistOutbox(rt);
3264
+ };
3265
+ const removeEntries = (rt, gone) => {
3266
+ const drop = new Set(gone);
3267
+ const kept = (rt.outbox ?? []).filter((entry) => !drop.has(entry));
3268
+ return setEntries(rt, kept);
3269
+ };
3270
+ const warnDropped = (rt, count, why) => {
3271
+ report(rt, {
3272
+ level: "warning",
3273
+ source: "relay",
3274
+ message: `Relay outbox dropped ${count} event(s): ${why}`
3275
+ });
3276
+ };
3277
+ /** Drops entries past `maxAgeMs`: a later replay could double count. */
3278
+ const pruneExpired = async (rt, now) => {
3279
+ const relay = rt.serverSide;
3280
+ const entries = await loadOutbox(rt);
3281
+ if (!relay) return entries;
3282
+ const maxAge = relay.outbox.maxAgeMs;
3283
+ const fresh = entries.filter((entry) => now - entry.queued_at <= maxAge);
3284
+ if (fresh.length === entries.length) return entries;
3285
+ warnDropped(rt, entries.length - fresh.length, "older than the max age");
3286
+ await setEntries(rt, fresh);
3287
+ return fresh;
3288
+ };
3289
+ /**
3290
+ * Persists a hashed contract event. The oldest entries go first past
3291
+ * `outbox.maxEvents`; an event id already queued is not added twice.
3292
+ */
3293
+ const enqueueOutbox = async (rt, event, now) => {
3294
+ const relay = rt.serverSide;
3295
+ if (!relay) return;
3296
+ const entries = await pruneExpired(rt, now);
3297
+ if (entries.some((item) => item.event.event_id === event.event_id)) return;
3298
+ const next = [...entries, {
3299
+ event,
3300
+ queued_at: now,
3301
+ attempts: 0
3302
+ }];
3303
+ const overflow = next.length - relay.outbox.maxEvents;
3304
+ if (overflow > 0) warnDropped(rt, overflow, "the outbox is full");
3305
+ await setEntries(rt, overflow > 0 ? next.slice(overflow) : next);
3306
+ };
3307
+ /** Empties the outbox and its storage (consent revoked or ATT denied). */
3308
+ const purgeOutbox = async (rt) => {
3309
+ clearTimer(rt, "relayTimer");
3310
+ rt.outbox = [];
3311
+ await persistOutbox(rt);
3312
+ };
3313
+ const isOnline = async (rt) => {
3314
+ const check = rt.options?.isOnline;
3315
+ if (!check) return true;
3316
+ return check();
3317
+ };
3318
+ const tokenOf = async (rt, refresh) => {
3319
+ const getToken = rt.serverSide?.getAuthToken;
3320
+ if (!getToken) return void 0;
3321
+ try {
3322
+ return textOf(await getToken({ refresh }));
3323
+ } catch (error) {
3324
+ report(rt, {
3325
+ level: "warning",
3326
+ source: "relay",
3327
+ message: `getAuthToken failed: ${errorMessage(error)}`,
3328
+ error
3329
+ });
3330
+ return;
3331
+ }
3332
+ };
3333
+ /** Current device context, or `null` when the host has none. */
3334
+ const readAppContext = async (rt) => {
3335
+ const getContext = rt.serverSide?.getAppContext;
3336
+ if (!getContext) return null;
3337
+ try {
3338
+ return await getContext() ?? null;
3339
+ } catch (error) {
3340
+ report(rt, {
3341
+ level: "warning",
3342
+ source: "relay",
3343
+ message: `getAppContext failed: ${errorMessage(error)}`,
3344
+ error
3345
+ });
3346
+ return null;
3347
+ }
3348
+ };
3349
+ /** ATT status as it is now: an iOS denial after queueing purges. */
3350
+ const attRevoked = async (rt) => {
3351
+ const app = await readAppContext(rt);
3352
+ if (!app) return false;
3353
+ return !appTrackingAllowed({
3354
+ platform: app.platform,
3355
+ att_status: app.attStatus
3356
+ });
3357
+ };
3358
+ const postOnce = async (rt, events, token) => {
3359
+ const relay = rt.serverSide;
3360
+ const fetchImpl = rt.options?.fetchImpl ?? globalThis.fetch;
3361
+ if (!relay || typeof fetchImpl !== "function") throw new Error("No fetch implementation for the relay");
3362
+ const body = JSON.stringify(buildTrackingEnvelope(events));
3363
+ const authorization = `Bearer ${token}`;
3364
+ const headers = {
3365
+ ...relayHeaders(rt),
3366
+ authorization
3367
+ };
3368
+ const res = await fetchImpl(relay.endpoint, {
3369
+ method: "POST",
3370
+ headers,
3371
+ body
3372
+ });
3373
+ if (isRetryableStatus(res.status)) throw new RelayHttpError(res.status);
3374
+ return res;
3375
+ };
3376
+ const post = (rt, chunk, token) => {
3377
+ const events = chunk.map((entry) => entry.event);
3378
+ const b1 = {
3379
+ extraAttempts: 2,
3380
+ baseDelayMs: 300
3381
+ };
3382
+ const run = () => postOnce(rt, events, token);
3383
+ return withExponentialRetry(run, {
3384
+ ...b1,
3385
+ shouldRetry: isRetryableError
3386
+ });
3387
+ };
3388
+ /** Counts an auth failure; entries at the limit are dropped. */
3389
+ const countAuthFailure = async (rt, chunk) => {
3390
+ const failed = new Set(chunk);
3391
+ const kept = [];
3392
+ let dropped = 0;
3393
+ for (const entry of rt.outbox ?? []) {
3394
+ if (!failed.has(entry)) {
3395
+ kept.push(entry);
3396
+ continue;
3397
+ }
3398
+ const attempts = entry.attempts + 1;
3399
+ if (attempts >= 3) dropped += 1;
3400
+ else kept.push({
3401
+ ...entry,
3402
+ attempts
3403
+ });
3404
+ }
3405
+ if (dropped > 0) reportRelay(rt, `Relay refused the customer token 3 times; ${dropped} event(s) dropped`);
3406
+ await setEntries(rt, kept);
3407
+ };
3408
+ const onAuthFailure = async (rt, chunk, auth) => {
3409
+ if (!auth.refreshed) {
3410
+ auth.refreshed = true;
3411
+ const fresh = await tokenOf(rt, true);
3412
+ if (fresh) {
3413
+ auth.token = fresh;
3414
+ return sendChunk(rt, chunk, auth);
3415
+ }
3416
+ }
3417
+ await countAuthFailure(rt, chunk);
3418
+ return "stop";
3419
+ };
3420
+ const onTooLarge = async (rt, chunk, auth) => {
3421
+ if (chunk.length === 1) {
3422
+ reportRelay(rt, "Relay responded 413 for one event; it was dropped");
3423
+ await removeEntries(rt, chunk);
3424
+ return "next";
3425
+ }
3426
+ const half = Math.ceil(chunk.length / 2);
3427
+ if (await sendChunk(rt, chunk.slice(0, half), auth) === "stop") return "stop";
3428
+ return sendChunk(rt, chunk.slice(half), auth);
3429
+ };
3430
+ /**
3431
+ * `202` (any `2xx`) removes accepted and rejected events (a rejection is
3432
+ * final).
3433
+ * `401`/`403` refresh the token once, then count toward the auth limit.
3434
+ * `404` turns the relay off for the session and keeps the outbox. `413`
3435
+ * splits. `408`/`429`/`5xx`/network keep the outbox for a later flush.
3436
+ * Anything else (`400`, `422`, ...) drops the chunk.
3437
+ */
3438
+ const sendChunk = async (rt, chunk, auth) => {
3439
+ let res;
3440
+ try {
3441
+ res = await post(rt, chunk, auth.token);
3442
+ } catch (error) {
3443
+ report(rt, {
3444
+ level: "warning",
3445
+ source: "relay",
3446
+ message: `${`Relay request failed: ${errorMessage(error)}`}; ${chunk.length} event(s) kept for a retry`,
3447
+ error
3448
+ });
3449
+ return "stop";
3450
+ }
3451
+ const status = res.status;
3452
+ if (status >= 200 && status < 300) {
3453
+ reportRejected(rt, await res.json().catch(() => void 0));
3454
+ await removeEntries(rt, chunk);
3455
+ return "next";
3456
+ }
3457
+ if (status === 401 || status === 403) return onAuthFailure(rt, chunk, auth);
3458
+ if (status === 404) {
3459
+ rt.relayDisabled = true;
3460
+ warnRelayOnce(rt, "not-found", "Relay endpoint not found (404); relay off for this session");
3461
+ return "stop";
3462
+ }
3463
+ if (status === 413) return onTooLarge(rt, chunk, auth);
3464
+ reportRelay(rt, `Relay responded ${status}; the events were dropped`);
3465
+ await removeEntries(rt, chunk);
3466
+ return "next";
3467
+ };
3468
+ const scheduleOutboxFlush = (rt) => {
3469
+ const relay = rt.serverSide;
3470
+ if (!relay || rt.relayDisabled || rt.relayTimer) return;
3471
+ if ((rt.outbox ?? []).length === 0) return;
3472
+ const delay = relay.flushIntervalMs > 0 ? relay.flushIntervalMs : RETRY_MS;
3473
+ rt.relayTimer = setTimeout(() => {
3474
+ rt.relayTimer = null;
3475
+ flushOutbox(rt);
3476
+ }, delay);
3477
+ };
3478
+ const runFlush = async (rt) => {
3479
+ clearTimer(rt, "relayTimer");
3480
+ const relay = rt.serverSide;
3481
+ if (!relay || relay.runtime !== "react-native" || rt.relayDisabled) return;
3482
+ if ((await loadOutbox(rt)).length === 0) return;
3483
+ if (!resolveConsent(rt).ads || await attRevoked(rt)) {
3484
+ await purgeOutbox(rt);
3485
+ return;
3486
+ }
3487
+ if (!await isOnline(rt)) return;
3488
+ const entries = await pruneExpired(rt, Date.now());
3489
+ const token = await tokenOf(rt, false);
3490
+ if (!token) {
3491
+ warnRelayOnce(rt, "no-token", "getAuthToken returned no token; relay events stay queued");
3492
+ return;
3493
+ }
3494
+ const auth = {
3495
+ token,
3496
+ refreshed: false
3497
+ };
3498
+ const chunks = chunkBy(entries, (entry) => entry.event, relay.batchSize);
3499
+ for (const chunk of chunks) if (await sendChunk(rt, chunk, auth) === "stop") break;
3500
+ };
3501
+ /**
3502
+ * Sends the outbox in FIFO order. Runs on a purchase, when the app
3503
+ * returns to the foreground, on start and on a timer while entries are
3504
+ * left (the timer also notices connectivity coming back). Calls made
3505
+ * during a flush run after it.
3506
+ */
3507
+ const flushOutbox = (rt) => {
3508
+ const settled = (rt.outboxFlush ?? Promise.resolve()).then(() => runFlush(rt)).catch((error) => {
3509
+ reportRelay(rt, `Relay outbox failed: ${errorMessage(error)}`, error);
3510
+ }).finally(() => {
3511
+ if (rt.outboxFlush === settled) rt.outboxFlush = null;
3512
+ scheduleOutboxFlush(rt);
3513
+ });
3514
+ rt.outboxFlush = settled;
3515
+ return settled;
3516
+ };
3517
+ //#endregion
3518
+ //#region src/relay.ts
3519
+ /** Events the app relays in contract v1: the verified purchase only. */
3520
+ const APP_RELAYED_EVENTS = /* @__PURE__ */ new Set(["purchase"]);
3521
+ const pageHref = () => {
3522
+ const location = globalThis.location;
3523
+ return textOf(location?.href);
3524
+ };
3525
+ const pageReferrer = () => {
3526
+ const doc = globalThis.document;
3527
+ return textOf(doc?.referrer);
3528
+ };
3071
3529
  const buildRelayEvent = async (rt, event) => {
3072
3530
  const relay = rt.serverSide;
3073
3531
  if (!relay) return null;
@@ -3106,7 +3564,7 @@ const buildRelayEvent = async (rt, event) => {
3106
3564
  };
3107
3565
  const i5 = {
3108
3566
  providers: [...relay.providers],
3109
- context: contextOf$1(rt)
3567
+ context: scopeContext(rt)
3110
3568
  };
3111
3569
  return buildTrackingEvent({
3112
3570
  ...i1,
@@ -3116,33 +3574,6 @@ const buildRelayEvent = async (rt, event) => {
3116
3574
  ...i5
3117
3575
  });
3118
3576
  };
3119
- const relayHeaders = (rt) => {
3120
- const b1 = { "content-type": "application/json" };
3121
- const b2 = { [RELAY_CONTRACT_HEADER]: "1" };
3122
- return {
3123
- ...b1,
3124
- ...b2,
3125
- ...rt.serverSide?.headers ?? {}
3126
- };
3127
- };
3128
- const reportRelay = (rt, message, error) => {
3129
- report(rt, {
3130
- level: "error",
3131
- source: "relay",
3132
- message,
3133
- error
3134
- });
3135
- };
3136
- const reportRejected = (rt, body) => {
3137
- const rejected = body?.rejected;
3138
- if (!Array.isArray(rejected)) return;
3139
- for (const entry of rejected) {
3140
- const reason = textOf(entry?.reason) ?? "rejected";
3141
- const eventId = textOf(entry?.event_id);
3142
- const suffix = eventId ? ` (${eventId})` : "";
3143
- reportRelay(rt, `Relay rejected an event: ${reason}${suffix}`);
3144
- }
3145
- };
3146
3577
  const postEnvelope = async (rt, events, keepalive) => {
3147
3578
  const relay = rt.serverSide;
3148
3579
  if (!relay) return;
@@ -3157,8 +3588,7 @@ const postEnvelope = async (rt, events, keepalive) => {
3157
3588
  };
3158
3589
  const res = await fetchImpl(relay.endpoint, b1);
3159
3590
  if (res.status === 202) {
3160
- const parsed = await res.json().catch(() => void 0);
3161
- reportRejected(rt, parsed);
3591
+ reportRejected(rt, await res.json().catch(() => void 0));
3162
3592
  return;
3163
3593
  }
3164
3594
  if (isRetryableStatus(res.status)) throw new RelayHttpError(res.status);
@@ -3173,30 +3603,12 @@ const sendBeacon = (rt, events) => {
3173
3603
  const blob = new Blob([body], { type: "application/json" });
3174
3604
  return nav.sendBeacon(relay.endpoint, blob);
3175
3605
  };
3176
- const chunkEvents = (events, batchSize) => {
3177
- const chunks = [];
3178
- let current = [];
3179
- let bytes = 0;
3180
- for (const event of events) {
3181
- const size = JSON.stringify(event).length;
3182
- const full = current.length >= batchSize || bytes + size > 6e4;
3183
- if (current.length > 0 && full) {
3184
- chunks.push(current);
3185
- current = [];
3186
- bytes = 0;
3187
- }
3188
- current.push(event);
3189
- bytes += size;
3190
- }
3191
- if (current.length > 0) chunks.push(current);
3192
- return chunks;
3193
- };
3194
3606
  /** Sends every buffered contract event. Keeps running on a failure. */
3195
3607
  const flushRelay = async (rt, options = {}) => {
3196
3608
  clearTimer(rt, "relayTimer");
3197
3609
  const relay = rt.serverSide;
3198
3610
  if (!relay || rt.relayBuffer.length === 0) return;
3199
- const chunks = chunkEvents(rt.relayBuffer, relay.batchSize);
3611
+ const chunks = chunkBy(rt.relayBuffer, (event) => event, relay.batchSize);
3200
3612
  rt.relayBuffer = [];
3201
3613
  const keepalive = options.keepalive ?? false;
3202
3614
  const send = async (chunk) => {
@@ -3225,10 +3637,73 @@ const scheduleRelayFlush = (rt) => {
3225
3637
  flushRelay(rt);
3226
3638
  }, relay.flushIntervalMs);
3227
3639
  };
3640
+ /**
3641
+ * The app relays a verified purchase only, under its `purchase:<order_id>`
3642
+ * id (the id the Meta SDK copy gets), and never on iOS without ATT
3643
+ * `authorized`.
3644
+ */
3645
+ const buildAppRelayEvent = async (rt, event) => {
3646
+ const relay = rt.serverSide;
3647
+ if (!relay || !APP_RELAYED_EVENTS.has(event.event.name)) return null;
3648
+ if (!resolveConsent(rt).ads) return null;
3649
+ const eventId = purchaseEventId((event.event.properties ?? {}).order_id);
3650
+ if (!eventId) {
3651
+ warnRelayOnce(rt, "order-id", `purchase not relayed: its order_id cannot form purchase:<order_id>`);
3652
+ return null;
3653
+ }
3654
+ const app = await readAppContext(rt);
3655
+ if (!app) {
3656
+ warnRelayOnce(rt, "app-context", "purchase not relayed: getAppContext returned no context");
3657
+ return null;
3658
+ }
3659
+ if (app.platform === "ios" && app.attStatus !== "authorized") return null;
3660
+ const hashOptions = {
3661
+ hash: rt.options?.hash,
3662
+ defaultCountry: rt.country
3663
+ };
3664
+ const user = await hashUserData(userInput(rt, event), hashOptions);
3665
+ const wireConsent = { ads: true };
3666
+ const context = {
3667
+ ...scopeContext(rt),
3668
+ runtime: relay.runtime,
3669
+ app
3670
+ };
3671
+ const i1 = {
3672
+ eventId,
3673
+ name: event.event.name,
3674
+ timestamp: event.at
3675
+ };
3676
+ const i2 = {
3677
+ properties: event.event.properties,
3678
+ currency: rt.currency
3679
+ };
3680
+ const i3 = {
3681
+ user,
3682
+ consent: wireConsent
3683
+ };
3684
+ const i4 = {
3685
+ providers: [...relay.providers],
3686
+ context
3687
+ };
3688
+ return buildTrackingEvent({
3689
+ ...i1,
3690
+ ...i2,
3691
+ ...i3,
3692
+ ...i4
3693
+ });
3694
+ };
3695
+ const relayAppTrack = async (rt, event) => {
3696
+ if (rt.relayDisabled) return;
3697
+ const built = await buildAppRelayEvent(rt, event);
3698
+ if (!built) return;
3699
+ await enqueueOutbox(rt, built, event.at);
3700
+ await flushOutbox(rt);
3701
+ };
3228
3702
  /** Builds and buffers a contract event, flushing per `batchSize`/purchase. */
3229
3703
  const relayTrack = async (rt, event) => {
3230
3704
  const relay = rt.serverSide;
3231
3705
  if (!relay || relay.providers.size === 0) return;
3706
+ if (relay.runtime === "react-native") return relayAppTrack(rt, event);
3232
3707
  const built = await buildRelayEvent(rt, event);
3233
3708
  if (!built) return;
3234
3709
  rt.relayBuffer.push(built);
@@ -3282,6 +3757,10 @@ const attachAppState = (rt) => {
3282
3757
  const appState = rt.options?.appState;
3283
3758
  if (!appState) return null;
3284
3759
  const subscription = appState.addEventListener("change", (state) => {
3760
+ if (state === "active") {
3761
+ if (rt.serverSide?.runtime === "react-native") flushOutbox(rt);
3762
+ return;
3763
+ }
3285
3764
  if (state !== "background" && state !== "inactive") return;
3286
3765
  flushInBackground(rt);
3287
3766
  });
@@ -3289,7 +3768,10 @@ const attachAppState = (rt) => {
3289
3768
  subscription?.remove();
3290
3769
  };
3291
3770
  };
3292
- /** Sends the queue when the page hides or the app goes to background. */
3771
+ /**
3772
+ * Sends the queue when the page hides or the app goes to background, and
3773
+ * the app relay outbox when the app returns to the foreground.
3774
+ */
3293
3775
  const attachLifecycle = (rt) => {
3294
3776
  rt.detachLifecycle?.();
3295
3777
  rt.detachLifecycle = null;
@@ -3322,6 +3804,8 @@ const SERVER_PROVIDERS = new Set(SERVER_PROVIDER_IDS);
3322
3804
  const DEFAULT_BATCH_SIZE = 10;
3323
3805
  const MIN_BATCH_SIZE = 1;
3324
3806
  const MAX_BATCH_SIZE = 20;
3807
+ const OUTBOX_MAX_AGE = 2820 * 60 * 1e3;
3808
+ const APP_SERVER_PROVIDERS = /* @__PURE__ */ new Set(["meta"]);
3325
3809
  const isProduction = (options) => {
3326
3810
  return options.env === "production";
3327
3811
  };
@@ -3351,8 +3835,31 @@ const validateEndpoint = (endpoint, production) => {
3351
3835
  const endpointRequired = (mode) => {
3352
3836
  throw new AnalyticsConfigError("ANALYTICS_SERVER_ENDPOINT_REQUIRED", `mode "${mode}" requires serverSide.endpoint`);
3353
3837
  };
3354
- const unsupportedRuntime = () => {
3355
- throw new AnalyticsConfigError("ANALYTICS_SERVER_MODE_UNSUPPORTED_RUNTIME", "server delivery is web-only; it is not supported on react-native");
3838
+ /** No page origin on a device: the endpoint must be an absolute URL. */
3839
+ const validateAppEndpoint = (endpoint, production) => {
3840
+ if (endpoint.startsWith("/")) throw new AnalyticsConfigError("ANALYTICS_INVALID_ENDPOINT", "on react-native serverSide.endpoint must be an https URL");
3841
+ validateEndpoint(endpoint, production);
3842
+ };
3843
+ /** The app relay needs the customer token and the device context. */
3844
+ const requireAppHooks = (options) => {
3845
+ const serverSide = options.serverSide;
3846
+ if (typeof serverSide?.getAuthToken !== "function") throw new AnalyticsConfigError("ANALYTICS_SERVER_AUTH_REQUIRED", "on react-native the relay requires serverSide.getAuthToken");
3847
+ if (typeof serverSide.getAppContext !== "function") throw new AnalyticsConfigError("ANALYTICS_SERVER_APP_CONTEXT_REQUIRED", "on react-native the relay requires serverSide.getAppContext");
3848
+ };
3849
+ /** Only Meta takes app events from the relay in contract v1. */
3850
+ const appProviders = (providers, warnings) => {
3851
+ const kept = /* @__PURE__ */ new Set();
3852
+ for (const id of providers) {
3853
+ if (APP_SERVER_PROVIDERS.has(id)) {
3854
+ kept.add(id);
3855
+ continue;
3856
+ }
3857
+ warnings.push(warn(`provider "${id}" is not relayed on react-native`));
3858
+ }
3859
+ return kept;
3860
+ };
3861
+ const positiveOr = (value, fallback) => {
3862
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
3356
3863
  };
3357
3864
  const resolveProviders = (options) => {
3358
3865
  const configured = options.serverSide?.providers;
@@ -3369,20 +3876,30 @@ const clampBatchSize = (value) => {
3369
3876
  if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_BATCH_SIZE;
3370
3877
  return Math.min(Math.max(Math.trunc(value), MIN_BATCH_SIZE), MAX_BATCH_SIZE);
3371
3878
  };
3372
- const resolveServerSide = (options, endpoint) => {
3879
+ const resolveServerSide = (options, endpoint, runtime) => {
3373
3880
  const serverSide = options.serverSide;
3374
3881
  const b1 = {
3375
3882
  endpoint,
3883
+ runtime,
3376
3884
  providers: resolveProviders(options)
3377
3885
  };
3378
3886
  const b2 = { batchSize: clampBatchSize(serverSide?.batchSize) };
3379
3887
  const flushIntervalMs = Math.max(serverSide?.flushIntervalMs ?? 0, 0);
3380
3888
  const headers = { ...serverSide?.headers ?? {} };
3889
+ const b3 = { getAuthToken: serverSide?.getAuthToken ?? null };
3890
+ const b4 = { getAppContext: serverSide?.getAppContext ?? null };
3891
+ const b5 = { outbox: {
3892
+ maxEvents: positiveOr(serverSide?.outbox?.maxEvents, 200),
3893
+ maxAgeMs: positiveOr(serverSide?.outbox?.maxAgeMs, OUTBOX_MAX_AGE)
3894
+ } };
3381
3895
  return {
3382
3896
  ...b1,
3383
3897
  ...b2,
3384
3898
  flushIntervalMs,
3385
- headers
3899
+ headers,
3900
+ ...b3,
3901
+ ...b4,
3902
+ ...b5
3386
3903
  };
3387
3904
  };
3388
3905
  /**
@@ -3394,7 +3911,8 @@ const resolveServerSide = (options, endpoint) => {
3394
3911
  const planDelivery = (options) => {
3395
3912
  const mode = options.mode;
3396
3913
  if (mode !== void 0 && !DELIVERY_MODES.has(mode)) throw new AnalyticsConfigError("ANALYTICS_INVALID_MODE", `Unknown delivery mode "${String(mode)}"`);
3397
- const web = resolveRuntime(options) === "web";
3914
+ const runtime = resolveRuntime(options);
3915
+ const web = runtime === "web";
3398
3916
  const production = isProduction(options);
3399
3917
  const endpoint = textOf(options.serverSide?.endpoint);
3400
3918
  const warnings = [];
@@ -3411,15 +3929,29 @@ const planDelivery = (options) => {
3411
3929
  }
3412
3930
  if (mode === void 0 && !endpoint) return client();
3413
3931
  if (mode === void 0 && !web) {
3414
- warnings.push(warn("server delivery is web-only; endpoint ignored"));
3932
+ warnings.push(warn(`on react-native set mode "hybrid" or "server" to relay; endpoint ignored`));
3415
3933
  return client();
3416
3934
  }
3417
3935
  if (!endpoint) return endpointRequired(mode ?? "hybrid");
3418
- if (!web) return unsupportedRuntime();
3419
- validateEndpoint(endpoint, production);
3936
+ const resolved = mode === "server" ? "server" : "hybrid";
3937
+ if (web) {
3938
+ validateEndpoint(endpoint, production);
3939
+ return {
3940
+ mode: resolved,
3941
+ serverSide: resolveServerSide(options, endpoint, runtime),
3942
+ warnings
3943
+ };
3944
+ }
3945
+ requireAppHooks(options);
3946
+ validateAppEndpoint(endpoint, production);
3947
+ const resolvedApp = resolveServerSide(options, endpoint, runtime);
3948
+ const providers = appProviders(resolvedApp.providers, warnings);
3420
3949
  return {
3421
- mode: mode === "server" ? "server" : "hybrid",
3422
- serverSide: resolveServerSide(options, endpoint),
3950
+ mode: resolved,
3951
+ serverSide: {
3952
+ ...resolvedApp,
3953
+ providers
3954
+ },
3423
3955
  warnings
3424
3956
  };
3425
3957
  };
@@ -3631,7 +4163,8 @@ const STORAGE_SUFFIXES = [
3631
4163
  "queue",
3632
4164
  "config",
3633
4165
  "interactions",
3634
- "samples"
4166
+ "samples",
4167
+ "relay-outbox"
3635
4168
  ];
3636
4169
  const toTrackEvent = (nameOrEvent, params) => {
3637
4170
  if (typeof nameOrEvent !== "string") return nameOrEvent;
@@ -4003,6 +4536,7 @@ const configureWith = async (rt, options) => {
4003
4536
  if (rt.user) await pushUser(rt);
4004
4537
  await replayPending(rt);
4005
4538
  if (rt.queue.length > 0) flushInBackground(rt);
4539
+ if (rt.serverSide?.runtime === "react-native") flushOutbox(rt);
4006
4540
  });
4007
4541
  };
4008
4542
  const trackWith = (rt, nameOrEvent, params, opts) => {
@@ -4046,12 +4580,14 @@ const setUserWith = (rt, user) => {
4046
4580
  });
4047
4581
  };
4048
4582
  /**
4049
- * Revoking ads consent stops the relay and deletes the first-party ids the
4050
- * SDK wrote (`_fbp`, `_fbc` and the `fs_ck_*` click-id snapshots), so no
4051
- * identifiers linger after the customer opts out.
4583
+ * Revoking ads consent stops the relay, empties the app relay outbox and
4584
+ * deletes the first-party ids the SDK wrote (`_fbp`, `_fbc` and the
4585
+ * `fs_ck_*` click-id snapshots), so no identifiers linger after the
4586
+ * customer opts out.
4052
4587
  */
4053
4588
  const revokeAdsArtifacts = async (rt) => {
4054
4589
  stopRelay(rt);
4590
+ await purgeOutbox(rt);
4055
4591
  deleteFbCookies();
4056
4592
  const storage = rt.options?.storage;
4057
4593
  if (storage) await clearClickIds(storage);
@@ -4141,6 +4677,21 @@ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
4141
4677
  const KNOWN_PROVIDERS = new Set(SERVER_PROVIDER_IDS);
4142
4678
  const USER_HASH_KEYS = Object.values(HASHED_USER_WIRE_KEYS);
4143
4679
  const CLICK_ID_KEYS = Object.values(CLICK_ID_WIRE_KEYS);
4680
+ const DEFAULT_RUNTIMES = ["web"];
4681
+ const UUID = /^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$/;
4682
+ const INSTALL_ID = /^[A-Za-z0-9-]{8,64}$/;
4683
+ const MAX_APP_ID = 155;
4684
+ const MAX_APP_TEXT = 64;
4685
+ const MAX_APP_LOCALE = 35;
4686
+ const MAX_INSTALL_REFERRER = 2048;
4687
+ const MAX_SCREEN = 1e5;
4688
+ const ATT_STATUSES = /* @__PURE__ */ new Set([
4689
+ "authorized",
4690
+ "denied",
4691
+ "not_determined",
4692
+ "restricted",
4693
+ "not_applicable"
4694
+ ]);
4144
4695
  var Rejection = class extends Error {
4145
4696
  reason;
4146
4697
  constructor(reason) {
@@ -4247,23 +4798,118 @@ const consentOf = (value) => {
4247
4798
  adPersonalization
4248
4799
  });
4249
4800
  };
4250
- const contextOf = (value) => {
4251
- if (!isRecord(value) || value.runtime !== "web") return fail("invalid_event");
4801
+ /** Optional text up to `max` characters; empty → `undefined`. */
4802
+ const textUpTo = (value, max) => {
4803
+ if (value === void 0) return void 0;
4804
+ if (typeof value !== "string" || value.length > max) return fail("invalid_event");
4805
+ return value.length > 0 ? value : void 0;
4806
+ };
4807
+ const requiredUpTo = (value, max) => {
4808
+ return textUpTo(value, max) ?? fail("invalid_event");
4809
+ };
4810
+ const screenSizeOf = (value) => {
4811
+ if (value === void 0) return void 0;
4812
+ const size = Number.isInteger(value) ? value : 0;
4813
+ return size >= 1 && size <= MAX_SCREEN ? size : fail("invalid_event");
4814
+ };
4815
+ const densityOf = (value) => {
4816
+ if (value === void 0) return void 0;
4817
+ return isDecimalString(value) && !value.startsWith("-") ? value : fail("invalid_decimal");
4818
+ };
4819
+ /** All-zero ids are dropped; anything else that is not a UUID rejects. */
4820
+ const deviceIdOf = (value) => {
4821
+ if (value === void 0 || isZeroId(value)) return void 0;
4822
+ if (typeof value === "string" && UUID.test(value)) return value;
4823
+ return fail("invalid_event");
4824
+ };
4825
+ const platformOf = (value) => {
4826
+ if (value === "ios" || value === "android") return value;
4827
+ return fail("invalid_event");
4828
+ };
4829
+ const attStatusOf = (value, platform) => {
4830
+ if (typeof value !== "string" || !ATT_STATUSES.has(value)) return fail("invalid_event");
4831
+ if (value === "not_applicable" && platform !== "android") return fail("invalid_event");
4832
+ return value;
4833
+ };
4834
+ const installIdOf = (value) => {
4835
+ if (typeof value === "string" && INSTALL_ID.test(value)) return value;
4836
+ return fail("invalid_event");
4837
+ };
4838
+ const appOf = (value) => {
4839
+ if (!isRecord(value)) return fail("invalid_event");
4840
+ const platform = platformOf(value.platform);
4841
+ const a1 = {
4842
+ platform,
4843
+ id: requiredUpTo(value.id, MAX_APP_ID)
4844
+ };
4845
+ const a2 = { version: textUpTo(value.version, MAX_APP_TEXT) };
4846
+ const a3 = { build: textUpTo(value.build, MAX_APP_TEXT) };
4847
+ const a4 = { os_version: requiredUpTo(value.os_version, MAX_APP_TEXT) };
4848
+ const a5 = { device_model: textUpTo(value.device_model, MAX_APP_TEXT) };
4849
+ const a6 = { locale: textUpTo(value.locale, MAX_APP_LOCALE) };
4850
+ const a7 = { timezone: textUpTo(value.timezone, MAX_APP_TEXT) };
4851
+ const a8 = { screen_width: screenSizeOf(value.screen_width) };
4852
+ const a9 = { screen_height: screenSizeOf(value.screen_height) };
4853
+ const a10 = { screen_density: densityOf(value.screen_density) };
4854
+ const a11 = { install_id: installIdOf(value.install_id) };
4855
+ const a12 = { vendor_id: deviceIdOf(value.vendor_id) };
4856
+ const a13 = { ad_id: deviceIdOf(value.ad_id) };
4857
+ const a14 = { att_status: attStatusOf(value.att_status, platform) };
4858
+ const tracking = value.advertiser_tracking;
4859
+ if (typeof tracking !== "boolean") return fail("invalid_event");
4860
+ const a15 = { advertiser_tracking: tracking };
4861
+ const a16 = { install_referrer: textUpTo(value.install_referrer, MAX_INSTALL_REFERRER) };
4862
+ const m1 = {
4863
+ ...a1,
4864
+ ...a2,
4865
+ ...a3,
4866
+ ...a4,
4867
+ ...a5,
4868
+ ...a6,
4869
+ ...a7,
4870
+ ...a8
4871
+ };
4872
+ const m2 = {
4873
+ ...a9,
4874
+ ...a10,
4875
+ ...a11,
4876
+ ...a12,
4877
+ ...a13,
4878
+ ...a14,
4879
+ ...a15
4880
+ };
4881
+ return withoutUndefined({
4882
+ ...m1,
4883
+ ...m2,
4884
+ ...a16
4885
+ });
4886
+ };
4887
+ const runtimeOf = (value, check) => {
4888
+ if (typeof value === "string" && check.runtimes.has(value)) return value;
4889
+ return fail("invalid_event");
4890
+ };
4891
+ const contextOf = (value, check) => {
4892
+ if (!isRecord(value)) return fail("invalid_event");
4893
+ const runtime = runtimeOf(value.runtime, check);
4894
+ const native = runtime === "react-native";
4252
4895
  const c1 = {
4253
- runtime: "web",
4896
+ runtime,
4254
4897
  locale: optionalText(value.locale)
4255
4898
  };
4256
4899
  const c2 = { channel_id: requiredText(value.channel_id) };
4257
4900
  const c3 = { store_id: optionalText(value.store_id) };
4258
4901
  const c4 = { brand_id: optionalText(value.brand_id) };
4259
4902
  const c5 = { fulfillment_id: optionalText(value.fulfillment_id) };
4260
- return withoutUndefined({
4903
+ const c6 = { app: native ? appOf(value.app) : void 0 };
4904
+ const m1 = {
4261
4905
  ...c1,
4262
4906
  ...c2,
4263
4907
  ...c3,
4264
4908
  ...c4,
4265
- ...c5
4266
- });
4909
+ ...c5,
4910
+ ...c6
4911
+ };
4912
+ return withoutUndefined(m1);
4267
4913
  };
4268
4914
  const decimalOf = (value) => {
4269
4915
  if (value === void 0) return void 0;
@@ -4316,15 +4962,17 @@ const parseEvent = (raw, check) => {
4316
4962
  name
4317
4963
  };
4318
4964
  const e2 = { timestamp: timestampOf(raw.timestamp, check) };
4319
- const e3 = { source_url: sourceUrlOf(raw.source_url, check) };
4320
- const e4 = { referrer_url: referrerOf(raw.referrer_url) };
4965
+ const context = contextOf(raw.context, check);
4966
+ const web = context.runtime === "web";
4967
+ const e3 = { source_url: web ? sourceUrlOf(raw.source_url, check) : void 0 };
4968
+ const e4 = { referrer_url: web ? referrerOf(raw.referrer_url) : void 0 };
4321
4969
  const e5 = { properties: propertiesOf(raw.properties) };
4322
4970
  const e6 = {
4323
4971
  user: userOf(raw.user),
4324
4972
  click_ids: clickIdsOf(raw.click_ids)
4325
4973
  };
4326
4974
  const e7 = { consent: consentOf(raw.consent) };
4327
- const e8 = { context: contextOf(raw.context) };
4975
+ const e8 = { context };
4328
4976
  const e9 = {
4329
4977
  value: decimalOf(raw.value),
4330
4978
  items: itemsOf(raw.items)
@@ -4346,7 +4994,7 @@ const parseEvent = (raw, check) => {
4346
4994
  ...e11,
4347
4995
  ...e12
4348
4996
  };
4349
- return withoutUndefined(event);
4997
+ return withAttPolicy(withoutUndefined(event));
4350
4998
  };
4351
4999
  const checkEvent = (raw, check) => {
4352
5000
  if (!isRecord(raw)) return { reason: "invalid_event" };
@@ -4362,11 +5010,19 @@ const checkOf = (options) => {
4362
5010
  const origins = parsed ? new Set(parsed) : null;
4363
5011
  const known = (options.providers ?? SERVER_PROVIDER_IDS).filter((id) => KNOWN_PROVIDERS.has(id));
4364
5012
  const providers = new Set(known);
4365
- return {
5013
+ const runtimes = new Set(options.runtimes ?? DEFAULT_RUNTIMES);
5014
+ const c1 = {
4366
5015
  now: options.now ?? Date.now(),
4367
5016
  origins,
4368
- providers,
4369
- allowLocalhost: options.allowLocalhost === true
5017
+ providers
5018
+ };
5019
+ const c2 = {
5020
+ allowLocalhost: options.allowLocalhost === true,
5021
+ runtimes
5022
+ };
5023
+ return {
5024
+ ...c1,
5025
+ ...c2
4370
5026
  };
4371
5027
  };
4372
5028
  const parseJson = (input) => {
@@ -4408,6 +5064,12 @@ const upgradeEnvelope = (envelope) => {
4408
5064
  * (`email`, `phone`, `first_name`, `last_name`, `device_ip`, `ttclid`) are
4409
5065
  * dropped, and `consent.ad_user_data` / `ad_personalization` default to
4410
5066
  * `ads`. Field names are snake_case, as on the wire.
5067
+ *
5068
+ * Only `options.runtimes` are accepted (default `["web"]`). A
5069
+ * `react-native` event needs `context.app`; its `source_url` and
5070
+ * `referrer_url` are dropped, all-zero `ad_id` / `vendor_id` are dropped,
5071
+ * and on iOS without ATT `authorized` the device ids and `user` hashes
5072
+ * are removed.
4411
5073
  */
4412
5074
  const validateEnvelope = (input, options = {}) => {
4413
5075
  const parsed = parseJson(input);
@@ -4466,6 +5128,24 @@ const validateEnvelope = (input, options = {}) => {
4466
5128
  };
4467
5129
  };
4468
5130
  //#endregion
5131
+ //#region src/provider-name.ts
5132
+ /**
5133
+ * Event name a destination gets for a Fire Spark event on the web, from
5134
+ * the same catalog transform the browser pixels use (`purchase` →
5135
+ * Meta `Purchase`, TikTok `CompletePayment`). A server must send this
5136
+ * exact name, or the platform cannot deduplicate it against the pixel.
5137
+ * `null` when the catalog does not send the event to that provider.
5138
+ */
5139
+ const providerEventName = (provider, name) => {
5140
+ return transformForProvider(provider, {
5141
+ name,
5142
+ params: {},
5143
+ runtime: "web",
5144
+ eventId: "name",
5145
+ eventTime: 0
5146
+ })?.name ?? null;
5147
+ };
5148
+ //#endregion
4469
5149
  //#region src/index.ts
4470
5150
  const configure = (options) => {
4471
5151
  return configureWith(runtime, options);
@@ -4533,4 +5213,4 @@ const analytics = {
4533
5213
  setConsent
4534
5214
  };
4535
5215
  //#endregion
4536
- export { Analytics, AnalyticsConfigError, BUILTIN_DESTINATION_IDS, CLICK_ID_STORAGE_PREFIX, CLICK_ID_TTL_MS, CLICK_ID_WIRE_KEYS, CONTRACT_PII_KEYS, FUNNEL_EVENTS, HASHED_USER_WIRE_KEYS, INTERACTION_EVENTS, MAX_ENVELOPE_EVENTS, SDK_VERSION, SERVER_PROVIDER_IDS, SUPPORTED_CONTRACT_VERSIONS, TRACKING_CONTRACT_VERSION, TRACKING_SDK_NAME, analytics, buildTrackingEnvelope, buildTrackingEvent, captureClickIds, clearClickIds, compactPayload, configure, customAdapter, endSession, fbcFromFbclid, flush, gclidFromGclAw, hasScript, hashUserData, isDecimalString, isFunnelEventName, isInteractionEventName, isValidEventId, loadScript, normalizeCountryCode, normalizeEmail, normalizeEmailForGoogle, normalizeExternalId, normalizeName, normalizePhoneE164, parseClickIdParams, phoneDigits, purchaseEventId, readCookie, reset, resolveDeliveryMode, setConsent, setUser, sha256Hex, toDecimalString, track, upgradeEnvelope, validateEnvelope };
5216
+ export { Analytics, AnalyticsConfigError, BUILTIN_DESTINATION_IDS, CLICK_ID_STORAGE_PREFIX, CLICK_ID_TTL_MS, CLICK_ID_WIRE_KEYS, CONTRACT_PII_KEYS, FUNNEL_EVENTS, HASHED_USER_WIRE_KEYS, INTERACTION_EVENTS, MAX_ENVELOPE_EVENTS, SDK_VERSION, SERVER_PROVIDER_IDS, SUPPORTED_CONTRACT_VERSIONS, TRACKING_CONTRACT_VERSION, TRACKING_SDK_NAME, analytics, appTrackingAllowed, buildTrackingEnvelope, buildTrackingEvent, captureClickIds, clearClickIds, compactPayload, configure, customAdapter, endSession, fbcFromFbclid, flush, gclidFromGclAw, hasScript, hashUserData, isDecimalString, isFunnelEventName, isInteractionEventName, isValidEventId, loadScript, normalizeCountryCode, normalizeEmail, normalizeEmailForGoogle, normalizeExternalId, normalizeName, normalizePhoneE164, parseClickIdParams, phoneDigits, providerEventName, purchaseEventId, readCookie, reset, resolveDeliveryMode, setConsent, setUser, sha256Hex, toDecimalString, track, upgradeEnvelope, validateEnvelope };