@aglyn/tenant-data-admin 1.0.0-beta.296 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/dynamic-list-materialize.js +59 -21
- package/src/lib/server/dynamic-list-materialize.js.map +1 -1
- package/src/lib/server/host-memberships.js +16 -0
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/host-visitor-records.d.ts +3 -2
- package/src/lib/server/host-visitor-records.js +12 -5
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/list-members.d.ts +18 -1
- package/src/lib/server/list-members.js +25 -3
- package/src/lib/server/list-members.js.map +1 -1
- package/src/lib/server/provision-starter.d.ts +5 -1
- package/src/lib/server/provision-starter.js +6 -2
- package/src/lib/server/provision-starter.js.map +1 -1
- package/src/lib/server/upsert-contact.d.ts +36 -0
- package/src/lib/server/upsert-contact.js +1 -1
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/lib/server/vercel-log-drain.d.ts +6 -1
- package/src/lib/server/vercel-log-drain.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-util-email": "1.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.1.0",
|
|
29
|
+
"@aglyn/shared-util-email": "1.1.0",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.1.0",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.1.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.1.0",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.1.0",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -476,6 +476,7 @@ const millis = (value)=>{
|
|
|
476
476
|
* org-owned contacts read is narrowed to.
|
|
477
477
|
* @param resume a cursor from a previous incomplete run.
|
|
478
478
|
*/ export async function materializeDynamicList(options) {
|
|
479
|
+
var _ref;
|
|
479
480
|
/*
|
|
480
481
|
* The rule cannot refer to the list it materializes — see
|
|
481
482
|
* `dynamicListRuleWithoutListReference` for the oscillation that produces,
|
|
@@ -516,26 +517,6 @@ const millis = (value)=>{
|
|
|
516
517
|
const key = personKey(candidate.email);
|
|
517
518
|
if (key) matches.set(key, candidate);
|
|
518
519
|
}
|
|
519
|
-
let enrolled = 0;
|
|
520
|
-
for (const candidate of matches.values()){
|
|
521
|
-
const result = await enrollListMember(_extends({
|
|
522
|
-
listRef: options.listRef,
|
|
523
|
-
// A group of one, and it costs nothing: the materializer passes NO
|
|
524
|
-
// consent (see below), so the group decides only which site is recorded
|
|
525
|
-
// as having captured the row.
|
|
526
|
-
group: soloConsentGroup(options.hostId),
|
|
527
|
-
email: candidate.email
|
|
528
|
-
}, candidate.name ? {
|
|
529
|
-
name: candidate.name
|
|
530
|
-
} : {}, {
|
|
531
|
-
source: `rule:${candidate.silo}`,
|
|
532
|
-
via: 'rule'
|
|
533
|
-
}));
|
|
534
|
-
// A refusal is not a materialization failure: an unusable address and a
|
|
535
|
-
// person whose row records a refusal are both simply not on this list,
|
|
536
|
-
// and a rule that selected them does not overrule either.
|
|
537
|
-
if (result.enrolled && result.created) enrolled += 1;
|
|
538
|
-
}
|
|
539
520
|
/*
|
|
540
521
|
* Reconciliation is allowed only for a run that saw the WHOLE population:
|
|
541
522
|
* one that started at the beginning AND finished.
|
|
@@ -554,6 +535,58 @@ const millis = (value)=>{
|
|
|
554
535
|
* a wrong count, which is recoverable, and a deleted enrollment destroys
|
|
555
536
|
* the record that says the person asked to be there, which is not.
|
|
556
537
|
*/ const sawWholePopulation = complete && !options.resume;
|
|
538
|
+
/*
|
|
539
|
+
* WHO IS ALREADY HERE, read once (AGL-4121).
|
|
540
|
+
*
|
|
541
|
+
* Enrolling costs three reads and a write per person, and nearly everyone a
|
|
542
|
+
* sweep matches was enrolled by the sweep before it, so an unchanged list
|
|
543
|
+
* used to pay that for its whole membership every hour to rewrite each row
|
|
544
|
+
* as it stood. What is held below lets `enrollListMember` settle those
|
|
545
|
+
* people with no read and no write. It decides nothing itself: a person it
|
|
546
|
+
* does not hold, a manual row the rule is about to take over, a row under a
|
|
547
|
+
* legacy id, all go through the same enrollment they always did.
|
|
548
|
+
*
|
|
549
|
+
* A run that saw everybody is about to read the rule's rows to reconcile, so
|
|
550
|
+
* it reads them here and reuses them. A partial run reconciles nothing and
|
|
551
|
+
* its list may be far longer than this run's matches, so it reads only those
|
|
552
|
+
* matches, one key each.
|
|
553
|
+
*/ const members = options.listRef.collection('members');
|
|
554
|
+
const readRuleRows = ()=>members.where('via', '==', 'rule').get();
|
|
555
|
+
const ruleRowsBefore = sawWholePopulation ? await readRuleRows() : null;
|
|
556
|
+
const heldRows = new Map();
|
|
557
|
+
for (const doc of (_ref = ruleRowsBefore == null ? void 0 : ruleRowsBefore.docs) != null ? _ref : [])heldRows.set(doc.id, doc);
|
|
558
|
+
if (!ruleRowsBefore && matches.size) {
|
|
559
|
+
const rows = await options.listRef.firestore.getAll(...[
|
|
560
|
+
...matches.keys()
|
|
561
|
+
].map((key)=>members.doc(key)));
|
|
562
|
+
for (const row of rows)if (row.exists) heldRows.set(row.id, row);
|
|
563
|
+
}
|
|
564
|
+
let enrolled = 0;
|
|
565
|
+
let wrote = false;
|
|
566
|
+
for (const [key, candidate] of matches){
|
|
567
|
+
const heldRow = heldRows.get(key);
|
|
568
|
+
const result = await enrollListMember(_extends({
|
|
569
|
+
listRef: options.listRef
|
|
570
|
+
}, heldRow ? {
|
|
571
|
+
heldRow
|
|
572
|
+
} : {}, {
|
|
573
|
+
// A group of one, and it costs nothing: the materializer passes NO
|
|
574
|
+
// consent (see below), so the group decides only which site is recorded
|
|
575
|
+
// as having captured the row.
|
|
576
|
+
group: soloConsentGroup(options.hostId),
|
|
577
|
+
email: candidate.email
|
|
578
|
+
}, candidate.name ? {
|
|
579
|
+
name: candidate.name
|
|
580
|
+
} : {}, {
|
|
581
|
+
source: `rule:${candidate.silo}`,
|
|
582
|
+
via: 'rule'
|
|
583
|
+
}));
|
|
584
|
+
// A refusal is not a materialization failure: an unusable address and a
|
|
585
|
+
// person whose row records a refusal are both simply not on this list,
|
|
586
|
+
// and a rule that selected them does not overrule either.
|
|
587
|
+
if (result.enrolled && result.created) enrolled += 1;
|
|
588
|
+
if (result.enrolled && !result.unchanged) wrote = true;
|
|
589
|
+
}
|
|
557
590
|
let removed = 0;
|
|
558
591
|
if (sawWholePopulation) {
|
|
559
592
|
/*
|
|
@@ -570,7 +603,12 @@ const millis = (value)=>{
|
|
|
570
603
|
* This is the one removal in this file and it is a MEMBERSHIP change —
|
|
571
604
|
* the person stopped matching the rule. It is not a capacity decision and
|
|
572
605
|
* there is no count in the condition.
|
|
573
|
-
|
|
606
|
+
*
|
|
607
|
+
* Read again only when the loop above wrote: then time has passed and
|
|
608
|
+
* somebody's hand-enrollment may have taken a row off the rule meanwhile,
|
|
609
|
+
* which this must see before it deletes. A loop that wrote nothing took no
|
|
610
|
+
* time, so the rows above are the read this would have made.
|
|
611
|
+
*/ const existing = ruleRowsBefore && !wrote ? ruleRowsBefore : await readRuleRows();
|
|
574
612
|
for (const doc of existing.docs){
|
|
575
613
|
if (matches.has(doc.id)) continue;
|
|
576
614
|
// A row adopted under a legacy id is keyed by neither `personKey` nor
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/dynamic-list-materialize.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\n/**\n * Materializes a `kind: 'dynamic'` list's rule into its `members`\n * subcollection (`docs/specs/email-overhaul.md` §3b/§3e).\n *\n * A dynamic list does NOT resolve at send time. It stores a rule, a sweep\n * writes the matching people into the same `members` collection a manual list\n * uses, and the send path keeps reading one deterministic collection. Three\n * reasons, all of them things that have already gone wrong here:\n *\n * 1. The send must not run an unbounded scan — that is what produced an\n * arbitrary, unstable 500 of a site's 3,000 leads.\n * 2. The composer needs a cheap count, not a 5,000-document scan per\n * keystroke.\n * 3. \"Who did this campaign go to\" is a support question and a compliance\n * question. A materialized membership answers it; a rule re-evaluated\n * later does not.\n *\n * ## ⛔ A CEILING NEVER REMOVES A PERSON\n *\n * This function has no quota comparison and must never grow one. Capacity in\n * this product is enforced at the REDUCTION, not at the use: a limit that\n * refuses a person or their data leaks, because the person is already there\n * and dropping them is not a refusal, it is deletion. So a rule that matches\n * more people than a plan's audience band, or than a single send's recipient\n * cap, materializes ALL of them. The ceiling that a large audience meets is\n * `performCampaignSend`'s, which refuses the SEND and states the count it\n * found — a refusal the merchant can see, argue with, and act on, where a\n * trimmed membership is silent and unreproducible.\n *\n * What bounds this function is the per-run SCAN budget below, which is a\n * different thing: it bounds how much work one sweep does, and the cursor it\n * returns resumes the same sweep on the next run. Running out of budget\n * postpones enrollments; it never removes anybody, and it never finishes a\n * sweep it did not complete.\n */\n\nimport { FieldValue } from 'firebase-admin/firestore'\nimport type {\n DocumentReference,\n Query,\n QueryDocumentSnapshot,\n} from 'firebase-admin/firestore'\nimport {\n soloConsentGroup,\n candidateMatchesDynamicListRule,\n dynamicListRuleIsEmpty,\n dynamicListRuleListIds,\n dynamicListRuleWithoutListReference,\n dynamicListRuleNeedsContactFacet,\n dynamicListDimensionsForCrmView,\n dynamicListPlanningRule,\n CRM_COLLECTIONS,\n normalizeCrmViewFilters,\n type DynamicListDimensions,\n dynamicListRuleNeedsEngagement,\n extractEmailFromFields,\n seenOnlyThroughGrant,\n isContactLifecycleStage,\n normalizeContactEmail,\n normalizeDynamicListRule,\n personKey,\n readContainerIds,\n readContactContainerIds,\n readContactFacet,\n type ContactCustomValue,\n type DynamicListCandidate,\n type DynamicListRule,\n type DynamicListSource,\n type ResolvedSegmentFilters,\n} from '@aglyn/aglyn/server'\nimport { consentGroupHoldersInMotion } from '@aglyn/aglyn/app-utils/consent-group-change'\nimport { firebaseAdmin } from './firebase-admin'\nimport { readPersonEngagementByKeys } from './email-delivery-log'\nimport { enrollListMember } from './list-members'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n scopedToHost,\n} from './organizations'\n\n/**\n * Documents one sweep run may READ across all sources.\n *\n * A bound on work, not on membership. When a run exhausts it the sweep stops\n * where it is, returns `complete: false` with the cursor it reached, and the\n * next run continues — the shape the import-history sweep already uses. The\n * alternative, an unbounded scan of every silo per list per run, is the\n * expensive-read pattern this codebase refuses.\n *\n * ⚠️ Membership reconciliation is SKIPPED on an incomplete run. A partial\n * scan has only seen part of the population, so anybody it did not reach\n * would look like a non-match — and acting on that would delete real members\n * because a budget ran out.\n */\nexport const DYNAMIC_LIST_SCAN_BUDGET = 5_000\n\n/** Documents read per source page. */\nconst PAGE_SIZE = 500\n\n/**\n * ⚠️ THE DATE FIELDS THIS FILE READS, AND WHO WRITES THEM.\n *\n * `createdAfterMs`/`createdBeforeMs` are applied IN MEMORY against\n * `createdAt`, never as a Firestore `orderBy` or `where`. That distinction is\n * the whole safety property: an `orderBy` on a data field drops every document\n * missing it from the QUERY, invisibly, where an in-memory filter still reads\n * the document and merely decides it does not match. The paging order is\n * `__name__`, the one key every document has.\n *\n * The rule's decision for an undated record is to EXCLUDE it, so the writers\n * were checked rather than assumed — a silo with an unstamped writer would\n * quietly shrink every dated rule:\n *\n * - `leads` — `addHostLead` is the single writer and always stamps it.\n * - `siteMembers` — `membership-register.ts` is the only creator; the other\n * member routes read or update an existing document.\n * - `contacts` — `upsertHostContact`'s create path and the v1 API both stamp.\n * - `formSubmissions` — the submit route is the only creator; the v1 API and\n * the inbox reply route read.\n *\n * A new writer of any of those four must stamp `createdAt` or be added here.\n *\n * ## Campaign membership is read the same way — off the paged document\n *\n * `campaignIds` is applied in memory too, and for a second reason beyond the\n * one above: it is an ARRAY, so a Firestore `array-contains-any` could express\n * only the single-campaign case and would need a composite index the moment it\n * met any other filter in the rule. The membership is already on the document\n * this scan has read, on a submission at the top and on a contact inside the\n * reading holder's facet, so matching it costs nothing the page did not\n * already pay.\n */\n\n/** Where a partial sweep stopped, so the next run resumes rather than restarts. */\nexport interface DynamicListCursor {\n /** The source being scanned when the budget ran out. */\n source: DynamicListSource\n /** The last document id read from it. */\n afterId: string\n}\n\nexport interface MaterializeDynamicListResult {\n /** People the rule matched and that are now enrolled. */\n matched: number\n /** Rows created by this run. */\n enrolled: number\n /** Rule-owned rows removed because the person no longer matches. */\n removed: number\n /** False when the scan budget ran out — `cursor` says where to resume. */\n complete: boolean\n cursor: DynamicListCursor | null\n /**\n * True when the rule selects nobody by construction (no sources). Reported\n * rather than silently materializing an empty list, because an empty list\n * reads in the composer exactly like a rule that has not run yet.\n */\n empty: boolean\n}\n\n/** What a read-only pass over the silos found. */\nexport interface DynamicListScanResult {\n /** Matched people, de-duplicated across silos by their person key. */\n candidates: DynamicListCandidate[]\n /** False when the scan budget ran out — `cursor` says where to resume. */\n complete: boolean\n cursor: DynamicListCursor | null\n /**\n * True when the rule selects nobody by construction — no sources, or a\n * `segmentId` naming a segment that no longer exists.\n */\n empty: boolean\n /** Documents read, against the budget. */\n read: number\n}\n\n/**\n * The silo collections, as queries.\n *\n * `contacts` is org-scoped and must go through `scopedToHost` — the Admin SDK\n * does not evaluate rules, so an unfiltered read would let one site's list\n * materialize another site's contacts. The other three are host-owned and\n * carry no `visibleTo` to filter on.\n */\nasync function sourceQuery(\n source: DynamicListSource,\n hostId: string,\n): Promise<Query> {\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n if (source === 'contacts') {\n const ref = await orgDataCollectionForHost(hostId, 'contacts')\n return scopedToHost(ref, hostId)\n }\n return hostRef.collection(source)\n}\n\nconst millis = (value: unknown): number | null => {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n const toMillis = (value as { toMillis?: unknown } | null)?.toMillis\n if (typeof toMillis === 'function') {\n const parsed = Number(toMillis.call(value))\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\n/**\n * The CRM fields a rule may read, out of ONE holder's facet (AGL-2603).\n *\n * The owner, the stage, the company and the custom values are this holder's\n * business records on a shared row. They are read through `readContactFacet`\n * for the group the sweep runs as — never off the top of the document, where\n * a pre-facet row could still carry somebody's fields, and never out of\n * another group's facet. A field the facet does not carry is left ABSENT on\n * the candidate, which the matcher reads as \"does not match\" for the first\n * three and as \"unset\" for a custom clause; a stage the model does not name\n * is dropped for the reason the normalizer drops one from a rule.\n */\nfunction crmFieldsFromFacet(\n data: Record<string, unknown>,\n groupId: string,\n): Pick<\n DynamicListCandidate,\n 'ownerUid' | 'lifecycleStage' | 'companyId' | 'custom' | 'lastEmailEngagementAtMs'\n> {\n const facet = readContactFacet(data, groupId)\n const custom =\n facet.custom && typeof facet.custom === 'object' && !Array.isArray(facet.custom)\n ? (facet.custom as Record<string, ContactCustomValue>)\n : undefined\n // The campaign engagement stamp (AGL-2616), on the same footing as the\n // owner: this holder's fact about the person, read out of this holder's\n // facet, absent when the webhook has never stamped one.\n const engaged = Number(facet.lastEmailEngagementAtMs ?? 0)\n return {\n ...(typeof facet.ownerUid === 'string' && facet.ownerUid\n ? { ownerUid: facet.ownerUid }\n : {}),\n ...(isContactLifecycleStage(facet.lifecycleStage)\n ? { lifecycleStage: facet.lifecycleStage }\n : {}),\n ...(typeof facet.companyId === 'string' && facet.companyId\n ? { companyId: facet.companyId }\n : {}),\n ...(custom ? { custom } : {}),\n ...(Number.isFinite(engaged) && engaged > 0\n ? { lastEmailEngagementAtMs: engaged }\n : {}),\n }\n}\n\n/**\n * Reads one silo document into the shape the rule matcher understands.\n *\n * @param groupId the consent group whose contact facet the campaign membership\n * and the CRM fields are read from, or `null` when the rule names none of\n * them and no group was resolved. A contact row is shared by every site in\n * the org and its membership, its owner, its stage, its company and its\n * custom values all live inside one holder's facet, so there is no\n * expression here that returns another holder's filing.\n */\nfunction toCandidate(\n source: DynamicListSource,\n doc: QueryDocumentSnapshot,\n groupId: string | null,\n): DynamicListCandidate | null {\n const data = doc.data() as Record<string, unknown>\n const email =\n source === 'formSubmissions'\n ? // A form does not guarantee a canonical email field, so this is the\n // same best-effort extraction the submissions route already uses to\n // decide whether a submission produces a contact at all.\n extractEmailFromFields(data['fields'] as Record<string, unknown>)\n : normalizeContactEmail(data['email'])\n if (!email) return null\n const createdAtMs = millis(data['createdAt'])\n return {\n silo: source,\n email,\n // `siteMembers` stores `displayName`; the rest store `name`. Reading only\n // `name` is what left every member campaign's merge tags blank.\n name:\n (typeof data['name'] === 'string' && data['name']) ||\n (typeof data['displayName'] === 'string' && data['displayName']) ||\n undefined,\n createdAtMs,\n ...(source === 'contacts'\n ? {\n tags: (data['tags'] as string[]) ?? [],\n sources: (data['sources'] as DynamicListCandidate['sources']) ?? {},\n ordersCount: Number(data['ordersCount'] ?? 0),\n ltvCents: Number(data['ltvCents'] ?? 0),\n lastPurchaseAtMs: millis(data['lastPurchaseAtMs']),\n // Inside the holder's facet, never the top of the document. A rule\n // with no facet clause resolves no group and reads nothing here,\n // which is what keeps the group lookup an opt-in cost.\n ...(groupId\n ? {\n campaignIds: readContactContainerIds(data, groupId, 'campaign'),\n ...crmFieldsFromFacet(data, groupId),\n }\n : {}),\n }\n : {}),\n ...(source === 'formSubmissions'\n ? {\n formName: String(data['formName'] ?? ''),\n // At the TOP of a submission, because a submission belongs to one\n // site — the same shape every other host resource carries it in.\n campaignIds: readContainerIds(data, 'campaign'),\n }\n : {}),\n }\n}\n\n/*==========================================\n * ENRICHMENT — the two dimensions the scan cannot read off a silo row.\n *\n * Engagement lives on `emailDeliveries/{personKey}` and list membership on\n * `orgs/{orgId}/lists/{listId}/members/{personKey}`. Both describe an ADDRESS\n * rather than a contact, a lead or a submission, so neither is in the\n * document the sweep just paged.\n *\n * Three properties, and each of them is a thing that could otherwise go\n * wrong here:\n *\n * 1. **KEYED reads, never queries.** `getAll` over document references. No\n * `where`, no `orderBy`, so no composite index, nothing that can be\n * truncated by a `limit`, and — the failure this codebase has hit\n * nineteen times — nothing that silently drops a document for missing\n * the field being ordered on.\n * 2. **Opt-in.** A rule with no engagement clause and no list reference\n * pays nothing at all. The cost belongs to the rules that ask for it,\n * not to every sweep.\n * 3. **Charged to the SAME scan budget.** Every enrichment read is counted\n * in `read`, so a rule that asks for engagement fills the budget faster\n * and its sweep simply takes more runs. The budget and the resume cursor\n * keep working exactly as they did; what changes is how much of the\n * budget one page costs.\n *=========================================*/\n\n/** What a rule needs looked up, resolved once per scan rather than per page. */\ninterface EnrichmentPlan {\n engagement: boolean\n /** `listId` → that list's `members` collection. */\n listMembers: Map<string, FirebaseFirestore.CollectionReference>\n}\n\n/**\n * Resolves what a rule needs enriched.\n *\n * A named list that no longer exists resolves to a collection with no\n * documents, which reads as \"nobody is a member\" — the same direction a\n * deleted `segmentId` takes, and the safe one: an `inListIds` naming a\n * deleted list selects nobody rather than everybody, and a `notInListIds`\n * naming one excludes nobody rather than the whole audience.\n */\nasync function planEnrichment(\n rule: DynamicListRule,\n hostId: string,\n): Promise<EnrichmentPlan> {\n const listIds = dynamicListRuleListIds(rule)\n const listMembers = new Map<string, FirebaseFirestore.CollectionReference>()\n if (listIds.length) {\n const lists = await orgDataCollectionForHost(hostId, 'lists')\n for (const listId of listIds) {\n listMembers.set(listId, lists.doc(listId).collection('members'))\n }\n }\n return { engagement: dynamicListRuleNeedsEngagement(rule), listMembers }\n}\n\n/** True when nothing needs looking up, so the page loop can skip the work. */\nfunction planIsEmpty(plan: EnrichmentPlan): boolean {\n return !plan.engagement && plan.listMembers.size === 0\n}\n\n/**\n * Fills the enrichment fields on one page's candidates.\n *\n * Keys are de-duplicated first: two silos can produce the same person on one\n * page, and looking them up twice would spend budget on an answer already in\n * hand.\n *\n * @returns how many documents were read, for the caller's budget.\n */\nasync function enrichCandidates(\n candidates: DynamicListCandidate[],\n plan: EnrichmentPlan,\n): Promise<number> {\n if (!candidates.length || planIsEmpty(plan)) return 0\n const keyed = new Map<string, DynamicListCandidate[]>()\n for (const candidate of candidates) {\n const key = personKey(candidate.email)\n if (!key) continue\n const held = keyed.get(key)\n if (held) held.push(candidate)\n else keyed.set(key, [candidate])\n }\n const keys = [...keyed.keys()]\n if (!keys.length) return 0\n const firestore = firebaseAdmin.app().firestore()\n let read = 0\n\n if (plan.engagement) {\n // The scan's own Firestore handle, passed rather than defaulted: the\n // rollup lives in another module with its own default, and two handles in\n // one sweep is two things a caller has to configure to reach one store.\n const engagement = await readPersonEngagementByKeys(keys, firestore)\n read += keys.length\n for (const [key, rows] of keyed) {\n const found = engagement.get(key)\n for (const candidate of rows) {\n candidate.lastOpenedAtMs = found?.lastOpenedAtMs ?? null\n candidate.lastClickedAtMs = found?.lastClickedAtMs ?? null\n }\n }\n }\n\n if (plan.listMembers.size) {\n // No pre-seeding of `listIds`. A candidate found on no list keeps the\n // field absent, and the matcher reads absent as \"on no list\" — see\n // `candidateMatchesDynamicListRule` for why that direction is the safe\n // one. Writing an empty array first would be a line saying the same thing\n // the matcher already says.\n for (const [listId, members] of plan.listMembers) {\n let snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n try {\n snapshots = await firestore.getAll(\n ...keys.map((key) => members.doc(key)),\n )\n } catch (error) {\n // A failed membership lookup leaves every candidate reading as a\n // non-member of this list. That keeps an `inListIds` rule from\n // enrolling people it could not confirm, and it is the direction a\n // reader can recover from — the next sweep asks again.\n console.error('[dynamic-list] list membership lookup failed', listId, error)\n }\n read += keys.length\n for (const snapshot of snapshots) {\n if (!snapshot?.exists) continue\n for (const candidate of keyed.get(snapshot.id) ?? []) {\n candidate.listIds = [...(candidate.listIds ?? []), listId]\n }\n }\n }\n }\n\n return read\n}\n\n/**\n * WHO A RULE SELECTS, without writing anything.\n *\n * The scan and the enrollment used to be one function, so \"who would this\n * match\" could only be answered by materializing it. That is the wrong shape\n * for two callers that now exist: a merchant asking to see an audience before\n * committing to it, and a fixed list using the filters to FIND people to add.\n * Neither may write memberships as a side effect of a question.\n *\n * One scanner rather than two. Every subtlety here is a place a second\n * implementation would drift — the in-memory date filter (an `orderBy` on a\n * data field would DROP undated documents rather than merely not matching\n * them), the `__name__` paging order, `scopedToHost` on `contacts` and on\n * nothing else, and a deleted `segmentId` narrowing to nobody rather than\n * widening to everybody. `materializeDynamicList` reads this and then enrolls.\n *\n * NOTHING here writes, and nothing here compares a count against a limit.\n */\nexport async function collectDynamicListCandidates(options: {\n hostId: string\n rule: unknown\n resume?: DynamicListCursor | null\n nowMs?: number\n scanBudget?: number\n}): Promise<DynamicListScanResult> {\n const rule: DynamicListRule = normalizeDynamicListRule(options.rule)\n const nowMs = options.nowMs ?? Date.now()\n const budget = options.scanBudget ?? DYNAMIC_LIST_SCAN_BUDGET\n if (dynamicListRuleIsEmpty(rule)) {\n return { candidates: [], complete: true, cursor: null, empty: true, read: 0 }\n }\n\n // A saved segment's filters, resolved ONCE rather than per candidate.\n let segment: ResolvedSegmentFilters | null = null\n if (rule.segmentId) {\n const segments = await orgDataCollectionForHost(\n options.hostId,\n 'contactSegments',\n )\n const snapshot = await segments.doc(rule.segmentId).get()\n // A deleted segment narrows to nothing rather than widening to everybody:\n // a rule whose filter vanished must not start matching the whole org.\n if (!snapshot.exists) {\n return {\n candidates: [],\n complete: true,\n cursor: null,\n empty: true,\n read: 0,\n }\n }\n segment = {\n tags: (snapshot.get('tags') as string[]) ?? [],\n sources: (snapshot.get('sources') as ResolvedSegmentFilters['sources']) ?? [],\n }\n }\n\n /*\n * A saved VIEW's filters, resolved ONCE into this language (AGL-2617).\n *\n * The same two leans the segment takes, for the same reason: a view that\n * was deleted narrows to nothing, and so does one whose clauses this\n * language cannot carry — `dynamicListDimensionsForCrmView` names them\n * rather than dropping them, and dropping one would make the audience\n * wider than the view the merchant picked. The picker offers only views\n * that translate whole, so the second case is a view edited after the\n * rule named it, and a view of another section — a list of companies is\n * not an audience of people — reads the same way.\n */\n let view: DynamicListDimensions | null = null\n if (rule.viewId) {\n const views = await orgDataCollectionForHost(\n options.hostId,\n CRM_COLLECTIONS.views,\n )\n const snapshot = await views.doc(rule.viewId).get()\n const translation =\n snapshot.exists && snapshot.get('section') === 'contacts'\n ? dynamicListDimensionsForCrmView(\n normalizeCrmViewFilters(snapshot.get('filters')),\n )\n : null\n if (!translation || translation.unsupported.length) {\n return {\n candidates: [],\n complete: true,\n cursor: null,\n empty: true,\n read: 0,\n }\n }\n view = translation.dimensions\n }\n\n /*\n * Resolved once for the whole scan: it names collections, and re-resolving\n * the org for every page would be a read per page for an unchanging answer.\n * Planned with the view's dimensions beside the rule's: a view naming an\n * owner needs the facet exactly as a rule naming one does.\n */\n const planning = dynamicListPlanningRule(rule, view)\n const enrichment = await planEnrichment(planning, options.hostId)\n\n /*\n * THE HOLDER whose contact facet a campaign or CRM clause is read from.\n *\n * The same group the writers use — the sites declared to be one sender, or\n * this site alone — because a facet written under one group id and read\n * under another is a membership that silently matches nobody. Resolved once,\n * and only for a rule that names something the facet holds: a campaign, an\n * owner, a stage, a company or a custom field. A rule naming none of them\n * pays no org read at all, which is the shape the engagement and list\n * lookups already take.\n */\n let facetGroupId: string | null = null\n if (dynamicListRuleNeedsContactFacet(planning)) {\n const found = await getOrgForHost(options.hostId).catch(() => null)\n const org = (found?.org as Record<string, unknown> | undefined) ?? null\n /*\n * NOT WHILE THE FACETS MOVE (AGL-3320). A consent group change re-homes\n * this site's facets after its declaration flips, and until it finishes a\n * person's record may still sit under the old key — where this read,\n * keyed by the new group, finds nothing. A rule reads that absence as a\n * non-match, and a non-match is a removal. So the scan reports itself\n * incomplete and reads nothing: the materializer's own rule for a partial\n * view then enrolls nobody new and removes nobody, and the first sweep\n * after the change finishes reads every record where it landed.\n */\n if (consentGroupHoldersInMotion(org, options.hostId)) {\n return {\n candidates: [],\n complete: false,\n cursor: options.resume ?? null,\n empty: false,\n read: 0,\n }\n }\n facetGroupId = (await consentGroupForSite(options.hostId, org)).groupId\n }\n\n /** Matched people, de-duplicated across silos by their person key. */\n const matches = new Map<string, DynamicListCandidate>()\n let read = 0\n let cursor: DynamicListCursor | null = null\n let complete = true\n\n const ordered = rule.sources\n const resumeIndex = options.resume\n ? ordered.indexOf(options.resume.source)\n : -1\n\n scan: for (let index = 0; index < ordered.length; index += 1) {\n const source = ordered[index] as DynamicListSource\n // A resume skips the sources already finished and re-enters the one that\n // was interrupted at the id it stopped on.\n if (resumeIndex >= 0 && index < resumeIndex) continue\n let after = resumeIndex === index ? options.resume?.afterId ?? '' : ''\n const base = await sourceQuery(source, options.hostId)\n for (;;) {\n /*\n * Ordered by document id, and paged with a `startAfter` cursor.\n *\n * `orderBy(FieldPath.documentId())` rather than a data field on\n * purpose: an `orderBy` on a field DROPS every document missing it, and\n * these four collections have writers old enough that no data field is\n * guaranteed on every row. The id is on all of them, so this is a total\n * order that cannot silently omit a person — which is the whole point\n * of the exercise, since the defect being fixed is an unordered\n * `limit()` returning an arbitrary subset.\n */\n let page = base\n .orderBy(firebaseAdmin.firestore.FieldPath.documentId())\n .limit(PAGE_SIZE)\n if (after) page = page.startAfter(after)\n const snapshot = await page.get()\n if (snapshot.empty) break\n /*\n * The page is read into candidates FIRST, then enriched, then matched.\n *\n * A per-document match would mean a per-document enrichment lookup, and\n * the whole reason enrichment is affordable is that one page's people\n * are fetched in one `getAll`. Only candidates are enriched — a\n * document with no usable address is dropped by `toCandidate` before it\n * can cost a lookup.\n */\n const pageCandidates: DynamicListCandidate[] = []\n for (const doc of snapshot.docs) {\n read += 1\n after = doc.id\n // A contact another site SHARED with this one (AGL-3336) is seen\n // here, not held: it is never this site's audience.\n if (source === 'contacts' && seenOnlyThroughGrant(doc.data(), options.hostId)) continue\n const candidate = toCandidate(source, doc, facetGroupId)\n if (candidate) pageCandidates.push(candidate)\n }\n read += await enrichCandidates(pageCandidates, enrichment)\n for (const candidate of pageCandidates) {\n if (\n !candidateMatchesDynamicListRule(candidate, rule, {\n segment,\n view,\n nowMs,\n })\n ) {\n continue\n }\n const key = personKey(candidate.email)\n if (key && !matches.has(key)) matches.set(key, candidate)\n }\n if (read >= budget) {\n complete = false\n cursor = { source, afterId: after }\n break scan\n }\n if (snapshot.size < PAGE_SIZE) break\n }\n }\n\n\n return {\n candidates: [...matches.values()],\n complete,\n cursor,\n empty: false,\n read,\n }\n}\n\n/**\n * Re-evaluates one dynamic list and writes the result into its members.\n *\n * @param listRef `orgs/{orgId}/lists/{listId}` — the caller has proved it\n * exists and that it is `kind: 'dynamic'`.\n * @param hostId the site whose silos the rule draws from, and the scope the\n * org-owned contacts read is narrowed to.\n * @param resume a cursor from a previous incomplete run.\n */\nexport async function materializeDynamicList(options: {\n listRef: DocumentReference\n hostId: string\n rule: unknown\n resume?: DynamicListCursor | null\n nowMs?: number\n /**\n * The scan budget. Passed by NOTHING in production — it exists so the suite\n * can drive a sweep into an exhausted budget and require that it still\n * removes nobody. A guarantee that only holds at the production budget was\n * never that guarantee.\n */\n scanBudget?: number\n}): Promise<MaterializeDynamicListResult> {\n /*\n * The rule cannot refer to the list it materializes — see\n * `dynamicListRuleWithoutListReference` for the oscillation that produces,\n * and note that half of its beats are DELETIONS of rows this sweep created.\n * Stripped here rather than at authoring time because the rule outlives any\n * one form: an API caller, an import and a copied list would each need to\n * remember, and the sweep is the one place all of them arrive.\n */\n const rule = dynamicListRuleWithoutListReference(\n normalizeDynamicListRule(options.rule),\n options.listRef.id,\n )\n const scan = await collectDynamicListCandidates({\n hostId: options.hostId,\n rule,\n ...(options.resume ? { resume: options.resume } : {}),\n ...(options.nowMs !== undefined ? { nowMs: options.nowMs } : {}),\n ...(options.scanBudget !== undefined\n ? { scanBudget: options.scanBudget }\n : {}),\n })\n if (scan.empty) {\n return {\n matched: 0,\n enrolled: 0,\n removed: 0,\n complete: true,\n cursor: null,\n empty: true,\n }\n }\n const { complete, cursor } = scan\n /*\n * Re-keyed by person rather than carried as a Map across the seam.\n *\n * Reconciliation below asks `matches.has(key)` about a stored row's id and\n * about its address, so it needs the same key the scan de-duplicated on —\n * computed by the same function, from the same addresses.\n */\n const matches = new Map<string, DynamicListCandidate>()\n for (const candidate of scan.candidates) {\n const key = personKey(candidate.email)\n if (key) matches.set(key, candidate)\n }\n\n let enrolled = 0\n for (const candidate of matches.values()) {\n const result = await enrollListMember({\n listRef: options.listRef,\n // A group of one, and it costs nothing: the materializer passes NO\n // consent (see below), so the group decides only which site is recorded\n // as having captured the row.\n group: soloConsentGroup(options.hostId),\n email: candidate.email,\n ...(candidate.name ? { name: candidate.name } : {}),\n source: `rule:${candidate.silo}`,\n via: 'rule',\n /*\n * ⛔ NO CONSENT IS PASSED, EVER.\n *\n * Matching a rule is not consenting to anything — the person is here\n * because they bought something, filled in a form or hold an account,\n * and none of those is an opt-in. Stamping a basis from a rule match\n * would let any merchant manufacture consent for their whole contact\n * list by writing a rule that selects it, which is precisely the\n * inference the consent arc refused to make. Their real basis, if they\n * have one, is on their own record and the send-time join reads it\n * there.\n */\n })\n // A refusal is not a materialization failure: an unusable address and a\n // person whose row records a refusal are both simply not on this list,\n // and a rule that selected them does not overrule either.\n if (result.enrolled && result.created) enrolled += 1\n }\n\n /*\n * Reconciliation is allowed only for a run that saw the WHOLE population:\n * one that started at the beginning AND finished.\n *\n * `complete` alone is not enough, and that is the trap. A run that RESUMES\n * from a cursor finishes the tail of the scan and reports `complete: true`\n * having examined only the tail — so its match set is the remainder, and\n * reconciling against it would delete every member found by the earlier\n * runs of the same sweep. That is a quota drop wearing the costume of a\n * membership change: nothing about it looks like a limit, and it removes\n * people for no reason but how the work was chunked.\n *\n * The cost is that a list whose population exceeds one run's scan budget\n * never reconciles, so somebody who stops matching stays enrolled until a\n * sweep fits in one run. That is the right way round: an over-full list is\n * a wrong count, which is recoverable, and a deleted enrollment destroys\n * the record that says the person asked to be there, which is not.\n */\n const sawWholePopulation = complete && !options.resume\n let removed = 0\n if (sawWholePopulation) {\n /*\n * Reconciliation.\n *\n * Only rows this materializer created are eligible (`via === 'rule'`). A\n * row somebody enrolled by hand, or that an automation's `enrollList`\n * step wrote, stays on a dynamic list forever: it was put there by a\n * decision, and a rule that does not happen to select that person is not\n * a decision to remove them. Rows written before `via` existed carry no\n * `via` at all and are therefore never eligible either, which is the\n * conservative direction for a field introduced after the data.\n *\n * This is the one removal in this file and it is a MEMBERSHIP change —\n * the person stopped matching the rule. It is not a capacity decision and\n * there is no count in the condition.\n */\n const existing = await options.listRef\n .collection('members')\n .where('via', '==', 'rule')\n .get()\n for (const doc of existing.docs) {\n if (matches.has(doc.id)) continue\n // A row adopted under a legacy id is keyed by neither `personKey` nor\n // anything this sweep computed, so it is matched by ADDRESS as well\n // before being removed. Getting that wrong un-enrolls a person who\n // still matches the rule.\n const email = normalizeContactEmail(doc.get('email'))\n const key = email ? personKey(email) : null\n if (key && matches.has(key)) continue\n await doc.ref.delete()\n removed += 1\n }\n }\n\n await options.listRef.set(\n {\n kind: 'dynamic',\n // The count the composer reads instead of scanning. Written only by a\n // run that saw everybody, for the same reason reconciliation is: a\n // partial or resumed run measured a fraction, and publishing that as\n // the list's size would under-report the audience in the one place a\n // merchant checks it before sending.\n ...(sawWholePopulation ? { memberCount: matches.size } : {}),\n lastEvaluatedAt: FieldValue.serverTimestamp(),\n ...(cursor ? { evaluationCursor: cursor } : { evaluationCursor: null }),\n },\n { merge: true },\n )\n\n return {\n matched: matches.size,\n enrolled,\n removed,\n complete,\n cursor,\n empty: false,\n }\n}\n"],"names":["FieldValue","soloConsentGroup","candidateMatchesDynamicListRule","dynamicListRuleIsEmpty","dynamicListRuleListIds","dynamicListRuleWithoutListReference","dynamicListRuleNeedsContactFacet","dynamicListDimensionsForCrmView","dynamicListPlanningRule","CRM_COLLECTIONS","normalizeCrmViewFilters","dynamicListRuleNeedsEngagement","extractEmailFromFields","seenOnlyThroughGrant","isContactLifecycleStage","normalizeContactEmail","normalizeDynamicListRule","personKey","readContainerIds","readContactContainerIds","readContactFacet","consentGroupHoldersInMotion","firebaseAdmin","readPersonEngagementByKeys","enrollListMember","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","scopedToHost","DYNAMIC_LIST_SCAN_BUDGET","PAGE_SIZE","sourceQuery","source","hostId","hostRef","app","firestore","collection","doc","ref","millis","value","Number","isFinite","toMillis","parsed","call","crmFieldsFromFacet","data","groupId","facet","custom","Array","isArray","undefined","engaged","lastEmailEngagementAtMs","ownerUid","lifecycleStage","companyId","toCandidate","email","createdAtMs","silo","name","tags","sources","ordersCount","ltvCents","lastPurchaseAtMs","campaignIds","formName","String","planEnrichment","rule","listIds","listMembers","Map","length","lists","listId","set","engagement","planIsEmpty","plan","size","enrichCandidates","candidates","keyed","candidate","key","held","get","push","keys","read","rows","found","lastOpenedAtMs","lastClickedAtMs","members","snapshots","getAll","map","error","console","snapshot","exists","id","collectDynamicListCandidates","options","nowMs","Date","now","budget","scanBudget","complete","cursor","empty","segment","segmentId","segments","view","viewId","views","translation","unsupported","dimensions","planning","enrichment","facetGroupId","catch","org","resume","matches","ordered","resumeIndex","indexOf","scan","index","after","afterId","base","page","orderBy","FieldPath","documentId","limit","startAfter","pageCandidates","docs","has","values","materializeDynamicList","listRef","matched","enrolled","removed","result","group","via","created","sawWholePopulation","existing","where","delete","kind","memberCount","lastEvaluatedAt","serverTimestamp","evaluationCursor","merge"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AAMrD,SACEC,gBAAgB,EAChBC,+BAA+B,EAC/BC,sBAAsB,EACtBC,sBAAsB,EACtBC,mCAAmC,EACnCC,gCAAgC,EAChCC,+BAA+B,EAC/BC,uBAAuB,EACvBC,eAAe,EACfC,uBAAuB,EAEvBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,wBAAwB,EACxBC,SAAS,EACTC,gBAAgB,EAChBC,uBAAuB,EACvBC,gBAAgB,QAMX,sBAAqB;AAC5B,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,0BAA0B,QAAQ,0BAAsB;AACjE,SAASC,gBAAgB,QAAQ,oBAAgB;AACjD,SACEC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,EACxBC,YAAY,QACP,qBAAiB;AAExB;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,2BAA2B,KAAK;AAE7C,oCAAoC,GACpC,MAAMC,YAAY;AA8ElB;;;;;;;CAOC,GACD,eAAeC,YACbC,MAAyB,EACzBC,MAAc;IAEd,MAAMC,UAAUZ,cAAca,GAAG,GAAGC,SAAS,GAAGC,UAAU,CAAC,SAASC,GAAG,CAACL;IACxE,IAAID,WAAW,YAAY;QACzB,MAAMO,MAAM,MAAMZ,yBAAyBM,QAAQ;QACnD,OAAOL,aAAaW,KAAKN;IAC3B;IACA,OAAOC,QAAQG,UAAU,CAACL;AAC5B;AAEA,MAAMQ,SAAS,CAACC;IACd,IAAI,OAAOA,UAAU,UAAU,OAAOC,OAAOC,QAAQ,CAAC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,GACD,MAAMM,qBAAqB9C,YAAY,CAACN,QAAQuB,MAAM;IACtD,IAAIwB,UAAU;IACd,IAAIK,oBAAoB;QACtB;;;;;;;;;;;;;;KAcC,GACD,MAAMC,WAAW,MAAMrD,QAAQ4C,OAAO,CACnCrH,UAAU,CAAC,WACX+H,KAAK,CAAC,OAAO,MAAM,QACnBxE,GAAG;QACN,KAAK,MAAMtD,OAAO6H,SAASb,IAAI,CAAE;YAC/B,IAAIhB,QAAQiB,GAAG,CAACjH,IAAIsE,EAAE,GAAG;YACzB,sEAAsE;YACtE,oEAAoE;YACpE,mEAAmE;YACnE,0BAA0B;YAC1B,MAAM/C,QAAQ9C,sBAAsBuB,IAAIsD,GAAG,CAAC;YAC5C,MAAMF,MAAM7B,QAAQ5C,UAAU4C,SAAS;YACvC,IAAI6B,OAAO4C,QAAQiB,GAAG,CAAC7D,MAAM;YAC7B,MAAMpD,IAAIC,GAAG,CAAC8H,MAAM;YACpBR,WAAW;QACb;IACF;IAEA,MAAM/C,QAAQ4C,OAAO,CAACzE,GAAG,CACvB;QACEqF,MAAM;OAMFJ,qBAAqB;QAAEK,aAAajC,QAAQjD,IAAI;IAAC,IAAI,CAAC;QAC1DmF,iBAAiBxK,WAAWyK,eAAe;OACvCpD,SAAS;QAAEqD,kBAAkBrD;IAAO,IAAI;QAAEqD,kBAAkB;IAAK,IAEvE;QAAEC,OAAO;IAAK;IAGhB,OAAO;QACLhB,SAASrB,QAAQjD,IAAI;QACrBuE;QACAC;QACAzC;QACAC;QACAC,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/dynamic-list-materialize.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\n/**\n * Materializes a `kind: 'dynamic'` list's rule into its `members`\n * subcollection (`docs/specs/email-overhaul.md` §3b/§3e).\n *\n * A dynamic list does NOT resolve at send time. It stores a rule, a sweep\n * writes the matching people into the same `members` collection a manual list\n * uses, and the send path keeps reading one deterministic collection. Three\n * reasons, all of them things that have already gone wrong here:\n *\n * 1. The send must not run an unbounded scan — that is what produced an\n * arbitrary, unstable 500 of a site's 3,000 leads.\n * 2. The composer needs a cheap count, not a 5,000-document scan per\n * keystroke.\n * 3. \"Who did this campaign go to\" is a support question and a compliance\n * question. A materialized membership answers it; a rule re-evaluated\n * later does not.\n *\n * ## ⛔ A CEILING NEVER REMOVES A PERSON\n *\n * This function has no quota comparison and must never grow one. Capacity in\n * this product is enforced at the REDUCTION, not at the use: a limit that\n * refuses a person or their data leaks, because the person is already there\n * and dropping them is not a refusal, it is deletion. So a rule that matches\n * more people than a plan's audience band, or than a single send's recipient\n * cap, materializes ALL of them. The ceiling that a large audience meets is\n * `performCampaignSend`'s, which refuses the SEND and states the count it\n * found — a refusal the merchant can see, argue with, and act on, where a\n * trimmed membership is silent and unreproducible.\n *\n * What bounds this function is the per-run SCAN budget below, which is a\n * different thing: it bounds how much work one sweep does, and the cursor it\n * returns resumes the same sweep on the next run. Running out of budget\n * postpones enrollments; it never removes anybody, and it never finishes a\n * sweep it did not complete.\n */\n\nimport { FieldValue } from 'firebase-admin/firestore'\nimport type {\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n} from 'firebase-admin/firestore'\nimport {\n soloConsentGroup,\n candidateMatchesDynamicListRule,\n dynamicListRuleIsEmpty,\n dynamicListRuleListIds,\n dynamicListRuleWithoutListReference,\n dynamicListRuleNeedsContactFacet,\n dynamicListDimensionsForCrmView,\n dynamicListPlanningRule,\n CRM_COLLECTIONS,\n normalizeCrmViewFilters,\n type DynamicListDimensions,\n dynamicListRuleNeedsEngagement,\n extractEmailFromFields,\n seenOnlyThroughGrant,\n isContactLifecycleStage,\n normalizeContactEmail,\n normalizeDynamicListRule,\n personKey,\n readContainerIds,\n readContactContainerIds,\n readContactFacet,\n type ContactCustomValue,\n type DynamicListCandidate,\n type DynamicListRule,\n type DynamicListSource,\n type ResolvedSegmentFilters,\n} from '@aglyn/aglyn/server'\nimport { consentGroupHoldersInMotion } from '@aglyn/aglyn/app-utils/consent-group-change'\nimport { firebaseAdmin } from './firebase-admin'\nimport { readPersonEngagementByKeys } from './email-delivery-log'\nimport { enrollListMember } from './list-members'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n scopedToHost,\n} from './organizations'\n\n/**\n * Documents one sweep run may READ across all sources.\n *\n * A bound on work, not on membership. When a run exhausts it the sweep stops\n * where it is, returns `complete: false` with the cursor it reached, and the\n * next run continues — the shape the import-history sweep already uses. The\n * alternative, an unbounded scan of every silo per list per run, is the\n * expensive-read pattern this codebase refuses.\n *\n * ⚠️ Membership reconciliation is SKIPPED on an incomplete run. A partial\n * scan has only seen part of the population, so anybody it did not reach\n * would look like a non-match — and acting on that would delete real members\n * because a budget ran out.\n */\nexport const DYNAMIC_LIST_SCAN_BUDGET = 5_000\n\n/** Documents read per source page. */\nconst PAGE_SIZE = 500\n\n/**\n * ⚠️ THE DATE FIELDS THIS FILE READS, AND WHO WRITES THEM.\n *\n * `createdAfterMs`/`createdBeforeMs` are applied IN MEMORY against\n * `createdAt`, never as a Firestore `orderBy` or `where`. That distinction is\n * the whole safety property: an `orderBy` on a data field drops every document\n * missing it from the QUERY, invisibly, where an in-memory filter still reads\n * the document and merely decides it does not match. The paging order is\n * `__name__`, the one key every document has.\n *\n * The rule's decision for an undated record is to EXCLUDE it, so the writers\n * were checked rather than assumed — a silo with an unstamped writer would\n * quietly shrink every dated rule:\n *\n * - `leads` — `addHostLead` is the single writer and always stamps it.\n * - `siteMembers` — `membership-register.ts` is the only creator; the other\n * member routes read or update an existing document.\n * - `contacts` — `upsertHostContact`'s create path and the v1 API both stamp.\n * - `formSubmissions` — the submit route is the only creator; the v1 API and\n * the inbox reply route read.\n *\n * A new writer of any of those four must stamp `createdAt` or be added here.\n *\n * ## Campaign membership is read the same way — off the paged document\n *\n * `campaignIds` is applied in memory too, and for a second reason beyond the\n * one above: it is an ARRAY, so a Firestore `array-contains-any` could express\n * only the single-campaign case and would need a composite index the moment it\n * met any other filter in the rule. The membership is already on the document\n * this scan has read, on a submission at the top and on a contact inside the\n * reading holder's facet, so matching it costs nothing the page did not\n * already pay.\n */\n\n/** Where a partial sweep stopped, so the next run resumes rather than restarts. */\nexport interface DynamicListCursor {\n /** The source being scanned when the budget ran out. */\n source: DynamicListSource\n /** The last document id read from it. */\n afterId: string\n}\n\nexport interface MaterializeDynamicListResult {\n /** People the rule matched and that are now enrolled. */\n matched: number\n /** Rows created by this run. */\n enrolled: number\n /** Rule-owned rows removed because the person no longer matches. */\n removed: number\n /** False when the scan budget ran out — `cursor` says where to resume. */\n complete: boolean\n cursor: DynamicListCursor | null\n /**\n * True when the rule selects nobody by construction (no sources). Reported\n * rather than silently materializing an empty list, because an empty list\n * reads in the composer exactly like a rule that has not run yet.\n */\n empty: boolean\n}\n\n/** What a read-only pass over the silos found. */\nexport interface DynamicListScanResult {\n /** Matched people, de-duplicated across silos by their person key. */\n candidates: DynamicListCandidate[]\n /** False when the scan budget ran out — `cursor` says where to resume. */\n complete: boolean\n cursor: DynamicListCursor | null\n /**\n * True when the rule selects nobody by construction — no sources, or a\n * `segmentId` naming a segment that no longer exists.\n */\n empty: boolean\n /** Documents read, against the budget. */\n read: number\n}\n\n/**\n * The silo collections, as queries.\n *\n * `contacts` is org-scoped and must go through `scopedToHost` — the Admin SDK\n * does not evaluate rules, so an unfiltered read would let one site's list\n * materialize another site's contacts. The other three are host-owned and\n * carry no `visibleTo` to filter on.\n */\nasync function sourceQuery(\n source: DynamicListSource,\n hostId: string,\n): Promise<Query> {\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n if (source === 'contacts') {\n const ref = await orgDataCollectionForHost(hostId, 'contacts')\n return scopedToHost(ref, hostId)\n }\n return hostRef.collection(source)\n}\n\nconst millis = (value: unknown): number | null => {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n const toMillis = (value as { toMillis?: unknown } | null)?.toMillis\n if (typeof toMillis === 'function') {\n const parsed = Number(toMillis.call(value))\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\n/**\n * The CRM fields a rule may read, out of ONE holder's facet (AGL-2603).\n *\n * The owner, the stage, the company and the custom values are this holder's\n * business records on a shared row. They are read through `readContactFacet`\n * for the group the sweep runs as — never off the top of the document, where\n * a pre-facet row could still carry somebody's fields, and never out of\n * another group's facet. A field the facet does not carry is left ABSENT on\n * the candidate, which the matcher reads as \"does not match\" for the first\n * three and as \"unset\" for a custom clause; a stage the model does not name\n * is dropped for the reason the normalizer drops one from a rule.\n */\nfunction crmFieldsFromFacet(\n data: Record<string, unknown>,\n groupId: string,\n): Pick<\n DynamicListCandidate,\n 'ownerUid' | 'lifecycleStage' | 'companyId' | 'custom' | 'lastEmailEngagementAtMs'\n> {\n const facet = readContactFacet(data, groupId)\n const custom =\n facet.custom && typeof facet.custom === 'object' && !Array.isArray(facet.custom)\n ? (facet.custom as Record<string, ContactCustomValue>)\n : undefined\n // The campaign engagement stamp (AGL-2616), on the same footing as the\n // owner: this holder's fact about the person, read out of this holder's\n // facet, absent when the webhook has never stamped one.\n const engaged = Number(facet.lastEmailEngagementAtMs ?? 0)\n return {\n ...(typeof facet.ownerUid === 'string' && facet.ownerUid\n ? { ownerUid: facet.ownerUid }\n : {}),\n ...(isContactLifecycleStage(facet.lifecycleStage)\n ? { lifecycleStage: facet.lifecycleStage }\n : {}),\n ...(typeof facet.companyId === 'string' && facet.companyId\n ? { companyId: facet.companyId }\n : {}),\n ...(custom ? { custom } : {}),\n ...(Number.isFinite(engaged) && engaged > 0\n ? { lastEmailEngagementAtMs: engaged }\n : {}),\n }\n}\n\n/**\n * Reads one silo document into the shape the rule matcher understands.\n *\n * @param groupId the consent group whose contact facet the campaign membership\n * and the CRM fields are read from, or `null` when the rule names none of\n * them and no group was resolved. A contact row is shared by every site in\n * the org and its membership, its owner, its stage, its company and its\n * custom values all live inside one holder's facet, so there is no\n * expression here that returns another holder's filing.\n */\nfunction toCandidate(\n source: DynamicListSource,\n doc: QueryDocumentSnapshot,\n groupId: string | null,\n): DynamicListCandidate | null {\n const data = doc.data() as Record<string, unknown>\n const email =\n source === 'formSubmissions'\n ? // A form does not guarantee a canonical email field, so this is the\n // same best-effort extraction the submissions route already uses to\n // decide whether a submission produces a contact at all.\n extractEmailFromFields(data['fields'] as Record<string, unknown>)\n : normalizeContactEmail(data['email'])\n if (!email) return null\n const createdAtMs = millis(data['createdAt'])\n return {\n silo: source,\n email,\n // `siteMembers` stores `displayName`; the rest store `name`. Reading only\n // `name` is what left every member campaign's merge tags blank.\n name:\n (typeof data['name'] === 'string' && data['name']) ||\n (typeof data['displayName'] === 'string' && data['displayName']) ||\n undefined,\n createdAtMs,\n ...(source === 'contacts'\n ? {\n tags: (data['tags'] as string[]) ?? [],\n sources: (data['sources'] as DynamicListCandidate['sources']) ?? {},\n ordersCount: Number(data['ordersCount'] ?? 0),\n ltvCents: Number(data['ltvCents'] ?? 0),\n lastPurchaseAtMs: millis(data['lastPurchaseAtMs']),\n // Inside the holder's facet, never the top of the document. A rule\n // with no facet clause resolves no group and reads nothing here,\n // which is what keeps the group lookup an opt-in cost.\n ...(groupId\n ? {\n campaignIds: readContactContainerIds(data, groupId, 'campaign'),\n ...crmFieldsFromFacet(data, groupId),\n }\n : {}),\n }\n : {}),\n ...(source === 'formSubmissions'\n ? {\n formName: String(data['formName'] ?? ''),\n // At the TOP of a submission, because a submission belongs to one\n // site — the same shape every other host resource carries it in.\n campaignIds: readContainerIds(data, 'campaign'),\n }\n : {}),\n }\n}\n\n/*==========================================\n * ENRICHMENT — the two dimensions the scan cannot read off a silo row.\n *\n * Engagement lives on `emailDeliveries/{personKey}` and list membership on\n * `orgs/{orgId}/lists/{listId}/members/{personKey}`. Both describe an ADDRESS\n * rather than a contact, a lead or a submission, so neither is in the\n * document the sweep just paged.\n *\n * Three properties, and each of them is a thing that could otherwise go\n * wrong here:\n *\n * 1. **KEYED reads, never queries.** `getAll` over document references. No\n * `where`, no `orderBy`, so no composite index, nothing that can be\n * truncated by a `limit`, and — the failure this codebase has hit\n * nineteen times — nothing that silently drops a document for missing\n * the field being ordered on.\n * 2. **Opt-in.** A rule with no engagement clause and no list reference\n * pays nothing at all. The cost belongs to the rules that ask for it,\n * not to every sweep.\n * 3. **Charged to the SAME scan budget.** Every enrichment read is counted\n * in `read`, so a rule that asks for engagement fills the budget faster\n * and its sweep simply takes more runs. The budget and the resume cursor\n * keep working exactly as they did; what changes is how much of the\n * budget one page costs.\n *=========================================*/\n\n/** What a rule needs looked up, resolved once per scan rather than per page. */\ninterface EnrichmentPlan {\n engagement: boolean\n /** `listId` → that list's `members` collection. */\n listMembers: Map<string, FirebaseFirestore.CollectionReference>\n}\n\n/**\n * Resolves what a rule needs enriched.\n *\n * A named list that no longer exists resolves to a collection with no\n * documents, which reads as \"nobody is a member\" — the same direction a\n * deleted `segmentId` takes, and the safe one: an `inListIds` naming a\n * deleted list selects nobody rather than everybody, and a `notInListIds`\n * naming one excludes nobody rather than the whole audience.\n */\nasync function planEnrichment(\n rule: DynamicListRule,\n hostId: string,\n): Promise<EnrichmentPlan> {\n const listIds = dynamicListRuleListIds(rule)\n const listMembers = new Map<string, FirebaseFirestore.CollectionReference>()\n if (listIds.length) {\n const lists = await orgDataCollectionForHost(hostId, 'lists')\n for (const listId of listIds) {\n listMembers.set(listId, lists.doc(listId).collection('members'))\n }\n }\n return { engagement: dynamicListRuleNeedsEngagement(rule), listMembers }\n}\n\n/** True when nothing needs looking up, so the page loop can skip the work. */\nfunction planIsEmpty(plan: EnrichmentPlan): boolean {\n return !plan.engagement && plan.listMembers.size === 0\n}\n\n/**\n * Fills the enrichment fields on one page's candidates.\n *\n * Keys are de-duplicated first: two silos can produce the same person on one\n * page, and looking them up twice would spend budget on an answer already in\n * hand.\n *\n * @returns how many documents were read, for the caller's budget.\n */\nasync function enrichCandidates(\n candidates: DynamicListCandidate[],\n plan: EnrichmentPlan,\n): Promise<number> {\n if (!candidates.length || planIsEmpty(plan)) return 0\n const keyed = new Map<string, DynamicListCandidate[]>()\n for (const candidate of candidates) {\n const key = personKey(candidate.email)\n if (!key) continue\n const held = keyed.get(key)\n if (held) held.push(candidate)\n else keyed.set(key, [candidate])\n }\n const keys = [...keyed.keys()]\n if (!keys.length) return 0\n const firestore = firebaseAdmin.app().firestore()\n let read = 0\n\n if (plan.engagement) {\n // The scan's own Firestore handle, passed rather than defaulted: the\n // rollup lives in another module with its own default, and two handles in\n // one sweep is two things a caller has to configure to reach one store.\n const engagement = await readPersonEngagementByKeys(keys, firestore)\n read += keys.length\n for (const [key, rows] of keyed) {\n const found = engagement.get(key)\n for (const candidate of rows) {\n candidate.lastOpenedAtMs = found?.lastOpenedAtMs ?? null\n candidate.lastClickedAtMs = found?.lastClickedAtMs ?? null\n }\n }\n }\n\n if (plan.listMembers.size) {\n // No pre-seeding of `listIds`. A candidate found on no list keeps the\n // field absent, and the matcher reads absent as \"on no list\" — see\n // `candidateMatchesDynamicListRule` for why that direction is the safe\n // one. Writing an empty array first would be a line saying the same thing\n // the matcher already says.\n for (const [listId, members] of plan.listMembers) {\n let snapshots: FirebaseFirestore.DocumentSnapshot[] = []\n try {\n snapshots = await firestore.getAll(\n ...keys.map((key) => members.doc(key)),\n )\n } catch (error) {\n // A failed membership lookup leaves every candidate reading as a\n // non-member of this list. That keeps an `inListIds` rule from\n // enrolling people it could not confirm, and it is the direction a\n // reader can recover from — the next sweep asks again.\n console.error('[dynamic-list] list membership lookup failed', listId, error)\n }\n read += keys.length\n for (const snapshot of snapshots) {\n if (!snapshot?.exists) continue\n for (const candidate of keyed.get(snapshot.id) ?? []) {\n candidate.listIds = [...(candidate.listIds ?? []), listId]\n }\n }\n }\n }\n\n return read\n}\n\n/**\n * WHO A RULE SELECTS, without writing anything.\n *\n * The scan and the enrollment used to be one function, so \"who would this\n * match\" could only be answered by materializing it. That is the wrong shape\n * for two callers that now exist: a merchant asking to see an audience before\n * committing to it, and a fixed list using the filters to FIND people to add.\n * Neither may write memberships as a side effect of a question.\n *\n * One scanner rather than two. Every subtlety here is a place a second\n * implementation would drift — the in-memory date filter (an `orderBy` on a\n * data field would DROP undated documents rather than merely not matching\n * them), the `__name__` paging order, `scopedToHost` on `contacts` and on\n * nothing else, and a deleted `segmentId` narrowing to nobody rather than\n * widening to everybody. `materializeDynamicList` reads this and then enrolls.\n *\n * NOTHING here writes, and nothing here compares a count against a limit.\n */\nexport async function collectDynamicListCandidates(options: {\n hostId: string\n rule: unknown\n resume?: DynamicListCursor | null\n nowMs?: number\n scanBudget?: number\n}): Promise<DynamicListScanResult> {\n const rule: DynamicListRule = normalizeDynamicListRule(options.rule)\n const nowMs = options.nowMs ?? Date.now()\n const budget = options.scanBudget ?? DYNAMIC_LIST_SCAN_BUDGET\n if (dynamicListRuleIsEmpty(rule)) {\n return { candidates: [], complete: true, cursor: null, empty: true, read: 0 }\n }\n\n // A saved segment's filters, resolved ONCE rather than per candidate.\n let segment: ResolvedSegmentFilters | null = null\n if (rule.segmentId) {\n const segments = await orgDataCollectionForHost(\n options.hostId,\n 'contactSegments',\n )\n const snapshot = await segments.doc(rule.segmentId).get()\n // A deleted segment narrows to nothing rather than widening to everybody:\n // a rule whose filter vanished must not start matching the whole org.\n if (!snapshot.exists) {\n return {\n candidates: [],\n complete: true,\n cursor: null,\n empty: true,\n read: 0,\n }\n }\n segment = {\n tags: (snapshot.get('tags') as string[]) ?? [],\n sources: (snapshot.get('sources') as ResolvedSegmentFilters['sources']) ?? [],\n }\n }\n\n /*\n * A saved VIEW's filters, resolved ONCE into this language (AGL-2617).\n *\n * The same two leans the segment takes, for the same reason: a view that\n * was deleted narrows to nothing, and so does one whose clauses this\n * language cannot carry — `dynamicListDimensionsForCrmView` names them\n * rather than dropping them, and dropping one would make the audience\n * wider than the view the merchant picked. The picker offers only views\n * that translate whole, so the second case is a view edited after the\n * rule named it, and a view of another section — a list of companies is\n * not an audience of people — reads the same way.\n */\n let view: DynamicListDimensions | null = null\n if (rule.viewId) {\n const views = await orgDataCollectionForHost(\n options.hostId,\n CRM_COLLECTIONS.views,\n )\n const snapshot = await views.doc(rule.viewId).get()\n const translation =\n snapshot.exists && snapshot.get('section') === 'contacts'\n ? dynamicListDimensionsForCrmView(\n normalizeCrmViewFilters(snapshot.get('filters')),\n )\n : null\n if (!translation || translation.unsupported.length) {\n return {\n candidates: [],\n complete: true,\n cursor: null,\n empty: true,\n read: 0,\n }\n }\n view = translation.dimensions\n }\n\n /*\n * Resolved once for the whole scan: it names collections, and re-resolving\n * the org for every page would be a read per page for an unchanging answer.\n * Planned with the view's dimensions beside the rule's: a view naming an\n * owner needs the facet exactly as a rule naming one does.\n */\n const planning = dynamicListPlanningRule(rule, view)\n const enrichment = await planEnrichment(planning, options.hostId)\n\n /*\n * THE HOLDER whose contact facet a campaign or CRM clause is read from.\n *\n * The same group the writers use — the sites declared to be one sender, or\n * this site alone — because a facet written under one group id and read\n * under another is a membership that silently matches nobody. Resolved once,\n * and only for a rule that names something the facet holds: a campaign, an\n * owner, a stage, a company or a custom field. A rule naming none of them\n * pays no org read at all, which is the shape the engagement and list\n * lookups already take.\n */\n let facetGroupId: string | null = null\n if (dynamicListRuleNeedsContactFacet(planning)) {\n const found = await getOrgForHost(options.hostId).catch(() => null)\n const org = (found?.org as Record<string, unknown> | undefined) ?? null\n /*\n * NOT WHILE THE FACETS MOVE (AGL-3320). A consent group change re-homes\n * this site's facets after its declaration flips, and until it finishes a\n * person's record may still sit under the old key — where this read,\n * keyed by the new group, finds nothing. A rule reads that absence as a\n * non-match, and a non-match is a removal. So the scan reports itself\n * incomplete and reads nothing: the materializer's own rule for a partial\n * view then enrolls nobody new and removes nobody, and the first sweep\n * after the change finishes reads every record where it landed.\n */\n if (consentGroupHoldersInMotion(org, options.hostId)) {\n return {\n candidates: [],\n complete: false,\n cursor: options.resume ?? null,\n empty: false,\n read: 0,\n }\n }\n facetGroupId = (await consentGroupForSite(options.hostId, org)).groupId\n }\n\n /** Matched people, de-duplicated across silos by their person key. */\n const matches = new Map<string, DynamicListCandidate>()\n let read = 0\n let cursor: DynamicListCursor | null = null\n let complete = true\n\n const ordered = rule.sources\n const resumeIndex = options.resume\n ? ordered.indexOf(options.resume.source)\n : -1\n\n scan: for (let index = 0; index < ordered.length; index += 1) {\n const source = ordered[index] as DynamicListSource\n // A resume skips the sources already finished and re-enters the one that\n // was interrupted at the id it stopped on.\n if (resumeIndex >= 0 && index < resumeIndex) continue\n let after = resumeIndex === index ? options.resume?.afterId ?? '' : ''\n const base = await sourceQuery(source, options.hostId)\n for (;;) {\n /*\n * Ordered by document id, and paged with a `startAfter` cursor.\n *\n * `orderBy(FieldPath.documentId())` rather than a data field on\n * purpose: an `orderBy` on a field DROPS every document missing it, and\n * these four collections have writers old enough that no data field is\n * guaranteed on every row. The id is on all of them, so this is a total\n * order that cannot silently omit a person — which is the whole point\n * of the exercise, since the defect being fixed is an unordered\n * `limit()` returning an arbitrary subset.\n */\n let page = base\n .orderBy(firebaseAdmin.firestore.FieldPath.documentId())\n .limit(PAGE_SIZE)\n if (after) page = page.startAfter(after)\n const snapshot = await page.get()\n if (snapshot.empty) break\n /*\n * The page is read into candidates FIRST, then enriched, then matched.\n *\n * A per-document match would mean a per-document enrichment lookup, and\n * the whole reason enrichment is affordable is that one page's people\n * are fetched in one `getAll`. Only candidates are enriched — a\n * document with no usable address is dropped by `toCandidate` before it\n * can cost a lookup.\n */\n const pageCandidates: DynamicListCandidate[] = []\n for (const doc of snapshot.docs) {\n read += 1\n after = doc.id\n // A contact another site SHARED with this one (AGL-3336) is seen\n // here, not held: it is never this site's audience.\n if (source === 'contacts' && seenOnlyThroughGrant(doc.data(), options.hostId)) continue\n const candidate = toCandidate(source, doc, facetGroupId)\n if (candidate) pageCandidates.push(candidate)\n }\n read += await enrichCandidates(pageCandidates, enrichment)\n for (const candidate of pageCandidates) {\n if (\n !candidateMatchesDynamicListRule(candidate, rule, {\n segment,\n view,\n nowMs,\n })\n ) {\n continue\n }\n const key = personKey(candidate.email)\n if (key && !matches.has(key)) matches.set(key, candidate)\n }\n if (read >= budget) {\n complete = false\n cursor = { source, afterId: after }\n break scan\n }\n if (snapshot.size < PAGE_SIZE) break\n }\n }\n\n\n return {\n candidates: [...matches.values()],\n complete,\n cursor,\n empty: false,\n read,\n }\n}\n\n/**\n * Re-evaluates one dynamic list and writes the result into its members.\n *\n * @param listRef `orgs/{orgId}/lists/{listId}` — the caller has proved it\n * exists and that it is `kind: 'dynamic'`.\n * @param hostId the site whose silos the rule draws from, and the scope the\n * org-owned contacts read is narrowed to.\n * @param resume a cursor from a previous incomplete run.\n */\nexport async function materializeDynamicList(options: {\n listRef: DocumentReference\n hostId: string\n rule: unknown\n resume?: DynamicListCursor | null\n nowMs?: number\n /**\n * The scan budget. Passed by NOTHING in production — it exists so the suite\n * can drive a sweep into an exhausted budget and require that it still\n * removes nobody. A guarantee that only holds at the production budget was\n * never that guarantee.\n */\n scanBudget?: number\n}): Promise<MaterializeDynamicListResult> {\n /*\n * The rule cannot refer to the list it materializes — see\n * `dynamicListRuleWithoutListReference` for the oscillation that produces,\n * and note that half of its beats are DELETIONS of rows this sweep created.\n * Stripped here rather than at authoring time because the rule outlives any\n * one form: an API caller, an import and a copied list would each need to\n * remember, and the sweep is the one place all of them arrive.\n */\n const rule = dynamicListRuleWithoutListReference(\n normalizeDynamicListRule(options.rule),\n options.listRef.id,\n )\n const scan = await collectDynamicListCandidates({\n hostId: options.hostId,\n rule,\n ...(options.resume ? { resume: options.resume } : {}),\n ...(options.nowMs !== undefined ? { nowMs: options.nowMs } : {}),\n ...(options.scanBudget !== undefined\n ? { scanBudget: options.scanBudget }\n : {}),\n })\n if (scan.empty) {\n return {\n matched: 0,\n enrolled: 0,\n removed: 0,\n complete: true,\n cursor: null,\n empty: true,\n }\n }\n const { complete, cursor } = scan\n /*\n * Re-keyed by person rather than carried as a Map across the seam.\n *\n * Reconciliation below asks `matches.has(key)` about a stored row's id and\n * about its address, so it needs the same key the scan de-duplicated on —\n * computed by the same function, from the same addresses.\n */\n const matches = new Map<string, DynamicListCandidate>()\n for (const candidate of scan.candidates) {\n const key = personKey(candidate.email)\n if (key) matches.set(key, candidate)\n }\n\n /*\n * Reconciliation is allowed only for a run that saw the WHOLE population:\n * one that started at the beginning AND finished.\n *\n * `complete` alone is not enough, and that is the trap. A run that RESUMES\n * from a cursor finishes the tail of the scan and reports `complete: true`\n * having examined only the tail — so its match set is the remainder, and\n * reconciling against it would delete every member found by the earlier\n * runs of the same sweep. That is a quota drop wearing the costume of a\n * membership change: nothing about it looks like a limit, and it removes\n * people for no reason but how the work was chunked.\n *\n * The cost is that a list whose population exceeds one run's scan budget\n * never reconciles, so somebody who stops matching stays enrolled until a\n * sweep fits in one run. That is the right way round: an over-full list is\n * a wrong count, which is recoverable, and a deleted enrollment destroys\n * the record that says the person asked to be there, which is not.\n */\n const sawWholePopulation = complete && !options.resume\n\n /*\n * WHO IS ALREADY HERE, read once (AGL-4121).\n *\n * Enrolling costs three reads and a write per person, and nearly everyone a\n * sweep matches was enrolled by the sweep before it, so an unchanged list\n * used to pay that for its whole membership every hour to rewrite each row\n * as it stood. What is held below lets `enrollListMember` settle those\n * people with no read and no write. It decides nothing itself: a person it\n * does not hold, a manual row the rule is about to take over, a row under a\n * legacy id, all go through the same enrollment they always did.\n *\n * A run that saw everybody is about to read the rule's rows to reconcile, so\n * it reads them here and reuses them. A partial run reconciles nothing and\n * its list may be far longer than this run's matches, so it reads only those\n * matches, one key each.\n */\n const members = options.listRef.collection('members')\n const readRuleRows = () => members.where('via', '==', 'rule').get()\n const ruleRowsBefore = sawWholePopulation ? await readRuleRows() : null\n const heldRows = new Map<string, DocumentSnapshot>()\n for (const doc of ruleRowsBefore?.docs ?? []) heldRows.set(doc.id, doc)\n if (!ruleRowsBefore && matches.size) {\n const rows = await options.listRef.firestore.getAll(\n ...[...matches.keys()].map((key) => members.doc(key)),\n )\n for (const row of rows) if (row.exists) heldRows.set(row.id, row)\n }\n\n let enrolled = 0\n let wrote = false\n for (const [key, candidate] of matches) {\n const heldRow = heldRows.get(key)\n const result = await enrollListMember({\n listRef: options.listRef,\n ...(heldRow ? { heldRow } : {}),\n // A group of one, and it costs nothing: the materializer passes NO\n // consent (see below), so the group decides only which site is recorded\n // as having captured the row.\n group: soloConsentGroup(options.hostId),\n email: candidate.email,\n ...(candidate.name ? { name: candidate.name } : {}),\n source: `rule:${candidate.silo}`,\n via: 'rule',\n /*\n * ⛔ NO CONSENT IS PASSED, EVER.\n *\n * Matching a rule is not consenting to anything — the person is here\n * because they bought something, filled in a form or hold an account,\n * and none of those is an opt-in. Stamping a basis from a rule match\n * would let any merchant manufacture consent for their whole contact\n * list by writing a rule that selects it, which is precisely the\n * inference the consent arc refused to make. Their real basis, if they\n * have one, is on their own record and the send-time join reads it\n * there.\n */\n })\n // A refusal is not a materialization failure: an unusable address and a\n // person whose row records a refusal are both simply not on this list,\n // and a rule that selected them does not overrule either.\n if (result.enrolled && result.created) enrolled += 1\n if (result.enrolled && !result.unchanged) wrote = true\n }\n\n let removed = 0\n if (sawWholePopulation) {\n /*\n * Reconciliation.\n *\n * Only rows this materializer created are eligible (`via === 'rule'`). A\n * row somebody enrolled by hand, or that an automation's `enrollList`\n * step wrote, stays on a dynamic list forever: it was put there by a\n * decision, and a rule that does not happen to select that person is not\n * a decision to remove them. Rows written before `via` existed carry no\n * `via` at all and are therefore never eligible either, which is the\n * conservative direction for a field introduced after the data.\n *\n * This is the one removal in this file and it is a MEMBERSHIP change —\n * the person stopped matching the rule. It is not a capacity decision and\n * there is no count in the condition.\n *\n * Read again only when the loop above wrote: then time has passed and\n * somebody's hand-enrollment may have taken a row off the rule meanwhile,\n * which this must see before it deletes. A loop that wrote nothing took no\n * time, so the rows above are the read this would have made.\n */\n const existing =\n ruleRowsBefore && !wrote ? ruleRowsBefore : await readRuleRows()\n for (const doc of existing.docs) {\n if (matches.has(doc.id)) continue\n // A row adopted under a legacy id is keyed by neither `personKey` nor\n // anything this sweep computed, so it is matched by ADDRESS as well\n // before being removed. Getting that wrong un-enrolls a person who\n // still matches the rule.\n const email = normalizeContactEmail(doc.get('email'))\n const key = email ? personKey(email) : null\n if (key && matches.has(key)) continue\n await doc.ref.delete()\n removed += 1\n }\n }\n\n await options.listRef.set(\n {\n kind: 'dynamic',\n // The count the composer reads instead of scanning. Written only by a\n // run that saw everybody, for the same reason reconciliation is: a\n // partial or resumed run measured a fraction, and publishing that as\n // the list's size would under-report the audience in the one place a\n // merchant checks it before sending.\n ...(sawWholePopulation ? { memberCount: matches.size } : {}),\n lastEvaluatedAt: FieldValue.serverTimestamp(),\n ...(cursor ? { evaluationCursor: cursor } : { evaluationCursor: null }),\n },\n { merge: true },\n )\n\n return {\n matched: matches.size,\n enrolled,\n removed,\n complete,\n cursor,\n empty: false,\n }\n}\n"],"names":["FieldValue","soloConsentGroup","candidateMatchesDynamicListRule","dynamicListRuleIsEmpty","dynamicListRuleListIds","dynamicListRuleWithoutListReference","dynamicListRuleNeedsContactFacet","dynamicListDimensionsForCrmView","dynamicListPlanningRule","CRM_COLLECTIONS","normalizeCrmViewFilters","dynamicListRuleNeedsEngagement","extractEmailFromFields","seenOnlyThroughGrant","isContactLifecycleStage","normalizeContactEmail","normalizeDynamicListRule","personKey","readContainerIds","readContactContainerIds","readContactFacet","consentGroupHoldersInMotion","firebaseAdmin","readPersonEngagementByKeys","enrollListMember","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","scopedToHost","DYNAMIC_LIST_SCAN_BUDGET","PAGE_SIZE","sourceQuery","source","hostId","hostRef","app","firestore","collection","doc","ref","millis","value","Number","isFinite","toMillis","parsed","call","crmFieldsFromFacet","data","groupId","facet","custom","Array","isArray","undefined","engaged","lastEmailEngagementAtMs","ownerUid","lifecycleStage","companyId","toCandidate","email","createdAtMs","silo","name","tags","sources","ordersCount","ltvCents","lastPurchaseAtMs","campaignIds","formName","String","planEnrichment","rule","listIds","listMembers","Map","length","lists","listId","set","engagement","planIsEmpty","plan","size","enrichCandidates","candidates","keyed","candidate","key","held","get","push","keys","read","rows","found","lastOpenedAtMs","lastClickedAtMs","members","snapshots","getAll","map","error","console","snapshot","exists","id","collectDynamicListCandidates","options","nowMs","Date","now","budget","scanBudget","complete","cursor","empty","segment","segmentId","segments","view","viewId","views","translation","unsupported","dimensions","planning","enrichment","facetGroupId","catch","org","resume","matches","ordered","resumeIndex","indexOf","scan","index","after","afterId","base","page","orderBy","FieldPath","documentId","limit","startAfter","pageCandidates","docs","has","values","materializeDynamicList","listRef","matched","enrolled","removed","sawWholePopulation","readRuleRows","where","ruleRowsBefore","heldRows","row","wrote","heldRow","result","group","via","created","unchanged","existing","delete","kind","memberCount","lastEvaluatedAt","serverTimestamp","evaluationCursor","merge"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AAOrD,SACEC,gBAAgB,EAChBC,+BAA+B,EAC/BC,sBAAsB,EACtBC,sBAAsB,EACtBC,mCAAmC,EACnCC,gCAAgC,EAChCC,+BAA+B,EAC/BC,uBAAuB,EACvBC,eAAe,EACfC,uBAAuB,EAEvBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,wBAAwB,EACxBC,SAAS,EACTC,gBAAgB,EAChBC,uBAAuB,EACvBC,gBAAgB,QAMX,sBAAqB;AAC5B,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC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259
259
|
update['seo.favicon'] = favicon.trim();
|
|
260
260
|
}
|
|
261
|
+
// The logos a create writes with its favicon, in the one request (AGL-4119).
|
|
262
|
+
// Not mirrored into any row; they ride this write so a new site's three
|
|
263
|
+
// fields land together, with no client write to wait on.
|
|
264
|
+
for (const field of [
|
|
265
|
+
'logoUrl',
|
|
266
|
+
'logoDarkUrl'
|
|
267
|
+
]){
|
|
268
|
+
if (!body || !(field in body)) continue;
|
|
269
|
+
const value = body[field];
|
|
270
|
+
if (typeof value !== 'string' || value.length > 2048) {
|
|
271
|
+
return {
|
|
272
|
+
error: 'A logo must be a link or a media reference.'
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
update[field] = value.trim();
|
|
276
|
+
}
|
|
261
277
|
return {
|
|
262
278
|
update: Object.keys(update).length ? update : null
|
|
263
279
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.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\n/**\n * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // The custom domain itself (AGL-3972), so a list shows the address the\n // site answers on rather than only its platform subdomain. Deleted, not\n // omitted, when the domain is released, for the merge reason the favicon\n // below gives.\n cname: hasCustomDomain(meta) ? String(meta?.cname).trim() : FieldValue.delete(),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/**\n * The host-document paths a membership row is derived from. A writer that\n * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the\n * rows are written by the Admin SDK at these writers and nowhere else, so a\n * change that skips the re-fan leaves every member's list on the old value\n * until something unrelated rewrites the row.\n */\nexport const PROJECTED_HOST_PATHS: readonly string[] = [\n 'displayName',\n 'subdomain',\n 'cname',\n 'seo.favicon',\n 'createdAt',\n]\n\n/** Whether a write that changed these paths owes the membership re-fan. */\nexport const changesProjectedHostFields = (paths: readonly string[]): boolean =>\n paths.some((path) => PROJECTED_HOST_PATHS.includes(path))\n\n/** The longest site name the console's Display name field accepts. */\nexport const HOST_DISPLAY_NAME_MAX = 200\n\n/**\n * The host-document update for a mirrored field a person changed in the\n * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.\n *\n * The console used to write `displayName` and `seo.favicon` from the browser\n * and then ping the server to re-fan the rows, chained on the write's\n * server acknowledgement. Under the multi-tab cache that acknowledgement can\n * take a minute (AGL-3806), and a page left in that minute, or a ping that\n * failed, left the rows on the old name for good. The server now writes the\n * field and re-fans in the same request, so the two cannot come apart.\n *\n * Answers `null` when the body names neither field (a plain re-fan), and an\n * error for a value the console would never send. A favicon of `''` is the\n * Remove button's clear, kept as `''` because that is what the card writes.\n */\nexport function projectedHostFieldsUpdate(\n body: Record<string, unknown> | null | undefined,\n): { update: Record<string, unknown> | null } | { error: string } {\n const update: Record<string, unknown> = {}\n if (body && 'displayName' in body) {\n const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : ''\n if (!name) return { error: 'A site needs a name.' }\n if (name.length > HOST_DISPLAY_NAME_MAX) {\n return { error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.` }\n }\n update['displayName'] = name\n }\n if (body && 'favicon' in body) {\n const favicon = body['favicon']\n if (typeof favicon !== 'string' || favicon.length > 2_048) {\n return { error: 'The favicon must be a link or a media reference.' }\n }\n update['seo.favicon'] = favicon.trim()\n }\n return { update: Object.keys(update).length ? update : null }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after\n * any write that changes one of `PROJECTED_HOST_PATHS`.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","String","delete","updatedAt","serverTimestamp","PROJECTED_HOST_PATHS","changesProjectedHostFields","paths","some","path","includes","HOST_DISPLAY_NAME_MAX","projectedHostFieldsUpdate","body","update","name","error","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","extraUids","uids","Set","filter","Boolean","deleteHostProjectionForUids"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AMiG,OAAO,IAAIC,IAAY;WACxBR,QAAQ3E,GAAG,CAAC,CAACiE,SAAWA,OAAOrD,GAAG;WAClCqE,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4BvE,QAAQ;WAAImE;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpBvE,MAAc,EACdmE,IAAuB;IAEvB,MAAMlG,KAAKJ;IACX,MAAM8E,cACJ1E,IACA;WAAI,IAAImG,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACrF,GAAG,CACpC,CAACc,MAAQ,CAAC+C;YACRA,MAAMlB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.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\n/**\n * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // The custom domain itself (AGL-3972), so a list shows the address the\n // site answers on rather than only its platform subdomain. Deleted, not\n // omitted, when the domain is released, for the merge reason the favicon\n // below gives.\n cname: hasCustomDomain(meta) ? String(meta?.cname).trim() : FieldValue.delete(),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/**\n * The host-document paths a membership row is derived from. A writer that\n * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the\n * rows are written by the Admin SDK at these writers and nowhere else, so a\n * change that skips the re-fan leaves every member's list on the old value\n * until something unrelated rewrites the row.\n */\nexport const PROJECTED_HOST_PATHS: readonly string[] = [\n 'displayName',\n 'subdomain',\n 'cname',\n 'seo.favicon',\n 'createdAt',\n]\n\n/** Whether a write that changed these paths owes the membership re-fan. */\nexport const changesProjectedHostFields = (paths: readonly string[]): boolean =>\n paths.some((path) => PROJECTED_HOST_PATHS.includes(path))\n\n/** The longest site name the console's Display name field accepts. */\nexport const HOST_DISPLAY_NAME_MAX = 200\n\n/**\n * The host-document update for a mirrored field a person changed in the\n * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.\n *\n * The console used to write `displayName` and `seo.favicon` from the browser\n * and then ping the server to re-fan the rows, chained on the write's\n * server acknowledgement. Under the multi-tab cache that acknowledgement can\n * take a minute (AGL-3806), and a page left in that minute, or a ping that\n * failed, left the rows on the old name for good. The server now writes the\n * field and re-fans in the same request, so the two cannot come apart.\n *\n * Answers `null` when the body names neither field (a plain re-fan), and an\n * error for a value the console would never send. A favicon of `''` is the\n * Remove button's clear, kept as `''` because that is what the card writes.\n */\nexport function projectedHostFieldsUpdate(\n body: Record<string, unknown> | null | undefined,\n): { update: Record<string, unknown> | null } | { error: string } {\n const update: Record<string, unknown> = {}\n if (body && 'displayName' in body) {\n const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : ''\n if (!name) return { error: 'A site needs a name.' }\n if (name.length > HOST_DISPLAY_NAME_MAX) {\n return { error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.` }\n }\n update['displayName'] = name\n }\n if (body && 'favicon' in body) {\n const favicon = body['favicon']\n if (typeof favicon !== 'string' || favicon.length > 2_048) {\n return { error: 'The favicon must be a link or a media reference.' }\n }\n update['seo.favicon'] = favicon.trim()\n }\n // The logos a create writes with its favicon, in the one request (AGL-4119).\n // Not mirrored into any row; they ride this write so a new site's three\n // fields land together, with no client write to wait on.\n for (const field of ['logoUrl', 'logoDarkUrl']) {\n if (!body || !(field in body)) continue\n const value = body[field]\n if (typeof value !== 'string' || value.length > 2_048) {\n return { error: 'A logo must be a link or a media reference.' }\n }\n update[field] = value.trim()\n }\n return { update: Object.keys(update).length ? update : null }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after\n * any write that changes one of `PROJECTED_HOST_PATHS`.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","String","delete","updatedAt","serverTimestamp","PROJECTED_HOST_PATHS","changesProjectedHostFields","paths","some","path","includes","HOST_DISPLAY_NAME_MAX","projectedHostFieldsUpdate","body","update","name","error","field","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","ext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B0C,WACxBC,KAAK,CAAC,IAAMC;IACjB;AACF;AAEA,sFAAsF,GACtF,OAAO,eAAeC,4BACpB/F,KAAa,EACb6B,GAAW;IAEX,MAAM9B,KAAKJ;IACX,MAAMe,UAAU,MAAMZ,WAAWC,IAAIC;IACrC,MAAM0E,cACJ3E,IACAW,QAAQK,GAAG,CAAC,CAACe,SAAW,CAAC+C;YACvBA,MAAMnB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAEJ;AAEA,qEAAqE,GACrE,OAAO,eAAekE,kCACpBhG,KAAa,EACb8B,MAAc,EACd;;;;GAIC,GACDmE,YAA+B,EAAE;IAEjC,MAAMlG,KAAKJ;IACX,MAAMgG,UAAU,MAAMnE,eAAezB,IAAIC;IACzC,MAAMkG,OAAO,IAAIC,IAAY;WACxBR,QAAQ5E,GAAG,CAAC,CAACkE,SAAWA,OAAOtD,GAAG;WAClCsE,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4BxE,QAAQ;WAAIoE;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpBxE,MAAc,EACdoE,IAAuB;IAEvB,MAAMnG,KAAKJ;IACX,MAAM+E,cACJ3E,IACA;WAAI,IAAIoG,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACtF,GAAG,CACpC,CAACc,MAAQ,CAACgD;YACRA,MAAMnB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
|
|
@@ -93,8 +93,9 @@ export declare function orgLeadsQueryForHost(hostId: string): Promise<{
|
|
|
93
93
|
*/
|
|
94
94
|
export declare function leadReadTokensForHost(hostId: string, group?: ConsentGroup): Promise<ScopeToken[]>;
|
|
95
95
|
/**
|
|
96
|
-
* The `visibleTo` a capture on this site stamps: the
|
|
97
|
-
*
|
|
96
|
+
* The `visibleTo` a capture on this site stamps: `['org']` where the org's
|
|
97
|
+
* CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent
|
|
98
|
+
* group's sites where the org keeps its sites apart.
|
|
98
99
|
*
|
|
99
100
|
* Widened by the capture, never by the lookup — a site that has never
|
|
100
101
|
* captured this person gains nothing by finding them, which is what keeps an
|
|
@@ -28,7 +28,7 @@ import { creditConversion } from "@aglyn/aglyn/plugin-manager/plugin-conversion-
|
|
|
28
28
|
import { notifyHostManagers } from "./notifications.js";
|
|
29
29
|
import { scheduleCapturedEmailCheck } from "./capture-email-check.js";
|
|
30
30
|
import firebaseAdmin from "./firebase-admin.js";
|
|
31
|
-
import { consentGroupForSite, orgDataCollectionForHost, scopedToHost } from "./organizations.js";
|
|
31
|
+
import { consentGroupForSite, getOrgForHost, orgDataCollectionForHost, scopedToHost } from "./organizations.js";
|
|
32
32
|
import { composeContactName, crmLeadListFields, crmReadTokens, crmScopeTokens } from "@aglyn/aglyn/server";
|
|
33
33
|
// The module path rather than the barrel, as `upsert-contact.ts` does: a spec
|
|
34
34
|
// that substitutes the barrel keeps the real rule for which group a grant is.
|
|
@@ -104,8 +104,9 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
104
104
|
return crmReadTokens(group != null ? group : await consentGroupForSite(hostId));
|
|
105
105
|
}
|
|
106
106
|
/**
|
|
107
|
-
* The `visibleTo` a capture on this site stamps: the
|
|
108
|
-
*
|
|
107
|
+
* The `visibleTo` a capture on this site stamps: `['org']` where the org's
|
|
108
|
+
* CRM default (`crmDefaultScopeOf`) is `'org'` — its default — and the consent
|
|
109
|
+
* group's sites where the org keeps its sites apart.
|
|
109
110
|
*
|
|
110
111
|
* Widened by the capture, never by the lookup — a site that has never
|
|
111
112
|
* captured this person gains nothing by finding them, which is what keeps an
|
|
@@ -113,8 +114,14 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
113
114
|
* existing lead union these in rather than replacing, exactly as
|
|
114
115
|
* `upsert-contact` does.
|
|
115
116
|
*/ export async function leadScopeForHost(hostId, org) {
|
|
116
|
-
|
|
117
|
-
|
|
117
|
+
var _ref;
|
|
118
|
+
var _this;
|
|
119
|
+
// The org document decides: a capture with none in hand reads it, rather
|
|
120
|
+
// than stamping the site alone for an org whose records belong to every
|
|
121
|
+
// site. An org that cannot be read stamps the site — never everyone.
|
|
122
|
+
const resolved = (_ref = org != null ? org : (_this = await getOrgForHost(hostId).catch(()=>null)) == null ? void 0 : _this.org) != null ? _ref : null;
|
|
123
|
+
const group = await consentGroupForSite(hostId, resolved);
|
|
124
|
+
return crmScopeTokens(resolved, group);
|
|
118
125
|
}
|
|
119
126
|
/**
|
|
120
127
|
* The lead for an address, wherever it currently lives.
|