@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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/ad-audience-sync-run.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 { AD_AUDIENCE_OPT_OUT_FIELD, readAdAudienceOptOut } from '@aglyn/aglyn/app-utils/ad-audience'\nimport { ACCOUNT_ACQUISITION_FIELD } from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n isAccountBanLockdownReason,\n LOCKDOWNS_COLLECTION,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport {\n AD_AUDIENCE_EXCLUSIONS,\n AD_AUDIENCE_PROVIDERS,\n adAudienceExclusion,\n buildGoogleMemberRequests,\n buildGoogleTokenRequest,\n buildLinkedInUserRequests,\n buildMetaReplaceRequests,\n diffAudience,\n hashAudienceEmail,\n isSuspiciousShrink,\n linkedInRefusedCount,\n resolveAccountCountry,\n type AdAudienceAccount,\n type AdAudienceConfig,\n type AdAudienceExclusion,\n type AdAudienceProvider,\n type AudienceRequest,\n} from './ad-audience-sync'\n\n/**\n * THE ACCOUNT-HOLDER AD AUDIENCE (AGL-3780) — reading, sending, recording.\n *\n * One run: every account from Auth (every pool), joined with the Firestore\n * facts eligibility needs, reduced to one hash set per provider, diffed\n * against what that provider was last sent, and — unless it is a dry run —\n * sent. Each provider is independent: an unconfigured one is skipped with a\n * line saying which variables it lacks, and a failing one fails alone.\n *\n * WHAT IS KEPT. `adAudienceSync/{provider}` holds the counts and times of the\n * last run, and `adAudienceSync/{provider}/members/{n}` the hashes it last\n * sent, in chunks. The hashes are kept because two of the three providers\n * have no replace: an account that is erased leaves no address behind, so\n * the only way to take it out of a Google list or a LinkedIn segment is the\n * hash this sync sent it under. Admin-SDK only; no client rule opens either.\n * No address is stored, and neither addresses nor hashes are ever logged.\n */\n\nexport const AD_AUDIENCE_SYNC_COLLECTION = 'adAudienceSync'\nexport const AD_AUDIENCE_MEMBERS_SUBCOLLECTION = 'members'\n/** Hashes per member chunk: 5,000 × 64 bytes stays far under a document's 1 MiB. */\nconst MEMBER_CHUNK = 5_000\n/** Auth pages walked per run (1,000 accounts each). */\nconst MAX_AUTH_PAGES = 500\n\n/** The Auth page reader, as `listUsersAcrossPools` answers it. */\nexport type ListUsersPage = (\n pageSize: number,\n pageToken?: string,\n) => Promise<{\n users: Array<{\n record: {\n uid: string\n email?: string\n emailVerified: boolean\n disabled: boolean\n customClaims?: Record<string, unknown>\n }\n }>\n nextPageToken: string | null | undefined\n}>\n\nexport interface AdAudienceReadDeps {\n firestore: FirebaseFirestore.Firestore\n listUserPage: ListUsersPage\n /** The account-ban list's answer for these addresses, lowercased. */\n bannedEmails: (emails: readonly string[]) => Promise<Set<string>>\n now: number\n}\n\n/** A number for each reason; never a person. */\nexport type ExclusionCounts = Record<AdAudienceExclusion, number>\n\nexport interface AdAudienceSelection {\n scanned: number\n eligible: AdAudienceAccount[]\n excluded: ExclusionCounts\n /** How the eligible accounts' country was decided. */\n countrySource: { billing: number; signup: number }\n}\n\n/** Every account, with the facts eligibility reads. */\nexport async function readAdAudienceAccounts(\n deps: AdAudienceReadDeps,\n): Promise<{ accounts: AdAudienceAccount[] }> {\n const db = deps.firestore\n\n // Profiles: the opt-out and the sign-up country, in one query.\n const profiles = await db\n .collection('users')\n .select(AD_AUDIENCE_OPT_OUT_FIELD, `${ACCOUNT_ACQUISITION_FIELD}.geo.country`)\n .get()\n const optedOut = new Set<string>()\n const signupCountry = new Map<string, string>()\n for (const doc of profiles.docs) {\n const data = (doc.data() ?? {}) as Record<string, unknown>\n if (readAdAudienceOptOut(data)) optedOut.add(doc.id)\n const geo = (data[ACCOUNT_ACQUISITION_FIELD] as { geo?: { country?: unknown } } | undefined)?.geo\n if (typeof geo?.country === 'string') signupCountry.set(doc.id, geo.country)\n }\n\n // Billing countries of the workspaces each account owns.\n const orgs = await db.collection('orgs').select('ownerUid', 'contact.address.country').get()\n const billing = new Map<string, string[]>()\n for (const doc of orgs.docs) {\n const owner = doc.get('ownerUid')\n const country = doc.get('contact.address.country')\n if (typeof owner !== 'string' || !owner || typeof country !== 'string' || !country) continue\n billing.set(owner, [...(billing.get(owner) ?? []), country])\n }\n\n // Account locks: `lockdowns/user--{uid}`, by document id range.\n const locks = await db\n .collection(LOCKDOWNS_COLLECTION)\n .where(FieldPath.documentId(), '>=', 'user--')\n .where(FieldPath.documentId(), '<', 'user-.')\n .get()\n const locked = new Set<string>()\n for (const doc of locks.docs) {\n const uid = doc.id.slice('user--'.length)\n const untilMs = doc.get('untilMs')\n // An `abuse` lock is a permanent ban whatever its expiry says.\n const live =\n isAccountBanLockdownReason(doc.get('reason')) ||\n !(typeof untilMs === 'number' && untilMs <= deps.now)\n if (uid && live) locked.add(uid)\n }\n\n const accounts: AdAudienceAccount[] = []\n let pageToken: string | undefined\n for (let page = 0; page < MAX_AUTH_PAGES; page += 1) {\n const listed = await deps.listUserPage(1000, pageToken)\n for (const { record } of listed.users) {\n accounts.push({\n uid: record.uid,\n email: record.email ?? null,\n emailVerified: Boolean(record.emailVerified),\n disabled: Boolean(record.disabled),\n staff: Boolean(record.customClaims?.['staff']),\n optedOut: optedOut.has(record.uid),\n locked: locked.has(record.uid),\n banned: false,\n billingCountries: billing.get(record.uid) ?? [],\n signupCountry: signupCountry.get(record.uid) ?? null,\n })\n }\n pageToken = listed.nextPageToken ?? undefined\n if (!pageToken) break\n }\n if (pageToken) {\n // A partial read would look like mass churn and remove real members.\n throw new Error(`more than ${MAX_AUTH_PAGES * 1000} accounts; raise MAX_AUTH_PAGES`)\n }\n\n const banned = await deps.bannedEmails(\n accounts.map((account) => account.email).filter((email): email is string => Boolean(email)),\n )\n for (const account of accounts) {\n if (account.email && banned.has(account.email.trim().toLowerCase())) account.banned = true\n }\n return { accounts }\n}\n\n/** The eligible accounts and the counts of everyone left out. */\nexport function selectAdAudience(\n accounts: readonly AdAudienceAccount[],\n internalDomains: readonly string[],\n): AdAudienceSelection {\n const excluded = Object.fromEntries(\n AD_AUDIENCE_EXCLUSIONS.map((reason) => [reason, 0]),\n ) as ExclusionCounts\n const eligible: AdAudienceAccount[] = []\n const countrySource = { billing: 0, signup: 0 }\n for (const account of accounts) {\n const reason = adAudienceExclusion(account, { internalDomains })\n if (reason) {\n excluded[reason] += 1\n continue\n }\n eligible.push(account)\n const { source } = resolveAccountCountry(account)\n if (source) countrySource[source] += 1\n }\n return { scanned: accounts.length, eligible, excluded, countrySource }\n}\n\n/** The set one provider should hold. Two addresses may share a hash. */\nexport function providerHashes(\n provider: AdAudienceProvider,\n eligible: readonly AdAudienceAccount[],\n): string[] {\n const hashes = new Set<string>()\n for (const account of eligible) {\n const hash = hashAudienceEmail(provider, account.email)\n if (hash) hashes.add(hash)\n }\n return [...hashes].sort()\n}\n\n/*==========================================\n * STATE\n *=========================================*/\n\n/** What one provider was last sent. */\nexport async function readSentHashes(\n firestore: FirebaseFirestore.Firestore,\n provider: AdAudienceProvider,\n): Promise<string[]> {\n const chunks = await firestore\n .collection(AD_AUDIENCE_SYNC_COLLECTION)\n .doc(provider)\n .collection(AD_AUDIENCE_MEMBERS_SUBCOLLECTION)\n .get()\n const hashes: string[] = []\n for (const doc of chunks.docs) {\n const held = doc.get('hashes')\n if (Array.isArray(held)) hashes.push(...held.filter((hash): hash is string => typeof hash === 'string'))\n }\n return hashes\n}\n\n/** Replace what one provider was last sent, and its counts. */\nasync function writeSentState(\n firestore: FirebaseFirestore.Firestore,\n provider: AdAudienceProvider,\n hashes: readonly string[],\n state: Record<string, unknown>,\n): Promise<void> {\n const ref = firestore.collection(AD_AUDIENCE_SYNC_COLLECTION).doc(provider)\n const members = ref.collection(AD_AUDIENCE_MEMBERS_SUBCOLLECTION)\n const existing = await members.get()\n const runs: string[][] = []\n for (let index = 0; index < hashes.length; index += MEMBER_CHUNK) {\n runs.push(hashes.slice(index, index + MEMBER_CHUNK))\n }\n for (const [index, run] of runs.entries()) {\n await members.doc(String(index).padStart(4, '0')).set({ hashes: run })\n }\n const keep = new Set(runs.map((_, index) => String(index).padStart(4, '0')))\n for (const doc of existing.docs) {\n if (!keep.has(doc.id)) await doc.ref.delete()\n }\n await ref.set({ provider, ...state, members: hashes.length, chunks: runs.length }, { merge: true })\n}\n\n/** The counts of a run on the provider's state document, members untouched. */\nasync function writeRunState(\n firestore: FirebaseFirestore.Firestore,\n provider: AdAudienceProvider,\n state: Record<string, unknown>,\n): Promise<void> {\n await firestore\n .collection(AD_AUDIENCE_SYNC_COLLECTION)\n .doc(provider)\n .set({ provider, ...state }, { merge: true })\n}\n\n/*==========================================\n * SENDING\n *=========================================*/\n\nexport type AudienceFetch = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; json: () => Promise<unknown> }>\n\n/** Thrown with the provider's status only; a response body may echo a token. */\nexport class AudienceSendError extends Error {\n constructor(\n readonly provider: AdAudienceProvider,\n readonly status: number,\n detail: string,\n ) {\n super(`${provider} answered ${status}: ${detail}`)\n }\n}\n\n/** The provider's error message, when it gave one, clipped. Never the request. */\nfunction errorDetail(answer: unknown): string {\n const error = (answer as { error?: unknown; message?: unknown } | null) ?? null\n const message =\n (typeof error?.error === 'object' && error?.error\n ? (error.error as { message?: unknown }).message\n : error?.error) ?? error?.message\n return typeof message === 'string' ? message.slice(0, 300) : 'no detail'\n}\n\nasync function send(\n fetcher: AudienceFetch,\n provider: AdAudienceProvider,\n request: AudienceRequest,\n): Promise<unknown> {\n const response = await fetcher(request.url, {\n method: request.method,\n headers: request.headers,\n body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body),\n })\n const answer = await response.json().catch(() => null)\n if (!response.ok) throw new AudienceSendError(provider, response.status, errorDetail(answer))\n return answer\n}\n\nasync function sendMeta(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['meta']>,\n hashes: readonly string[],\n now: number,\n): Promise<void> {\n // A session id unique within the ad account: the run's clock is.\n for (const request of buildMetaReplaceRequests(config, hashes, now)) {\n await send(fetcher, 'meta', request)\n }\n}\n\nasync function sendGoogle(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['google']>,\n diff: { toAdd: string[]; toRemove: string[] },\n): Promise<void> {\n const token = (await send(fetcher, 'google', buildGoogleTokenRequest(config))) as {\n access_token?: unknown\n } | null\n if (typeof token?.access_token !== 'string') {\n throw new AudienceSendError('google', 200, 'the token endpoint returned no access token')\n }\n for (const request of buildGoogleMemberRequests(config, token.access_token, 'remove', diff.toRemove)) {\n await send(fetcher, 'google', request)\n }\n for (const request of buildGoogleMemberRequests(config, token.access_token, 'ingest', diff.toAdd)) {\n await send(fetcher, 'google', request)\n }\n}\n\nasync function sendLinkedIn(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['linkedin']>,\n diff: { toAdd: string[]; toRemove: string[] },\n): Promise<void> {\n const requests = [\n ...buildLinkedInUserRequests(config, 'REMOVE', diff.toRemove),\n ...buildLinkedInUserRequests(config, 'ADD', diff.toAdd),\n ]\n for (const request of requests) {\n const refused = linkedInRefusedCount(await send(fetcher, 'linkedin', request))\n if (refused) {\n throw new AudienceSendError('linkedin', 400, `${refused} of the batch were refused`)\n }\n }\n}\n\n/*==========================================\n * ONE RUN\n *=========================================*/\n\nexport type ProviderOutcome =\n | 'unconfigured'\n | 'dry-run'\n | 'flag-off'\n | 'unchanged'\n | 'empty'\n | 'held-shrink'\n | 'sent'\n | 'failed'\n\nexport interface ProviderReport {\n outcome: ProviderOutcome\n eligible: number\n previous: number\n toAdd: number\n toRemove: number\n /** For `unconfigured`: the variables it lacks. */\n missing?: string[]\n /** For `failed`: the provider's status and message, never a payload. */\n error?: string\n}\n\nexport interface AdAudienceSyncReport {\n dryRun: boolean\n flagOn: boolean\n scanned: number\n eligible: number\n excluded: ExclusionCounts\n countrySource: { billing: number; signup: number }\n providers: Record<AdAudienceProvider, ProviderReport>\n}\n\nexport interface AdAudienceRunOptions {\n /** Report what would change and send nothing. */\n dryRun: boolean\n /** `release_ad_audience_sync`. Off, a run that is not a dry run sends nothing. */\n flagOn: boolean\n /** Send a set that shrank by more than half anyway. */\n force?: boolean\n config: AdAudienceConfig\n internalDomains: readonly string[]\n accounts: readonly AdAudienceAccount[]\n firestore: FirebaseFirestore.Firestore\n fetch: AudienceFetch\n now: number\n /** One line per provider, for the function log. Counts only. */\n log?: (line: string) => void\n}\n\nexport async function runAdAudienceSync(options: AdAudienceRunOptions): Promise<AdAudienceSyncReport> {\n const log = options.log ?? ((line: string) => console.info(line))\n const selection = selectAdAudience(options.accounts, options.internalDomains)\n const providers = {} as Record<AdAudienceProvider, ProviderReport>\n\n for (const provider of AD_AUDIENCE_PROVIDERS) {\n const hashes = providerHashes(provider, selection.eligible)\n const config = options.config[provider]\n const base = { eligible: hashes.length, previous: 0, toAdd: 0, toRemove: 0 }\n if (!config) {\n providers[provider] = { ...base, outcome: 'unconfigured', missing: options.config.missing[provider] }\n log(`[ad-audience-sync] ${provider} skipped — set ${options.config.missing[provider].join(', ')}`)\n continue\n }\n const previous = await readSentHashes(options.firestore, provider)\n const diff = diffAudience(previous, hashes)\n const counts = {\n ...base,\n previous: previous.length,\n toAdd: diff.toAdd.length,\n toRemove: diff.toRemove.length,\n }\n const outcome = (value: ProviderOutcome, extra: Partial<ProviderReport> = {}) => {\n providers[provider] = { ...counts, outcome: value, ...extra }\n log(\n `[ad-audience-sync] ${provider} ${value}: eligible ${counts.eligible}, ` +\n `previous ${counts.previous}, add ${counts.toAdd}, remove ${counts.toRemove}` +\n (extra.error ? ` — ${extra.error}` : ''),\n )\n }\n if (options.dryRun) {\n outcome('dry-run')\n continue\n }\n if (!options.flagOn) {\n outcome('flag-off')\n continue\n }\n const stamp = { lastRunAtMs: options.now, eligible: counts.eligible }\n if (!diff.toAdd.length && !diff.toRemove.length) {\n await writeRunState(options.firestore, provider, { ...stamp, lastOutcome: 'unchanged' })\n outcome('unchanged')\n continue\n }\n // Meta replaces with what it is sent, and an empty replace is no replace.\n if (!hashes.length) {\n await writeRunState(options.firestore, provider, { ...stamp, lastOutcome: 'empty' })\n outcome('empty', { error: 'no eligible account; the audience was left as it is' })\n continue\n }\n if (!options.force && isSuspiciousShrink(previous.length, hashes.length)) {\n await writeRunState(options.firestore, provider, { ...stamp, lastOutcome: 'held-shrink' })\n outcome('held-shrink', {\n error: `the audience would shrink from ${previous.length} to ${hashes.length}; held until a run with force`,\n })\n continue\n }\n try {\n if (provider === 'meta') {\n await sendMeta(options.fetch, config as NonNullable<AdAudienceConfig['meta']>, hashes, options.now)\n } else if (provider === 'google') {\n await sendGoogle(options.fetch, config as NonNullable<AdAudienceConfig['google']>, diff)\n } else {\n await sendLinkedIn(options.fetch, config as NonNullable<AdAudienceConfig['linkedin']>, diff)\n }\n } catch (error) {\n // The stored set stays as it was: the next run retries the whole diff,\n // and every provider takes a repeated add or remove without harm.\n const message = error instanceof AudienceSendError ? error.message : `${provider} send failed`\n if (!(error instanceof AudienceSendError)) console.error(`[ad-audience-sync] ${provider}`, error)\n await writeRunState(options.firestore, provider, {\n ...stamp,\n lastOutcome: 'failed',\n lastError: message,\n })\n outcome('failed', { error: message })\n continue\n }\n await writeSentState(options.firestore, provider, hashes, {\n ...stamp,\n lastOutcome: 'sent',\n lastSentAtMs: options.now,\n lastAdded: counts.toAdd,\n lastRemoved: counts.toRemove,\n lastError: null,\n })\n outcome('sent')\n }\n\n return {\n dryRun: options.dryRun,\n flagOn: options.flagOn,\n scanned: selection.scanned,\n eligible: selection.eligible.length,\n excluded: selection.excluded,\n countrySource: selection.countrySource,\n providers,\n }\n}\n"],"names":["AD_AUDIENCE_OPT_OUT_FIELD","readAdAudienceOptOut","ACCOUNT_ACQUISITION_FIELD","isAccountBanLockdownReason","LOCKDOWNS_COLLECTION","FieldPath","AD_AUDIENCE_EXCLUSIONS","AD_AUDIENCE_PROVIDERS","adAudienceExclusion","buildGoogleMemberRequests","buildGoogleTokenRequest","buildLinkedInUserRequests","buildMetaReplaceRequests","diffAudience","hashAudienceEmail","isSuspiciousShrink","linkedInRefusedCount","resolveAccountCountry","AD_AUDIENCE_SYNC_COLLECTION","AD_AUDIENCE_MEMBERS_SUBCOLLECTION","MEMBER_CHUNK","MAX_AUTH_PAGES","readAdAudienceAccounts","deps","db","firestore","profiles","collection","select","get","optedOut","Set","signupCountry","Map","doc","docs","data","add","id","geo","country","set","orgs","billing","owner","locks","where","documentId","locked","uid","slice","length","untilMs","live","now","accounts","pageToken","page","listed","listUserPage","record","users","push","email","emailVerified","Boolean","disabled","staff","customClaims","has","banned","billingCountries","nextPageToken","undefined","Error","bannedEmails","map","account","filter","trim","toLowerCase","selectAdAudience","internalDomains","excluded","Object","fromEntries","reason","eligible","countrySource","signup","source","scanned","providerHashes","provider","hashes","hash","sort","readSentHashes","chunks","held","Array","isArray","writeSentState","state","ref","members","existing","runs","index","run","entries","String","padStart","keep","_","delete","merge","writeRunState","AudienceSendError","status","detail","errorDetail","answer","error","message","send","fetcher","request","response","url","method","headers","body","JSON","stringify","json","catch","ok","sendMeta","config","sendGoogle","diff","token","access_token","toRemove","toAdd","sendLinkedIn","requests","refused","runAdAudienceSync","options","log","line","console","info","selection","providers","base","previous","outcome","missing","join","counts","value","extra","dryRun","flagOn","stamp","lastRunAtMs","lastOutcome","force","fetch","lastError","lastSentAtMs","lastAdded","lastRemoved"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,EAAEC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AEbmC,QAAQ,UAAU;gBAAEpC,OAAOC;YAAQ;YACnC;QACF;QACA,MAAMtB,eAAegD,QAAQ7H,SAAS,EAAEoE,UAAUC,QAAQ,aACrDyE;YACHE,aAAa;YACbI,cAAcvB,QAAQhG,GAAG;YACzBwH,WAAWZ,OAAOjB,KAAK;YACvB8B,aAAab,OAAOlB,QAAQ;YAC5B4B,WAAW;;QAEbb,QAAQ;IACV;IAEA,OAAO;QACLM,QAAQf,QAAQe,MAAM;QACtBC,QAAQhB,QAAQgB,MAAM;QACtB3E,SAASgE,UAAUhE,OAAO;QAC1BJ,UAAUoE,UAAUpE,QAAQ,CAACpC,MAAM;QACnCgC,UAAUwE,UAAUxE,QAAQ;QAC5BK,eAAemE,UAAUnE,aAAa;QACtCoE;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/ad-audience-sync-run.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 { AD_AUDIENCE_OPT_OUT_FIELD, readAdAudienceOptOut } from '@aglyn/aglyn/app-utils/ad-audience'\nimport { ACCOUNT_ACQUISITION_FIELD } from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n isAccountBanLockdownReason,\n LOCKDOWNS_COLLECTION,\n} from '@aglyn/aglyn/app-utils/lockdown'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { FieldPath, Timestamp } from 'firebase-admin/firestore'\nimport {\n AD_AUDIENCE_EXCLUSIONS,\n AD_AUDIENCE_LAPSE_MS,\n AD_AUDIENCE_PROVIDERS,\n AD_AUDIENCE_STAGES,\n adAudienceExclusion,\n adAudienceStages,\n buildGoogleMemberRequests,\n buildGoogleTokenRequest,\n buildLinkedInUserRequests,\n buildMetaReplaceRequests,\n diffAudience,\n hashAudienceEmail,\n instantMs,\n isOwnPublishedScreen,\n isRealActivityAction,\n isSuspiciousShrink,\n linkedInRefusedCount,\n resolveAccountCountry,\n type AdAudienceAccount,\n type AdAudienceConfig,\n type AdAudienceExclusion,\n type AdAudienceListConfig,\n type AdAudienceProvider,\n type AdAudienceStage,\n type AudienceRequest,\n} from './ad-audience-sync'\n\n/**\n * THE ACCOUNT-HOLDER AD AUDIENCE (AGL-3780) — reading, sending, recording.\n *\n * One run: every account from Auth (every pool), joined with the Firestore\n * facts eligibility needs, reduced to one hash set per provider, diffed\n * against what that provider was last sent, and — unless it is a dry run —\n * sent. Each provider is independent: an unconfigured one is skipped with a\n * line saying which variables it lacks, and a failing one fails alone.\n *\n * WHAT IS KEPT. `adAudienceSync/{provider}` holds the counts and times of the\n * last run, and `adAudienceSync/{provider}/members/{n}` the hashes it last\n * sent, in chunks. The hashes are kept because two of the three providers\n * have no replace: an account that is erased leaves no address behind, so\n * the only way to take it out of a Google list or a LinkedIn segment is the\n * hash this sync sent it under. Admin-SDK only; no client rule opens either.\n * No address is stored, and neither addresses nor hashes are ever logged.\n *\n * A STAGE list (AGL-4072) keeps the same two things under its own document,\n * `adAudienceSync/{provider}--{stage}`, so each stage has its own ledger, its\n * own diff and its own shrink guard, and nothing one list does can touch what\n * another was sent.\n */\n\nexport const AD_AUDIENCE_SYNC_COLLECTION = 'adAudienceSync'\nexport const AD_AUDIENCE_MEMBERS_SUBCOLLECTION = 'members'\n/** Hashes per member chunk: 5,000 × 64 bytes stays far under a document's 1 MiB. */\nconst MEMBER_CHUNK = 5_000\n/** Auth pages walked per run (1,000 accounts each). */\nconst MAX_AUTH_PAGES = 500\n/** Page documents read per page of the published-page scan. */\nconst SCREEN_PAGE = 5_000\n/** Change-log entries read per page while looking for one the person made. */\nconst ACTIVITY_PAGE = 25\n/** Pages of change log read per account before it is called quiet. */\nconst ACTIVITY_PAGES = 4\n/** Accounts whose recent activity is read at once. */\nconst ACTIVITY_CONCURRENCY = 20\n\n/** The ledger document of one list: the provider's own, or `{provider}--{stage}`. */\nexport function adAudienceLedgerId(provider: AdAudienceProvider, stage?: AdAudienceStage | null): string {\n return stage ? `${provider}--${stage}` : provider\n}\n\n/** The Auth page reader, as `listUsersAcrossPools` answers it. */\nexport type ListUsersPage = (\n pageSize: number,\n pageToken?: string,\n) => Promise<{\n users: Array<{\n record: {\n uid: string\n email?: string\n emailVerified: boolean\n disabled: boolean\n customClaims?: Record<string, unknown>\n /**\n * Only `creationTime` is read. `lastSignInTime` and `lastRefreshTime`\n * are never activity: a silent re-sign-in moves both with nobody there.\n */\n metadata?: { creationTime?: string }\n }\n }>\n nextPageToken: string | null | undefined\n}>\n\nexport interface AdAudienceReadDeps {\n firestore: FirebaseFirestore.Firestore\n listUserPage: ListUsersPage\n /** The account-ban list's answer for these addresses, lowercased. */\n bannedEmails: (emails: readonly string[]) => Promise<Set<string>>\n now: number\n /**\n * The operator's own domains. Only narrows whose recent activity is read:\n * an internal account is in no list, so its change log is not looked at.\n */\n internalDomains?: readonly string[]\n /**\n * The newest real activity of one account since `sinceMs`, or null. The\n * Firestore reader `readRecentActivityAtMs` unless a spec passes its own.\n */\n recentActivity?: (uid: string, sinceMs: number) => Promise<number | null>\n}\n\n/** A number for each reason; never a person. */\nexport type ExclusionCounts = Record<AdAudienceExclusion, number>\n\nexport interface AdAudienceSelection {\n scanned: number\n eligible: AdAudienceAccount[]\n excluded: ExclusionCounts\n /** How the eligible accounts' country was decided. */\n countrySource: { billing: number; signup: number }\n /** The eligible accounts in each stage (AGL-4072). */\n stages: Record<AdAudienceStage, AdAudienceAccount[]>\n}\n\n/** Every account, with the facts eligibility and the stage lists read. */\nexport async function readAdAudienceAccounts(\n deps: AdAudienceReadDeps,\n): Promise<{ accounts: AdAudienceAccount[] }> {\n const db = deps.firestore\n\n // Profiles: the opt-out and the sign-up country, in one query.\n const profiles = await db\n .collection('users')\n .select(AD_AUDIENCE_OPT_OUT_FIELD, `${ACCOUNT_ACQUISITION_FIELD}.geo.country`)\n .get()\n const optedOut = new Set<string>()\n const signupCountry = new Map<string, string>()\n for (const doc of profiles.docs) {\n const data = (doc.data() ?? {}) as Record<string, unknown>\n if (readAdAudienceOptOut(data)) optedOut.add(doc.id)\n const geo = (data[ACCOUNT_ACQUISITION_FIELD] as { geo?: { country?: unknown } } | undefined)?.geo\n if (typeof geo?.country === 'string') signupCountry.set(doc.id, geo.country)\n }\n\n // The workspaces each account owns, in one query: their billing countries,\n // whether any is on a paid plan, and the sites they hold. The plan is\n // `resolveEffectivePlan`'s, the one every entitlement reads — a canceled\n // subscription is Free, a staff comp is the plan it grants — and it needs\n // only the org document's own fields (the derived `billingStatus` included).\n const orgs = await db\n .collection('orgs')\n .select(\n 'ownerUid',\n 'contact.address.country',\n 'plan',\n 'billingStatus',\n 'subscription.status',\n 'entitlements.planComp',\n 'hosts',\n )\n .get()\n const billing = new Map<string, string[]>()\n const paidOwners = new Set<string>()\n const hostOwner = new Map<string, string>()\n for (const doc of orgs.docs) {\n const owner = doc.get('ownerUid')\n if (typeof owner !== 'string' || !owner) continue\n const country = doc.get('contact.address.country')\n if (typeof country === 'string' && country) {\n billing.set(owner, [...(billing.get(owner) ?? []), country])\n }\n const data = (doc.data() ?? {}) as Record<string, unknown>\n if (resolveEffectivePlan(data as never) !== 'free') paidOwners.add(owner)\n const hosts = data['hosts']\n if (hosts && typeof hosts === 'object') {\n for (const hostId of Object.keys(hosts as Record<string, unknown>)) hostOwner.set(hostId, owner)\n }\n }\n\n // The stage facts never hold up the all-holders list: a read that fails\n // leaves the accounts in no stage tonight, which every stage list's shrink\n // hold (or its refusal to send an empty replace) keeps from reaching a\n // provider, and the main list is synced as ever.\n const publishedOwners = await readOwnPublishedOwners(db, hostOwner, deps.now).catch(\n (error: unknown): null => {\n console.error('[ad-audience-sync] the published-page read failed; no stage tonight', error)\n return null\n },\n )\n\n // Account locks: `lockdowns/user--{uid}`, by document id range.\n const locks = await db\n .collection(LOCKDOWNS_COLLECTION)\n .where(FieldPath.documentId(), '>=', 'user--')\n .where(FieldPath.documentId(), '<', 'user-.')\n .get()\n const locked = new Set<string>()\n for (const doc of locks.docs) {\n const uid = doc.id.slice('user--'.length)\n const untilMs = doc.get('untilMs')\n // An `abuse` lock is a permanent ban whatever its expiry says.\n const live =\n isAccountBanLockdownReason(doc.get('reason')) ||\n !(typeof untilMs === 'number' && untilMs <= deps.now)\n if (uid && live) locked.add(uid)\n }\n\n const accounts: AdAudienceAccount[] = []\n let pageToken: string | undefined\n for (let page = 0; page < MAX_AUTH_PAGES; page += 1) {\n const listed = await deps.listUserPage(1000, pageToken)\n for (const { record } of listed.users) {\n accounts.push({\n uid: record.uid,\n email: record.email ?? null,\n emailVerified: Boolean(record.emailVerified),\n disabled: Boolean(record.disabled),\n staff: Boolean(record.customClaims?.['staff']),\n optedOut: optedOut.has(record.uid),\n locked: locked.has(record.uid),\n banned: false,\n billingCountries: billing.get(record.uid) ?? [],\n signupCountry: signupCountry.get(record.uid) ?? null,\n ...(publishedOwners\n ? {\n stageFacts: {\n createdAtMs: instantMs(record.metadata?.creationTime),\n ownsPaidWorkspace: paidOwners.has(record.uid),\n ownsPublishedSite: publishedOwners.has(record.uid),\n lastActivityAtMs: null,\n },\n }\n : {}),\n })\n }\n pageToken = listed.nextPageToken ?? undefined\n if (!pageToken) break\n }\n if (pageToken) {\n // A partial read would look like mass churn and remove real members.\n throw new Error(`more than ${MAX_AUTH_PAGES * 1000} accounts; raise MAX_AUTH_PAGES`)\n }\n\n const banned = await deps.bannedEmails(\n accounts.map((account) => account.email).filter((email): email is string => Boolean(email)),\n )\n for (const account of accounts) {\n if (account.email && banned.has(account.email.trim().toLowerCase())) account.banned = true\n }\n\n // Recent activity, for the only accounts it can change anything for: those\n // in the audience and old enough to lapse. Everyone else's change log is\n // never read, which keeps the nightly cost to the accounts that matter.\n const since = deps.now - AD_AUDIENCE_LAPSE_MS\n const recentActivity =\n deps.recentActivity ?? ((uid: string, sinceMs: number) => readRecentActivityAtMs(db, uid, sinceMs))\n const internalDomains = deps.internalDomains ?? []\n const candidates = accounts.filter((account) => {\n const created = account.stageFacts?.createdAtMs\n return (\n typeof created === 'number' &&\n created < since &&\n !adAudienceExclusion(account, { internalDomains })\n )\n })\n let activityFailures = 0\n for (let index = 0; index < candidates.length; index += ACTIVITY_CONCURRENCY) {\n await Promise.all(\n candidates.slice(index, index + ACTIVITY_CONCURRENCY).map(async (account) => {\n try {\n const at = await recentActivity(account.uid, since)\n if (account.stageFacts) account.stageFacts.lastActivityAtMs = at\n } catch {\n // Unknown is not quiet: out of every stage tonight, never lapsed by mistake.\n delete account.stageFacts\n activityFailures += 1\n }\n }),\n )\n }\n if (activityFailures) {\n console.error(`[ad-audience-sync] recent activity unread for ${activityFailures} accounts; in no stage tonight`)\n }\n return { accounts }\n}\n\n/**\n * The owners of a site with a page of their own published, from one scan of\n * every page document (`hosts/{hostId}/screens/{id}`), paged by path and\n * reading only the fields the test needs. One query instead of one per site;\n * a page whose site no workspace holds counts for nobody.\n */\nasync function readOwnPublishedOwners(\n db: FirebaseFirestore.Firestore,\n hostOwner: ReadonlyMap<string, string>,\n now: number,\n): Promise<Set<string>> {\n const owners = new Set<string>()\n if (!hostOwner.size) return owners\n const base = db\n .collectionGroup('screens')\n .orderBy(FieldPath.documentId())\n .select('publishedAt', 'deletedAt', 'createdAt', 'updatedAt', 'createdBy')\n .limit(SCREEN_PAGE)\n let after: FirebaseFirestore.QueryDocumentSnapshot | undefined\n for (;;) {\n const page = await (after ? base.startAfter(after) : base).get()\n for (const doc of page.docs) {\n // `hosts/{hostId}/screens/{screenId}`; any other `screens` is not a site's.\n const [root, hostId] = doc.ref.path.split('/')\n const owner = root === 'hosts' ? hostOwner.get(hostId) : undefined\n if (!owner || owners.has(owner)) continue\n if (isOwnPublishedScreen((doc.data() ?? {}) as Record<string, unknown>, now)) owners.add(owner)\n }\n if (page.docs.length < SCREEN_PAGE) break\n after = page.docs[page.docs.length - 1]\n }\n return owners\n}\n\n/**\n * The newest thing one account DID since `sinceMs`, or null when nothing was\n * recorded. Two signals, both read through collection-group indexes that\n * already exist for the staff activity feed and the AI job list:\n *\n * - **Change-log entries** under the account's id, on any site's or\n * workspace's log (`hosts/{id}/activity`, `orgs/{id}/activity`): page\n * edits, publishes, form and CRM actions, settings. Entries the platform\n * writes under the person's id without them acting\n * (`isRealActivityAction`) are skipped.\n * - **AI jobs the account started** (`orgs/{id}/aiJobs` by `createdBy`). The\n * start only: a job's later updates are the platform's.\n *\n * Firebase's sign-in and token-refresh times, and the device \"last seen\"\n * stamps, are never read: a silent re-sign-in moves them with nobody there.\n */\nexport async function readRecentActivityAtMs(\n db: FirebaseFirestore.Firestore,\n uid: string,\n sinceMs: number,\n): Promise<number | null> {\n const since = Timestamp.fromMillis(sinceMs)\n const jobs = db\n .collectionGroup('aiJobs')\n .where('createdBy', '==', uid)\n .where('createdAt', '>=', since)\n .orderBy('createdAt', 'desc')\n .select('createdAt')\n .limit(1)\n .get()\n const log = db\n .collectionGroup('activity')\n .where('actorId', '==', uid)\n .where('createdAt', '>=', since)\n .orderBy('createdAt', 'desc')\n .select('action', 'createdAt')\n .limit(ACTIVITY_PAGE)\n let newest: number | null = null\n let after: FirebaseFirestore.QueryDocumentSnapshot | undefined\n // Newest first, so the first real entry is the newest; a page of nothing\n // but platform entries reads the next one, a few pages at most.\n for (let page = 0; page < ACTIVITY_PAGES && newest === null; page += 1) {\n const entries = await (after ? log.startAfter(after) : log).get()\n const real = entries.docs.find((doc) => isRealActivityAction(doc.get('action')))\n if (real) newest = instantMs(real.get('createdAt')) ?? sinceMs\n if (entries.docs.length < ACTIVITY_PAGE) break\n after = entries.docs[entries.docs.length - 1]\n }\n const job = (await jobs).docs[0]\n const started = job ? (instantMs(job.get('createdAt')) ?? sinceMs) : null\n return newest === null ? started : started === null ? newest : Math.max(newest, started)\n}\n\n/** The eligible accounts, the counts of everyone left out, and each stage. */\nexport function selectAdAudience(\n accounts: readonly AdAudienceAccount[],\n internalDomains: readonly string[],\n now: number = Date.now(),\n): AdAudienceSelection {\n const excluded = Object.fromEntries(\n AD_AUDIENCE_EXCLUSIONS.map((reason) => [reason, 0]),\n ) as ExclusionCounts\n const eligible: AdAudienceAccount[] = []\n const countrySource = { billing: 0, signup: 0 }\n const stages = Object.fromEntries(AD_AUDIENCE_STAGES.map((stage) => [stage, []])) as unknown as Record<\n AdAudienceStage,\n AdAudienceAccount[]\n >\n for (const account of accounts) {\n const reason = adAudienceExclusion(account, { internalDomains })\n if (reason) {\n excluded[reason] += 1\n continue\n }\n eligible.push(account)\n const { source } = resolveAccountCountry(account)\n if (source) countrySource[source] += 1\n for (const stage of adAudienceStages(account, now)) stages[stage].push(account)\n }\n return { scanned: accounts.length, eligible, excluded, countrySource, stages }\n}\n\n/** The set one provider should hold. Two addresses may share a hash. */\nexport function providerHashes(\n provider: AdAudienceProvider,\n eligible: readonly AdAudienceAccount[],\n): string[] {\n const hashes = new Set<string>()\n for (const account of eligible) {\n const hash = hashAudienceEmail(provider, account.email)\n if (hash) hashes.add(hash)\n }\n return [...hashes].sort()\n}\n\n/*==========================================\n * STATE\n *=========================================*/\n\n/**\n * What one list was last sent: the provider's all-holders list, or with\n * `stage` that stage's list, each from its own ledger.\n */\nexport async function readSentHashes(\n firestore: FirebaseFirestore.Firestore,\n provider: AdAudienceProvider,\n stage?: AdAudienceStage | null,\n): Promise<string[]> {\n const chunks = await firestore\n .collection(AD_AUDIENCE_SYNC_COLLECTION)\n .doc(adAudienceLedgerId(provider, stage))\n .collection(AD_AUDIENCE_MEMBERS_SUBCOLLECTION)\n .get()\n const hashes: string[] = []\n for (const doc of chunks.docs) {\n const held = doc.get('hashes')\n if (Array.isArray(held)) hashes.push(...held.filter((hash): hash is string => typeof hash === 'string'))\n }\n return hashes\n}\n\n/** The list a ledger write is for. */\ninterface LedgerList {\n provider: AdAudienceProvider\n stage: AdAudienceStage | null\n}\n\n/** The fields that say which list a state document belongs to. */\nconst ledgerFields = (list: LedgerList) => ({\n provider: list.provider,\n ...(list.stage ? { stage: list.stage } : {}),\n})\n\n/** Replace what one list was last sent, and its counts. */\nasync function writeSentState(\n firestore: FirebaseFirestore.Firestore,\n list: LedgerList,\n hashes: readonly string[],\n state: Record<string, unknown>,\n): Promise<void> {\n const ref = firestore.collection(AD_AUDIENCE_SYNC_COLLECTION).doc(adAudienceLedgerId(list.provider, list.stage))\n const members = ref.collection(AD_AUDIENCE_MEMBERS_SUBCOLLECTION)\n const existing = await members.get()\n const runs: string[][] = []\n for (let index = 0; index < hashes.length; index += MEMBER_CHUNK) {\n runs.push(hashes.slice(index, index + MEMBER_CHUNK))\n }\n for (const [index, run] of runs.entries()) {\n await members.doc(String(index).padStart(4, '0')).set({ hashes: run })\n }\n const keep = new Set(runs.map((_, index) => String(index).padStart(4, '0')))\n for (const doc of existing.docs) {\n if (!keep.has(doc.id)) await doc.ref.delete()\n }\n await ref.set({ ...ledgerFields(list), ...state, members: hashes.length, chunks: runs.length }, { merge: true })\n}\n\n/** The counts of a run on the list's state document, members untouched. */\nasync function writeRunState(\n firestore: FirebaseFirestore.Firestore,\n list: LedgerList,\n state: Record<string, unknown>,\n): Promise<void> {\n await firestore\n .collection(AD_AUDIENCE_SYNC_COLLECTION)\n .doc(adAudienceLedgerId(list.provider, list.stage))\n .set({ ...ledgerFields(list), ...state }, { merge: true })\n}\n\n/*==========================================\n * SENDING\n *=========================================*/\n\nexport type AudienceFetch = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; json: () => Promise<unknown> }>\n\n/** Thrown with the provider's status only; a response body may echo a token. */\nexport class AudienceSendError extends Error {\n constructor(\n readonly provider: AdAudienceProvider,\n readonly status: number,\n detail: string,\n ) {\n super(`${provider} answered ${status}: ${detail}`)\n }\n}\n\n/** The provider's error message, when it gave one, clipped. Never the request. */\nfunction errorDetail(answer: unknown): string {\n const error = (answer as { error?: unknown; message?: unknown } | null) ?? null\n const message =\n (typeof error?.error === 'object' && error?.error\n ? (error.error as { message?: unknown }).message\n : error?.error) ?? error?.message\n return typeof message === 'string' ? message.slice(0, 300) : 'no detail'\n}\n\nasync function send(\n fetcher: AudienceFetch,\n provider: AdAudienceProvider,\n request: AudienceRequest,\n): Promise<unknown> {\n const response = await fetcher(request.url, {\n method: request.method,\n headers: request.headers,\n body: typeof request.body === 'string' ? request.body : JSON.stringify(request.body),\n })\n const answer = await response.json().catch(() => null)\n if (!response.ok) throw new AudienceSendError(provider, response.status, errorDetail(answer))\n return answer\n}\n\nasync function sendMeta(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['meta']>,\n hashes: readonly string[],\n now: number,\n): Promise<void> {\n // A session id unique within the ad account: the run's clock is.\n for (const request of buildMetaReplaceRequests(config, hashes, now)) {\n await send(fetcher, 'meta', request)\n }\n}\n\nasync function sendGoogle(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['google']>,\n diff: { toAdd: string[]; toRemove: string[] },\n): Promise<void> {\n const token = (await send(fetcher, 'google', buildGoogleTokenRequest(config))) as {\n access_token?: unknown\n } | null\n if (typeof token?.access_token !== 'string') {\n throw new AudienceSendError('google', 200, 'the token endpoint returned no access token')\n }\n for (const request of buildGoogleMemberRequests(config, token.access_token, 'remove', diff.toRemove)) {\n await send(fetcher, 'google', request)\n }\n for (const request of buildGoogleMemberRequests(config, token.access_token, 'ingest', diff.toAdd)) {\n await send(fetcher, 'google', request)\n }\n}\n\nasync function sendLinkedIn(\n fetcher: AudienceFetch,\n config: NonNullable<AdAudienceConfig['linkedin']>,\n diff: { toAdd: string[]; toRemove: string[] },\n): Promise<void> {\n const requests = [\n ...buildLinkedInUserRequests(config, 'REMOVE', diff.toRemove),\n ...buildLinkedInUserRequests(config, 'ADD', diff.toAdd),\n ]\n for (const request of requests) {\n const refused = linkedInRefusedCount(await send(fetcher, 'linkedin', request))\n if (refused) {\n throw new AudienceSendError('linkedin', 400, `${refused} of the batch were refused`)\n }\n }\n}\n\n/*==========================================\n * ONE RUN\n *=========================================*/\n\nexport type ProviderOutcome =\n | 'unconfigured'\n | 'dry-run'\n | 'flag-off'\n | 'unchanged'\n | 'empty'\n | 'held-shrink'\n | 'sent'\n | 'failed'\n\nexport interface ProviderReport {\n outcome: ProviderOutcome\n eligible: number\n previous: number\n toAdd: number\n toRemove: number\n /** For `unconfigured`: the variables it lacks. */\n missing?: string[]\n /** For `failed`: the provider's status and message, never a payload. */\n error?: string\n}\n\n/** One stage's list on every provider (AGL-4072). */\nexport interface StageReport {\n /**\n * The eligible accounts in the stage. Counted for every stage on every\n * run, whether or not any of its lists is configured, so the report says\n * when a stage is big enough to be worth a list.\n */\n eligible: number\n providers: Record<AdAudienceProvider, ProviderReport>\n}\n\nexport interface AdAudienceSyncReport {\n dryRun: boolean\n flagOn: boolean\n scanned: number\n eligible: number\n excluded: ExclusionCounts\n countrySource: { billing: number; signup: number }\n providers: Record<AdAudienceProvider, ProviderReport>\n stages: Record<AdAudienceStage, StageReport>\n}\n\nexport interface AdAudienceRunOptions {\n /** Report what would change and send nothing. */\n dryRun: boolean\n /** `release_ad_audience_sync`. Off, a run that is not a dry run sends nothing. */\n flagOn: boolean\n /** Send a set that shrank by more than half anyway. */\n force?: boolean\n config: AdAudienceConfig\n internalDomains: readonly string[]\n accounts: readonly AdAudienceAccount[]\n firestore: FirebaseFirestore.Firestore\n fetch: AudienceFetch\n now: number\n /** One line per provider, for the function log. Counts only. */\n log?: (line: string) => void\n}\n\n/**\n * One list on one provider: read what it was last sent, diff, and — unless\n * this run may not send — send and record. The all-holders list and every\n * stage list go through exactly this, each against its own ledger.\n */\nasync function syncList(\n options: AdAudienceRunOptions,\n log: (line: string) => void,\n list: LedgerList,\n listConfig: AdAudienceListConfig,\n hashes: string[],\n /** Added to the clock for Meta's session id, which must be unique per run and audience. */\n sessionOffset: number,\n): Promise<ProviderReport> {\n const { provider, stage } = list\n const name = stage ? `${provider} ${stage}` : provider\n const config = listConfig[provider]\n const base = { eligible: hashes.length, previous: 0, toAdd: 0, toRemove: 0 }\n if (!config) {\n // A stage list nobody set up is the normal case; its line is the stage's.\n if (!stage) log(`[ad-audience-sync] ${provider} skipped — set ${listConfig.missing[provider].join(', ')}`)\n return { ...base, outcome: 'unconfigured', missing: listConfig.missing[provider] }\n }\n const previous = await readSentHashes(options.firestore, provider, stage)\n const diff = diffAudience(previous, hashes)\n const counts = {\n ...base,\n previous: previous.length,\n toAdd: diff.toAdd.length,\n toRemove: diff.toRemove.length,\n }\n const outcome = (value: ProviderOutcome, extra: Partial<ProviderReport> = {}): ProviderReport => {\n log(\n `[ad-audience-sync] ${name} ${value}: eligible ${counts.eligible}, ` +\n `previous ${counts.previous}, add ${counts.toAdd}, remove ${counts.toRemove}` +\n (extra.error ? ` — ${extra.error}` : ''),\n )\n return { ...counts, outcome: value, ...extra }\n }\n if (options.dryRun) return outcome('dry-run')\n if (!options.flagOn) return outcome('flag-off')\n const stamp = { lastRunAtMs: options.now, eligible: counts.eligible }\n if (!diff.toAdd.length && !diff.toRemove.length) {\n await writeRunState(options.firestore, list, { ...stamp, lastOutcome: 'unchanged' })\n return outcome('unchanged')\n }\n // Meta replaces with what it is sent, and an empty replace is no replace.\n if (!hashes.length) {\n await writeRunState(options.firestore, list, { ...stamp, lastOutcome: 'empty' })\n return outcome('empty', { error: 'no eligible account; the audience was left as it is' })\n }\n if (!options.force && isSuspiciousShrink(previous.length, hashes.length)) {\n await writeRunState(options.firestore, list, { ...stamp, lastOutcome: 'held-shrink' })\n return outcome('held-shrink', {\n error: `the audience would shrink from ${previous.length} to ${hashes.length}; held until a run with force`,\n })\n }\n try {\n if (provider === 'meta') {\n await sendMeta(\n options.fetch,\n config as NonNullable<AdAudienceConfig['meta']>,\n hashes,\n options.now + sessionOffset,\n )\n } else if (provider === 'google') {\n await sendGoogle(options.fetch, config as NonNullable<AdAudienceConfig['google']>, diff)\n } else {\n await sendLinkedIn(options.fetch, config as NonNullable<AdAudienceConfig['linkedin']>, diff)\n }\n } catch (error) {\n // The stored set stays as it was: the next run retries the whole diff,\n // and every provider takes a repeated add or remove without harm.\n const message = error instanceof AudienceSendError ? error.message : `${provider} send failed`\n if (!(error instanceof AudienceSendError)) console.error(`[ad-audience-sync] ${name}`, error)\n await writeRunState(options.firestore, list, {\n ...stamp,\n lastOutcome: 'failed',\n lastError: message,\n })\n return outcome('failed', { error: message })\n }\n await writeSentState(options.firestore, list, hashes, {\n ...stamp,\n lastOutcome: 'sent',\n lastSentAtMs: options.now,\n lastAdded: counts.toAdd,\n lastRemoved: counts.toRemove,\n lastError: null,\n })\n return outcome('sent')\n}\n\nexport async function runAdAudienceSync(options: AdAudienceRunOptions): Promise<AdAudienceSyncReport> {\n const log = options.log ?? ((line: string) => console.info(line))\n const selection = selectAdAudience(options.accounts, options.internalDomains, options.now)\n\n const providers = {} as Record<AdAudienceProvider, ProviderReport>\n for (const provider of AD_AUDIENCE_PROVIDERS) {\n providers[provider] = await syncList(\n options,\n log,\n { provider, stage: null },\n options.config,\n providerHashes(provider, selection.eligible),\n 0,\n )\n }\n\n // The stage lists: each a subset of the same eligible audience, each with\n // its own ledger, diff and shrink guard. Each failing alone, like a provider.\n const stages = {} as Record<AdAudienceStage, StageReport>\n for (const [index, stage] of AD_AUDIENCE_STAGES.entries()) {\n const members = selection.stages[stage]\n const stageProviders = {} as Record<AdAudienceProvider, ProviderReport>\n for (const provider of AD_AUDIENCE_PROVIDERS) {\n stageProviders[provider] = await syncList(\n options,\n log,\n { provider, stage },\n options.config.stages[stage],\n providerHashes(provider, members),\n index + 1,\n )\n }\n const unset = AD_AUDIENCE_PROVIDERS.filter((provider) => stageProviders[provider].outcome === 'unconfigured')\n log(\n `[ad-audience-sync] stage ${stage}: eligible ${members.length}` +\n (unset.length ? `; no list set on ${unset.join(', ')}` : ''),\n )\n stages[stage] = { eligible: members.length, providers: stageProviders }\n }\n\n return {\n dryRun: options.dryRun,\n flagOn: options.flagOn,\n scanned: selection.scanned,\n eligible: selection.eligible.length,\n excluded: selection.excluded,\n countrySource: selection.countrySource,\n providers,\n stages,\n }\n}\n"],"names":["AD_AUDIENCE_OPT_OUT_FIELD","readAdAudienceOptOut","ACCOUNT_ACQUISITION_FIELD","isAccountBanLockdownReason","LOCKDOWNS_COLLECTION","resolveEffectivePlan","FieldPath","Timestamp","AD_AUDIENCE_EXCLUSIONS","AD_AUDIENCE_LAPSE_MS","AD_AUDIENCE_PROVIDERS","AD_AUDIENCE_STAGES","adAudienceExclusion","adAudienceStages","buildGoogleMemberRequests","buildGoogleTokenRequest","buildLinkedInUserRequests","buildMetaReplaceRequests","diffAudience","hashAudienceEmail","instantMs","isOwnPublishedScreen","isRealActivityAction","isSuspiciousShrink","linkedInRefusedCount","resolveAccountCountry","AD_AUDIENCE_SYNC_COLLECTION","AD_AUDIENCE_MEMBERS_SUBCOLLECTION","MEMBER_CHUNK","MAX_AUTH_PAGES","SCREEN_PAGE","ACTIVITY_PAGE","ACTIVITY_PAGES","ACTIVITY_CONCURRENCY","adAudienceLedgerId","provider","stage","readAdAudienceAccounts","deps","db","firestore","profiles","collection","select","get","optedOut","Set","signupCountry","Map","doc","docs","data","add","id","geo","country","set","orgs","billing","paidOwners","hostOwner","owner","hosts","hostId","Object","keys","publishedOwners","readOwnPublishedOwners","now","catch","error","console","locks","where","documentId","locked","uid","slice","length","untilMs","live","accounts","pageToken","page","listed","listUserPage","record","users","push","email","emailVerified","Boolean","disabled","staff","customClaims","has","banned","billingCountries","stageFacts","createdAtMs","metadata","creationTime","ownsPaidWorkspace","ownsPublishedSite","lastActivityAtMs","nextPageToken","undefined","Error","bannedEmails","map","account","filter","trim","toLowerCase","since","recentActivity","sinceMs","readRecentActivityAtMs","internalDomains","candidates","created","activityFailures","index","Promise","all","at","owners","size","base","collectionGroup","orderBy","limit","after","startAfter","root","ref","path","split","fromMillis","jobs","log","newest","entries","real","find","job","started","Math","max","selectAdAudience","Date","excluded","fromEntries","reason","eligible","countrySource","signup","stages","source","scanned","providerHashes","hashes","hash","sort","readSentHashes","chunks","held","Array","isArray","ledgerFields","list","writeSentState","state","members","existing","runs","run","String","padStart","keep","_","delete","merge","writeRunState","AudienceSendError","status","detail","errorDetail","answer","message","send","fetcher","request","response","url","method","headers","body","JSON","stringify","json","ok","sendMeta","config","sendGoogle","diff","token","access_token","toRemove","toAdd","sendLinkedIn","requests","refused","syncList","options","listConfig","sessionOffset","name","previous","missing","join","outcome","counts","value","extra","dryRun","flagOn","stamp","lastRunAtMs","lastOutcome","force","fetch","lastError","lastSentAtMs","lastAdded","lastRemoved","runAdAudienceSync","line","info","selection","providers","stageProviders","unset"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,EAAEC,oBAAoB,QAAQ,qCAAoC;AACpG,SAASC,yBAAyB,QAAQ,6CAA4C;AACtF,SACEC,0BAA0B,EAC1BC,oBAAoB,QACf,kCAAiC;AACxC,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SAASC,SAAS,EAAEC,SAAS,QAAQ,2BAA0B;AAC/D,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,qBAAqB,EACrBC,kBAAkB,EAClBC,mBAAmB,EACnBC,gBAAgB,EAChBC,yBAAyB,EACzBC,uBAAuB,EACvBC,yBAAyB,EACzBC,wBAAwB,EACxBC,YAAY,EACZC,iBAAiB,EACjBC,SAAS,EACTC,oBAAoB,EACpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,oBAAoB,EACpBC,qBAAqB,QAQhB,wBAAoB;AAE3B;;;;;;;;;;;;;;;;;;;;;CAqBC,GAED,OAAO,MAAMC,8BAA8B,iBAAgB;AAC3D,OAAO,MAAMC,oCAAoC,UAAS;AAC1D,kFAAkF,GAClF,MAAMC,eAAe;AACrB,qDAAqD,GACrD,MAAMC,iBAAiB;AACvB,6D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,QAAQY,MAAM;QACtBnE,SAASgF,UAAUhF,OAAO;QAC1BL,UAAUqF,UAAUrF,QAAQ,CAAC5E,MAAM;QACnCyE,UAAUwF,UAAUxF,QAAQ;QAC5BI,eAAeoF,UAAUpF,aAAa;QACtCqF;QACAnF;IACF;AACF"}
@@ -25,6 +25,11 @@
25
25
  * and conversion APIs are the ad-conversions plugin, which this shares
26
26
  * nothing with.
27
27
  *
28
+ * Beside that one all-holders list, each provider may keep a STAGE list per
29
+ * stage (AGL-4072): free and not published, free and published, paid, and
30
+ * lapsed. Each is a subset of the same eligible audience, configured by its
31
+ * own list id, and synced, recorded and guarded exactly like the main list.
32
+ *
28
33
  * Everything here is pure — normalization, hashing, who is eligible, the
29
34
  * add/remove diff and each provider's request — so the spec walks every rule
30
35
  * without a network. `ad-audience-sync-run.ts` reads the accounts, sends and
@@ -80,6 +85,26 @@ export interface AdAudienceAccount {
80
85
  billingCountries: readonly string[];
81
86
  /** `users/{uid}.acquisition.geo.country`: where the sign-up request came from. */
82
87
  signupCountry: string | null;
88
+ /**
89
+ * The facts the STAGE lists read (AGL-4072). Optional so an account read
90
+ * without them is simply in no stage; eligibility never looks at them.
91
+ */
92
+ stageFacts?: AdAudienceStageFacts;
93
+ }
94
+ /** What decides an eligible account's stage (AGL-4072). */
95
+ export interface AdAudienceStageFacts {
96
+ /** When the Auth account was made (`metadata.creationTime`), or null. */
97
+ createdAtMs: number | null;
98
+ /** The account OWNS a workspace whose effective plan is a paid one. */
99
+ ownsPaidWorkspace: boolean;
100
+ /** The account owns a site with a page of its own that is published. */
101
+ ownsPublishedSite: boolean;
102
+ /**
103
+ * The newest real activity found inside the lapse window, or null when
104
+ * none was found there. Only read for an account old enough to lapse; it is
105
+ * never a sign-in time.
106
+ */
107
+ lastActivityAtMs: number | null;
83
108
  }
84
109
  /** Why an account is left out. Counted in every report; never per person. */
85
110
  export type AdAudienceExclusion = 'no-email' | 'disabled' | 'staff' | 'internal' | 'locked' | 'banned' | 'opted-out' | 'unverified' | 'no-country' | 'not-us';
@@ -130,6 +155,75 @@ export declare function emailDomain(address: string | null | undefined): string
130
155
  export declare function adAudienceExclusion(account: AdAudienceAccount, options?: {
131
156
  internalDomains?: readonly string[];
132
157
  }): AdAudienceExclusion | null;
158
+ /**
159
+ * The stage lists kept beside the all-holders list, so the ads for people
160
+ * who already have an account can say something that fits where they are.
161
+ * Each one is a SUBSET of the eligible audience — every exclusion above
162
+ * still applies first — and each is optional, sent only when its own list id
163
+ * is set.
164
+ *
165
+ * - `free-unpublished` — owns no workspace on a paid plan, and no site with a
166
+ * page of its own published.
167
+ * - `free-published` — owns no workspace on a paid plan, and at least one
168
+ * site with a page of its own published.
169
+ * - `paid` — owns at least one workspace on a paid plan.
170
+ * - `lapsed` — the account is more than 30 days old and nothing it did in the
171
+ * last 30 days was recorded. It overlaps the other three on purpose: a
172
+ * paying account that went quiet is both.
173
+ */
174
+ export declare const AD_AUDIENCE_STAGES: readonly ["free-unpublished", "free-published", "paid", "lapsed"];
175
+ export type AdAudienceStage = (typeof AD_AUDIENCE_STAGES)[number];
176
+ export declare const AD_AUDIENCE_STAGE_LABELS: Record<AdAudienceStage, string>;
177
+ /** How long an account must be quiet, and old, to be lapsed. */
178
+ export declare const AD_AUDIENCE_LAPSE_DAYS = 30;
179
+ export declare const AD_AUDIENCE_LAPSE_MS: number;
180
+ /** Whether one change-log entry's action is something the person did. */
181
+ export declare function isRealActivityAction(action: unknown): boolean;
182
+ /**
183
+ * An instant in milliseconds off a stored value in whichever form it reached
184
+ * this reader — a Firestore `Timestamp`, `{ seconds }` or `{ _seconds }`, a
185
+ * `Date`, a number or an ISO string — or null.
186
+ */
187
+ export declare function instantMs(value: unknown): number | null;
188
+ /** A page document's fields the published test reads. */
189
+ export interface AdAudienceScreenFacts {
190
+ publishedAt?: unknown;
191
+ deletedAt?: unknown;
192
+ createdAt?: unknown;
193
+ updatedAt?: unknown;
194
+ createdBy?: unknown;
195
+ }
196
+ /**
197
+ * Whether one page counts as the account's own and published: live
198
+ * (`publishedAt` set and not in the future, not deleted) and worked on by a
199
+ * person — made by one (`createdBy`), or saved more than a minute after it
200
+ * was made.
201
+ *
202
+ * The second half is why "has a published site" cannot be read off the site:
203
+ * every new site is born a published starter website, so a site that is live
204
+ * says nothing about whether its owner did anything. It is the weekly
205
+ * activity report's test, less the page's version history, which is one more
206
+ * read per page and moves with `updatedAt` anyway.
207
+ */
208
+ export declare function isOwnPublishedScreen(screen: AdAudienceScreenFacts, now: number): boolean;
209
+ /**
210
+ * Whether an account has lapsed: older than the window, and no real activity
211
+ * found inside it. An account with no creation time is never lapsed — there
212
+ * is no telling it from one made today.
213
+ *
214
+ * Only what the platform recorded the person DOING counts — their entries in
215
+ * a site's or workspace's change log and the AI jobs they started. Firebase's
216
+ * `lastSignInTime` and `lastRefreshTime` are deliberately not read: a browser
217
+ * tab reloading in the background signs the person back in silently, which
218
+ * moves both with nobody there.
219
+ */
220
+ export declare function isLapsedAccount(facts: AdAudienceStageFacts, now: number): boolean;
221
+ /**
222
+ * Every stage an ELIGIBLE account is in. Eligibility is the caller's: this
223
+ * classifies, it does not include. An account read without stage facts is
224
+ * in none.
225
+ */
226
+ export declare function adAudienceStages(account: AdAudienceAccount, now: number): AdAudienceStage[];
133
227
  /** What has to change for a provider to hold `next` when it holds `previous`. */
134
228
  export declare function diffAudience(previous: Iterable<string>, next: Iterable<string>): {
135
229
  toAdd: string[];
@@ -163,18 +257,33 @@ export interface LinkedInAudienceConfig {
163
257
  accessToken: string;
164
258
  segmentId: string;
165
259
  }
166
- export interface AdAudienceConfig {
260
+ /** One list on each provider: its settings, or null with the names it lacks. */
261
+ export interface AdAudienceListConfig {
167
262
  meta: MetaAudienceConfig | null;
168
263
  google: GoogleAudienceConfig | null;
169
264
  linkedin: LinkedInAudienceConfig | null;
170
265
  /** For each provider left unconfigured, the variables it is missing. */
171
266
  missing: Record<AdAudienceProvider, string[]>;
172
267
  }
268
+ export interface AdAudienceConfig extends AdAudienceListConfig {
269
+ /**
270
+ * The stage lists (AGL-4072). Each reuses its provider's credentials and
271
+ * names only its own list id, so a stage is configured when the provider's
272
+ * credentials are set and that stage's id is too.
273
+ */
274
+ stages: Record<AdAudienceStage, AdAudienceListConfig>;
275
+ }
173
276
  /**
174
277
  * The variables, read here by their literal names so the self-host
175
278
  * environment reference can see every one of them.
176
279
  */
177
280
  export declare function adAudienceEnv(): Record<string, string | undefined>;
281
+ /**
282
+ * The variable that holds one stage's list id on one provider, e.g.
283
+ * `META_AUDIENCE_SYNC_STAGE_FREE_UNPUBLISHED_AUDIENCE_ID`. Every name it
284
+ * builds is read literally in `adAudienceEnv`.
285
+ */
286
+ export declare function stageListVariable(provider: AdAudienceProvider, stage: AdAudienceStage): string;
178
287
  /**
179
288
  * Each provider's settings, or null with the names it lacks. A provider is
180
289
  * configured only when every required variable is set; a half-configured one
@@ -183,7 +292,11 @@ export declare function adAudienceEnv(): Record<string, string | undefined>;
183
292
  * The Meta audience is never created here. Creating one when the id is unset
184
293
  * would mint a fresh, empty audience on every run whose variable was lost, and
185
294
  * the ads targeting the real one would go on pointing at it, so the id is
186
- * required and the audience is made once, by hand.
295
+ * required and the audience is made once, by hand. The same holds for every
296
+ * stage list: an unset stage id is a stage that is not sent, never one made.
297
+ *
298
+ * A stage list never depends on the all-holders list's id: it needs only
299
+ * its provider's credentials and its own id.
187
300
  */
188
301
  export declare function readAdAudienceConfig(env?: Record<string, string | undefined>): AdAudienceConfig;
189
302
  /** One HTTP request, built without sending it. */