@fire-spark/analytics-server 0.25.0 → 0.27.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/app-DlzC8Iq0.js +55 -0
- package/dist/google.d.ts +1 -1
- package/dist/google.js +2 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +201 -30
- package/dist/meta.d.ts +79 -7
- package/dist/meta.js +363 -117
- package/dist/{retry-CKgkb0DS.d.ts → retry-BRNUy4Of.d.ts} +48 -7
- package/dist/tiktok.d.ts +2 -2
- package/dist/tiktok.js +1 -0
- package/package.json +3 -3
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { isValidEventId, validateEnvelope } from "@fire-spark/analytics";
|
|
2
|
+
//#region src/app.ts
|
|
3
|
+
const ENVELOPE_SDK = {
|
|
4
|
+
name: "analytics-server",
|
|
5
|
+
version: "1"
|
|
6
|
+
};
|
|
7
|
+
/** `runtimes` for `validateEnvelope` on the app relay. */
|
|
8
|
+
const APP_RUNTIMES = ["web", "react-native"];
|
|
9
|
+
const isRecord = (value) => {
|
|
10
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
11
|
+
};
|
|
12
|
+
/** `context.runtime` of a validated event; `web` when absent. */
|
|
13
|
+
const runtimeOf = (event) => {
|
|
14
|
+
return event.context.runtime ?? "web";
|
|
15
|
+
};
|
|
16
|
+
/** `context.app` of a validated app event. */
|
|
17
|
+
const appContextOf = (event) => event.context.app;
|
|
18
|
+
const rejectionOf = (raw, reason) => {
|
|
19
|
+
const id = isRecord(raw) ? raw.event_id : void 0;
|
|
20
|
+
return isValidEventId(id) ? {
|
|
21
|
+
reason,
|
|
22
|
+
event_id: id
|
|
23
|
+
} : { reason };
|
|
24
|
+
};
|
|
25
|
+
const envelopeOf = (event, now) => {
|
|
26
|
+
return {
|
|
27
|
+
v: 1,
|
|
28
|
+
sdk: ENVELOPE_SDK,
|
|
29
|
+
sent_at: new Date(now).toISOString(),
|
|
30
|
+
events: [event]
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Validates one app event with the contract validator (`react-native`
|
|
35
|
+
* runtime, `context.app` and the ATT policy). Only `app_context_missing`
|
|
36
|
+
* is told apart here; every other reason is the validator's.
|
|
37
|
+
*/
|
|
38
|
+
const checkAppEvent = (raw, now, providers) => {
|
|
39
|
+
if (!isRecord(raw) || !isRecord(raw.context)) return rejectionOf(raw, "invalid_event");
|
|
40
|
+
if (raw.context.runtime !== "react-native") return rejectionOf(raw, "invalid_event");
|
|
41
|
+
if (raw.context.app === void 0 || raw.context.app === null) return rejectionOf(raw, "app_context_missing");
|
|
42
|
+
const options = {
|
|
43
|
+
now,
|
|
44
|
+
providers,
|
|
45
|
+
runtimes: APP_RUNTIMES
|
|
46
|
+
};
|
|
47
|
+
const result = validateEnvelope(envelopeOf(raw, now), options);
|
|
48
|
+
if (!result.ok) return rejectionOf(raw, "invalid_event");
|
|
49
|
+
const valid = result.envelope.events[0];
|
|
50
|
+
if (valid) return { event: valid };
|
|
51
|
+
const reason = result.rejected[0]?.reason ?? "invalid_event";
|
|
52
|
+
return rejectionOf(raw, reason);
|
|
53
|
+
};
|
|
54
|
+
//#endregion
|
|
55
|
+
export { runtimeOf as i, appContextOf as n, checkAppEvent as r, APP_RUNTIMES as t };
|
package/dist/google.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as ServerProvider, R as JsonNumber, T as ResolvedEvent, i as HttpReply, t as AttemptOutcome } from "./retry-BRNUy4Of.js";
|
|
2
2
|
//#region src/google.types.d.ts
|
|
3
3
|
interface GoogleDataManagerOptions {
|
|
4
4
|
/** Service account e-mail (`client_email` of the JSON key). */
|
package/dist/google.js
CHANGED
|
@@ -492,6 +492,7 @@ const disabledProvider = (error) => {
|
|
|
492
492
|
return {
|
|
493
493
|
id: PROVIDER,
|
|
494
494
|
maxBatchSize: MAX_BATCH,
|
|
495
|
+
runtimes: ["web"],
|
|
495
496
|
prepare,
|
|
496
497
|
send
|
|
497
498
|
};
|
|
@@ -579,6 +580,7 @@ const googleDataManager = (options) => {
|
|
|
579
580
|
return {
|
|
580
581
|
id: PROVIDER,
|
|
581
582
|
maxBatchSize: MAX_BATCH,
|
|
583
|
+
runtimes: ["web"],
|
|
582
584
|
prepare,
|
|
583
585
|
send
|
|
584
586
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { SUPPORTED_CONTRACT_VERSIONS, TrackingEventV1, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope } from "@fire-spark/analytics";
|
|
1
|
+
import { A as ServerProvider, B as decimalText, C as RelayRejectedEvent, D as ServerEventInput, E as RetryPolicy, F as TrackingHandlerOptions, I as VerifyEvent, L as VerifyEventContext, M as ServerTracker, N as ServerTrackerOptions, O as ServerIssue, P as ServerUserInput, R as JsonNumber, S as RelayRejectReason, T as ResolvedEvent, V as stringifyJson, _ as ProviderReason, a as backoffDelay, b as RelayErrorBody, c as AnalyticsServerConfigError, d as AppTrackingHandlerOptions, f as DeliveryOptions, g as ProviderOutcome, h as ProviderContext, i as HttpReply, j as ServerTrackResult, k as ServerIssueSource, l as AnalyticsServerConfigErrorCode, m as PreparedEvents, n as DEFAULT_RETRY_POLICY, o as postJson, p as IdempotencyStore, r as FinalOutcome, s as withProviderRetry, t as AttemptOutcome, u as AppAuthentication, v as ProviderResult, w as RequestMeta, x as RelayErrorCode, y as RelayAcceptedBody, z as decimalNumber } from "./retry-BRNUy4Of.js";
|
|
2
|
+
import { SUPPORTED_CONTRACT_VERSIONS, TrackingAppContextV1, TrackingEventV1, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope } from "@fire-spark/analytics";
|
|
3
3
|
//#region src/handler.d.ts
|
|
4
4
|
declare const DEFAULT_MAX_BODY_BYTES = 65536;
|
|
5
5
|
declare const CONTRACT_HEADER = "x-firespark-contract";
|
|
@@ -11,6 +11,14 @@ declare const CONTRACT_HEADER = "x-firespark-contract";
|
|
|
11
11
|
* is no `waitUntil`.
|
|
12
12
|
*/
|
|
13
13
|
declare const createTrackingHandler: (options: TrackingHandlerOptions) => (request: Request) => Promise<Response>;
|
|
14
|
+
/**
|
|
15
|
+
* `POST` handler for app (React Native) events. No `Origin` gate: the
|
|
16
|
+
* request must pass `authenticate`, come from an app in `allowedApps` and
|
|
17
|
+
* carry an event in `relayedEvents` (default `purchase`), which is always
|
|
18
|
+
* re-read by `verifyEvent` before any provider sees it. Same response as
|
|
19
|
+
* `createTrackingHandler`.
|
|
20
|
+
*/
|
|
21
|
+
declare const createAppTrackingHandler: (options: AppTrackingHandlerOptions) => (request: Request) => Promise<Response>;
|
|
14
22
|
//#endregion
|
|
15
23
|
//#region src/tracker.d.ts
|
|
16
24
|
/**
|
|
@@ -48,4 +56,4 @@ declare const cleanUserAgent: (value: unknown) => string | undefined;
|
|
|
48
56
|
*/
|
|
49
57
|
declare const defaultRequestMeta: (request: Request) => RequestMeta;
|
|
50
58
|
//#endregion
|
|
51
|
-
export { AnalyticsServerConfigError, type AnalyticsServerConfigErrorCode, type AttemptOutcome, CONTRACT_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_RETRY_POLICY, type DeliveryOptions, type FinalOutcome, type HttpReply, IDEMPOTENCY_TTL_SECONDS, type IdempotencyStore, JsonNumber, type PreparedEvents, type ProviderContext, type ProviderOutcome, type ProviderReason, type ProviderResult, type RelayAcceptedBody, type RelayErrorBody, type RelayErrorCode, type RelayRejectReason, type RelayRejectedEvent, type RequestMeta, type ResolvedEvent, type RetryPolicy, SUPPORTED_CONTRACT_VERSIONS, type ServerEventInput, type ServerIssue, type ServerIssueSource, type ServerProvider, type ServerTrackResult, type ServerTracker, type ServerTrackerOptions, type ServerUserInput, type TrackingHandlerOptions, type VerifyEvent, backoffDelay, cleanIp, cleanUserAgent, createServerTracker, createTrackingHandler, decimalNumber, decimalText, defaultRequestMeta, defineServerProvider, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, postJson, redactText, sha256Hex, stringifyJson, upgradeEnvelope, validateEnvelope, withProviderRetry };
|
|
59
|
+
export { AnalyticsServerConfigError, type AnalyticsServerConfigErrorCode, type AppAuthentication, type AppTrackingHandlerOptions, type AttemptOutcome, CONTRACT_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_RETRY_POLICY, type DeliveryOptions, type FinalOutcome, type HttpReply, IDEMPOTENCY_TTL_SECONDS, type IdempotencyStore, JsonNumber, type PreparedEvents, type ProviderContext, type ProviderOutcome, type ProviderReason, type ProviderResult, type RelayAcceptedBody, type RelayErrorBody, type RelayErrorCode, type RelayRejectReason, type RelayRejectedEvent, type RequestMeta, type ResolvedEvent, type RetryPolicy, SUPPORTED_CONTRACT_VERSIONS, type ServerEventInput, type ServerIssue, type ServerIssueSource, type ServerProvider, type ServerTrackResult, type ServerTracker, type ServerTrackerOptions, type ServerUserInput, type TrackingAppContextV1, type TrackingHandlerOptions, type VerifyEvent, type VerifyEventContext, backoffDelay, cleanIp, cleanUserAgent, createAppTrackingHandler, createServerTracker, createTrackingHandler, decimalNumber, decimalText, defaultRequestMeta, defineServerProvider, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, postJson, redactText, sha256Hex, stringifyJson, upgradeEnvelope, validateEnvelope, withProviderRetry };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { i as runtimeOf, n as appContextOf, r as checkAppEvent, t as APP_RUNTIMES } from "./app-DlzC8Iq0.js";
|
|
1
2
|
import { a as stringifyJson, c as backoffDelay, d as resolveRetryPolicy, f as withProviderRetry, i as decimalText, l as postJson, o as AnalyticsServerConfigError, r as decimalNumber, s as DEFAULT_RETRY_POLICY, t as JsonNumber } from "./json-D5hsBi3M.js";
|
|
2
3
|
import { t as defineServerProvider } from "./provider-DIOneNqa.js";
|
|
3
|
-
import { HASHED_USER_WIRE_KEYS, MAX_ENVELOPE_EVENTS, SERVER_PROVIDER_IDS, SUPPORTED_CONTRACT_VERSIONS, SUPPORTED_CONTRACT_VERSIONS as SUPPORTED_CONTRACT_VERSIONS$1, buildTrackingEnvelope, hashUserData, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope, validateEnvelope as validateEnvelope$1 } from "@fire-spark/analytics";
|
|
4
|
+
import { HASHED_USER_WIRE_KEYS, MAX_ENVELOPE_EVENTS, SERVER_PROVIDER_IDS, SUPPORTED_CONTRACT_VERSIONS, SUPPORTED_CONTRACT_VERSIONS as SUPPORTED_CONTRACT_VERSIONS$1, appTrackingAllowed, buildTrackingEnvelope, hashUserData, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope, validateEnvelope as validateEnvelope$1 } from "@fire-spark/analytics";
|
|
4
5
|
//#region src/env.ts
|
|
5
6
|
const processEnv = () => {
|
|
6
7
|
return globalThis.process?.env ?? {};
|
|
@@ -140,6 +141,17 @@ const targets = (provider, event) => {
|
|
|
140
141
|
if (!isBuiltin(provider.id)) return true;
|
|
141
142
|
return event.providers.includes(provider.id);
|
|
142
143
|
};
|
|
144
|
+
const DEFAULT_RUNTIMES = ["web"];
|
|
145
|
+
/** A provider without `runtimes` only maps web events. */
|
|
146
|
+
const supportsRuntime = (provider, event) => {
|
|
147
|
+
return (provider.runtimes ?? DEFAULT_RUNTIMES).includes(runtimeOf(event));
|
|
148
|
+
};
|
|
149
|
+
/** Whether some configured provider would send this event. */
|
|
150
|
+
const isDeliverable = (pipeline, event) => {
|
|
151
|
+
return pipeline.providers.some((provider) => {
|
|
152
|
+
return targets(provider, event) && supportsRuntime(provider, event);
|
|
153
|
+
});
|
|
154
|
+
};
|
|
143
155
|
const skippedFor = (pipeline, event, reason) => {
|
|
144
156
|
const b1 = {
|
|
145
157
|
eventIds: [event.event_id],
|
|
@@ -178,8 +190,11 @@ const warnUnconfigured = (pipeline, events) => {
|
|
|
178
190
|
const verifyOne = async (pipeline, event, options) => {
|
|
179
191
|
const verifyEvent = pipeline.verifyEvent;
|
|
180
192
|
let result;
|
|
193
|
+
const context = options.verifyContext;
|
|
194
|
+
const input = contractEvent(event);
|
|
181
195
|
try {
|
|
182
|
-
result = await verifyEvent(
|
|
196
|
+
if (context) result = await verifyEvent(input, context);
|
|
197
|
+
else result = await verifyEvent(input);
|
|
183
198
|
} catch {
|
|
184
199
|
throw new VerifyFailure();
|
|
185
200
|
}
|
|
@@ -337,8 +352,28 @@ const reportFailure = (pipeline, result) => {
|
|
|
337
352
|
pipeline.report(issue);
|
|
338
353
|
};
|
|
339
354
|
const runProvider = async (pipeline, provider, events) => {
|
|
340
|
-
const
|
|
341
|
-
|
|
355
|
+
const listed = events.filter((event) => targets(provider, event));
|
|
356
|
+
const reason = "provider_not_supported_for_runtime";
|
|
357
|
+
const unsupported = [];
|
|
358
|
+
const targeted = listed.filter((event) => {
|
|
359
|
+
if (supportsRuntime(provider, event)) return true;
|
|
360
|
+
const b1 = {
|
|
361
|
+
provider: provider.id,
|
|
362
|
+
eventIds: [event.event_id]
|
|
363
|
+
};
|
|
364
|
+
const b2 = {
|
|
365
|
+
outcome: "skipped",
|
|
366
|
+
reason,
|
|
367
|
+
retryable: false
|
|
368
|
+
};
|
|
369
|
+
unsupported.push({
|
|
370
|
+
...b1,
|
|
371
|
+
...b2,
|
|
372
|
+
attempts: 0
|
|
373
|
+
});
|
|
374
|
+
return false;
|
|
375
|
+
});
|
|
376
|
+
if (targeted.length === 0) return unsupported;
|
|
342
377
|
const signal = AbortSignal.timeout(pipeline.retry.totalBudgetMs);
|
|
343
378
|
const c1 = {
|
|
344
379
|
fetch: pipeline.fetch,
|
|
@@ -370,9 +405,10 @@ const runProvider = async (pipeline, provider, events) => {
|
|
|
370
405
|
provider: provider.id,
|
|
371
406
|
message: p1
|
|
372
407
|
});
|
|
373
|
-
|
|
408
|
+
const failure = failedResult(provider, targeted, "invalid_payload");
|
|
409
|
+
return [...unsupported, failure];
|
|
374
410
|
}
|
|
375
|
-
const results = [...prepared.skipped];
|
|
411
|
+
const results = [...unsupported, ...prepared.skipped];
|
|
376
412
|
for (const batch of chunk$1(prepared.ready, provider.maxBatchSize)) try {
|
|
377
413
|
results.push(await provider.send(batch, ctx));
|
|
378
414
|
} catch {
|
|
@@ -539,6 +575,32 @@ const keepAlive = (waitUntil, delivery) => {
|
|
|
539
575
|
return false;
|
|
540
576
|
}
|
|
541
577
|
};
|
|
578
|
+
const reportInvalid = (pipeline, invalid) => {
|
|
579
|
+
if (invalid.length === 0) return;
|
|
580
|
+
const p1 = `${invalid.length} event(s) failed validation`;
|
|
581
|
+
const b1 = {
|
|
582
|
+
level: "warning",
|
|
583
|
+
source: "validation"
|
|
584
|
+
};
|
|
585
|
+
const ids = invalid.flatMap((item) => item.event_id ?? []);
|
|
586
|
+
pipeline.report({
|
|
587
|
+
...b1,
|
|
588
|
+
message: p1,
|
|
589
|
+
eventIds: ids
|
|
590
|
+
});
|
|
591
|
+
};
|
|
592
|
+
/** Answers `503` so the client retries; reports why. */
|
|
593
|
+
const failClosed = (pipeline, error) => {
|
|
594
|
+
const verify = error instanceof VerifyFailure;
|
|
595
|
+
const source = verify ? "verify" : "config";
|
|
596
|
+
const message = `${verify ? "verifyEvent threw" : "tracking handler failed"}; answered 503 so the client retries`;
|
|
597
|
+
pipeline.report({
|
|
598
|
+
level: "error",
|
|
599
|
+
source,
|
|
600
|
+
message
|
|
601
|
+
});
|
|
602
|
+
return fail(503, "internal_error");
|
|
603
|
+
};
|
|
542
604
|
/**
|
|
543
605
|
* `POST` handler for the relay endpoint (`serverSide.endpoint`), for any
|
|
544
606
|
* runtime with web `Request` / `Response` (Next.js route handlers, Hono,
|
|
@@ -578,7 +640,8 @@ const createTrackingHandler = (options) => {
|
|
|
578
640
|
...b1,
|
|
579
641
|
...b2
|
|
580
642
|
}, validation());
|
|
581
|
-
|
|
643
|
+
const clean = result.ok ? result.envelope.events[0] : void 0;
|
|
644
|
+
return clean && runtimeOf(clean) === "web" ? clean : null;
|
|
582
645
|
};
|
|
583
646
|
const handle = async (request) => {
|
|
584
647
|
if (request.method !== "POST") return json(405, { error: "method_not_allowed" }, { allow: "POST" });
|
|
@@ -592,21 +655,18 @@ const createTrackingHandler = (options) => {
|
|
|
592
655
|
const result = validateEnvelope$1(body, validation());
|
|
593
656
|
if (!result.ok && result.error === "unsupported_contract_version") return unsupported();
|
|
594
657
|
if (!result.ok) return fail(400, result.error);
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
const ids = result.rejected.flatMap((item) => item.event_id ?? []);
|
|
602
|
-
pipeline.report({
|
|
603
|
-
...b1,
|
|
604
|
-
message: p1,
|
|
605
|
-
eventIds: ids
|
|
658
|
+
const invalid = [...result.rejected];
|
|
659
|
+
const web = result.envelope.events.filter((event) => {
|
|
660
|
+
if (runtimeOf(event) === "web") return true;
|
|
661
|
+
invalid.push({
|
|
662
|
+
event_id: event.event_id,
|
|
663
|
+
reason: "invalid_event"
|
|
606
664
|
});
|
|
607
|
-
|
|
665
|
+
return false;
|
|
666
|
+
});
|
|
667
|
+
reportInvalid(pipeline, invalid);
|
|
608
668
|
const meta = cleanRequestMeta(getMeta(request));
|
|
609
|
-
const events =
|
|
669
|
+
const events = web.map((event) => ({
|
|
610
670
|
...event,
|
|
611
671
|
...meta
|
|
612
672
|
}));
|
|
@@ -617,7 +677,7 @@ const createTrackingHandler = (options) => {
|
|
|
617
677
|
const b2 = [admission.deliverable, admission.skipped];
|
|
618
678
|
const delivery = deliverEvents(pipeline, ...b2);
|
|
619
679
|
if (!keepAlive(options.waitUntil, delivery)) await delivery;
|
|
620
|
-
const rejected = [...
|
|
680
|
+
const rejected = [...invalid, ...admission.rejected];
|
|
621
681
|
return json(202, {
|
|
622
682
|
accepted: admission.accepted,
|
|
623
683
|
rejected
|
|
@@ -627,15 +687,126 @@ const createTrackingHandler = (options) => {
|
|
|
627
687
|
try {
|
|
628
688
|
return await handle(request);
|
|
629
689
|
} catch (error) {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
690
|
+
return failClosed(pipeline, error);
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
};
|
|
694
|
+
const configError = (code, message) => {
|
|
695
|
+
return new AnalyticsServerConfigError(code, message);
|
|
696
|
+
};
|
|
697
|
+
const parseAllowedApps = (apps) => {
|
|
698
|
+
const p1 = "createAppTrackingHandler: allowedApps needs at least one app id";
|
|
699
|
+
if (!Array.isArray(apps)) throw configError("ANALYTICS_SERVER_APP_ALLOWLIST_REQUIRED", p1);
|
|
700
|
+
const ids = apps.flatMap((id) => {
|
|
701
|
+
return typeof id === "string" && id.trim() ? [id.trim()] : [];
|
|
702
|
+
});
|
|
703
|
+
if (ids.length === 0) throw configError("ANALYTICS_SERVER_APP_ALLOWLIST_REQUIRED", p1);
|
|
704
|
+
return new Set(ids);
|
|
705
|
+
};
|
|
706
|
+
const assertAppOptions = (options) => {
|
|
707
|
+
if (typeof options.authenticate !== "function") throw configError("ANALYTICS_SERVER_AUTHENTICATE_REQUIRED", "createAppTrackingHandler: authenticate is required");
|
|
708
|
+
if (typeof options.verifyEvent !== "function") throw configError("ANALYTICS_SERVER_VERIFY_EVENT_REQUIRED", "createAppTrackingHandler: verifyEvent is required");
|
|
709
|
+
return parseAllowedApps(options.allowedApps);
|
|
710
|
+
};
|
|
711
|
+
const parseEvents = (body) => {
|
|
712
|
+
return JSON.parse(body).events;
|
|
713
|
+
};
|
|
714
|
+
/**
|
|
715
|
+
* `POST` handler for app (React Native) events. No `Origin` gate: the
|
|
716
|
+
* request must pass `authenticate`, come from an app in `allowedApps` and
|
|
717
|
+
* carry an event in `relayedEvents` (default `purchase`), which is always
|
|
718
|
+
* re-read by `verifyEvent` before any provider sees it. Same response as
|
|
719
|
+
* `createTrackingHandler`.
|
|
720
|
+
*/
|
|
721
|
+
const createAppTrackingHandler = (options) => {
|
|
722
|
+
const apps = assertAppOptions(options);
|
|
723
|
+
const relayed = options.relayedEvents ?? ["purchase"];
|
|
724
|
+
const names = new Set(relayed);
|
|
725
|
+
const pipeline = createPipeline({
|
|
726
|
+
...options,
|
|
727
|
+
verifyEventNames: [...names],
|
|
728
|
+
allowUnverifiedPurchases: false
|
|
729
|
+
});
|
|
730
|
+
const maxBytes = options.maxBodyBytes ?? 65536;
|
|
731
|
+
const getMeta = options.getRequestMeta ?? defaultRequestMeta;
|
|
732
|
+
const providers = SERVER_PROVIDER_IDS;
|
|
733
|
+
const revalidate = (event) => {
|
|
734
|
+
const check = checkAppEvent(event, pipeline.now(), providers);
|
|
735
|
+
return "event" in check ? check.event : null;
|
|
736
|
+
};
|
|
737
|
+
const policyOf = (event) => {
|
|
738
|
+
const app = appContextOf(event);
|
|
739
|
+
if (!app || !apps.has(app.id)) return "app_not_allowed";
|
|
740
|
+
if (!event.consent.ads || !appTrackingAllowed(app)) return "consent_denied";
|
|
741
|
+
if (!names.has(event.name)) return "event_not_relayed";
|
|
742
|
+
if (!isDeliverable(pipeline, event)) return "provider_not_supported_for_runtime";
|
|
743
|
+
return null;
|
|
744
|
+
};
|
|
745
|
+
const handle = async (request) => {
|
|
746
|
+
if (request.method !== "POST") return json(405, { error: "method_not_allowed" }, { allow: "POST" });
|
|
747
|
+
if ((await options.authenticate(request))?.ok !== true) return json(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
|
|
748
|
+
if (!isJsonContentType(request.headers.get("content-type"))) return fail(415, "unsupported_media_type");
|
|
749
|
+
if (declaredTooLarge(request, maxBytes)) return fail(413, "payload_too_large");
|
|
750
|
+
if (!contractHeaderOk(request.headers.get("x-firespark-contract"))) return unsupported();
|
|
751
|
+
const body = await readBodyLimited(request, maxBytes);
|
|
752
|
+
if (body === null) return fail(413, "payload_too_large");
|
|
753
|
+
const now = pipeline.now();
|
|
754
|
+
const result = validateEnvelope$1(body, {
|
|
755
|
+
now,
|
|
756
|
+
providers,
|
|
757
|
+
runtimes: APP_RUNTIMES
|
|
758
|
+
});
|
|
759
|
+
if (!result.ok && result.error === "unsupported_contract_version") return unsupported();
|
|
760
|
+
if (!result.ok) return fail(400, result.error);
|
|
761
|
+
const invalid = [];
|
|
762
|
+
const refused = [];
|
|
763
|
+
const skipped = [];
|
|
764
|
+
const meta = cleanRequestMeta(getMeta(request));
|
|
765
|
+
const events = [];
|
|
766
|
+
for (const raw of parseEvents(body)) {
|
|
767
|
+
const check = checkAppEvent(raw, now, providers);
|
|
768
|
+
if (!("event" in check)) {
|
|
769
|
+
invalid.push(check);
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
const reason = policyOf(check.event);
|
|
773
|
+
if (!reason) {
|
|
774
|
+
events.push({
|
|
775
|
+
...check.event,
|
|
776
|
+
...meta
|
|
777
|
+
});
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
refused.push({
|
|
781
|
+
event_id: check.event.event_id,
|
|
782
|
+
reason
|
|
637
783
|
});
|
|
638
|
-
|
|
784
|
+
skipped.push(...skippedFor(pipeline, check.event, reason));
|
|
785
|
+
}
|
|
786
|
+
reportInvalid(pipeline, invalid);
|
|
787
|
+
const admission = await admitEvents(pipeline, events, {
|
|
788
|
+
verify: true,
|
|
789
|
+
revalidate,
|
|
790
|
+
verifyContext: { request }
|
|
791
|
+
});
|
|
792
|
+
const b2 = [...skipped, ...admission.skipped];
|
|
793
|
+
const delivery = deliverEvents(pipeline, admission.deliverable, b2);
|
|
794
|
+
if (!keepAlive(options.waitUntil, delivery)) await delivery;
|
|
795
|
+
const rejected = [
|
|
796
|
+
...invalid,
|
|
797
|
+
...refused,
|
|
798
|
+
...admission.rejected
|
|
799
|
+
];
|
|
800
|
+
return json(202, {
|
|
801
|
+
accepted: admission.accepted,
|
|
802
|
+
rejected
|
|
803
|
+
});
|
|
804
|
+
};
|
|
805
|
+
return async (request) => {
|
|
806
|
+
try {
|
|
807
|
+
return await handle(request);
|
|
808
|
+
} catch (error) {
|
|
809
|
+
return failClosed(pipeline, error);
|
|
639
810
|
}
|
|
640
811
|
};
|
|
641
812
|
};
|
|
@@ -747,4 +918,4 @@ const createServerTracker = (options) => {
|
|
|
747
918
|
return { track };
|
|
748
919
|
};
|
|
749
920
|
//#endregion
|
|
750
|
-
export { AnalyticsServerConfigError, CONTRACT_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_RETRY_POLICY, IDEMPOTENCY_TTL_SECONDS, JsonNumber, SUPPORTED_CONTRACT_VERSIONS, backoffDelay, cleanIp, cleanUserAgent, createServerTracker, createTrackingHandler, decimalNumber, decimalText, defaultRequestMeta, defineServerProvider, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, postJson, redactText, sha256Hex, stringifyJson, upgradeEnvelope, validateEnvelope, withProviderRetry };
|
|
921
|
+
export { AnalyticsServerConfigError, CONTRACT_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_RETRY_POLICY, IDEMPOTENCY_TTL_SECONDS, JsonNumber, SUPPORTED_CONTRACT_VERSIONS, backoffDelay, cleanIp, cleanUserAgent, createAppTrackingHandler, createServerTracker, createTrackingHandler, decimalNumber, decimalText, defaultRequestMeta, defineServerProvider, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, postJson, redactText, sha256Hex, stringifyJson, upgradeEnvelope, validateEnvelope, withProviderRetry };
|
package/dist/meta.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as ServerProvider, R as JsonNumber, T as ResolvedEvent, i as HttpReply, t as AttemptOutcome } from "./retry-BRNUy4Of.js";
|
|
2
|
+
import "@fire-spark/analytics";
|
|
2
3
|
//#region src/meta.types.d.ts
|
|
3
4
|
interface MetaDataProcessingOptions {
|
|
4
5
|
/** For example `["LDU"]` (Limited Data Use). */
|
|
@@ -21,6 +22,79 @@ interface MetaConversionsApiOptions {
|
|
|
21
22
|
allowTestInProduction?: boolean;
|
|
22
23
|
dataProcessingOptions?: MetaDataProcessingOptions;
|
|
23
24
|
}
|
|
25
|
+
interface MetaAppConversionsApiOptions {
|
|
26
|
+
/** Numeric id of the dataset linked to the app in Events Manager. */
|
|
27
|
+
datasetId: string;
|
|
28
|
+
/** Conversions API token. Server only, never logged. */
|
|
29
|
+
accessToken: string;
|
|
30
|
+
/** Default `v27.0`. */
|
|
31
|
+
graphVersion?: `v${number}.0`;
|
|
32
|
+
/** Events Manager → Test Events. Dropped in production. */
|
|
33
|
+
testEventCode?: string;
|
|
34
|
+
/** Keeps `testEventCode` in production. */
|
|
35
|
+
allowTestInProduction?: boolean;
|
|
36
|
+
/** Limited Data Use. Not set by default. */
|
|
37
|
+
dataProcessingOptions?: MetaDataProcessingOptions;
|
|
38
|
+
/**
|
|
39
|
+
* Contract name → Meta `event_name`, merged over the default
|
|
40
|
+
* `{ purchase: "fb_mobile_purchase" }`. Use it for the Test Events check
|
|
41
|
+
* of `Purchase` against `fb_mobile_purchase`.
|
|
42
|
+
*/
|
|
43
|
+
eventNames?: Readonly<Record<string, string>>;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/meta.shared.d.ts
|
|
47
|
+
/** Meta response → outcome, per the retry matrix. */
|
|
48
|
+
declare const classifyMetaReply: (reply: HttpReply, expected: number) => AttemptOutcome;
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/meta.app.d.ts
|
|
51
|
+
/** One Conversions API app event (`action_source: "app"`). */
|
|
52
|
+
declare const metaAppEventOf: (event: ResolvedEvent, options: MetaAppConversionsApiOptions) => Promise<Partial<{
|
|
53
|
+
data_processing_options?: string[] | undefined;
|
|
54
|
+
data_processing_options_country?: number | undefined;
|
|
55
|
+
data_processing_options_state?: number | undefined;
|
|
56
|
+
event_name: string | undefined;
|
|
57
|
+
event_time: number;
|
|
58
|
+
event_id: string;
|
|
59
|
+
action_source: string;
|
|
60
|
+
app_data: Partial<{
|
|
61
|
+
advertiser_tracking_enabled: number;
|
|
62
|
+
application_tracking_enabled: number;
|
|
63
|
+
vendor_id: string | undefined;
|
|
64
|
+
install_referrer: string | undefined;
|
|
65
|
+
extinfo: string[];
|
|
66
|
+
}>;
|
|
67
|
+
user_data: Partial<{
|
|
68
|
+
anon_id: string;
|
|
69
|
+
madid: string | undefined;
|
|
70
|
+
client_ip_address: string | undefined;
|
|
71
|
+
em: string[] | undefined;
|
|
72
|
+
ph: string[] | undefined;
|
|
73
|
+
external_id: string[] | undefined;
|
|
74
|
+
fn: string[] | undefined;
|
|
75
|
+
ln: string[] | undefined;
|
|
76
|
+
country: string[] | undefined;
|
|
77
|
+
}>;
|
|
78
|
+
custom_data: Partial<{
|
|
79
|
+
currency: string | undefined;
|
|
80
|
+
value: JsonNumber | undefined;
|
|
81
|
+
order_id: string | undefined;
|
|
82
|
+
content_type: string | undefined;
|
|
83
|
+
contents: Partial<{
|
|
84
|
+
id: string;
|
|
85
|
+
quantity: JsonNumber | undefined;
|
|
86
|
+
item_price: JsonNumber | undefined;
|
|
87
|
+
}>[] | undefined;
|
|
88
|
+
num_items: JsonNumber | undefined;
|
|
89
|
+
}>;
|
|
90
|
+
}> | undefined>;
|
|
91
|
+
/**
|
|
92
|
+
* Meta Conversions API destination for app events (React Native), sent
|
|
93
|
+
* to the dataset linked to the app. Use it with `createAppTrackingHandler`.
|
|
94
|
+
* The token travels in the JSON body, never in the URL, and is never
|
|
95
|
+
* logged.
|
|
96
|
+
*/
|
|
97
|
+
declare const metaAppConversionsApi: (options: MetaAppConversionsApiOptions) => ServerProvider;
|
|
24
98
|
//#endregion
|
|
25
99
|
//#region src/meta.d.ts
|
|
26
100
|
/** One Conversions API server event. `event_name` is the pixel's name. */
|
|
@@ -32,7 +106,7 @@ declare const metaEventOf: (event: ResolvedEvent, options: MetaConversionsApiOpt
|
|
|
32
106
|
event_time: number;
|
|
33
107
|
event_id: string;
|
|
34
108
|
action_source: string;
|
|
35
|
-
event_source_url: string;
|
|
109
|
+
event_source_url: string | undefined;
|
|
36
110
|
referrer_url: string | undefined;
|
|
37
111
|
user_data: Partial<{
|
|
38
112
|
em: string[] | undefined;
|
|
@@ -60,12 +134,10 @@ declare const metaEventOf: (event: ResolvedEvent, options: MetaConversionsApiOpt
|
|
|
60
134
|
num_items: JsonNumber | undefined;
|
|
61
135
|
}>;
|
|
62
136
|
}>>;
|
|
63
|
-
/** Meta response → outcome, per the retry matrix. */
|
|
64
|
-
declare const classifyMetaReply: (reply: HttpReply, expected: number) => AttemptOutcome;
|
|
65
137
|
/**
|
|
66
|
-
* Meta Conversions API destination. The token travels in
|
|
67
|
-
* never in the URL, and is never logged.
|
|
138
|
+
* Meta Conversions API destination for web events. The token travels in
|
|
139
|
+
* the JSON body, never in the URL, and is never logged.
|
|
68
140
|
*/
|
|
69
141
|
declare const metaConversionsApi: (options: MetaConversionsApiOptions) => ServerProvider;
|
|
70
142
|
//#endregion
|
|
71
|
-
export { type MetaConversionsApiOptions, classifyMetaReply, metaConversionsApi, metaEventOf };
|
|
143
|
+
export { type MetaAppConversionsApiOptions, type MetaConversionsApiOptions, type MetaDataProcessingOptions, classifyMetaReply, metaAppConversionsApi, metaAppEventOf, metaConversionsApi, metaEventOf };
|
package/dist/meta.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
+
import { n as appContextOf } from "./app-DlzC8Iq0.js";
|
|
1
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";
|
|
2
3
|
import { n as testCodeFor } from "./provider-DIOneNqa.js";
|
|
3
4
|
import { providerEventName, sha256Hex } from "@fire-spark/analytics";
|
|
4
5
|
import { Big } from "big.js";
|
|
5
|
-
//#region src/meta.ts
|
|
6
|
-
const
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
const
|
|
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}$/;
|
|
10
11
|
const GRAPH_VERSION = /^v\d{1,3}\.0$/;
|
|
12
|
+
const GRAPH_BASE = "https://graph.facebook.com";
|
|
11
13
|
/** Graph errors worth retrying: 1, 2 unknown/service; 4, 17, 32, 613 limits. */
|
|
12
14
|
const RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
|
|
13
15
|
4,
|
|
@@ -17,7 +19,9 @@ const RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
|
|
|
17
19
|
]);
|
|
18
20
|
const TRANSIENT_CODES = /* @__PURE__ */ new Set([1, 2]);
|
|
19
21
|
const ZERO = new Big(0);
|
|
20
|
-
const list = (value) =>
|
|
22
|
+
const list = (value) => {
|
|
23
|
+
return value ? [value] : void 0;
|
|
24
|
+
};
|
|
21
25
|
const contentsOf = (event) => {
|
|
22
26
|
return (event.items ?? []).map((item) => {
|
|
23
27
|
return compact({
|
|
@@ -34,6 +38,347 @@ const numItemsOf = (event) => {
|
|
|
34
38
|
const add = (sum, quantity) => sum.plus(quantity ?? "1");
|
|
35
39
|
return decimalNumber(items.reduce((sum, item) => add(sum, item.quantity), ZERO).toFixed());
|
|
36
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;
|
|
37
382
|
const customDataOf = (event) => {
|
|
38
383
|
const items = event.items ?? [];
|
|
39
384
|
const priced = items.length > 0;
|
|
@@ -84,18 +429,6 @@ const userDataOf = async (event) => {
|
|
|
84
429
|
...u9
|
|
85
430
|
});
|
|
86
431
|
};
|
|
87
|
-
const processingOptionsOf = (options) => {
|
|
88
|
-
const dpo = options.dataProcessingOptions;
|
|
89
|
-
if (!dpo) return {};
|
|
90
|
-
const d1 = { data_processing_options: [...dpo.options] };
|
|
91
|
-
const d2 = { data_processing_options_country: dpo.country };
|
|
92
|
-
const d3 = { data_processing_options_state: dpo.state };
|
|
93
|
-
return compact({
|
|
94
|
-
...d1,
|
|
95
|
-
...d2,
|
|
96
|
-
...d3
|
|
97
|
-
});
|
|
98
|
-
};
|
|
99
432
|
/** One Conversions API server event. `event_name` is the pixel's name. */
|
|
100
433
|
const metaEventOf = async (event, options) => {
|
|
101
434
|
const e1 = {
|
|
@@ -110,7 +443,7 @@ const metaEventOf = async (event, options) => {
|
|
|
110
443
|
const e4 = { referrer_url: event.referrer_url };
|
|
111
444
|
const e5 = { user_data: await userDataOf(event) };
|
|
112
445
|
const e6 = { custom_data: customDataOf(event) };
|
|
113
|
-
const e7 = processingOptionsOf(options);
|
|
446
|
+
const e7 = processingOptionsOf(options.dataProcessingOptions);
|
|
114
447
|
return compact({
|
|
115
448
|
...e1,
|
|
116
449
|
...e2,
|
|
@@ -121,89 +454,15 @@ const metaEventOf = async (event, options) => {
|
|
|
121
454
|
...e7
|
|
122
455
|
});
|
|
123
456
|
};
|
|
124
|
-
const recordOf = (value) => {
|
|
125
|
-
return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
126
|
-
};
|
|
127
|
-
const textOf = (value) => {
|
|
128
|
-
return typeof value === "string" && value ? value : void 0;
|
|
129
|
-
};
|
|
130
|
-
const failed = (reason, retryable) => {
|
|
131
|
-
return {
|
|
132
|
-
outcome: "failed",
|
|
133
|
-
reason,
|
|
134
|
-
retryable
|
|
135
|
-
};
|
|
136
|
-
};
|
|
137
|
-
const classifyError = (status, error) => {
|
|
138
|
-
const code = typeof error.code === "number" ? error.code : void 0;
|
|
139
|
-
if (code === 190) return failed("auth", false);
|
|
140
|
-
if (code !== void 0 && code >= 200 && code <= 299) return failed("auth", false);
|
|
141
|
-
if (code === 100) return failed("invalid_payload", false);
|
|
142
|
-
if (code !== void 0 && RATE_LIMIT_CODES.has(code)) return failed("rate_limited", true);
|
|
143
|
-
if (code !== void 0 && TRANSIENT_CODES.has(code)) return failed("upstream_error", true);
|
|
144
|
-
if (error.is_transient === true) return failed("upstream_error", true);
|
|
145
|
-
if (status >= 500) return failed("upstream_error", true);
|
|
146
|
-
if (status === 429) return failed("rate_limited", true);
|
|
147
|
-
if (status === 401 || status === 403) return failed("auth", false);
|
|
148
|
-
return failed("invalid_payload", false);
|
|
149
|
-
};
|
|
150
|
-
/** Meta response → outcome, per the retry matrix. */
|
|
151
|
-
const classifyMetaReply = (reply, expected) => {
|
|
152
|
-
const body = recordOf(reply.body);
|
|
153
|
-
const error = recordOf(body.error);
|
|
154
|
-
const hasError = Object.keys(error).length > 0;
|
|
155
|
-
const traceId = textOf(error.fbtrace_id) ?? textOf(body.fbtrace_id);
|
|
156
|
-
const base = {
|
|
157
|
-
httpStatus: reply.status,
|
|
158
|
-
traceId
|
|
159
|
-
};
|
|
160
|
-
if (reply.status === 200 && !hasError) {
|
|
161
|
-
if (body.events_received === expected) return {
|
|
162
|
-
...base,
|
|
163
|
-
outcome: "sent",
|
|
164
|
-
retryable: false
|
|
165
|
-
};
|
|
166
|
-
return {
|
|
167
|
-
...base,
|
|
168
|
-
...failed("upstream_error", false)
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
const code = typeof error.code === "number" ? error.code : void 0;
|
|
172
|
-
const outcome = classifyError(reply.status, error);
|
|
173
|
-
return {
|
|
174
|
-
...base,
|
|
175
|
-
...outcome,
|
|
176
|
-
providerCode: code
|
|
177
|
-
};
|
|
178
|
-
};
|
|
179
457
|
const assertOptions = (options) => {
|
|
180
|
-
if (!
|
|
181
|
-
|
|
182
|
-
const version = options.graphVersion ?? DEFAULT_GRAPH_VERSION;
|
|
183
|
-
if (!GRAPH_VERSION.test(version)) throw new AnalyticsServerConfigError("META_GRAPH_VERSION_INVALID", "metaConversionsApi: graphVersion must look like v27.0");
|
|
184
|
-
return version;
|
|
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);
|
|
185
460
|
};
|
|
186
461
|
const prepare = (events) => {
|
|
187
462
|
const ready = [];
|
|
188
463
|
const skipped = [];
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
provider: PROVIDER,
|
|
192
|
-
eventIds: [event.event_id]
|
|
193
|
-
};
|
|
194
|
-
const b2 = {
|
|
195
|
-
outcome: "skipped",
|
|
196
|
-
reason,
|
|
197
|
-
retryable: false
|
|
198
|
-
};
|
|
199
|
-
skipped.push({
|
|
200
|
-
...b1,
|
|
201
|
-
...b2,
|
|
202
|
-
attempts: 0
|
|
203
|
-
});
|
|
204
|
-
};
|
|
205
|
-
for (const event of events) if (!providerEventName(PROVIDER, event.name)) skip(event, "not_mapped");
|
|
206
|
-
else if (!event.userAgent) skip(event, "no_identifier");
|
|
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"));
|
|
207
466
|
else ready.push(event);
|
|
208
467
|
return {
|
|
209
468
|
ready,
|
|
@@ -211,14 +470,12 @@ const prepare = (events) => {
|
|
|
211
470
|
};
|
|
212
471
|
};
|
|
213
472
|
/**
|
|
214
|
-
* Meta Conversions API destination. The token travels in
|
|
215
|
-
* never in the URL, and is never logged.
|
|
473
|
+
* Meta Conversions API destination for web events. The token travels in
|
|
474
|
+
* the JSON body, never in the URL, and is never logged.
|
|
216
475
|
*/
|
|
217
476
|
const metaConversionsApi = (options) => {
|
|
218
|
-
const
|
|
219
|
-
const pixelId = String(options.pixelId);
|
|
477
|
+
const url = metaEventsUrl(assertOptions(options), String(options.pixelId));
|
|
220
478
|
const accessToken = options.accessToken.trim();
|
|
221
|
-
const url = `https://graph.facebook.com/${version}/${pixelId}/events`;
|
|
222
479
|
const send = async (events, ctx) => {
|
|
223
480
|
const body = stringifyJson({
|
|
224
481
|
...compact({
|
|
@@ -227,26 +484,15 @@ const metaConversionsApi = (options) => {
|
|
|
227
484
|
}),
|
|
228
485
|
access_token: accessToken
|
|
229
486
|
});
|
|
230
|
-
|
|
231
|
-
const reply = await postJson(ctx, {
|
|
232
|
-
url,
|
|
233
|
-
body
|
|
234
|
-
}, signal);
|
|
235
|
-
return classifyMetaReply(reply, events.length);
|
|
236
|
-
});
|
|
237
|
-
const eventIds = events.map((event) => event.event_id);
|
|
238
|
-
return {
|
|
239
|
-
provider: PROVIDER,
|
|
240
|
-
eventIds,
|
|
241
|
-
...final
|
|
242
|
-
};
|
|
487
|
+
return sendMetaBatch(ctx, url, body, events);
|
|
243
488
|
};
|
|
244
489
|
return {
|
|
245
490
|
id: PROVIDER,
|
|
246
|
-
maxBatchSize:
|
|
491
|
+
maxBatchSize: META_MAX_BATCH,
|
|
492
|
+
runtimes: ["web"],
|
|
247
493
|
prepare,
|
|
248
494
|
send
|
|
249
495
|
};
|
|
250
496
|
};
|
|
251
497
|
//#endregion
|
|
252
|
-
export { classifyMetaReply, metaConversionsApi, metaEventOf };
|
|
498
|
+
export { classifyMetaReply, metaAppConversionsApi, metaAppEventOf, metaConversionsApi, metaEventOf };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HashedUserDataV1, RejectReason, ServerProviderId, TrackingEventV1 } from "@fire-spark/analytics";
|
|
1
|
+
import { AnalyticsRuntime, HashedUserDataV1, RejectReason, ServerProviderId, TrackingEventV1 } from "@fire-spark/analytics";
|
|
2
2
|
//#region src/json.d.ts
|
|
3
3
|
/** A JSON number written exactly as its decimal string. */
|
|
4
4
|
declare class JsonNumber {
|
|
@@ -28,7 +28,7 @@ interface ResolvedEvent extends TrackingEventV1 {
|
|
|
28
28
|
userAgent?: string;
|
|
29
29
|
}
|
|
30
30
|
type ProviderOutcome = "sent" | "skipped" | "failed";
|
|
31
|
-
type ProviderReason = "consent_denied" | "not_mapped" | "no_identifier" | "duplicate" | "verify_rejected" | "verify_not_configured" | "not_configured" | "auth" | "invalid_payload" | "rate_limited" | "upstream_error" | "timeout";
|
|
31
|
+
type ProviderReason = "consent_denied" | "not_mapped" | "no_identifier" | "duplicate" | "verify_rejected" | "verify_not_configured" | "not_configured" | "auth" | "invalid_payload" | "rate_limited" | "upstream_error" | "timeout" | "app_context_missing" | "app_not_allowed" | "provider_not_supported_for_runtime" | "event_not_relayed" | "unauthorized";
|
|
32
32
|
/** What happened to a group of events at one provider. */
|
|
33
33
|
interface ProviderResult {
|
|
34
34
|
provider: ServerProviderId | (string & {});
|
|
@@ -96,6 +96,11 @@ interface ServerProvider {
|
|
|
96
96
|
readonly id: ServerProviderId | (string & {});
|
|
97
97
|
/** Events per request. */
|
|
98
98
|
readonly maxBatchSize: number;
|
|
99
|
+
/**
|
|
100
|
+
* Runtimes whose events this provider maps. Default `["web"]`. Events of
|
|
101
|
+
* another runtime are skipped with `provider_not_supported_for_runtime`.
|
|
102
|
+
*/
|
|
103
|
+
readonly runtimes?: readonly AnalyticsRuntime[];
|
|
99
104
|
/** Local checks only, no I/O. Returns the events to send. */
|
|
100
105
|
prepare(events: ResolvedEvent[]): PreparedEvents;
|
|
101
106
|
send(events: ResolvedEvent[], ctx: ProviderContext): Promise<ProviderResult>;
|
|
@@ -104,14 +109,19 @@ interface ServerProvider {
|
|
|
104
109
|
interface IdempotencyStore {
|
|
105
110
|
claim: (key: string, ttlSeconds: number) => Promise<boolean>;
|
|
106
111
|
}
|
|
112
|
+
/** Second argument of `verifyEvent`, passed by `createAppTrackingHandler`. */
|
|
113
|
+
interface VerifyEventContext {
|
|
114
|
+
/** The app's request, to forward its `Authorization` to your backend. */
|
|
115
|
+
request: Request;
|
|
116
|
+
}
|
|
107
117
|
/**
|
|
108
118
|
* Loads the order behind an event from your backend with server
|
|
109
119
|
* credentials. Return the event with authoritative `value`, `currency` and
|
|
110
120
|
* `items`, or `null` to drop it.
|
|
111
121
|
*/
|
|
112
|
-
type VerifyEvent = (event: TrackingEventV1) => Promise<TrackingEventV1 | null>;
|
|
122
|
+
type VerifyEvent = (event: TrackingEventV1, context?: VerifyEventContext) => Promise<TrackingEventV1 | null>;
|
|
113
123
|
/** Why the relay did not accept an event (the `202` `rejected` list). */
|
|
114
|
-
type RelayRejectReason = RejectReason | "consent_denied" | "verify_rejected" | "verify_not_configured";
|
|
124
|
+
type RelayRejectReason = RejectReason | "consent_denied" | "verify_rejected" | "verify_not_configured" | "app_context_missing" | "app_not_allowed" | "provider_not_supported_for_runtime" | "event_not_relayed" | "unauthorized";
|
|
115
125
|
interface RelayRejectedEvent {
|
|
116
126
|
event_id?: string;
|
|
117
127
|
reason: RelayRejectReason;
|
|
@@ -121,7 +131,7 @@ interface RelayAcceptedBody {
|
|
|
121
131
|
accepted: string[];
|
|
122
132
|
rejected: RelayRejectedEvent[];
|
|
123
133
|
}
|
|
124
|
-
type RelayErrorCode = "method_not_allowed" | "unsupported_media_type" | "payload_too_large" | "origin_not_allowed" | "invalid_json" | "invalid_envelope" | "unsupported_contract_version" | "internal_error";
|
|
134
|
+
type RelayErrorCode = "method_not_allowed" | "unsupported_media_type" | "payload_too_large" | "origin_not_allowed" | "unauthorized" | "invalid_json" | "invalid_envelope" | "unsupported_contract_version" | "internal_error";
|
|
125
135
|
interface RelayErrorBody {
|
|
126
136
|
error: RelayErrorCode;
|
|
127
137
|
/** Only with `unsupported_contract_version`. */
|
|
@@ -169,6 +179,37 @@ interface TrackingHandlerOptions extends DeliveryOptions {
|
|
|
169
179
|
/** Accepts `http://localhost` pages. Ignored in production. */
|
|
170
180
|
allowLocalhost?: boolean;
|
|
171
181
|
}
|
|
182
|
+
/** What `authenticate` decides about an app request. */
|
|
183
|
+
type AppAuthentication = {
|
|
184
|
+
ok: true;
|
|
185
|
+
} | {
|
|
186
|
+
ok: false;
|
|
187
|
+
};
|
|
188
|
+
type DeliveryWithoutVerify = Omit<DeliveryOptions, "verifyEvent" | "allowUnverifiedPurchases" | "verifyEventNames">;
|
|
189
|
+
interface AppTrackingHandlerOptions extends DeliveryWithoutVerify {
|
|
190
|
+
/** Bundle ids / package names (`context.app.id`) allowed. Required. */
|
|
191
|
+
allowedApps: readonly string[];
|
|
192
|
+
/**
|
|
193
|
+
* First gate, before the body is read. A plausible bearer token is
|
|
194
|
+
* enough: `verifyEvent` proves it when it loads the order with it.
|
|
195
|
+
* `{ ok: false }` answers `401 unauthorized`. Required.
|
|
196
|
+
*/
|
|
197
|
+
authenticate: (request: Request) => AppAuthentication | Promise<AppAuthentication>;
|
|
198
|
+
/**
|
|
199
|
+
* Loads the order with the app's own token (`context.request`) and
|
|
200
|
+
* returns the server's value and currency. Required: the app handler has
|
|
201
|
+
* no unverified mode. Every relayed event goes through it.
|
|
202
|
+
*/
|
|
203
|
+
verifyEvent: VerifyEvent;
|
|
204
|
+
/** Event names relayed. Default `["purchase"]`. */
|
|
205
|
+
relayedEvents?: readonly string[];
|
|
206
|
+
/** Same as `createTrackingHandler`. */
|
|
207
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
208
|
+
/** Default: first `x-forwarded-for` entry, else `x-real-ip`. */
|
|
209
|
+
getRequestMeta?: (request: Request) => RequestMeta;
|
|
210
|
+
/** Default 65536. */
|
|
211
|
+
maxBodyBytes?: number;
|
|
212
|
+
}
|
|
172
213
|
/** Raw personal data the tracker hashes before anything else sees it. */
|
|
173
214
|
interface ServerUserInput extends HashedUserDataV1 {
|
|
174
215
|
email?: string;
|
|
@@ -193,7 +234,7 @@ interface ServerTrackResult {
|
|
|
193
234
|
interface ServerTracker {
|
|
194
235
|
track: (events: ServerEventInput[], meta?: RequestMeta) => Promise<ServerTrackResult>;
|
|
195
236
|
}
|
|
196
|
-
type AnalyticsServerConfigErrorCode = "ALLOWED_ORIGINS_REQUIRED" | "ALLOWED_ORIGIN_INVALID" | "PROVIDERS_REQUIRED" | "PROVIDER_DUPLICATED" | "META_PIXEL_ID_INVALID" | "META_ACCESS_TOKEN_REQUIRED" | "META_GRAPH_VERSION_INVALID" | "TIKTOK_PIXEL_CODE_INVALID" | "TIKTOK_ACCESS_TOKEN_REQUIRED" | "TIKTOK_API_VERSION_INVALID" | "GOOGLE_CREDENTIALS_REQUIRED" | "GOOGLE_SERVICE_ACCOUNT_INVALID" | "GOOGLE_PRIVATE_KEY_INVALID" | "GOOGLE_CUSTOMER_ID_INVALID" | "GOOGLE_LOGIN_CUSTOMER_ID_INVALID" | "GOOGLE_CONVERSION_ACTIONS_INVALID";
|
|
237
|
+
type AnalyticsServerConfigErrorCode = "ALLOWED_ORIGINS_REQUIRED" | "ALLOWED_ORIGIN_INVALID" | "PROVIDERS_REQUIRED" | "PROVIDER_DUPLICATED" | "ANALYTICS_SERVER_APP_ALLOWLIST_REQUIRED" | "ANALYTICS_SERVER_AUTHENTICATE_REQUIRED" | "ANALYTICS_SERVER_VERIFY_EVENT_REQUIRED" | "META_PIXEL_ID_INVALID" | "META_DATASET_ID_INVALID" | "META_ACCESS_TOKEN_REQUIRED" | "META_GRAPH_VERSION_INVALID" | "TIKTOK_PIXEL_CODE_INVALID" | "TIKTOK_ACCESS_TOKEN_REQUIRED" | "TIKTOK_API_VERSION_INVALID" | "GOOGLE_CREDENTIALS_REQUIRED" | "GOOGLE_SERVICE_ACCOUNT_INVALID" | "GOOGLE_PRIVATE_KEY_INVALID" | "GOOGLE_CUSTOMER_ID_INVALID" | "GOOGLE_LOGIN_CUSTOMER_ID_INVALID" | "GOOGLE_CONVERSION_ACTIONS_INVALID";
|
|
197
238
|
/** Invalid setup, thrown when the handler or a provider is created. */
|
|
198
239
|
declare class AnalyticsServerConfigError extends Error {
|
|
199
240
|
readonly code: AnalyticsServerConfigErrorCode;
|
|
@@ -234,4 +275,4 @@ declare const postJson: (ctx: ProviderContext, request: {
|
|
|
234
275
|
headers?: Record<string, string>;
|
|
235
276
|
}, signal: AbortSignal) => Promise<HttpReply>;
|
|
236
277
|
//#endregion
|
|
237
|
-
export {
|
|
278
|
+
export { ServerProvider as A, decimalText as B, RelayRejectedEvent as C, ServerEventInput as D, RetryPolicy as E, TrackingHandlerOptions as F, VerifyEvent as I, VerifyEventContext as L, ServerTracker as M, ServerTrackerOptions as N, ServerIssue as O, ServerUserInput as P, JsonNumber as R, RelayRejectReason as S, ResolvedEvent as T, stringifyJson as V, ProviderReason as _, backoffDelay as a, RelayErrorBody as b, AnalyticsServerConfigError as c, AppTrackingHandlerOptions as d, DeliveryOptions as f, ProviderOutcome as g, ProviderContext as h, HttpReply as i, ServerTrackResult as j, ServerIssueSource as k, AnalyticsServerConfigErrorCode as l, PreparedEvents as m, DEFAULT_RETRY_POLICY as n, postJson as o, IdempotencyStore as p, FinalOutcome as r, withProviderRetry as s, AttemptOutcome as t, AppAuthentication as u, ProviderResult as v, RequestMeta as w, RelayErrorCode as x, RelayAcceptedBody as y, decimalNumber as z };
|
package/dist/tiktok.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as ServerProvider, R as JsonNumber, T as ResolvedEvent, _ as ProviderReason, i as HttpReply, t as AttemptOutcome } from "./retry-BRNUy4Of.js";
|
|
2
2
|
//#region src/tiktok.types.d.ts
|
|
3
3
|
interface TikTokEventsApiOptions {
|
|
4
4
|
/** Pixel code from TikTok Events Manager (`event_source_id`). */
|
|
@@ -47,7 +47,7 @@ declare const tiktokEventOf: (event: ResolvedEvent, options: TikTokEventsApiOpti
|
|
|
47
47
|
locale: string | undefined;
|
|
48
48
|
}>;
|
|
49
49
|
page: Partial<{
|
|
50
|
-
url: string;
|
|
50
|
+
url: string | undefined;
|
|
51
51
|
referrer: string | undefined;
|
|
52
52
|
}>;
|
|
53
53
|
properties: Partial<{
|
package/dist/tiktok.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fire-spark/analytics-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"description": "Fire Spark server-side tracking relay (Meta Conversions API, TikTok Events API, Google Data Manager API)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -35,14 +35,14 @@
|
|
|
35
35
|
"big.js": "6.2.1"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@fire-spark/analytics": "^0.
|
|
38
|
+
"@fire-spark/analytics": "^0.27.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/big.js": "6.2.2",
|
|
42
42
|
"tsdown": "^0.22.14",
|
|
43
43
|
"typescript": "^7.0.2",
|
|
44
44
|
"vitest": "^2.1.8",
|
|
45
|
-
"@fire-spark/analytics": "0.
|
|
45
|
+
"@fire-spark/analytics": "0.27.0"
|
|
46
46
|
},
|
|
47
47
|
"publishConfig": {
|
|
48
48
|
"access": "public"
|