@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
package/dist/google.js
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
import { a as stringifyJson, f as withProviderRetry, l as postJson, n as compact, o as AnalyticsServerConfigError, r as decimalNumber, t as JsonNumber, u as readBody } from "./json-D5hsBi3M.js";
|
|
2
|
+
import { Big } from "big.js";
|
|
3
|
+
//#region src/google-auth.ts
|
|
4
|
+
const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
5
|
+
/** The only scope requested: Data Manager, nothing else in the account. */
|
|
6
|
+
const DATA_MANAGER_SCOPE = "https://www.googleapis.com/auth/datamanager";
|
|
7
|
+
/** A cached token is refreshed this long before Google says it expires. */
|
|
8
|
+
const TOKEN_REFRESH_MARGIN_MS = 3e5;
|
|
9
|
+
const PROVIDER$1 = "google-ads";
|
|
10
|
+
const JWT_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
|
|
11
|
+
const ASSERTION_SECONDS = 3600;
|
|
12
|
+
const PEM_BODY = /-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END/;
|
|
13
|
+
const SAFE_ERROR = /^[a-z_]{1,64}$/;
|
|
14
|
+
const RSA = {
|
|
15
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
16
|
+
hash: "SHA-256"
|
|
17
|
+
};
|
|
18
|
+
const HEADER = {
|
|
19
|
+
alg: "RS256",
|
|
20
|
+
typ: "JWT"
|
|
21
|
+
};
|
|
22
|
+
/** Escaped `\n` from an environment variable become real newlines. */
|
|
23
|
+
const normalizePrivateKey = (value) => {
|
|
24
|
+
return value.replace(/\\n/g, "\n").trim();
|
|
25
|
+
};
|
|
26
|
+
/** DER bytes of a PEM PKCS#8 key, or `null` when it is not one. */
|
|
27
|
+
const pkcs8Der = (pem) => {
|
|
28
|
+
const match = PEM_BODY.exec(pem);
|
|
29
|
+
if (!match) return null;
|
|
30
|
+
const base64 = (match[1] ?? "").replace(/\s+/g, "");
|
|
31
|
+
try {
|
|
32
|
+
const binary = atob(base64);
|
|
33
|
+
if (binary.length === 0) return null;
|
|
34
|
+
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
35
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
36
|
+
return bytes;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const base64Url = (bytes) => {
|
|
42
|
+
let binary = "";
|
|
43
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
44
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
45
|
+
};
|
|
46
|
+
const encoder = new TextEncoder();
|
|
47
|
+
const encodeJson = (value) => {
|
|
48
|
+
return base64Url(encoder.encode(JSON.stringify(value)));
|
|
49
|
+
};
|
|
50
|
+
const failed = (reason, retryable) => {
|
|
51
|
+
return {
|
|
52
|
+
outcome: "failed",
|
|
53
|
+
reason,
|
|
54
|
+
retryable
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const recordOf$1 = (value) => {
|
|
58
|
+
return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
59
|
+
};
|
|
60
|
+
/** OAuth `error` (`invalid_grant`) as a code; never its description. */
|
|
61
|
+
const errorCodeOf = (body) => {
|
|
62
|
+
const code = body.error;
|
|
63
|
+
return typeof code === "string" && SAFE_ERROR.test(code) ? code : void 0;
|
|
64
|
+
};
|
|
65
|
+
/** Token endpoint reply → token and lifetime, or an attempt outcome. */
|
|
66
|
+
const classifyTokenReply = (reply) => {
|
|
67
|
+
const body = recordOf$1(reply.body);
|
|
68
|
+
const token = body.access_token;
|
|
69
|
+
const seconds = body.expires_in;
|
|
70
|
+
if (reply.status === 200) {
|
|
71
|
+
if (typeof token === "string" && token.length > 0 && typeof seconds === "number" && seconds > 0) return {
|
|
72
|
+
token,
|
|
73
|
+
expiresInMs: seconds * 1e3
|
|
74
|
+
};
|
|
75
|
+
return { outcome: failed("upstream_error", true) };
|
|
76
|
+
}
|
|
77
|
+
const b1 = {
|
|
78
|
+
httpStatus: reply.status,
|
|
79
|
+
providerCode: errorCodeOf(body)
|
|
80
|
+
};
|
|
81
|
+
if (reply.status === 429) return { outcome: {
|
|
82
|
+
...failed("rate_limited", true),
|
|
83
|
+
...b1
|
|
84
|
+
} };
|
|
85
|
+
if (reply.status >= 500) return { outcome: {
|
|
86
|
+
...failed("upstream_error", true),
|
|
87
|
+
...b1
|
|
88
|
+
} };
|
|
89
|
+
return { outcome: {
|
|
90
|
+
...failed("auth", false),
|
|
91
|
+
...b1
|
|
92
|
+
} };
|
|
93
|
+
};
|
|
94
|
+
const importKey = async (privateKey) => {
|
|
95
|
+
const der = pkcs8Der(privateKey);
|
|
96
|
+
if (!der) return null;
|
|
97
|
+
try {
|
|
98
|
+
const p1 = [
|
|
99
|
+
"pkcs8",
|
|
100
|
+
der,
|
|
101
|
+
RSA,
|
|
102
|
+
false,
|
|
103
|
+
["sign"]
|
|
104
|
+
];
|
|
105
|
+
return await crypto.subtle.importKey(...p1);
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* OAuth 2.0 service account flow: a signed RS256 JWT is exchanged for an
|
|
112
|
+
* access token with the Data Manager scope only. The token is cached
|
|
113
|
+
* until five minutes before it expires, and concurrent callers share one
|
|
114
|
+
* request. The key, the assertion and the token are never logged.
|
|
115
|
+
*/
|
|
116
|
+
const googleTokenSource = (credentials) => {
|
|
117
|
+
let keyPromise;
|
|
118
|
+
let cached;
|
|
119
|
+
let pending;
|
|
120
|
+
const assertionOf = async (key, nowMs) => {
|
|
121
|
+
const iat = Math.floor(nowMs / 1e3);
|
|
122
|
+
const c1 = {
|
|
123
|
+
iss: credentials.clientEmail,
|
|
124
|
+
scope: DATA_MANAGER_SCOPE
|
|
125
|
+
};
|
|
126
|
+
const c2 = {
|
|
127
|
+
aud: GOOGLE_TOKEN_URL,
|
|
128
|
+
iat,
|
|
129
|
+
exp: iat + ASSERTION_SECONDS
|
|
130
|
+
};
|
|
131
|
+
const unsigned = `${encodeJson(HEADER)}.${encodeJson({
|
|
132
|
+
...c1,
|
|
133
|
+
...c2
|
|
134
|
+
})}`;
|
|
135
|
+
const data = encoder.encode(unsigned);
|
|
136
|
+
const signature = await crypto.subtle.sign(RSA.name, key, data);
|
|
137
|
+
return `${unsigned}.${base64Url(new Uint8Array(signature))}`;
|
|
138
|
+
};
|
|
139
|
+
const request = async (ctx, signal) => {
|
|
140
|
+
keyPromise ??= importKey(credentials.privateKey);
|
|
141
|
+
const key = await keyPromise;
|
|
142
|
+
if (!key) {
|
|
143
|
+
const p1 = "googleDataManager: privateKey could not be imported";
|
|
144
|
+
const b1 = {
|
|
145
|
+
level: "error",
|
|
146
|
+
source: "config"
|
|
147
|
+
};
|
|
148
|
+
const b2 = { providerCode: "GOOGLE_PRIVATE_KEY_INVALID" };
|
|
149
|
+
ctx.report({
|
|
150
|
+
...b1,
|
|
151
|
+
provider: PROVIDER$1,
|
|
152
|
+
message: p1,
|
|
153
|
+
...b2
|
|
154
|
+
});
|
|
155
|
+
return { outcome: failed("auth", false) };
|
|
156
|
+
}
|
|
157
|
+
const startedAt = ctx.now();
|
|
158
|
+
const assertion = await assertionOf(key, startedAt);
|
|
159
|
+
const init = {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
162
|
+
body: new URLSearchParams({
|
|
163
|
+
grant_type: JWT_GRANT,
|
|
164
|
+
assertion
|
|
165
|
+
}).toString(),
|
|
166
|
+
signal
|
|
167
|
+
};
|
|
168
|
+
const response = await ctx.fetch(GOOGLE_TOKEN_URL, init);
|
|
169
|
+
const reply = {
|
|
170
|
+
status: response.status,
|
|
171
|
+
body: await readBody(response)
|
|
172
|
+
};
|
|
173
|
+
const result = classifyTokenReply(reply);
|
|
174
|
+
if ("outcome" in result) return result;
|
|
175
|
+
const expiresAt = startedAt + result.expiresInMs;
|
|
176
|
+
cached = {
|
|
177
|
+
token: result.token,
|
|
178
|
+
expiresAt
|
|
179
|
+
};
|
|
180
|
+
return { token: result.token };
|
|
181
|
+
};
|
|
182
|
+
const cachedToken = (nowMs) => {
|
|
183
|
+
if (!cached || nowMs >= cached.expiresAt - 3e5) return;
|
|
184
|
+
return cached.token;
|
|
185
|
+
};
|
|
186
|
+
const get = (ctx, signal) => {
|
|
187
|
+
const token = cachedToken(ctx.now());
|
|
188
|
+
if (token) return Promise.resolve({ token });
|
|
189
|
+
pending ??= request(ctx, signal).finally(() => {
|
|
190
|
+
pending = void 0;
|
|
191
|
+
});
|
|
192
|
+
return pending;
|
|
193
|
+
};
|
|
194
|
+
const invalidate = () => {
|
|
195
|
+
cached = void 0;
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
get,
|
|
199
|
+
invalidate
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/google.ts
|
|
204
|
+
const PROVIDER = "google-ads";
|
|
205
|
+
const INGEST_URL = "https://datamanager.googleapis.com/v1/events:ingest";
|
|
206
|
+
/** Data Manager limits: 2000 events and 10 destinations per request. */
|
|
207
|
+
const MAX_BATCH = 2e3;
|
|
208
|
+
const MAX_DESTINATIONS = 10;
|
|
209
|
+
const CUSTOMER_ID = /^\d{10}$/;
|
|
210
|
+
const ACTION_ID = /^\d{1,20}$/;
|
|
211
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
212
|
+
const SAFE_STATUS = /^[A-Z_]{1,64}$/;
|
|
213
|
+
const TRUE_VALUES = /* @__PURE__ */ new Set([
|
|
214
|
+
"1",
|
|
215
|
+
"true",
|
|
216
|
+
"yes"
|
|
217
|
+
]);
|
|
218
|
+
/** Server-only variables `googleDataManagerFromEnv` reads. */
|
|
219
|
+
const GOOGLE_DATA_MANAGER_ENV_VARS = {
|
|
220
|
+
serviceAccountJson: "FIRESPARK_GOOGLE_DATA_MANAGER_SERVICE_ACCOUNT_JSON",
|
|
221
|
+
clientEmail: "FIRESPARK_GOOGLE_DATA_MANAGER_CLIENT_EMAIL",
|
|
222
|
+
privateKey: "FIRESPARK_GOOGLE_DATA_MANAGER_PRIVATE_KEY",
|
|
223
|
+
customerId: "FIRESPARK_GOOGLE_ADS_CUSTOMER_ID",
|
|
224
|
+
loginCustomerId: "FIRESPARK_GOOGLE_ADS_LOGIN_CUSTOMER_ID",
|
|
225
|
+
conversionActions: "FIRESPARK_GOOGLE_ADS_CONVERSION_ACTIONS",
|
|
226
|
+
validateOnly: "FIRESPARK_GOOGLE_DATA_MANAGER_VALIDATE_ONLY"
|
|
227
|
+
};
|
|
228
|
+
const configError = (code, text) => {
|
|
229
|
+
return new AnalyticsServerConfigError(code, `googleDataManager: ${text}`);
|
|
230
|
+
};
|
|
231
|
+
const consentOf = (granted) => {
|
|
232
|
+
return granted ? "CONSENT_GRANTED" : "CONSENT_DENIED";
|
|
233
|
+
};
|
|
234
|
+
const consentFor = (event) => {
|
|
235
|
+
const { ads, ad_user_data: userData } = event.consent;
|
|
236
|
+
const personalization = event.consent.ad_personalization ?? ads;
|
|
237
|
+
return {
|
|
238
|
+
ad_user_data: consentOf(userData ?? ads),
|
|
239
|
+
ad_personalization: consentOf(personalization)
|
|
240
|
+
};
|
|
241
|
+
};
|
|
242
|
+
/** Hashed e-mail and E.164 phone, only with `ad_user_data` consent. */
|
|
243
|
+
const userIdentifiersOf = (event) => {
|
|
244
|
+
if ((event.consent.ad_user_data ?? event.consent.ads) === false) return [];
|
|
245
|
+
const { user } = event;
|
|
246
|
+
const email = user.email_google_sha256 ?? user.email_sha256;
|
|
247
|
+
const b1 = email ? [{ email_address: email }] : [];
|
|
248
|
+
const phone = user.phone_e164_sha256;
|
|
249
|
+
const b2 = phone ? [{ phone_number: phone }] : [];
|
|
250
|
+
return [...b1, ...b2];
|
|
251
|
+
};
|
|
252
|
+
const adIdentifiersOf = (event) => {
|
|
253
|
+
const { gclid, gbraid, wbraid } = event.click_ids;
|
|
254
|
+
const session = event.click_ids.google_session_attributes;
|
|
255
|
+
return compact({
|
|
256
|
+
gclid,
|
|
257
|
+
gbraid,
|
|
258
|
+
wbraid,
|
|
259
|
+
session_attributes: session
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
const deviceOf = (event) => {
|
|
263
|
+
return compact({
|
|
264
|
+
user_agent: event.userAgent,
|
|
265
|
+
ip_address: event.ipAddress
|
|
266
|
+
});
|
|
267
|
+
};
|
|
268
|
+
/** Whole-unit quantity as written; `null` when it has a fraction. */
|
|
269
|
+
const quantityOf = (quantity) => {
|
|
270
|
+
try {
|
|
271
|
+
const amount = new Big(quantity);
|
|
272
|
+
return amount.mod(1).eq(0) ? new JsonNumber(amount.toFixed()) : null;
|
|
273
|
+
} catch {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
/**
|
|
278
|
+
* `cart_data.items`. Google's `quantity` is an integer, so a fractional
|
|
279
|
+
* quantity (for example `"1.5"` kg) drops the whole cart rather than
|
|
280
|
+
* rounding it; `conversion_value` still carries the exact total.
|
|
281
|
+
*/
|
|
282
|
+
const cartDataOf = (event) => {
|
|
283
|
+
const items = event.items ?? [];
|
|
284
|
+
const mapped = [];
|
|
285
|
+
for (const item of items) {
|
|
286
|
+
const quantity = item.quantity ? quantityOf(item.quantity) : void 0;
|
|
287
|
+
if (quantity === null) return void 0;
|
|
288
|
+
const b1 = {
|
|
289
|
+
merchant_product_id: item.id,
|
|
290
|
+
quantity
|
|
291
|
+
};
|
|
292
|
+
mapped.push(compact({
|
|
293
|
+
...b1,
|
|
294
|
+
unit_price: decimalNumber(item.price)
|
|
295
|
+
}));
|
|
296
|
+
}
|
|
297
|
+
return mapped.length > 0 ? { items: mapped } : void 0;
|
|
298
|
+
};
|
|
299
|
+
/**
|
|
300
|
+
* One Data Manager event for a conversion action. `transaction_id` is the
|
|
301
|
+
* order id (what the Google tag sends, so Google deduplicates), else the
|
|
302
|
+
* Fire Spark event id.
|
|
303
|
+
*/
|
|
304
|
+
const googleEventOf = (event, actionId) => {
|
|
305
|
+
const identifiers = userIdentifiersOf(event);
|
|
306
|
+
const e1 = { destination_references: [actionId] };
|
|
307
|
+
const e2 = { transaction_id: event.order_id ?? event.event_id };
|
|
308
|
+
const e3 = { event_timestamp: new Date(event.timestamp).toISOString() };
|
|
309
|
+
const e4 = {
|
|
310
|
+
event_source: "WEB",
|
|
311
|
+
currency: event.currency
|
|
312
|
+
};
|
|
313
|
+
const e5 = { conversion_value: decimalNumber(event.value) };
|
|
314
|
+
const e6 = { user_data: compact({ user_identifiers: identifiers }) };
|
|
315
|
+
const e7 = { ad_identifiers: adIdentifiersOf(event) };
|
|
316
|
+
const e8 = { event_device_info: deviceOf(event) };
|
|
317
|
+
const e9 = {
|
|
318
|
+
consent: consentFor(event),
|
|
319
|
+
cart_data: cartDataOf(event)
|
|
320
|
+
};
|
|
321
|
+
return compact({
|
|
322
|
+
...e1,
|
|
323
|
+
...e2,
|
|
324
|
+
...e3,
|
|
325
|
+
...e4,
|
|
326
|
+
...e5,
|
|
327
|
+
...e6,
|
|
328
|
+
...e7,
|
|
329
|
+
...e8,
|
|
330
|
+
...e9
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
const accountOf = (accountId) => {
|
|
334
|
+
return {
|
|
335
|
+
account_type: "GOOGLE_ADS",
|
|
336
|
+
account_id: accountId
|
|
337
|
+
};
|
|
338
|
+
};
|
|
339
|
+
const destinationOf = (config, actionId) => {
|
|
340
|
+
const login = config.loginCustomerId;
|
|
341
|
+
const d1 = { reference: actionId };
|
|
342
|
+
const d2 = { operating_account: accountOf(config.customerId) };
|
|
343
|
+
const d3 = { login_account: login ? accountOf(login) : void 0 };
|
|
344
|
+
const d4 = { product_destination_id: actionId };
|
|
345
|
+
return compact({
|
|
346
|
+
...d1,
|
|
347
|
+
...d2,
|
|
348
|
+
...d3,
|
|
349
|
+
...d4
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
const recordOf = (value) => {
|
|
353
|
+
return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
354
|
+
};
|
|
355
|
+
const textOf = (value) => {
|
|
356
|
+
return typeof value === "string" && value ? value : void 0;
|
|
357
|
+
};
|
|
358
|
+
const statusRule = (httpStatus, status) => {
|
|
359
|
+
const retry = (reason) => ({
|
|
360
|
+
reason,
|
|
361
|
+
retry: true
|
|
362
|
+
});
|
|
363
|
+
const stop = (reason) => ({
|
|
364
|
+
reason,
|
|
365
|
+
retry: false
|
|
366
|
+
});
|
|
367
|
+
if (httpStatus === 429 || status === "RESOURCE_EXHAUSTED") return retry("rate_limited");
|
|
368
|
+
if (httpStatus === 401 || status === "UNAUTHENTICATED") return stop("auth");
|
|
369
|
+
if (httpStatus === 403 || status === "PERMISSION_DENIED") return stop("auth");
|
|
370
|
+
if (httpStatus === 408 || httpStatus === 409 || httpStatus >= 500) return retry("upstream_error");
|
|
371
|
+
return stop("invalid_payload");
|
|
372
|
+
};
|
|
373
|
+
/** Data Manager response → outcome. Google's error text is never kept. */
|
|
374
|
+
const classifyGoogleReply = (reply) => {
|
|
375
|
+
const body = recordOf(reply.body);
|
|
376
|
+
const error = recordOf(body.error);
|
|
377
|
+
const traceId = textOf(body.requestId) ?? textOf(body.request_id);
|
|
378
|
+
const base = {
|
|
379
|
+
httpStatus: reply.status,
|
|
380
|
+
traceId
|
|
381
|
+
};
|
|
382
|
+
if (reply.status >= 200 && reply.status < 300 && Object.keys(error).length === 0) return {
|
|
383
|
+
...base,
|
|
384
|
+
outcome: "sent",
|
|
385
|
+
retryable: false
|
|
386
|
+
};
|
|
387
|
+
const status = textOf(error.status);
|
|
388
|
+
const providerCode = status && SAFE_STATUS.test(status) ? status : void 0;
|
|
389
|
+
const { reason, retry } = statusRule(reply.status, providerCode);
|
|
390
|
+
const b1 = {
|
|
391
|
+
outcome: "failed",
|
|
392
|
+
reason,
|
|
393
|
+
retryable: retry
|
|
394
|
+
};
|
|
395
|
+
return {
|
|
396
|
+
...base,
|
|
397
|
+
...b1,
|
|
398
|
+
providerCode
|
|
399
|
+
};
|
|
400
|
+
};
|
|
401
|
+
const digitsOf = (value) => {
|
|
402
|
+
return String(value ?? "").replace(/-/g, "").trim();
|
|
403
|
+
};
|
|
404
|
+
const actionsOf = (value) => {
|
|
405
|
+
const bad = () => {
|
|
406
|
+
return configError("GOOGLE_CONVERSION_ACTIONS_INVALID", `conversionActions must map event names to numeric conversion action ids (at most ${MAX_DESTINATIONS})`);
|
|
407
|
+
};
|
|
408
|
+
const record = recordOf(value);
|
|
409
|
+
const actions = /* @__PURE__ */ new Map();
|
|
410
|
+
for (const [name, id] of Object.entries(record)) {
|
|
411
|
+
const actionId = typeof id === "number" ? String(id) : id;
|
|
412
|
+
const valid = typeof actionId === "string" && ACTION_ID.test(actionId);
|
|
413
|
+
if (!name.trim() || !valid) throw bad();
|
|
414
|
+
actions.set(name.trim(), actionId);
|
|
415
|
+
}
|
|
416
|
+
const distinct = new Set(actions.values()).size;
|
|
417
|
+
if (actions.size === 0 || distinct > MAX_DESTINATIONS) throw bad();
|
|
418
|
+
return actions;
|
|
419
|
+
};
|
|
420
|
+
/** Checks the options; throws an `AnalyticsServerConfigError`. */
|
|
421
|
+
const resolveConfig = (options) => {
|
|
422
|
+
const clientEmail = String(options?.clientEmail ?? "").trim();
|
|
423
|
+
const rawKey = String(options?.privateKey ?? "");
|
|
424
|
+
if (!clientEmail || !rawKey.trim()) throw configError("GOOGLE_CREDENTIALS_REQUIRED", "clientEmail and privateKey are required");
|
|
425
|
+
if (!EMAIL.test(clientEmail)) throw configError("GOOGLE_SERVICE_ACCOUNT_INVALID", "clientEmail must be the service account e-mail");
|
|
426
|
+
const privateKey = normalizePrivateKey(rawKey);
|
|
427
|
+
if (!pkcs8Der(privateKey)) throw configError("GOOGLE_PRIVATE_KEY_INVALID", "privateKey must be the PEM PKCS#8 key of the JSON key file");
|
|
428
|
+
const customerId = digitsOf(options.customerId);
|
|
429
|
+
if (!CUSTOMER_ID.test(customerId)) throw configError("GOOGLE_CUSTOMER_ID_INVALID", "customerId must be the 10-digit Google Ads customer id");
|
|
430
|
+
const login = options.loginCustomerId;
|
|
431
|
+
const loginCustomerId = login ? digitsOf(login) : void 0;
|
|
432
|
+
if (loginCustomerId !== void 0 && !CUSTOMER_ID.test(loginCustomerId)) throw configError("GOOGLE_LOGIN_CUSTOMER_ID_INVALID", "loginCustomerId must be the 10-digit manager account id");
|
|
433
|
+
return {
|
|
434
|
+
clientEmail,
|
|
435
|
+
privateKey,
|
|
436
|
+
customerId,
|
|
437
|
+
loginCustomerId,
|
|
438
|
+
actions: actionsOf(options.conversionActions)
|
|
439
|
+
};
|
|
440
|
+
};
|
|
441
|
+
const hasIdentifier = (event) => {
|
|
442
|
+
const ads = adIdentifiersOf(event);
|
|
443
|
+
return Object.keys(ads).length > 0 || userIdentifiersOf(event).length > 0;
|
|
444
|
+
};
|
|
445
|
+
const validateOnlyFor = (options, ctx) => {
|
|
446
|
+
if (!options.validateOnly) return false;
|
|
447
|
+
if (!ctx.isProduction || options.allowTestInProduction) return true;
|
|
448
|
+
const p1 = `${PROVIDER} validate_only ignored in production`;
|
|
449
|
+
ctx.report({
|
|
450
|
+
level: "warning",
|
|
451
|
+
source: "config",
|
|
452
|
+
provider: PROVIDER,
|
|
453
|
+
message: p1
|
|
454
|
+
});
|
|
455
|
+
return false;
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* Fail closed: nothing reaches Google, every event fails with
|
|
459
|
+
* `not_configured`, and a `config` error with the code is reported.
|
|
460
|
+
* Other providers in the same handler keep working.
|
|
461
|
+
*/
|
|
462
|
+
const disabledProvider = (error) => {
|
|
463
|
+
const send = async (events, ctx) => {
|
|
464
|
+
const eventIds = events.map((event) => event.event_id);
|
|
465
|
+
const b1 = {
|
|
466
|
+
level: "error",
|
|
467
|
+
source: "config"
|
|
468
|
+
};
|
|
469
|
+
const b2 = {
|
|
470
|
+
message: error.message,
|
|
471
|
+
providerCode: error.code,
|
|
472
|
+
eventIds
|
|
473
|
+
};
|
|
474
|
+
ctx.report({
|
|
475
|
+
...b1,
|
|
476
|
+
provider: PROVIDER,
|
|
477
|
+
...b2
|
|
478
|
+
});
|
|
479
|
+
return {
|
|
480
|
+
provider: PROVIDER,
|
|
481
|
+
eventIds,
|
|
482
|
+
outcome: "failed",
|
|
483
|
+
reason: "not_configured",
|
|
484
|
+
retryable: false,
|
|
485
|
+
attempts: 0
|
|
486
|
+
};
|
|
487
|
+
};
|
|
488
|
+
const prepare = (events) => ({
|
|
489
|
+
ready: events,
|
|
490
|
+
skipped: []
|
|
491
|
+
});
|
|
492
|
+
return {
|
|
493
|
+
id: PROVIDER,
|
|
494
|
+
maxBatchSize: MAX_BATCH,
|
|
495
|
+
prepare,
|
|
496
|
+
send
|
|
497
|
+
};
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* Google Data Manager destination (`events:ingest`) for Google Ads
|
|
501
|
+
* conversions. Authenticates as a service account with the Data Manager
|
|
502
|
+
* scope only. Invalid options never throw: the provider fails closed (see
|
|
503
|
+
* `disabledProvider`). The key and tokens are never logged.
|
|
504
|
+
*/
|
|
505
|
+
const googleDataManager = (options) => {
|
|
506
|
+
let config;
|
|
507
|
+
try {
|
|
508
|
+
config = resolveConfig(options);
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (error instanceof AnalyticsServerConfigError) return disabledProvider(error);
|
|
511
|
+
return disabledProvider(configError("GOOGLE_CREDENTIALS_REQUIRED", "options could not be read"));
|
|
512
|
+
}
|
|
513
|
+
const { actions, clientEmail, privateKey } = config;
|
|
514
|
+
const tokens = googleTokenSource({
|
|
515
|
+
clientEmail,
|
|
516
|
+
privateKey
|
|
517
|
+
});
|
|
518
|
+
const prepare = (events) => {
|
|
519
|
+
const ready = [];
|
|
520
|
+
const skipped = [];
|
|
521
|
+
const skip = (event, reason) => {
|
|
522
|
+
const b1 = {
|
|
523
|
+
provider: PROVIDER,
|
|
524
|
+
eventIds: [event.event_id]
|
|
525
|
+
};
|
|
526
|
+
const b2 = {
|
|
527
|
+
outcome: "skipped",
|
|
528
|
+
reason,
|
|
529
|
+
retryable: false
|
|
530
|
+
};
|
|
531
|
+
skipped.push({
|
|
532
|
+
...b1,
|
|
533
|
+
...b2,
|
|
534
|
+
attempts: 0
|
|
535
|
+
});
|
|
536
|
+
};
|
|
537
|
+
for (const event of events) if (!actions.has(event.name)) skip(event, "not_mapped");
|
|
538
|
+
else if (!hasIdentifier(event)) skip(event, "no_identifier");
|
|
539
|
+
else ready.push(event);
|
|
540
|
+
return {
|
|
541
|
+
ready,
|
|
542
|
+
skipped
|
|
543
|
+
};
|
|
544
|
+
};
|
|
545
|
+
const send = async (events, ctx) => {
|
|
546
|
+
const actionOf = (event) => actions.get(event.name) ?? "";
|
|
547
|
+
const body = stringifyJson(compact({
|
|
548
|
+
destinations: [...new Set(events.map(actionOf))].map((id) => destinationOf(config, id)),
|
|
549
|
+
events: events.map((event) => googleEventOf(event, actionOf(event))),
|
|
550
|
+
encoding: "HEX",
|
|
551
|
+
validate_only: validateOnlyFor(options, ctx) || void 0
|
|
552
|
+
}));
|
|
553
|
+
let refreshed = false;
|
|
554
|
+
const final = await withProviderRetry(ctx, async (signal) => {
|
|
555
|
+
const auth = await tokens.get(ctx, signal);
|
|
556
|
+
if ("outcome" in auth) return auth.outcome;
|
|
557
|
+
const headers = { authorization: `Bearer ${auth.token}` };
|
|
558
|
+
const reply = await postJson(ctx, {
|
|
559
|
+
url: INGEST_URL,
|
|
560
|
+
body,
|
|
561
|
+
headers
|
|
562
|
+
}, signal);
|
|
563
|
+
const outcome = classifyGoogleReply(reply);
|
|
564
|
+
if (reply.status !== 401 || refreshed) return outcome;
|
|
565
|
+
refreshed = true;
|
|
566
|
+
tokens.invalidate();
|
|
567
|
+
return {
|
|
568
|
+
...outcome,
|
|
569
|
+
retryable: true
|
|
570
|
+
};
|
|
571
|
+
});
|
|
572
|
+
const eventIds = events.map((event) => event.event_id);
|
|
573
|
+
return {
|
|
574
|
+
provider: PROVIDER,
|
|
575
|
+
eventIds,
|
|
576
|
+
...final
|
|
577
|
+
};
|
|
578
|
+
};
|
|
579
|
+
return {
|
|
580
|
+
id: PROVIDER,
|
|
581
|
+
maxBatchSize: MAX_BATCH,
|
|
582
|
+
prepare,
|
|
583
|
+
send
|
|
584
|
+
};
|
|
585
|
+
};
|
|
586
|
+
const parseJson = (text) => {
|
|
587
|
+
try {
|
|
588
|
+
return JSON.parse(text);
|
|
589
|
+
} catch {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
const credentialsFromEnv = (env) => {
|
|
594
|
+
const vars = GOOGLE_DATA_MANAGER_ENV_VARS;
|
|
595
|
+
const json = env[vars.serviceAccountJson]?.trim();
|
|
596
|
+
if (!json) return {
|
|
597
|
+
clientEmail: env[vars.clientEmail] ?? "",
|
|
598
|
+
privateKey: env[vars.privateKey] ?? ""
|
|
599
|
+
};
|
|
600
|
+
const key = recordOf(parseJson(json));
|
|
601
|
+
const clientEmail = key.client_email;
|
|
602
|
+
const privateKey = key.private_key;
|
|
603
|
+
if (!(typeof clientEmail === "string" && !!clientEmail) || typeof privateKey !== "string" || !privateKey) throw configError("GOOGLE_SERVICE_ACCOUNT_INVALID", `the service account JSON must have client_email and private_key`);
|
|
604
|
+
return {
|
|
605
|
+
clientEmail,
|
|
606
|
+
privateKey
|
|
607
|
+
};
|
|
608
|
+
};
|
|
609
|
+
const actionsFromEnv = (env) => {
|
|
610
|
+
const name = GOOGLE_DATA_MANAGER_ENV_VARS.conversionActions;
|
|
611
|
+
const text = env[name]?.trim();
|
|
612
|
+
if (!text) return {};
|
|
613
|
+
const parsed = parseJson(text);
|
|
614
|
+
if (Object.keys(recordOf(parsed)).length > 0) return recordOf(parsed);
|
|
615
|
+
const p1 = `${name} must be a JSON object like {"purchase":"987654321"}`;
|
|
616
|
+
throw configError("GOOGLE_CONVERSION_ACTIONS_INVALID", p1);
|
|
617
|
+
};
|
|
618
|
+
/** Options from the server-only variables in `GOOGLE_DATA_MANAGER_ENV_VARS`. */
|
|
619
|
+
const googleDataManagerOptionsFromEnv = (env) => {
|
|
620
|
+
const vars = GOOGLE_DATA_MANAGER_ENV_VARS;
|
|
621
|
+
const credentials = credentialsFromEnv(env);
|
|
622
|
+
const conversionActions = actionsFromEnv(env);
|
|
623
|
+
const customerId = env[vars.customerId] ?? "";
|
|
624
|
+
const loginCustomerId = env[vars.loginCustomerId]?.trim() || void 0;
|
|
625
|
+
const flag = env[vars.validateOnly]?.trim().toLowerCase() ?? "";
|
|
626
|
+
const o1 = {
|
|
627
|
+
customerId,
|
|
628
|
+
loginCustomerId,
|
|
629
|
+
conversionActions
|
|
630
|
+
};
|
|
631
|
+
return {
|
|
632
|
+
...credentials,
|
|
633
|
+
...o1,
|
|
634
|
+
validateOnly: TRUE_VALUES.has(flag)
|
|
635
|
+
};
|
|
636
|
+
};
|
|
637
|
+
/**
|
|
638
|
+
* `googleDataManager` configured from server-only environment variables
|
|
639
|
+
* (pass `process.env`, or the Worker `env`). Never throws: a missing or
|
|
640
|
+
* invalid variable makes the provider fail closed.
|
|
641
|
+
*/
|
|
642
|
+
const googleDataManagerFromEnv = (env) => {
|
|
643
|
+
try {
|
|
644
|
+
return googleDataManager(googleDataManagerOptionsFromEnv(env));
|
|
645
|
+
} catch (error) {
|
|
646
|
+
if (error instanceof AnalyticsServerConfigError) return disabledProvider(error);
|
|
647
|
+
return disabledProvider(configError("GOOGLE_CREDENTIALS_REQUIRED", "environment variables could not be read"));
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
//#endregion
|
|
651
|
+
export { DATA_MANAGER_SCOPE, GOOGLE_DATA_MANAGER_ENV_VARS, GOOGLE_TOKEN_URL, TOKEN_REFRESH_MARGIN_MS, classifyGoogleReply, classifyTokenReply, googleDataManager, googleDataManagerFromEnv, googleDataManagerOptionsFromEnv, googleEventOf };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { A as ServerTracker, C as ResolvedEvent, D as ServerIssueSource, E as ServerIssue, F as JsonNumber, I as decimalNumber, L as decimalText, M as ServerUserInput, N as TrackingHandlerOptions, O as ServerProvider, P as VerifyEvent, R as stringifyJson, S as RequestMeta, T as ServerEventInput, _ as RelayAcceptedBody, a as backoffDelay, b as RelayRejectReason, c as AnalyticsServerConfigError, d as IdempotencyStore, f as PreparedEvents, g as ProviderResult, h as ProviderReason, i as HttpReply, j as ServerTrackerOptions, k as ServerTrackResult, l as AnalyticsServerConfigErrorCode, m as ProviderOutcome, n as DEFAULT_RETRY_POLICY, o as postJson, p as ProviderContext, r as FinalOutcome, s as withProviderRetry, t as AttemptOutcome, u as DeliveryOptions, v as RelayErrorBody, w as RetryPolicy, x as RelayRejectedEvent, y as RelayErrorCode } from "./retry-CKgkb0DS.js";
|
|
2
|
+
import { SUPPORTED_CONTRACT_VERSIONS, TrackingEventV1, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope } from "@fire-spark/analytics";
|
|
3
|
+
//#region src/handler.d.ts
|
|
4
|
+
declare const DEFAULT_MAX_BODY_BYTES = 65536;
|
|
5
|
+
declare const CONTRACT_HEADER = "x-firespark-contract";
|
|
6
|
+
/**
|
|
7
|
+
* `POST` handler for the relay endpoint (`serverSide.endpoint`), for any
|
|
8
|
+
* runtime with web `Request` / `Response` (Next.js route handlers, Hono,
|
|
9
|
+
* Workers). Answers `202` once the events are checked; provider delivery
|
|
10
|
+
* runs afterwards inside `waitUntil`, or before the response when there
|
|
11
|
+
* is no `waitUntil`.
|
|
12
|
+
*/
|
|
13
|
+
declare const createTrackingHandler: (options: TrackingHandlerOptions) => (request: Request) => Promise<Response>;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/tracker.d.ts
|
|
16
|
+
/**
|
|
17
|
+
* Sends events built on your server (an order webhook, a back-office
|
|
18
|
+
* action) through the same providers. Raw personal data in `user` is
|
|
19
|
+
* hashed here and never sent. These events are trusted, so `verifyEvent`
|
|
20
|
+
* does not run; consent and idempotency still apply.
|
|
21
|
+
*/
|
|
22
|
+
declare const createServerTracker: (options: ServerTrackerOptions) => ServerTracker;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/deliver.d.ts
|
|
25
|
+
/** Seconds an idempotency claim lasts: the ad platforms' 48 h dedup window. */
|
|
26
|
+
declare const IDEMPOTENCY_TTL_SECONDS = 172800;
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/provider.d.ts
|
|
29
|
+
/** Typed identity helper for a custom destination. */
|
|
30
|
+
declare const defineServerProvider: (provider: ServerProvider) => ServerProvider;
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/redact.d.ts
|
|
33
|
+
/**
|
|
34
|
+
* Last line of defense for issue text: strips emails, hashes, tokens,
|
|
35
|
+
* PEM keys, JWTs, IP addresses and query strings. Issue messages are
|
|
36
|
+
* fixed templates; this only catches what a template could not rule out.
|
|
37
|
+
*/
|
|
38
|
+
declare const redactText: (text: string, secrets?: readonly string[]) => string;
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/request.d.ts
|
|
41
|
+
/** IPv4 or IPv6 text, or `undefined`. */
|
|
42
|
+
declare const cleanIp: (value: unknown) => string | undefined;
|
|
43
|
+
declare const cleanUserAgent: (value: unknown) => string | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* First `x-forwarded-for` entry, else `x-real-ip`, plus `user-agent`.
|
|
46
|
+
* On Vercel the platform sets `x-forwarded-for`; behind another proxy,
|
|
47
|
+
* pass `getRequestMeta` so a client-sent header is not trusted.
|
|
48
|
+
*/
|
|
49
|
+
declare const defaultRequestMeta: (request: Request) => RequestMeta;
|
|
50
|
+
//#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 };
|