@getvitops/utils 8.1.0 → 8.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +264 -8
  2. package/dist/{adc-BFrzpMHq.d.mts → adc-BoEoogyo.d.mts} +2 -3
  3. package/dist/adc-BoEoogyo.d.mts.map +1 -0
  4. package/dist/ads/index.d.mts +50 -17
  5. package/dist/ads/index.d.mts.map +1 -1
  6. package/dist/ads/index.mjs +75 -7
  7. package/dist/ads/index.mjs.map +1 -1
  8. package/dist/cloudflare-BiK61Oq4.d.mts.map +1 -1
  9. package/dist/color/index.d.mts +34 -35
  10. package/dist/color/index.d.mts.map +1 -1
  11. package/dist/color/index.mjs +3 -1
  12. package/dist/color/index.mjs.map +1 -1
  13. package/dist/crm/index.d.mts +288 -0
  14. package/dist/crm/index.d.mts.map +1 -0
  15. package/dist/crm/index.mjs +731 -0
  16. package/dist/crm/index.mjs.map +1 -0
  17. package/dist/email/index.d.mts +216 -0
  18. package/dist/email/index.d.mts.map +1 -0
  19. package/dist/email/index.mjs +331 -0
  20. package/dist/email/index.mjs.map +1 -0
  21. package/dist/favicon.d.mts +8 -9
  22. package/dist/favicon.d.mts.map +1 -1
  23. package/dist/git/index.d.mts +65 -0
  24. package/dist/git/index.d.mts.map +1 -0
  25. package/dist/git/index.mjs +107 -0
  26. package/dist/git/index.mjs.map +1 -0
  27. package/dist/hosting/index.d.mts +29 -29
  28. package/dist/hosting/index.d.mts.map +1 -1
  29. package/dist/hosting/index.mjs +7 -4
  30. package/dist/hosting/index.mjs.map +1 -1
  31. package/dist/identity-BoRddTx3.mjs +35 -0
  32. package/dist/identity-BoRddTx3.mjs.map +1 -0
  33. package/dist/index.d.mts +24 -25
  34. package/dist/index.d.mts.map +1 -1
  35. package/dist/index.mjs +5 -5
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/indexing/index.d.mts +23 -24
  38. package/dist/indexing/index.d.mts.map +1 -1
  39. package/dist/media/index.d.mts +24 -24
  40. package/dist/media/index.d.mts.map +1 -1
  41. package/dist/media/index.mjs +3 -3
  42. package/dist/media/index.mjs.map +1 -1
  43. package/dist/notify/index.d.mts +26 -15
  44. package/dist/notify/index.d.mts.map +1 -1
  45. package/dist/notify/index.mjs +50 -20
  46. package/dist/notify/index.mjs.map +1 -1
  47. package/dist/onboarding/index.d.mts +10 -141
  48. package/dist/onboarding/index.d.mts.map +1 -1
  49. package/dist/onboarding/index.mjs +1 -144
  50. package/dist/onboarding/index.mjs.map +1 -1
  51. package/dist/plan-BLKikoOG.mjs +150 -0
  52. package/dist/plan-BLKikoOG.mjs.map +1 -0
  53. package/dist/plan-Hq8Pb0Uw.d.mts +133 -0
  54. package/dist/plan-Hq8Pb0Uw.d.mts.map +1 -0
  55. package/dist/reviews/index.d.mts +12 -13
  56. package/dist/reviews/index.d.mts.map +1 -1
  57. package/dist/schema/index.d.mts +7 -7
  58. package/dist/schema/index.d.mts.map +1 -1
  59. package/dist/security/index.d.mts +2 -2
  60. package/dist/security/index.d.mts.map +1 -1
  61. package/dist/{token-Bz_-igw-.d.mts → token-DmmoQ7um.d.mts} +6 -3
  62. package/dist/token-DmmoQ7um.d.mts.map +1 -0
  63. package/dist/tracking/index.d.mts +43 -17
  64. package/dist/tracking/index.d.mts.map +1 -1
  65. package/dist/tracking/index.mjs +2 -1
  66. package/dist/tracking/index.mjs.map +1 -1
  67. package/dist/{types-CHHjzRrv.d.mts → types-7ELci8RQ.d.mts} +4 -2
  68. package/dist/types-7ELci8RQ.d.mts.map +1 -0
  69. package/package.json +14 -4
  70. package/dist/adc-BFrzpMHq.d.mts.map +0 -1
  71. package/dist/token-Bz_-igw-.d.mts.map +0 -1
  72. package/dist/types-CHHjzRrv.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/notify/email.ts","../../src/notify/plan.ts","../../src/notify/render.ts","../../src/notify/index.ts"],"sourcesContent":["/**\n * The e-mail channel — Cloudflare Email Sending.\n *\n * I/O only: it executes an `EmailPlan` and decides nothing. Whether to send, to\n * whom, and from where were all settled in `plan.ts`.\n *\n * **The binding is passed in, never imported.** `@getvitops/utils` does not depend\n * on `cloudflare:workers`, so this module runs in Node and in a test with a stub,\n * and the Astro package gains no Cloudflare coupling. The consumer's route hands\n * over `env.EMAIL`.\n *\n * Uses the current Email Sending binding — a structured `send({ to, from,\n * subject, html, text })` — not the legacy `EmailMessage` + hand-built MIME path.\n * The domain in `from` must have been onboarded (`wrangler email sending enable\n * <domain>`); nothing here can check that, which is why `E_SENDER_NOT_VERIFIED`\n * is surfaced verbatim rather than collapsed into \"send failed\".\n */\nimport type { RenderedMessage } from './types.ts';\nimport type { ChannelResult, EmailBinding, EmailPlan } from './types.ts';\n\n/**\n * Provider errors worth retrying.\n *\n * Everything else is a configuration fault — an unverified sender, a malformed\n * payload, a suppressed recipient — where a retry is pure latency and the send\n * will fail identically. Retrying those also burns the daily quota.\n */\nconst RETRYABLE = new Set([\n 'E_RATE_LIMIT_EXCEEDED',\n 'E_DELIVERY_FAILED',\n 'E_INTERNAL_SERVER_ERROR',\n]);\n\nfunction codeOf(error: unknown): string | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport interface SendEmailOptions {\n /** Attempts for a retryable failure (default 3). */\n attempts?: number;\n /**\n * Per-attempt ceiling in milliseconds (default 10000; `0` disables).\n *\n * `binding.send()` is a network call with no deadline of its own, so without\n * this one hung attempt hangs the request that produced it — forever, in the\n * one module otherwise built on always saying why. A conversion endpoint\n * cannot be the thing that makes a form submission time out, so the bound\n * belongs here rather than in every consumer's wrapper.\n *\n * A timeout is treated as retryable: it is a transient condition by\n * definition, unlike `E_SENDER_NOT_VERIFIED` and friends.\n */\n timeoutMs?: number;\n /** Injected for tests; real callers let it default to a real delay. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/** Marker for a send that exceeded its deadline, so the retry rule can see it. */\nconst TIMEOUT_CODE = 'E_SEND_TIMEOUT';\n\n/**\n * Race a send against its deadline.\n *\n * The timer is always cleared — a pending `setTimeout` keeps a Worker's event\n * loop alive past the response, which turns a bounded send into an unbounded\n * invocation and bills for the difference.\n */\nasync function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {\n if (ms <= 0) return work;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`Email send exceeded ${ms}ms.`) as Error & { code: string };\n err.code = TIMEOUT_CODE;\n reject(err);\n }, ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * Send one rendered message according to a plan.\n *\n * Never throws: a failed notification must not take down the request that\n * produced it. The visitor has already submitted their form, and failing their\n * response because our mail didn't go out would turn a lost notification into a\n * lost conversion. The failure is returned instead, for the caller to log.\n */\nexport async function sendEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n binding: EmailBinding,\n options: SendEmailOptions = {},\n): Promise<ChannelResult> {\n if (!plan.enabled || !plan.to || !plan.from) {\n return { channel: 'email', sent: false, reason: plan.skip ?? 'Channel not enabled.' };\n }\n\n const attempts = Math.max(1, options.attempts ?? 3);\n const sleep = options.sleep ?? wait;\n const timeoutMs = options.timeoutMs ?? 10_000;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await withTimeout(\n binding.send({\n to: plan.to,\n from: plan.fromName ? { email: plan.from, name: plan.fromName } : { email: plan.from },\n subject: message.subject,\n text: message.text,\n html: message.html,\n ...(plan.replyTo ? { replyTo: plan.replyTo } : {}),\n }),\n timeoutMs,\n );\n return { channel: 'email', sent: true };\n } catch (error) {\n const code = codeOf(error);\n if (attempt === attempts || !code || !(RETRYABLE.has(code) || code === TIMEOUT_CODE)) {\n return {\n channel: 'email',\n sent: false,\n reason: messageOf(error),\n ...(code ? { code } : {}),\n };\n }\n // Exponential backoff. Cloudflare's rate limit is per-account, so a burst\n // of conversions retrying in lockstep would keep colliding.\n await sleep(2 ** (attempt - 1) * 250);\n }\n }\n\n /* c8 ignore next -- the loop always returns; this satisfies the type checker. */\n return { channel: 'email', sent: false, reason: 'Exhausted attempts.' };\n}\n\n/**\n * Print the message instead of sending it.\n *\n * The dev path, for a machine with no binding. Explicit rather than a silent\n * no-op, because \"I never saw the notification\" is the symptom of both a broken\n * integration and a working one nobody could observe.\n */\nexport function logEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n log: (line: string) => void = console.log,\n): ChannelResult {\n log(\n [\n '\\n========== NOTIFICATION EMAIL (not sent — no binding) ==========',\n `To: ${plan.to ?? '(unresolved)'}`,\n `From: ${plan.from ?? '(unresolved)'}`,\n `Subject: ${message.subject}`,\n '---',\n message.text,\n '================================================================\\n',\n ].join('\\n'),\n );\n return { channel: 'email', sent: false, reason: 'No binding — logged to the console.' };\n}\n","/**\n * Every decision a notification makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no binding, no clock. Whether a\n * channel fires, who it reaches, and *why* it was skipped are all decided here and\n * asserted in `plan.test.ts`; the senders beside this file do what they are told\n * and decide nothing. That is the same split `indexing/plan.ts` makes against\n * `gsc.ts`, and `@getvitops/core`'s consent store makes against its DOM wiring,\n * for the same reason: the consequential logic has to be testable without the\n * environment it runs in.\n *\n * The practical payoff is that a misconfigured site can be told exactly what will\n * and won't happen without sending anything — a silently unsent conversion\n * notification is indistinguishable from no conversion.\n */\nimport type { EmailChannelConfig, EmailPlan, NotificationPlan, NotifyContext } from './types.ts';\n\n/** Default Workers binding name for Cloudflare Email Sending. */\nexport const DEFAULT_EMAIL_BINDING = 'EMAIL';\n\n/** Normalise the `email` shorthand: a bare address means a Cloudflare send to it. */\nexport function normalizeEmailChannel(\n input: string | EmailChannelConfig | undefined,\n): EmailChannelConfig | undefined {\n if (input === undefined) return undefined;\n return typeof input === 'string' ? { provider: 'cloudflare', to: input } : input;\n}\n\n/**\n * Who the notification reaches.\n *\n * An explicit recipient wins; otherwise it falls to the site's own contact\n * addresses, primary first. This cascade is why a site that has already said\n * where it receives mail doesn't have to say it twice.\n */\nexport function resolveRecipient(\n channel: EmailChannelConfig,\n ctx: NotifyContext,\n): string | undefined {\n if (channel.to) return channel.to;\n return ctx.locationEmails?.find((e) => !!e);\n}\n\n/**\n * The From address.\n *\n * `noreply@<canonical>` by default, because the sending domain has to be one the\n * site controls — Cloudflare rejects anything else with `E_SENDER_NOT_VERIFIED`,\n * and guessing from the recipient's domain would send that failure every time.\n */\nexport function resolveSender(channel: EmailChannelConfig, ctx: NotifyContext): string | undefined {\n if (channel.from) return channel.from;\n if (!ctx.canonical) return undefined;\n let host: string;\n try {\n host = new URL(ctx.canonical).hostname;\n } catch {\n // A bare hostname is a legitimate way to write `domains.canonical`.\n host = ctx.canonical.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '');\n }\n return host ? `noreply@${host}` : undefined;\n}\n\n/**\n * Decide what will be sent, and say why anything won't be.\n *\n * Every \"off\" carries a reason rather than being an absence, so a caller can\n * report the misconfiguration instead of reporting success over a no-op.\n */\nexport function planNotifications(ctx: NotifyContext): NotificationPlan {\n const email = planEmail(ctx);\n return { email, empty: !email.enabled };\n}\n\nfunction planEmail(ctx: NotifyContext): EmailPlan {\n const channel = normalizeEmailChannel(ctx.notifications?.email);\n const binding = channel?.binding ?? DEFAULT_EMAIL_BINDING;\n\n if (!channel) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip: 'No `notifications.email` configured.',\n };\n }\n\n const to = resolveRecipient(channel, ctx);\n if (!to) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip:\n 'No recipient: set `notifications.email.to`, or give a location an `email` ' +\n 'so the notification has somewhere to go.',\n };\n }\n\n const from = resolveSender(channel, ctx);\n if (!from) {\n return {\n provider: 'cloudflare',\n binding,\n to,\n enabled: false,\n skip:\n 'No sender: set `notifications.email.from`, or `domains.canonical` so ' +\n '`noreply@<host>` can be derived. Cloudflare only sends from a domain you have onboarded.',\n };\n }\n\n return {\n provider: 'cloudflare',\n binding,\n to,\n from,\n fromName: channel.fromName ?? ctx.organizationName,\n replyTo: channel.replyTo,\n enabled: true,\n };\n}\n","/**\n * Turning a `ConversionEvent` into something a person reads.\n *\n * Pure, and separate from both the plan and the sender, because rendering is the\n * part that differs per channel: an SMS channel will render the same event in 160\n * characters, a portal log as a row. The event stays the fact; only this file has\n * an opinion about prose.\n *\n * The layout is three sections — who got in touch, which ad sent them, and what\n * the request looked like — because that is the order the reader needs them in.\n * The contact details are the point; attribution is why it matters; the visitor\n * context is for when something looks wrong.\n */\nimport { getPrimaryClickId, identifyPlatform } from '../tracking/platform.ts';\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport type { RenderedMessage } from './types.ts';\n\n/**\n * Fields never worth putting in a notification.\n *\n * A honeypot is not visitor-supplied — it is bait, and reporting it as something\n * they submitted is untrue. The same rule `legal/derive.ts` applies when deriving\n * `piiCollected`, and for the same reason. Callers may strip more.\n */\nconst OMIT_FIELDS = new Set(['website', '_honeypot', 'honeypot', 'cf-turnstile-response']);\n\nfunction label(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1).replace(/[_-]/g, ' ');\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/** One section: a heading and its lines. Empty sections are dropped by the caller. */\ninterface Section {\n heading: string;\n lines: [string, string][];\n}\n\n/**\n * Who submitted the form, for the subject line.\n *\n * `formData['name']` alone is the shape a form has when someone writes it that\n * way, and most don't: a downstream site had `first_name`/`last_name` on five of\n * six forms, so every notification read \"from Unknown\" and the renderer could\n * not be adopted at all. The cascade is ordered most-specific first, and falls\n * back to the email rather than to nothing — an address identifies the person\n * even when no name field exists.\n */\nfunction submitterName(formData: Record<string, string>): string {\n const get = (...keys: string[]): string | undefined => {\n for (const k of keys) {\n const v = formData[k]?.trim();\n if (v) return v;\n }\n return undefined;\n };\n const full = get('name', 'full_name', 'fullName', 'fullname', 'your-name');\n if (full) return full;\n const first = get('first_name', 'firstName', 'firstname', 'given_name');\n const last = get('last_name', 'lastName', 'lastname', 'family_name', 'surname');\n if (first || last) return [first, last].filter(Boolean).join(' ');\n return get('email', 'email_address', 'emailAddress') ?? 'Unknown';\n}\n\n/**\n * The event as sections — the shared structure behind both renderings.\n *\n * Extracted so the text and HTML versions cannot disagree about content. They\n * differ only in markup; a field added here appears in both.\n */\nexport function describeEvent(event: ConversionEvent): { subject: string; sections: Section[] } {\n const t = event.tracking;\n const platform = t ? identifyPlatform(t) : null;\n const clickId = t ? getPrimaryClickId(t) : null;\n\n const contact: [string, string][] = [];\n let subject: string;\n\n if (event.type === 'form' && event.formData) {\n const name = submitterName(event.formData);\n subject = `[Contact Form] New submission from ${name}`;\n for (const [key, value] of Object.entries(event.formData)) {\n if (!OMIT_FIELDS.has(key) && value) contact.push([label(key), value]);\n }\n } else {\n const phone = event.phone ?? 'unknown';\n subject = `[Phone Call] Visitor calling ${phone}`;\n contact.push(['Phone', phone]);\n }\n\n const attribution: [string, string][] = [];\n if (t) {\n if (platform) attribution.push(['Platform', platform]);\n if (clickId) attribution.push([`Click ID (${clickId.param})`, clickId.value]);\n for (const key of ['utm_campaign', 'utm_source', 'utm_medium', 'utm_content', 'utm_term']) {\n const value = t[key];\n if (value) attribution.push([label(key.replace('utm_', '')), String(value)]);\n }\n if (t.ab_variant) attribution.push(['A/B variant', t.ab_variant]);\n }\n\n const context: [string, string][] = [];\n if (t?.landingPage) context.push(['Landing page', t.landingPage]);\n if (t?.referrer) context.push(['Referrer', t.referrer]);\n if (t?.ts) context.push(['First visit', new Date(t.ts).toISOString()]);\n context.push(['Received', new Date(event.at).toISOString()]);\n if (event.userAgent) context.push(['User agent', event.userAgent]);\n if (event.ip) context.push(['IP', event.ip]);\n\n const sections: Section[] = [\n { heading: 'Contact details', lines: contact },\n // Stated rather than omitted: \"we don't know where this came from\" is a\n // useful answer, and a silently missing section reads as a bug in the tool.\n {\n heading: 'Ad attribution',\n lines: attribution.length\n ? attribution\n : [['Source', 'None — visitor arrived without ad tracking']],\n },\n { heading: 'Visitor context', lines: context },\n ];\n\n return { subject, sections: sections.filter((s) => s.lines.length) };\n}\n\n/** Render for e-mail. Both halves, always — see `RenderedMessage`. */\nexport function renderEmail(event: ConversionEvent): RenderedMessage {\n const { subject, sections } = describeEvent(event);\n\n const text = sections\n .map((s) => [`--- ${s.heading} ---`, ...s.lines.map(([k, v]) => `${k}: ${v}`)].join('\\n'))\n .join('\\n\\n');\n\n const html = sections\n .map(\n (s) =>\n `<h2 style=\"font:600 14px system-ui;margin:24px 0 8px\">${escapeHtml(s.heading)}</h2>` +\n `<table style=\"font:14px system-ui;border-collapse:collapse\">${s.lines\n .map(\n ([k, v]) =>\n `<tr><td style=\"padding:2px 12px 2px 0;color:#666;vertical-align:top\">${escapeHtml(k)}</td>` +\n `<td style=\"padding:2px 0\">${escapeHtml(v)}</td></tr>`,\n )\n .join('')}</table>`,\n )\n .join('');\n\n return { subject, text, html };\n}\n","/**\n * Conversion notifications — plan, render, dispatch.\n *\n * The seam between \"a conversion happened\" and \"someone found out about it\".\n * A `ConversionEvent` from `@getvitops/utils/tracking` goes in; where it goes and\n * how it reads are config, not code at the call site.\n *\n * Three files, three jobs, matching `indexing/`:\n * - `plan.ts` decides everything, purely — which channels, which recipients,\n * and why anything is off.\n * - `render.ts` turns the event into prose, purely.\n * - `email.ts` executes, and decides nothing.\n *\n * ---\n *\n * **TODO — further channels.** Only `email` is implemented. The seam is\n * `NotificationsConfig` + a sender with `sendEmail`'s signature `(plan, message,\n * transport) => ChannelResult`; adding one should mean a new sender file, a new\n * branch in `planNotifications`, and a schema variant — touching neither\n * `ConversionEvent` nor the recipient cascade. Planned:\n * - `sms` — the same event rendered short. `render.ts` already separates\n * `describeEvent` from `renderEmail` for exactly this.\n * - `persist` — append to a store (D1, a portal log) the client reviews.\n * The generic `email`/`text`/`persist` helpers taking content + provider config\n * belong at that point, not before: one implemented channel is not enough to know\n * what the abstraction should be.\n */\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport { logEmail, sendEmail } from './email.ts';\nimport { planNotifications } from './plan.ts';\nimport { renderEmail } from './render.ts';\nimport type { ChannelResult, EmailBinding, NotifyContext } from './types.ts';\n\nexport interface NotifyDeps {\n /**\n * The Workers `send_email` binding (`env.EMAIL`). Omit it and the notification\n * is printed instead — the dev path.\n */\n email?: EmailBinding | undefined;\n}\n\nexport interface NotifyResult {\n results: ChannelResult[];\n /** True when at least one channel delivered. */\n delivered: boolean;\n}\n\n/**\n * Notify every configured channel about a conversion.\n *\n * Channels are independent: one failing must not stop the others, and none of\n * them may throw into the request that produced the event. Every outcome —\n * delivered, skipped, failed — comes back as data for the caller to log.\n */\nexport async function notify(\n event: ConversionEvent,\n ctx: NotifyContext,\n deps: NotifyDeps = {},\n): Promise<NotifyResult> {\n const plan = planNotifications(ctx);\n const results: ChannelResult[] = [];\n\n if (plan.email.enabled) {\n const message = renderEmail(event);\n results.push(\n deps.email ? await sendEmail(plan.email, message, deps.email) : logEmail(plan.email, message),\n );\n } else {\n results.push({ channel: 'email', sent: false, reason: plan.email.skip ?? 'Not configured.' });\n }\n\n return { results, delivered: results.some((r) => r.sent) };\n}\n\nexport {\n DEFAULT_EMAIL_BINDING,\n normalizeEmailChannel,\n planNotifications,\n resolveRecipient,\n resolveSender,\n} from './plan.ts';\nexport { describeEvent, renderEmail } from './render.ts';\nexport { logEmail, sendEmail } from './email.ts';\nexport type {\n ChannelPlan,\n ChannelResult,\n EmailBinding,\n EmailChannelConfig,\n EmailPlan,\n NotificationPlan,\n NotificationsConfig,\n NotifyContext,\n RenderedMessage,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,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V,KACE,MACC,yDAAyD,WAAW,EAAE,OAAO,EAAE,mEAChB,EAAE,MAC9D,KACE,CAAC,GAAG,OACH,wEAAwE,WAAW,CAAC,EAAE,iCACzD,WAAW,CAAC,EAAE,WAC/C,CAAC,CACA,KAAK,EAAE,EAAE,SAChB,CAAC,CACA,KAAK,EAEmB;CAAE;AAC/B;;;;;;;;;;;ACpGA,eAAsB,OACpB,OACA,KACA,OAAmB,CAAC,GACG;CACvB,MAAM,OAAO,kBAAkB,GAAG;CAClC,MAAM,UAA2B,CAAC;CAElC,IAAI,KAAK,MAAM,SAAS;EACtB,MAAM,UAAU,YAAY,KAAK;EACjC,QAAQ,KACN,KAAK,QAAQ,MAAM,UAAU,KAAK,OAAO,SAAS,KAAK,KAAK,IAAI,SAAS,KAAK,OAAO,OAAO,CAC9F;CACF,OACE,QAAQ,KAAK;EAAE,SAAS;EAAS,MAAM;EAAO,QAAQ,KAAK,MAAM,QAAQ;CAAkB,CAAC;CAG9F,OAAO;EAAE;EAAS,WAAW,QAAQ,MAAM,MAAM,EAAE,IAAI;CAAE;AAC3D"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/notify/email.ts","../../src/notify/plan.ts","../../src/notify/render.ts","../../src/notify/index.ts"],"sourcesContent":["/**\n * The e-mail channel — Cloudflare Email Sending.\n *\n * I/O only: it executes an `EmailPlan` and decides nothing. Whether to send, to\n * whom, and from where were all settled in `plan.ts`.\n *\n * **The binding is passed in, never imported.** `@getvitops/utils` does not depend\n * on `cloudflare:workers`, so this module runs in Node and in a test with a stub,\n * and the Astro package gains no Cloudflare coupling. The consumer's route hands\n * over `env.EMAIL`.\n *\n * Uses the current Email Sending binding — a structured `send({ to, from,\n * subject, html, text })` — not the legacy `EmailMessage` + hand-built MIME path.\n * The domain in `from` must have been onboarded (`wrangler email sending enable\n * <domain>`); nothing here can check that, which is why `E_SENDER_NOT_VERIFIED`\n * is surfaced verbatim rather than collapsed into \"send failed\".\n */\nimport type { RenderedMessage } from './types.ts';\nimport type { ChannelResult, EmailBinding, EmailPlan } from './types.ts';\n\n/**\n * Provider errors worth retrying.\n *\n * Everything else is a configuration fault — an unverified sender, a malformed\n * payload, a suppressed recipient — where a retry is pure latency and the send\n * will fail identically. Retrying those also burns the daily quota.\n */\nconst RETRYABLE = new Set([\n 'E_RATE_LIMIT_EXCEEDED',\n 'E_DELIVERY_FAILED',\n 'E_INTERNAL_SERVER_ERROR',\n]);\n\nfunction codeOf(error: unknown): string | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport interface SendEmailOptions {\n /** Attempts for a retryable failure (default 3). */\n attempts?: number;\n /**\n * Per-attempt ceiling in milliseconds (default 10000; `0` disables).\n *\n * `binding.send()` is a network call with no deadline of its own, so without\n * this one hung attempt hangs the request that produced it — forever, in the\n * one module otherwise built on always saying why. A conversion endpoint\n * cannot be the thing that makes a form submission time out, so the bound\n * belongs here rather than in every consumer's wrapper.\n *\n * A timeout is treated as retryable: it is a transient condition by\n * definition, unlike `E_SENDER_NOT_VERIFIED` and friends.\n */\n timeoutMs?: number;\n /** Injected for tests; real callers let it default to a real delay. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/** Marker for a send that exceeded its deadline, so the retry rule can see it. */\nconst TIMEOUT_CODE = 'E_SEND_TIMEOUT';\n\n/**\n * Race a send against its deadline.\n *\n * The timer is always cleared — a pending `setTimeout` keeps a Worker's event\n * loop alive past the response, which turns a bounded send into an unbounded\n * invocation and bills for the difference.\n */\nasync function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {\n if (ms <= 0) return work;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const err = new Error(`Email send exceeded ${ms}ms.`) as Error & { code: string };\n err.code = TIMEOUT_CODE;\n reject(err);\n }, ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * Send one rendered message according to a plan.\n *\n * Never throws: a failed notification must not take down the request that\n * produced it. The visitor has already submitted their form, and failing their\n * response because our mail didn't go out would turn a lost notification into a\n * lost conversion. The failure is returned instead, for the caller to log.\n */\nexport async function sendEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n binding: EmailBinding,\n options: SendEmailOptions = {},\n): Promise<ChannelResult> {\n if (!plan.enabled || !plan.to || !plan.from) {\n return { channel: 'email', sent: false, reason: plan.skip ?? 'Channel not enabled.' };\n }\n\n const attempts = Math.max(1, options.attempts ?? 3);\n const sleep = options.sleep ?? wait;\n const timeoutMs = options.timeoutMs ?? 10_000;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await withTimeout(\n binding.send({\n to: plan.to,\n from: plan.fromName ? { email: plan.from, name: plan.fromName } : { email: plan.from },\n subject: message.subject,\n text: message.text,\n html: message.html,\n ...(plan.replyTo ? { replyTo: plan.replyTo } : {}),\n }),\n timeoutMs,\n );\n return { channel: 'email', sent: true };\n } catch (error) {\n const code = codeOf(error);\n if (attempt === attempts || !code || !(RETRYABLE.has(code) || code === TIMEOUT_CODE)) {\n return {\n channel: 'email',\n sent: false,\n reason: messageOf(error),\n ...(code ? { code } : {}),\n };\n }\n // Exponential backoff. Cloudflare's rate limit is per-account, so a burst\n // of conversions retrying in lockstep would keep colliding.\n await sleep(2 ** (attempt - 1) * 250);\n }\n }\n\n /* c8 ignore next -- the loop always returns; this satisfies the type checker. */\n return { channel: 'email', sent: false, reason: 'Exhausted attempts.' };\n}\n\n/**\n * Print the message instead of sending it.\n *\n * The dev path, for a machine with no binding. Explicit rather than a silent\n * no-op, because \"I never saw the notification\" is the symptom of both a broken\n * integration and a working one nobody could observe.\n */\nexport function logEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n log: (line: string) => void = console.log,\n): ChannelResult {\n log(\n [\n '\\n========== NOTIFICATION EMAIL (not sent — no binding) ==========',\n `To: ${plan.to ?? '(unresolved)'}`,\n `From: ${plan.from ?? '(unresolved)'}`,\n `Subject: ${message.subject}`,\n '---',\n message.text,\n '================================================================\\n',\n ].join('\\n'),\n );\n return { channel: 'email', sent: false, reason: 'No binding — logged to the console.' };\n}\n","/**\n * Every decision a notification makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no binding, no clock. Whether a\n * channel fires, who it reaches, and *why* it was skipped are all decided here and\n * asserted in `plan.test.ts`; the senders beside this file do what they are told\n * and decide nothing. That is the same split `indexing/plan.ts` makes against\n * `gsc.ts`, and `@getvitops/core`'s consent store makes against its DOM wiring,\n * for the same reason: the consequential logic has to be testable without the\n * environment it runs in.\n *\n * The practical payoff is that a misconfigured site can be told exactly what will\n * and won't happen without sending anything — a silently unsent conversion\n * notification is indistinguishable from no conversion.\n */\nimport type { EmailChannelConfig, EmailPlan, NotificationPlan, NotifyContext } from './types.ts';\n\n/** Default Workers binding name for Cloudflare Email Sending. */\nexport const DEFAULT_EMAIL_BINDING = 'EMAIL';\n\n/** Normalise the `email` shorthand: a bare address means a Cloudflare send to it. */\nexport function normalizeEmailChannel(\n input: string | EmailChannelConfig | undefined,\n): EmailChannelConfig | undefined {\n if (input === undefined) return undefined;\n return typeof input === 'string' ? { provider: 'cloudflare', to: input } : input;\n}\n\n/**\n * Who the notification reaches.\n *\n * An explicit recipient wins; otherwise it falls to the site's own contact\n * addresses, primary first. This cascade is why a site that has already said\n * where it receives mail doesn't have to say it twice.\n */\nexport function resolveRecipient(\n channel: EmailChannelConfig,\n ctx: NotifyContext,\n): string | undefined {\n if (channel.to) return channel.to;\n return ctx.locationEmails?.find((e) => !!e);\n}\n\n/**\n * The From address.\n *\n * `noreply@<canonical>` by default, because the sending domain has to be one the\n * site controls — Cloudflare rejects anything else with `E_SENDER_NOT_VERIFIED`,\n * and guessing from the recipient's domain would send that failure every time.\n */\nexport function resolveSender(channel: EmailChannelConfig, ctx: NotifyContext): string | undefined {\n if (channel.from) return channel.from;\n if (!ctx.canonical) return undefined;\n let host: string;\n try {\n host = new URL(ctx.canonical).hostname;\n } catch {\n // A bare hostname is a legitimate way to write `domains.canonical`.\n host = ctx.canonical.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '');\n }\n return host ? `noreply@${host}` : undefined;\n}\n\n/**\n * Decide what will be sent, and say why anything won't be.\n *\n * Every \"off\" carries a reason rather than being an absence, so a caller can\n * report the misconfiguration instead of reporting success over a no-op.\n */\nexport function planNotifications(ctx: NotifyContext): NotificationPlan {\n const email = planEmail(ctx);\n return { email, empty: !email.enabled };\n}\n\nfunction planEmail(ctx: NotifyContext): EmailPlan {\n const channel = normalizeEmailChannel(ctx.notifications?.email);\n const binding = channel?.binding ?? DEFAULT_EMAIL_BINDING;\n\n if (!channel) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip: 'No `notifications.email` configured.',\n };\n }\n\n const to = resolveRecipient(channel, ctx);\n if (!to) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip:\n 'No recipient: set `notifications.email.to`, or give a location an `email` ' +\n 'so the notification has somewhere to go.',\n };\n }\n\n const from = resolveSender(channel, ctx);\n if (!from) {\n return {\n provider: 'cloudflare',\n binding,\n to,\n enabled: false,\n skip:\n 'No sender: set `notifications.email.from`, or `domains.canonical` so ' +\n '`noreply@<host>` can be derived. Cloudflare only sends from a domain you have onboarded.',\n };\n }\n\n return {\n provider: 'cloudflare',\n binding,\n to,\n from,\n fromName: channel.fromName ?? ctx.organizationName,\n replyTo: channel.replyTo,\n enabled: true,\n };\n}\n","/**\n * Turning a `ConversionEvent` into something a person reads.\n *\n * Pure, and separate from both the plan and the sender, because rendering is the\n * part that differs per channel: an SMS channel will render the same event in 160\n * characters, a portal log as a row. The event stays the fact; only this file has\n * an opinion about prose.\n *\n * The layout is three sections — who got in touch, which ad sent them, and what\n * the request looked like — because that is the order the reader needs them in.\n * The contact details are the point; attribution is why it matters; the visitor\n * context is for when something looks wrong.\n */\nimport { identifySubmitter } from '../tracking/identity.ts';\nimport { getPrimaryClickId, identifyPlatform } from '../tracking/platform.ts';\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport type { RenderedMessage } from './types.ts';\n\n/**\n * Fields never worth putting in a notification.\n *\n * A honeypot is not visitor-supplied — it is bait, and reporting it as something\n * they submitted is untrue. The same rule `legal/derive.ts` applies when deriving\n * `piiCollected`, and for the same reason. Callers may strip more.\n */\nconst OMIT_FIELDS = new Set(['website', '_honeypot', 'honeypot', 'cf-turnstile-response']);\n\nfunction label(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1).replace(/[_-]/g, ' ');\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/** One section: a heading and its lines. Empty sections are dropped by the caller. */\ninterface Section {\n heading: string;\n lines: [string, string][];\n}\n\n/**\n * One line, already rendered both ways — a plain fact (`html` is just the\n * escaped `text`) or a link (`html` an anchor, `text` the bare href). Built at\n * the point each line is known rather than carried as a union and branched on\n * later: `describeEvent`'s lines are always plain `[label, value]` pairs (see\n * `Section` above, which `render.test.ts` destructures as such), and the one\n * line shape `renderEmail` adds itself — the \"Actions\" link — is turned into\n * this same rendered shape immediately, so the two renderers below share one\n * line format instead of branching on what kind of line each one is.\n */\ninterface RenderedLine {\n label: string;\n text: string;\n html: string;\n}\n\n/** A section as `renderEmail` assembles it — `describeEvent`'s output plus its own additions. */\ninterface RenderSection {\n heading: string;\n lines: RenderedLine[];\n}\n\nfunction factLine([label, value]: readonly [string, string]): RenderedLine {\n return { label, text: value, html: escapeHtml(value) };\n}\n\nfunction linkLine(label: string, href: string): RenderedLine {\n return { label, text: href, html: `<a href=\"${escapeHtml(href)}\">${escapeHtml(href)}</a>` };\n}\n\nfunction toRenderSection(section: Section): RenderSection {\n return { heading: section.heading, lines: section.lines.map(factLine) };\n}\n\n/**\n * Who submitted the form, for the subject line.\n *\n * `formData['name']` alone is the shape a form has when someone writes it that\n * way, and most don't: a downstream site had `first_name`/`last_name` on five of\n * six forms, so every notification read \"from Unknown\" and the renderer could\n * not be adopted at all. The cascade is ordered most-specific first, and falls\n * back to the email rather than to nothing — an address identifies the person\n * even when no name field exists.\n */\nfunction submitterName(formData: Record<string, string>): string {\n return identifySubmitter(formData).fullName;\n}\n\n/**\n * The event as sections — the shared structure behind both renderings.\n *\n * Extracted so the text and HTML versions cannot disagree about content. They\n * differ only in markup; a field added here appears in both.\n */\nexport function describeEvent(event: ConversionEvent): { subject: string; sections: Section[] } {\n const t = event.tracking;\n const platform = t ? identifyPlatform(t) : null;\n const clickId = t ? getPrimaryClickId(t) : null;\n\n const contact: [string, string][] = [];\n let subject: string;\n\n if (event.type === 'form' && event.formData) {\n const name = submitterName(event.formData);\n subject = `[Contact Form] New submission from ${name}`;\n for (const [key, value] of Object.entries(event.formData)) {\n if (!OMIT_FIELDS.has(key) && value) contact.push([label(key), value]);\n }\n } else if (event.type === 'email') {\n const email = event.email ?? 'unknown';\n subject = `[Email Click] Visitor emailing ${email}`;\n contact.push(['Email', email]);\n } else {\n const phone = event.phone ?? 'unknown';\n subject = `[Phone Call] Visitor calling ${phone}`;\n contact.push(['Phone', phone]);\n }\n\n const attribution: [string, string][] = [];\n if (t) {\n if (platform) attribution.push(['Platform', platform]);\n if (clickId) attribution.push([`Click ID (${clickId.param})`, clickId.value]);\n for (const key of ['utm_campaign', 'utm_source', 'utm_medium', 'utm_content', 'utm_term']) {\n const value = t[key];\n if (value) attribution.push([label(key.replace('utm_', '')), String(value)]);\n }\n if (t.ab_variant) attribution.push(['A/B variant', t.ab_variant]);\n }\n\n const context: [string, string][] = [];\n if (t?.landingPage) context.push(['Landing page', t.landingPage]);\n if (t?.referrer) context.push(['Referrer', t.referrer]);\n if (t?.ts) context.push(['First visit', new Date(t.ts).toISOString()]);\n context.push(['Received', new Date(event.at).toISOString()]);\n if (event.userAgent) context.push(['User agent', event.userAgent]);\n if (event.ip) context.push(['IP', event.ip]);\n\n const sections: Section[] = [\n { heading: 'Contact details', lines: contact },\n // Stated rather than omitted: \"we don't know where this came from\" is a\n // useful answer, and a silently missing section reads as a bug in the tool.\n {\n heading: 'Ad attribution',\n lines: attribution.length\n ? attribution\n : [['Source', 'None — visitor arrived without ad tracking']],\n },\n { heading: 'Visitor context', lines: context },\n ];\n\n return { subject, sections: sections.filter((s) => s.lines.length) };\n}\n\n/** Render for e-mail. Both halves, always — see `RenderedMessage`. */\nexport function renderEmail(\n event: ConversionEvent,\n extra: { notes?: string[] | undefined; actionUrl?: string | undefined } = {},\n): RenderedMessage {\n const { subject, sections: eventSections } = describeEvent(event);\n\n // `{clickId}` is the only placeholder — an event has no durable id nothing\n // in this toolchain could look back up (there's no store), so interpolating\n // one would be decorative. Omitted entirely when there's no click ID to\n // interpolate, rather than emailing a link with a literal `{clickId}` in it.\n const clickId = event.tracking ? getPrimaryClickId(event.tracking) : null;\n const actionSection: RenderSection | null =\n extra.actionUrl && clickId\n ? {\n heading: 'Actions',\n lines: [\n linkLine(\n 'View in ad platform',\n extra.actionUrl.replace(/\\{clickId\\}/g, encodeURIComponent(clickId.value)),\n ),\n ],\n }\n : null;\n\n // Deliberately a channel-neutral `string[]` rather than a typed CRM result —\n // this module gains no dependency on `crm`, and the seam serves any future\n // sink the same way.\n const sections: RenderSection[] = [\n ...eventSections.map(toRenderSection),\n ...(actionSection ? [actionSection] : []),\n ...(extra.notes && extra.notes.length\n ? [{ heading: 'Delivery', lines: extra.notes.map((n) => factLine(['CRM', n])) }]\n : []),\n ];\n\n const text = sections\n .map((s) => [`--- ${s.heading} ---`, ...s.lines.map((l) => `${l.label}: ${l.text}`)].join('\\n'))\n .join('\\n\\n');\n\n const html = sections\n .map(\n (s) =>\n `<h2 style=\"font:600 14px system-ui;margin:24px 0 8px\">${escapeHtml(s.heading)}</h2>` +\n `<table style=\"font:14px system-ui;border-collapse:collapse\">${s.lines\n .map(\n (l) =>\n `<tr><td style=\"padding:2px 12px 2px 0;color:#666;vertical-align:top\">${escapeHtml(l.label)}</td>` +\n `<td style=\"padding:2px 0\">${l.html}</td></tr>`,\n )\n .join('')}</table>`,\n )\n .join('');\n\n return { subject, text, html };\n}\n","/**\n * Conversion notifications — plan, render, dispatch.\n *\n * The seam between \"a conversion happened\" and \"someone found out about it\".\n * A `ConversionEvent` from `@getvitops/utils/tracking` goes in; where it goes and\n * how it reads are config, not code at the call site.\n *\n * Three files, three jobs, matching `indexing/`:\n * - `plan.ts` decides everything, purely — which channels, which recipients,\n * and why anything is off.\n * - `render.ts` turns the event into prose, purely.\n * - `email.ts` executes, and decides nothing.\n *\n * ---\n *\n * **TODO — further channels.** Only `email` is implemented. The seam is\n * `NotificationsConfig` + a sender with `sendEmail`'s signature `(plan, message,\n * transport) => ChannelResult`; adding one should mean a new sender file, a new\n * branch in `planNotifications`, and a schema variant — touching neither\n * `ConversionEvent` nor the recipient cascade. Planned:\n * - `sms` — the same event rendered short. `render.ts` already separates\n * `describeEvent` from `renderEmail` for exactly this.\n * - `persist` — append to a store (D1, a portal log) the client reviews.\n * The generic `email`/`text`/`persist` helpers taking content + provider config\n * belong at that point, not before: one implemented channel is not enough to know\n * what the abstraction should be.\n */\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport { logEmail, sendEmail } from './email.ts';\nimport { planNotifications } from './plan.ts';\nimport { renderEmail } from './render.ts';\nimport type { ChannelResult, EmailBinding, NotifyContext } from './types.ts';\n\nexport interface NotifyDeps {\n /**\n * The Workers `send_email` binding (`env.EMAIL`). Omit it and the notification\n * is printed instead — the dev path.\n */\n email?: EmailBinding | undefined;\n}\n\nexport interface NotifyResult {\n results: ChannelResult[];\n /** True when at least one channel delivered. */\n delivered: boolean;\n}\n\n/**\n * Notify every configured channel about a conversion.\n *\n * Channels are independent: one failing must not stop the others, and none of\n * them may throw into the request that produced the event. Every outcome —\n * delivered, skipped, failed — comes back as data for the caller to log.\n */\nexport async function notify(\n event: ConversionEvent,\n ctx: NotifyContext,\n deps: NotifyDeps = {},\n extra: { notes?: string[] | undefined } = {},\n): Promise<NotifyResult> {\n const plan = planNotifications(ctx);\n const results: ChannelResult[] = [];\n\n if (plan.email.enabled) {\n const message = renderEmail(event, { ...extra, actionUrl: ctx.notifications?.actionUrl });\n results.push(\n deps.email ? await sendEmail(plan.email, message, deps.email) : logEmail(plan.email, message),\n );\n } else {\n results.push({ channel: 'email', sent: false, reason: plan.email.skip ?? 'Not configured.' });\n }\n\n return { results, delivered: results.some((r) => r.sent) };\n}\n\nexport {\n DEFAULT_EMAIL_BINDING,\n normalizeEmailChannel,\n planNotifications,\n resolveRecipient,\n resolveSender,\n} from './plan.ts';\nexport { describeEvent, renderEmail } from './render.ts';\nexport { logEmail, sendEmail } from './email.ts';\nexport type {\n ChannelPlan,\n ChannelResult,\n EmailBinding,\n EmailChannelConfig,\n EmailPlan,\n NotificationPlan,\n NotificationsConfig,\n NotifyContext,\n RenderedMessage,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;;AA2BA,MAAM,4BAAY,IAAI,IAAI;CACxB;CACA;CACA;AACF,CAAC;AAED,SAAS,OAAO,OAAoC;CAClD,MAAM,OAAQ,OAAqC;CACnD,OAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAsBA,MAAM,QAAQ,OAA8B,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;;AAGhF,MAAM,eAAe;;;;;;;;AASrB,eAAe,YAAe,MAAkB,IAAwB;CACtE,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,MACA,IAAI,SAAgB,GAAG,WAAW;GAChC,QAAQ,iBAAiB;IACvB,MAAM,sBAAM,IAAI,MAAM,uBAAuB,GAAG,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MAdX,SACV,KACE,MACC,yDAAyD,WAAW,EAAE,OAAO,EAAE,mEAChB,EAAE,MAC9D,KACE,MACC,wEAAwE,WAAW,EAAE,KAAK,EAAE,iCAC/D,EAAE,KAAK,WACxC,CAAC,CACA,KAAK,EAAE,EAAE,SAChB,CAAC,CACA,KAAK,EAEmB;CAAE;AAC/B;;;;;;;;;;;AC/JA,eAAsB,OACpB,OACA,KACA,OAAmB,CAAC,GACpB,QAA0C,CAAC,GACpB;CACvB,MAAM,OAAO,kBAAkB,GAAG;CAClC,MAAM,UAA2B,CAAC;CAElC,IAAI,KAAK,MAAM,SAAS;EACtB,MAAM,UAAU,YAAY,OAAO;GAAE,GAAG;GAAO,WAAW,IAAI,eAAe;EAAU,CAAC;EACxF,QAAQ,KACN,KAAK,QAAQ,MAAM,UAAU,KAAK,OAAO,SAAS,KAAK,KAAK,IAAI,SAAS,KAAK,OAAO,OAAO,CAC9F;CACF,OACE,QAAQ,KAAK;EAAE,SAAS;EAAS,MAAM;EAAO,QAAQ,KAAK,MAAM,QAAQ;CAAkB,CAAC;CAG9F,OAAO;EAAE;EAAS,WAAW,QAAQ,MAAM,MAAM,EAAE,IAAI;CAAE;AAC3D"}
