@fire-spark/analytics-server 0.0.0-stage → 0.25.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/google.d.ts +112 -0
- package/dist/google.js +651 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +750 -0
- package/dist/json-D5hsBi3M.js +183 -0
- package/dist/meta.d.ts +71 -0
- package/dist/meta.js +252 -0
- package/dist/provider-DIOneNqa.js +22 -0
- package/dist/retry-CKgkb0DS.d.ts +237 -0
- package/dist/tiktok.d.ts +77 -0
- package/dist/tiktok.js +374 -0
- package/package.json +77 -3
- package/README.md +0 -3
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { HashedUserDataV1, RejectReason, ServerProviderId, TrackingEventV1 } from "@fire-spark/analytics";
|
|
2
|
+
//#region src/json.d.ts
|
|
3
|
+
/** A JSON number written exactly as its decimal string. */
|
|
4
|
+
declare class JsonNumber {
|
|
5
|
+
readonly token: string;
|
|
6
|
+
constructor(token: string);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Money for a JSON number field: `"25.90"` is written as `25.90`, never
|
|
10
|
+
* `25.9`. Returns `undefined` for anything that is not a decimal string.
|
|
11
|
+
*/
|
|
12
|
+
declare const decimalNumber: (value: unknown) => JsonNumber | undefined;
|
|
13
|
+
/** Money for a JSON string field, with the same digits. */
|
|
14
|
+
declare const decimalText: (value: unknown) => string | undefined;
|
|
15
|
+
/** `JSON.stringify` that writes `JsonNumber` tokens as they are. */
|
|
16
|
+
declare const stringifyJson: (value: unknown) => string;
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/types.d.ts
|
|
19
|
+
/** Request data the server reads itself. The body never supplies it. */
|
|
20
|
+
interface RequestMeta {
|
|
21
|
+
/** IPv4 or IPv6 of the shopper. */
|
|
22
|
+
ipAddress?: string;
|
|
23
|
+
userAgent?: string;
|
|
24
|
+
}
|
|
25
|
+
/** A validated contract event plus the request data the server read. */
|
|
26
|
+
interface ResolvedEvent extends TrackingEventV1 {
|
|
27
|
+
ipAddress?: string;
|
|
28
|
+
userAgent?: string;
|
|
29
|
+
}
|
|
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";
|
|
32
|
+
/** What happened to a group of events at one provider. */
|
|
33
|
+
interface ProviderResult {
|
|
34
|
+
provider: ServerProviderId | (string & {});
|
|
35
|
+
eventIds: string[];
|
|
36
|
+
outcome: ProviderOutcome;
|
|
37
|
+
reason?: ProviderReason;
|
|
38
|
+
httpStatus?: number;
|
|
39
|
+
/** Meta `error.code`, TikTok `code` or Google `error.status`. */
|
|
40
|
+
providerCode?: string | number;
|
|
41
|
+
/** `true` when a later attempt could still succeed. */
|
|
42
|
+
retryable: boolean;
|
|
43
|
+
/** HTTP requests made (0 when nothing was sent). */
|
|
44
|
+
attempts: number;
|
|
45
|
+
/** Meta `fbtrace_id`, TikTok `request_id` or Google `requestId`. */
|
|
46
|
+
traceId?: string;
|
|
47
|
+
}
|
|
48
|
+
interface RetryPolicy {
|
|
49
|
+
/** Requests per batch, the first included. Default 3. */
|
|
50
|
+
maxAttempts: number;
|
|
51
|
+
/** Default 250. */
|
|
52
|
+
baseDelayMs: number;
|
|
53
|
+
/** Default 2000. */
|
|
54
|
+
maxDelayMs: number;
|
|
55
|
+
/** Time for every attempt of a batch, waits included. Default 8000. */
|
|
56
|
+
totalBudgetMs: number;
|
|
57
|
+
}
|
|
58
|
+
type ServerIssueSource = "validation" | "provider" | "auth" | "config" | "verify" | "idempotency";
|
|
59
|
+
/**
|
|
60
|
+
* A problem worth logging. `message` never carries personal data, hashes,
|
|
61
|
+
* IP addresses, user agents, tokens or URLs with query strings.
|
|
62
|
+
*/
|
|
63
|
+
interface ServerIssue {
|
|
64
|
+
level: "error" | "warning";
|
|
65
|
+
source: ServerIssueSource;
|
|
66
|
+
provider?: string;
|
|
67
|
+
message: string;
|
|
68
|
+
eventIds?: string[];
|
|
69
|
+
providerCode?: string | number;
|
|
70
|
+
traceId?: string;
|
|
71
|
+
}
|
|
72
|
+
interface ProviderContext {
|
|
73
|
+
fetch: typeof fetch;
|
|
74
|
+
/** Aborts when the delivery budget runs out. */
|
|
75
|
+
signal: AbortSignal;
|
|
76
|
+
retry: RetryPolicy;
|
|
77
|
+
report: (issue: ServerIssue) => void;
|
|
78
|
+
/** `VERCEL_ENV` or `NODE_ENV` is `production`, unless overridden. */
|
|
79
|
+
isProduction: boolean;
|
|
80
|
+
/** Epoch ms. */
|
|
81
|
+
now: () => number;
|
|
82
|
+
/** Waits between retries; resolves early when `signal` aborts. */
|
|
83
|
+
sleep: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
84
|
+
/** Number in [0, 1) for the retry jitter. */
|
|
85
|
+
random: () => number;
|
|
86
|
+
}
|
|
87
|
+
interface PreparedEvents {
|
|
88
|
+
ready: ResolvedEvent[];
|
|
89
|
+
skipped: ProviderResult[];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A server destination. Built-in: `metaConversionsApi`, `tiktokEventsApi`,
|
|
93
|
+
* `googleDataManager`.
|
|
94
|
+
*/
|
|
95
|
+
interface ServerProvider {
|
|
96
|
+
readonly id: ServerProviderId | (string & {});
|
|
97
|
+
/** Events per request. */
|
|
98
|
+
readonly maxBatchSize: number;
|
|
99
|
+
/** Local checks only, no I/O. Returns the events to send. */
|
|
100
|
+
prepare(events: ResolvedEvent[]): PreparedEvents;
|
|
101
|
+
send(events: ResolvedEvent[], ctx: ProviderContext): Promise<ProviderResult>;
|
|
102
|
+
}
|
|
103
|
+
/** Store for `claim()`: `true` the first time a key is claimed. */
|
|
104
|
+
interface IdempotencyStore {
|
|
105
|
+
claim: (key: string, ttlSeconds: number) => Promise<boolean>;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Loads the order behind an event from your backend with server
|
|
109
|
+
* credentials. Return the event with authoritative `value`, `currency` and
|
|
110
|
+
* `items`, or `null` to drop it.
|
|
111
|
+
*/
|
|
112
|
+
type VerifyEvent = (event: TrackingEventV1) => Promise<TrackingEventV1 | null>;
|
|
113
|
+
/** Why the relay did not accept an event (the `202` `rejected` list). */
|
|
114
|
+
type RelayRejectReason = RejectReason | "consent_denied" | "verify_rejected" | "verify_not_configured";
|
|
115
|
+
interface RelayRejectedEvent {
|
|
116
|
+
event_id?: string;
|
|
117
|
+
reason: RelayRejectReason;
|
|
118
|
+
}
|
|
119
|
+
/** `202` body. Duplicates count as accepted; they are not sent again. */
|
|
120
|
+
interface RelayAcceptedBody {
|
|
121
|
+
accepted: string[];
|
|
122
|
+
rejected: RelayRejectedEvent[];
|
|
123
|
+
}
|
|
124
|
+
type RelayErrorCode = "method_not_allowed" | "unsupported_media_type" | "payload_too_large" | "origin_not_allowed" | "invalid_json" | "invalid_envelope" | "unsupported_contract_version" | "internal_error";
|
|
125
|
+
interface RelayErrorBody {
|
|
126
|
+
error: RelayErrorCode;
|
|
127
|
+
/** Only with `unsupported_contract_version`. */
|
|
128
|
+
supported?: number[];
|
|
129
|
+
}
|
|
130
|
+
interface DeliveryOptions {
|
|
131
|
+
providers: ServerProvider[];
|
|
132
|
+
/**
|
|
133
|
+
* Runs `purchase` events (and `verifyEventNames`) through your backend
|
|
134
|
+
* before they are sent. Required unless `allowUnverifiedPurchases`.
|
|
135
|
+
*/
|
|
136
|
+
verifyEvent?: VerifyEvent;
|
|
137
|
+
/**
|
|
138
|
+
* Relays purchases without `verifyEvent`. Anyone who can reach the
|
|
139
|
+
* endpoint can then report a purchase that never happened, with any
|
|
140
|
+
* value, to your ad accounts. Leave it off in production.
|
|
141
|
+
*/
|
|
142
|
+
allowUnverifiedPurchases?: boolean;
|
|
143
|
+
/** Event names that need `verifyEvent`. Default `["purchase"]`. */
|
|
144
|
+
verifyEventNames?: string[];
|
|
145
|
+
/** Skips an event id already claimed (48 h), for example in Redis. */
|
|
146
|
+
idempotency?: IdempotencyStore;
|
|
147
|
+
retry?: Partial<RetryPolicy>;
|
|
148
|
+
onIssue?: (issue: ServerIssue) => void;
|
|
149
|
+
onResult?: (results: ProviderResult[]) => void;
|
|
150
|
+
/** Default: global `fetch`. */
|
|
151
|
+
fetch?: typeof fetch;
|
|
152
|
+
/** Default: `VERCEL_ENV` or `NODE_ENV` is `production`. */
|
|
153
|
+
isProduction?: boolean;
|
|
154
|
+
/** Epoch ms. Default `Date.now`. */
|
|
155
|
+
now?: () => number;
|
|
156
|
+
}
|
|
157
|
+
interface TrackingHandlerOptions extends DeliveryOptions {
|
|
158
|
+
/** Origins allowed to post (`https://shop.example.com`). Required. */
|
|
159
|
+
allowedOrigins: string[];
|
|
160
|
+
/**
|
|
161
|
+
* Keeps the function alive after the `202` (`waitUntil` from
|
|
162
|
+
* `@vercel/functions`). Without it, the response waits for delivery.
|
|
163
|
+
*/
|
|
164
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
165
|
+
/** Default: first `x-forwarded-for` entry, else `x-real-ip`. */
|
|
166
|
+
getRequestMeta?: (request: Request) => RequestMeta;
|
|
167
|
+
/** Default 65536. */
|
|
168
|
+
maxBodyBytes?: number;
|
|
169
|
+
/** Accepts `http://localhost` pages. Ignored in production. */
|
|
170
|
+
allowLocalhost?: boolean;
|
|
171
|
+
}
|
|
172
|
+
/** Raw personal data the tracker hashes before anything else sees it. */
|
|
173
|
+
interface ServerUserInput extends HashedUserDataV1 {
|
|
174
|
+
email?: string;
|
|
175
|
+
phone?: string;
|
|
176
|
+
firstName?: string;
|
|
177
|
+
lastName?: string;
|
|
178
|
+
externalId?: string;
|
|
179
|
+
}
|
|
180
|
+
/** A contract event built on the server; `user` may carry raw data. */
|
|
181
|
+
interface ServerEventInput extends Omit<TrackingEventV1, "user"> {
|
|
182
|
+
user: ServerUserInput;
|
|
183
|
+
}
|
|
184
|
+
interface ServerTrackerOptions extends DeliveryOptions {
|
|
185
|
+
/** ISO 3166-1 alpha-2 for phones without a country code. */
|
|
186
|
+
defaultCountry?: string;
|
|
187
|
+
}
|
|
188
|
+
interface ServerTrackResult {
|
|
189
|
+
accepted: string[];
|
|
190
|
+
rejected: RelayRejectedEvent[];
|
|
191
|
+
results: ProviderResult[];
|
|
192
|
+
}
|
|
193
|
+
interface ServerTracker {
|
|
194
|
+
track: (events: ServerEventInput[], meta?: RequestMeta) => Promise<ServerTrackResult>;
|
|
195
|
+
}
|
|
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";
|
|
197
|
+
/** Invalid setup, thrown when the handler or a provider is created. */
|
|
198
|
+
declare class AnalyticsServerConfigError extends Error {
|
|
199
|
+
readonly code: AnalyticsServerConfigErrorCode;
|
|
200
|
+
constructor(code: AnalyticsServerConfigErrorCode, message: string);
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/retry.d.ts
|
|
204
|
+
declare const DEFAULT_RETRY_POLICY: RetryPolicy;
|
|
205
|
+
/** Result of one HTTP attempt, classified by the provider. */
|
|
206
|
+
interface AttemptOutcome {
|
|
207
|
+
outcome: "sent" | "failed" | "skipped";
|
|
208
|
+
reason?: ProviderReason;
|
|
209
|
+
retryable: boolean;
|
|
210
|
+
httpStatus?: number;
|
|
211
|
+
providerCode?: string | number;
|
|
212
|
+
traceId?: string;
|
|
213
|
+
}
|
|
214
|
+
interface FinalOutcome extends AttemptOutcome {
|
|
215
|
+
attempts: number;
|
|
216
|
+
}
|
|
217
|
+
interface HttpReply {
|
|
218
|
+
status: number;
|
|
219
|
+
/** Parsed JSON body, or `null` when it is not JSON. */
|
|
220
|
+
body: unknown;
|
|
221
|
+
}
|
|
222
|
+
/** Full jitter: random in [0, min(maxDelayMs, baseDelayMs · 2^attempt)). */
|
|
223
|
+
declare const backoffDelay: (policy: RetryPolicy, attempt: number, random: () => number) => number;
|
|
224
|
+
/**
|
|
225
|
+
* Runs `attempt` until it succeeds, fails for good, runs out of attempts,
|
|
226
|
+
* or the next wait would pass `totalBudgetMs`. A thrown error (network
|
|
227
|
+
* failure) counts as a retryable `upstream_error`; an abort as `timeout`.
|
|
228
|
+
*/
|
|
229
|
+
declare const withProviderRetry: (ctx: ProviderContext, attempt: (signal: AbortSignal) => Promise<AttemptOutcome>) => Promise<FinalOutcome>;
|
|
230
|
+
/** POSTs a JSON body. The body (and any token in it) is never logged. */
|
|
231
|
+
declare const postJson: (ctx: ProviderContext, request: {
|
|
232
|
+
url: string;
|
|
233
|
+
body: string;
|
|
234
|
+
headers?: Record<string, string>;
|
|
235
|
+
}, signal: AbortSignal) => Promise<HttpReply>;
|
|
236
|
+
//#endregion
|
|
237
|
+
export { ServerTracker as A, ResolvedEvent as C, ServerIssueSource as D, ServerIssue as E, JsonNumber as F, decimalNumber as I, decimalText as L, ServerUserInput as M, TrackingHandlerOptions as N, ServerProvider as O, VerifyEvent as P, stringifyJson as R, RequestMeta as S, ServerEventInput as T, RelayAcceptedBody as _, backoffDelay as a, RelayRejectReason as b, AnalyticsServerConfigError as c, IdempotencyStore as d, PreparedEvents as f, ProviderResult as g, ProviderReason as h, HttpReply as i, ServerTrackerOptions as j, ServerTrackResult as k, AnalyticsServerConfigErrorCode as l, ProviderOutcome as m, DEFAULT_RETRY_POLICY as n, postJson as o, ProviderContext as p, FinalOutcome as r, withProviderRetry as s, AttemptOutcome as t, DeliveryOptions as u, RelayErrorBody as v, RetryPolicy as w, RelayRejectedEvent as x, RelayErrorCode as y };
|
package/dist/tiktok.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { C as ResolvedEvent, F as JsonNumber, O as ServerProvider, h as ProviderReason, i as HttpReply, t as AttemptOutcome } from "./retry-CKgkb0DS.js";
|
|
2
|
+
//#region src/tiktok.types.d.ts
|
|
3
|
+
interface TikTokEventsApiOptions {
|
|
4
|
+
/** Pixel code from TikTok Events Manager (`event_source_id`). */
|
|
5
|
+
pixelCode: string;
|
|
6
|
+
/** Events API access token. Server only, never logged. */
|
|
7
|
+
accessToken: string;
|
|
8
|
+
/** Default `v1.3`. */
|
|
9
|
+
apiVersion?: "v1.3";
|
|
10
|
+
/** Events Manager → Test Events. Dropped in production. */
|
|
11
|
+
testEventCode?: string;
|
|
12
|
+
/** Keeps `testEventCode` in production. */
|
|
13
|
+
allowTestInProduction?: boolean;
|
|
14
|
+
/** Sends `limited_data_use: true` on every event. */
|
|
15
|
+
limitedDataUse?: boolean;
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/tiktok-codes.d.ts
|
|
19
|
+
interface TikTokCodeRule {
|
|
20
|
+
reason: ProviderReason;
|
|
21
|
+
retryable: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* TikTok API for Business return codes (v1.3 return codes appendix,
|
|
25
|
+
* https://business-api.tiktok.com/portal/docs/return-codes-appendix/v1.3).
|
|
26
|
+
* `0` (OK) and `20001` (partial success) are handled before this table.
|
|
27
|
+
* A code missing here falls back to `tiktokCodeRule`'s ranges.
|
|
28
|
+
*/
|
|
29
|
+
declare const TIKTOK_RETURN_CODES: Readonly<Record<number, TikTokCodeRule>>;
|
|
30
|
+
/** Rule for a non-zero TikTok `code`. */
|
|
31
|
+
declare const tiktokCodeRule: (code: number) => TikTokCodeRule;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/tiktok.d.ts
|
|
34
|
+
/** One Events API 2.0 web event. `event` is the `ttq.track` name. */
|
|
35
|
+
declare const tiktokEventOf: (event: ResolvedEvent, options: TikTokEventsApiOptions) => Partial<{
|
|
36
|
+
event: string | null;
|
|
37
|
+
event_time: number;
|
|
38
|
+
event_id: string;
|
|
39
|
+
user: Partial<{
|
|
40
|
+
email: string | undefined;
|
|
41
|
+
phone: string | undefined;
|
|
42
|
+
external_id: string | undefined;
|
|
43
|
+
ttclid: string | undefined;
|
|
44
|
+
ttp: string | undefined;
|
|
45
|
+
ip: string | undefined;
|
|
46
|
+
user_agent: string | undefined;
|
|
47
|
+
locale: string | undefined;
|
|
48
|
+
}>;
|
|
49
|
+
page: Partial<{
|
|
50
|
+
url: string;
|
|
51
|
+
referrer: string | undefined;
|
|
52
|
+
}>;
|
|
53
|
+
properties: Partial<{
|
|
54
|
+
currency: string | undefined;
|
|
55
|
+
value: JsonNumber | undefined;
|
|
56
|
+
order_id: string | undefined;
|
|
57
|
+
content_type: string | undefined;
|
|
58
|
+
contents: Partial<{
|
|
59
|
+
content_id: string;
|
|
60
|
+
price: JsonNumber | undefined;
|
|
61
|
+
quantity: JsonNumber | undefined;
|
|
62
|
+
content_name: string | undefined;
|
|
63
|
+
content_category: string | undefined;
|
|
64
|
+
brand: string | undefined;
|
|
65
|
+
}>[];
|
|
66
|
+
}>;
|
|
67
|
+
limited_data_use: boolean | undefined;
|
|
68
|
+
}>;
|
|
69
|
+
/** TikTok response → outcome, per the retry matrix and return codes. */
|
|
70
|
+
declare const classifyTikTokReply: (reply: HttpReply) => AttemptOutcome;
|
|
71
|
+
/**
|
|
72
|
+
* TikTok Events API 2.0 destination (web events). The token travels in
|
|
73
|
+
* the `Access-Token` header and is never logged.
|
|
74
|
+
*/
|
|
75
|
+
declare const tiktokEventsApi: (options: TikTokEventsApiOptions) => ServerProvider;
|
|
76
|
+
//#endregion
|
|
77
|
+
export { TIKTOK_RETURN_CODES, type TikTokCodeRule, type TikTokEventsApiOptions, classifyTikTokReply, tiktokCodeRule, tiktokEventOf, tiktokEventsApi };
|
package/dist/tiktok.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { a as stringifyJson, f as withProviderRetry, l as postJson, n as compact, o as AnalyticsServerConfigError, r as decimalNumber } from "./json-D5hsBi3M.js";
|
|
2
|
+
import { n as testCodeFor } from "./provider-DIOneNqa.js";
|
|
3
|
+
import { providerEventName } from "@fire-spark/analytics";
|
|
4
|
+
//#region src/tiktok-codes.ts
|
|
5
|
+
const rule = (reason, retryable) => {
|
|
6
|
+
return {
|
|
7
|
+
reason,
|
|
8
|
+
retryable
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
const AUTH = rule("auth", false);
|
|
12
|
+
const INVALID = rule("invalid_payload", false);
|
|
13
|
+
const RATE_LIMITED = rule("rate_limited", true);
|
|
14
|
+
const UPSTREAM = rule("upstream_error", true);
|
|
15
|
+
/**
|
|
16
|
+
* TikTok API for Business return codes (v1.3 return codes appendix,
|
|
17
|
+
* https://business-api.tiktok.com/portal/docs/return-codes-appendix/v1.3).
|
|
18
|
+
* `0` (OK) and `20001` (partial success) are handled before this table.
|
|
19
|
+
* A code missing here falls back to `tiktokCodeRule`'s ranges.
|
|
20
|
+
*/
|
|
21
|
+
const TIKTOK_RETURN_CODES = {
|
|
22
|
+
4e4: INVALID,
|
|
23
|
+
40001: AUTH,
|
|
24
|
+
40002: INVALID,
|
|
25
|
+
40006: INVALID,
|
|
26
|
+
40007: INVALID,
|
|
27
|
+
40008: INVALID,
|
|
28
|
+
40009: INVALID,
|
|
29
|
+
40010: INVALID,
|
|
30
|
+
40011: INVALID,
|
|
31
|
+
40013: INVALID,
|
|
32
|
+
40014: INVALID,
|
|
33
|
+
40016: RATE_LIMITED,
|
|
34
|
+
40050: rule("duplicate", false),
|
|
35
|
+
40051: INVALID,
|
|
36
|
+
40052: INVALID,
|
|
37
|
+
40053: INVALID,
|
|
38
|
+
40065: INVALID,
|
|
39
|
+
40100: RATE_LIMITED,
|
|
40
|
+
40101: AUTH,
|
|
41
|
+
40102: AUTH,
|
|
42
|
+
40103: AUTH,
|
|
43
|
+
40104: AUTH,
|
|
44
|
+
40105: AUTH,
|
|
45
|
+
40106: AUTH,
|
|
46
|
+
40107: AUTH,
|
|
47
|
+
40108: AUTH,
|
|
48
|
+
40109: AUTH,
|
|
49
|
+
40110: AUTH,
|
|
50
|
+
40112: AUTH,
|
|
51
|
+
40113: AUTH,
|
|
52
|
+
40115: AUTH,
|
|
53
|
+
40116: AUTH,
|
|
54
|
+
40117: AUTH,
|
|
55
|
+
40118: AUTH,
|
|
56
|
+
40119: AUTH,
|
|
57
|
+
40121: AUTH,
|
|
58
|
+
40122: AUTH,
|
|
59
|
+
40124: AUTH,
|
|
60
|
+
40125: AUTH,
|
|
61
|
+
40131: AUTH,
|
|
62
|
+
40132: RATE_LIMITED,
|
|
63
|
+
40133: RATE_LIMITED,
|
|
64
|
+
40200: INVALID,
|
|
65
|
+
40201: INVALID,
|
|
66
|
+
/** Runtime error; TikTok says a retry may resolve it. */
|
|
67
|
+
40202: UPSTREAM,
|
|
68
|
+
40300: AUTH,
|
|
69
|
+
40301: AUTH,
|
|
70
|
+
40502: RATE_LIMITED,
|
|
71
|
+
40700: INVALID,
|
|
72
|
+
40900: INVALID,
|
|
73
|
+
40901: INVALID,
|
|
74
|
+
40902: UPSTREAM,
|
|
75
|
+
40903: UPSTREAM,
|
|
76
|
+
40904: INVALID,
|
|
77
|
+
40905: INVALID,
|
|
78
|
+
40906: INVALID,
|
|
79
|
+
40907: INVALID,
|
|
80
|
+
40908: INVALID,
|
|
81
|
+
40909: INVALID,
|
|
82
|
+
40910: INVALID,
|
|
83
|
+
40911: INVALID,
|
|
84
|
+
40912: INVALID,
|
|
85
|
+
40913: UPSTREAM,
|
|
86
|
+
40914: INVALID,
|
|
87
|
+
40915: INVALID,
|
|
88
|
+
41e3: AUTH,
|
|
89
|
+
41001: INVALID,
|
|
90
|
+
41002: INVALID,
|
|
91
|
+
5e4: UPSTREAM,
|
|
92
|
+
50002: UPSTREAM,
|
|
93
|
+
51305: UPSTREAM,
|
|
94
|
+
60001: UPSTREAM
|
|
95
|
+
};
|
|
96
|
+
/** Rule for a non-zero TikTok `code`. */
|
|
97
|
+
const tiktokCodeRule = (code) => {
|
|
98
|
+
const known = TIKTOK_RETURN_CODES[code];
|
|
99
|
+
if (known) return known;
|
|
100
|
+
if (code >= 5e4) return UPSTREAM;
|
|
101
|
+
return INVALID;
|
|
102
|
+
};
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/tiktok.ts
|
|
105
|
+
const PROVIDER = "tiktok";
|
|
106
|
+
const MAX_BATCH = 1e3;
|
|
107
|
+
const PIXEL_CODE = /^[A-Za-z0-9]{1,64}$/;
|
|
108
|
+
const API_VERSIONS = /* @__PURE__ */ new Set(["v1.3"]);
|
|
109
|
+
const PARTIAL_SUCCESS = 20001;
|
|
110
|
+
const contentsOf = (event) => {
|
|
111
|
+
return (event.items ?? []).map((item) => {
|
|
112
|
+
const c1 = {
|
|
113
|
+
content_id: item.id,
|
|
114
|
+
price: decimalNumber(item.price)
|
|
115
|
+
};
|
|
116
|
+
const c2 = { quantity: decimalNumber(item.quantity) };
|
|
117
|
+
const c3 = { content_name: item.name };
|
|
118
|
+
const c4 = {
|
|
119
|
+
content_category: item.category,
|
|
120
|
+
brand: item.brand
|
|
121
|
+
};
|
|
122
|
+
return compact({
|
|
123
|
+
...c1,
|
|
124
|
+
...c2,
|
|
125
|
+
...c3,
|
|
126
|
+
...c4
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
const propertiesOf = (event) => {
|
|
131
|
+
const priced = (event.items ?? []).length > 0;
|
|
132
|
+
const p1 = {
|
|
133
|
+
currency: event.currency,
|
|
134
|
+
value: decimalNumber(event.value)
|
|
135
|
+
};
|
|
136
|
+
const p2 = { order_id: event.order_id };
|
|
137
|
+
const p3 = { content_type: priced ? "product" : void 0 };
|
|
138
|
+
return compact({
|
|
139
|
+
...p1,
|
|
140
|
+
...p2,
|
|
141
|
+
...p3,
|
|
142
|
+
contents: contentsOf(event)
|
|
143
|
+
});
|
|
144
|
+
};
|
|
145
|
+
const userOf = (event) => {
|
|
146
|
+
const { user, click_ids: clickIds } = event;
|
|
147
|
+
const u1 = {
|
|
148
|
+
email: user.email_sha256,
|
|
149
|
+
phone: user.phone_e164_sha256
|
|
150
|
+
};
|
|
151
|
+
const u2 = { external_id: user.external_id_sha256 };
|
|
152
|
+
const u3 = {
|
|
153
|
+
ttclid: clickIds.ttclid,
|
|
154
|
+
ttp: clickIds.ttp
|
|
155
|
+
};
|
|
156
|
+
const u4 = {
|
|
157
|
+
ip: event.ipAddress,
|
|
158
|
+
user_agent: event.userAgent
|
|
159
|
+
};
|
|
160
|
+
const u5 = { locale: event.context.locale };
|
|
161
|
+
return compact({
|
|
162
|
+
...u1,
|
|
163
|
+
...u2,
|
|
164
|
+
...u3,
|
|
165
|
+
...u4,
|
|
166
|
+
...u5
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
/** One Events API 2.0 web event. `event` is the `ttq.track` name. */
|
|
170
|
+
const tiktokEventOf = (event, options) => {
|
|
171
|
+
const e1 = {
|
|
172
|
+
event: providerEventName(PROVIDER, event.name),
|
|
173
|
+
event_time: Math.floor(event.timestamp / 1e3),
|
|
174
|
+
event_id: event.event_id
|
|
175
|
+
};
|
|
176
|
+
const e2 = { user: userOf(event) };
|
|
177
|
+
const e3 = {
|
|
178
|
+
page: compact({
|
|
179
|
+
url: event.source_url,
|
|
180
|
+
referrer: event.referrer_url
|
|
181
|
+
}),
|
|
182
|
+
properties: propertiesOf(event)
|
|
183
|
+
};
|
|
184
|
+
const e4 = { limited_data_use: options.limitedDataUse };
|
|
185
|
+
return compact({
|
|
186
|
+
...e1,
|
|
187
|
+
...e2,
|
|
188
|
+
...e3,
|
|
189
|
+
...e4
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
const recordOf = (value) => {
|
|
193
|
+
return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
194
|
+
};
|
|
195
|
+
const textOf = (value) => {
|
|
196
|
+
return typeof value === "string" && value ? value : void 0;
|
|
197
|
+
};
|
|
198
|
+
const statusOutcome = (status) => {
|
|
199
|
+
if (status >= 500) return {
|
|
200
|
+
reason: "upstream_error",
|
|
201
|
+
retry: true
|
|
202
|
+
};
|
|
203
|
+
if (status === 429) return {
|
|
204
|
+
reason: "rate_limited",
|
|
205
|
+
retry: true
|
|
206
|
+
};
|
|
207
|
+
if (status === 401 || status === 403) return {
|
|
208
|
+
reason: "auth",
|
|
209
|
+
retry: false
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
reason: "invalid_payload",
|
|
213
|
+
retry: false
|
|
214
|
+
};
|
|
215
|
+
};
|
|
216
|
+
/** TikTok response → outcome, per the retry matrix and return codes. */
|
|
217
|
+
const classifyTikTokReply = (reply) => {
|
|
218
|
+
const body = recordOf(reply.body);
|
|
219
|
+
const code = typeof body.code === "number" ? body.code : void 0;
|
|
220
|
+
const traceId = textOf(body.request_id);
|
|
221
|
+
const base = {
|
|
222
|
+
httpStatus: reply.status,
|
|
223
|
+
traceId
|
|
224
|
+
};
|
|
225
|
+
if (reply.status !== 200) {
|
|
226
|
+
const { reason, retry } = statusOutcome(reply.status);
|
|
227
|
+
const b1 = {
|
|
228
|
+
outcome: "failed",
|
|
229
|
+
reason,
|
|
230
|
+
retryable: retry
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
...base,
|
|
234
|
+
...b1,
|
|
235
|
+
providerCode: code
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (code === 0 || code === PARTIAL_SUCCESS) return {
|
|
239
|
+
...base,
|
|
240
|
+
outcome: "sent",
|
|
241
|
+
retryable: false,
|
|
242
|
+
providerCode: code
|
|
243
|
+
};
|
|
244
|
+
if (code === void 0) {
|
|
245
|
+
const b1 = {
|
|
246
|
+
reason: "upstream_error",
|
|
247
|
+
retryable: true
|
|
248
|
+
};
|
|
249
|
+
return {
|
|
250
|
+
...base,
|
|
251
|
+
outcome: "failed",
|
|
252
|
+
...b1
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
const { reason, retryable } = tiktokCodeRule(code);
|
|
256
|
+
const outcome = reason === "duplicate" ? "skipped" : "failed";
|
|
257
|
+
return {
|
|
258
|
+
...base,
|
|
259
|
+
outcome,
|
|
260
|
+
reason,
|
|
261
|
+
retryable,
|
|
262
|
+
providerCode: code
|
|
263
|
+
};
|
|
264
|
+
};
|
|
265
|
+
const hasIdentifier = (event) => {
|
|
266
|
+
const { user, click_ids: clickIds } = event;
|
|
267
|
+
const b1 = [
|
|
268
|
+
clickIds.ttclid,
|
|
269
|
+
clickIds.ttp,
|
|
270
|
+
user.email_sha256
|
|
271
|
+
];
|
|
272
|
+
const b2 = [
|
|
273
|
+
user.phone_e164_sha256,
|
|
274
|
+
user.external_id_sha256,
|
|
275
|
+
event.ipAddress
|
|
276
|
+
];
|
|
277
|
+
return [...b1, ...b2].some((value) => !!value);
|
|
278
|
+
};
|
|
279
|
+
const assertOptions = (options) => {
|
|
280
|
+
if (!PIXEL_CODE.test(String(options.pixelCode ?? ""))) throw new AnalyticsServerConfigError("TIKTOK_PIXEL_CODE_INVALID", "tiktokEventsApi: pixelCode must be the TikTok pixel code");
|
|
281
|
+
if (typeof options.accessToken !== "string" || !options.accessToken.trim()) throw new AnalyticsServerConfigError("TIKTOK_ACCESS_TOKEN_REQUIRED", "tiktokEventsApi: accessToken is required");
|
|
282
|
+
const version = options.apiVersion ?? "v1.3";
|
|
283
|
+
if (!API_VERSIONS.has(version)) throw new AnalyticsServerConfigError("TIKTOK_API_VERSION_INVALID", "tiktokEventsApi: apiVersion must be v1.3");
|
|
284
|
+
return version;
|
|
285
|
+
};
|
|
286
|
+
const prepare = (events) => {
|
|
287
|
+
const ready = [];
|
|
288
|
+
const skipped = [];
|
|
289
|
+
const skip = (event, reason) => {
|
|
290
|
+
const b1 = {
|
|
291
|
+
provider: PROVIDER,
|
|
292
|
+
eventIds: [event.event_id]
|
|
293
|
+
};
|
|
294
|
+
const b2 = {
|
|
295
|
+
outcome: "skipped",
|
|
296
|
+
reason,
|
|
297
|
+
retryable: false
|
|
298
|
+
};
|
|
299
|
+
skipped.push({
|
|
300
|
+
...b1,
|
|
301
|
+
...b2,
|
|
302
|
+
attempts: 0
|
|
303
|
+
});
|
|
304
|
+
};
|
|
305
|
+
for (const event of events) if (!providerEventName(PROVIDER, event.name)) skip(event, "not_mapped");
|
|
306
|
+
else if (!hasIdentifier(event)) skip(event, "no_identifier");
|
|
307
|
+
else ready.push(event);
|
|
308
|
+
return {
|
|
309
|
+
ready,
|
|
310
|
+
skipped
|
|
311
|
+
};
|
|
312
|
+
};
|
|
313
|
+
/**
|
|
314
|
+
* TikTok Events API 2.0 destination (web events). The token travels in
|
|
315
|
+
* the `Access-Token` header and is never logged.
|
|
316
|
+
*/
|
|
317
|
+
const tiktokEventsApi = (options) => {
|
|
318
|
+
const version = assertOptions(options);
|
|
319
|
+
const pixelCode = String(options.pixelCode);
|
|
320
|
+
const accessToken = options.accessToken.trim();
|
|
321
|
+
const url = `https://business-api.tiktok.com/open_api/${version}/event/track/`;
|
|
322
|
+
const headers = { "Access-Token": accessToken };
|
|
323
|
+
const send = async (events, ctx) => {
|
|
324
|
+
const data = events.map((event) => tiktokEventOf(event, options));
|
|
325
|
+
const test_event_code = testCodeFor(PROVIDER, options, ctx);
|
|
326
|
+
const body = stringifyJson(compact({
|
|
327
|
+
event_source: "web",
|
|
328
|
+
event_source_id: pixelCode,
|
|
329
|
+
test_event_code,
|
|
330
|
+
data
|
|
331
|
+
}));
|
|
332
|
+
const final = await withProviderRetry(ctx, async (signal) => {
|
|
333
|
+
const reply = await postJson(ctx, {
|
|
334
|
+
url,
|
|
335
|
+
body,
|
|
336
|
+
headers
|
|
337
|
+
}, signal);
|
|
338
|
+
return classifyTikTokReply(reply);
|
|
339
|
+
});
|
|
340
|
+
if (final.providerCode === PARTIAL_SUCCESS) {
|
|
341
|
+
const p1 = "tiktok accepted part of the batch (code 20001)";
|
|
342
|
+
const b2 = {
|
|
343
|
+
level: "warning",
|
|
344
|
+
source: "provider"
|
|
345
|
+
};
|
|
346
|
+
const eventIds = events.map((event) => event.event_id);
|
|
347
|
+
const b3 = {
|
|
348
|
+
providerCode: PARTIAL_SUCCESS,
|
|
349
|
+
traceId: final.traceId
|
|
350
|
+
};
|
|
351
|
+
ctx.report({
|
|
352
|
+
...b2,
|
|
353
|
+
provider: PROVIDER,
|
|
354
|
+
message: p1,
|
|
355
|
+
eventIds,
|
|
356
|
+
...b3
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
const eventIds = events.map((event) => event.event_id);
|
|
360
|
+
return {
|
|
361
|
+
provider: PROVIDER,
|
|
362
|
+
eventIds,
|
|
363
|
+
...final
|
|
364
|
+
};
|
|
365
|
+
};
|
|
366
|
+
return {
|
|
367
|
+
id: PROVIDER,
|
|
368
|
+
maxBatchSize: MAX_BATCH,
|
|
369
|
+
prepare,
|
|
370
|
+
send
|
|
371
|
+
};
|
|
372
|
+
};
|
|
373
|
+
//#endregion
|
|
374
|
+
export { TIKTOK_RETURN_CODES, classifyTikTokReply, tiktokCodeRule, tiktokEventOf, tiktokEventsApi };
|