@aglyn/tenant-data-admin 1.0.0-beta.283 → 1.0.0-beta.285
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/package.json +7 -7
- package/src/lib/server/ad-audience-sync-run.d.ts +63 -6
- package/src/lib/server/ad-audience-sync-run.js +289 -124
- package/src/lib/server/ad-audience-sync-run.js.map +1 -1
- package/src/lib/server/ad-audience-sync.d.ts +115 -2
- package/src/lib/server/ad-audience-sync.js +203 -25
- package/src/lib/server/ad-audience-sync.js.map +1 -1
|
@@ -26,6 +26,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
26
26
|
* and conversion APIs are the ad-conversions plugin, which this shares
|
|
27
27
|
* nothing with.
|
|
28
28
|
*
|
|
29
|
+
* Beside that one all-holders list, each provider may keep a STAGE list per
|
|
30
|
+
* stage (AGL-4072): free and not published, free and published, paid, and
|
|
31
|
+
* lapsed. Each is a subset of the same eligible audience, configured by its
|
|
32
|
+
* own list id, and synced, recorded and guarded exactly like the main list.
|
|
33
|
+
*
|
|
29
34
|
* Everything here is pure — normalization, hashing, who is eligible, the
|
|
30
35
|
* add/remove diff and each provider's request — so the spec walks every rule
|
|
31
36
|
* without a network. `ad-audience-sync-run.ts` reads the accounts, sends and
|
|
@@ -179,6 +184,123 @@ const ALPHA2 = /^[A-Z]{2}$/;
|
|
|
179
184
|
if (country !== AD_AUDIENCE_COUNTRY) return 'not-us';
|
|
180
185
|
return null;
|
|
181
186
|
}
|
|
187
|
+
/*==========================================
|
|
188
|
+
* STAGES (AGL-4072)
|
|
189
|
+
*=========================================*/ /**
|
|
190
|
+
* The stage lists kept beside the all-holders list, so the ads for people
|
|
191
|
+
* who already have an account can say something that fits where they are.
|
|
192
|
+
* Each one is a SUBSET of the eligible audience — every exclusion above
|
|
193
|
+
* still applies first — and each is optional, sent only when its own list id
|
|
194
|
+
* is set.
|
|
195
|
+
*
|
|
196
|
+
* - `free-unpublished` — owns no workspace on a paid plan, and no site with a
|
|
197
|
+
* page of its own published.
|
|
198
|
+
* - `free-published` — owns no workspace on a paid plan, and at least one
|
|
199
|
+
* site with a page of its own published.
|
|
200
|
+
* - `paid` — owns at least one workspace on a paid plan.
|
|
201
|
+
* - `lapsed` — the account is more than 30 days old and nothing it did in the
|
|
202
|
+
* last 30 days was recorded. It overlaps the other three on purpose: a
|
|
203
|
+
* paying account that went quiet is both.
|
|
204
|
+
*/ export const AD_AUDIENCE_STAGES = [
|
|
205
|
+
'free-unpublished',
|
|
206
|
+
'free-published',
|
|
207
|
+
'paid',
|
|
208
|
+
'lapsed'
|
|
209
|
+
];
|
|
210
|
+
export const AD_AUDIENCE_STAGE_LABELS = {
|
|
211
|
+
'free-unpublished': 'free, not published',
|
|
212
|
+
'free-published': 'free, published',
|
|
213
|
+
paid: 'paid',
|
|
214
|
+
lapsed: 'lapsed'
|
|
215
|
+
};
|
|
216
|
+
/** How long an account must be quiet, and old, to be lapsed. */ export const AD_AUDIENCE_LAPSE_DAYS = 30;
|
|
217
|
+
export const AD_AUDIENCE_LAPSE_MS = AD_AUDIENCE_LAPSE_DAYS * 86400000;
|
|
218
|
+
/**
|
|
219
|
+
* Change-log actions the platform writes under the person's id that are not
|
|
220
|
+
* the person doing anything: the site made at sign-up, the starter it was
|
|
221
|
+
* filled from, and an AI job's output landing (the job's START is what
|
|
222
|
+
* counts, and it is read on its own). The same set the weekly activity
|
|
223
|
+
* report leaves out.
|
|
224
|
+
*/ const NOT_A_PERSON_ACTING = new Set([
|
|
225
|
+
'ai.job.output',
|
|
226
|
+
'Created the site',
|
|
227
|
+
'Started from the starter site'
|
|
228
|
+
]);
|
|
229
|
+
/** Whether one change-log entry's action is something the person did. */ export function isRealActivityAction(action) {
|
|
230
|
+
return typeof action === 'string' && Boolean(action) && !NOT_A_PERSON_ACTING.has(action);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* An instant in milliseconds off a stored value in whichever form it reached
|
|
234
|
+
* this reader — a Firestore `Timestamp`, `{ seconds }` or `{ _seconds }`, a
|
|
235
|
+
* `Date`, a number or an ISO string — or null.
|
|
236
|
+
*/ export function instantMs(value) {
|
|
237
|
+
var _record_seconds;
|
|
238
|
+
if (value === null || value === undefined) return null;
|
|
239
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
|
240
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime();
|
|
241
|
+
if (typeof value === 'string') {
|
|
242
|
+
const parsed = Date.parse(value);
|
|
243
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
244
|
+
}
|
|
245
|
+
if (typeof value !== 'object') return null;
|
|
246
|
+
const toMillis = value.toMillis;
|
|
247
|
+
if (typeof toMillis === 'function') {
|
|
248
|
+
const ms = Number(toMillis.call(value));
|
|
249
|
+
return Number.isFinite(ms) ? ms : null;
|
|
250
|
+
}
|
|
251
|
+
const record = value;
|
|
252
|
+
const seconds = Number((_record_seconds = record.seconds) != null ? _record_seconds : record._seconds);
|
|
253
|
+
return Number.isFinite(seconds) ? seconds * 1000 : null;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Whether one page counts as the account's own and published: live
|
|
257
|
+
* (`publishedAt` set and not in the future, not deleted) and worked on by a
|
|
258
|
+
* person — made by one (`createdBy`), or saved more than a minute after it
|
|
259
|
+
* was made.
|
|
260
|
+
*
|
|
261
|
+
* The second half is why "has a published site" cannot be read off the site:
|
|
262
|
+
* every new site is born a published starter website, so a site that is live
|
|
263
|
+
* says nothing about whether its owner did anything. It is the weekly
|
|
264
|
+
* activity report's test, less the page's version history, which is one more
|
|
265
|
+
* read per page and moves with `updatedAt` anyway.
|
|
266
|
+
*/ export function isOwnPublishedScreen(screen, now) {
|
|
267
|
+
var _instantMs, _instantMs1;
|
|
268
|
+
if (screen.deletedAt) return false;
|
|
269
|
+
const published = instantMs(screen.publishedAt);
|
|
270
|
+
if (published === null || published > now) return false;
|
|
271
|
+
if (typeof screen.createdBy === 'string' && screen.createdBy) return true;
|
|
272
|
+
const created = (_instantMs = instantMs(screen.createdAt)) != null ? _instantMs : 0;
|
|
273
|
+
const updated = (_instantMs1 = instantMs(screen.updatedAt)) != null ? _instantMs1 : 0;
|
|
274
|
+
return updated - created > 60000;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Whether an account has lapsed: older than the window, and no real activity
|
|
278
|
+
* found inside it. An account with no creation time is never lapsed — there
|
|
279
|
+
* is no telling it from one made today.
|
|
280
|
+
*
|
|
281
|
+
* Only what the platform recorded the person DOING counts — their entries in
|
|
282
|
+
* a site's or workspace's change log and the AI jobs they started. Firebase's
|
|
283
|
+
* `lastSignInTime` and `lastRefreshTime` are deliberately not read: a browser
|
|
284
|
+
* tab reloading in the background signs the person back in silently, which
|
|
285
|
+
* moves both with nobody there.
|
|
286
|
+
*/ export function isLapsedAccount(facts, now) {
|
|
287
|
+
if (facts.createdAtMs === null) return false;
|
|
288
|
+
if (now - facts.createdAtMs <= AD_AUDIENCE_LAPSE_MS) return false;
|
|
289
|
+
return facts.lastActivityAtMs === null || now - facts.lastActivityAtMs > AD_AUDIENCE_LAPSE_MS;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Every stage an ELIGIBLE account is in. Eligibility is the caller's: this
|
|
293
|
+
* classifies, it does not include. An account read without stage facts is
|
|
294
|
+
* in none.
|
|
295
|
+
*/ export function adAudienceStages(account, now) {
|
|
296
|
+
const facts = account.stageFacts;
|
|
297
|
+
if (!facts) return [];
|
|
298
|
+
const stages = [
|
|
299
|
+
facts.ownsPaidWorkspace ? 'paid' : facts.ownsPublishedSite ? 'free-published' : 'free-unpublished'
|
|
300
|
+
];
|
|
301
|
+
if (isLapsedAccount(facts, now)) stages.push('lapsed');
|
|
302
|
+
return stages;
|
|
303
|
+
}
|
|
182
304
|
/*==========================================
|
|
183
305
|
* THE DIFF
|
|
184
306
|
*=========================================*/ /** What has to change for a provider to hold `next` when it holds `previous`. */ export function diffAudience(previous, next) {
|
|
@@ -222,51 +344,78 @@ const ALPHA2 = /^[A-Z]{2}$/;
|
|
|
222
344
|
GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID: process.env.GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID,
|
|
223
345
|
GOOGLE_AUDIENCE_SYNC_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_USER_LIST_ID,
|
|
224
346
|
LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN: process.env.LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN,
|
|
225
|
-
LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID
|
|
347
|
+
LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID,
|
|
348
|
+
// The stage lists (AGL-4072): one list id per provider and stage.
|
|
349
|
+
META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID,
|
|
350
|
+
META_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_AUDIENCE_ID,
|
|
351
|
+
META_AUDIENCE_SYNC_STAGE_PAID_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_PAID_AUDIENCE_ID,
|
|
352
|
+
META_AUDIENCE_SYNC_STAGE_LAPSED_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_LAPSED_AUDIENCE_ID,
|
|
353
|
+
GOOGLE_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_USER_LIST_ID,
|
|
354
|
+
GOOGLE_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_USER_LIST_ID,
|
|
355
|
+
GOOGLE_AUDIENCE_SYNC_STAGE_PAID_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_PAID_USER_LIST_ID,
|
|
356
|
+
GOOGLE_AUDIENCE_SYNC_STAGE_LAPSED_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_LAPSED_USER_LIST_ID,
|
|
357
|
+
LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_SEGMENT_ID,
|
|
358
|
+
LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_SEGMENT_ID,
|
|
359
|
+
LINKEDIN_AUDIENCE_SYNC_STAGE_PAID_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_PAID_SEGMENT_ID,
|
|
360
|
+
LINKEDIN_AUDIENCE_SYNC_STAGE_LAPSED_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_LAPSED_SEGMENT_ID
|
|
226
361
|
};
|
|
227
362
|
}
|
|
228
|
-
const
|
|
363
|
+
/** Each provider's credentials: what every one of its lists shares. */ const CREDENTIALS = {
|
|
229
364
|
meta: [
|
|
230
|
-
'META_AUDIENCE_SYNC_ACCESS_TOKEN'
|
|
231
|
-
'META_AUDIENCE_SYNC_AUDIENCE_ID'
|
|
365
|
+
'META_AUDIENCE_SYNC_ACCESS_TOKEN'
|
|
232
366
|
],
|
|
233
367
|
google: [
|
|
234
368
|
'GOOGLE_AUDIENCE_SYNC_CLIENT_ID',
|
|
235
369
|
'GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET',
|
|
236
370
|
'GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN',
|
|
237
|
-
'GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID'
|
|
238
|
-
'GOOGLE_AUDIENCE_SYNC_USER_LIST_ID'
|
|
371
|
+
'GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID'
|
|
239
372
|
],
|
|
240
373
|
linkedin: [
|
|
241
|
-
'LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'
|
|
242
|
-
'LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID'
|
|
374
|
+
'LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'
|
|
243
375
|
]
|
|
244
376
|
};
|
|
377
|
+
/** The all-holders list id on each provider. */ const LIST_ID = {
|
|
378
|
+
meta: 'META_AUDIENCE_SYNC_AUDIENCE_ID',
|
|
379
|
+
google: 'GOOGLE_AUDIENCE_SYNC_USER_LIST_ID',
|
|
380
|
+
linkedin: 'LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID'
|
|
381
|
+
};
|
|
382
|
+
const LIST_ID_SUFFIX = {
|
|
383
|
+
meta: 'AUDIENCE_ID',
|
|
384
|
+
google: 'USER_LIST_ID',
|
|
385
|
+
linkedin: 'SEGMENT_ID'
|
|
386
|
+
};
|
|
387
|
+
const PROVIDER_PREFIX = {
|
|
388
|
+
meta: 'META_AUDIENCE_SYNC',
|
|
389
|
+
google: 'GOOGLE_AUDIENCE_SYNC',
|
|
390
|
+
linkedin: 'LINKEDIN_AUDIENCE_SYNC'
|
|
391
|
+
};
|
|
392
|
+
/**
|
|
393
|
+
* The variable that holds one stage's list id on one provider, e.g.
|
|
394
|
+
* `META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID`. Every name it
|
|
395
|
+
* builds is read literally in `adAudienceEnv`.
|
|
396
|
+
*/ export function stageListVariable(provider, stage) {
|
|
397
|
+
const name = stage.toUpperCase().replace(/-/g, '_');
|
|
398
|
+
return `${PROVIDER_PREFIX[provider]}_STAGE_${name}_${LIST_ID_SUFFIX[provider]}`;
|
|
399
|
+
}
|
|
245
400
|
const digits = (value)=>value.replace(/\D/g, '');
|
|
246
401
|
/**
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
|
|
251
|
-
* The Meta audience is never created here. Creating one when the id is unset
|
|
252
|
-
* would mint a fresh, empty audience on every run whose variable was lost, and
|
|
253
|
-
* the ads targeting the real one would go on pointing at it, so the id is
|
|
254
|
-
* required and the audience is made once, by hand.
|
|
255
|
-
*/ export function readAdAudienceConfig(env = adAudienceEnv()) {
|
|
256
|
-
const value = (name)=>{
|
|
257
|
-
var _env_name;
|
|
258
|
-
return String((_env_name = env[name]) != null ? _env_name : '').trim();
|
|
259
|
-
};
|
|
402
|
+
* One list on every provider, given the variable that names its id on each.
|
|
403
|
+
* Shared by the all-holders list and every stage, so the credentials are
|
|
404
|
+
* read, and normalized, in exactly one way.
|
|
405
|
+
*/ function readListConfig(value, listVariable) {
|
|
260
406
|
const missing = Object.fromEntries(AD_AUDIENCE_PROVIDERS.map((provider)=>[
|
|
261
407
|
provider,
|
|
262
|
-
|
|
408
|
+
[
|
|
409
|
+
...CREDENTIALS[provider],
|
|
410
|
+
listVariable[provider]
|
|
411
|
+
].filter((name)=>!value(name))
|
|
263
412
|
]));
|
|
264
413
|
const loginCustomerId = digits(value('GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID'));
|
|
265
414
|
return {
|
|
266
415
|
meta: missing.meta.length ? null : {
|
|
267
416
|
accessToken: value('META_AUDIENCE_SYNC_ACCESS_TOKEN'),
|
|
268
417
|
// `act_` belongs to the ad account, never to an audience id.
|
|
269
|
-
audienceId: value(
|
|
418
|
+
audienceId: value(listVariable.meta)
|
|
270
419
|
},
|
|
271
420
|
google: missing.google.length ? null : {
|
|
272
421
|
clientId: value('GOOGLE_AUDIENCE_SYNC_CLIENT_ID'),
|
|
@@ -275,16 +424,45 @@ const digits = (value)=>value.replace(/\D/g, '');
|
|
|
275
424
|
// Google Ads shows `841-500-9958`; the API takes the digits.
|
|
276
425
|
customerId: digits(value('GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID')),
|
|
277
426
|
loginCustomerId: loginCustomerId || null,
|
|
278
|
-
userListId: digits(value(
|
|
427
|
+
userListId: digits(value(listVariable.google))
|
|
279
428
|
},
|
|
280
429
|
linkedin: missing.linkedin.length ? null : {
|
|
281
430
|
accessToken: value('LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'),
|
|
282
431
|
// The segment URN's id, whichever form was pasted.
|
|
283
|
-
segmentId: value(
|
|
432
|
+
segmentId: value(listVariable.linkedin).replace(/^urn:li:dmpSegment:/, '')
|
|
284
433
|
},
|
|
285
434
|
missing
|
|
286
435
|
};
|
|
287
436
|
}
|
|
437
|
+
/**
|
|
438
|
+
* Each provider's settings, or null with the names it lacks. A provider is
|
|
439
|
+
* configured only when every required variable is set; a half-configured one
|
|
440
|
+
* is skipped, never half-sent.
|
|
441
|
+
*
|
|
442
|
+
* The Meta audience is never created here. Creating one when the id is unset
|
|
443
|
+
* would mint a fresh, empty audience on every run whose variable was lost, and
|
|
444
|
+
* the ads targeting the real one would go on pointing at it, so the id is
|
|
445
|
+
* required and the audience is made once, by hand. The same holds for every
|
|
446
|
+
* stage list: an unset stage id is a stage that is not sent, never one made.
|
|
447
|
+
*
|
|
448
|
+
* A stage list never depends on the all-holders list's id: it needs only
|
|
449
|
+
* its provider's credentials and its own id.
|
|
450
|
+
*/ export function readAdAudienceConfig(env = adAudienceEnv()) {
|
|
451
|
+
const value = (name)=>{
|
|
452
|
+
var _env_name;
|
|
453
|
+
return String((_env_name = env[name]) != null ? _env_name : '').trim();
|
|
454
|
+
};
|
|
455
|
+
const stages = Object.fromEntries(AD_AUDIENCE_STAGES.map((stage)=>[
|
|
456
|
+
stage,
|
|
457
|
+
readListConfig(value, Object.fromEntries(AD_AUDIENCE_PROVIDERS.map((provider)=>[
|
|
458
|
+
provider,
|
|
459
|
+
stageListVariable(provider, stage)
|
|
460
|
+
])))
|
|
461
|
+
]));
|
|
462
|
+
return _extends({}, readListConfig(value, LIST_ID), {
|
|
463
|
+
stages
|
|
464
|
+
});
|
|
465
|
+
}
|
|
288
466
|
/**
|
|
289
467
|
* META — the replace session.
|
|
290
468
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/ad-audience-sync.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\n\n/**\n * THE ACCOUNT-HOLDER AD AUDIENCE (AGL-3780) — the pure half.\n *\n * Once a night the operator's own account holders are kept in step with a\n * customer-list audience on each of the operator's OWN ad accounts — Meta\n * Custom Audiences, Google Customer Match and LinkedIn DMP segments — so\n * signed-up people can be retargeted and left out of prospecting. This is\n * the platform's marketing, not a merchant feature: a merchant's own pixels\n * and conversion APIs are the ad-conversions plugin, which this shares\n * nothing with.\n *\n * Everything here is pure — normalization, hashing, who is eligible, the\n * add/remove diff and each provider's request — so the spec walks every rule\n * without a network. `ad-audience-sync-run.ts` reads the accounts, sends and\n * records.\n *\n * No address ever leaves in the clear: each provider receives the SHA-256 hex\n * digest of the address normalized the way that provider documents, and\n * nothing here logs either one.\n */\n\nexport const AD_AUDIENCE_PROVIDERS = ['meta', 'google', 'linkedin'] as const\nexport type AdAudienceProvider = (typeof AD_AUDIENCE_PROVIDERS)[number]\n\nexport const AD_AUDIENCE_PROVIDER_LABELS: Record<AdAudienceProvider, string> = {\n meta: 'Meta',\n google: 'Google',\n linkedin: 'LinkedIn',\n}\n\n/*==========================================\n * NORMALIZATION AND HASHING\n *=========================================*/\n\nconst GOOGLE_CONSUMER_DOMAINS = new Set(['gmail.com', 'googlemail.com'])\n\n/**\n * The address the way one provider says to normalize it before hashing, or\n * null when it is not an address at all.\n *\n * - **Meta** (Custom Audiences, `EMAIL`): trim leading and trailing white\n * space, lowercase.\n * - **LinkedIn** (DMP segment users, `SHA256_EMAIL`): lowercase, remove any\n * white space.\n * - **Google** (Data Manager API, Customer Match): lowercase, remove leading,\n * trailing and inner white space, and for `gmail.com` and `googlemail.com`\n * only, remove the dots from the local part and drop a `+` and everything\n * after it. Other domains keep both.\n *\n * Inner white space is never part of a deliverable address, so removing it\n * for Meta as well would change nothing real; it is left exactly as Meta\n * documents it.\n */\nexport function normalizeAudienceEmail(\n provider: AdAudienceProvider,\n raw: unknown,\n): string | null {\n if (typeof raw !== 'string') return null\n let email =\n provider === 'meta' ? raw.trim().toLowerCase() : raw.replace(/\\s+/g, '').toLowerCase()\n const at = email.lastIndexOf('@')\n if (at <= 0 || at === email.length - 1 || email.indexOf('@') !== at) return null\n if (provider === 'google') {\n let local = email.slice(0, at)\n const domain = email.slice(at + 1)\n if (GOOGLE_CONSUMER_DOMAINS.has(domain)) {\n const plus = local.indexOf('+')\n if (plus >= 0) local = local.slice(0, plus)\n local = local.replace(/\\./g, '')\n if (!local) return null\n email = `${local}@${domain}`\n }\n }\n return email\n}\n\n/** Lowercase SHA-256 hex of a UTF-8 string: what all three providers take. */\nexport function sha256Hex(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex')\n}\n\n/** The hash one provider receives for an address, or null for no address. */\nexport function hashAudienceEmail(provider: AdAudienceProvider, raw: unknown): string | null {\n const normalized = normalizeAudienceEmail(provider, raw)\n return normalized ? sha256Hex(normalized) : null\n}\n\n/*==========================================\n * ELIGIBILITY\n *=========================================*/\n\n/** What the sync knows about one account, read from Auth and Firestore. */\nexport interface AdAudienceAccount {\n uid: string\n email: string | null\n emailVerified: boolean\n disabled: boolean\n /** The `staff` custom claim. */\n staff: boolean\n /** `users/{uid}.adAudienceOptOut` is set. */\n optedOut: boolean\n /** An account lockdown is in force (`lockdowns/user--{uid}`). */\n locked: boolean\n /** The address is on the account-ban suppression list (an `abuse` ban). */\n banned: boolean\n /**\n * The billing-address countries (`orgs/{id}.contact.address.country`) of\n * the workspaces the account OWNS.\n */\n billingCountries: readonly string[]\n /** `users/{uid}.acquisition.geo.country`: where the sign-up request came from. */\n signupCountry: string | null\n}\n\n/** Why an account is left out. Counted in every report; never per person. */\nexport type AdAudienceExclusion =\n | 'no-email'\n | 'disabled'\n | 'staff'\n | 'internal'\n | 'locked'\n | 'banned'\n | 'opted-out'\n | 'unverified'\n | 'no-country'\n | 'not-us'\n\nexport const AD_AUDIENCE_EXCLUSIONS: readonly AdAudienceExclusion[] = [\n 'no-email',\n 'disabled',\n 'staff',\n 'internal',\n 'locked',\n 'banned',\n 'opted-out',\n 'unverified',\n 'no-country',\n 'not-us',\n]\n\n/** The one country the audience is built for. */\nexport const AD_AUDIENCE_COUNTRY = 'US'\n\nexport type AdAudienceCountrySource = 'billing' | 'signup'\n\nconst ALPHA2 = /^[A-Z]{2}$/\n\n/**\n * The account's country, and which signal said so.\n *\n * 1. **The billing address** of a workspace the account owns. It is the\n * address the account holder typed or gave Stripe, it is the address tax\n * is computed on, and it is the strongest country fact the platform holds.\n * When the account owns workspaces billed in different countries, the\n * answer is US only when EVERY one of them is US: an account that bills\n * from abroad is not counted as a US account holder on the strength of\n * one US workspace.\n * 2. Otherwise **the sign-up geography**: the country the edge reported for\n * the request that created the account (AGL-3289). It says where the\n * person was when they signed up, which is a weaker fact, and it is the\n * one most accounts have.\n * 3. Otherwise nothing, and an account with no country is left out. A phone\n * number's `+1` is deliberately not a signal: it is shared with Canada and\n * the Caribbean.\n */\nexport function resolveAccountCountry(account: {\n billingCountries: readonly string[]\n signupCountry: string | null\n}): { country: string | null; source: AdAudienceCountrySource | null } {\n const billing = [\n ...new Set(\n account.billingCountries\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => ALPHA2.test(country)),\n ),\n ]\n if (billing.length) {\n const foreign = billing.find((country) => country !== AD_AUDIENCE_COUNTRY)\n return { country: foreign ?? AD_AUDIENCE_COUNTRY, source: 'billing' }\n }\n const signup = String(account.signupCountry ?? '').trim().toUpperCase()\n if (ALPHA2.test(signup)) return { country: signup, source: 'signup' }\n return { country: null, source: null }\n}\n\n/** The domain part of an operator address, lowercased, or null. */\nexport function emailDomain(address: string | null | undefined): string | null {\n const value = String(address ?? '').trim().toLowerCase()\n const at = value.lastIndexOf('@')\n return at > 0 && at < value.length - 1 ? value.slice(at + 1) : null\n}\n\n/**\n * Why this account is left out, or null when it belongs in the audience.\n *\n * Every condition must hold: an address, not disabled, not staff, not on the\n * operator's own domain, no account lock (an `abuse` lock is a permanent ban),\n * not on the ban list, not opted out, a verified address, and a United\n * States country. Account deletion needs no rule: an erased account has no\n * Auth record, so it is never read at all, and the diff removes it.\n *\n * The address must be VERIFIED because anyone can sign up with an address\n * that is not theirs, and uploading it would put a person who never signed up\n * into the audience. A Google or SSO sign-in arrives verified.\n */\nexport function adAudienceExclusion(\n account: AdAudienceAccount,\n options: { internalDomains?: readonly string[] } = {},\n): AdAudienceExclusion | null {\n const domain = emailDomain(account.email)\n if (!domain) return 'no-email'\n if (account.disabled) return 'disabled'\n if (account.staff) return 'staff'\n if ((options.internalDomains ?? []).some((internal) => internal.toLowerCase() === domain)) {\n return 'internal'\n }\n if (account.locked) return 'locked'\n if (account.banned) return 'banned'\n if (account.optedOut) return 'opted-out'\n if (!account.emailVerified) return 'unverified'\n const { country } = resolveAccountCountry(account)\n if (!country) return 'no-country'\n if (country !== AD_AUDIENCE_COUNTRY) return 'not-us'\n return null\n}\n\n/*==========================================\n * THE DIFF\n *=========================================*/\n\n/** What has to change for a provider to hold `next` when it holds `previous`. */\nexport function diffAudience(\n previous: Iterable<string>,\n next: Iterable<string>,\n): { toAdd: string[]; toRemove: string[] } {\n const before = new Set(previous)\n const after = new Set(next)\n return {\n toAdd: [...after].filter((hash) => !before.has(hash)).sort(),\n toRemove: [...before].filter((hash) => !after.has(hash)).sort(),\n }\n}\n\n/**\n * Whether a night's set shrank so far it is more likely a failed read than\n * real churn. Below twenty there is no telling the two apart, so it is never\n * refused; above it, losing more than half the audience in one night is held\n * until a person passes `force`.\n */\nexport function isSuspiciousShrink(previousSize: number, nextSize: number): boolean {\n return previousSize >= 20 && nextSize < previousSize / 2\n}\n\n/** `items` in runs of at most `size`. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n const runs: T[][] = []\n for (let index = 0; index < items.length; index += size) {\n runs.push(items.slice(index, index + size))\n }\n return runs\n}\n\n/*==========================================\n * CONFIGURATION\n *=========================================*/\n\nexport interface MetaAudienceConfig {\n accessToken: string\n audienceId: string\n}\n\nexport interface GoogleAudienceConfig {\n clientId: string\n clientSecret: string\n refreshToken: string\n /** The Google Ads customer that owns the list, digits only. */\n customerId: string\n /** A manager account the credentials reach the customer through, digits only. */\n loginCustomerId: string | null\n /** The Customer Match user list id. */\n userListId: string\n}\n\nexport interface LinkedInAudienceConfig {\n accessToken: string\n segmentId: string\n}\n\nexport interface AdAudienceConfig {\n meta: MetaAudienceConfig | null\n google: GoogleAudienceConfig | null\n linkedin: LinkedInAudienceConfig | null\n /** For each provider left unconfigured, the variables it is missing. */\n missing: Record<AdAudienceProvider, string[]>\n}\n\n/**\n * The variables, read here by their literal names so the self-host\n * environment reference can see every one of them.\n */\nexport function adAudienceEnv(): Record<string, string | undefined> {\n return {\n META_AUDIENCE_SYNC_ACCESS_TOKEN: process.env.META_AUDIENCE_SYNC_ACCESS_TOKEN,\n META_AUDIENCE_SYNC_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_AUDIENCE_ID,\n GOOGLE_AUDIENCE_SYNC_CLIENT_ID: process.env.GOOGLE_AUDIENCE_SYNC_CLIENT_ID,\n GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET: process.env.GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET,\n GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN: process.env.GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN,\n GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID: process.env.GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID,\n GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID: process.env.GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID,\n GOOGLE_AUDIENCE_SYNC_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_USER_LIST_ID,\n LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN: process.env.LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN,\n LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID,\n }\n}\n\nconst REQUIRED: Record<AdAudienceProvider, readonly string[]> = {\n meta: ['META_AUDIENCE_SYNC_ACCESS_TOKEN', 'META_AUDIENCE_SYNC_AUDIENCE_ID'],\n google: [\n 'GOOGLE_AUDIENCE_SYNC_CLIENT_ID',\n 'GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET',\n 'GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN',\n 'GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID',\n 'GOOGLE_AUDIENCE_SYNC_USER_LIST_ID',\n ],\n linkedin: ['LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN', 'LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID'],\n}\n\nconst digits = (value: string) => value.replace(/\\D/g, '')\n\n/**\n * Each provider's settings, or null with the names it lacks. A provider is\n * configured only when every required variable is set; a half-configured one\n * is skipped, never half-sent.\n *\n * The Meta audience is never created here. Creating one when the id is unset\n * would mint a fresh, empty audience on every run whose variable was lost, and\n * the ads targeting the real one would go on pointing at it, so the id is\n * required and the audience is made once, by hand.\n */\nexport function readAdAudienceConfig(\n env: Record<string, string | undefined> = adAudienceEnv(),\n): AdAudienceConfig {\n const value = (name: string) => String(env[name] ?? '').trim()\n const missing = Object.fromEntries(\n AD_AUDIENCE_PROVIDERS.map((provider) => [\n provider,\n REQUIRED[provider].filter((name) => !value(name)),\n ]),\n ) as Record<AdAudienceProvider, string[]>\n const loginCustomerId = digits(value('GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID'))\n return {\n meta: missing.meta.length\n ? null\n : {\n accessToken: value('META_AUDIENCE_SYNC_ACCESS_TOKEN'),\n // `act_` belongs to the ad account, never to an audience id.\n audienceId: value('META_AUDIENCE_SYNC_AUDIENCE_ID'),\n },\n google: missing.google.length\n ? null\n : {\n clientId: value('GOOGLE_AUDIENCE_SYNC_CLIENT_ID'),\n clientSecret: value('GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET'),\n refreshToken: value('GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN'),\n // Google Ads shows `841-500-9958`; the API takes the digits.\n customerId: digits(value('GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID')),\n loginCustomerId: loginCustomerId || null,\n userListId: digits(value('GOOGLE_AUDIENCE_SYNC_USER_LIST_ID')),\n },\n linkedin: missing.linkedin.length\n ? null\n : {\n accessToken: value('LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'),\n // The segment URN's id, whichever form was pasted.\n segmentId: value('LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID').replace(/^urn:li:dmpSegment:/, ''),\n },\n missing,\n }\n}\n\n/*==========================================\n * PROVIDER REQUESTS\n *=========================================*/\n\n/** One HTTP request, built without sending it. */\nexport interface AudienceRequest {\n method: 'POST'\n url: string\n headers: Record<string, string>\n /** A JSON body, or a form body when `headers` says so. */\n body: Record<string, unknown> | string\n}\n\n/**\n * META — the replace session.\n *\n * `POST /{audience}/usersreplace` swaps the audience's whole membership for\n * the batches of one session: `batch_seq` 1 opens it and `last_batch_flag`\n * closes it, so a removal needs no separate call and nothing has to be\n * remembered about who was there before. Each batch carries at most 10,000\n * hashes, and the session must finish inside 90 minutes. A replace does not\n * reset an ad set's learning phase, which an add and a delete would.\n */\nexport const META_GRAPH_VERSION = 'v25.0'\nexport const META_REPLACE_BATCH = 10_000\n\nexport function buildMetaReplaceRequests(\n config: MetaAudienceConfig,\n hashes: readonly string[],\n sessionId: number,\n): AudienceRequest[] {\n const batches = chunk(hashes, META_REPLACE_BATCH)\n return batches.map((batch, index) => ({\n method: 'POST',\n url: `https://graph.facebook.com/${META_GRAPH_VERSION}/${encodeURIComponent(config.audienceId)}/usersreplace`,\n headers: { 'Content-Type': 'application/json' },\n body: {\n payload: { schema: 'EMAIL_SHA256', data: batch },\n session: {\n session_id: sessionId,\n batch_seq: index + 1,\n last_batch_flag: index === batches.length - 1,\n estimated_num_total: hashes.length,\n },\n access_token: config.accessToken,\n },\n }))\n}\n\n/**\n * GOOGLE — the Data Manager API, not the Google Ads API.\n *\n * Since 2026-04-01 the Google Ads API's `OfflineUserDataJobService` refuses\n * Customer Match uploads for a developer token with no Customer Match\n * activity in the six months before, and Google points every such project at\n * the Data Manager API instead. It needs an OAuth token with the\n * `datamanager` scope and no developer token.\n *\n * Adds go to `audienceMembers:ingest` and removals to `audienceMembers:remove`,\n * 10,000 members a request. The Data Manager API has no replace, so the\n * removals come from the set this sync last sent.\n *\n * No `consent` is sent. The audience is United States account holders only,\n * for whom Google requires no consent signal, and stating `CONSENT_GRANTED`\n * would assert a consent this platform does not collect.\n * `customerMatchTermsOfServiceStatus: ACCEPTED` is the operator's own\n * acceptance of the Customer Match terms, which Google requires on an\n * ingest; they are accepted in the Google Ads account before this is\n * configured.\n */\nexport const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'\nexport const GOOGLE_DATA_MANAGER_BASE = 'https://datamanager.googleapis.com/v1'\nexport const GOOGLE_MEMBERS_BATCH = 10_000\n\nexport function buildGoogleTokenRequest(config: GoogleAudienceConfig): AudienceRequest {\n return {\n method: 'POST',\n url: GOOGLE_TOKEN_URL,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n refresh_token: config.refreshToken,\n }).toString(),\n }\n}\n\nexport function buildGoogleMemberRequests(\n config: GoogleAudienceConfig,\n accessToken: string,\n action: 'ingest' | 'remove',\n hashes: readonly string[],\n): AudienceRequest[] {\n const destination = {\n operatingAccount: { accountType: 'GOOGLE_ADS', accountId: config.customerId },\n ...(config.loginCustomerId\n ? { loginAccount: { accountType: 'GOOGLE_ADS', accountId: config.loginCustomerId } }\n : {}),\n productDestinationId: config.userListId,\n }\n return chunk(hashes, GOOGLE_MEMBERS_BATCH).map((batch) => ({\n method: 'POST',\n url: `${GOOGLE_DATA_MANAGER_BASE}/audienceMembers:${action}`,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: {\n destinations: [destination],\n audienceMembers: batch.map((hash) => ({\n userData: { userIdentifiers: [{ emailAddress: hash }] },\n })),\n encoding: 'HEX',\n ...(action === 'ingest'\n ? { termsOfService: { customerMatchTermsOfServiceStatus: 'ACCEPTED' } }\n : {}),\n },\n }))\n}\n\n/**\n * LINKEDIN — DMP segment users, streamed.\n *\n * `POST /rest/dmpSegments/{id}/users` with `X-RestLi-Method: BATCH_CREATE`\n * takes up to 5,000 `ADD` or `REMOVE` elements a request. There is no\n * replace, so the removals come from the set this sync last sent. Adding an\n * id twice or removing one already gone both answer 201, so a retry is safe.\n * The API is open only to developers LinkedIn has approved for Matched\n * Audiences, with the `rw_dmp_segments` permission.\n */\nexport const LINKEDIN_VERSION = '202609'\nexport const LINKEDIN_USERS_BATCH = 5_000\n\nexport function buildLinkedInUserRequests(\n config: LinkedInAudienceConfig,\n action: 'ADD' | 'REMOVE',\n hashes: readonly string[],\n): AudienceRequest[] {\n return chunk(hashes, LINKEDIN_USERS_BATCH).map((batch) => ({\n method: 'POST',\n url: `https://api.linkedin.com/rest/dmpSegments/${encodeURIComponent(config.segmentId)}/users`,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.accessToken}`,\n 'LinkedIn-Version': LINKEDIN_VERSION,\n 'X-Restli-Protocol-Version': '2.0.0',\n 'X-RestLi-Method': 'BATCH_CREATE',\n },\n body: {\n elements: batch.map((hash) => ({\n action,\n userIds: [{ idType: 'SHA256_EMAIL', idValue: hash }],\n })),\n },\n }))\n}\n\n/** How many elements of a LinkedIn batch response were refused. */\nexport function linkedInRefusedCount(answer: unknown): number {\n const elements = (answer as { elements?: unknown } | null)?.elements\n if (!Array.isArray(elements)) return 0\n return elements.filter((element) => {\n const status = Number((element as { status?: unknown } | null)?.status)\n return !(status >= 200 && status < 300)\n }).length\n}\n"],"names":["createHash","AD_AUDIENCE_PROVIDERS","AD_AUDIENCE_PROVIDER_LABELS","meta","google","linkedin","GOOGLE_CONSUMER_DOMAINS","Set","normalizeAudienceEmail","provider","raw","email","trim","toLowerCase","replace","at","lastIndexOf","length","indexOf","local","slice","domain","has","plus","sha256Hex","value","update","digest","hashAudienceEmail","normalized","AD_AUDIENCE_EXCLUSIONS","AD_AUDIENCE_COUNTRY","ALPHA2","resolveAccountCountry","account","billing","billingCountries","map","country","String","toUpperCase","filter","test","foreign","find","source","signup","signupCountry","emailDomain","address","adAudienceExclusion","options","disabled","staff","internalDomains","some","internal","locked","banned","optedOut","emailVerified","diffAudience","previous","next","before","after","toAdd","hash","sort","toRemove","isSuspiciousShrink","previousSize","nextSize","chunk","items","size","runs","index","push","adAudienceEnv","META_AUDIENCE_SYNC_ACCESS_TOKEN","process","env","META_AUDIENCE_SYNC_AUDIENCE_ID","GOOGLE_AUDIENCE_SYNC_CLIENT_ID","GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET","GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN","GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID","GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID","GOOGLE_AUDIENCE_SYNC_USER_LIST_ID","LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN","LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID","REQUIRED","digits","readAdAudienceConfig","name","missing","Object","fromEntries","loginCustomerId","accessToken","audienceId","clientId","clientSecret","refreshToken","customerId","userListId","segmentId","META_GRAPH_VERSION","META_REPLACE_BATCH","buildMetaReplaceRequests","config","hashes","sessionId","batches","batch","method","url","encodeURIComponent","headers","body","payload","schema","data","session","session_id","batch_seq","last_batch_flag","estimated_num_total","access_token","GOOGLE_TOKEN_URL","GOOGLE_DATA_MANAGER_BASE","GOOGLE_MEMBERS_BATCH","buildGoogleTokenRequest","URLSearchParams","grant_type","client_id","client_secret","refresh_token","toString","buildGoogleMemberRequests","action","destination","operatingAccount","accountType","accountId","loginAccount","productDestinationId","Authorization","destinations","audienceMembers","userData","userIdentifiers","emailAddress","encoding","termsOfService","customerMatchTermsOfServiceStatus","LINKEDIN_VERSION","LINKEDIN_USERS_BATCH","buildLinkedInUserRequests","elements","userIds","idType","idValue","linkedInRefusedCount","answer","Array","isArray","element","status","Number"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AAExC;;;;;;;;;;;;;;;;;;;CAmBC,GAED,OAAO,MAAMC,wBAAwB;IAAC;IAAQ;IAAU;CAAW,CAAS;AAG5E,OAAO,MAAMC,8BAAkE;IAC7EC,MAAM;IACNC,QAAQ;IACRC,UAAU;AACZ,EAAC;AAED;;2CAE2C,GAE3C,MAAMC,0BAA0B,IAAIC,IAAI;IAAC;IAAa;CAAiB;AAEvE;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,uBACdC,QAA4B,EAC5BC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,UAAU,OAAO;IACpC,IAAIC,QACFF,aAAa,SAASC,IAAIE,IAAI,GAAGC,WAAW,KAAKH,IAAII,OAAO,CAAC,QAAQ,IAAID,WAAW;IACt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AAU,CAAA;wBAC7B0E;wBACAoB,SAAS;4BAAC;gCAAEC,QAAQ;gCAAgBC,SAAShG;4BAAK;yBAAE;oBACtD,CAAA;YACF;QACF,CAAA;AACF;AAEA,iEAAiE,GACjE,OAAO,SAASiG,qBAAqBC,MAAe;IAClD,MAAML,WAAYK,0BAAD,AAACA,OAA0CL,QAAQ;IACpE,IAAI,CAACM,MAAMC,OAAO,CAACP,WAAW,OAAO;IACrC,OAAOA,SAASvH,MAAM,CAAC,CAAC+H;QACtB,MAAMC,SAASC,OAAQF,2BAAD,AAACA,QAAyCC,MAAM;QACtE,OAAO,CAAEA,CAAAA,UAAU,OAAOA,SAAS,GAAE;IACvC,GAAGxJ,MAAM;AACX"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/ad-audience-sync.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\n\n/**\n * THE ACCOUNT-HOLDER AD AUDIENCE (AGL-3780) — the pure half.\n *\n * Once a night the operator's own account holders are kept in step with a\n * customer-list audience on each of the operator's OWN ad accounts — Meta\n * Custom Audiences, Google Customer Match and LinkedIn DMP segments — so\n * signed-up people can be retargeted and left out of prospecting. This is\n * the platform's marketing, not a merchant feature: a merchant's own pixels\n * and conversion APIs are the ad-conversions plugin, which this shares\n * nothing with.\n *\n * Beside that one all-holders list, each provider may keep a STAGE list per\n * stage (AGL-4072): free and not published, free and published, paid, and\n * lapsed. Each is a subset of the same eligible audience, configured by its\n * own list id, and synced, recorded and guarded exactly like the main list.\n *\n * Everything here is pure — normalization, hashing, who is eligible, the\n * add/remove diff and each provider's request — so the spec walks every rule\n * without a network. `ad-audience-sync-run.ts` reads the accounts, sends and\n * records.\n *\n * No address ever leaves in the clear: each provider receives the SHA-256 hex\n * digest of the address normalized the way that provider documents, and\n * nothing here logs either one.\n */\n\nexport const AD_AUDIENCE_PROVIDERS = ['meta', 'google', 'linkedin'] as const\nexport type AdAudienceProvider = (typeof AD_AUDIENCE_PROVIDERS)[number]\n\nexport const AD_AUDIENCE_PROVIDER_LABELS: Record<AdAudienceProvider, string> = {\n meta: 'Meta',\n google: 'Google',\n linkedin: 'LinkedIn',\n}\n\n/*==========================================\n * NORMALIZATION AND HASHING\n *=========================================*/\n\nconst GOOGLE_CONSUMER_DOMAINS = new Set(['gmail.com', 'googlemail.com'])\n\n/**\n * The address the way one provider says to normalize it before hashing, or\n * null when it is not an address at all.\n *\n * - **Meta** (Custom Audiences, `EMAIL`): trim leading and trailing white\n * space, lowercase.\n * - **LinkedIn** (DMP segment users, `SHA256_EMAIL`): lowercase, remove any\n * white space.\n * - **Google** (Data Manager API, Customer Match): lowercase, remove leading,\n * trailing and inner white space, and for `gmail.com` and `googlemail.com`\n * only, remove the dots from the local part and drop a `+` and everything\n * after it. Other domains keep both.\n *\n * Inner white space is never part of a deliverable address, so removing it\n * for Meta as well would change nothing real; it is left exactly as Meta\n * documents it.\n */\nexport function normalizeAudienceEmail(\n provider: AdAudienceProvider,\n raw: unknown,\n): string | null {\n if (typeof raw !== 'string') return null\n let email =\n provider === 'meta' ? raw.trim().toLowerCase() : raw.replace(/\\s+/g, '').toLowerCase()\n const at = email.lastIndexOf('@')\n if (at <= 0 || at === email.length - 1 || email.indexOf('@') !== at) return null\n if (provider === 'google') {\n let local = email.slice(0, at)\n const domain = email.slice(at + 1)\n if (GOOGLE_CONSUMER_DOMAINS.has(domain)) {\n const plus = local.indexOf('+')\n if (plus >= 0) local = local.slice(0, plus)\n local = local.replace(/\\./g, '')\n if (!local) return null\n email = `${local}@${domain}`\n }\n }\n return email\n}\n\n/** Lowercase SHA-256 hex of a UTF-8 string: what all three providers take. */\nexport function sha256Hex(value: string): string {\n return createHash('sha256').update(value, 'utf8').digest('hex')\n}\n\n/** The hash one provider receives for an address, or null for no address. */\nexport function hashAudienceEmail(provider: AdAudienceProvider, raw: unknown): string | null {\n const normalized = normalizeAudienceEmail(provider, raw)\n return normalized ? sha256Hex(normalized) : null\n}\n\n/*==========================================\n * ELIGIBILITY\n *=========================================*/\n\n/** What the sync knows about one account, read from Auth and Firestore. */\nexport interface AdAudienceAccount {\n uid: string\n email: string | null\n emailVerified: boolean\n disabled: boolean\n /** The `staff` custom claim. */\n staff: boolean\n /** `users/{uid}.adAudienceOptOut` is set. */\n optedOut: boolean\n /** An account lockdown is in force (`lockdowns/user--{uid}`). */\n locked: boolean\n /** The address is on the account-ban suppression list (an `abuse` ban). */\n banned: boolean\n /**\n * The billing-address countries (`orgs/{id}.contact.address.country`) of\n * the workspaces the account OWNS.\n */\n billingCountries: readonly string[]\n /** `users/{uid}.acquisition.geo.country`: where the sign-up request came from. */\n signupCountry: string | null\n /**\n * The facts the STAGE lists read (AGL-4072). Optional so an account read\n * without them is simply in no stage; eligibility never looks at them.\n */\n stageFacts?: AdAudienceStageFacts\n}\n\n/** What decides an eligible account's stage (AGL-4072). */\nexport interface AdAudienceStageFacts {\n /** When the Auth account was made (`metadata.creationTime`), or null. */\n createdAtMs: number | null\n /** The account OWNS a workspace whose effective plan is a paid one. */\n ownsPaidWorkspace: boolean\n /** The account owns a site with a page of its own that is published. */\n ownsPublishedSite: boolean\n /**\n * The newest real activity found inside the lapse window, or null when\n * none was found there. Only read for an account old enough to lapse; it is\n * never a sign-in time.\n */\n lastActivityAtMs: number | null\n}\n\n/** Why an account is left out. Counted in every report; never per person. */\nexport type AdAudienceExclusion =\n | 'no-email'\n | 'disabled'\n | 'staff'\n | 'internal'\n | 'locked'\n | 'banned'\n | 'opted-out'\n | 'unverified'\n | 'no-country'\n | 'not-us'\n\nexport const AD_AUDIENCE_EXCLUSIONS: readonly AdAudienceExclusion[] = [\n 'no-email',\n 'disabled',\n 'staff',\n 'internal',\n 'locked',\n 'banned',\n 'opted-out',\n 'unverified',\n 'no-country',\n 'not-us',\n]\n\n/** The one country the audience is built for. */\nexport const AD_AUDIENCE_COUNTRY = 'US'\n\nexport type AdAudienceCountrySource = 'billing' | 'signup'\n\nconst ALPHA2 = /^[A-Z]{2}$/\n\n/**\n * The account's country, and which signal said so.\n *\n * 1. **The billing address** of a workspace the account owns. It is the\n * address the account holder typed or gave Stripe, it is the address tax\n * is computed on, and it is the strongest country fact the platform holds.\n * When the account owns workspaces billed in different countries, the\n * answer is US only when EVERY one of them is US: an account that bills\n * from abroad is not counted as a US account holder on the strength of\n * one US workspace.\n * 2. Otherwise **the sign-up geography**: the country the edge reported for\n * the request that created the account (AGL-3289). It says where the\n * person was when they signed up, which is a weaker fact, and it is the\n * one most accounts have.\n * 3. Otherwise nothing, and an account with no country is left out. A phone\n * number's `+1` is deliberately not a signal: it is shared with Canada and\n * the Caribbean.\n */\nexport function resolveAccountCountry(account: {\n billingCountries: readonly string[]\n signupCountry: string | null\n}): { country: string | null; source: AdAudienceCountrySource | null } {\n const billing = [\n ...new Set(\n account.billingCountries\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => ALPHA2.test(country)),\n ),\n ]\n if (billing.length) {\n const foreign = billing.find((country) => country !== AD_AUDIENCE_COUNTRY)\n return { country: foreign ?? AD_AUDIENCE_COUNTRY, source: 'billing' }\n }\n const signup = String(account.signupCountry ?? '').trim().toUpperCase()\n if (ALPHA2.test(signup)) return { country: signup, source: 'signup' }\n return { country: null, source: null }\n}\n\n/** The domain part of an operator address, lowercased, or null. */\nexport function emailDomain(address: string | null | undefined): string | null {\n const value = String(address ?? '').trim().toLowerCase()\n const at = value.lastIndexOf('@')\n return at > 0 && at < value.length - 1 ? value.slice(at + 1) : null\n}\n\n/**\n * Why this account is left out, or null when it belongs in the audience.\n *\n * Every condition must hold: an address, not disabled, not staff, not on the\n * operator's own domain, no account lock (an `abuse` lock is a permanent ban),\n * not on the ban list, not opted out, a verified address, and a United\n * States country. Account deletion needs no rule: an erased account has no\n * Auth record, so it is never read at all, and the diff removes it.\n *\n * The address must be VERIFIED because anyone can sign up with an address\n * that is not theirs, and uploading it would put a person who never signed up\n * into the audience. A Google or SSO sign-in arrives verified.\n */\nexport function adAudienceExclusion(\n account: AdAudienceAccount,\n options: { internalDomains?: readonly string[] } = {},\n): AdAudienceExclusion | null {\n const domain = emailDomain(account.email)\n if (!domain) return 'no-email'\n if (account.disabled) return 'disabled'\n if (account.staff) return 'staff'\n if ((options.internalDomains ?? []).some((internal) => internal.toLowerCase() === domain)) {\n return 'internal'\n }\n if (account.locked) return 'locked'\n if (account.banned) return 'banned'\n if (account.optedOut) return 'opted-out'\n if (!account.emailVerified) return 'unverified'\n const { country } = resolveAccountCountry(account)\n if (!country) return 'no-country'\n if (country !== AD_AUDIENCE_COUNTRY) return 'not-us'\n return null\n}\n\n/*==========================================\n * STAGES (AGL-4072)\n *=========================================*/\n\n/**\n * The stage lists kept beside the all-holders list, so the ads for people\n * who already have an account can say something that fits where they are.\n * Each one is a SUBSET of the eligible audience — every exclusion above\n * still applies first — and each is optional, sent only when its own list id\n * is set.\n *\n * - `free-unpublished` — owns no workspace on a paid plan, and no site with a\n * page of its own published.\n * - `free-published` — owns no workspace on a paid plan, and at least one\n * site with a page of its own published.\n * - `paid` — owns at least one workspace on a paid plan.\n * - `lapsed` — the account is more than 30 days old and nothing it did in the\n * last 30 days was recorded. It overlaps the other three on purpose: a\n * paying account that went quiet is both.\n */\nexport const AD_AUDIENCE_STAGES = ['free-unpublished', 'free-published', 'paid', 'lapsed'] as const\nexport type AdAudienceStage = (typeof AD_AUDIENCE_STAGES)[number]\n\nexport const AD_AUDIENCE_STAGE_LABELS: Record<AdAudienceStage, string> = {\n 'free-unpublished': 'free, not published',\n 'free-published': 'free, published',\n paid: 'paid',\n lapsed: 'lapsed',\n}\n\n/** How long an account must be quiet, and old, to be lapsed. */\nexport const AD_AUDIENCE_LAPSE_DAYS = 30\nexport const AD_AUDIENCE_LAPSE_MS = AD_AUDIENCE_LAPSE_DAYS * 86_400_000\n\n/**\n * Change-log actions the platform writes under the person's id that are not\n * the person doing anything: the site made at sign-up, the starter it was\n * filled from, and an AI job's output landing (the job's START is what\n * counts, and it is read on its own). The same set the weekly activity\n * report leaves out.\n */\nconst NOT_A_PERSON_ACTING = new Set(['ai.job.output', 'Created the site', 'Started from the starter site'])\n\n/** Whether one change-log entry's action is something the person did. */\nexport function isRealActivityAction(action: unknown): boolean {\n return typeof action === 'string' && Boolean(action) && !NOT_A_PERSON_ACTING.has(action)\n}\n\n/**\n * An instant in milliseconds off a stored value in whichever form it reached\n * this reader — a Firestore `Timestamp`, `{ seconds }` or `{ _seconds }`, a\n * `Date`, a number or an ISO string — or null.\n */\nexport function instantMs(value: unknown): number | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime()\n if (typeof value === 'string') {\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n if (typeof value !== 'object') return null\n const toMillis = (value as { toMillis?: unknown }).toMillis\n if (typeof toMillis === 'function') {\n const ms = Number(toMillis.call(value))\n return Number.isFinite(ms) ? ms : null\n }\n const record = value as { seconds?: unknown; _seconds?: unknown }\n const seconds = Number(record.seconds ?? record._seconds)\n return Number.isFinite(seconds) ? seconds * 1000 : null\n}\n\n/** A page document's fields the published test reads. */\nexport interface AdAudienceScreenFacts {\n publishedAt?: unknown\n deletedAt?: unknown\n createdAt?: unknown\n updatedAt?: unknown\n createdBy?: unknown\n}\n\n/**\n * Whether one page counts as the account's own and published: live\n * (`publishedAt` set and not in the future, not deleted) and worked on by a\n * person — made by one (`createdBy`), or saved more than a minute after it\n * was made.\n *\n * The second half is why \"has a published site\" cannot be read off the site:\n * every new site is born a published starter website, so a site that is live\n * says nothing about whether its owner did anything. It is the weekly\n * activity report's test, less the page's version history, which is one more\n * read per page and moves with `updatedAt` anyway.\n */\nexport function isOwnPublishedScreen(screen: AdAudienceScreenFacts, now: number): boolean {\n if (screen.deletedAt) return false\n const published = instantMs(screen.publishedAt)\n if (published === null || published > now) return false\n if (typeof screen.createdBy === 'string' && screen.createdBy) return true\n const created = instantMs(screen.createdAt) ?? 0\n const updated = instantMs(screen.updatedAt) ?? 0\n return updated - created > 60_000\n}\n\n/**\n * Whether an account has lapsed: older than the window, and no real activity\n * found inside it. An account with no creation time is never lapsed — there\n * is no telling it from one made today.\n *\n * Only what the platform recorded the person DOING counts — their entries in\n * a site's or workspace's change log and the AI jobs they started. Firebase's\n * `lastSignInTime` and `lastRefreshTime` are deliberately not read: a browser\n * tab reloading in the background signs the person back in silently, which\n * moves both with nobody there.\n */\nexport function isLapsedAccount(facts: AdAudienceStageFacts, now: number): boolean {\n if (facts.createdAtMs === null) return false\n if (now - facts.createdAtMs <= AD_AUDIENCE_LAPSE_MS) return false\n return facts.lastActivityAtMs === null || now - facts.lastActivityAtMs > AD_AUDIENCE_LAPSE_MS\n}\n\n/**\n * Every stage an ELIGIBLE account is in. Eligibility is the caller's: this\n * classifies, it does not include. An account read without stage facts is\n * in none.\n */\nexport function adAudienceStages(account: AdAudienceAccount, now: number): AdAudienceStage[] {\n const facts = account.stageFacts\n if (!facts) return []\n const stages: AdAudienceStage[] = [\n facts.ownsPaidWorkspace ? 'paid' : facts.ownsPublishedSite ? 'free-published' : 'free-unpublished',\n ]\n if (isLapsedAccount(facts, now)) stages.push('lapsed')\n return stages\n}\n\n/*==========================================\n * THE DIFF\n *=========================================*/\n\n/** What has to change for a provider to hold `next` when it holds `previous`. */\nexport function diffAudience(\n previous: Iterable<string>,\n next: Iterable<string>,\n): { toAdd: string[]; toRemove: string[] } {\n const before = new Set(previous)\n const after = new Set(next)\n return {\n toAdd: [...after].filter((hash) => !before.has(hash)).sort(),\n toRemove: [...before].filter((hash) => !after.has(hash)).sort(),\n }\n}\n\n/**\n * Whether a night's set shrank so far it is more likely a failed read than\n * real churn. Below twenty there is no telling the two apart, so it is never\n * refused; above it, losing more than half the audience in one night is held\n * until a person passes `force`.\n */\nexport function isSuspiciousShrink(previousSize: number, nextSize: number): boolean {\n return previousSize >= 20 && nextSize < previousSize / 2\n}\n\n/** `items` in runs of at most `size`. */\nexport function chunk<T>(items: readonly T[], size: number): T[][] {\n const runs: T[][] = []\n for (let index = 0; index < items.length; index += size) {\n runs.push(items.slice(index, index + size))\n }\n return runs\n}\n\n/*==========================================\n * CONFIGURATION\n *=========================================*/\n\nexport interface MetaAudienceConfig {\n accessToken: string\n audienceId: string\n}\n\nexport interface GoogleAudienceConfig {\n clientId: string\n clientSecret: string\n refreshToken: string\n /** The Google Ads customer that owns the list, digits only. */\n customerId: string\n /** A manager account the credentials reach the customer through, digits only. */\n loginCustomerId: string | null\n /** The Customer Match user list id. */\n userListId: string\n}\n\nexport interface LinkedInAudienceConfig {\n accessToken: string\n segmentId: string\n}\n\n/** One list on each provider: its settings, or null with the names it lacks. */\nexport interface AdAudienceListConfig {\n meta: MetaAudienceConfig | null\n google: GoogleAudienceConfig | null\n linkedin: LinkedInAudienceConfig | null\n /** For each provider left unconfigured, the variables it is missing. */\n missing: Record<AdAudienceProvider, string[]>\n}\n\nexport interface AdAudienceConfig extends AdAudienceListConfig {\n /**\n * The stage lists (AGL-4072). Each reuses its provider's credentials and\n * names only its own list id, so a stage is configured when the provider's\n * credentials are set and that stage's id is too.\n */\n stages: Record<AdAudienceStage, AdAudienceListConfig>\n}\n\n/**\n * The variables, read here by their literal names so the self-host\n * environment reference can see every one of them.\n */\nexport function adAudienceEnv(): Record<string, string | undefined> {\n return {\n META_AUDIENCE_SYNC_ACCESS_TOKEN: process.env.META_AUDIENCE_SYNC_ACCESS_TOKEN,\n META_AUDIENCE_SYNC_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_AUDIENCE_ID,\n GOOGLE_AUDIENCE_SYNC_CLIENT_ID: process.env.GOOGLE_AUDIENCE_SYNC_CLIENT_ID,\n GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET: process.env.GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET,\n GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN: process.env.GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN,\n GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID: process.env.GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID,\n GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID: process.env.GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID,\n GOOGLE_AUDIENCE_SYNC_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_USER_LIST_ID,\n LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN: process.env.LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN,\n LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID,\n // The stage lists (AGL-4072): one list id per provider and stage.\n META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID:\n process.env.META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID,\n META_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_AUDIENCE_ID:\n process.env.META_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_AUDIENCE_ID,\n META_AUDIENCE_SYNC_STAGE_PAID_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_PAID_AUDIENCE_ID,\n META_AUDIENCE_SYNC_STAGE_LAPSED_AUDIENCE_ID: process.env.META_AUDIENCE_SYNC_STAGE_LAPSED_AUDIENCE_ID,\n GOOGLE_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_USER_LIST_ID:\n process.env.GOOGLE_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_USER_LIST_ID,\n GOOGLE_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_USER_LIST_ID:\n process.env.GOOGLE_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_USER_LIST_ID,\n GOOGLE_AUDIENCE_SYNC_STAGE_PAID_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_PAID_USER_LIST_ID,\n GOOGLE_AUDIENCE_SYNC_STAGE_LAPSED_USER_LIST_ID: process.env.GOOGLE_AUDIENCE_SYNC_STAGE_LAPSED_USER_LIST_ID,\n LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_SEGMENT_ID:\n process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_SEGMENT_ID,\n LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_SEGMENT_ID:\n process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_SEGMENT_ID,\n LINKEDIN_AUDIENCE_SYNC_STAGE_PAID_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_PAID_SEGMENT_ID,\n LINKEDIN_AUDIENCE_SYNC_STAGE_LAPSED_SEGMENT_ID: process.env.LINKEDIN_AUDIENCE_SYNC_STAGE_LAPSED_SEGMENT_ID,\n }\n}\n\n/** Each provider's credentials: what every one of its lists shares. */\nconst CREDENTIALS: Record<AdAudienceProvider, readonly string[]> = {\n meta: ['META_AUDIENCE_SYNC_ACCESS_TOKEN'],\n google: [\n 'GOOGLE_AUDIENCE_SYNC_CLIENT_ID',\n 'GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET',\n 'GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN',\n 'GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID',\n ],\n linkedin: ['LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'],\n}\n\n/** The all-holders list id on each provider. */\nconst LIST_ID: Record<AdAudienceProvider, string> = {\n meta: 'META_AUDIENCE_SYNC_AUDIENCE_ID',\n google: 'GOOGLE_AUDIENCE_SYNC_USER_LIST_ID',\n linkedin: 'LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID',\n}\n\nconst LIST_ID_SUFFIX: Record<AdAudienceProvider, string> = {\n meta: 'AUDIENCE_ID',\n google: 'USER_LIST_ID',\n linkedin: 'SEGMENT_ID',\n}\n\nconst PROVIDER_PREFIX: Record<AdAudienceProvider, string> = {\n meta: 'META_AUDIENCE_SYNC',\n google: 'GOOGLE_AUDIENCE_SYNC',\n linkedin: 'LINKEDIN_AUDIENCE_SYNC',\n}\n\n/**\n * The variable that holds one stage's list id on one provider, e.g.\n * `META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID`. Every name it\n * builds is read literally in `adAudienceEnv`.\n */\nexport function stageListVariable(provider: AdAudienceProvider, stage: AdAudienceStage): string {\n const name = stage.toUpperCase().replace(/-/g, '_')\n return `${PROVIDER_PREFIX[provider]}_STAGE_${name}_${LIST_ID_SUFFIX[provider]}`\n}\n\nconst digits = (value: string) => value.replace(/\\D/g, '')\n\n/**\n * One list on every provider, given the variable that names its id on each.\n * Shared by the all-holders list and every stage, so the credentials are\n * read, and normalized, in exactly one way.\n */\nfunction readListConfig(\n value: (name: string) => string,\n listVariable: Record<AdAudienceProvider, string>,\n): AdAudienceListConfig {\n const missing = Object.fromEntries(\n AD_AUDIENCE_PROVIDERS.map((provider) => [\n provider,\n [...CREDENTIALS[provider], listVariable[provider]].filter((name) => !value(name)),\n ]),\n ) as Record<AdAudienceProvider, string[]>\n const loginCustomerId = digits(value('GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID'))\n return {\n meta: missing.meta.length\n ? null\n : {\n accessToken: value('META_AUDIENCE_SYNC_ACCESS_TOKEN'),\n // `act_` belongs to the ad account, never to an audience id.\n audienceId: value(listVariable.meta),\n },\n google: missing.google.length\n ? null\n : {\n clientId: value('GOOGLE_AUDIENCE_SYNC_CLIENT_ID'),\n clientSecret: value('GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET'),\n refreshToken: value('GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN'),\n // Google Ads shows `841-500-9958`; the API takes the digits.\n customerId: digits(value('GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID')),\n loginCustomerId: loginCustomerId || null,\n userListId: digits(value(listVariable.google)),\n },\n linkedin: missing.linkedin.length\n ? null\n : {\n accessToken: value('LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN'),\n // The segment URN's id, whichever form was pasted.\n segmentId: value(listVariable.linkedin).replace(/^urn:li:dmpSegment:/, ''),\n },\n missing,\n }\n}\n\n/**\n * Each provider's settings, or null with the names it lacks. A provider is\n * configured only when every required variable is set; a half-configured one\n * is skipped, never half-sent.\n *\n * The Meta audience is never created here. Creating one when the id is unset\n * would mint a fresh, empty audience on every run whose variable was lost, and\n * the ads targeting the real one would go on pointing at it, so the id is\n * required and the audience is made once, by hand. The same holds for every\n * stage list: an unset stage id is a stage that is not sent, never one made.\n *\n * A stage list never depends on the all-holders list's id: it needs only\n * its provider's credentials and its own id.\n */\nexport function readAdAudienceConfig(\n env: Record<string, string | undefined> = adAudienceEnv(),\n): AdAudienceConfig {\n const value = (name: string) => String(env[name] ?? '').trim()\n const stages = Object.fromEntries(\n AD_AUDIENCE_STAGES.map((stage) => [\n stage,\n readListConfig(\n value,\n Object.fromEntries(\n AD_AUDIENCE_PROVIDERS.map((provider) => [provider, stageListVariable(provider, stage)]),\n ) as Record<AdAudienceProvider, string>,\n ),\n ]),\n ) as Record<AdAudienceStage, AdAudienceListConfig>\n return { ...readListConfig(value, LIST_ID), stages }\n}\n\n/*==========================================\n * PROVIDER REQUESTS\n *=========================================*/\n\n/** One HTTP request, built without sending it. */\nexport interface AudienceRequest {\n method: 'POST'\n url: string\n headers: Record<string, string>\n /** A JSON body, or a form body when `headers` says so. */\n body: Record<string, unknown> | string\n}\n\n/**\n * META — the replace session.\n *\n * `POST /{audience}/usersreplace` swaps the audience's whole membership for\n * the batches of one session: `batch_seq` 1 opens it and `last_batch_flag`\n * closes it, so a removal needs no separate call and nothing has to be\n * remembered about who was there before. Each batch carries at most 10,000\n * hashes, and the session must finish inside 90 minutes. A replace does not\n * reset an ad set's learning phase, which an add and a delete would.\n */\nexport const META_GRAPH_VERSION = 'v25.0'\nexport const META_REPLACE_BATCH = 10_000\n\nexport function buildMetaReplaceRequests(\n config: MetaAudienceConfig,\n hashes: readonly string[],\n sessionId: number,\n): AudienceRequest[] {\n const batches = chunk(hashes, META_REPLACE_BATCH)\n return batches.map((batch, index) => ({\n method: 'POST',\n url: `https://graph.facebook.com/${META_GRAPH_VERSION}/${encodeURIComponent(config.audienceId)}/usersreplace`,\n headers: { 'Content-Type': 'application/json' },\n body: {\n payload: { schema: 'EMAIL_SHA256', data: batch },\n session: {\n session_id: sessionId,\n batch_seq: index + 1,\n last_batch_flag: index === batches.length - 1,\n estimated_num_total: hashes.length,\n },\n access_token: config.accessToken,\n },\n }))\n}\n\n/**\n * GOOGLE — the Data Manager API, not the Google Ads API.\n *\n * Since 2026-04-01 the Google Ads API's `OfflineUserDataJobService` refuses\n * Customer Match uploads for a developer token with no Customer Match\n * activity in the six months before, and Google points every such project at\n * the Data Manager API instead. It needs an OAuth token with the\n * `datamanager` scope and no developer token.\n *\n * Adds go to `audienceMembers:ingest` and removals to `audienceMembers:remove`,\n * 10,000 members a request. The Data Manager API has no replace, so the\n * removals come from the set this sync last sent.\n *\n * No `consent` is sent. The audience is United States account holders only,\n * for whom Google requires no consent signal, and stating `CONSENT_GRANTED`\n * would assert a consent this platform does not collect.\n * `customerMatchTermsOfServiceStatus: ACCEPTED` is the operator's own\n * acceptance of the Customer Match terms, which Google requires on an\n * ingest; they are accepted in the Google Ads account before this is\n * configured.\n */\nexport const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token'\nexport const GOOGLE_DATA_MANAGER_BASE = 'https://datamanager.googleapis.com/v1'\nexport const GOOGLE_MEMBERS_BATCH = 10_000\n\nexport function buildGoogleTokenRequest(config: GoogleAudienceConfig): AudienceRequest {\n return {\n method: 'POST',\n url: GOOGLE_TOKEN_URL,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n refresh_token: config.refreshToken,\n }).toString(),\n }\n}\n\nexport function buildGoogleMemberRequests(\n config: GoogleAudienceConfig,\n accessToken: string,\n action: 'ingest' | 'remove',\n hashes: readonly string[],\n): AudienceRequest[] {\n const destination = {\n operatingAccount: { accountType: 'GOOGLE_ADS', accountId: config.customerId },\n ...(config.loginCustomerId\n ? { loginAccount: { accountType: 'GOOGLE_ADS', accountId: config.loginCustomerId } }\n : {}),\n productDestinationId: config.userListId,\n }\n return chunk(hashes, GOOGLE_MEMBERS_BATCH).map((batch) => ({\n method: 'POST',\n url: `${GOOGLE_DATA_MANAGER_BASE}/audienceMembers:${action}`,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: {\n destinations: [destination],\n audienceMembers: batch.map((hash) => ({\n userData: { userIdentifiers: [{ emailAddress: hash }] },\n })),\n encoding: 'HEX',\n ...(action === 'ingest'\n ? { termsOfService: { customerMatchTermsOfServiceStatus: 'ACCEPTED' } }\n : {}),\n },\n }))\n}\n\n/**\n * LINKEDIN — DMP segment users, streamed.\n *\n * `POST /rest/dmpSegments/{id}/users` with `X-RestLi-Method: BATCH_CREATE`\n * takes up to 5,000 `ADD` or `REMOVE` elements a request. There is no\n * replace, so the removals come from the set this sync last sent. Adding an\n * id twice or removing one already gone both answer 201, so a retry is safe.\n * The API is open only to developers LinkedIn has approved for Matched\n * Audiences, with the `rw_dmp_segments` permission.\n */\nexport const LINKEDIN_VERSION = '202609'\nexport const LINKEDIN_USERS_BATCH = 5_000\n\nexport function buildLinkedInUserRequests(\n config: LinkedInAudienceConfig,\n action: 'ADD' | 'REMOVE',\n hashes: readonly string[],\n): AudienceRequest[] {\n return chunk(hashes, LINKEDIN_USERS_BATCH).map((batch) => ({\n method: 'POST',\n url: `https://api.linkedin.com/rest/dmpSegments/${encodeURIComponent(config.segmentId)}/users`,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.accessToken}`,\n 'LinkedIn-Version': LINKEDIN_VERSION,\n 'X-Restli-Protocol-Version': '2.0.0',\n 'X-RestLi-Method': 'BATCH_CREATE',\n },\n body: {\n elements: batch.map((hash) => ({\n action,\n userIds: [{ idType: 'SHA256_EMAIL', idValue: hash }],\n })),\n },\n }))\n}\n\n/** How many elements of a LinkedIn batch response were refused. */\nexport function linkedInRefusedCount(answer: unknown): number {\n const elements = (answer as { elements?: unknown } | null)?.elements\n if (!Array.isArray(elements)) return 0\n return elements.filter((element) => {\n const status = Number((element as { status?: unknown } | null)?.status)\n return !(status >= 200 && status < 300)\n }).length\n}\n"],"names":["createHash","AD_AUDIENCE_PROVIDERS","AD_AUDIENCE_PROVIDER_LABELS","meta","google","linkedin","GOOGLE_CONSUMER_DOMAINS","Set","normalizeAudienceEmail","provider","raw","email","trim","toLowerCase","replace","at","lastIndexOf","length","indexOf","local","slice","domain","has","plus","sha256Hex","value","update","digest","hashAudienceEmail","normalized","AD_AUDIENCE_EXCLUSIONS","AD_AUDIENCE_COUNTRY","ALPHA2","resolveAccountCountry","account","billing","billingCountries","map","country","String","toUpperCase","filter","test","foreign","find","source","signup","signupCountry","emailDomain","address","adAudienceExclusion","options","disabled","staff","internalDomains","some","internal","locked","banned","optedOut","emailVerified","AD_AUDIENCE_STAGES","AD_AUDIENCE_STAGE_LABELS","paid","lapsed","AD_AUDIENCE_LAPSE_DAYS","AD_AUDIENCE_LAPSE_MS","NOT_A_PERSON_ACTING","isRealActivityAction","action","Boolean","instantMs","record","undefined","Number","isFinite","Date","isNaN","getTime","parsed","parse","toMillis","ms","call","seconds","_seconds","isOwnPublishedScreen","screen","now","deletedAt","published","publishedAt","createdBy","created","createdAt","updated","updatedAt","isLapsedAccount","facts","createdAtMs","lastActivityAtMs","adAudienceStages","stageFacts","stages","ownsPaidWorkspace","ownsPublishedSite","push","diffAudience","previous","next","before","after","toAdd","hash","sort","toRemove","isSuspiciousShrink","previousSize","nextSize","chunk","items","size","runs","index","adAudienceEnv","META_AUDIENCE_SYNC_ACCESS_TOKEN","process","env","META_AUDIENCE_SYNC_AUDIENCE_ID","GOOGLE_AUDIENCE_SYNC_CLIENT_ID","GOOGLE_AUDIENCE_SYNC_CLIENT_SECRET","GOOGLE_AUDIENCE_SYNC_REFRESH_TOKEN","GOOGLE_AUDIENCE_SYNC_CUSTOMER_ID","GOOGLE_AUDIENCE_SYNC_LOGIN_CUSTOMER_ID","GOOGLE_AUDIENCE_SYNC_USER_LIST_ID","LINKEDIN_AUDIENCE_SYNC_ACCESS_TOKEN","LINKEDIN_AUDIENCE_SYNC_SEGMENT_ID","META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID","META_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_AUDIENCE_ID","META_AUDIENCE_SYNC_STAGE_PAID_AUDIENCE_ID","META_AUDIENCE_SYNC_STAGE_LAPSED_AUDIENCE_ID","GOOGLE_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_USER_LIST_ID","GOOGLE_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_USER_LIST_ID","GOOGLE_AUDIENCE_SYNC_STAGE_PAID_USER_LIST_ID","GOOGLE_AUDIENCE_SYNC_STAGE_LAPSED_USER_LIST_ID","LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_SEGMENT_ID","LINKEDIN_AUDIENCE_SYNC_STAGE_FREE_PUBLISHED_SEGMENT_ID","LINKEDIN_AUDIENCE_SYNC_STAGE_PAID_SEGMENT_ID","LINKEDIN_AUDIENCE_SYNC_STAGE_LAPSED_SEGMENT_ID","CREDENTIALS","LIST_ID","LIST_ID_SUFFIX","PROVIDER_PREFIX","stageListVariable","stage","name","digits","readListConfig","listVariable","missing","Object","fromEntries","loginCustomerId","accessToken","audienceId","clientId","clientSecret","refreshToken","customerId","userListId","segmentId","readAdAudienceConfig","META_GRAPH_VERSION","META_REPLACE_BATCH","buildMetaReplaceRequests","config","hashes","sessionId","batches","batch","method","url","encodeURIComponent","headers","body","payload","schema","data","session","session_id","batch_seq","last_batch_flag","estimated_num_total","access_token","GOOGLE_TOKEN_URL","GOOGLE_DATA_MANAGER_BASE","GOOGLE_MEMBERS_BATCH","buildGoogleTokenRequest","URLSearchParams","grant_type","client_id","client_secret","refresh_token","toString","buildGoogleMemberRequests","destination","operatingAccount","accountType","accountId","loginAccount","productDestinationId","Authorization","destinations","audienceMembers","userData","userIdentifiers","emailAddress","encoding","termsOfService","customerMatchTermsOfServiceStatus","LINKEDIN_VERSION","LINKEDIN_USERS_BATCH","buildLinkedInUserRequests","elements","userIds","idType","idValue","linkedInRefusedCount","answer","Array","isArray","element","status"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AAExC;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,OAAO,MAAMC,wBAAwB;IAAC;IAAQ;IAAU;CAAW,CAAS;AAG5E,OAAO,MAAMC,8BAAkE;IAC7EC,MAAM;IACNC,QAAQ;IACRC,UAAU;AACZ,EAAC;AAED;;2CAE2C,GAE3C,MAAMC,0BAA0B,IAAIC,IAAI;IAAC;IAAa;CAAiB;AAEvE;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,uBACdC,QAA4B,EAC5BC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,UAAU,OAAO;IACpC,IAAIC,QACFF,aAAa,SAASC,IAAIE,IAAI,GAAGC,WAAW,KAAKH,IAAII,OAAO,CAAC,QAAQ,IAAID,WAAW;IACtF,MAAME,KAAKJ,MAAMK,WAAW,CAAC;IAC7B,IAAID,MAAM,KAAKA,OAAOJ,MAAMM,MAA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