@aglyn/plugins-outreach 1.0.0-beta.160 → 1.0.0-beta.162
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/README.md +4 -0
- package/package.json +13 -13
- package/src/lib/components/compliance-section.d.ts +3 -2
- package/src/lib/components/compliance-section.js +7 -2
- package/src/lib/components/compliance-section.js.map +1 -1
- package/src/lib/components/do-not-contact-domains.d.ts +29 -0
- package/src/lib/components/do-not-contact-domains.js +208 -0
- package/src/lib/components/do-not-contact-domains.js.map +1 -0
- package/src/lib/components/use-outreach-api.d.ts +5 -1
- package/src/lib/components/use-outreach-api.js +12 -0
- package/src/lib/components/use-outreach-api.js.map +1 -1
- package/src/lib/components/use-outreach-data.d.ts +8 -1
- package/src/lib/components/use-outreach-data.js +32 -0
- package/src/lib/components/use-outreach-data.js.map +1 -1
- package/src/lib/constants/api-routes.d.ts +5 -0
- package/src/lib/constants/api-routes.js +4 -0
- package/src/lib/constants/api-routes.js.map +1 -1
- package/src/lib/engine/do-not-contact-domain.d.ts +39 -0
- package/src/lib/engine/do-not-contact-domain.js +51 -0
- package/src/lib/engine/do-not-contact-domain.js.map +1 -0
- package/src/lib/engine/gates.d.ts +6 -1
- package/src/lib/engine/gates.js +12 -1
- package/src/lib/engine/gates.js.map +1 -1
- package/src/lib/engine/gateway-block.d.ts +31 -0
- package/src/lib/engine/gateway-block.js +54 -0
- package/src/lib/engine/gateway-block.js.map +1 -0
- package/src/lib/engine/index.d.ts +3 -0
- package/src/lib/engine/index.js +3 -0
- package/src/lib/engine/index.js.map +1 -1
- package/src/lib/engine/mailbox-health.d.ts +5 -0
- package/src/lib/engine/mailbox-health.js +12 -5
- package/src/lib/engine/mailbox-health.js.map +1 -1
- package/src/lib/engine/mailbox-notice.d.ts +46 -0
- package/src/lib/engine/mailbox-notice.js +64 -0
- package/src/lib/engine/mailbox-notice.js.map +1 -0
- package/src/lib/enrollment/enroll-people.js +6 -3
- package/src/lib/enrollment/enroll-people.js.map +1 -1
- package/src/lib/enrollment/gate-lookups.js +7 -3
- package/src/lib/enrollment/gate-lookups.js.map +1 -1
- package/src/lib/model/outreach-api.d.ts +23 -2
- package/src/lib/model/outreach-api.js.map +1 -1
- package/src/lib/model/outreach.types.d.ts +33 -1
- package/src/lib/model/outreach.types.js +11 -1
- package/src/lib/model/outreach.types.js.map +1 -1
- package/src/lib/routes/do-not-contact-routes.d.ts +35 -0
- package/src/lib/routes/do-not-contact-routes.js +92 -0
- package/src/lib/routes/do-not-contact-routes.js.map +1 -0
- package/src/lib/routes/enroll-routes.js +1 -0
- package/src/lib/routes/enroll-routes.js.map +1 -1
- package/src/lib/routes/enrollment-routes.js +13 -0
- package/src/lib/routes/enrollment-routes.js.map +1 -1
- package/src/lib/routes/platform-deps.d.ts +2 -1
- package/src/lib/routes/platform-deps.js +2 -1
- package/src/lib/routes/platform-deps.js.map +1 -1
- package/src/lib/routes/register-routes.js +8 -1
- package/src/lib/routes/register-routes.js.map +1 -1
- package/src/lib/routes/route-deps.d.ts +6 -0
- package/src/lib/routes/route-deps.js.map +1 -1
- package/src/lib/runtime/enrollment-events.d.ts +6 -2
- package/src/lib/runtime/enrollment-events.js +20 -3
- package/src/lib/runtime/enrollment-events.js.map +1 -1
- package/src/lib/runtime/mailbox-health-store.d.ts +1 -1
- package/src/lib/runtime/mailbox-health-store.js +17 -4
- package/src/lib/runtime/mailbox-health-store.js.map +1 -1
- package/src/lib/runtime/mailbox-notices.d.ts +39 -0
- package/src/lib/runtime/mailbox-notices.js +117 -0
- package/src/lib/runtime/mailbox-notices.js.map +1 -0
- package/src/lib/runtime/person-erasure.d.ts +4 -0
- package/src/lib/runtime/person-erasure.js.map +1 -1
- package/src/lib/runtime/platform-runtime-deps.js +32 -0
- package/src/lib/runtime/platform-runtime-deps.js.map +1 -1
- package/src/lib/runtime/runtime-deps.d.ts +38 -0
- package/src/lib/runtime/runtime-deps.js.map +1 -1
- package/src/lib/runtime/send-job.js +6 -6
- package/src/lib/runtime/send-job.js.map +1 -1
- package/src/lib/runtime/sync-job.d.ts +2 -0
- package/src/lib/runtime/sync-job.js +84 -15
- package/src/lib/runtime/sync-job.js.map +1 -1
- package/src/lib/runtime/timeline.d.ts +10 -1
- package/src/lib/runtime/timeline.js +23 -1
- package/src/lib/runtime/timeline.js.map +1 -1
- package/src/lib/runtime/unsubscribe-route.d.ts +1 -1
- package/src/lib/runtime/unsubscribe-route.js.map +1 -1
- package/src/lib/server.d.ts +1 -1
- package/src/lib/server.js +1 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/storage/do-not-contact-store.d.ts +28 -1
- package/src/lib/storage/do-not-contact-store.js +117 -9
- package/src/lib/storage/do-not-contact-store.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/sync-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { crmInboundExcerpt, emailAddressOf } from '@aglyn/aglyn/app-utils/crm-inbound'\nimport { outreachMessageIdHeader } from '../engine/compose'\nimport { readOutreachDeliveryReport } from '../engine/delivery-status'\nimport type { OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { effectiveOutreachWindow, postponeOutreachForAutoReply } from '../engine/schedule'\nimport {\n decideOutreachThread,\n type OutreachMessageClassification,\n type OutreachThreadDecision,\n} from '../engine/thread-classification'\nimport { outreachHeader, outreachThreadMessageFromGmail, type OutreachThreadMessage } from '../engine/thread-message'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { markOutreachMailboxReconnectRequired } from '../mailboxes/mailbox-transport'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n} from '../model/outreach.types'\nimport { addOutreachDoNotContact } from '../storage/do-not-contact-store'\nimport {\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport type { GmailClient } from '../transport/gmail-client'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { applyOutreachEvent, recordOutreachOptOut } from './enrollment-events'\nimport {\n applyOutreachMailboxHealth,\n emptyOutreachHealthDelta,\n type OutreachMailboxHealthDelta,\n} from './mailbox-health-store'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { markOutreachLeadWorking } from './lead-records'\nimport { fileOutreachEmail, fileOutreachTask } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * For each connected or paused mailbox, what came back since the last run —\n * read with `format=full`, turned into the engine's message shape and\n * classified by `decideOutreachThread`:\n *\n * - a REPLY stops the enrollment, files the message on the contact's\n * timeline (once per `Message-ID`, under the capture address's own id for\n * it) and gives the rep the task \"Reply from <name>\";\n * - an OUT-OF-OFFICE postpones the next step a working week from the reply;\n * - an OPT-OUT — a reply asking to be left alone, or a message to the\n * `+unsubscribe` address the `mailto:` names — puts the address on the\n * organization's do-not-contact list and off the site's `sales` topic,\n * and stops every open enrollment of it;\n * - a HARD BOUNCE stops the enrollment, files the address on the platform's\n * suppression list and the do-not-contact list.\n *\n * Four reads find those, each narrowed by Gmail rather than read in full:\n * the threads of this mailbox's enrollments that have new mail; delivery\n * reports outside those threads (a receiving server's own bounce), by\n * searching for the mail systems that send them; messages to the\n * unsubscribe address; and messages from the people this mailbox is\n * writing to, in a thread of their own.\n *\n * Every write it makes is idempotent — the do-not-contact list keeps its\n * first entry, a topic opt-out keeps its first moment, a timeline entry is\n * filed once per message — and the messages it handled are marked AFTER\n * their effects, on the enrollment and on the mailbox, so a run that dies\n * part-way repeats harmless work rather than skipping some. The mailbox's\n * health takes the run's bounces and complaints in one write at the end,\n * which is where it pauses itself.\n *==========================================*/\n\nexport { OUTREACH_SYNC_JOB_ID } from '../constants/runtime-jobs'\n\n/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */\nexport const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60_000\n\n/** How far a run reads back past the previous one, for mail Gmail indexed late. */\nexport const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60_000\n\n/** How long after its last send an enrollment's mail is still watched. */\nexport const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60_000\n\n/** The most pages of one search a run reads. */\nconst SEARCH_PAGES = 5\n/** Handled message ids a mailbox keeps, and an enrollment keeps. */\nconst MAILBOX_HANDLED_MAX = 500\nconst ENROLLMENT_HANDLED_MAX = 100\n/** Addresses in one `from:` search. */\nconst FROM_CHUNK = 15\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OutreachSyncReport {\n [key: string]: number\n mailboxes: number\n threads: number\n replies: number\n optOuts: number\n bounces: number\n postponed: number\n paused: number\n}\n\ninterface SyncContext {\n deps: OutreachRuntimeDeps\n firestore: Firestore\n orgId: string\n mailbox: OutreachMailbox\n client: GmailClient\n selfAddresses: string[]\n unsubscribeAddress: string | null\n sequences: Map<string, OutreachSequence | null>\n delta: OutreachMailboxHealthDelta\n report: OutreachSyncReport\n nowMs: number\n}\n\n/** Runs the sync job once — see the module note. */\nexport async function runOutreachSyncJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSyncReport> {\n const firestore = deps.firestore()\n const report: OutreachSyncReport = {\n mailboxes: 0,\n threads: 0,\n replies: 0,\n optOuts: 0,\n bounces: 0,\n postponed: 0,\n paused: 0,\n }\n const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get()\n const byOrg = new Map<string, OutreachMailbox[]>()\n for (const doc of all.docs) {\n const orgId = doc.ref.parent.parent?.id\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!orgId || !mailbox || (mailbox.status !== 'connected' && mailbox.status !== 'paused')) continue\n byOrg.set(orgId, [...(byOrg.get(orgId) ?? []), mailbox])\n }\n for (const [orgId, mailboxes] of byOrg) {\n if (deps.now() >= context.deadlineMs) break\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) continue\n for (const mailbox of mailboxes) {\n if (deps.now() >= context.deadlineMs) break\n try {\n await syncMailbox(deps, firestore, { orgId, mailbox, report, nowMs: context.nowMs })\n report.mailboxes += 1\n } catch (error) {\n // One mailbox's failure is its own; the next mailbox is read. A grant\n // Google refused is the mailbox's to reconnect.\n if (isReconnectRequired(error)) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',\n nowMs: context.nowMs,\n })\n }\n console.error('[outreach] syncing a mailbox failed', error)\n }\n }\n }\n return report\n}\n\n/** Every stub a search finds, a few pages deep. */\nasync function search(\n client: GmailClient,\n q: string,\n): Promise<Array<{ id: string; threadId: string }>> {\n const found: Array<{ id: string; threadId: string }> = []\n let pageToken: string | null = null\n for (let page = 0; page < SEARCH_PAGES; page += 1) {\n const list = await client.listMessages({ q, maxResults: 100, pageToken, includeSpamTrash: true })\n found.push(...list.messages.filter((message) => message.id))\n pageToken = list.nextPageToken\n if (!pageToken) break\n }\n return found\n}\n\nasync function syncMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: { orgId: string; mailbox: OutreachMailbox; report: OutreachSyncReport; nowMs: number },\n): Promise<void> {\n const { orgId, mailbox, report, nowMs } = input\n const opened = await deps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason !== 'not-configured') {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n }\n return\n }\n const unsubscribe = outreachUnsubscribeMailbox(mailbox.email)\n const context: SyncContext = {\n deps,\n firestore,\n orgId,\n mailbox,\n client: opened.client,\n selfAddresses: [\n mailbox.email,\n mailbox.sendAs,\n ...(mailbox.sendAsOptions ?? []).map((option) => option.email),\n ].filter(Boolean),\n unsubscribeAddress: unsubscribe?.address ?? null,\n sequences: new Map(),\n delta: emptyOutreachHealthDelta(),\n report,\n nowMs,\n }\n\n // The enrollments this mailbox is writing to, by thread and by address.\n const watched = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('mailboxId', '==', mailbox.id)\n .where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n .get()\n const byThread = new Map<string, OutreachEnrollment>()\n const byAddress = new Map<string, OutreachEnrollment>()\n for (const doc of watched.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment) continue\n for (const threadId of enrollment.gmailThreadIds) byThread.set(threadId, enrollment)\n const known = byAddress.get(enrollment.email)\n if (!known || (enrollment.lastSentAtMs ?? 0) > (known.lastSentAtMs ?? 0)) byAddress.set(enrollment.email, enrollment)\n }\n\n const sinceMs = Math.max(Number(mailbox.sync?.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS\n const after = `after:${Math.floor(sinceMs / 1000)}`\n // Every message this run or an earlier one handled outside an enrollment's\n // thread; one message is handled once however many searches find it.\n const handled = new Set(mailbox.sync?.handledMessageIds ?? [])\n const newlyHandled: string[] = []\n const markHandled = (id: string) => {\n if (handled.has(id)) return\n handled.add(id)\n newlyHandled.push(id)\n }\n const fresh = (stub: { id: string; threadId: string }) => !handled.has(stub.id) && !byThread.has(stub.threadId)\n\n // 1. The enrollments' own threads that have new mail.\n const inbound = await search(context.client, `${after} -from:me`)\n for (const threadId of new Set(inbound.map((stub) => stub.threadId))) {\n const enrollment = byThread.get(threadId)\n if (!enrollment) continue\n const thread = await context.client.getFullThread(threadId)\n report.threads += 1\n await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail))\n }\n\n // 2. Delivery reports outside those threads: a receiving server's bounce.\n for (const stub of await search(context.client, `${after} from:(mailer-daemon OR postmaster)`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const delivery = readOutreachDeliveryReport(message)\n if (delivery?.kind === 'hard') {\n for (const address of delivery.failedAddresses) {\n const enrollment = byAddress.get(address)\n if (enrollment) await applyMessages(context, enrollment, [message])\n }\n }\n markHandled(stub.id)\n }\n\n // 3. Messages to the unsubscribe address: whoever wrote asked to leave.\n if (unsubscribe) {\n for (const stub of await search(context.client, `${after} to:${unsubscribe.address}`)) {\n if (handled.has(stub.id)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: ['From'] })\n const from = emailAddressOf(metadata.headers.find((header) => header.name.toLowerCase() === 'from')?.value ?? '')\n const address = normalizeContactEmail(from)\n if (address && !context.selfAddresses.includes(address)) {\n const enrollment = byAddress.get(address) ?? null\n await recordOutreachOptOut(deps, {\n orgId,\n email: address,\n source: 'unsubscribe',\n enrollment,\n hostIds: enrollment ? [enrollment.hostId] : [],\n detail: 'Wrote to the unsubscribe address.',\n nowMs,\n })\n report.optOuts += 1\n }\n markHandled(stub.id)\n }\n }\n\n // 4. The people this mailbox writes to, answering in a thread of their own.\n const addresses = [...byAddress.keys()]\n for (let start = 0; start < addresses.length; start += FROM_CHUNK) {\n const chunk = addresses.slice(start, start + FROM_CHUNK)\n for (const stub of await search(context.client, `${after} from:(${chunk.join(' OR ')})`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const enrollment = byAddress.get(normalizeContactEmail(emailAddressOf(message.from)) ?? '')\n if (enrollment) await applyMessages(context, enrollment, [message])\n markHandled(stub.id)\n }\n }\n\n const paused = await applyOutreachMailboxHealth(deps, { orgId, mailboxId: mailbox.id, delta: context.delta })\n if (paused) report.paused += 1\n await mailboxRef(firestore, orgId, mailbox.id).update({\n sync: {\n throughMs: nowMs,\n handledMessageIds: [...(mailbox.sync?.handledMessageIds ?? []), ...newlyHandled].slice(-MAILBOX_HANDLED_MAX),\n },\n })\n}\n\n/** The sequence an enrollment runs through, read once per run. */\nasync function sequenceOf(context: SyncContext, sequenceId: string): Promise<OutreachSequence | null> {\n if (!context.sequences.has(sequenceId)) {\n const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get()\n context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined))\n }\n return context.sequences.get(sequenceId) ?? null\n}\n\n/** A message's `Message-ID` in header form, or `null` when it carries none. */\nconst messageIdOf = (message: OutreachThreadMessage) => outreachMessageIdHeader(outreachHeader(message, 'Message-ID'))\n\n/** A bounce's diagnostic with the recipient's address taken out of it. */\nexport function scrubbedOutreachDiagnostic(diagnostic: string | null, email: string): string | null {\n if (!diagnostic) return null\n const pattern = new RegExp(email.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi')\n return diagnostic.replace(pattern, 'the address')\n}\n\n/** Files a message the person wrote on their timeline. */\nasync function fileInbound(context: SyncContext, enrollment: OutreachEnrollment, message: OutreachThreadMessage) {\n const messageId = messageIdOf(message)\n if (!messageId) return\n await fileOutreachEmail(context.deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'inbound',\n subject: message.subject,\n from: emailAddressOf(message.from) ?? message.from,\n to: context.mailbox.sendAs || context.mailbox.email,\n messageId,\n inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),\n body: crmInboundExcerpt(message.textBody ?? message.snippet ?? '', message.htmlBody ?? ''),\n atMs: message.internalDateMs,\n byUid: '',\n })\n}\n\n/**\n * What the new messages of one enrollment mean, done: the effects first,\n * each idempotent, then the event and the handled ids in one transaction.\n */\nasync function applyMessages(\n context: SyncContext,\n enrollment: OutreachEnrollment,\n messages: readonly OutreachThreadMessage[],\n): Promise<void> {\n const { deps, firestore, report, nowMs } = context\n const decision: OutreachThreadDecision = decideOutreachThread({\n messages,\n recipient: enrollment.email,\n handledMessageIds: enrollment.syncedMessageIds ?? [],\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const freshIds = decision.classifications.map((classification) => classification.messageId).filter(Boolean)\n if (!freshIds.length) return\n const decidedBy: OutreachMessageClassification | null = decision.decidedBy\n const decidingMessage = decidedBy ? messages.find((message) => message.id === decidedBy.messageId) ?? null : null\n const lastSentMessageId = enrollment.messageIds[enrollment.messageIds.length - 1] ?? null\n\n for (const classification of decision.classifications) {\n const aboutRecipient =\n !classification.bounce?.recipients.length || classification.bounce.recipients.includes(enrollment.email)\n if (classification.kind === 'hard_bounce' && aboutRecipient) {\n context.delta.bounces.push({ atMs: classification.atMs || nowMs, messageId: lastSentMessageId })\n }\n if (classification.complaint) {\n context.delta.complaintAtMs = Math.max(context.delta.complaintAtMs ?? 0, classification.atMs || nowMs)\n }\n }\n\n let event: OutreachEnrollmentEvent | null = null\n let postponedTo: number | null = null\n switch (decision.outcome) {\n case 'opted_out': {\n if (decidingMessage) await fileInbound(context, enrollment, decidingMessage)\n await recordOutreachOptOut(deps, {\n orgId: context.orgId,\n email: enrollment.email,\n source: decidedBy?.evidence?.startsWith('To:') ? 'unsubscribe' : 'opt_out_reply',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: decidedBy?.evidence ?? null,\n nowMs,\n })\n report.optOuts += 1\n break\n }\n case 'replied': {\n if (decidingMessage) {\n await fileInbound(context, enrollment, decidingMessage)\n try {\n await fileOutreachTask(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `reply:${messageIdOf(decidingMessage) ?? decidingMessage.id}`,\n title: `Reply from ${enrollment.contactName || enrollment.email}`,\n notes: crmInboundExcerpt(decidingMessage.textBody ?? decidingMessage.snippet ?? '', decidingMessage.htmlBody ?? '').slice(0, 500),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: context.mailbox.connectedByUid,\n })\n } catch (error) {\n console.error('[outreach] the reply task could not be filed', error)\n }\n }\n // A lead somebody wrote back to is being worked (AGL-3234).\n if (enrollment.target === 'lead' && enrollment.leadId) {\n await markOutreachLeadWorking(firestore, { hostId: enrollment.hostId, leadId: enrollment.leadId })\n }\n context.delta.replies += 1\n event = { type: 'reply', atMs: decidedBy?.atMs || nowMs, detail: decidedBy?.evidence ?? null }\n report.replies += 1\n break\n }\n case 'bounced': {\n const diagnostic = scrubbedOutreachDiagnostic(decidedBy?.bounce?.diagnostic ?? decidedBy?.bounce?.status ?? null, enrollment.email)\n await deps.suppressBouncedEmail({ email: enrollment.email, hostId: enrollment.hostId })\n await addOutreachDoNotContact(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n reason: 'hard_bounce',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n event = { type: 'bounce', atMs: decidedBy?.atMs || nowMs, detail: diagnostic }\n report.bounces += 1\n break\n }\n case 'postpone': {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n postponedTo = postponeOutreachForAutoReply({\n nextDueAtMs: enrollment.nextDueAtMs,\n receivedAtMs: decidedBy?.atMs || nowMs,\n timeZone: context.mailbox.timezone,\n window: effectiveOutreachWindow(sequence?.settings.window, context.mailbox.window),\n random: deps.random,\n })\n break\n }\n default:\n break\n }\n\n const outcome = await applyOutreachEvent(firestore, {\n orgId: context.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: (current) => {\n const extra: Record<string, unknown> = {\n syncedMessageIds: [...(current.syncedMessageIds ?? []), ...freshIds].slice(-ENROLLMENT_HANDLED_MAX),\n }\n const waiting = current.status === 'active' || current.status === 'paused'\n if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {\n extra['nextDueAtMs'] = postponedTo\n }\n return extra\n },\n nowMs,\n })\n if (postponedTo !== null && outcome.enrollment?.nextDueAtMs === postponedTo) report.postponed += 1\n // The run's own view of the enrollment moves with it, so a second message\n // of it in this run is judged against what this one did.\n if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment)\n}\n"],"names":["normalizeContactEmail","crmInboundExcerpt","emailAddressOf","outreachMessageIdHeader","readOutreachDeliveryReport","effectiveOutreachWindow","postponeOutreachForAutoReply","decideOutreachThread","outreachHeader","outreachThreadMessageFromGmail","mailboxRef","markOutreachMailboxReconnectRequired","OUTREACH_COLLECTIONS","addOutreachDoNotContact","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","applyOutreachEvent","recordOutreachOptOut","applyOutreachMailboxHealth","emptyOutreachHealthDelta","markOutreachLeadWorking","fileOutreachEmail","fileOutreachTask","outreachUnsubscribeMailbox","OUTREACH_SYNC_JOB_ID","OUTREACH_SYNC_LOOKBACK_MS","OUTREACH_SYNC_OVERLAP_MS","OUTREACH_SYNC_WATCH_MS","SEARCH_PAGES","MAILBOX_HANDLED_MAX","ENROLLMENT_HANDLED_MAX","FROM_CHUNK","runOutreachSyncJob","deps","context","firestore","report","mailboxes","threads","replies","optOuts","bounces","postponed","paused","all","collectionGroup","get","byOrg","Map","doc","docs","orgId","ref","parent","id","mailbox","data","status","set","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","syncMailbox","nowMs","error","mailboxId","errorCode","code","console","search","client","q","found","pageToken","page","list","listMessages","maxResults","includeSpamTrash","push","messages","filter","message","nextPageToken","input","opened","openMailbox","ok","reason","unsubscribe","email","selfAddresses","sendAs","sendAsOptions","map","option","Boolean","unsubscribeAddress","address","sequences","delta","watched","where","byThread","byAddress","enrollment","known","threadId","gmailThreadIds","lastSentAtMs","sinceMs","Math","max","Number","sync","throughMs","after","floor","handled","Set","handledMessageIds","newlyHandled","markHandled","has","add","fresh","stub","inbound","thread","getFullThread","applyMessages","getFullMessage","delivery","kind","failedAddresses","metadata","getMessage","metadataHeaders","from","headers","find","header","name","toLowerCase","value","includes","source","hostIds","hostId","detail","addresses","keys","start","length","chunk","slice","join","update","sequenceOf","sequenceId","snapshot","undefined","messageIdOf","scrubbedOutreachDiagnostic","diagnostic","pattern","RegExp","replace","fileInbound","messageId","link","direction","subject","to","inReplyTo","body","textBody","snippet","htmlBody","atMs","internalDateMs","byUid","outcome","decision","recipient","syncedMessageIds","threadSubject","freshIds","classifications","classification","decidedBy","decidingMessage","lastSentMessageId","messageIds","aboutRecipient","bounce","recipients","complaint","complaintAtMs","event","postponedTo","evidence","startsWith","dedupeKey","title","contactName","notes","dueAtMs","assigneeUid","connectedByUid","target","leadId","type","suppressBouncedEmail","enrollmentId","sequence","nextDueAtMs","receivedAtMs","timeZone","timezone","window","settings","random","extra","current","waiting","Object","assign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,qCAAoC;AACtF,SAASC,uBAAuB,QAAQ,uBAAmB;AAC3D,SAASC,0BAA0B,QAAQ,+BAA2B;AAEtE,SAASC,uBAAuB,EAAEC,4BAA4B,QAAQ,wBAAoB;AAC1F,SACEC,oBAAoB,QAGf,qCAAiC;AACxC,SAASC,cAAc,EAAEC,8BAA8B,QAAoC,8BAA0B;AACrH,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SAASC,oCAAoC,QAAQ,oCAAgC;AACrF,SACEC,oBAAoB,QAIf,6BAAyB;AA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ins/outreach/src/lib/runtime/sync-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { isPublicMailboxDomain } from '@aglyn/aglyn/app-utils/crm'\nimport { crmInboundExcerpt, emailAddressOf } from '@aglyn/aglyn/app-utils/crm-inbound'\nimport { outreachMessageIdHeader } from '../engine/compose'\nimport { readOutreachDeliveryReport } from '../engine/delivery-status'\nimport { outreachEmailDomain } from '../engine/do-not-contact-domain'\nimport type { OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { isOutreachGatewayBlock, outreachGatewayBlockDetail } from '../engine/gateway-block'\nimport { effectiveOutreachWindow, postponeOutreachForAutoReply } from '../engine/schedule'\nimport {\n decideOutreachThread,\n type OutreachMessageClassification,\n type OutreachThreadDecision,\n} from '../engine/thread-classification'\nimport { outreachHeader, outreachThreadMessageFromGmail, type OutreachThreadMessage } from '../engine/thread-message'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n} from '../model/outreach.types'\nimport { addOutreachDoNotContact, addOutreachDoNotContactDomain } from '../storage/do-not-contact-store'\nimport {\n outreachEnrollmentLink,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport type { GmailClient } from '../transport/gmail-client'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { applyOutreachEvent, recordOutreachOptOut } from './enrollment-events'\nimport {\n applyOutreachMailboxHealth,\n emptyOutreachHealthDelta,\n type OutreachMailboxHealthDelta,\n} from './mailbox-health-store'\nimport { noteOutreachMailboxReconnectRequired } from './mailbox-notices'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { markOutreachLeadWorking } from './lead-records'\nimport { fileOutreachEmail, fileOutreachTask, markOutreachEmailDelivery } from './timeline'\nimport { outreachUnsubscribeMailbox } from './unsubscribe-link'\n\n/*==========================================\n * THE SYNC JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * For each connected or paused mailbox, what came back since the last run —\n * read with `format=full`, turned into the engine's message shape and\n * classified by `decideOutreachThread`:\n *\n * - a REPLY stops the enrollment, files the message on the contact's\n * timeline (once per `Message-ID`, under the capture address's own id for\n * it) and gives the rep the task \"Reply from <name>\";\n * - an OUT-OF-OFFICE postpones the next step a working week from the reply;\n * - an OPT-OUT — a reply asking to be left alone, or a message to the\n * `+unsubscribe` address the `mailto:` names — puts the address on the\n * organization's do-not-contact list and off the site's `sales` topic,\n * and stops every open enrollment of it;\n * - a HARD BOUNCE stops the enrollment, files the address on the platform's\n * suppression list and the do-not-contact list — and, when its diagnostic\n * reads as the domain's mail gateway refusing the sender rather than one\n * address being unknown (`engine/gateway-block`, AGL-3244), files the\n * DOMAIN on the do-not-contact list too, and says so on the enrollment.\n *\n * Every verdict a list takes is said on the record the person is as well\n * (AGL-3245): the lead and the contact carry `emailState` through the\n * platform's stamp, and a bounce or a complaint lands on the send's own\n * timeline entry, so a member reading the record sees what the runtime saw.\n *\n * Four reads find those, each narrowed by Gmail rather than read in full:\n * the threads of this mailbox's enrollments that have new mail; delivery\n * reports outside those threads (a receiving server's own bounce), by\n * searching for the mail systems that send them; messages to the\n * unsubscribe address; and messages from the people this mailbox is\n * writing to, in a thread of their own.\n *\n * Every write it makes is idempotent — the do-not-contact list keeps its\n * first entry, a topic opt-out keeps its first moment, a timeline entry is\n * filed once per message — and the messages it handled are marked AFTER\n * their effects, on the enrollment and on the mailbox, so a run that dies\n * part-way repeats harmless work rather than skipping some. The mailbox's\n * health takes the run's bounces and complaints in one write at the end,\n * which is where it pauses itself.\n *==========================================*/\n\nexport { OUTREACH_SYNC_JOB_ID } from '../constants/runtime-jobs'\n\n/** The furthest back a run reads: a mailbox's first run, or one that fell behind. */\nexport const OUTREACH_SYNC_LOOKBACK_MS = 7 * 24 * 60 * 60_000\n\n/** How far a run reads back past the previous one, for mail Gmail indexed late. */\nexport const OUTREACH_SYNC_OVERLAP_MS = 2 * 60 * 60_000\n\n/** How long after its last send an enrollment's mail is still watched. */\nexport const OUTREACH_SYNC_WATCH_MS = 45 * 24 * 60 * 60_000\n\n/** The most pages of one search a run reads. */\nconst SEARCH_PAGES = 5\n/** Handled message ids a mailbox keeps, and an enrollment keeps. */\nconst MAILBOX_HANDLED_MAX = 500\nconst ENROLLMENT_HANDLED_MAX = 100\n/** Addresses in one `from:` search. */\nconst FROM_CHUNK = 15\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OutreachSyncReport {\n [key: string]: number\n mailboxes: number\n threads: number\n replies: number\n optOuts: number\n bounces: number\n /** Hard bounces that read as a gateway block, each filing its domain (AGL-3244). */\n gatewayBlocks: number\n postponed: number\n paused: number\n}\n\ninterface SyncContext {\n deps: OutreachRuntimeDeps\n firestore: Firestore\n orgId: string\n mailbox: OutreachMailbox\n client: GmailClient\n selfAddresses: string[]\n unsubscribeAddress: string | null\n sequences: Map<string, OutreachSequence | null>\n delta: OutreachMailboxHealthDelta\n report: OutreachSyncReport\n nowMs: number\n}\n\n/** Runs the sync job once — see the module note. */\nexport async function runOutreachSyncJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSyncReport> {\n const firestore = deps.firestore()\n const report: OutreachSyncReport = {\n mailboxes: 0,\n threads: 0,\n replies: 0,\n optOuts: 0,\n bounces: 0,\n gatewayBlocks: 0,\n postponed: 0,\n paused: 0,\n }\n const all = await firestore.collectionGroup(OUTREACH_COLLECTIONS.mailboxes).get()\n const byOrg = new Map<string, OutreachMailbox[]>()\n for (const doc of all.docs) {\n const orgId = doc.ref.parent.parent?.id\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!orgId || !mailbox || (mailbox.status !== 'connected' && mailbox.status !== 'paused')) continue\n byOrg.set(orgId, [...(byOrg.get(orgId) ?? []), mailbox])\n }\n for (const [orgId, mailboxes] of byOrg) {\n if (deps.now() >= context.deadlineMs) break\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) continue\n for (const mailbox of mailboxes) {\n if (deps.now() >= context.deadlineMs) break\n try {\n await syncMailbox(deps, firestore, { orgId, mailbox, report, nowMs: context.nowMs })\n report.mailboxes += 1\n } catch (error) {\n // One mailbox's failure is its own; the next mailbox is read. A grant\n // Google refused is the mailbox's to reconnect.\n if (isReconnectRequired(error)) {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: error instanceof GmailTransportError ? error.code : 'invalid_grant',\n nowMs: context.nowMs,\n })\n }\n console.error('[outreach] syncing a mailbox failed', error)\n }\n }\n }\n return report\n}\n\n/** Every stub a search finds, a few pages deep. */\nasync function search(\n client: GmailClient,\n q: string,\n): Promise<Array<{ id: string; threadId: string }>> {\n const found: Array<{ id: string; threadId: string }> = []\n let pageToken: string | null = null\n for (let page = 0; page < SEARCH_PAGES; page += 1) {\n const list = await client.listMessages({ q, maxResults: 100, pageToken, includeSpamTrash: true })\n found.push(...list.messages.filter((message) => message.id))\n pageToken = list.nextPageToken\n if (!pageToken) break\n }\n return found\n}\n\nasync function syncMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: { orgId: string; mailbox: OutreachMailbox; report: OutreachSyncReport; nowMs: number },\n): Promise<void> {\n const { orgId, mailbox, report, nowMs } = input\n const opened = await deps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason !== 'not-configured') {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n }\n return\n }\n const unsubscribe = outreachUnsubscribeMailbox(mailbox.email)\n const context: SyncContext = {\n deps,\n firestore,\n orgId,\n mailbox,\n client: opened.client,\n selfAddresses: [\n mailbox.email,\n mailbox.sendAs,\n ...(mailbox.sendAsOptions ?? []).map((option) => option.email),\n ].filter(Boolean),\n unsubscribeAddress: unsubscribe?.address ?? null,\n sequences: new Map(),\n delta: emptyOutreachHealthDelta(),\n report,\n nowMs,\n }\n\n // The enrollments this mailbox is writing to, by thread and by address.\n const watched = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('mailboxId', '==', mailbox.id)\n .where('lastSentAtMs', '>=', nowMs - OUTREACH_SYNC_WATCH_MS)\n .get()\n const byThread = new Map<string, OutreachEnrollment>()\n const byAddress = new Map<string, OutreachEnrollment>()\n for (const doc of watched.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment) continue\n for (const threadId of enrollment.gmailThreadIds) byThread.set(threadId, enrollment)\n const known = byAddress.get(enrollment.email)\n if (!known || (enrollment.lastSentAtMs ?? 0) > (known.lastSentAtMs ?? 0)) byAddress.set(enrollment.email, enrollment)\n }\n\n const sinceMs = Math.max(Number(mailbox.sync?.throughMs) || 0, nowMs - OUTREACH_SYNC_LOOKBACK_MS) - OUTREACH_SYNC_OVERLAP_MS\n const after = `after:${Math.floor(sinceMs / 1000)}`\n // Every message this run or an earlier one handled outside an enrollment's\n // thread; one message is handled once however many searches find it.\n const handled = new Set(mailbox.sync?.handledMessageIds ?? [])\n const newlyHandled: string[] = []\n const markHandled = (id: string) => {\n if (handled.has(id)) return\n handled.add(id)\n newlyHandled.push(id)\n }\n const fresh = (stub: { id: string; threadId: string }) => !handled.has(stub.id) && !byThread.has(stub.threadId)\n\n // 1. The enrollments' own threads that have new mail.\n const inbound = await search(context.client, `${after} -from:me`)\n for (const threadId of new Set(inbound.map((stub) => stub.threadId))) {\n const enrollment = byThread.get(threadId)\n if (!enrollment) continue\n const thread = await context.client.getFullThread(threadId)\n report.threads += 1\n await applyMessages(context, enrollment, thread.messages.map(outreachThreadMessageFromGmail))\n }\n\n // 2. Delivery reports outside those threads: a receiving server's bounce.\n for (const stub of await search(context.client, `${after} from:(mailer-daemon OR postmaster)`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const delivery = readOutreachDeliveryReport(message)\n if (delivery?.kind === 'hard') {\n for (const address of delivery.failedAddresses) {\n const enrollment = byAddress.get(address)\n if (enrollment) await applyMessages(context, enrollment, [message])\n }\n }\n markHandled(stub.id)\n }\n\n // 3. Messages to the unsubscribe address: whoever wrote asked to leave.\n if (unsubscribe) {\n for (const stub of await search(context.client, `${after} to:${unsubscribe.address}`)) {\n if (handled.has(stub.id)) continue\n const metadata = await context.client.getMessage(stub.id, { metadataHeaders: ['From'] })\n const from = emailAddressOf(metadata.headers.find((header) => header.name.toLowerCase() === 'from')?.value ?? '')\n const address = normalizeContactEmail(from)\n if (address && !context.selfAddresses.includes(address)) {\n const enrollment = byAddress.get(address) ?? null\n await recordOutreachOptOut(deps, {\n orgId,\n email: address,\n source: 'unsubscribe',\n enrollment,\n hostIds: enrollment ? [enrollment.hostId] : [],\n detail: 'Wrote to the unsubscribe address.',\n nowMs,\n })\n report.optOuts += 1\n }\n markHandled(stub.id)\n }\n }\n\n // 4. The people this mailbox writes to, answering in a thread of their own.\n const addresses = [...byAddress.keys()]\n for (let start = 0; start < addresses.length; start += FROM_CHUNK) {\n const chunk = addresses.slice(start, start + FROM_CHUNK)\n for (const stub of await search(context.client, `${after} from:(${chunk.join(' OR ')})`)) {\n if (!fresh(stub)) continue\n const message = outreachThreadMessageFromGmail(await context.client.getFullMessage(stub.id))\n const enrollment = byAddress.get(normalizeContactEmail(emailAddressOf(message.from)) ?? '')\n if (enrollment) await applyMessages(context, enrollment, [message])\n markHandled(stub.id)\n }\n }\n\n const paused = await applyOutreachMailboxHealth(deps, { orgId, mailboxId: mailbox.id, delta: context.delta })\n if (paused) report.paused += 1\n await mailboxRef(firestore, orgId, mailbox.id).update({\n sync: {\n throughMs: nowMs,\n handledMessageIds: [...(mailbox.sync?.handledMessageIds ?? []), ...newlyHandled].slice(-MAILBOX_HANDLED_MAX),\n },\n })\n}\n\n/** The sequence an enrollment runs through, read once per run. */\nasync function sequenceOf(context: SyncContext, sequenceId: string): Promise<OutreachSequence | null> {\n if (!context.sequences.has(sequenceId)) {\n const snapshot = await outreachOrgCollection(context.firestore, context.orgId, 'sequences').doc(sequenceId).get()\n context.sequences.set(sequenceId, readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined))\n }\n return context.sequences.get(sequenceId) ?? null\n}\n\n/** A message's `Message-ID` in header form, or `null` when it carries none. */\nconst messageIdOf = (message: OutreachThreadMessage) => outreachMessageIdHeader(outreachHeader(message, 'Message-ID'))\n\n/** A bounce's diagnostic with the recipient's address taken out of it. */\nexport function scrubbedOutreachDiagnostic(diagnostic: string | null, email: string): string | null {\n if (!diagnostic) return null\n const pattern = new RegExp(email.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi')\n return diagnostic.replace(pattern, 'the address')\n}\n\n/** Files a message the person wrote on their timeline. */\nasync function fileInbound(context: SyncContext, enrollment: OutreachEnrollment, message: OutreachThreadMessage) {\n const messageId = messageIdOf(message)\n if (!messageId) return\n await fileOutreachEmail(context.deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'inbound',\n subject: message.subject,\n from: emailAddressOf(message.from) ?? message.from,\n to: context.mailbox.sendAs || context.mailbox.email,\n messageId,\n inReplyTo: outreachMessageIdHeader(outreachHeader(message, 'In-Reply-To')),\n body: crmInboundExcerpt(message.textBody ?? message.snippet ?? '', message.htmlBody ?? ''),\n atMs: message.internalDateMs,\n byUid: '',\n })\n}\n\n/**\n * What the new messages of one enrollment mean, done: the effects first,\n * each idempotent, then the event and the handled ids in one transaction.\n */\nasync function applyMessages(\n context: SyncContext,\n enrollment: OutreachEnrollment,\n messages: readonly OutreachThreadMessage[],\n): Promise<void> {\n const { deps, firestore, report, nowMs } = context\n const decision: OutreachThreadDecision = decideOutreachThread({\n messages,\n recipient: enrollment.email,\n handledMessageIds: enrollment.syncedMessageIds ?? [],\n selfAddresses: context.selfAddresses,\n unsubscribeAddress: context.unsubscribeAddress,\n threadSubject: enrollment.threadSubject,\n })\n const freshIds = decision.classifications.map((classification) => classification.messageId).filter(Boolean)\n if (!freshIds.length) return\n const decidedBy: OutreachMessageClassification | null = decision.decidedBy\n const decidingMessage = decidedBy ? messages.find((message) => message.id === decidedBy.messageId) ?? null : null\n const lastSentMessageId = enrollment.messageIds[enrollment.messageIds.length - 1] ?? null\n\n for (const classification of decision.classifications) {\n const aboutRecipient =\n !classification.bounce?.recipients.length || classification.bounce.recipients.includes(enrollment.email)\n if (classification.kind === 'hard_bounce' && aboutRecipient) {\n context.delta.bounces.push({ atMs: classification.atMs || nowMs, messageId: lastSentMessageId })\n }\n if (classification.complaint) {\n context.delta.complaintAtMs = Math.max(context.delta.complaintAtMs ?? 0, classification.atMs || nowMs)\n }\n }\n\n let event: OutreachEnrollmentEvent | null = null\n let postponedTo: number | null = null\n switch (decision.outcome) {\n case 'opted_out': {\n if (decidingMessage) await fileInbound(context, enrollment, decidingMessage)\n const complaint = decidedBy?.complaint === true\n await recordOutreachOptOut(deps, {\n orgId: context.orgId,\n email: enrollment.email,\n source: decidedBy?.evidence?.startsWith('To:') ? 'unsubscribe' : 'opt_out_reply',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: decidedBy?.evidence ?? null,\n nowMs,\n complaint,\n })\n // A reply that called the email spam marks the send it answered\n // (AGL-3245), as the campaign webhook would mark a reported one.\n if (complaint) {\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'complained',\n atMs: decidedBy?.atMs || nowMs,\n detail: decidedBy?.evidence ?? null,\n })\n }\n report.optOuts += 1\n break\n }\n case 'replied': {\n if (decidingMessage) {\n await fileInbound(context, enrollment, decidingMessage)\n try {\n await fileOutreachTask(deps, {\n orgId: context.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `reply:${messageIdOf(decidingMessage) ?? decidingMessage.id}`,\n title: `Reply from ${enrollment.contactName || enrollment.email}`,\n notes: crmInboundExcerpt(decidingMessage.textBody ?? decidingMessage.snippet ?? '', decidingMessage.htmlBody ?? '').slice(0, 500),\n kind: 'email',\n dueAtMs: nowMs,\n assigneeUid: context.mailbox.connectedByUid,\n })\n } catch (error) {\n console.error('[outreach] the reply task could not be filed', error)\n }\n }\n // A lead somebody wrote back to is being worked (AGL-3234).\n if (enrollment.target === 'lead' && enrollment.leadId) {\n await markOutreachLeadWorking(firestore, { hostId: enrollment.hostId, leadId: enrollment.leadId })\n }\n context.delta.replies += 1\n event = { type: 'reply', atMs: decidedBy?.atMs || nowMs, detail: decidedBy?.evidence ?? null }\n report.replies += 1\n break\n }\n case 'bounced': {\n const diagnostic = scrubbedOutreachDiagnostic(decidedBy?.bounce?.diagnostic ?? decidedBy?.bounce?.status ?? null, enrollment.email)\n await deps.suppressBouncedEmail({ email: enrollment.email, hostId: enrollment.hostId })\n await addOutreachDoNotContact(firestore, {\n orgId: context.orgId,\n email: enrollment.email,\n reason: 'hard_bounce',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n let detail = diagnostic\n // A gateway block is the domain's verdict on the sender (AGL-3244):\n // the domain is filed beside the address, and the enrollment says so.\n // Never a public mailbox provider's domain — Gmail refusing one\n // message on policy is not a reason to stop writing to Gmail.\n const domain = outreachEmailDomain(enrollment.email)\n const gateway = isOutreachGatewayBlock(decidedBy?.bounce ?? null)\n if (domain && !isPublicMailboxDomain(domain) && gateway) {\n await addOutreachDoNotContactDomain(firestore, {\n orgId: context.orgId,\n domain,\n reason: 'gateway_block',\n source: 'runtime',\n nowMs,\n enrollmentId: enrollment.id,\n sequenceId: enrollment.sequenceId,\n detail: diagnostic,\n })\n detail = outreachGatewayBlockDetail(domain, diagnostic)\n report.gatewayBlocks += 1\n }\n const bouncedAtMs = decidedBy?.atMs || nowMs\n // The record the person is says so too (AGL-3245): the verdict on the\n // lead and the contact, and the bounce on the send's own timeline\n // entry, so the record reads Sent, then Bounced.\n await deps.stampRecordEmailState({\n orgId: context.orgId,\n email: enrollment.email,\n state: {\n status: gateway ? 'blocked' : 'bounced',\n atMs: bouncedAtMs,\n source: 'sequence',\n detail: diagnostic,\n enrollmentId: enrollment.id,\n },\n })\n await markOutreachEmailDelivery(deps, {\n orgId: context.orgId,\n messageId: lastSentMessageId,\n state: 'bounced',\n atMs: bouncedAtMs,\n detail: diagnostic,\n })\n event = { type: 'bounce', atMs: bouncedAtMs, detail }\n report.bounces += 1\n break\n }\n case 'postpone': {\n const sequence = await sequenceOf(context, enrollment.sequenceId)\n postponedTo = postponeOutreachForAutoReply({\n nextDueAtMs: enrollment.nextDueAtMs,\n receivedAtMs: decidedBy?.atMs || nowMs,\n timeZone: context.mailbox.timezone,\n window: effectiveOutreachWindow(sequence?.settings.window, context.mailbox.window),\n random: deps.random,\n })\n break\n }\n default:\n break\n }\n\n const outcome = await applyOutreachEvent(firestore, {\n orgId: context.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: (current) => {\n const extra: Record<string, unknown> = {\n syncedMessageIds: [...(current.syncedMessageIds ?? []), ...freshIds].slice(-ENROLLMENT_HANDLED_MAX),\n }\n const waiting = current.status === 'active' || current.status === 'paused'\n if (postponedTo !== null && waiting && current.nextDueAtMs !== null && postponedTo > current.nextDueAtMs) {\n extra['nextDueAtMs'] = postponedTo\n }\n return extra\n },\n nowMs,\n })\n if (postponedTo !== null && outcome.enrollment?.nextDueAtMs === postponedTo) report.postponed += 1\n // The run's own view of the enrollment moves with it, so a second message\n // of it in this run is judged against what this one did.\n if (outcome.enrollment) Object.assign(enrollment, outcome.enrollment)\n}\n"],"names":["normalizeContactEmail","isPublicMailboxDomain","crmInboundExcerpt","emailAddressOf","outreachMessageIdHeader","readOutreachDeliveryReport","outreachEmailDomain","isOutreachGatewayBlock","outreachGatewayBlockDetail","effectiveOutreachWindow","postponeOutreachForAutoReply","decideOutreachThread","outreachHeader","outreachThreadMessageFromGmail","mailboxRef","OUTREACH_COLLECTIONS","addOutreachDoNotContact","addOutreachDoNotContactDomain","outreachEnrollmentLink","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","applyOutreachEvent","recordOutreachOptOut","applyOutreachMailboxHealth","emptyOutreachHealthDelta","noteOutreachMailboxReconnectRequired","markOutreachLeadWorking","fileOutreachEmail","fileOutreachTask","markOutreachEmailDelivery","outreachUnsubscribeMailbox","OUTREACH_SYNC_JOB_ID","OUTREACH_SYNC_LOOKBACK_MS","OUTREACH_SYNC_OVERLAP_MS","OUTREACH_SYNC_WATCH_MS","SEARCH_PAGES","MAILBOX_HANDLED_MAX","ENROLLMENT_HANDLED_MAX","FROM_CHUNK","runOutreachSyncJob","deps","context","firestore","report","mailboxes","threads","replies","optOuts","bounces","gatewayBlocks","postponed","paused","all","collectionGroup","get","byOrg","Map","doc","docs","orgId","ref","parent","id","mailbox","data","status","set","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","syncMailbox","nowMs","error","mailboxId","errorCode","code","console","search","client","q","found","pageToken","page","list","listMessages","maxResults","includeSpamTrash","push","messages","filter","message","nextPageToken","input","opened","openMailbox","ok","reason","unsubscribe","email","selfAddresses","sendAs","sendAsOptions","map","option","Boolean","unsubscribeAddress","address","sequences","delta","watched","where","byThread","byAddress","enrollment","known","threadId","gmailThreadIds","lastSentAtMs","sinceMs","Math","max","Number","sync","throughMs","after","floor","handled","Set","handledMessageIds","newlyHandled","markHandled","has","add","fresh","stub","inbound","thread","getFullThread","applyMessages","getFullMessage","delivery","kind","failedAddresses","metadata","getMessage","metadataHeaders","from","headers","find","header","name","toLowerCase","value","includes","source","hostIds","hostId","detail","addresses","keys","start","length","chunk","slice","join","update","sequenceOf","sequenceId","snapshot","undefined","messageIdOf","scrubbedOutreachDiagnostic","diagnostic","pattern","RegExp","replace","fileInbound","messageId","link","direction","subject","to","inReplyTo","body","textBody","snippet","htmlBody","atMs","internalDateMs","byUid","outcome","decision","recipient","syncedMessageIds","threadSubject","freshIds","classifications","classification","decidedBy","decidingMessage","lastSentMessageId","messageIds","aboutRecipient","bounce","recipients","complaint","complaintAtMs","event","postponedTo","evidence","startsWith","state","dedupeKey","title","contactName","notes","dueAtMs","assigneeUid","connectedByUid","target","leadId","type","suppressBouncedEmail","enrollmentId","domain","gateway","bouncedAtMs","stampRecordEmailState","sequence","nextDueAtMs","receivedAtMs","timeZone","timezone","window","settings","random","extra","current","waiting","Object","assign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,qCAAoC;AACtF,SAASC,uBAAuB,QAAQ,uBAAmB;AAC3D,SAASC,0BAA0B,QAAQ,+BAA2B;AACtE,SAASC,mBAAmB,QAAQ,qCAAiC;AAErE,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,6BAAyB;AAC5F,SAASC,uBAAuB,EAAEC,4BAA4B,QAAQ,wBAAoB;AAC1F,SACEC,oBAAoB,QAGf,qCAAiC;AACxC,SAASC,cAAc,EAAEC,8BAA8B,QAAoC,8BAA0B;AACrH,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SACEC,oBAAoB,QAIf,6BAAyB;AAChC,SAASC,uBAAuB,EAAEC,6BAA6B,QA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AAQ7E,UAAU,EAAE8H,OAAOC,MAAM,CAAC/H,YAAY6E,QAAQ7E,UAAU;AACtE"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import type { PluginRecordLink, PluginRecordTaskKind, PluginRecordWrite } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline';
|
|
17
|
+
import type { PluginRecordDeliveryRequest, PluginRecordLink, PluginRecordTaskKind, PluginRecordWrite } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline';
|
|
18
18
|
import type { OutreachTaskKind } from '../model/outreach.types';
|
|
19
19
|
import type { OutreachRuntimeDeps } from './runtime-deps';
|
|
20
20
|
/**
|
|
@@ -50,6 +50,15 @@ export declare function fileOutreachEmail(deps: Pick<OutreachRuntimeDeps, 'timel
|
|
|
50
50
|
byUid: string;
|
|
51
51
|
byName?: string | null;
|
|
52
52
|
}): Promise<PluginRecordWrite | null>;
|
|
53
|
+
/**
|
|
54
|
+
* Marks a sent email bounced or reported on the record it was filed on
|
|
55
|
+
* (AGL-3245), so the timeline reads Sent, then Bounced, with what the
|
|
56
|
+
* server said. Answers `null` when the workspace keeps no records or its
|
|
57
|
+
* record system keeps no delivery state; never throws.
|
|
58
|
+
*/
|
|
59
|
+
export declare function markOutreachEmailDelivery(deps: Pick<OutreachRuntimeDeps, 'timeline'>, input: Omit<PluginRecordDeliveryRequest, 'messageId'> & {
|
|
60
|
+
messageId: string | null;
|
|
61
|
+
}): Promise<PluginRecordWrite | null>;
|
|
53
62
|
/**
|
|
54
63
|
* Files one task on a contact. Answers the record system's answer, `null`
|
|
55
64
|
* when the workspace keeps no records; a writer that THROWS is the caller's,
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import {
|
|
16
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
import { OUTREACH_PLUGIN_ID } from "../constants/bundle-common.js";
|
|
17
18
|
/**
|
|
18
19
|
* OUTREACH ON THE CONTACT'S TIMELINE (AGL-2981).
|
|
19
20
|
*
|
|
@@ -63,6 +64,27 @@
|
|
|
63
64
|
return null;
|
|
64
65
|
}
|
|
65
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Marks a sent email bounced or reported on the record it was filed on
|
|
69
|
+
* (AGL-3245), so the timeline reads Sent, then Bounced, with what the
|
|
70
|
+
* server said. Answers `null` when the workspace keeps no records or its
|
|
71
|
+
* record system keeps no delivery state; never throws.
|
|
72
|
+
*/ export async function markOutreachEmailDelivery(deps, input) {
|
|
73
|
+
const writer = deps.timeline();
|
|
74
|
+
if (!(writer == null ? void 0 : writer.recordEmailDelivery) || !input.messageId) return null;
|
|
75
|
+
try {
|
|
76
|
+
const written = await writer.recordEmailDelivery(_extends({}, input, {
|
|
77
|
+
messageId: input.messageId
|
|
78
|
+
}));
|
|
79
|
+
if (written.ok === false && written.status !== 404) {
|
|
80
|
+
console.warn(`[outreach] the record system did not mark the email ${input.state}: ${written.error}`);
|
|
81
|
+
}
|
|
82
|
+
return written;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
console.error('[outreach] marking an email on the record failed', error);
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
66
88
|
/**
|
|
67
89
|
* Files one task on a contact. Answers the record system's answer, `null`
|
|
68
90
|
* when the workspace keeps no records; a writer that THROWS is the caller's,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/timeline.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n PluginRecordLink,\n PluginRecordTaskKind,\n PluginRecordWrite,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { OUTREACH_PLUGIN_ID } from '../constants/bundle-common'\nimport type { OutreachTaskKind } from '../model/outreach.types'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\n\n/**\n * OUTREACH ON THE CONTACT'S TIMELINE (AGL-2981).\n *\n * Every email a sequence sends, every reply it reads, and every task it\n * asks of the rep goes onto the contact's record through the core's\n * record-timeline seam — whichever plugin keeps the workspace's records —\n * never by writing that plugin's documents. An email is filed once per\n * `Message-ID`, under the id the capture address would file a forwarded copy\n * by; a task once per the key given here.\n *\n * The timeline is bookkeeping beside the act: an email has already left\n * when it is filed, so a writer that refuses or fails is logged and the\n * send stands. A workspace with no record system files nothing.\n */\n\n/** The record system's word for a step's task kind. */\nexport const OUTREACH_TASK_KIND_TO_RECORD: Record<OutreachTaskKind, PluginRecordTaskKind> = {\n call: 'call',\n linkedin: 'todo',\n todo: 'todo',\n}\n\n/** Files one email on a person's record — the contact, or the lead while they are one (AGL-3234); never throws. */\nexport async function fileOutreachEmail(\n deps: Pick<OutreachRuntimeDeps, 'timeline'>,\n input: {\n orgId: string\n hostId: string\n /** The record the entry lands on: `{ contactId }` or `{ leadId }`. */\n link: PluginRecordLink\n direction: 'outbound' | 'inbound'\n subject: string\n from: string\n to: string | null\n messageId: string\n inReplyTo?: string | null\n body: string\n atMs: number\n byUid: string\n byName?: string | null\n },\n): Promise<PluginRecordWrite | null> {\n const writer = deps.timeline()\n if (!writer) return null\n try {\n const written = await writer.logActivity({\n orgId: input.orgId,\n hostId: input.hostId,\n link: input.link,\n sourcePluginId: OUTREACH_PLUGIN_ID,\n kind: 'email',\n atMs: input.atMs,\n body: input.body,\n byUid: input.byUid,\n byName: input.byName ?? null,\n email: {\n direction: input.direction,\n subject: input.subject,\n from: input.from,\n to: input.to,\n messageId: input.messageId,\n inReplyTo: input.inReplyTo ?? null,\n },\n })\n if (written.ok === false) console.warn(`[outreach] the record system did not file an email: ${written.error}`)\n return written\n } catch (error) {\n console.error('[outreach] filing an email on the record failed', error)\n return null\n }\n}\n\n/**\n * Files one task on a contact. Answers the record system's answer, `null`\n * when the workspace keeps no records; a writer that THROWS is the caller's,\n * which a step waits out rather than completing without its task.\n */\nexport async function fileOutreachTask(\n deps: Pick<OutreachRuntimeDeps, 'timeline'>,\n input: {\n orgId: string\n hostId: string\n /** The record the task lands on: `{ contactId }` or `{ leadId }`. */\n link: PluginRecordLink\n dedupeKey: string\n title: string\n notes?: string | null\n kind: PluginRecordTaskKind\n dueAtMs: number\n assigneeUid: string\n },\n): Promise<PluginRecordWrite | null> {\n const writer = deps.timeline()\n if (!writer) return null\n return writer.createTask({\n orgId: input.orgId,\n hostId: input.hostId,\n link: input.link,\n sourcePluginId: OUTREACH_PLUGIN_ID,\n dedupeKey: input.dedupeKey,\n title: input.title,\n notes: input.notes ?? null,\n kind: input.kind,\n dueAtMs: input.dueAtMs,\n assigneeUid: input.assigneeUid,\n createdByUid: '',\n })\n}\n"],"names":["OUTREACH_PLUGIN_ID","OUTREACH_TASK_KIND_TO_RECORD","call","linkedin","todo","fileOutreachEmail","deps","input","writer","timeline","written","logActivity","orgId","hostId","link","sourcePluginId","kind","atMs","body","byUid","byName","email","direction","subject","from","to","messageId","inReplyTo","ok","console","warn","error","fileOutreachTask","createTask","dedupeKey","title","notes","dueAtMs","assigneeUid","createdByUid"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/timeline.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n PluginRecordDeliveryRequest,\n PluginRecordLink,\n PluginRecordTaskKind,\n PluginRecordWrite,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { OUTREACH_PLUGIN_ID } from '../constants/bundle-common'\nimport type { OutreachTaskKind } from '../model/outreach.types'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\n\n/**\n * OUTREACH ON THE CONTACT'S TIMELINE (AGL-2981).\n *\n * Every email a sequence sends, every reply it reads, and every task it\n * asks of the rep goes onto the contact's record through the core's\n * record-timeline seam — whichever plugin keeps the workspace's records —\n * never by writing that plugin's documents. An email is filed once per\n * `Message-ID`, under the id the capture address would file a forwarded copy\n * by; a task once per the key given here.\n *\n * The timeline is bookkeeping beside the act: an email has already left\n * when it is filed, so a writer that refuses or fails is logged and the\n * send stands. A workspace with no record system files nothing.\n */\n\n/** The record system's word for a step's task kind. */\nexport const OUTREACH_TASK_KIND_TO_RECORD: Record<OutreachTaskKind, PluginRecordTaskKind> = {\n call: 'call',\n linkedin: 'todo',\n todo: 'todo',\n}\n\n/** Files one email on a person's record — the contact, or the lead while they are one (AGL-3234); never throws. */\nexport async function fileOutreachEmail(\n deps: Pick<OutreachRuntimeDeps, 'timeline'>,\n input: {\n orgId: string\n hostId: string\n /** The record the entry lands on: `{ contactId }` or `{ leadId }`. */\n link: PluginRecordLink\n direction: 'outbound' | 'inbound'\n subject: string\n from: string\n to: string | null\n messageId: string\n inReplyTo?: string | null\n body: string\n atMs: number\n byUid: string\n byName?: string | null\n },\n): Promise<PluginRecordWrite | null> {\n const writer = deps.timeline()\n if (!writer) return null\n try {\n const written = await writer.logActivity({\n orgId: input.orgId,\n hostId: input.hostId,\n link: input.link,\n sourcePluginId: OUTREACH_PLUGIN_ID,\n kind: 'email',\n atMs: input.atMs,\n body: input.body,\n byUid: input.byUid,\n byName: input.byName ?? null,\n email: {\n direction: input.direction,\n subject: input.subject,\n from: input.from,\n to: input.to,\n messageId: input.messageId,\n inReplyTo: input.inReplyTo ?? null,\n },\n })\n if (written.ok === false) console.warn(`[outreach] the record system did not file an email: ${written.error}`)\n return written\n } catch (error) {\n console.error('[outreach] filing an email on the record failed', error)\n return null\n }\n}\n\n/**\n * Marks a sent email bounced or reported on the record it was filed on\n * (AGL-3245), so the timeline reads Sent, then Bounced, with what the\n * server said. Answers `null` when the workspace keeps no records or its\n * record system keeps no delivery state; never throws.\n */\nexport async function markOutreachEmailDelivery(\n deps: Pick<OutreachRuntimeDeps, 'timeline'>,\n input: Omit<PluginRecordDeliveryRequest, 'messageId'> & { messageId: string | null },\n): Promise<PluginRecordWrite | null> {\n const writer = deps.timeline()\n if (!writer?.recordEmailDelivery || !input.messageId) return null\n try {\n const written = await writer.recordEmailDelivery({ ...input, messageId: input.messageId })\n if (written.ok === false && written.status !== 404) {\n console.warn(`[outreach] the record system did not mark the email ${input.state}: ${written.error}`)\n }\n return written\n } catch (error) {\n console.error('[outreach] marking an email on the record failed', error)\n return null\n }\n}\n\n/**\n * Files one task on a contact. Answers the record system's answer, `null`\n * when the workspace keeps no records; a writer that THROWS is the caller's,\n * which a step waits out rather than completing without its task.\n */\nexport async function fileOutreachTask(\n deps: Pick<OutreachRuntimeDeps, 'timeline'>,\n input: {\n orgId: string\n hostId: string\n /** The record the task lands on: `{ contactId }` or `{ leadId }`. */\n link: PluginRecordLink\n dedupeKey: string\n title: string\n notes?: string | null\n kind: PluginRecordTaskKind\n dueAtMs: number\n assigneeUid: string\n },\n): Promise<PluginRecordWrite | null> {\n const writer = deps.timeline()\n if (!writer) return null\n return writer.createTask({\n orgId: input.orgId,\n hostId: input.hostId,\n link: input.link,\n sourcePluginId: OUTREACH_PLUGIN_ID,\n dedupeKey: input.dedupeKey,\n title: input.title,\n notes: input.notes ?? null,\n kind: input.kind,\n dueAtMs: input.dueAtMs,\n assigneeUid: input.assigneeUid,\n createdByUid: '',\n })\n}\n"],"names":["OUTREACH_PLUGIN_ID","OUTREACH_TASK_KIND_TO_RECORD","call","linkedin","todo","fileOutreachEmail","deps","input","writer","timeline","written","logActivity","orgId","hostId","link","sourcePluginId","kind","atMs","body","byUid","byName","email","direction","subject","from","to","messageId","inReplyTo","ok","console","warn","error","markOutreachEmailDelivery","recordEmailDelivery","status","state","fileOutreachTask","createTask","dedupeKey","title","notes","dueAtMs","assigneeUid","createdByUid"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAQD,SAASA,kBAAkB,QAAQ,gCAA4B;AAI/D;;;;;;;;;;;;;CAaC,GAED,qDAAqD,GACrD,OAAO,MAAMC,+BAA+E;IAC1FC,MAAM;IACNC,UAAU;IACVC,MAAM;AACR,EAAC;AAED,iHAAiH,GACjH,OAAO,eAAeC,kBACpBC,IAA2C,EAC3CC,KAeC;IAED,MAAMC,SAASF,KAAKG,QAAQ;IAC5B,IAAI,CAACD,QAAQ,OAAO;IACpB,IAAI;YAUQD,eAOKA;QAhBf,MAAMG,UAAU,MAAMF,OAAOG,WAAW,CAAC;YACvCC,OAAOL,MAAMK,KAAK;YAClBC,QAAQN,MAAMM,MAAM;YACpBC,MAAMP,MAAMO,IAAI;YAChBC,gBAAgBf;YAChBgB,MAAM;YACNC,MAAMV,MAAMU,IAAI;YAChBC,MAAMX,MAAMW,IAAI;YAChBC,OAAOZ,MAAMY,KAAK;YAClBC,MAAM,GAAEb,gBAAAA,MAAMa,MAAM,YAAZb,gBAAgB;YACxBc,OAAO;gBACLC,WAAWf,MAAMe,SAAS;gBAC1BC,SAAShB,MAAMgB,OAAO;gBACtBC,MAAMjB,MAAMiB,IAAI;gBAChBC,IAAIlB,MAAMkB,EAAE;gBACZC,WAAWnB,MAAMmB,S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AAe;QACtBS,MAAMT,MAAMS,IAAI;QAChByB,SAASlC,MAAMkC,OAAO;QACtBC,aAAanC,MAAMmC,WAAW;QAC9BC,cAAc;IAChB;AACF"}
|
|
@@ -21,4 +21,4 @@ export declare function outreachUnsubscribePage(input: {
|
|
|
21
21
|
title: string;
|
|
22
22
|
body: string;
|
|
23
23
|
}, status?: number): Response;
|
|
24
|
-
export declare function createOutreachUnsubscribeRoute(deps: Pick<OutreachRuntimeDeps, 'firestore' | 'now' | 'optOutOfSalesTopic'>): PluginWebApiHandler;
|
|
24
|
+
export declare function createOutreachUnsubscribeRoute(deps: Pick<OutreachRuntimeDeps, 'firestore' | 'now' | 'optOutOfSalesTopic' | 'stampRecordEmailState'>): PluginWebApiHandler;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/unsubscribe-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { outreachOrgCollection, readStoredOutreachEnrollment } from '../storage/outreach-records'\nimport { recordOutreachOptOut } from './enrollment-events'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { readOutreachUnsubscribeToken } from './unsubscribe-link'\n\n/**\n * ONE-CLICK UNSUBSCRIBE (AGL-2981): `GET` and `POST /api/outreach/unsubscribe?t=…`.\n *\n * The link in every Outreach email's `List-Unsubscribe` header. A mailbox\n * provider POSTs it with `List-Unsubscribe=One-Click` and no person present\n * (RFC 8058); a mail client that opens it for a person sends a GET. BOTH\n * act, and both answer a plain page saying it is done.\n *\n * That GET acts is deliberate, and the opposite of the platform's newsletter\n * links. A person who used their mail client's Unsubscribe command has asked\n * already, and a second button would be a way out with a hurdle in it. The\n * one caller that could fetch the link without asking — a link scanner — can\n * only make a cold sequence stop writing to somebody, which is the direction\n * cold email should err in.\n *\n * No sign-in: the signature in the token is the authority, and a token that\n * does not verify changes nothing. It is registered as a recipient link, so\n * it answers whether or not Outreach is released to the organization now —\n * an opt-out outlives a paused rollout. Each act is idempotent: the link\n * used twice changes nothing the first use did not.\n *\n * What it records is what a reply saying \"stop\" records: the organization's\n * do-not-contact list, the site's `sales` topic, and every open enrollment\n * of the address stopped. An enrollment that no longer exists belongs to a\n * person or a workspace already erased, whose every site already refuses\n * them; the page says the same thing either way, and reveals nothing.\n */\n\nconst PAGE_HEADERS = {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'X-Robots-Tag': 'noindex',\n 'Referrer-Policy': 'no-referrer',\n}\n\nconst escapeHtml = (value: string) =>\n value.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`)\n\n/** The plain page both methods answer with. */\nexport function outreachUnsubscribePage(input: { title: string; body: string }, status = 200): Response {\n const html =\n '<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">' +\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">' +\n // The reader's own colors, light or dark: the page has no theme to take.\n '<meta name=\"color-scheme\" content=\"light dark\">' +\n `<title>${escapeHtml(input.title)}</title>` +\n '<style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;line-height:1.5}h1{font-size:1.5rem}</style>' +\n `</head><body><main><h1>${escapeHtml(input.title)}</h1><p>${escapeHtml(input.body)}</p></main></body></html>`\n return new Response(html, { status, headers: PAGE_HEADERS })\n}\n\nexport function createOutreachUnsubscribeRoute(\n deps: Pick<OutreachRuntimeDeps, 'firestore' | 'now' | 'optOutOfSalesTopic'>,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'GET' && request.method !== 'POST') {\n return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, POST' } })\n }\n const target = readOutreachUnsubscribeToken(new URL(request.url).searchParams.get('t'))\n if (!target) {\n return outreachUnsubscribePage(\n {\n title: 'This link doesn’t work',\n body: 'This unsubscribe link isn’t valid. To stop these emails, reply to one of them with “no”.',\n },\n 400,\n )\n }\n const firestore = deps.firestore()\n const snapshot = await outreachOrgCollection(firestore, target.orgId, 'enrollments').doc(target.enrollmentId).get()\n const enrollment = readStoredOutreachEnrollment(target.enrollmentId, snapshot.exists ? snapshot.data() : undefined)\n if (enrollment) {\n await recordOutreachOptOut(deps, {\n orgId: target.orgId,\n email: enrollment.email,\n source: 'unsubscribe',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: request.method === 'POST' ? 'One-click unsubscribe.' : 'Used the unsubscribe link.',\n nowMs: deps.now(),\n })\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, target.orgId).catch(() => null)\n const sender = settings?.brandName || settings?.legalName || 'The sender'\n return outreachUnsubscribePage({\n title: 'You’re unsubscribed',\n body: `${sender} won’t send you any more of these emails.`,\n })\n }\n}\n"],"names":["readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachEnrollment","recordOutreachOptOut","readOutreachUnsubscribeToken","PAGE_HEADERS","escapeHtml","value","replace","character","charCodeAt","outreachUnsubscribePage","input","status","html","title","body","Response","headers","createOutreachUnsubscribeRoute","deps","request","method","Allow","target","URL","url","searchParams","get","firestore","snapshot","orgId","doc","enrollmentId","enrollment","exists","data","undefined","email","source","hostIds","hostId","detail","nowMs","now","settings","catch","sender","brandName","legalName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,iCAAiC,QAAQ,0CAAsC;AACxF,SAASC,qBAAqB,EAAEC,4BAA4B,QAAQ,iCAA6B;AACjG,SAASC,oBAAoB,QAAQ,yBAAqB;AAE1D,SAASC,4BAA4B,QAAQ,wBAAoB;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,MAAMC,eAAe;IACnB,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,mBAAmB;AACrB;AAEA,MAAMC,aAAa,CAACC,QAClBA,MAAMC,OAAO,CAAC,YAAY,CAACC,YAAc,CAAC,EAAE,EAAEA,UAAUC,UAAU,CAAC,GAAG,CAAC,CAAC;AAE1E,6CAA6C,GAC7C,OAAO,SAASC,wBAAwBC,KAAsC,EAAEC,SAAS,GAAG;IAC1F,MAAMC,OACJ,gEACA,yEACA,yEAAyE;IACzE,oDACA,CAAC,OAAO,EAAER,WAAWM,MAAMG,KAAK,EAAE,QAAQ,CAAC,GAC3C,8IACA,CAAC,uBAAuB,EAAET,WAAWM,MAAMG,KAAK,EAAE,QAAQ,EAAET,WAAWM,MAAMI,IAAI,EAAE,yBAAyB,CAAC;IAC/G,OAAO,IAAIC,SAASH,MAAM;QAAED;QAAQK,SAASb;IAAa;AAC5D;AAEA,OAAO,SAASc,+BACdC,
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/unsubscribe-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { outreachOrgCollection, readStoredOutreachEnrollment } from '../storage/outreach-records'\nimport { recordOutreachOptOut } from './enrollment-events'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { readOutreachUnsubscribeToken } from './unsubscribe-link'\n\n/**\n * ONE-CLICK UNSUBSCRIBE (AGL-2981): `GET` and `POST /api/outreach/unsubscribe?t=…`.\n *\n * The link in every Outreach email's `List-Unsubscribe` header. A mailbox\n * provider POSTs it with `List-Unsubscribe=One-Click` and no person present\n * (RFC 8058); a mail client that opens it for a person sends a GET. BOTH\n * act, and both answer a plain page saying it is done.\n *\n * That GET acts is deliberate, and the opposite of the platform's newsletter\n * links. A person who used their mail client's Unsubscribe command has asked\n * already, and a second button would be a way out with a hurdle in it. The\n * one caller that could fetch the link without asking — a link scanner — can\n * only make a cold sequence stop writing to somebody, which is the direction\n * cold email should err in.\n *\n * No sign-in: the signature in the token is the authority, and a token that\n * does not verify changes nothing. It is registered as a recipient link, so\n * it answers whether or not Outreach is released to the organization now —\n * an opt-out outlives a paused rollout. Each act is idempotent: the link\n * used twice changes nothing the first use did not.\n *\n * What it records is what a reply saying \"stop\" records: the organization's\n * do-not-contact list, the site's `sales` topic, and every open enrollment\n * of the address stopped. An enrollment that no longer exists belongs to a\n * person or a workspace already erased, whose every site already refuses\n * them; the page says the same thing either way, and reveals nothing.\n */\n\nconst PAGE_HEADERS = {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'X-Robots-Tag': 'noindex',\n 'Referrer-Policy': 'no-referrer',\n}\n\nconst escapeHtml = (value: string) =>\n value.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`)\n\n/** The plain page both methods answer with. */\nexport function outreachUnsubscribePage(input: { title: string; body: string }, status = 200): Response {\n const html =\n '<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">' +\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">' +\n // The reader's own colors, light or dark: the page has no theme to take.\n '<meta name=\"color-scheme\" content=\"light dark\">' +\n `<title>${escapeHtml(input.title)}</title>` +\n '<style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;line-height:1.5}h1{font-size:1.5rem}</style>' +\n `</head><body><main><h1>${escapeHtml(input.title)}</h1><p>${escapeHtml(input.body)}</p></main></body></html>`\n return new Response(html, { status, headers: PAGE_HEADERS })\n}\n\nexport function createOutreachUnsubscribeRoute(\n deps: Pick<OutreachRuntimeDeps, 'firestore' | 'now' | 'optOutOfSalesTopic' | 'stampRecordEmailState'>,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'GET' && request.method !== 'POST') {\n return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, POST' } })\n }\n const target = readOutreachUnsubscribeToken(new URL(request.url).searchParams.get('t'))\n if (!target) {\n return outreachUnsubscribePage(\n {\n title: 'This link doesn’t work',\n body: 'This unsubscribe link isn’t valid. To stop these emails, reply to one of them with “no”.',\n },\n 400,\n )\n }\n const firestore = deps.firestore()\n const snapshot = await outreachOrgCollection(firestore, target.orgId, 'enrollments').doc(target.enrollmentId).get()\n const enrollment = readStoredOutreachEnrollment(target.enrollmentId, snapshot.exists ? snapshot.data() : undefined)\n if (enrollment) {\n await recordOutreachOptOut(deps, {\n orgId: target.orgId,\n email: enrollment.email,\n source: 'unsubscribe',\n enrollment,\n hostIds: [enrollment.hostId],\n detail: request.method === 'POST' ? 'One-click unsubscribe.' : 'Used the unsubscribe link.',\n nowMs: deps.now(),\n })\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, target.orgId).catch(() => null)\n const sender = settings?.brandName || settings?.legalName || 'The sender'\n return outreachUnsubscribePage({\n title: 'You’re unsubscribed',\n body: `${sender} won’t send you any more of these emails.`,\n })\n }\n}\n"],"names":["readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachEnrollment","recordOutreachOptOut","readOutreachUnsubscribeToken","PAGE_HEADERS","escapeHtml","value","replace","character","charCodeAt","outreachUnsubscribePage","input","status","html","title","body","Response","headers","createOutreachUnsubscribeRoute","deps","request","method","Allow","target","URL","url","searchParams","get","firestore","snapshot","orgId","doc","enrollmentId","enrollment","exists","data","undefined","email","source","hostIds","hostId","detail","nowMs","now","settings","catch","sender","brandName","legalName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,iCAAiC,QAAQ,0CAAsC;AACxF,SAASC,qBAAqB,EAAEC,4BAA4B,QAAQ,iCAA6B;AACjG,SAASC,oBAAoB,QAAQ,yBAAqB;AAE1D,SAASC,4BAA4B,QAAQ,wBAAoB;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,MAAMC,eAAe;IACnB,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,mBAAmB;AACrB;AAEA,MAAMC,aAAa,CAACC,QAClBA,MAAMC,OAAO,CAAC,YAAY,CAACC,YAAc,CAAC,EAAE,EAAEA,UAAUC,UAAU,CAAC,GAAG,CAAC,CAAC;AAE1E,6CAA6C,GAC7C,OAAO,SAASC,wBAAwBC,KAAsC,EAAEC,SAAS,GAAG;IAC1F,MAAMC,OACJ,gEACA,yEACA,yEAAyE;IACzE,oDACA,CAAC,OAAO,EAAER,WAAWM,MAAMG,KAAK,EAAE,QAAQ,CAAC,GAC3C,8IACA,CAAC,uBAAuB,EAAET,WAAWM,MAAMG,KAAK,EAAE,QAAQ,EAAET,WAAWM,MAAMI,IAAI,EAAE,yBAAyB,CAAC;IAC/G,OAAO,IAAIC,SAASH,MAAM;QAAED;QAAQK,SAASb;IAAa;AAC5D;AAEA,OAAO,SAASc,+BACdC,IAAqG;IAErG,OAAO,OAAOC;QACZ,IAAIA,QAAQC,MAAM,KAAK,SAASD,QAAQC,MAAM,KAAK,QAAQ;YACzD,OAAO,IAAIL,SAAS,sBAAsB;gBAAEJ,QAAQ;gBAAKK,SAAS;oBAAEK,OAAO;gBAAY;YAAE;QAC3F;QACA,MAAMC,SAASpB,6BAA6B,IAAIqB,IAAIJ,QAAQK,GAAG,EAAEC,YAAY,CAACC,GAAG,CAAC;QAClF,IAAI,CAACJ,QAAQ;YACX,OAAOb,wBACL;gBACEI,OAAO;gBACPC,MAAM;YACR,GACA;QAEJ;QACA,MAAMa,YAAYT,KAAKS,SAAS;QAChC,MAAMC,WAAW,MAAM7B,sBAAsB4B,WAAWL,OAAOO,KAAK,EAAE,eAAeC,GAAG,CAACR,OAAOS,YAAY,EAAEL,GAAG;QACjH,MAAMM,aAAahC,6BAA6BsB,OAAOS,YAAY,EAAEH,SAASK,MAAM,GAAGL,SAASM,IAAI,KAAKC;QACzG,IAAIH,YAAY;YACd,MAAM/B,qBAAqBiB,MAAM;gBAC/BW,OAAOP,OAAOO,KAAK;gBACnBO,OAAOJ,WAAWI,KAAK;gBACvBC,QAAQ;gBACRL;gBACAM,SAAS;oBAACN,WAAWO,MAAM;iBAAC;gBAC5BC,QAAQrB,QAAQC,MAAM,KAAK,SAAS,2BAA2B;gBAC/DqB,OAAOvB,KAAKwB,GAAG;YACjB;QACF;QACA,MAAMC,WAAW,MAAM7C,kCAAkC6B,WAAWL,OAAOO,KAAK,EAAEe,KAAK,CAAC,IAAM;QAC9F,MAAMC,SAASF,CAAAA,4BAAAA,SAAUG,SAAS,MAAIH,4BAAAA,SAAUI,SAAS,KAAI;QAC7D,OAAOtC,wBAAwB;YAC7BI,OAAO;YACPC,MAAM,GAAG+B,OAAO,yCAAyC,CAAC;QAC5D;IACF;AACF"}
|
package/src/lib/server.d.ts
CHANGED
|
@@ -50,4 +50,4 @@ export type { GmailClient, GmailFullThread, GmailMessageMetadata, GmailThread, }
|
|
|
50
50
|
export { buildRfc5322Message, encodeGmailRawMessage, LIST_UNSUBSCRIBE_ONE_CLICK, Rfc5322MessageError, type OutreachComposedMessage, type OutreachMailAddress, } from './transport/rfc5322';
|
|
51
51
|
export { sendComposedOutreachEmail, sendOutreachMessage, type OutreachSentMessage, type SendOutreachMessageOptions, } from './transport/send-message';
|
|
52
52
|
export { outreachComplianceSettingsRef, readOutreachComplianceSettingsDoc, writeOutreachComplianceSettings, type WriteOutreachComplianceSettingsInput, type WriteOutreachComplianceSettingsResult, } from './storage/compliance-settings-store';
|
|
53
|
-
export { addOutreachDoNotContact, getOutreachDoNotContactEntry, isOutreachDoNotContact, lookupOutreachDoNotContact, outreachDoNotContactCollection, readOutreachDoNotContactEntry, type AddOutreachDoNotContactInput, type AddOutreachDoNotContactResult, } from './storage/do-not-contact-store';
|
|
53
|
+
export { addOutreachDoNotContact, addOutreachDoNotContactDomain, getOutreachDoNotContactEntry, isOutreachDoNotContact, listOutreachDoNotContactDomains, lookupOutreachDoNotContact, lookupOutreachDoNotContactDomains, outreachDoNotContactCollection, outreachDoNotContactDomainCollection, readOutreachDoNotContactDomainEntry, readOutreachDoNotContactEntry, removeOutreachDoNotContactDomain, type AddOutreachDoNotContactDomainInput, type AddOutreachDoNotContactDomainResult, type AddOutreachDoNotContactInput, type AddOutreachDoNotContactResult, } from './storage/do-not-contact-store';
|
package/src/lib/server.js
CHANGED
|
@@ -97,6 +97,6 @@ export { sendComposedOutreachEmail, sendOutreachMessage } from "./transport/send
|
|
|
97
97
|
// the list is checked before every send, and a reply that opts out, an
|
|
98
98
|
// unsubscribe and a hard bounce each put the address on it.
|
|
99
99
|
export { outreachComplianceSettingsRef, readOutreachComplianceSettingsDoc, writeOutreachComplianceSettings } from "./storage/compliance-settings-store.js";
|
|
100
|
-
export { addOutreachDoNotContact, getOutreachDoNotContactEntry, isOutreachDoNotContact, lookupOutreachDoNotContact, outreachDoNotContactCollection, readOutreachDoNotContactEntry } from "./storage/do-not-contact-store.js";
|
|
100
|
+
export { addOutreachDoNotContact, addOutreachDoNotContactDomain, getOutreachDoNotContactEntry, isOutreachDoNotContact, listOutreachDoNotContactDomains, lookupOutreachDoNotContact, lookupOutreachDoNotContactDomains, outreachDoNotContactCollection, outreachDoNotContactDomainCollection, readOutreachDoNotContactDomainEntry, readOutreachDoNotContactEntry, removeOutreachDoNotContactDomain } from "./storage/do-not-contact-store.js";
|
|
101
101
|
|
|
102
102
|
//# sourceMappingURL=server.js.map
|
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/outreach/src/lib/server.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 * Outreach's SERVER half (AGL-2974), `@aglyn/plugins-outreach/server`.\n *\n * Every write to an `outreach*` collection is made here: the Firestore rules\n * refuse all of them to clients, so a mailbox, a sequence, an enrollment and a\n * credential only ever change through a handler registered below, behind the\n * session, entitlement and permission checks that handler makes.\n *\n * `outreach/ping` exists so the wiring is proven rather than assumed, as the\n * CRM's does: `plugins.config.json` names `registerOutreachConsoleApi` and the\n * `outreach` prefix, the generated server manifest loads this module, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler — after its\n * own gates, which already refuse a request while `release_outreach` is off\n * for the caller. A first real route that also had to be the first wiring\n * test would be two things to debug at once.\n *\n * A route that reads or writes org data resolves the caller the way the CRM's\n * org routes do (`resolveOrgMembership` / `memberHasOrgPermission` from\n * `@aglyn/tenant-data-admin`) and asks `checkEntitlement(org, 'outreach')`\n * and `outreach.use` before it touches a document.\n */\n\nimport {\n registerPluginApiRoute,\n registerPluginPermissions,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { OUTREACH_API_ROUTES } from './constants/api-routes'\nimport {\n OUTREACH_PERMISSIONS,\n OUTREACH_PLUGIN_ID,\n} from './constants/bundle-common'\nimport { registerOutreachMailboxRoutes } from './mailboxes/register-mailbox-routes'\nimport { registerOutreachRoutes } from './routes/register-routes'\n\n/**\n * No auth, no org, no data: it answers whether this server bundle was loaded\n * and its routes registered, which is a fact about the process rather than\n * about any workspace.\n */\nexport const outreachPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: OUTREACH_PLUGIN_ID })\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerOutreachConsoleApi(): void {\n // The server resolves plugin permission keys from this registry, so a\n // route's `outreach.use` check and the console's gate read the same tier\n // defaults.\n registerPluginPermissions(OUTREACH_PERMISSIONS)\n registerPluginApiRoute(OUTREACH_API_ROUTES.ping, outreachPingHandler)\n // Connect a Google mailbox, its settings, pause, test and disconnect\n // (AGL-2978).\n registerOutreachMailboxRoutes()\n // Compliance settings, sequences, enrollment and enrollment actions\n // (AGL-2980).\n registerOutreachRoutes()\n // The one-click unsubscribe every email carries (AGL-2981): a recipient\n // link, so it answers whether or not Outreach is released to the\n // organization now. Its module loads on the first request.\n registerPluginApiRoute(\n OUTREACH_API_ROUTES.unsubscribe,\n {\n web: async (request, context) =>\n (await import('./runtime/platform-runtime-deps')).platformOutreachUnsubscribeRoute()(request, context),\n },\n { recipientLink: true },\n )\n // A link in a tracked sequence email (AGL-3239): a recipient link for the\n // same reason, and more pressingly — a link already sitting in somebody's\n // inbox has to keep forwarding them whether or not the rollout is paused.\n registerPluginApiRoute(\n OUTREACH_API_ROUTES.click,\n {\n web: async (request, context) =>\n (await import('./runtime/platform-runtime-deps')).platformOutreachClickRoute()(request, context),\n },\n { recipientLink: true },\n )\n}\n\n// The transport the sending runtime reaches a connected mailbox through\n// (AGL-2978): open a mailbox's Gmail client, mark one reconnect-required,\n// send the engine's composed email through the one RFC 5322 writer, and read\n// a thread whole for the engine's reply and bounce classifier.\nexport {\n markOutreachMailboxReconnectRequired,\n openOutreachMailboxClient,\n type OpenedOutreachMailbox,\n} from './mailboxes/mailbox-transport'\nexport {\n GmailTransportError,\n isReconnectRequired,\n type GmailTransportErrorCode,\n} from './transport/gmail-errors'\nexport type {\n GmailClient,\n GmailFullThread,\n GmailMessageMetadata,\n GmailThread,\n} from './transport/gmail-client'\nexport {\n buildRfc5322Message,\n encodeGmailRawMessage,\n LIST_UNSUBSCRIBE_ONE_CLICK,\n Rfc5322MessageError,\n type OutreachComposedMessage,\n type OutreachMailAddress,\n} from './transport/rfc5322'\nexport {\n sendComposedOutreachEmail,\n sendOutreachMessage,\n type OutreachSentMessage,\n type SendOutreachMessageOptions,\n} from './transport/send-message'\n\n// The organization's compliance settings and do-not-contact list\n// (AGL-2980), for the sending runtime: the footer is read before every send,\n// the list is checked before every send, and a reply that opts out, an\n// unsubscribe and a hard bounce each put the address on it.\nexport {\n outreachComplianceSettingsRef,\n readOutreachComplianceSettingsDoc,\n writeOutreachComplianceSettings,\n type WriteOutreachComplianceSettingsInput,\n type WriteOutreachComplianceSettingsResult,\n} from './storage/compliance-settings-store'\nexport {\n addOutreachDoNotContact,\n getOutreachDoNotContactEntry,\n isOutreachDoNotContact,\n lookupOutreachDoNotContact,\n outreachDoNotContactCollection,\n readOutreachDoNotContactEntry,\n type AddOutreachDoNotContactInput,\n type AddOutreachDoNotContactResult,\n} from './storage/do-not-contact-store'\n"],"names":["registerPluginApiRoute","registerPluginPermissions","OUTREACH_API_ROUTES","OUTREACH_PERMISSIONS","OUTREACH_PLUGIN_ID","registerOutreachMailboxRoutes","registerOutreachRoutes","outreachPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","registerOutreachConsoleApi","ping","unsubscribe","web","request","context","platformOutreachUnsubscribeRoute","recipientLink","click","platformOutreachClickRoute","markOutreachMailboxReconnectRequired","openOutreachMailboxClient","GmailTransportError","isReconnectRequired","buildRfc5322Message","encodeGmailRawMessage","LIST_UNSUBSCRIBE_ONE_CLICK","Rfc5322MessageError","sendComposedOutreachEmail","sendOutreachMessage","outreachComplianceSettingsRef","readOutreachComplianceSettingsDoc","writeOutreachComplianceSettings","addOutreachDoNotContact","getOutreachDoNotContactEntry","isOutreachDoNotContact","lookupOutreachDoNotContact","outreachDoNotContactCollection","readOutreachDoNotContactEntry"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,SACEA,sBAAsB,EACtBC,yBAAyB,QAEpB,sBAAqB;AAC5B,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SACEC,oBAAoB,EACpBC,kBAAkB,QACb,+BAA2B;AAClC,SAASC,6BAA6B,QAAQ,yCAAqC;AACnF,SAASC,sBAAsB,QAAQ,8BAA0B;AAEjE;;;;CAIC,GACD,OAAO,MAAMC,sBAAwC,CAACC,KAAKC;IACzD,IAAID,IAAIE,MAAM,KAAK,OAAO;QACxBD,IAAIE,SAAS,CAAC,SAAS;QACvBF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;QACnD;IACF;IACAL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEE,IAAI;QAAMC,QAAQZ;IAAmB;AAC9D,EAAC;AAED,8EAA8E,GAC9E,OAAO,SAASa;IACd,sEAAsE;IACtE,yEAAyE;IACzE,YAAY;IACZhB,0BAA0BE;IAC1BH,uBAAuBE,oBAAoBgB,IAAI,EAAEX;IACjD,qEAAqE;IACrE,cAAc;IACdF;IACA,oEAAoE;IACpE,cAAc;IACdC;IACA,wEAAwE;IACxE,iEAAiE;IACjE,2DAA2D;IAC3DN,uBACEE,oBAAoBiB,WAAW,EAC/B;QACEC,KAAK,OAAOC,SAASC,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,qCAAiC,EAAGC,gCAAgC,GAAGF,SAASC;IAClG,GACA;QAAEE,eAAe;IAAK;IAExB,0EAA0E;IAC1E,0EAA0E;IAC1E,0EAA0E;IAC1ExB,uBACEE,oBAAoBuB,KAAK,EACzB;QACEL,KAAK,OAAOC,SAASC,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,qCAAiC,EAAGI,0BAA0B,GAAGL,SAASC;IAC5F,GACA;QAAEE,eAAe;IAAK;AAE1B;AAEA,wEAAwE;AACxE,0EAA0E;AAC1E,6EAA6E;AAC7E,+DAA+D;AAC/D,SACEG,oCAAoC,EACpCC,yBAAyB,QAEpB,mCAA+B;AACtC,SACEC,mBAAmB,EACnBC,mBAAmB,QAEd,8BAA0B;AAOjC,SACEC,mBAAmB,EACnBC,qBAAqB,EACrBC,0BAA0B,EAC1BC,mBAAmB,QAGd,yBAAqB;AAC5B,SACEC,yBAAyB,EACzBC,mBAAmB,QAGd,8BAA0B;AAEjC,iEAAiE;AACjE,6EAA6E;AAC7E,uEAAuE;AACvE,4DAA4D;AAC5D,SACEC,6BAA6B,EAC7BC,iCAAiC,EACjCC,+BAA+B,QAG1B,yCAAqC;AAC5C,SACEC,uBAAuB,EACvBC,4BAA4B,EAC5BC,sBAAsB,EACtBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,6BAA6B,
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/outreach/src/lib/server.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 * Outreach's SERVER half (AGL-2974), `@aglyn/plugins-outreach/server`.\n *\n * Every write to an `outreach*` collection is made here: the Firestore rules\n * refuse all of them to clients, so a mailbox, a sequence, an enrollment and a\n * credential only ever change through a handler registered below, behind the\n * session, entitlement and permission checks that handler makes.\n *\n * `outreach/ping` exists so the wiring is proven rather than assumed, as the\n * CRM's does: `plugins.config.json` names `registerOutreachConsoleApi` and the\n * `outreach` prefix, the generated server manifest loads this module, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler — after its\n * own gates, which already refuse a request while `release_outreach` is off\n * for the caller. A first real route that also had to be the first wiring\n * test would be two things to debug at once.\n *\n * A route that reads or writes org data resolves the caller the way the CRM's\n * org routes do (`resolveOrgMembership` / `memberHasOrgPermission` from\n * `@aglyn/tenant-data-admin`) and asks `checkEntitlement(org, 'outreach')`\n * and `outreach.use` before it touches a document.\n */\n\nimport {\n registerPluginApiRoute,\n registerPluginPermissions,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { OUTREACH_API_ROUTES } from './constants/api-routes'\nimport {\n OUTREACH_PERMISSIONS,\n OUTREACH_PLUGIN_ID,\n} from './constants/bundle-common'\nimport { registerOutreachMailboxRoutes } from './mailboxes/register-mailbox-routes'\nimport { registerOutreachRoutes } from './routes/register-routes'\n\n/**\n * No auth, no org, no data: it answers whether this server bundle was loaded\n * and its routes registered, which is a fact about the process rather than\n * about any workspace.\n */\nexport const outreachPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: OUTREACH_PLUGIN_ID })\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerOutreachConsoleApi(): void {\n // The server resolves plugin permission keys from this registry, so a\n // route's `outreach.use` check and the console's gate read the same tier\n // defaults.\n registerPluginPermissions(OUTREACH_PERMISSIONS)\n registerPluginApiRoute(OUTREACH_API_ROUTES.ping, outreachPingHandler)\n // Connect a Google mailbox, its settings, pause, test and disconnect\n // (AGL-2978).\n registerOutreachMailboxRoutes()\n // Compliance settings, sequences, enrollment and enrollment actions\n // (AGL-2980).\n registerOutreachRoutes()\n // The one-click unsubscribe every email carries (AGL-2981): a recipient\n // link, so it answers whether or not Outreach is released to the\n // organization now. Its module loads on the first request.\n registerPluginApiRoute(\n OUTREACH_API_ROUTES.unsubscribe,\n {\n web: async (request, context) =>\n (await import('./runtime/platform-runtime-deps')).platformOutreachUnsubscribeRoute()(request, context),\n },\n { recipientLink: true },\n )\n // A link in a tracked sequence email (AGL-3239): a recipient link for the\n // same reason, and more pressingly — a link already sitting in somebody's\n // inbox has to keep forwarding them whether or not the rollout is paused.\n registerPluginApiRoute(\n OUTREACH_API_ROUTES.click,\n {\n web: async (request, context) =>\n (await import('./runtime/platform-runtime-deps')).platformOutreachClickRoute()(request, context),\n },\n { recipientLink: true },\n )\n}\n\n// The transport the sending runtime reaches a connected mailbox through\n// (AGL-2978): open a mailbox's Gmail client, mark one reconnect-required,\n// send the engine's composed email through the one RFC 5322 writer, and read\n// a thread whole for the engine's reply and bounce classifier.\nexport {\n markOutreachMailboxReconnectRequired,\n openOutreachMailboxClient,\n type OpenedOutreachMailbox,\n} from './mailboxes/mailbox-transport'\nexport {\n GmailTransportError,\n isReconnectRequired,\n type GmailTransportErrorCode,\n} from './transport/gmail-errors'\nexport type {\n GmailClient,\n GmailFullThread,\n GmailMessageMetadata,\n GmailThread,\n} from './transport/gmail-client'\nexport {\n buildRfc5322Message,\n encodeGmailRawMessage,\n LIST_UNSUBSCRIBE_ONE_CLICK,\n Rfc5322MessageError,\n type OutreachComposedMessage,\n type OutreachMailAddress,\n} from './transport/rfc5322'\nexport {\n sendComposedOutreachEmail,\n sendOutreachMessage,\n type OutreachSentMessage,\n type SendOutreachMessageOptions,\n} from './transport/send-message'\n\n// The organization's compliance settings and do-not-contact list\n// (AGL-2980), for the sending runtime: the footer is read before every send,\n// the list is checked before every send, and a reply that opts out, an\n// unsubscribe and a hard bounce each put the address on it.\nexport {\n outreachComplianceSettingsRef,\n readOutreachComplianceSettingsDoc,\n writeOutreachComplianceSettings,\n type WriteOutreachComplianceSettingsInput,\n type WriteOutreachComplianceSettingsResult,\n} from './storage/compliance-settings-store'\nexport {\n addOutreachDoNotContact,\n addOutreachDoNotContactDomain,\n getOutreachDoNotContactEntry,\n isOutreachDoNotContact,\n listOutreachDoNotContactDomains,\n lookupOutreachDoNotContact,\n lookupOutreachDoNotContactDomains,\n outreachDoNotContactCollection,\n outreachDoNotContactDomainCollection,\n readOutreachDoNotContactDomainEntry,\n readOutreachDoNotContactEntry,\n removeOutreachDoNotContactDomain,\n type AddOutreachDoNotContactDomainInput,\n type AddOutreachDoNotContactDomainResult,\n type AddOutreachDoNotContactInput,\n type AddOutreachDoNotContactResult,\n} from './storage/do-not-contact-store'\n"],"names":["registerPluginApiRoute","registerPluginPermissions","OUTREACH_API_ROUTES","OUTREACH_PERMISSIONS","OUTREACH_PLUGIN_ID","registerOutreachMailboxRoutes","registerOutreachRoutes","outreachPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","registerOutreachConsoleApi","ping","unsubscribe","web","request","context","platformOutreachUnsubscribeRoute","recipientLink","click","platformOutreachClickRoute","markOutreachMailboxReconnectRequired","openOutreachMailboxClient","GmailTransportError","isReconnectRequired","buildRfc5322Message","encodeGmailRawMessage","LIST_UNSUBSCRIBE_ONE_CLICK","Rfc5322MessageError","sendComposedOutreachEmail","sendOutreachMessage","outreachComplianceSettingsRef","readOutreachComplianceSettingsDoc","writeOutreachComplianceSettings","addOutreachDoNotContact","addOutreachDoNotContactDomain","getOutreachDoNotContactEntry","isOutreachDoNotContact","listOutreachDoNotContactDomains","lookupOutreachDoNotContact","lookupOutreachDoNotContactDomains","outreachDoNotContactCollection","outreachDoNotContactDomainCollection","readOutreachDoNotContactDomainEntry","readOutreachDoNotContactEntry","removeOutreachDoNotContactDomain"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,SACEA,sBAAsB,EACtBC,yBAAyB,QAEpB,sBAAqB;AAC5B,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SACEC,oBAAoB,EACpBC,kBAAkB,QACb,+BAA2B;AAClC,SAASC,6BAA6B,QAAQ,yCAAqC;AACnF,SAASC,sBAAsB,QAAQ,8BAA0B;AAEjE;;;;CAI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6EAA6E;AAC7E,uEAAuE;AACvE,4DAA4D;AAC5D,SACEC,6BAA6B,EAC7BC,iCAAiC,EACjCC,+BAA+B,QAG1B,yCAAqC;AAC5C,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,4BAA4B,EAC5BC,sBAAsB,EACtBC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,iCAAiC,EACjCC,8BAA8B,EAC9BC,oCAAoC,EACpCC,mCAAmC,EACnCC,6BAA6B,EAC7BC,gCAAgC,QAK3B,oCAAgC"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type OutreachDoNotContactEntry, type OutreachDoNotContactReason, type OutreachDoNotContactSource } from '../model/outreach.types';
|
|
17
|
+
import { type OutreachDoNotContactDomainEntry, type OutreachDoNotContactEntry, type OutreachDoNotContactReason, type OutreachDoNotContactSource } from '../model/outreach.types';
|
|
18
18
|
/** The longest detail an entry keeps. */
|
|
19
19
|
export declare const OUTREACH_DO_NOT_CONTACT_DETAIL_MAX = 500;
|
|
20
20
|
/** `orgs/{orgId}/outreachDoNotContact`. */
|
|
@@ -58,3 +58,30 @@ export interface AddOutreachDoNotContactResult {
|
|
|
58
58
|
* anything.
|
|
59
59
|
*/
|
|
60
60
|
export declare function addOutreachDoNotContact(firestore: FirebaseFirestore.Firestore, input: AddOutreachDoNotContactInput): Promise<AddOutreachDoNotContactResult>;
|
|
61
|
+
/** `orgs/{orgId}/outreachDoNotContactDomains`. */
|
|
62
|
+
export declare function outreachDoNotContactDomainCollection(firestore: FirebaseFirestore.Firestore, orgId: string): FirebaseFirestore.CollectionReference;
|
|
63
|
+
/** A stored domain entry held to its shape, or `null` for a document that is not one. */
|
|
64
|
+
export declare function readOutreachDoNotContactDomainEntry(domain: string, data: Record<string, unknown> | undefined): OutreachDoNotContactDomainEntry | null;
|
|
65
|
+
/**
|
|
66
|
+
* Whether each address's DOMAIN is on the list, in one round trip, keyed by
|
|
67
|
+
* the address exactly as given: `true` or `false` per address, `null` for
|
|
68
|
+
* an address whose domain cannot be read off it and for every address when
|
|
69
|
+
* the read failed.
|
|
70
|
+
*/
|
|
71
|
+
export declare function lookupOutreachDoNotContactDomains(firestore: FirebaseFirestore.Firestore, orgId: string, emails: readonly string[]): Promise<Map<string, boolean | null>>;
|
|
72
|
+
/** Every domain on the list, alphabetically. */
|
|
73
|
+
export declare function listOutreachDoNotContactDomains(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<OutreachDoNotContactDomainEntry[]>;
|
|
74
|
+
export interface AddOutreachDoNotContactDomainInput extends Omit<AddOutreachDoNotContactInput, 'email'> {
|
|
75
|
+
/** The domain, or an address at it; spelled by `normalizeOutreachDomain`. */
|
|
76
|
+
domain: string;
|
|
77
|
+
}
|
|
78
|
+
export interface AddOutreachDoNotContactDomainResult {
|
|
79
|
+
domain: string;
|
|
80
|
+
/** False when the domain was on the list already; its entry is unchanged. */
|
|
81
|
+
created: boolean;
|
|
82
|
+
entry: OutreachDoNotContactDomainEntry;
|
|
83
|
+
}
|
|
84
|
+
/** Puts a domain on the list; a second add changes nothing. Throws for a value that is not a domain. */
|
|
85
|
+
export declare function addOutreachDoNotContactDomain(firestore: FirebaseFirestore.Firestore, input: AddOutreachDoNotContactDomainInput): Promise<AddOutreachDoNotContactDomainResult>;
|
|
86
|
+
/** Takes a domain off the list; answers whether it was on it. */
|
|
87
|
+
export declare function removeOutreachDoNotContactDomain(firestore: FirebaseFirestore.Firestore, orgId: string, value: string): Promise<boolean>;
|