@@ -1,140 +1,9 @@
1
1
  import { n as findZoneId, r as listApexTxt, t as createApexTxt } from "../cloudflare-BiK61Oq4.mjs";
2
- import { i as GoogleOAuth, n as GoogleAuthLike } from "../token-Bz_-igw-.mjs";
3
-
4
- //#region src/onboarding/types.d.ts
5
- /**
6
- * The onboarding module's own option surface.
7
- *
8
- * Deliberately structural rather than `Config['site']['searchConsole']` imported
9
- * from `@getvitops/generator`: the generator already depends on this package, so
10
- * importing back would be a cycle. The vocabulary mirrors that block field for
11
- * field, so the CLI's adapter is a flat map — the same arrangement, and for the
12
- * same reason, as `IndexingConfig` beside it.
13
- *
14
- * Optional fields are written `?: T | undefined` throughout: `exactOptionalPropertyTypes`
15
- * is on, and these types describe a *parsed JSON config* where an absent key and an
16
- * explicit `undefined` are the same thing.
17
- */
18
- /** One domain to onboard, as the config declares it. */
19
- interface DomainSetup {
20
- /** The domain, bare (`acme.ca`). Becomes the `sc-domain:` property and the DNS zone name. */
21
- domain: string;
22
- /**
23
- * Emails added as verification owners on the Site Verification web resource.
24
- * Additive: existing owners are never removed.
25
- */
26
- delegatedOwners?: string[] | undefined;
27
- /**
28
- * A Google Group to grant Full-User access in Search Console. Surfaced as a
29
- * reminder only — Search Console has no user/permission API.
30
- */
31
- fullUserGroup?: string | undefined;
32
- }
33
- /** Everything `plan()` needs, once the CLI has read the config and creds. */
34
- interface OnboardingConfig {
35
- /** The domains to onboard. Already filtered to `--domain` if that was passed. */
36
- domains: DomainSetup[];
37
- }
38
- /**
39
- * One domain's observed live state, gathered by the executors before planning.
40
- *
41
- * `plan()` compares this against the desired `DomainSetup` to decide each step —
42
- * the same shape the indexing planner takes its sitemap snapshot in, for the same
43
- * reason: the decision is pure, the observation is not.
44
- */
45
- interface DomainState {
46
- /** The Cloudflare zone id for the domain, if one was found. */
47
- zoneId?: string | undefined;
48
- /** An apex TXT record already carrying the verification token exists. */
49
- txtPresent: boolean;
50
- /** The Site Verification web resource reports this domain as verified. */
51
- verified: boolean;
52
- /** Owners currently on the web resource (empty when not yet verified). */
53
- currentOwners: string[];
54
- /** A `sc-domain:` property already exists in Search Console. */
55
- propertyExists: boolean;
56
- }
57
- //#endregion
58
- //#region src/onboarding/plan.d.ts
59
- /** A step's decision: do it, or skip it because it already holds. */
60
- type StepAction = 'create' | 'update' | 'skip';
61
- interface StepPlan {
62
- action: StepAction;
63
- /** Why it's a skip, or what the mutation will do. */
64
- detail: string;
65
- }
66
- /** The four onboarding steps for one domain, decided against its live state. */
67
- interface DomainPlan {
68
- domain: string;
69
- /** `sc-domain:` property identifier this domain maps to. */
70
- siteUrl: string;
71
- /** Ensure the apex TXT verification record. */
72
- txt: StepPlan;
73
- /** Verify ownership via the Site Verification API (DNS_TXT). */
74
- verify: StepPlan;
75
- /** Add the Search Console domain property. */
76
- property: StepPlan;
77
- /** Add delegated owners to the verified web resource. */
78
- owners: StepPlan;
79
- /** Owners not yet present that the run should add. */
80
- ownersToAdd: string[];
81
- /** Manual follow-ups (e.g. a Full-User group). */
82
- reminders: string[];
83
- }
84
- interface OnboardingPlan {
85
- domains: DomainPlan[];
86
- /** Operator-facing warnings that span the whole run. */
87
- notes: string[];
88
- }
89
- /** The `sc-domain:` property identifier for a bare domain. */
90
- declare const siteUrlFor: (domain: string) => string;
91
- /**
92
- * Backoff ladder for the verification retry, in milliseconds.
93
- *
94
- * DNS_TXT verification fails until the record has propagated, which is a matter of
95
- * seconds-to-minutes, not a real error — so the schedule is a *policy*, decided
96
- * here and asserted in the tests, while the actual sleeping is the CLI's job.
97
- * Capped at `maxAttempts`; a domain still unverified after the last attempt is
98
- * reported PENDING, never failed.
99
- */
100
- declare function backoffSchedule(maxAttempts?: number): number[];
101
- /** Decide the four steps for one domain from its desired config and live state. */
102
- declare function planDomain(setup: DomainSetup, state: DomainState): DomainPlan;
103
- /**
104
- * The owner set to PUT: everyone already there, plus everyone being added.
105
- *
106
- * `updateOwners` REPLACES the owner list, so this is the one computation standing
107
- * between a delegation and locking yourself out — pass a bare `ownersToAdd` and
108
- * the account that just verified the domain is removed from it. It belongs here
109
- * rather than at the call site for exactly that reason: it is a decision, it is
110
- * the dangerous one, and the executor is not allowed to make it.
111
- *
112
- * `current` comes FIRST so the API's own casing survives dedupe; matching is
113
- * case-insensitive, mirroring `planDomain`'s `present` check, because Google
114
- * echoes back addresses in whatever case the account uses and a case-sensitive
115
- * `Set` would re-add an owner who is already there.
116
- */
117
- declare function ownerUnion(current: string[], toAdd: string[]): string[];
118
- /** Plan every domain. */
119
- declare function plan(config: OnboardingConfig, states: Map<string, DomainState>): OnboardingPlan;
120
- /** Any step on any domain is a mutation — i.e. the live state has drifted. */
121
- declare function hasDrift(p: OnboardingPlan): boolean;
122
- /** Render a plan as the block `--dry` and `--check` print. */
123
- declare function formatPlan(p: OnboardingPlan): string;
124
- /** The outcome of one domain's run, for the summary table. */
125
- interface DomainResult {
126
- domain: string;
127
- txt: 'created' | 'present' | 'failed' | '—';
128
- verified: 'yes' | 'pending' | 'failed' | '—';
129
- property: 'added' | 'present' | 'failed' | '—';
130
- reminders: string[];
131
- }
132
- /** Render the end-of-run summary: one row per domain, plus any reminders. */
133
- declare function formatSummary(results: DomainResult[]): string;
134
- //#endregion
2
+ import { i as GoogleOAuth, n as GoogleAuthLike } from "../token-DmmoQ7um.mjs";
3
+ import { a as StepPlan, c as formatSummary, d as plan, f as planDomain, g as OnboardingConfig, h as DomainState, i as StepAction, l as hasDrift, m as DomainSetup, n as DomainResult, o as backoffSchedule, p as siteUrlFor, r as OnboardingPlan, s as formatPlan, t as DomainPlan, u as ownerUnion } from "../plan-Hq8Pb0Uw.mjs";
135
4
  //#region src/onboarding/google.d.ts
136
5
  /** Exchange a user OAuth refresh token for a short-lived access token. */
137
- declare function refreshTokenGrant(oauth: GoogleOAuth, fetchImpl?: typeof fetch): Promise<string>;
6
+ export declare function refreshTokenGrant(oauth: GoogleOAuth, fetchImpl?: typeof fetch): Promise<string>;
138
7
  /**
139
8
  * Ask the Site Verification API for the DNS_TXT token for a domain.
140
9
  *
@@ -142,7 +11,7 @@ declare function refreshTokenGrant(oauth: GoogleOAuth, fetchImpl?: typeof fetch)
142
11
  * record. It is deterministic per (user, domain), so re-fetching it and comparing
143
12
  * against DNS is what makes the TXT step idempotent.
144
13
  */
145
- declare function getVerificationToken(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
14
+ export declare function getVerificationToken(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
146
15
  ok: boolean;
147
16
  status: number;
148
17
  token?: string;
@@ -156,7 +25,7 @@ declare function getVerificationToken(auth: GoogleAuthLike, domain: string, fetc
156
25
  * contains resources the user already owns — so a hit *is* the verified state, and
157
26
  * carries the id and owners the later steps need.
158
27
  */
159
- declare function getWebResource(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
28
+ export declare function getWebResource(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
160
29
  ok: boolean;
161
30
  status: number;
162
31
  exists: boolean;
@@ -165,7 +34,7 @@ declare function getWebResource(auth: GoogleAuthLike, domain: string, fetchImpl?
165
34
  message?: string;
166
35
  }>;
167
36
  /** Verify ownership (DNS_TXT). Succeeds only once the TXT record has propagated. */
168
- declare function verifyWebResource(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
37
+ export declare function verifyWebResource(auth: GoogleAuthLike, domain: string, fetchImpl?: typeof fetch): Promise<{
169
38
  ok: boolean;
170
39
  status: number;
171
40
  id?: string;
@@ -179,13 +48,13 @@ declare function verifyWebResource(auth: GoogleAuthLike, domain: string, fetchIm
179
48
  * current owners and the ones to add — never a bare list of new owners, which
180
49
  * would drop everyone already there.
181
50
  */
182
- declare function updateOwners(auth: GoogleAuthLike, id: string, domain: string, owners: string[], fetchImpl?: typeof fetch): Promise<{
51
+ export declare function updateOwners(auth: GoogleAuthLike, id: string, domain: string, owners: string[], fetchImpl?: typeof fetch): Promise<{
183
52
  ok: boolean;
184
53
  status: number;
185
54
  message?: string;
186
55
  }>;
187
56
  /** Whether a Search Console property already exists (`GET sites/{siteUrl}`). */
188
- declare function getSite(auth: GoogleAuthLike, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
57
+ export declare function getSite(auth: GoogleAuthLike, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
189
58
  ok: boolean;
190
59
  status: number;
191
60
  exists: boolean;
@@ -197,11 +66,11 @@ declare function getSite(auth: GoogleAuthLike, siteUrl: string, fetchImpl?: type
197
66
  * A `403` here almost always means the domain is not yet verified for this user
198
67
  * rather than a transient error — property creation is gated on ownership.
199
68
  */
200
- declare function addSite(auth: GoogleAuthLike, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
69
+ export declare function addSite(auth: GoogleAuthLike, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
201
70
  ok: boolean;
202
71
  status: number;
203
72
  message?: string;
204
73
  }>;
205
74
  //#endregion
206
- export { type DomainPlan, type DomainResult, type DomainSetup, type DomainState, type GoogleOAuth, type OnboardingConfig, type OnboardingPlan, type StepAction, type StepPlan, addSite, backoffSchedule, createApexTxt, findZoneId, formatPlan, formatSummary, getSite, getVerificationToken, getWebResource, hasDrift, listApexTxt, ownerUnion, plan, planDomain, refreshTokenGrant, siteUrlFor, updateOwners, verifyWebResource };
75
+ export { type DomainPlan, type DomainResult, type DomainSetup, type DomainState, type GoogleOAuth, type OnboardingConfig, type OnboardingPlan, type StepAction, type StepPlan, backoffSchedule, createApexTxt, findZoneId, formatPlan, formatSummary, hasDrift, listApexTxt, ownerUnion, plan, planDomain, siteUrlFor };
207
76
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/onboarding/types.ts","../../src/onboarding/plan.ts","../../src/onboarding/google.ts"],"mappings":";;;;;;;;AAeA;;;;;;;;AAYe;AAIf;AAAA,UAhBiB,WAAA;;EAEf,MAAA;EAgBoB;AAiBtB;;;EA5BE,eAAA;EA8BA;;;;EAzBA,aAAA;AAAA;AAiCc;AAAA,UA7BC,gBAAA;;EAEf,OAAA,EAAS,WAAW;AAAA;;;;;;;ACXd;UD4BS,WAAA;ECxBU;ED0BzB,MAAA;ECrBK;EDuBL,UAAA;ECnBU;EDqBV,QAAA;ECnBgB;EDqBhB,aAAA;EC/BA;EDiCA,cAAA;AAAA;;;;KC3CU,UAAA;AAAA,UAEK,QAAA;EACf,MAAA,EAAQ,UAAU;ED8BH;EC5Bf,MAAA;AAAA;;UAIe,UAAA;EACf,MAAA;ED6BA;EC3BA,OAAA;ED+BA;EC7BA,GAAA,EAAK,QAAA;ED6BS;EC3Bd,MAAA,EAAQ,QAAA;;EAER,QAAA,EAAU,QAAA;EAlBA;EAoBV,MAAA,EAAQ,QAAA;;EAER,WAAA;EAtBoB;EAwBp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AAM,cAAA,EACN,EAAA,UACA,MAAA,UACA,MAAA,YACA,SAAA,UAAkB,KAAA,GACjB,OAAA;EAAU,EAAA;EAAa,MAAA;EAAgB,OAAA;AAAA;;iBAWpB,OAAA,CACpB,IAAA,EAAM,cAAA,EACN,OAAA,UACA,SAAA,UAAkB,KAAA,GACjB,OAAA;EAAU,EAAA;EAAa,MAAA;EAAgB,MAAA;EAAiB,OAAA;AAAA;AD1GpD;AAIP;;;;AAAyC;AAJlC,iBCyHe,OAAA,CACpB,IAAA,EAAM,cAAA,EACN,OAAA,UACA,SAAA,UAAkB,KAAA,GACjB,OAAA;EAAU,EAAA;EAAa,MAAA;EAAgB,OAAA;AAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/onboarding/google.ts"],"mappings":";;;;;wBA+BgB,kBACd,OAAO,aACP,mBAAkB,QACjB;;;;;;;;wBAamB,qBACpB,MAAM,gBACN,gBACA,mBAAkB,QACjB;EAAU;EAAa;EAAgB;EAAgB;;;;;;;;;;wBAoBpC,eACpB,MAAM,gBACN,gBACA,mBAAkB,QACjB;EACD;EACA;EACA;EACA;EACA;EACA;;;wBAwBoB,kBACpB,MAAM,gBACN,gBACA,mBAAkB,QACjB;EAAU;EAAa;EAAgB;EAAa;EAAkB;;;;;;;;;wBAuBnD,aACpB,MAAM,gBACN,YACA,gBACA,kBACA,mBAAkB,QACjB;EAAU;EAAa;EAAgB;;;wBAWpB,QACpB,MAAM,gBACN,iBACA,mBAAkB,QACjB;EAAU;EAAa;EAAgB;EAAiB;;;;;;;;wBAerC,QACpB,MAAM,gBACN,iBACA,mBAAkB,QACjB;EAAU;EAAa;EAAgB"}
@@ -1,150 +1,7 @@
1
1
  import { a as googleHeaders, i as googleAccessToken, n as encodeSite, r as errorDetail } from "../token-DkKC5m23.mjs";
2
- import { t as table } from "../plan-format-A18SvJ7C.mjs";
2
+ import { a as ownerUnion, c as siteUrlFor, i as hasDrift, n as formatPlan, o as plan, r as formatSummary, s as planDomain, t as backoffSchedule } from "../plan-BLKikoOG.mjs";
3
3
  import { n as findZoneId, r as listApexTxt, t as createApexTxt } from "../cloudflare-CD8vwrgj.mjs";
4
4
 
5
- //#region src/onboarding/plan.ts
6
- /** The `sc-domain:` property identifier for a bare domain. */
7
- const siteUrlFor = (domain) => `sc-domain:${domain}`;
8
- /**
9
- * Backoff ladder for the verification retry, in milliseconds.
10
- *
11
- * DNS_TXT verification fails until the record has propagated, which is a matter of
12
- * seconds-to-minutes, not a real error — so the schedule is a *policy*, decided
13
- * here and asserted in the tests, while the actual sleeping is the CLI's job.
14
- * Capped at `maxAttempts`; a domain still unverified after the last attempt is
15
- * reported PENDING, never failed.
16
- */
17
- function backoffSchedule(maxAttempts = 5) {
18
- const out = [];
19
- for (let i = 1; i <= maxAttempts; i++) out.push(2 ** i * 1e3);
20
- return out;
21
- }
22
- /** Decide the four steps for one domain from its desired config and live state. */
23
- function planDomain(setup, state) {
24
- const reminders = [];
25
- if (setup.fullUserGroup) reminders.push(`add ${setup.fullUserGroup} as a Full User in Search Console — no API exists for this, do it in the UI`);
26
- const txt = state.txtPresent ? {
27
- action: "skip",
28
- detail: "apex TXT already present"
29
- } : {
30
- action: "create",
31
- detail: "create apex TXT verification record"
32
- };
33
- const verify = state.verified ? {
34
- action: "skip",
35
- detail: "ownership already verified"
36
- } : {
37
- action: "create",
38
- detail: "verify ownership (DNS_TXT)"
39
- };
40
- const property = state.propertyExists ? {
41
- action: "skip",
42
- detail: "property already exists"
43
- } : {
44
- action: "create",
45
- detail: `add property ${siteUrlFor(setup.domain)}`
46
- };
47
- const desired = setup.delegatedOwners ?? [];
48
- const present = new Set(state.currentOwners.map((o) => o.toLowerCase()));
49
- const ownersToAdd = desired.filter((o) => !present.has(o.toLowerCase()));
50
- const owners = desired.length === 0 ? {
51
- action: "skip",
52
- detail: "no delegated owners"
53
- } : ownersToAdd.length === 0 ? {
54
- action: "skip",
55
- detail: "all delegated owners already present"
56
- } : {
57
- action: "update",
58
- detail: `add ${ownersToAdd.length} owner(s): ${ownersToAdd.join(", ")}`
59
- };
60
- return {
61
- domain: setup.domain,
62
- siteUrl: siteUrlFor(setup.domain),
63
- txt,
64
- verify,
65
- property,
66
- owners,
67
- ownersToAdd,
68
- reminders
69
- };
70
- }
71
- /**
72
- * The owner set to PUT: everyone already there, plus everyone being added.
73
- *
74
- * `updateOwners` REPLACES the owner list, so this is the one computation standing
75
- * between a delegation and locking yourself out — pass a bare `ownersToAdd` and
76
- * the account that just verified the domain is removed from it. It belongs here
77
- * rather than at the call site for exactly that reason: it is a decision, it is
78
- * the dangerous one, and the executor is not allowed to make it.
79
- *
80
- * `current` comes FIRST so the API's own casing survives dedupe; matching is
81
- * case-insensitive, mirroring `planDomain`'s `present` check, because Google
82
- * echoes back addresses in whatever case the account uses and a case-sensitive
83
- * `Set` would re-add an owner who is already there.
84
- */
85
- function ownerUnion(current, toAdd) {
86
- const out = [];
87
- const seen = /* @__PURE__ */ new Set();
88
- for (const o of [...current, ...toAdd]) {
89
- const key = o.toLowerCase();
90
- if (seen.has(key)) continue;
91
- seen.add(key);
92
- out.push(o);
93
- }
94
- return out;
95
- }
96
- /** Plan every domain. */
97
- function plan(config, states) {
98
- const notes = [];
99
- return {
100
- domains: config.domains.map((setup) => {
101
- const state = states.get(setup.domain);
102
- if (!state) notes.push(`${setup.domain}: no observed state; treating everything as pending`);
103
- return planDomain(setup, state ?? {
104
- txtPresent: false,
105
- verified: false,
106
- currentOwners: [],
107
- propertyExists: false
108
- });
109
- }),
110
- notes
111
- };
112
- }
113
- /** Any step on any domain is a mutation — i.e. the live state has drifted. */
114
- function hasDrift(p) {
115
- return p.domains.some((d) => d.txt.action !== "skip" || d.verify.action !== "skip" || d.property.action !== "skip" || d.owners.action !== "skip");
116
- }
117
- /** Render a plan as the block `--dry` and `--check` print. */
118
- function formatPlan(p) {
119
- const lines = [];
120
- const glyph = (s) => s.action === "skip" ? "·" : "+";
121
- for (const d of p.domains) {
122
- lines.push(d.domain);
123
- lines.push(` ${glyph(d.txt)} TXT ${d.txt.detail}`);
124
- lines.push(` ${glyph(d.verify)} verify ${d.verify.detail}`);
125
- lines.push(` ${glyph(d.property)} property ${d.property.detail}`);
126
- lines.push(` ${glyph(d.owners)} owners ${d.owners.detail}`);
127
- for (const r of d.reminders) lines.push(` ! ${r}`);
128
- }
129
- for (const n of p.notes) lines.push(`! ${n}`);
130
- return lines.join("\n");
131
- }
132
- /** Render the end-of-run summary: one row per domain, plus any reminders. */
133
- function formatSummary(results) {
134
- return table([
135
- "DOMAIN",
136
- "TXT",
137
- "VERIFIED",
138
- "PROPERTY"
139
- ], results.map((r) => [
140
- r.domain,
141
- r.txt,
142
- r.verified,
143
- r.property
144
- ]), results.flatMap((r) => r.reminders.map((m) => ` ! ${r.domain}: ${m}`)));
145
- }
146
-
147
- //#endregion
148
5
  //#region src/onboarding/google.ts
149
6
  /**
150
7
  * Google — the two APIs onboarding drives, and the user-OAuth token behind both.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/onboarding/plan.ts","../../src/onboarding/google.ts"],"sourcesContent":["/**\n * Every decision `vitops search setup` makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no `fs`, no clock. The executors\n * beside this one gather each domain's live state and apply what they are told;\n * this module decides, from that state, what is left to do. That split is what\n * makes `--dry` a complete account of a run and `--check` an honest drift report —\n * the same arrangement the indexing planner makes against `gsc.ts`/`indexnow.ts`.\n *\n * Idempotency lives here too: a step whose desired state already holds resolves to\n * `skip`, so a re-run of a fully-onboarded domain is all skips — a no-op, by\n * construction rather than by the executors checking twice.\n */\nimport type { DomainSetup, DomainState, OnboardingConfig } from './types.ts';\nimport { table } from '../plan-format.ts';\n\n/** A step's decision: do it, or skip it because it already holds. */\nexport type StepAction = 'create' | 'update' | 'skip';\n\nexport interface StepPlan {\n action: StepAction;\n /** Why it's a skip, or what the mutation will do. */\n detail: string;\n}\n\n/** The four onboarding steps for one domain, decided against its live state. */\nexport interface DomainPlan {\n domain: string;\n /** `sc-domain:` property identifier this domain maps to. */\n siteUrl: string;\n /** Ensure the apex TXT verification record. */\n txt: StepPlan;\n /** Verify ownership via the Site Verification API (DNS_TXT). */\n verify: StepPlan;\n /** Add the Search Console domain property. */\n property: StepPlan;\n /** Add delegated owners to the verified web resource. */\n owners: StepPlan;\n /** Owners not yet present that the run should add. */\n ownersToAdd: string[];\n /** Manual follow-ups (e.g. a Full-User group). */\n reminders: string[];\n}\n\nexport interface OnboardingPlan {\n domains: DomainPlan[];\n /** Operator-facing warnings that span the whole run. */\n notes: string[];\n}\n\n/** The `sc-domain:` property identifier for a bare domain. */\nexport const siteUrlFor = (domain: string): string => `sc-domain:${domain}`;\n\n/**\n * Backoff ladder for the verification retry, in milliseconds.\n *\n * DNS_TXT verification fails until the record has propagated, which is a matter of\n * seconds-to-minutes, not a real error — so the schedule is a *policy*, decided\n * here and asserted in the tests, while the actual sleeping is the CLI's job.\n * Capped at `maxAttempts`; a domain still unverified after the last attempt is\n * reported PENDING, never failed.\n */\nexport function backoffSchedule(maxAttempts = 5): number[] {\n const out: number[] = [];\n for (let i = 1; i <= maxAttempts; i++) out.push(2 ** i * 1000);\n return out;\n}\n\n/** Decide the four steps for one domain from its desired config and live state. */\nexport function planDomain(setup: DomainSetup, state: DomainState): DomainPlan {\n const reminders: string[] = [];\n if (setup.fullUserGroup)\n reminders.push(\n `add ${setup.fullUserGroup} as a Full User in Search Console — no API exists for this, do it in the UI`,\n );\n\n const txt: StepPlan = state.txtPresent\n ? { action: 'skip', detail: 'apex TXT already present' }\n : { action: 'create', detail: 'create apex TXT verification record' };\n\n const verify: StepPlan = state.verified\n ? { action: 'skip', detail: 'ownership already verified' }\n : { action: 'create', detail: 'verify ownership (DNS_TXT)' };\n\n const property: StepPlan = state.propertyExists\n ? { action: 'skip', detail: 'property already exists' }\n : { action: 'create', detail: `add property ${siteUrlFor(setup.domain)}` };\n\n // Owners can only be read once verified; before that, treat every delegated\n // owner as still-to-add so --check reports the drift rather than hiding it.\n const desired = setup.delegatedOwners ?? [];\n const present = new Set(state.currentOwners.map((o) => o.toLowerCase()));\n const ownersToAdd = desired.filter((o) => !present.has(o.toLowerCase()));\n const owners: StepPlan =\n desired.length === 0\n ? { action: 'skip', detail: 'no delegated owners' }\n : ownersToAdd.length === 0\n ? { action: 'skip', detail: 'all delegated owners already present' }\n : {\n action: 'update',\n detail: `add ${ownersToAdd.length} owner(s): ${ownersToAdd.join(', ')}`,\n };\n\n return {\n domain: setup.domain,\n siteUrl: siteUrlFor(setup.domain),\n txt,\n verify,\n property,\n owners,\n ownersToAdd,\n reminders,\n };\n}\n\n/**\n * The owner set to PUT: everyone already there, plus everyone being added.\n *\n * `updateOwners` REPLACES the owner list, so this is the one computation standing\n * between a delegation and locking yourself out — pass a bare `ownersToAdd` and\n * the account that just verified the domain is removed from it. It belongs here\n * rather than at the call site for exactly that reason: it is a decision, it is\n * the dangerous one, and the executor is not allowed to make it.\n *\n * `current` comes FIRST so the API's own casing survives dedupe; matching is\n * case-insensitive, mirroring `planDomain`'s `present` check, because Google\n * echoes back addresses in whatever case the account uses and a case-sensitive\n * `Set` would re-add an owner who is already there.\n */\nexport function ownerUnion(current: string[], toAdd: string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const o of [...current, ...toAdd]) {\n const key = o.toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(o);\n }\n return out;\n}\n\n/** Plan every domain. */\nexport function plan(config: OnboardingConfig, states: Map<string, DomainState>): OnboardingPlan {\n const notes: string[] = [];\n const domains = config.domains.map((setup) => {\n const state = states.get(setup.domain);\n if (!state)\n // Should not happen — the CLI observes every domain before planning — but a\n // missing observation must not silently read as \"nothing to do\".\n notes.push(`${setup.domain}: no observed state; treating everything as pending`);\n return planDomain(\n setup,\n state ?? { txtPresent: false, verified: false, currentOwners: [], propertyExists: false },\n );\n });\n return { domains, notes };\n}\n\n/** Any step on any domain is a mutation — i.e. the live state has drifted. */\nexport function hasDrift(p: OnboardingPlan): boolean {\n return p.domains.some(\n (d) =>\n d.txt.action !== 'skip' ||\n d.verify.action !== 'skip' ||\n d.property.action !== 'skip' ||\n d.owners.action !== 'skip',\n );\n}\n\n/** Render a plan as the block `--dry` and `--check` print. */\nexport function formatPlan(p: OnboardingPlan): string {\n const lines: string[] = [];\n const glyph = (s: StepPlan) => (s.action === 'skip' ? '·' : '+');\n for (const d of p.domains) {\n lines.push(d.domain);\n lines.push(` ${glyph(d.txt)} TXT ${d.txt.detail}`);\n lines.push(` ${glyph(d.verify)} verify ${d.verify.detail}`);\n lines.push(` ${glyph(d.property)} property ${d.property.detail}`);\n lines.push(` ${glyph(d.owners)} owners ${d.owners.detail}`);\n for (const r of d.reminders) lines.push(` ! ${r}`);\n }\n for (const n of p.notes) lines.push(`! ${n}`);\n return lines.join('\\n');\n}\n\n/** The outcome of one domain's run, for the summary table. */\nexport interface DomainResult {\n domain: string;\n txt: 'created' | 'present' | 'failed' | '—';\n verified: 'yes' | 'pending' | 'failed' | '—';\n property: 'added' | 'present' | 'failed' | '—';\n reminders: string[];\n}\n\n/** Render the end-of-run summary: one row per domain, plus any reminders. */\nexport function formatSummary(results: DomainResult[]): string {\n const headers = ['DOMAIN', 'TXT', 'VERIFIED', 'PROPERTY'];\n const rows = results.map((r) => [r.domain, r.txt, r.verified, r.property]);\n const reminders = results.flatMap((r) => r.reminders.map((m) => ` ! ${r.domain}: ${m}`));\n return table(headers, rows, reminders);\n}\n","/**\n * Google — the two APIs onboarding drives, and the user-OAuth token behind both.\n *\n * Auth here is a **user OAuth refresh token**, not a service account: verifying a\n * site and adding a Search Console property act *as a person* who can own them, not\n * as a project robot. That makes the token exchange simpler than the indexing\n * module's — a `refresh_token` grant, no JWT and no `node:crypto` — but it needs\n * broader scope, granted when the refresh token is minted:\n * - `https://www.googleapis.com/auth/siteverification` (Site Verification API)\n * - `https://www.googleapis.com/auth/webmasters` (Search Console API)\n *\n * The exchange itself lives in `../google/token.ts`, shared with `indexing/gsc.ts`\n * — the grants differ, everything after building the form body did not. It throws\n * (nothing downstream can run without a token) while every API call below returns\n * a structured result and lets the caller decide per domain. `googleapis` is\n * deliberately not a dependency — these are a handful of REST endpoints in a CLI\n * that installs into every consumer.\n */\nimport {\n encodeSite,\n errorDetail,\n googleAccessToken,\n googleHeaders,\n type GoogleAuthLike,\n type GoogleOAuth,\n} from '../google/token.ts';\n\nconst SITEVERIFICATION = 'https://www.googleapis.com/siteVerification/v1';\nconst WEBMASTERS = 'https://www.googleapis.com/webmasters/v3';\n\n/** Exchange a user OAuth refresh token for a short-lived access token. */\nexport function refreshTokenGrant(\n oauth: GoogleOAuth,\n fetchImpl: typeof fetch = fetch,\n): Promise<string> {\n return googleAccessToken({ kind: 'oauth', oauth }, fetchImpl);\n}\n\nconst inetSite = (domain: string) => ({ type: 'INET_DOMAIN', identifier: domain });\n\n/**\n * Ask the Site Verification API for the DNS_TXT token for a domain.\n *\n * Returns the full `google-site-verification=…` value that goes in the apex TXT\n * record. It is deterministic per (user, domain), so re-fetching it and comparing\n * against DNS is what makes the TXT step idempotent.\n */\nexport async function getVerificationToken(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; token?: string; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/token`, {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ verificationMethod: 'DNS_TXT', site: inetSite(domain) }),\n });\n if (!res.ok) return { ok: false, status: res.status, message: await res.text() };\n const body = (await res.json()) as { token?: string };\n if (!body.token) return { ok: false, status: res.status, message: 'no token in response' };\n return { ok: true, status: res.status, token: body.token };\n}\n\n/**\n * Look up the verified web resource for a domain, if any.\n *\n * Uses `webResource.list` rather than a `get` by id, because the id format for an\n * INET_DOMAIN resource is awkward to construct by hand and the list only ever\n * contains resources the user already owns — so a hit *is* the verified state, and\n * carries the id and owners the later steps need.\n */\nexport async function getWebResource(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{\n ok: boolean;\n status: number;\n exists: boolean;\n id?: string;\n owners: string[];\n message?: string;\n}> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource`, {\n headers: googleHeaders(auth),\n });\n if (!res.ok)\n return { ok: false, status: res.status, exists: false, owners: [], message: await res.text() };\n const body = (await res.json()) as {\n items?: { id?: string; site?: { type?: string; identifier?: string }; owners?: string[] }[];\n };\n const match = body.items?.find(\n (it) => it.site?.type === 'INET_DOMAIN' && it.site?.identifier === domain,\n );\n if (!match) return { ok: true, status: res.status, exists: false, owners: [] };\n return {\n ok: true,\n status: res.status,\n exists: true,\n ...(match.id ? { id: match.id } : {}),\n owners: match.owners ?? [],\n };\n}\n\n/** Verify ownership (DNS_TXT). Succeeds only once the TXT record has propagated. */\nexport async function verifyWebResource(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; id?: string; owners: string[]; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource?verificationMethod=DNS_TXT`, {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ site: inetSite(domain), verificationMethod: 'DNS_TXT' }),\n });\n if (!res.ok) return { ok: false, status: res.status, owners: [], message: await res.text() };\n const body = (await res.json()) as { id?: string; owners?: string[] };\n return {\n ok: true,\n status: res.status,\n ...(body.id ? { id: body.id } : {}),\n owners: body.owners ?? [],\n };\n}\n\n/**\n * Set the owners of a verified web resource to a given list.\n *\n * The API replaces the owner set, so the caller passes the **union** of the\n * current owners and the ones to add — never a bare list of new owners, which\n * would drop everyone already there.\n */\nexport async function updateOwners(\n auth: GoogleAuthLike,\n id: string,\n domain: string,\n owners: string[],\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource/${encodeURIComponent(id)}`, {\n method: 'PUT',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ id, site: inetSite(domain), owners }),\n });\n if (!res.ok) return { ok: false, status: res.status, message: await res.text() };\n return { ok: true, status: res.status };\n}\n\n/** Whether a Search Console property already exists (`GET sites/{siteUrl}`). */\nexport async function getSite(\n auth: GoogleAuthLike,\n siteUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; exists: boolean; message?: string }> {\n const res = await fetchImpl(`${WEBMASTERS}/sites/${encodeSite(siteUrl)}`, {\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status, exists: true };\n if (res.status === 404) return { ok: true, status: res.status, exists: false };\n return { ok: false, status: res.status, exists: false, message: await res.text() };\n}\n\n/**\n * Add a Search Console property (`PUT sites/{siteUrl}`).\n *\n * A `403` here almost always means the domain is not yet verified for this user\n * rather than a transient error — property creation is gated on ownership.\n */\nexport async function addSite(\n auth: GoogleAuthLike,\n siteUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const res = await fetchImpl(`${WEBMASTERS}/sites/${encodeSite(siteUrl)}`, {\n method: 'PUT',\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status };\n const message = await errorDetail(res, (status) =>\n status === 403\n ? `403 — \"${siteUrl}\" is not verified for this account yet, or the OAuth token lacks the webmasters scope`\n : undefined,\n );\n return { ok: false, status: res.status, message };\n}\n"],"mappings":";;;;;;AAmDA,MAAa,cAAc,WAA2B,aAAa;;;;;;;;;;AAWnE,SAAgB,gBAAgB,cAAc,GAAa;CACzD,MAAM,MAAgB,CAAC;CACvB,KAAK,IAAI,IAAI,GAAG,KAAK,aAAa,KAAK,IAAI,KAAK,KAAK,IAAI,GAAI;CAC7D,OAAO;AACT;;AAGA,SAAgB,WAAW,OAAoB,OAAgC;CAC7E,MAAM,YAAsB,CAAC;CAC7B,IAAI,MAAM,eACR,UAAU,KACR,OAAO,MAAM,cAA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AS,MAAM,IAAI,KAAK;CAAE;CAC/E,OAAO;EAAE,IAAI;EAAM,QAAQ,IAAI;CAAO;AACxC;;AAGA,eAAsB,QACpB,MACA,SACA,YAA0B,OACmD;CAC7E,MAAM,MAAM,MAAM,UAAU,GAAG,WAAW,SAAS,WAAW,OAAO,KAAK,EACxE,SAAS,cAAc,IAAI,EAC7B,CAAC;CACD,IAAI,IAAI,IAAI,OAAO;EAAE,IAAI;EAAM,QAAQ,IAAI;EAAQ,QAAQ;CAAK;CAChE,IAAI,IAAI,WAAW,KAAK,OAAO;EAAE,IAAI;EAAM,QAAQ,IAAI;EAAQ,QAAQ;CAAM;CAC7E,OAAO;EAAE,IAAI;EAAO,QAAQ,IAAI;EAAQ,QAAQ;EAAO,SAAS,MAAM,IAAI,KAAK;CAAE;AACnF;;;;;;;AAQA,eAAsB,QACpB,MACA,SACA,YAA0B,OACkC;CAC5D,MAAM,MAAM,MAAM,UAAU,GAAG,WAAW,SAAS,WAAW,OAAO,KAAK;EACxE,QAAQ;EACR,SAAS,cAAc,IAAI;CAC7B,CAAC;CACD,IAAI,IAAI,IAAI,OAAO;EAAE,IAAI;EAAM,QAAQ,IAAI;CAAO;CAClD,MAAM,UAAU,MAAM,YAAY,MAAM,WACtC,WAAW,MACP,UAAU,QAAQ,yFAClB,MACN;CACA,OAAO;EAAE,IAAI;EAAO,QAAQ,IAAI;EAAQ;CAAQ;AAClD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/onboarding/google.ts"],"sourcesContent":["/**\n * Google — the two APIs onboarding drives, and the user-OAuth token behind both.\n *\n * Auth here is a **user OAuth refresh token**, not a service account: verifying a\n * site and adding a Search Console property act *as a person* who can own them, not\n * as a project robot. That makes the token exchange simpler than the indexing\n * module's — a `refresh_token` grant, no JWT and no `node:crypto` — but it needs\n * broader scope, granted when the refresh token is minted:\n * - `https://www.googleapis.com/auth/siteverification` (Site Verification API)\n * - `https://www.googleapis.com/auth/webmasters` (Search Console API)\n *\n * The exchange itself lives in `../google/token.ts`, shared with `indexing/gsc.ts`\n * — the grants differ, everything after building the form body did not. It throws\n * (nothing downstream can run without a token) while every API call below returns\n * a structured result and lets the caller decide per domain. `googleapis` is\n * deliberately not a dependency — these are a handful of REST endpoints in a CLI\n * that installs into every consumer.\n */\nimport {\n encodeSite,\n errorDetail,\n googleAccessToken,\n googleHeaders,\n type GoogleAuthLike,\n type GoogleOAuth,\n} from '../google/token.ts';\n\nconst SITEVERIFICATION = 'https://www.googleapis.com/siteVerification/v1';\nconst WEBMASTERS = 'https://www.googleapis.com/webmasters/v3';\n\n/** Exchange a user OAuth refresh token for a short-lived access token. */\nexport function refreshTokenGrant(\n oauth: GoogleOAuth,\n fetchImpl: typeof fetch = fetch,\n): Promise<string> {\n return googleAccessToken({ kind: 'oauth', oauth }, fetchImpl);\n}\n\nconst inetSite = (domain: string) => ({ type: 'INET_DOMAIN', identifier: domain });\n\n/**\n * Ask the Site Verification API for the DNS_TXT token for a domain.\n *\n * Returns the full `google-site-verification=…` value that goes in the apex TXT\n * record. It is deterministic per (user, domain), so re-fetching it and comparing\n * against DNS is what makes the TXT step idempotent.\n */\nexport async function getVerificationToken(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; token?: string; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/token`, {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ verificationMethod: 'DNS_TXT', site: inetSite(domain) }),\n });\n if (!res.ok) return { ok: false, status: res.status, message: await res.text() };\n const body = (await res.json()) as { token?: string };\n if (!body.token) return { ok: false, status: res.status, message: 'no token in response' };\n return { ok: true, status: res.status, token: body.token };\n}\n\n/**\n * Look up the verified web resource for a domain, if any.\n *\n * Uses `webResource.list` rather than a `get` by id, because the id format for an\n * INET_DOMAIN resource is awkward to construct by hand and the list only ever\n * contains resources the user already owns — so a hit *is* the verified state, and\n * carries the id and owners the later steps need.\n */\nexport async function getWebResource(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{\n ok: boolean;\n status: number;\n exists: boolean;\n id?: string;\n owners: string[];\n message?: string;\n}> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource`, {\n headers: googleHeaders(auth),\n });\n if (!res.ok)\n return { ok: false, status: res.status, exists: false, owners: [], message: await res.text() };\n const body = (await res.json()) as {\n items?: { id?: string; site?: { type?: string; identifier?: string }; owners?: string[] }[];\n };\n const match = body.items?.find(\n (it) => it.site?.type === 'INET_DOMAIN' && it.site?.identifier === domain,\n );\n if (!match) return { ok: true, status: res.status, exists: false, owners: [] };\n return {\n ok: true,\n status: res.status,\n exists: true,\n ...(match.id ? { id: match.id } : {}),\n owners: match.owners ?? [],\n };\n}\n\n/** Verify ownership (DNS_TXT). Succeeds only once the TXT record has propagated. */\nexport async function verifyWebResource(\n auth: GoogleAuthLike,\n domain: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; id?: string; owners: string[]; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource?verificationMethod=DNS_TXT`, {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ site: inetSite(domain), verificationMethod: 'DNS_TXT' }),\n });\n if (!res.ok) return { ok: false, status: res.status, owners: [], message: await res.text() };\n const body = (await res.json()) as { id?: string; owners?: string[] };\n return {\n ok: true,\n status: res.status,\n ...(body.id ? { id: body.id } : {}),\n owners: body.owners ?? [],\n };\n}\n\n/**\n * Set the owners of a verified web resource to a given list.\n *\n * The API replaces the owner set, so the caller passes the **union** of the\n * current owners and the ones to add — never a bare list of new owners, which\n * would drop everyone already there.\n */\nexport async function updateOwners(\n auth: GoogleAuthLike,\n id: string,\n domain: string,\n owners: string[],\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const res = await fetchImpl(`${SITEVERIFICATION}/webResource/${encodeURIComponent(id)}`, {\n method: 'PUT',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ id, site: inetSite(domain), owners }),\n });\n if (!res.ok) return { ok: false, status: res.status, message: await res.text() };\n return { ok: true, status: res.status };\n}\n\n/** Whether a Search Console property already exists (`GET sites/{siteUrl}`). */\nexport async function getSite(\n auth: GoogleAuthLike,\n siteUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; exists: boolean; message?: string }> {\n const res = await fetchImpl(`${WEBMASTERS}/sites/${encodeSite(siteUrl)}`, {\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status, exists: true };\n if (res.status === 404) return { ok: true, status: res.status, exists: false };\n return { ok: false, status: res.status, exists: false, message: await res.text() };\n}\n\n/**\n * Add a Search Console property (`PUT sites/{siteUrl}`).\n *\n * A `403` here almost always means the domain is not yet verified for this user\n * rather than a transient error — property creation is gated on ownership.\n */\nexport async function addSite(\n auth: GoogleAuthLike,\n siteUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const res = await fetchImpl(`${WEBMASTERS}/sites/${encodeSite(siteUrl)}`, {\n method: 'PUT',\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status };\n const message = await errorDetail(res, (status) =>\n status === 403\n ? `403 — \"${siteUrl}\" is not verified for this account yet, or the OAuth token lacks the webmasters scope`\n : undefined,\n );\n return { ok: false, status: res.status, message };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,mBAAmB;AACzB,MAAM,aAAa;;AAGnB,SAAgB,kBACd,OACA,YAA0B,OACT;CACjB,OAAO,kBAAkB;EAAE,MAAM;EAAS;CAAM,GAAG,SAAS;AAC9D;AAEA,MAAM,YAAY,YAAoB;CAAE,MAAM;CAAe,YAAY;AAAO;;;;;;;;AAShF,eAAsB,qBACpB,MACA,QACA,YAA0B,OACkD;CAC5E,M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