@aglyn/aglyn 1.0.0-beta.233 → 1.0.0-beta.235
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/lib/app-utils/activity-labels.d.ts +117 -0
- package/src/lib/app-utils/activity-labels.js +343 -0
- package/src/lib/app-utils/activity-labels.js.map +1 -0
- package/src/lib/app-utils/admin-audit-index.d.ts +11 -0
- package/src/lib/app-utils/admin-audit-index.js +12 -1
- package/src/lib/app-utils/admin-audit-index.js.map +1 -1
- package/src/lib/app-utils/advertising-consent.d.ts +111 -0
- package/src/lib/app-utils/advertising-consent.js +216 -0
- package/src/lib/app-utils/advertising-consent.js.map +1 -0
- package/src/lib/app-utils/advertising-events.d.ts +98 -0
- package/src/lib/app-utils/advertising-events.js +340 -0
- package/src/lib/app-utils/advertising-events.js.map +1 -0
- package/src/lib/app-utils/advertising-tag-mounts.js +15 -8
- package/src/lib/app-utils/advertising-tag-mounts.js.map +1 -1
- package/src/lib/app-utils/advertising-tags.d.ts +54 -8
- package/src/lib/app-utils/advertising-tags.js +126 -28
- package/src/lib/app-utils/advertising-tags.js.map +1 -1
- package/src/lib/app-utils/analytics-events.d.ts +15 -86
- package/src/lib/app-utils/analytics-events.js +21 -6
- package/src/lib/app-utils/analytics-events.js.map +1 -1
- package/src/lib/app-utils/consent-banner-ui.d.ts +14 -0
- package/src/lib/app-utils/consent-banner-ui.js +23 -2
- package/src/lib/app-utils/consent-banner-ui.js.map +1 -1
- package/src/lib/app-utils/docs-help-section-excerpt-text.d.ts +14 -0
- package/src/lib/app-utils/docs-help-section-excerpt-text.js +31 -0
- package/src/lib/app-utils/docs-help-section-excerpt-text.js.map +1 -0
- package/src/lib/app-utils/docs-help-section-excerpt.d.ts +13 -0
- package/src/lib/app-utils/docs-help-section-excerpt.js +37 -0
- package/src/lib/app-utils/docs-help-section-excerpt.js.map +1 -0
- package/src/lib/app-utils/docs-help-sections.generated.d.ts +31 -0
- package/src/lib/app-utils/docs-help-sections.generated.js +660 -0
- package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -0
- package/src/lib/app-utils/docs-help.d.ts +16 -4
- package/src/lib/app-utils/docs-help.generated.d.ts +171 -34
- package/src/lib/app-utils/docs-help.generated.js +1104 -3
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-help.js +25 -6
- package/src/lib/app-utils/docs-help.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +1008 -91
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/health-report.js +12 -0
- package/src/lib/app-utils/health-report.js.map +1 -1
- package/src/lib/app-utils/plugin-release-flags.generated.d.ts +1 -1
- package/src/lib/app-utils/plugin-release-flags.generated.js +7 -1
- package/src/lib/app-utils/plugin-release-flags.generated.js.map +1 -1
- package/src/lib/app-utils/realm-host-surface.generated.js +1 -0
- package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
- package/src/lib/app-utils/variables.d.ts +2 -0
- package/src/lib/app-utils/variables.js +3 -0
- package/src/lib/app-utils/variables.js.map +1 -1
- package/src/lib/app-utils/visitor-consent.d.ts +34 -0
- package/src/lib/app-utils/visitor-consent.js +49 -2
- package/src/lib/app-utils/visitor-consent.js.map +1 -1
- package/src/lib/app-utils/where-used-summary.d.ts +41 -0
- package/src/lib/app-utils/where-used-summary.js +33 -0
- package/src/lib/app-utils/where-used-summary.js.map +1 -0
- package/src/lib/app-utils/where-used.d.ts +2 -20
- package/src/lib/app-utils/where-used.js +13 -12
- package/src/lib/app-utils/where-used.js.map +1 -1
- package/src/lib/foundation/definitions/platform.types.d.ts +33 -0
- package/src/lib/foundation/definitions/platform.types.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.d.ts +7 -0
- package/src/lib/plugin-manager/first-party-plugins.generated.js +166 -2
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/plugin-activity-actions.d.ts +51 -0
- package/src/lib/plugin-manager/plugin-activity-actions.js +43 -0
- package/src/lib/plugin-manager/plugin-activity-actions.js.map +1 -1
- package/src/lib/plugin-manager/plugin-advertising-conversions.d.ts +84 -0
- package/src/lib/plugin-manager/plugin-advertising-conversions.js +86 -0
- package/src/lib/plugin-manager/plugin-advertising-conversions.js.map +1 -0
- package/src/lib/plugin-manager/plugin-config.d.ts +23 -0
- package/src/lib/plugin-manager/plugin-config.js.map +1 -1
- package/src/lib/plugin-manager/plugin-local-deliveries.d.ts +161 -0
- package/src/lib/plugin-manager/plugin-local-deliveries.js +46 -0
- package/src/lib/plugin-manager/plugin-local-deliveries.js.map +1 -0
- package/src/lib/plugin-manager/plugin-media-ingest.d.ts +87 -0
- package/src/lib/plugin-manager/plugin-media-ingest.js +34 -0
- package/src/lib/plugin-manager/plugin-media-ingest.js.map +1 -0
- package/src/lib/plugin-manager/plugin-order-email-copies.d.ts +93 -0
- package/src/lib/plugin-manager/plugin-order-email-copies.js +104 -0
- package/src/lib/plugin-manager/plugin-order-email-copies.js.map +1 -0
- package/src/lib/plugin-manager/plugin-shipment-records.d.ts +7 -0
- package/src/lib/plugin-manager/plugin-shipment-records.js.map +1 -1
- package/src/lib/plugin-manager/plugin-site-csp.d.ts +58 -0
- package/src/lib/plugin-manager/plugin-site-csp.js +103 -0
- package/src/lib/plugin-manager/plugin-site-csp.js.map +1 -0
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js +1 -0
- package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
- package/src/lib/plugin-manager/site-page-hooks.d.ts +13 -0
- package/src/lib/plugin-manager/site-page-hooks.js +31 -0
- package/src/lib/plugin-manager/site-page-hooks.js.map +1 -1
- package/src/lib/plugin-manager/stock-photo-provider.d.ts +141 -0
- package/src/lib/plugin-manager/stock-photo-provider.js +59 -0
- package/src/lib/plugin-manager/stock-photo-provider.js.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/analytics-events.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 * The one GA4 event taxonomy, shared by the marketing site (tenant runtime)\n * and the console (AGL-1561). See `docs/ANALYTICS.md` for the event map and\n * which GTM-plan §6 metric each event serves.\n *\n * ## Why this module exists\n *\n * Before it, every GA event in the repo was an ad-hoc\n * `;(window as any).gtag?.('event', 'name', {...})` — five of them across the\n * marketing and commerce plugins, plus bare string literals passed to Firebase\n * `logEvent` in the console. Nothing checked the names, nothing checked the\n * params, and a typo produced a silently-missing metric rather than an error.\n * That is the failure mode analytics is worst at surfacing: the number simply\n * reads zero, and zero is indistinguishable from \"nobody did it\".\n *\n * So the names and their params are a TYPE here ({@link AnalyticsEventParams}),\n * and `trackEvent` is generic over it: a misspelled event name or a missing\n * required param is a compile error.\n *\n * That sweep missed five (AGL-1591, closed): the commerce plugin's\n * `view_item` / `add_to_cart` / `begin_checkout` and the marketing runtime's\n * `aglyn_overlay` / `aglyn_experiment`. `window.gtag` is now called in exactly\n * two places in the repo — {@link deliver} below, and `readGaClientId` above,\n * which reads rather than sends.\n *\n * ## Reserved names\n *\n * Where GA4 has a recommended event we use its exact name and its exact param\n * spelling — `sign_up`, `login`, `generate_lead`, `begin_checkout`,\n * `purchase`, `select_content` — so the built-in reports, the funnel\n * explorations and the \"key events\" toggles work without custom definitions.\n * Custom snake_case names appear only where GA4 has no standard: the four\n * activation events, which are Aglyn-specific product milestones.\n *\n * ## Consent (AGL-1498) — the gate is that gtag never loads\n *\n * On tenant sites, including aglyn.com itself, `site-analytics.tsx` renders the\n * gtag `<Script>` pair ONLY when the recorded consent state grants analytics.\n * There is therefore no `window.gtag` at all for a visitor who has not granted,\n * and {@link trackEvent} drops the event on the floor.\n *\n * It drops it — it does not QUEUE it. That distinction is the whole point and\n * `analytics-events.spec.ts` asserts it: an event fired before consent is gone\n * for good, and does not reappear when a later grant loads gtag. A queue would\n * quietly convert \"we did not track you\" into \"we tracked you and waited\", and\n * a replayed hit carries the pre-consent timestamp and page into GA, which is\n * exactly the thing the consent gate exists to prevent. Deliberately no retry,\n * no buffer, no flush-on-grant.\n *\n * ## No PII, enforced rather than promised\n *\n * Every payload passes through {@link sanitizeEventParams} before it reaches a\n * transport: an exact-key denylist drops the identity-bearing params someone\n * will eventually add by reflex (`email`, `org_name`, `first_name`, ...), any\n * value that looks like an email address drops its key entirely, URLs are\n * reduced to origin + pathname so query strings can never smuggle a token or\n * an address, and strings are length-capped. The console separately sets a\n * `user_id` — that is an opaque Firebase uid and is the one identifier GA is\n * allowed to hold.\n *\n * Sanitizing here rather than at each call site is the point: a new call site\n * cannot forget.\n *\n * ## Authored events (AGL-1587)\n *\n * One call site cannot use the taxonomy at all: the `trackGaEvent` action step,\n * whose event name and params are typed by a SITE AUTHOR in the interaction\n * builder. A closed union cannot contain a name nobody has written yet, so\n * {@link trackAuthoredEvent} is the escape hatch — and it is deliberately the\n * only one, so that untrusted input still passes {@link sanitizeEventParams}\n * rather than reaching `window.gtag` raw.\n *\n * The test for which door an event uses is WHO NAMED IT, not whether GA4\n * recommends the name. `aglyn_overlay` and `aglyn_experiment` are outside GA4's\n * recommended set and were candidates for the hatch (AGL-1591); they are in the\n * union instead, because a developer wrote their names and their keys, so they\n * can have compile-time checking — and because the hatch guarantees the\n * opposite of what they need. {@link resolveAuthoredEventName} refuses any name\n * we send — the union AND the server-only names beside it — precisely so that\n * \"not one of ours\" means \"authored\"; put our own events through the hatch and\n * that stops being true, authored hits stop being separable from ours in\n * reports, and an authored `aglyn_experiment` step starts voting in the\n * experiment that decides which variant ships.\n */\n\n/**\n * Read the browser's GA `client_id` — the identifier that ties a hit to a GA\n * user and session.\n *\n * Needed because `purchase` is sent SERVER-side, from the Stripe webhook,\n * where the authoritative money is (see `ga4-measurement-protocol.ts`). The\n * Measurement Protocol requires a `client_id` and a server cannot know one,\n * so it is captured here when checkout starts and carried on the Stripe\n * object's metadata. Without it the revenue still lands, but attached to a\n * synthetic user with no acquisition session — which is exactly the campaign\n * attribution the whole exercise is for.\n *\n * Resolves to null rather than hanging when gtag is absent (no consent, an ad\n * blocker, analytics not configured) or slow to answer. The 500ms cap matters:\n * this sits directly in front of a checkout redirect, and analytics must never\n * be able to delay a payment.\n */\nexport function readGaClientId(\n measurementId: string | undefined | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n if (typeof window === 'undefined' || !measurementId) return resolve(null)\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return resolve(null)\n let settled = false\n const finish = (value: string | null) => {\n if (settled) return\n settled = true\n resolve(value)\n }\n // Never let a missing callback strand the checkout.\n setTimeout(() => finish(null), 500)\n try {\n ;(gtag as (...args: unknown[]) => void)(\n 'get',\n measurementId,\n 'client_id',\n (id: unknown) => finish(typeof id === 'string' && id ? id : null),\n )\n } catch {\n finish(null)\n }\n })\n}\n\n/** Which door an account was created through (AGL-1497 enumerates all four). */\nexport type SignUpMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'google_signin'\n\n/** How a returning user authenticated. */\nexport type LoginMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'sso'\n | 'passkey'\n\n/**\n * A GA4 `items` entry. Only the fields we actually populate — GA accepts more,\n * but an unpopulated field is a column of nulls in every report.\n */\nexport interface AnalyticsItem {\n /** Opaque identifier — a price id, plan key or marketplace listing id. */\n item_id: string\n /** Human-readable product name. NEVER a customer or org name. */\n item_name: string\n /** Distinguishes the revenue lines: `subscription` vs `marketplace`. */\n item_category?: string\n price?: number\n quantity?: number\n}\n\n/**\n * The taxonomy. Adding an event means adding a line here first — which is what\n * makes `docs/ANALYTICS.md` checkable against the code rather than aspirational.\n */\nexport interface AnalyticsEventParams {\n // --- Acquisition (GTM §6: signups, cost/lead by channel) -----------------\n /**\n * GA4 recommended. Real account creation only, never a sign-in.\n *\n * The three campaign params are optional and come from\n * `utmEventParams` (AGL-1731) — present when the signup URL named a\n * campaign, absent entirely otherwise. They are what lets a September ad\n * spend be evaluated: without them a paid click, an organic visit and a\n * partner link arrive indistinguishable and the money cannot be traced to\n * an account. Named `campaign_*` rather than `utm_*` because these are our\n * own registered dimensions and the `utm_` spellings belong to GA's\n * automatic campaign collection.\n */\n sign_up: {\n method: SignUpMethod\n campaign_source?: string\n campaign_medium?: string\n campaign_name?: string\n }\n /** GA4 recommended. Returning user only. */\n login: { method: LoginMethod }\n /**\n * GA4 recommended. Fired on a SUCCESSFUL form submission — never on click,\n * never on a validation failure. `form_name` is the author-given form name,\n * which is site content and not personal data.\n */\n generate_lead: { form_name: string; form_location?: string }\n /**\n * GA4 recommended. A CTA click, with the section that produced it.\n *\n * Fired by `analytics-link-clicks.ts` (AGL-1562) from a delegated listener,\n * not per call site: an authored page has no code to add a handler to.\n */\n select_content: {\n content_type: string\n content_id: string\n /** Which product surface — see `click.surface`. */\n surface?: string\n }\n\n // --- Activation (GTM §6: % publish a site, % connect Stripe) -------------\n /** Custom: no GA4 equivalent. A new organization exists. */\n org_created: { plan?: string }\n /** Custom: no GA4 equivalent. A new site/host exists. */\n host_created: Record<string, never>\n /**\n * Custom: no GA4 equivalent, and the GTM plan's headline activation metric.\n * A site actually went live.\n */\n site_published: { first_publish?: boolean }\n /**\n * Custom: no GA4 equivalent (AGL-3594). How a person chose to start a new\n * site in the guided start: the ready-made starter, or AI.\n */\n site_start_choice: { choice: 'starter' | 'ai' }\n /** Custom: no GA4 equivalent. Stripe Connect onboarding completed. */\n stripe_connected: Record<string, never>\n\n // --- Revenue (GTM §6: paid conversions, ARPA, annual mix) ---------------\n /** GA4 recommended. A plan checkout started. */\n begin_checkout: {\n currency: string\n value: number\n items: AnalyticsItem[]\n /** `monthly` | `annual` — feeds the §6 annual-mix metric. */\n billing_interval?: string\n }\n /**\n * GA4 recommended. A payment actually succeeded. `transaction_id` is the\n * Stripe object id and is what makes the event idempotent in GA: GA4\n * de-duplicates purchases by transaction id, so a webhook retry cannot\n * inflate revenue.\n */\n purchase: {\n transaction_id: string\n currency: string\n value: number\n items: AnalyticsItem[]\n billing_interval?: string\n /**\n * GA4's shipping charged on the transaction, in currency units. Optional\n * because only a tenant STOREFRONT purchase ships anything — a plan or a\n * marketplace purchase has no shipping to report and omits it.\n *\n * There is deliberately no sibling `tax` (AGL-1639, AGL-1641). The\n * asymmetry is the point and is not an inconsistency to tidy away:\n * `shipping` is a COMPONENT of the `value` beside it, so reporting it\n * describes that value; `tax` is not, because `value` is already ex-tax,\n * so reporting it would assert a relationship that does not hold and\n * invite the subtraction that removes tax a second time.\n */\n shipping?: number\n }\n\n // --- Commerce (tenant storefronts, AGL-1591) -----------------------------\n /**\n * GA4 recommended. A product detail page was viewed on a tenant storefront.\n *\n * Only `items`, and only `item_id`/`item_name` within it: those are the two\n * fields the storefront actually has at this point, and an unpopulated\n * `price`/`item_category` would be a column of nulls in the merchant's\n * reports. The item id is the PRODUCT id — the same id `add_to_cart` and\n * `begin_checkout` use — which is what lets GA join the three into one\n * per-product funnel.\n */\n view_item: { items: AnalyticsItem[] }\n /**\n * GA4 recommended. A storefront product was added to the cart.\n *\n * `currency`/`value` are optional because GA4 pairs them — a `value` with no\n * `currency` is dropped by GA — so they travel together or not at all, and\n * {@link buildAddToCartParams} is what keeps that true. They are populated\n * wherever the surface holds a server-priced figure: the product detail\n * block knows the resolved variant's price and the chosen quantity, so the\n * merchant's \"value added to cart\" is a real number rather than the empty\n * column an items-only hit produces.\n */\n add_to_cart: { currency?: string; value?: number; items: AnalyticsItem[] }\n /**\n * GA4 recommended. The shopper looked at their cart — the funnel step\n * between {@link AnalyticsEventParams.add_to_cart} and\n * {@link AnalyticsEventParams.begin_checkout}, and the one GA4's own\n * shopping-behavior report reads to tell \"never opened the cart\" apart from\n * \"opened it and did not check out\". Without it those two collapse into one\n * drop, and the merchant cannot tell a discovery problem from a pricing one.\n *\n * Fired when the cart is actually ON SCREEN carrying lines — a drawer that\n * opened, or an inline cart block that resolved — never on the badge render\n * that every page of a storefront performs. An empty cart is not a view of\n * anything and reports nothing.\n */\n view_cart: { currency: string; value: number; items: AnalyticsItem[] }\n\n // --- Engagement ---------------------------------------------------------\n /**\n * Custom: no GA4 equivalent. An announcement bar or popup was shown,\n * dismissed or clicked on a tenant site (AGL-200/271).\n *\n * In the taxonomy rather than {@link trackAuthoredEvent} even though it is\n * not a GA4 recommended name: the name and every key here are written by US,\n * which is exactly what the closed union is for. See the note on\n * {@link trackAuthoredEvent} for why the two must not be mixed.\n */\n aglyn_overlay: { overlay_action: string; overlay_id?: string }\n /**\n * Custom: no GA4 equivalent. An experiment exposure or conversion\n * (AGL-253). `experiment_action` is `exposure` | `conversion`.\n *\n * Being in the union also makes the name RESERVED against authored events,\n * which matters more here than anywhere else in this file: these are the\n * counts that decide which variant wins, and a hand-authored\n * `aglyn_experiment` step would silently vote in that election.\n */\n aglyn_experiment: {\n experiment_id: string\n variant_id: string\n experiment_action: string\n }\n /**\n * GA4 recommended-ish. Outbound click to docs, GitHub, etc. Fired by\n * `analytics-link-clicks.ts` (AGL-1562) rather than at a call site.\n */\n click: {\n link_domain: string\n link_id?: string\n /**\n * Which product surface produced the click. GA's built-in Hostname\n * dimension already separates the DOMAINS; this separates surfaces that\n * could share one, and keeps the shared click listener from having to\n * know anything about either.\n *\n * `site` — a tenant published site — is the only value ever SENT. `docs`\n * was designed for (AGL-1579) and is not emitted: `apps/docs` cannot\n * import `libs/`, so this listener is not installed there\n * (docs/ANALYTICS.md decision 7 has the Vercel setting that would change\n * that). Registering `surface` as a dimension and reading a one-value\n * breakdown is the trap — the absent `docs` row means \"no listener\", not\n * \"no clicks\".\n */\n surface?: string\n }\n /**\n * Custom: no GA4 equivalent. One Aglyn Assist message sent (AGL-1860).\n * `tier` is the capability tier served (`free` | `entitled`);\n * `grounded` says whether docs retrieval found sections to cite —\n * ungrounded questions at volume are the docs-gap signal the data loop\n * mines. No question text: params carry no user content.\n */\n assistant_message_sent: { tier: string; grounded: boolean }\n /**\n * Custom: no GA4 equivalent. Explicit thumbs on an Assist answer\n * (AGL-1860). `feedback` is `up` | `down`.\n */\n assistant_feedback: { feedback: string }\n /**\n * Custom: no GA4 equivalent. Aglyn Assist offered to open a page for the\n * user (AGL-1988, level 2). `action` is the registry action id — a closed\n * set, so it carries no user content.\n *\n * The pair below is the only read on whether the confirm gate is a real\n * choice or a speed bump people click through. A shown-to-confirmed ratio\n * near 1 means the card is not being read, and the copy has to change\n * BEFORE the ladder goes anywhere near a write.\n */\n assistant_proposal_shown: { action: string }\n /** Custom: no GA4 equivalent. The user confirmed and was navigated. */\n assistant_proposal_confirmed: { action: string }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `done`\n * (AGL-2904), observed from the console's jobs drawer. `kind` is the\n * closed `AiJobKind` set and `credits` the job's spend at the plan's\n * credit rate — no brief, no output: params carry no user content.\n */\n ai_job_completed: { kind: string; credits: number }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `failed`\n * (AGL-2904). `kind` only; the failure text is a fixed customer-safe\n * sentence and says nothing a rate could use.\n */\n ai_job_failed: { kind: string }\n /**\n * Custom: no GA4 equivalent. A \"Create with AI\" entry was opened on a plan\n * that could buy the AI add-on and has not (AGL-3601), so it showed the\n * add-on instead of a brief. `kind` is the closed set of what the entry\n * makes (`page`, `template`, `layout`, `form`, `component`, `workflow`);\n * `can_manage` is whether the reader could buy it themselves.\n */\n ai_upsell_shown: { kind: string; can_manage: boolean }\n /**\n * Custom: no GA4 equivalent. The reader followed that dialog to Billing's\n * add-ons — the numerator against `ai_upsell_shown`.\n */\n ai_upsell_clicked: { kind: string }\n\n // --- Retention (AGL-1859/AGL-1863: the leave path, measurable) -----------\n /**\n * Custom: no GA4 equivalent. The churn survey was answered — step 1 of the\n * cancellation/deletion funnel, and the DENOMINATOR every step below is a\n * rate against. Fired for both leave paths.\n *\n * `reason` is the closed `ChurnSurveyReason` set, never the free-text\n * detail: the detail is customer-written prose, it belongs in Firestore\n * where the data loop reads it, and shipping it to GA would put user\n * content in analytics params. `surface` separates a subscription cancel\n * from an account delete — counting only one understates churn by exactly\n * the orgs that chose the other.\n */\n churn_survey_submitted: { reason: string; surface: string; plan?: string }\n /**\n * Custom: no GA4 equivalent. The customer took the smaller tier instead of\n * leaving — a SAVE, at reduced ARPA. `from_plan`/`to_plan` are what makes\n * that tradeoff measurable rather than a win recorded without its cost.\n */\n downsell_accepted: { from_plan: string; to_plan: string; surface: string }\n /**\n * Custom: no GA4 equivalent. The time-boxed winback discount was accepted.\n *\n * `percent_off` and `duration_months` are reported because the discount is\n * bounded and the bound is the entire point (AGL-1620/AGL-1863): a retained\n * org and the margin it was retained at are one fact, and a save recorded\n * without its price reads as free.\n */\n winback_discount_accepted: {\n percent_off: number\n duration_months: number\n plan?: string\n surface: string\n }\n /**\n * Custom: no GA4 equivalent. They left anyway — the funnel's terminal step,\n * and the numerator for churn.\n *\n * `funnel_completed` is false when the cancel arrived without a funnelId\n * (support ops, Stripe dashboard). It mirrors the `funnelSkipped` marker\n * the routes write, so the GA funnel and the Firestore record agree instead\n * of quietly disagreeing about how many departures were ever surveyed.\n */\n cancellation_completed: {\n surface: string\n plan?: string\n funnel_completed: boolean\n }\n\n // --- Plan changes taken from the grid (AGL-2235, under AGL-1859 §4) ------\n /**\n * Custom: no GA4 equivalent. A downgrade was confirmed and SCHEDULED from\n * the billing plan grid — the same economic event `downsell_accepted`\n * records, arrived at by the other door.\n *\n * Why this has to exist separately: all four retention events above fire\n * from `retention-funnel.dialog.tsx` and from nowhere else. A customer who\n * moves Pro → Starter through the cancel funnel is counted; a customer who\n * moves Pro → Starter by clicking Downgrade on the plan card was counted by\n * nothing. So \"how many orgs moved down\" was unanswerable, and the number\n * that WAS answerable — `downsell_accepted` — undercounted by exactly the\n * share that took the direct route while reading like a total. A save rate\n * computed against it is wrong in the flattering direction, which is the\n * worst direction for a retention number to be wrong in.\n *\n * `effective_at` is the whole point of the event's name: this is the\n * asymmetric-friction arm of AGL-1859 §2, and a downgrade that has been\n * SCHEDULED is not a downgrade that has HAPPENED. Reported as the server's\n * ISO date so the gap between decision and effect — up to a full cycle, and\n * the window in which \"keep my plan\" can still save the org — is visible in\n * the data instead of being collapsed into the decision day.\n *\n * No amount, price or fee: pricing is locked for Sept 1, money belongs to\n * `purchase`/`refund`, and a tier pair already says what changed.\n */\n plan_downgrade_scheduled: {\n from_plan: string\n to_plan: string\n interval: string\n effective_at?: string\n }\n /**\n * Custom: no GA4 equivalent. An existing subscriber moved UP in place.\n *\n * Not `app_upgrade` — that name is GA4-RESERVED (it means an app binary\n * version bump) and a hit using it is dropped, which is silence rather than\n * pollution and therefore the harder failure to notice.\n *\n * `purchase` covers only the Checkout path, so before this, expansion\n * revenue from customers who ALREADY had a subscription was dark: the\n * in-place switch never opens a Checkout and never mints a new\n * subscription, so nothing in the revenue taxonomy saw it. Upgrades are the\n * half of AGL-1859 §2 that is supposed to be frictionless, and an\n * unmeasured half cannot be shown to be.\n */\n plan_upgraded: {\n from_plan: string\n to_plan: string\n interval: string\n }\n}\n\nexport type AnalyticsEventName = keyof AnalyticsEventParams\n\n/**\n * Where a sanitized event goes. The console registers a Firebase\n * `logEvent` transport; the tenant runtime and the plugin bundles have none\n * and fall through to `window.gtag`, which only exists once consent has been\n * granted.\n */\nexport type AnalyticsTransport = (\n name: AnalyticsEventName,\n params: Record<string, unknown>,\n) => void | Promise<void>\n\nlet configuredTransport: AnalyticsTransport | null = null\n\n/**\n * Register the transport for this surface. The console calls this once, with\n * Firebase's `logEvent`, because the console's GA is Firebase-initialised and\n * its `user_id`/user-property state lives on the Firebase Analytics instance —\n * poking `window.gtag` directly there would emit hits that miss it.\n *\n * The tenant runtime deliberately does NOT call this: the plugin bundles run\n * in their own realm and do not share this module instance with the host app,\n * so a module-scope singleton would be invisible to exactly the call sites\n * that need it (the form and newsletter elements). `window.gtag` is the only\n * thing genuinely shared across that boundary, and it is also the consent\n * gate, which makes the fallback the correct primary path there rather than a\n * degraded one.\n */\nexport function configureAnalyticsTransport(\n transport: AnalyticsTransport | null,\n): void {\n configuredTransport = transport\n}\n\n/** Test seam — drops the registered transport. */\nexport function resetAnalyticsTransport(): void {\n configuredTransport = null\n}\n\n/**\n * Param keys that must never reach GA, matched EXACTLY. Substring matching\n * would be wrong in both directions: it would drop the legitimate\n * `form_name` / `item_name` / `link_domain`, and it would still miss a\n * creatively-named new one. The value scan below is the backstop for those.\n */\nconst DENIED_PARAM_KEYS: ReadonlySet<string> = new Set([\n 'email',\n 'email_address',\n 'user_email',\n 'name',\n 'full_name',\n 'first_name',\n 'last_name',\n 'user_name',\n 'username',\n 'customer_name',\n 'org_name',\n 'organization_name',\n 'company',\n 'company_name',\n 'phone',\n 'phone_number',\n 'address',\n 'street',\n 'postal_code',\n 'zip',\n 'ip',\n 'ip_address',\n])\n\n/** Deliberately loose — this is a \"does it smell like an address\" test. */\nconst EMAIL_SHAPED = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\n/**\n * GA4 truncates param values at 100 chars anyway; do it ourselves, visibly.\n *\n * Exported because an AUTHOR types some of these (the `trackGaEvent` step's\n * parameters), and the field they type into caps its input at the same number\n * — the truncation point and the affordance that describes it have to be one\n * value, or the editor promises a length the delivery quietly shortens.\n */\nexport const ANALYTICS_PARAM_MAX_LENGTH = 100\n\nfunction scrubValue(value: string): string | null {\n let candidate = value\n if (/^https?:\\/\\//i.test(candidate)) {\n try {\n const url = new URL(candidate)\n // Origin + pathname only: a query string is where a session token, a\n // signup email or a Stripe id ends up, and none of them belong in GA.\n candidate = `${url.origin}${url.pathname}`\n } catch {\n return null\n }\n }\n // AFTER the URL reduction, not before. A page URL routinely carries an\n // address in its query (`?email=…` on a prefilled signup link), and testing\n // the raw string would throw the whole URL away for PII that the reduction\n // was about to remove — losing the legitimate page dimension to protect\n // something already protected. Testing the REDUCED value still catches an\n // address embedded in the path itself, which the reduction keeps.\n if (EMAIL_SHAPED.test(candidate)) return null\n return candidate.slice(0, ANALYTICS_PARAM_MAX_LENGTH)\n}\n\n/**\n * Strip anything identity-bearing from an event payload. Exported so\n * `analytics-events.spec.ts` can assert the guarantee directly rather than\n * only through `trackEvent`.\n */\nexport function sanitizeEventParams(\n params: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const safe: Record<string, unknown> = {}\n if (!params) return safe\n for (const [key, value] of Object.entries(params)) {\n if (DENIED_PARAM_KEYS.has(key.toLowerCase())) continue\n if (value === undefined || value === null) continue\n if (typeof value === 'string') {\n const scrubbed = scrubValue(value)\n if (scrubbed === null || scrubbed === '') continue\n safe[key] = scrubbed\n continue\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n safe[key] = value\n continue\n }\n if (Array.isArray(value)) {\n // `items` — sanitize each entry with the same rules.\n safe[key] = value.map((entry) =>\n entry && typeof entry === 'object'\n ? sanitizeEventParams(entry as Record<string, unknown>)\n : entry,\n )\n continue\n }\n if (typeof value === 'object') {\n safe[key] = sanitizeEventParams(value as Record<string, unknown>)\n }\n // Anything else (function, symbol) is dropped.\n }\n return safe\n}\n\n/**\n * Fire a GA4 event.\n *\n * Never throws and never queues. If the surface has no transport and no\n * `window.gtag` — which on a tenant site means the visitor has not granted\n * analytics consent — the event is DROPPED, permanently. See the module\n * comment for why a queue would be the wrong answer.\n */\nexport function trackEvent<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): void {\n deliver(name, sanitizeEventParams(params as Record<string, unknown>))\n}\n\n/**\n * How long a navigation may be held waiting for a hit to reach gtag. Short\n * enough to be invisible next to a Stripe redirect, long enough to cover a\n * Firebase Analytics init that has not settled yet.\n */\nconst NAVIGATION_FLUSH_TIMEOUT_MS = 300\n\n/**\n * Fire a GA4 event and resolve once it has been HANDED TO gtag — for the call\n * sites that navigate away in the same tick (AGL-1580).\n *\n * ## What was actually losing the event\n *\n * Not the transport, which was the obvious suspect and the wrong one. Measured\n * against real gtag.js with every transport interposed: gtag flushes its queue\n * on pagehide through `fetch(..., { keepalive: true })`, which is precisely the\n * mechanism that survives a document teardown. Once a hit reaches gtag, a\n * navigation does not destroy it — and `transport_type: 'beacon'`, the standard\n * answer, therefore fixes nothing here.\n *\n * What is lost is the hit that never REACHES gtag. Firebase's `logEvent` is\n * `async` and awaits the SDK's initialization promise before calling gtag\n * (`@firebase/analytics/dist/index.cjs.js`, `logEvent$1`). While that promise is\n * already settled the continuation is a microtask, microtasks drain before the\n * queued navigation task, and the hit gets out. While it is still PENDING — the\n * first checkout of a fresh session, exactly the case that has never yet been\n * seen in the property — the continuation is scheduled behind the navigation\n * and never runs at all. Measured both ways: pending init loses the event,\n * awaiting it delivers it, nothing else changed.\n *\n * ## Why a timeout rather than a bare await\n *\n * A bare `await` on `logEvent` hands the user's redirect to the analytics\n * stack. When the analytics host is blocked — an ad blocker, a corporate proxy,\n * a consent tool that never loads — Firebase's initialization promise can stay\n * pending indefinitely, and the checkout would hang on a metric. So the wait is\n * RACED against {@link NAVIGATION_FLUSH_TIMEOUT_MS}: a blocked analytics stack\n * costs the redirect 300ms once and then it proceeds, which is the same outcome\n * the caller had before this existed. Never rejects, for the same reason\n * {@link trackEvent} never throws.\n *\n * On a surface with no registered transport — the tenant runtime and the plugin\n * bundles, which go straight to `window.gtag` — delivery is synchronous, so\n * this resolves immediately and costs the storefront checkout nothing at all.\n */\nexport async function trackEventBeforeNavigation<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n): Promise<void> {\n const delivered = deliver(\n name,\n sanitizeEventParams(params as Record<string, unknown>),\n )\n // Synchronous transport (or none): already handed over, nothing to wait for.\n if (!delivered || typeof delivered.then !== 'function') return\n await Promise.race([\n // A transport that REJECTS must not become an unhandled rejection, and\n // must not hold the navigation either — it has already failed.\n Promise.resolve(delivered).catch((): void => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, NAVIGATION_FLUSH_TIMEOUT_MS),\n ),\n ])\n}\n\n/**\n * Build the ONE `begin_checkout` payload, for every surface that starts a\n * checkout (AGL-1591).\n *\n * ## Why a constructor and not just the type\n *\n * Two surfaces fire this name: the console, when a plan checkout starts, and a\n * tenant storefront, when a cart checks out. Until AGL-1591 the storefront\n * fired it raw and carried `value`/`currency` only, so ONE event name arrived\n * in two shapes — and a `begin_checkout` breakdown showed two populations that\n * could not be compared, with the storefront half missing the `items` the GA4\n * ecommerce funnel is built on. Routing both through {@link trackEvent} makes\n * the compiler settle the KEYS.\n *\n * It does not settle the NUMBER, which is the other way two call sites of one\n * event diverge, and the more dangerous one because nothing about it looks\n * wrong: the console's annual plans are priced per-month-billed-yearly, so its\n * `value` is twelve of them, and that only stayed right because a comment said\n * so. Here `value` DERIVES from the items unless a caller states a different\n * one — a cart states its subtotal, which is authoritative after discounts —\n * so \"what the customer is about to be charged\" has one definition rather than\n * one per surface.\n *\n * Server-safe: pure, no DOM, so the Measurement Protocol sender can compose\n * the matching `purchase` items from the same shapes.\n */\nexport function buildBeginCheckoutParams(input: {\n items: AnalyticsItem[]\n /**\n * The amount actually being charged. Defaults to the sum of the items'\n * `price * quantity`, which is right whenever nothing has adjusted it.\n */\n value?: number\n /** ISO 4217. Defaults to `USD`, the only currency either surface bills in. */\n currency?: string\n /** `monthly` | `annual`. Subscriptions only — a storefront cart has none. */\n billingInterval?: string\n}): AnalyticsEventParams['begin_checkout'] {\n return {\n ...priceItems(input),\n ...(input.billingInterval ? { billing_interval: input.billingInterval } : {}),\n }\n}\n\n/**\n * The `currency`/`value`/`items` triple every GA4 ecommerce step shares.\n *\n * Private, because a caller should reach for the named builder for the event\n * it is about to send: the names differ in what they mean by `value` even\n * though the arithmetic is identical, and the JSDoc on each is where that is\n * written down.\n */\nfunction priceItems(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): { currency: string; value: number; items: AnalyticsItem[] } {\n const items = input.items ?? []\n const summed = items.reduce(\n (total, item) => total + (item.price ?? 0) * (item.quantity ?? 1),\n 0,\n )\n return {\n currency: input.currency ?? 'USD',\n // Money, so two decimals: a float sum of cents-derived prices produces\n // `59.99999999999999`, and GA would report that verbatim.\n value: Math.round((input.value ?? summed) * 100) / 100,\n items,\n }\n}\n\n/**\n * Build `view_cart` — the shopper is looking at the cart's contents.\n *\n * `value` is the cart's subtotal as the SERVER priced it, which is what makes\n * this comparable with the `begin_checkout` the same cart sends moments later:\n * two steps of one funnel that disagreed about the size of the same cart would\n * read as shoppers editing it between screens.\n */\nexport function buildViewCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['view_cart'] {\n return priceItems(input)\n}\n\n/**\n * Build `add_to_cart` — one product going in, not the cart's new total.\n *\n * `value` is what was JUST ADDED (`price * quantity`), which is GA4's\n * definition and the only one that makes the metric additive: summing a\n * running cart total over a session would count the first item once per\n * subsequent add.\n *\n * Callers that cannot price the line — a quick-add with no resolved variant —\n * pass items alone and the pair is omitted rather than reported as zero. A\n * zero here would read as a free product in the merchant's report.\n */\nexport function buildAddToCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['add_to_cart'] {\n const priced = priceItems(input)\n if (!(priced.value > 0)) return { items: priced.items }\n return priced\n}\n\n/**\n * Decide `site_published`'s `first_publish` from the host's routing map as it\n * stood BEFORE the route being published was registered (AGL-1588).\n *\n * ## What \"first\" means, and why it is defined once\n *\n * Three call sites report `site_published` — `publishScreenRoute`, the\n * besigner's one-click publish, and the scheduled publish executor, the last\n * of which is server-side and sends over the Measurement Protocol. A\n * breakdown is only worth registering if all three mean the same thing by it,\n * and \"first\" has several plausible readings. This is the one they share:\n *\n * **The host had no live route at all before this one.** Not \"first for the\n * org\" — that needs a cross-host query the server path cannot make, and the\n * scheduled sender's client id is derived from the HOST anyway, so an org is\n * not a thing it can see. Not \"first for this screen\" either, which would be\n * true of every second page a site adds and would make the dimension a\n * synonym for the event.\n *\n * So the metric it separates is the GTM §6 activation one: `first_publish:\n * true` counts sites that came alive, where the event alone counts publishes.\n *\n * ## The one dishonesty, and why it does not matter\n *\n * Unpublishing every route and publishing again reports `true` a second time.\n * Detecting that needs publish history the routing map does not keep. It is\n * harmless for the metric it exists for, because activation is read as the\n * share of USERS who ever sent `first_publish: true`, and a user counted twice\n * is still one user.\n *\n * Callers pass what they already hold — the live-subscribed map in the\n * console, a read snapshot on the server — and never a map read back AFTER\n * the write, which is never empty.\n *\n * ## The placeholder home page is not a publish (AGL-3408)\n *\n * Every new site is created with a home page already routed at `/`, so read\n * literally the map is never empty and no site would ever report a first\n * publish. The host's `defaultHomeScreenId` names that placeholder, and its\n * entry is not counted: the site \"came alive\" when its owner put something on\n * it, not when the platform did. Republishing the placeholder itself after\n * editing it counts, which is the same act: that publish is read against the\n * map with the marker still set, and clears it in the same write (AGL-3478).\n */\nexport function isFirstPublishedRoute(\n routing: Record<string, unknown> | null | undefined,\n defaultHomeScreenId?: string | null,\n): boolean {\n return !Object.keys(routing ?? {}).some(\n (screenId) => screenId !== defaultHomeScreenId,\n )\n}\n\n/**\n * The one delivery path, shared by {@link trackEvent} and\n * {@link trackAuthoredEvent}. Takes an ALREADY-sanitized payload — every\n * caller sanitizes first, which is what keeps \"a new call site cannot forget\"\n * true of the authored path too.\n */\nfunction deliver(\n name: string,\n safe: Record<string, unknown>,\n): void | Promise<void> {\n try {\n if (configuredTransport) {\n // The transport's name parameter is the taxonomy union, which an\n // authored name is by definition outside. Nominal only: the console is\n // the sole surface that registers one and it has no authored events\n // (the interaction runtime is tenant-side), and Firebase `logEvent`\n // takes an arbitrary string regardless.\n // Returned, not discarded (AGL-1580). A transport may be ASYNC —\n // Firebase's `logEvent` awaits the SDK's initialization promise before it\n // reaches gtag at all — and a caller that is about to navigate has to be\n // able to wait for it. See `trackEventBeforeNavigation`.\n return configuredTransport(name as AnalyticsEventName, safe)\n }\n if (typeof window === 'undefined') return\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return\n // Synchronous, so nothing is returned and nothing needs awaiting: by the\n // time this call has returned, gtag.js already holds the hit.\n ;(gtag as (...args: unknown[]) => void)('event', name, safe)\n } catch {\n // Analytics never breaks the page — the same posture as the error beacon\n // and the pageview beacon.\n }\n}\n\n/**\n * The taxonomy's names at RUN time. A `Record<AnalyticsEventName, true>` rather\n * than a hand-kept array so the compiler enforces both directions: adding an\n * event to {@link AnalyticsEventParams} without adding it here is a missing-key\n * error, and a name here that is not in the taxonomy is an excess-property one.\n *\n * It exists for {@link trackAuthoredEvent}, which has to refuse these names —\n * a drifting copy would silently re-open the collision it is here to close.\n */\nconst TAXONOMY_EVENT_NAMES: Record<AnalyticsEventName, true> = {\n sign_up: true,\n login: true,\n generate_lead: true,\n select_content: true,\n org_created: true,\n host_created: true,\n site_published: true,\n site_start_choice: true,\n stripe_connected: true,\n begin_checkout: true,\n purchase: true,\n view_item: true,\n add_to_cart: true,\n view_cart: true,\n aglyn_overlay: true,\n aglyn_experiment: true,\n click: true,\n assistant_message_sent: true,\n assistant_feedback: true,\n assistant_proposal_shown: true,\n assistant_proposal_confirmed: true,\n ai_job_completed: true,\n ai_job_failed: true,\n ai_upsell_shown: true,\n ai_upsell_clicked: true,\n churn_survey_submitted: true,\n downsell_accepted: true,\n winback_discount_accepted: true,\n cancellation_completed: true,\n plan_downgrade_scheduled: true,\n plan_upgraded: true,\n}\n\n/** The taxonomy, enumerable. */\nexport const ANALYTICS_EVENT_NAMES = Object.keys(\n TAXONOMY_EVENT_NAMES,\n) as AnalyticsEventName[]\n\n/**\n * Event names WE send that this module's union cannot hold, because nothing\n * client-side ever fires them: they are emitted only by the Measurement\n * Protocol sender (`ga4-measurement-protocol.ts`), from a Stripe webhook.\n *\n * They still have to be RESERVED against authored names, and the reason is\n * the same one that puts `purchase` in the union — only less obvious, which\n * is why it was missed. `aglyn.com` is itself a tenant site, pointed at the\n * platform measurement id (`site-analytics.tsx`), so an authored\n * `trackGaEvent` step on our own marketing site lands in the SAME property as\n * these server hits. An authored `refund` does not merely add noise: GA4\n * treats `refund` as ecommerce and SUBTRACTS its `value` from reported\n * revenue, so a mistyped step could walk real money out of the report — the\n * `purchase` hazard, running in the direction nobody audits.\n *\n * Kept as a separate list rather than folded into {@link AnalyticsEventParams}\n * on purpose: adding them to the union would give {@link trackEvent} a\n * client-side door to events that must only ever come from the server, where\n * the authoritative money is. A name here is ours, is never sent from a\n * browser, and is never available to an author.\n *\n * This list is the reason \"not in {@link ANALYTICS_EVENT_NAMES}\" is NOT on its\n * own a sound test for \"authored\" — use {@link isReservedAnalyticsEventName}.\n */\nconst SERVER_ONLY_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'refund',\n 'subscription_cancelled',\n])\n\n/**\n * Every event name Aglyn itself sends, from any surface — the union plus the\n * server-only names above. Exported so a caller can ask the question the two\n * separate lists no longer answer alone.\n */\nexport function isReservedAnalyticsEventName(name: string): boolean {\n return (\n TAXONOMY_EVENT_NAMES[name as AnalyticsEventName] === true ||\n SERVER_ONLY_EVENT_NAMES.has(name)\n )\n}\n\n/**\n * GA4's own reserved event names — GA drops a hit that uses one, so sending it\n * is not pollution but silence, which is the worse failure of the two because\n * nothing anywhere says so.\n */\nconst GA4_RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_background',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_convert',\n 'app_store_subscription_renew',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n])\n\n/** GA4 reserves these prefixes outright, whatever follows them. */\nconst GA4_RESERVED_PREFIXES = ['firebase_', 'google_', 'ga_'] as const\n\n/** GA4's hard limit on an event name. Over it, GA drops the event. */\nconst MAX_EVENT_NAME_LENGTH = 40\n\n/**\n * The outcome of putting an authored name through GA4's rules, so the\n * interaction builder can say WHY it refused a name and the runtime can drop\n * the event for the same reason.\n */\nexport interface ResolvedAuthoredEventName {\n /** The name to send, or null when the event must not be sent at all. */\n name: string | null\n /**\n * `reserved` — collides with the taxonomy or with GA4's own names.\n * `unusable` — nothing survives normalization (empty, or no leading letter).\n */\n reason?: 'reserved' | 'unusable'\n}\n\n/**\n * Put an authored event name through GA4's naming rules and our own.\n *\n * Normalization is forgiving on purpose: `\"CTA Click!\"` becomes `cta_click`\n * and still reports, where GA would have dropped it. Names already sitting in\n * published sites were never validated, so refusing them outright would delete\n * working metrics from a paying customer's property to fix a formatting nit.\n *\n * Collisions, in contrast, are refused rather than rewritten. On a tenant site\n * the authored events and OUR events (`generate_lead` from the form element,\n * `select_content`/`click` from the link listener) land in the same property,\n * so an authored `purchase` does not merely add noise — it mixes hand-authored\n * hits into a real revenue number. Refusing is also what keeps authored events\n * separable in reports: an event that is not one of {@link ANALYTICS_EVENT_NAMES}\n * is, by construction, authored.\n *\n * Deliberately NOT prefixed (`site_*`) to achieve that separation. A prefix\n * would rename events already flowing into customers' properties and break\n * every report and key-event conversion configured on the old name — a\n * migration cost paid by people who did nothing wrong.\n */\nexport function resolveAuthoredEventName(\n raw: string | undefined | null,\n): ResolvedAuthoredEventName {\n const normalized = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Anything GA4 does not allow in a name becomes an underscore...\n .replace(/[^a-z0-9_]+/g, '_')\n // ...and a name must START with a letter, so drop what precedes one.\n .replace(/^[^a-z]+/, '')\n .replace(/_{2,}/g, '_')\n .slice(0, MAX_EVENT_NAME_LENGTH)\n // Truncation can leave a trailing underscore; so can the substitution.\n .replace(/_+$/, '')\n if (!normalized) return { name: null, reason: 'unusable' }\n if (\n isReservedAnalyticsEventName(normalized) ||\n GA4_RESERVED_EVENT_NAMES.has(normalized) ||\n GA4_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))\n ) {\n return { name: null, reason: 'reserved' }\n }\n return { name: normalized }\n}\n\n/** One warning per distinct name per page load — an `everyTime` automation\n * would otherwise fill the console with the same line. */\nconst warnedAuthoredNames = new Set<string>()\n\n/**\n * Fire an event whose name and params were written by a SITE AUTHOR, not by a\n * developer — today only the `trackGaEvent` action step (AGL-1587).\n *\n * Same consent gate, same sanitizer, same drop-never-queue posture as\n * {@link trackEvent}; the only difference is that the name is checked at run\n * time instead of by the compiler, because there is no compiler between the\n * interaction builder and here.\n *\n * A refused event is dropped and warned about in the console rather than\n * surfaced in the page. Nothing here can reach the author — the code is\n * running for a VISITOR of their site, and turning the author's configuration\n * mistake into something a visitor sees would be a worse bug than the missing\n * metric. The author-facing half lives in `validateInteraction`, which refuses\n * to save a name this function would refuse to send, so a silent drop should\n * only ever happen to a step authored before AGL-1587.\n */\nexport function trackAuthoredEvent(\n name: string | undefined | null,\n params?: Record<string, unknown> | null,\n): void {\n const resolved = resolveAuthoredEventName(name)\n if (!resolved.name) {\n const key = String(name ?? '')\n if (!warnedAuthoredNames.has(key)) {\n warnedAuthoredNames.add(key)\n try {\n console.warn(\n `[aglyn] analytics: the event \"${key}\" was not sent — ` +\n (resolved.reason === 'reserved'\n ? 'that name is reserved. Rename the step in the interaction builder.'\n : 'an event name must start with a letter.'),\n )\n } catch {\n // A console that throws is still not worth breaking the page for.\n }\n }\n return\n }\n deliver(resolved.name, sanitizeEventParams(params ?? undefined))\n}\n\n/** Test seam — forgets which authored names have already been warned about. */\nexport function resetAuthoredEventWarnings(): void {\n warnedAuthoredNames.clear()\n}\n"],"names":["readGaClientId","measurementId","Promise","resolve","window","gtag","settled","finish","value","setTimeout","id","configuredTransport","configureAnalyticsTransport","transport","resetAnalyticsTransport","DENIED_PARAM_KEYS","Set","EMAIL_SHAPED","ANALYTICS_PARAM_MAX_LENGTH","scrubValue","candidate","test","url","URL","origin","pathname","slice","sanitizeEventParams","params","safe","key","Object","entries","has","toLowerCase","undefined","scrubbed","Array","isArray","map","entry","trackEvent","name","deliver","NAVIGATION_FLUSH_TIMEOUT_MS","trackEventBeforeNavigation","delivered","then","race","catch","buildBeginCheckoutParams","input","priceItems","billingInterval","billing_interval","items","summed","reduce","total","item","price","quantity","currency","Math","round","buildViewCartParams","buildAddToCartParams","priced","isFirstPublishedRoute","routing","defaultHomeScreenId","keys","some","screenId","TAXONOMY_EVENT_NAMES","sign_up","login","generate_lead","select_content","org_created","host_created","site_published","site_start_choice","stripe_connected","begin_checkout","purchase","view_item","add_to_cart","view_cart","aglyn_overlay","aglyn_experiment","click","assistant_message_sent","assistant_feedback","assistant_proposal_shown","assistant_proposal_confirmed","ai_job_completed","ai_job_failed","ai_upsell_shown","ai_upsell_clicked","churn_survey_submitted","downsell_accepted","winback_discount_accepted","cancellation_completed","plan_downgrade_scheduled","plan_upgraded","ANALYTICS_EVENT_NAMES","SERVER_ONLY_EVENT_NAMES","isReservedAnalyticsEventName","GA4_RESERVED_EVENT_NAMES","GA4_RESERVED_PREFIXES","MAX_EVENT_NAME_LENGTH","resolveAuthoredEventName","raw","normalized","String","trim","replace","reason","prefix","startsWith","warnedAuthoredNames","trackAuthoredEvent","resolved","add","console","warn","resetAuthoredEventWarnings","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFC,GAED;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASA,eACdC,aAAwC;IAExC,OAAO,IAAIC,QAAQ,CAACC;QAClB,IAAI,OAAOC,WAAW,eAAe,C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AI,EAAE;QAClB,MAAMZ,MAAMqF,OAAOzE,eAAAA,OAAQ;QAC3B,IAAI,CAAC+E,oBAAoBxF,GAAG,CAACH,MAAM;YACjC2F,oBAAoBG,GAAG,CAAC9F;YACxB,IAAI;gBACF+F,QAAQC,IAAI,CACV,CAAC,8BAA8B,EAAEhG,IAAI,iBAAiB,CAAC,GACpD6F,CAAAA,SAASL,MAAM,KAAK,aACjB,uEACA,yCAAwC;YAElD,EAAE,eAAM;YACN,kEAAkE;YACpE;QACF;QACA;IACF;IACA3E,QAAQgF,SAASjF,IAAI,EAAEf,oBAAoBC,iBAAAA,SAAUO;AACvD;AAEA,6EAA6E,GAC7E,OAAO,SAAS4F;IACdN,oBAAoBO,KAAK;AAC3B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/analytics-events.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 * The one GA4 event taxonomy, shared by the marketing site (tenant runtime)\n * and the console (AGL-1561). See `docs/ANALYTICS.md` for the event map and\n * which GTM-plan §6 metric each event serves.\n *\n * ## Why this module exists\n *\n * Before it, every GA event in the repo was an ad-hoc\n * `;(window as any).gtag?.('event', 'name', {...})` — five of them across the\n * marketing and commerce plugins, plus bare string literals passed to Firebase\n * `logEvent` in the console. Nothing checked the names, nothing checked the\n * params, and a typo produced a silently-missing metric rather than an error.\n * That is the failure mode analytics is worst at surfacing: the number simply\n * reads zero, and zero is indistinguishable from \"nobody did it\".\n *\n * So the names and their params are a TYPE here ({@link AnalyticsEventParams}),\n * and `trackEvent` is generic over it: a misspelled event name or a missing\n * required param is a compile error.\n *\n * That sweep missed five (AGL-1591, closed): the commerce plugin's\n * `view_item` / `add_to_cart` / `begin_checkout` and the marketing runtime's\n * `aglyn_overlay` / `aglyn_experiment`. `window.gtag` is now called in exactly\n * two places in the repo — {@link deliver} below, and `readGaClientId` above,\n * which reads rather than sends.\n *\n * ## Reserved names\n *\n * Where GA4 has a recommended event we use its exact name and its exact param\n * spelling — `sign_up`, `login`, `generate_lead`, `begin_checkout`,\n * `purchase`, `select_content` — so the built-in reports, the funnel\n * explorations and the \"key events\" toggles work without custom definitions.\n * Custom snake_case names appear only where GA4 has no standard: the four\n * activation events, which are Aglyn-specific product milestones.\n *\n * ## Consent (AGL-1498) — the gate is that gtag never loads\n *\n * On tenant sites, including aglyn.com itself, `site-analytics.tsx` renders the\n * gtag `<Script>` pair ONLY when the recorded consent state grants analytics.\n * There is therefore no `window.gtag` at all for a visitor who has not granted,\n * and {@link trackEvent} drops the event on the floor.\n *\n * It drops it — it does not QUEUE it. That distinction is the whole point and\n * `analytics-events.spec.ts` asserts it: an event fired before consent is gone\n * for good, and does not reappear when a later grant loads gtag. A queue would\n * quietly convert \"we did not track you\" into \"we tracked you and waited\", and\n * a replayed hit carries the pre-consent timestamp and page into GA, which is\n * exactly the thing the consent gate exists to prevent. Deliberately no retry,\n * no buffer, no flush-on-grant.\n *\n * ## No PII, enforced rather than promised\n *\n * Every payload passes through {@link sanitizeEventParams} before it reaches a\n * transport: an exact-key denylist drops the identity-bearing params someone\n * will eventually add by reflex (`email`, `org_name`, `first_name`, ...), any\n * value that looks like an email address drops its key entirely, URLs are\n * reduced to origin + pathname so query strings can never smuggle a token or\n * an address, and strings are length-capped. The console separately sets a\n * `user_id` — that is an opaque Firebase uid and is the one identifier GA is\n * allowed to hold.\n *\n * Sanitizing here rather than at each call site is the point: a new call site\n * cannot forget.\n *\n * ## Authored events (AGL-1587)\n *\n * One call site cannot use the taxonomy at all: the `trackGaEvent` action step,\n * whose event name and params are typed by a SITE AUTHOR in the interaction\n * builder. A closed union cannot contain a name nobody has written yet, so\n * {@link trackAuthoredEvent} is the escape hatch — and it is deliberately the\n * only one, so that untrusted input still passes {@link sanitizeEventParams}\n * rather than reaching `window.gtag` raw.\n *\n * The test for which door an event uses is WHO NAMED IT, not whether GA4\n * recommends the name. `aglyn_overlay` and `aglyn_experiment` are outside GA4's\n * recommended set and were candidates for the hatch (AGL-1591); they are in the\n * union instead, because a developer wrote their names and their keys, so they\n * can have compile-time checking — and because the hatch guarantees the\n * opposite of what they need. {@link resolveAuthoredEventName} refuses any name\n * we send — the union AND the server-only names beside it — precisely so that\n * \"not one of ours\" means \"authored\"; put our own events through the hatch and\n * that stops being true, authored hits stop being separable from ours in\n * reports, and an authored `aglyn_experiment` step starts voting in the\n * experiment that decides which variant ships.\n */\n\nimport { sendAdvertisingEvent } from './advertising-events'\n\n/**\n * Read the browser's GA `client_id` — the identifier that ties a hit to a GA\n * user and session.\n *\n * Needed because `purchase` is sent SERVER-side, from the Stripe webhook,\n * where the authoritative money is (see `ga4-measurement-protocol.ts`). The\n * Measurement Protocol requires a `client_id` and a server cannot know one,\n * so it is captured here when checkout starts and carried on the Stripe\n * object's metadata. Without it the revenue still lands, but attached to a\n * synthetic user with no acquisition session — which is exactly the campaign\n * attribution the whole exercise is for.\n *\n * Resolves to null rather than hanging when gtag is absent (no consent, an ad\n * blocker, analytics not configured) or slow to answer. The 500ms cap matters:\n * this sits directly in front of a checkout redirect, and analytics must never\n * be able to delay a payment.\n */\nexport function readGaClientId(\n measurementId: string | undefined | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n if (typeof window === 'undefined' || !measurementId) return resolve(null)\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return resolve(null)\n let settled = false\n const finish = (value: string | null) => {\n if (settled) return\n settled = true\n resolve(value)\n }\n // Never let a missing callback strand the checkout.\n setTimeout(() => finish(null), 500)\n try {\n ;(gtag as (...args: unknown[]) => void)(\n 'get',\n measurementId,\n 'client_id',\n (id: unknown) => finish(typeof id === 'string' && id ? id : null),\n )\n } catch {\n finish(null)\n }\n })\n}\n\n/** Which door an account was created through (AGL-1497 enumerates all four). */\nexport type SignUpMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'google_signin'\n\n/** How a returning user authenticated. */\nexport type LoginMethod =\n | 'password'\n | 'google_popup'\n | 'google_redirect'\n | 'sso'\n | 'passkey'\n\n/**\n * A GA4 `items` entry. Only the fields we actually populate — GA accepts more,\n * but an unpopulated field is a column of nulls in every report.\n */\nexport interface AnalyticsItem {\n /** Opaque identifier — a price id, plan key or marketplace listing id. */\n item_id: string\n /** Human-readable product name. NEVER a customer or org name. */\n item_name: string\n /** Distinguishes the revenue lines: `subscription` vs `marketplace`. */\n item_category?: string\n price?: number\n quantity?: number\n}\n\n/**\n * The taxonomy. Adding an event means adding a line here first — which is what\n * makes `docs/ANALYTICS.md` checkable against the code rather than aspirational.\n */\nexport interface AnalyticsEventParams {\n // --- Acquisition (GTM §6: signups, cost/lead by channel) -----------------\n /**\n * GA4 recommended. Real account creation only, never a sign-in.\n *\n * The three campaign params are optional and come from\n * `utmEventParams` (AGL-1731) — present when the signup URL named a\n * campaign, absent entirely otherwise. They are what lets a September ad\n * spend be evaluated: without them a paid click, an organic visit and a\n * partner link arrive indistinguishable and the money cannot be traced to\n * an account. Named `campaign_*` rather than `utm_*` because these are our\n * own registered dimensions and the `utm_` spellings belong to GA's\n * automatic campaign collection.\n */\n sign_up: {\n method: SignUpMethod\n campaign_source?: string\n campaign_medium?: string\n campaign_name?: string\n }\n /** GA4 recommended. Returning user only. */\n login: { method: LoginMethod }\n /**\n * GA4 recommended. Fired on a SUCCESSFUL form submission — never on click,\n * never on a validation failure. `form_name` is the author-given form name,\n * which is site content and not personal data.\n */\n generate_lead: { form_name: string; form_location?: string }\n /**\n * GA4 recommended. A CTA click, with the section that produced it.\n *\n * Fired by `analytics-link-clicks.ts` (AGL-1562) from a delegated listener,\n * not per call site: an authored page has no code to add a handler to.\n */\n select_content: {\n content_type: string\n content_id: string\n /** Which product surface — see `click.surface`. */\n surface?: string\n }\n\n // --- Activation (GTM §6: % publish a site, % connect Stripe) -------------\n /** Custom: no GA4 equivalent. A new organization exists. */\n org_created: { plan?: string }\n /** Custom: no GA4 equivalent. A new site/host exists. */\n host_created: Record<string, never>\n /**\n * Custom: no GA4 equivalent, and the GTM plan's headline activation metric.\n * A site actually went live.\n */\n site_published: { first_publish?: boolean }\n /**\n * Custom: no GA4 equivalent (AGL-3594). How a person chose to start a new\n * site in the guided start: the ready-made starter, or AI.\n */\n site_start_choice: { choice: 'starter' | 'ai' }\n /** Custom: no GA4 equivalent. Stripe Connect onboarding completed. */\n stripe_connected: Record<string, never>\n\n // --- Revenue (GTM §6: paid conversions, ARPA, annual mix) ---------------\n /** GA4 recommended. A plan checkout started. */\n begin_checkout: {\n currency: string\n value: number\n items: AnalyticsItem[]\n /** `monthly` | `annual` — feeds the §6 annual-mix metric. */\n billing_interval?: string\n }\n /**\n * GA4 recommended. A payment actually succeeded. `transaction_id` is the\n * Stripe object id and is what makes the event idempotent in GA: GA4\n * de-duplicates purchases by transaction id, so a webhook retry cannot\n * inflate revenue.\n */\n purchase: {\n transaction_id: string\n currency: string\n value: number\n items: AnalyticsItem[]\n billing_interval?: string\n /**\n * GA4's shipping charged on the transaction, in currency units. Optional\n * because only a tenant STOREFRONT purchase ships anything — a plan or a\n * marketplace purchase has no shipping to report and omits it.\n *\n * There is deliberately no sibling `tax` (AGL-1639, AGL-1641). The\n * asymmetry is the point and is not an inconsistency to tidy away:\n * `shipping` is a COMPONENT of the `value` beside it, so reporting it\n * describes that value; `tax` is not, because `value` is already ex-tax,\n * so reporting it would assert a relationship that does not hold and\n * invite the subtraction that removes tax a second time.\n */\n shipping?: number\n }\n\n // --- Commerce (tenant storefronts, AGL-1591) -----------------------------\n /**\n * GA4 recommended. A product detail page was viewed on a tenant storefront.\n *\n * Only `items`, and only `item_id`/`item_name` within it: those are the two\n * fields the storefront actually has at this point, and an unpopulated\n * `price`/`item_category` would be a column of nulls in the merchant's\n * reports. The item id is the PRODUCT id — the same id `add_to_cart` and\n * `begin_checkout` use — which is what lets GA join the three into one\n * per-product funnel.\n */\n view_item: { items: AnalyticsItem[] }\n /**\n * GA4 recommended. A storefront product was added to the cart.\n *\n * `currency`/`value` are optional because GA4 pairs them — a `value` with no\n * `currency` is dropped by GA — so they travel together or not at all, and\n * {@link buildAddToCartParams} is what keeps that true. They are populated\n * wherever the surface holds a server-priced figure: the product detail\n * block knows the resolved variant's price and the chosen quantity, so the\n * merchant's \"value added to cart\" is a real number rather than the empty\n * column an items-only hit produces.\n */\n add_to_cart: { currency?: string; value?: number; items: AnalyticsItem[] }\n /**\n * GA4 recommended. The shopper looked at their cart — the funnel step\n * between {@link AnalyticsEventParams.add_to_cart} and\n * {@link AnalyticsEventParams.begin_checkout}, and the one GA4's own\n * shopping-behavior report reads to tell \"never opened the cart\" apart from\n * \"opened it and did not check out\". Without it those two collapse into one\n * drop, and the merchant cannot tell a discovery problem from a pricing one.\n *\n * Fired when the cart is actually ON SCREEN carrying lines — a drawer that\n * opened, or an inline cart block that resolved — never on the badge render\n * that every page of a storefront performs. An empty cart is not a view of\n * anything and reports nothing.\n */\n view_cart: { currency: string; value: number; items: AnalyticsItem[] }\n\n // --- Engagement ---------------------------------------------------------\n /**\n * Custom: no GA4 equivalent. An announcement bar or popup was shown,\n * dismissed or clicked on a tenant site (AGL-200/271).\n *\n * In the taxonomy rather than {@link trackAuthoredEvent} even though it is\n * not a GA4 recommended name: the name and every key here are written by US,\n * which is exactly what the closed union is for. See the note on\n * {@link trackAuthoredEvent} for why the two must not be mixed.\n */\n aglyn_overlay: { overlay_action: string; overlay_id?: string }\n /**\n * Custom: no GA4 equivalent. An experiment exposure or conversion\n * (AGL-253). `experiment_action` is `exposure` | `conversion`.\n *\n * Being in the union also makes the name RESERVED against authored events,\n * which matters more here than anywhere else in this file: these are the\n * counts that decide which variant wins, and a hand-authored\n * `aglyn_experiment` step would silently vote in that election.\n */\n aglyn_experiment: {\n experiment_id: string\n variant_id: string\n experiment_action: string\n }\n /**\n * GA4 recommended-ish. Outbound click to docs, GitHub, etc. Fired by\n * `analytics-link-clicks.ts` (AGL-1562) rather than at a call site.\n */\n click: {\n link_domain: string\n link_id?: string\n /**\n * Which product surface produced the click. GA's built-in Hostname\n * dimension already separates the DOMAINS; this separates surfaces that\n * could share one, and keeps the shared click listener from having to\n * know anything about either.\n *\n * `site` — a tenant published site — is the only value ever SENT. `docs`\n * was designed for (AGL-1579) and is not emitted: `apps/docs` cannot\n * import `libs/`, so this listener is not installed there\n * (docs/ANALYTICS.md decision 7 has the Vercel setting that would change\n * that). Registering `surface` as a dimension and reading a one-value\n * breakdown is the trap — the absent `docs` row means \"no listener\", not\n * \"no clicks\".\n */\n surface?: string\n }\n /**\n * Custom: no GA4 equivalent. One Aglyn Assist message sent (AGL-1860).\n * `tier` is the capability tier served (`free` | `entitled`);\n * `grounded` says whether docs retrieval found sections to cite —\n * ungrounded questions at volume are the docs-gap signal the data loop\n * mines. No question text: params carry no user content.\n */\n assistant_message_sent: { tier: string; grounded: boolean }\n /**\n * Custom: no GA4 equivalent. Explicit thumbs on an Assist answer\n * (AGL-1860). `feedback` is `up` | `down`.\n */\n assistant_feedback: { feedback: string }\n /**\n * Custom: no GA4 equivalent. Aglyn Assist offered to open a page for the\n * user (AGL-1988, level 2). `action` is the registry action id — a closed\n * set, so it carries no user content.\n *\n * The pair below is the only read on whether the confirm gate is a real\n * choice or a speed bump people click through. A shown-to-confirmed ratio\n * near 1 means the card is not being read, and the copy has to change\n * BEFORE the ladder goes anywhere near a write.\n */\n assistant_proposal_shown: { action: string }\n /** Custom: no GA4 equivalent. The user confirmed and was navigated. */\n assistant_proposal_confirmed: { action: string }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `done`\n * (AGL-2904), observed from the console's jobs drawer. `kind` is the\n * closed `AiJobKind` set and `credits` the job's spend at the plan's\n * credit rate — no brief, no output: params carry no user content.\n */\n ai_job_completed: { kind: string; credits: number }\n /**\n * Custom: no GA4 equivalent. An AI generation job reached `failed`\n * (AGL-2904). `kind` only; the failure text is a fixed customer-safe\n * sentence and says nothing a rate could use.\n */\n ai_job_failed: { kind: string }\n /**\n * Custom: no GA4 equivalent. A \"Create with AI\" entry was opened on a plan\n * that could buy the AI add-on and has not (AGL-3601), so it showed the\n * add-on instead of a brief. `kind` is the closed set of what the entry\n * makes (`page`, `template`, `layout`, `form`, `component`, `workflow`);\n * `can_manage` is whether the reader could buy it themselves.\n */\n ai_upsell_shown: { kind: string; can_manage: boolean }\n /**\n * Custom: no GA4 equivalent. The reader followed that dialog to Billing's\n * add-ons — the numerator against `ai_upsell_shown`.\n */\n ai_upsell_clicked: { kind: string }\n\n // --- Retention (AGL-1859/AGL-1863: the leave path, measurable) -----------\n /**\n * Custom: no GA4 equivalent. The churn survey was answered — step 1 of the\n * cancellation/deletion funnel, and the DENOMINATOR every step below is a\n * rate against. Fired for both leave paths.\n *\n * `reason` is the closed `ChurnSurveyReason` set, never the free-text\n * detail: the detail is customer-written prose, it belongs in Firestore\n * where the data loop reads it, and shipping it to GA would put user\n * content in analytics params. `surface` separates a subscription cancel\n * from an account delete — counting only one understates churn by exactly\n * the orgs that chose the other.\n */\n churn_survey_submitted: { reason: string; surface: string; plan?: string }\n /**\n * Custom: no GA4 equivalent. The customer took the smaller tier instead of\n * leaving — a SAVE, at reduced ARPA. `from_plan`/`to_plan` are what makes\n * that tradeoff measurable rather than a win recorded without its cost.\n */\n downsell_accepted: { from_plan: string; to_plan: string; surface: string }\n /**\n * Custom: no GA4 equivalent. The time-boxed winback discount was accepted.\n *\n * `percent_off` and `duration_months` are reported because the discount is\n * bounded and the bound is the entire point (AGL-1620/AGL-1863): a retained\n * org and the margin it was retained at are one fact, and a save recorded\n * without its price reads as free.\n */\n winback_discount_accepted: {\n percent_off: number\n duration_months: number\n plan?: string\n surface: string\n }\n /**\n * Custom: no GA4 equivalent. They left anyway — the funnel's terminal step,\n * and the numerator for churn.\n *\n * `funnel_completed` is false when the cancel arrived without a funnelId\n * (support ops, Stripe dashboard). It mirrors the `funnelSkipped` marker\n * the routes write, so the GA funnel and the Firestore record agree instead\n * of quietly disagreeing about how many departures were ever surveyed.\n */\n cancellation_completed: {\n surface: string\n plan?: string\n funnel_completed: boolean\n }\n\n // --- Plan changes taken from the grid (AGL-2235, under AGL-1859 §4) ------\n /**\n * Custom: no GA4 equivalent. A downgrade was confirmed and SCHEDULED from\n * the billing plan grid — the same economic event `downsell_accepted`\n * records, arrived at by the other door.\n *\n * Why this has to exist separately: all four retention events above fire\n * from `retention-funnel.dialog.tsx` and from nowhere else. A customer who\n * moves Pro → Starter through the cancel funnel is counted; a customer who\n * moves Pro → Starter by clicking Downgrade on the plan card was counted by\n * nothing. So \"how many orgs moved down\" was unanswerable, and the number\n * that WAS answerable — `downsell_accepted` — undercounted by exactly the\n * share that took the direct route while reading like a total. A save rate\n * computed against it is wrong in the flattering direction, which is the\n * worst direction for a retention number to be wrong in.\n *\n * `effective_at` is the whole point of the event's name: this is the\n * asymmetric-friction arm of AGL-1859 §2, and a downgrade that has been\n * SCHEDULED is not a downgrade that has HAPPENED. Reported as the server's\n * ISO date so the gap between decision and effect — up to a full cycle, and\n * the window in which \"keep my plan\" can still save the org — is visible in\n * the data instead of being collapsed into the decision day.\n *\n * No amount, price or fee: pricing is locked for Sept 1, money belongs to\n * `purchase`/`refund`, and a tier pair already says what changed.\n */\n plan_downgrade_scheduled: {\n from_plan: string\n to_plan: string\n interval: string\n effective_at?: string\n }\n /**\n * Custom: no GA4 equivalent. An existing subscriber moved UP in place.\n *\n * Not `app_upgrade` — that name is GA4-RESERVED (it means an app binary\n * version bump) and a hit using it is dropped, which is silence rather than\n * pollution and therefore the harder failure to notice.\n *\n * `purchase` covers only the Checkout path, so before this, expansion\n * revenue from customers who ALREADY had a subscription was dark: the\n * in-place switch never opens a Checkout and never mints a new\n * subscription, so nothing in the revenue taxonomy saw it. Upgrades are the\n * half of AGL-1859 §2 that is supposed to be frictionless, and an\n * unmeasured half cannot be shown to be.\n */\n plan_upgraded: {\n from_plan: string\n to_plan: string\n interval: string\n }\n}\n\nexport type AnalyticsEventName = keyof AnalyticsEventParams\n\n/**\n * Where a sanitized event goes. The console registers a Firebase\n * `logEvent` transport; the tenant runtime and the plugin bundles have none\n * and fall through to `window.gtag`, which only exists once consent has been\n * granted.\n */\nexport type AnalyticsTransport = (\n name: AnalyticsEventName,\n params: Record<string, unknown>,\n) => void | Promise<void>\n\nlet configuredTransport: AnalyticsTransport | null = null\n\n/**\n * Register the transport for this surface. The console calls this once, with\n * Firebase's `logEvent`, because the console's GA is Firebase-initialised and\n * its `user_id`/user-property state lives on the Firebase Analytics instance —\n * poking `window.gtag` directly there would emit hits that miss it.\n *\n * The tenant runtime deliberately does NOT call this: the plugin bundles run\n * in their own realm and do not share this module instance with the host app,\n * so a module-scope singleton would be invisible to exactly the call sites\n * that need it (the form and newsletter elements). `window.gtag` is the only\n * thing genuinely shared across that boundary, and it is also the consent\n * gate, which makes the fallback the correct primary path there rather than a\n * degraded one.\n */\nexport function configureAnalyticsTransport(\n transport: AnalyticsTransport | null,\n): void {\n configuredTransport = transport\n}\n\n/** Test seam — drops the registered transport. */\nexport function resetAnalyticsTransport(): void {\n configuredTransport = null\n}\n\n/**\n * Param keys that must never reach GA, matched EXACTLY. Substring matching\n * would be wrong in both directions: it would drop the legitimate\n * `form_name` / `item_name` / `link_domain`, and it would still miss a\n * creatively-named new one. The value scan below is the backstop for those.\n */\nconst DENIED_PARAM_KEYS: ReadonlySet<string> = new Set([\n 'email',\n 'email_address',\n 'user_email',\n 'name',\n 'full_name',\n 'first_name',\n 'last_name',\n 'user_name',\n 'username',\n 'customer_name',\n 'org_name',\n 'organization_name',\n 'company',\n 'company_name',\n 'phone',\n 'phone_number',\n 'address',\n 'street',\n 'postal_code',\n 'zip',\n 'ip',\n 'ip_address',\n])\n\n/** Deliberately loose — this is a \"does it smell like an address\" test. */\nconst EMAIL_SHAPED = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\n/**\n * GA4 truncates param values at 100 chars anyway; do it ourselves, visibly.\n *\n * Exported because an AUTHOR types some of these (the `trackGaEvent` step's\n * parameters), and the field they type into caps its input at the same number\n * — the truncation point and the affordance that describes it have to be one\n * value, or the editor promises a length the delivery quietly shortens.\n */\nexport const ANALYTICS_PARAM_MAX_LENGTH = 100\n\nfunction scrubValue(value: string): string | null {\n let candidate = value\n if (/^https?:\\/\\//i.test(candidate)) {\n try {\n const url = new URL(candidate)\n // Origin + pathname only: a query string is where a session token, a\n // signup email or a Stripe id ends up, and none of them belong in GA.\n candidate = `${url.origin}${url.pathname}`\n } catch {\n return null\n }\n }\n // AFTER the URL reduction, not before. A page URL routinely carries an\n // address in its query (`?email=…` on a prefilled signup link), and testing\n // the raw string would throw the whole URL away for PII that the reduction\n // was about to remove — losing the legitimate page dimension to protect\n // something already protected. Testing the REDUCED value still catches an\n // address embedded in the path itself, which the reduction keeps.\n if (EMAIL_SHAPED.test(candidate)) return null\n return candidate.slice(0, ANALYTICS_PARAM_MAX_LENGTH)\n}\n\n/**\n * Strip anything identity-bearing from an event payload. Exported so\n * `analytics-events.spec.ts` can assert the guarantee directly rather than\n * only through `trackEvent`.\n */\nexport function sanitizeEventParams(\n params: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const safe: Record<string, unknown> = {}\n if (!params) return safe\n for (const [key, value] of Object.entries(params)) {\n if (DENIED_PARAM_KEYS.has(key.toLowerCase())) continue\n if (value === undefined || value === null) continue\n if (typeof value === 'string') {\n const scrubbed = scrubValue(value)\n if (scrubbed === null || scrubbed === '') continue\n safe[key] = scrubbed\n continue\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n safe[key] = value\n continue\n }\n if (Array.isArray(value)) {\n // `items` — sanitize each entry with the same rules.\n safe[key] = value.map((entry) =>\n entry && typeof entry === 'object'\n ? sanitizeEventParams(entry as Record<string, unknown>)\n : entry,\n )\n continue\n }\n if (typeof value === 'object') {\n safe[key] = sanitizeEventParams(value as Record<string, unknown>)\n }\n // Anything else (function, symbol) is dropped.\n }\n return safe\n}\n\n/**\n * Fire a GA4 event.\n *\n * Never throws and never queues. If the surface has no transport and no\n * `window.gtag` — which on a tenant site means the visitor has not granted\n * analytics consent — the event is DROPPED, permanently. See the module\n * comment for why a queue would be the wrong answer.\n */\nexport function trackEvent<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n options?: AnalyticsEventOptions,\n): void {\n deliver(name, sanitizeEventParams(params as Record<string, unknown>), options)\n}\n\n/**\n * What travels beside an event without being one of its parameters\n * (AGL-3694). Never sent to the Google tag.\n */\nexport interface AnalyticsEventOptions {\n /**\n * The id a site's own advertising tags send this conversion under, when the\n * server reports the same conversion through a Conversions API and the\n * vendor must pair the two (`advertising-events.ts`). A purchase derives its\n * own from `transaction_id` and needs none.\n */\n advertisingEventId?: string | null\n}\n\n/**\n * How long a navigation may be held waiting for a hit to reach gtag. Short\n * enough to be invisible next to a Stripe redirect, long enough to cover a\n * Firebase Analytics init that has not settled yet.\n */\nconst NAVIGATION_FLUSH_TIMEOUT_MS = 300\n\n/**\n * Fire a GA4 event and resolve once it has been HANDED TO gtag — for the call\n * sites that navigate away in the same tick (AGL-1580).\n *\n * ## What was actually losing the event\n *\n * Not the transport, which was the obvious suspect and the wrong one. Measured\n * against real gtag.js with every transport interposed: gtag flushes its queue\n * on pagehide through `fetch(..., { keepalive: true })`, which is precisely the\n * mechanism that survives a document teardown. Once a hit reaches gtag, a\n * navigation does not destroy it — and `transport_type: 'beacon'`, the standard\n * answer, therefore fixes nothing here.\n *\n * What is lost is the hit that never REACHES gtag. Firebase's `logEvent` is\n * `async` and awaits the SDK's initialization promise before calling gtag\n * (`@firebase/analytics/dist/index.cjs.js`, `logEvent$1`). While that promise is\n * already settled the continuation is a microtask, microtasks drain before the\n * queued navigation task, and the hit gets out. While it is still PENDING — the\n * first checkout of a fresh session, exactly the case that has never yet been\n * seen in the property — the continuation is scheduled behind the navigation\n * and never runs at all. Measured both ways: pending init loses the event,\n * awaiting it delivers it, nothing else changed.\n *\n * ## Why a timeout rather than a bare await\n *\n * A bare `await` on `logEvent` hands the user's redirect to the analytics\n * stack. When the analytics host is blocked — an ad blocker, a corporate proxy,\n * a consent tool that never loads — Firebase's initialization promise can stay\n * pending indefinitely, and the checkout would hang on a metric. So the wait is\n * RACED against {@link NAVIGATION_FLUSH_TIMEOUT_MS}: a blocked analytics stack\n * costs the redirect 300ms once and then it proceeds, which is the same outcome\n * the caller had before this existed. Never rejects, for the same reason\n * {@link trackEvent} never throws.\n *\n * On a surface with no registered transport — the tenant runtime and the plugin\n * bundles, which go straight to `window.gtag` — delivery is synchronous, so\n * this resolves immediately and costs the storefront checkout nothing at all.\n */\nexport async function trackEventBeforeNavigation<K extends AnalyticsEventName>(\n name: K,\n params: AnalyticsEventParams[K],\n options?: AnalyticsEventOptions,\n): Promise<void> {\n const delivered = deliver(\n name,\n sanitizeEventParams(params as Record<string, unknown>),\n options,\n )\n // Synchronous transport (or none): already handed over, nothing to wait for.\n if (!delivered || typeof delivered.then !== 'function') return\n await Promise.race([\n // A transport that REJECTS must not become an unhandled rejection, and\n // must not hold the navigation either — it has already failed.\n Promise.resolve(delivered).catch((): void => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, NAVIGATION_FLUSH_TIMEOUT_MS),\n ),\n ])\n}\n\n/**\n * Build the ONE `begin_checkout` payload, for every surface that starts a\n * checkout (AGL-1591).\n *\n * ## Why a constructor and not just the type\n *\n * Two surfaces fire this name: the console, when a plan checkout starts, and a\n * tenant storefront, when a cart checks out. Until AGL-1591 the storefront\n * fired it raw and carried `value`/`currency` only, so ONE event name arrived\n * in two shapes — and a `begin_checkout` breakdown showed two populations that\n * could not be compared, with the storefront half missing the `items` the GA4\n * ecommerce funnel is built on. Routing both through {@link trackEvent} makes\n * the compiler settle the KEYS.\n *\n * It does not settle the NUMBER, which is the other way two call sites of one\n * event diverge, and the more dangerous one because nothing about it looks\n * wrong: the console's annual plans are priced per-month-billed-yearly, so its\n * `value` is twelve of them, and that only stayed right because a comment said\n * so. Here `value` DERIVES from the items unless a caller states a different\n * one — a cart states its subtotal, which is authoritative after discounts —\n * so \"what the customer is about to be charged\" has one definition rather than\n * one per surface.\n *\n * Server-safe: pure, no DOM, so the Measurement Protocol sender can compose\n * the matching `purchase` items from the same shapes.\n */\nexport function buildBeginCheckoutParams(input: {\n items: AnalyticsItem[]\n /**\n * The amount actually being charged. Defaults to the sum of the items'\n * `price * quantity`, which is right whenever nothing has adjusted it.\n */\n value?: number\n /** ISO 4217. Defaults to `USD`, the only currency either surface bills in. */\n currency?: string\n /** `monthly` | `annual`. Subscriptions only — a storefront cart has none. */\n billingInterval?: string\n}): AnalyticsEventParams['begin_checkout'] {\n return {\n ...priceItems(input),\n ...(input.billingInterval ? { billing_interval: input.billingInterval } : {}),\n }\n}\n\n/**\n * The `currency`/`value`/`items` triple every GA4 ecommerce step shares.\n *\n * Private, because a caller should reach for the named builder for the event\n * it is about to send: the names differ in what they mean by `value` even\n * though the arithmetic is identical, and the JSDoc on each is where that is\n * written down.\n */\nfunction priceItems(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): { currency: string; value: number; items: AnalyticsItem[] } {\n const items = input.items ?? []\n const summed = items.reduce(\n (total, item) => total + (item.price ?? 0) * (item.quantity ?? 1),\n 0,\n )\n return {\n currency: input.currency ?? 'USD',\n // Money, so two decimals: a float sum of cents-derived prices produces\n // `59.99999999999999`, and GA would report that verbatim.\n value: Math.round((input.value ?? summed) * 100) / 100,\n items,\n }\n}\n\n/**\n * Build `view_cart` — the shopper is looking at the cart's contents.\n *\n * `value` is the cart's subtotal as the SERVER priced it, which is what makes\n * this comparable with the `begin_checkout` the same cart sends moments later:\n * two steps of one funnel that disagreed about the size of the same cart would\n * read as shoppers editing it between screens.\n */\nexport function buildViewCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['view_cart'] {\n return priceItems(input)\n}\n\n/**\n * Build `add_to_cart` — one product going in, not the cart's new total.\n *\n * `value` is what was JUST ADDED (`price * quantity`), which is GA4's\n * definition and the only one that makes the metric additive: summing a\n * running cart total over a session would count the first item once per\n * subsequent add.\n *\n * Callers that cannot price the line — a quick-add with no resolved variant —\n * pass items alone and the pair is omitted rather than reported as zero. A\n * zero here would read as a free product in the merchant's report.\n */\nexport function buildAddToCartParams(input: {\n items: AnalyticsItem[]\n value?: number\n currency?: string\n}): AnalyticsEventParams['add_to_cart'] {\n const priced = priceItems(input)\n if (!(priced.value > 0)) return { items: priced.items }\n return priced\n}\n\n/**\n * Decide `site_published`'s `first_publish` from the host's routing map as it\n * stood BEFORE the route being published was registered (AGL-1588).\n *\n * ## What \"first\" means, and why it is defined once\n *\n * Three call sites report `site_published` — `publishScreenRoute`, the\n * besigner's one-click publish, and the scheduled publish executor, the last\n * of which is server-side and sends over the Measurement Protocol. A\n * breakdown is only worth registering if all three mean the same thing by it,\n * and \"first\" has several plausible readings. This is the one they share:\n *\n * **The host had no live route at all before this one.** Not \"first for the\n * org\" — that needs a cross-host query the server path cannot make, and the\n * scheduled sender's client id is derived from the HOST anyway, so an org is\n * not a thing it can see. Not \"first for this screen\" either, which would be\n * true of every second page a site adds and would make the dimension a\n * synonym for the event.\n *\n * So the metric it separates is the GTM §6 activation one: `first_publish:\n * true` counts sites that came alive, where the event alone counts publishes.\n *\n * ## The one dishonesty, and why it does not matter\n *\n * Unpublishing every route and publishing again reports `true` a second time.\n * Detecting that needs publish history the routing map does not keep. It is\n * harmless for the metric it exists for, because activation is read as the\n * share of USERS who ever sent `first_publish: true`, and a user counted twice\n * is still one user.\n *\n * Callers pass what they already hold — the live-subscribed map in the\n * console, a read snapshot on the server — and never a map read back AFTER\n * the write, which is never empty.\n *\n * ## The placeholder home page is not a publish (AGL-3408)\n *\n * Every new site is created with a home page already routed at `/`, so read\n * literally the map is never empty and no site would ever report a first\n * publish. The host's `defaultHomeScreenId` names that placeholder, and its\n * entry is not counted: the site \"came alive\" when its owner put something on\n * it, not when the platform did. Republishing the placeholder itself after\n * editing it counts, which is the same act: that publish is read against the\n * map with the marker still set, and clears it in the same write (AGL-3478).\n */\nexport function isFirstPublishedRoute(\n routing: Record<string, unknown> | null | undefined,\n defaultHomeScreenId?: string | null,\n): boolean {\n return !Object.keys(routing ?? {}).some(\n (screenId) => screenId !== defaultHomeScreenId,\n )\n}\n\n/**\n * The one delivery path, shared by {@link trackEvent} and\n * {@link trackAuthoredEvent}. Takes an ALREADY-sanitized payload — every\n * caller sanitizes first, which is what keeps \"a new call site cannot forget\"\n * true of the authored path too.\n */\nfunction deliver(\n name: string,\n safe: Record<string, unknown>,\n options?: AnalyticsEventOptions,\n): void | Promise<void> {\n // A site owner's own advertising tags (AGL-3694), BEFORE the Google path\n // and independent of it: a site may run a pixel and no Google tag at all.\n // Structural like the rest — only a tag the consent gate mounted on the\n // merchant's own site carries the marks this looks for, so for a visitor\n // who did not grant advertising this reaches nothing. Synchronous, so it\n // holds no navigation.\n try {\n sendAdvertisingEvent(name, safe, {\n eventId: options?.advertisingEventId ?? null,\n })\n } catch {\n // Never breaks the page, like every other delivery here.\n }\n try {\n if (configuredTransport) {\n // The transport's name parameter is the taxonomy union, which an\n // authored name is by definition outside. Nominal only: the console is\n // the sole surface that registers one and it has no authored events\n // (the interaction runtime is tenant-side), and Firebase `logEvent`\n // takes an arbitrary string regardless.\n // Returned, not discarded (AGL-1580). A transport may be ASYNC —\n // Firebase's `logEvent` awaits the SDK's initialization promise before it\n // reaches gtag at all — and a caller that is about to navigate has to be\n // able to wait for it. See `trackEventBeforeNavigation`.\n return configuredTransport(name as AnalyticsEventName, safe)\n }\n if (typeof window === 'undefined') return\n const gtag = (window as unknown as { gtag?: unknown }).gtag\n if (typeof gtag !== 'function') return\n // Synchronous, so nothing is returned and nothing needs awaiting: by the\n // time this call has returned, gtag.js already holds the hit.\n ;(gtag as (...args: unknown[]) => void)('event', name, safe)\n } catch {\n // Analytics never breaks the page — the same posture as the error beacon\n // and the pageview beacon.\n }\n}\n\n/**\n * The taxonomy's names at RUN time. A `Record<AnalyticsEventName, true>` rather\n * than a hand-kept array so the compiler enforces both directions: adding an\n * event to {@link AnalyticsEventParams} without adding it here is a missing-key\n * error, and a name here that is not in the taxonomy is an excess-property one.\n *\n * It exists for {@link trackAuthoredEvent}, which has to refuse these names —\n * a drifting copy would silently re-open the collision it is here to close.\n */\nconst TAXONOMY_EVENT_NAMES: Record<AnalyticsEventName, true> = {\n sign_up: true,\n login: true,\n generate_lead: true,\n select_content: true,\n org_created: true,\n host_created: true,\n site_published: true,\n site_start_choice: true,\n stripe_connected: true,\n begin_checkout: true,\n purchase: true,\n view_item: true,\n add_to_cart: true,\n view_cart: true,\n aglyn_overlay: true,\n aglyn_experiment: true,\n click: true,\n assistant_message_sent: true,\n assistant_feedback: true,\n assistant_proposal_shown: true,\n assistant_proposal_confirmed: true,\n ai_job_completed: true,\n ai_job_failed: true,\n ai_upsell_shown: true,\n ai_upsell_clicked: true,\n churn_survey_submitted: true,\n downsell_accepted: true,\n winback_discount_accepted: true,\n cancellation_completed: true,\n plan_downgrade_scheduled: true,\n plan_upgraded: true,\n}\n\n/** The taxonomy, enumerable. */\nexport const ANALYTICS_EVENT_NAMES = Object.keys(\n TAXONOMY_EVENT_NAMES,\n) as AnalyticsEventName[]\n\n/**\n * Event names WE send that this module's union cannot hold, because nothing\n * client-side ever fires them: they are emitted only by the Measurement\n * Protocol sender (`ga4-measurement-protocol.ts`), from a Stripe webhook.\n *\n * They still have to be RESERVED against authored names, and the reason is\n * the same one that puts `purchase` in the union — only less obvious, which\n * is why it was missed. `aglyn.com` is itself a tenant site, pointed at the\n * platform measurement id (`site-analytics.tsx`), so an authored\n * `trackGaEvent` step on our own marketing site lands in the SAME property as\n * these server hits. An authored `refund` does not merely add noise: GA4\n * treats `refund` as ecommerce and SUBTRACTS its `value` from reported\n * revenue, so a mistyped step could walk real money out of the report — the\n * `purchase` hazard, running in the direction nobody audits.\n *\n * Kept as a separate list rather than folded into {@link AnalyticsEventParams}\n * on purpose: adding them to the union would give {@link trackEvent} a\n * client-side door to events that must only ever come from the server, where\n * the authoritative money is. A name here is ours, is never sent from a\n * browser, and is never available to an author.\n *\n * This list is the reason \"not in {@link ANALYTICS_EVENT_NAMES}\" is NOT on its\n * own a sound test for \"authored\" — use {@link isReservedAnalyticsEventName}.\n */\nconst SERVER_ONLY_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'refund',\n 'subscription_cancelled',\n])\n\n/**\n * Every event name Aglyn itself sends, from any surface — the union plus the\n * server-only names above. Exported so a caller can ask the question the two\n * separate lists no longer answer alone.\n */\nexport function isReservedAnalyticsEventName(name: string): boolean {\n return (\n TAXONOMY_EVENT_NAMES[name as AnalyticsEventName] === true ||\n SERVER_ONLY_EVENT_NAMES.has(name)\n )\n}\n\n/**\n * GA4's own reserved event names — GA drops a hit that uses one, so sending it\n * is not pollution but silence, which is the worse failure of the two because\n * nothing anywhere says so.\n */\nconst GA4_RESERVED_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_background',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_convert',\n 'app_store_subscription_renew',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n])\n\n/** GA4 reserves these prefixes outright, whatever follows them. */\nconst GA4_RESERVED_PREFIXES = ['firebase_', 'google_', 'ga_'] as const\n\n/** GA4's hard limit on an event name. Over it, GA drops the event. */\nconst MAX_EVENT_NAME_LENGTH = 40\n\n/**\n * The outcome of putting an authored name through GA4's rules, so the\n * interaction builder can say WHY it refused a name and the runtime can drop\n * the event for the same reason.\n */\nexport interface ResolvedAuthoredEventName {\n /** The name to send, or null when the event must not be sent at all. */\n name: string | null\n /**\n * `reserved` — collides with the taxonomy or with GA4's own names.\n * `unusable` — nothing survives normalization (empty, or no leading letter).\n */\n reason?: 'reserved' | 'unusable'\n}\n\n/**\n * Put an authored event name through GA4's naming rules and our own.\n *\n * Normalization is forgiving on purpose: `\"CTA Click!\"` becomes `cta_click`\n * and still reports, where GA would have dropped it. Names already sitting in\n * published sites were never validated, so refusing them outright would delete\n * working metrics from a paying customer's property to fix a formatting nit.\n *\n * Collisions, in contrast, are refused rather than rewritten. On a tenant site\n * the authored events and OUR events (`generate_lead` from the form element,\n * `select_content`/`click` from the link listener) land in the same property,\n * so an authored `purchase` does not merely add noise — it mixes hand-authored\n * hits into a real revenue number. Refusing is also what keeps authored events\n * separable in reports: an event that is not one of {@link ANALYTICS_EVENT_NAMES}\n * is, by construction, authored.\n *\n * Deliberately NOT prefixed (`site_*`) to achieve that separation. A prefix\n * would rename events already flowing into customers' properties and break\n * every report and key-event conversion configured on the old name — a\n * migration cost paid by people who did nothing wrong.\n */\nexport function resolveAuthoredEventName(\n raw: string | undefined | null,\n): ResolvedAuthoredEventName {\n const normalized = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Anything GA4 does not allow in a name becomes an underscore...\n .replace(/[^a-z0-9_]+/g, '_')\n // ...and a name must START with a letter, so drop what precedes one.\n .replace(/^[^a-z]+/, '')\n .replace(/_{2,}/g, '_')\n .slice(0, MAX_EVENT_NAME_LENGTH)\n // Truncation can leave a trailing underscore; so can the substitution.\n .replace(/_+$/, '')\n if (!normalized) return { name: null, reason: 'unusable' }\n if (\n isReservedAnalyticsEventName(normalized) ||\n GA4_RESERVED_EVENT_NAMES.has(normalized) ||\n GA4_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))\n ) {\n return { name: null, reason: 'reserved' }\n }\n return { name: normalized }\n}\n\n/** One warning per distinct name per page load — an `everyTime` automation\n * would otherwise fill the console with the same line. */\nconst warnedAuthoredNames = new Set<string>()\n\n/**\n * Fire an event whose name and params were written by a SITE AUTHOR, not by a\n * developer — today only the `trackGaEvent` action step (AGL-1587).\n *\n * Same consent gate, same sanitizer, same drop-never-queue posture as\n * {@link trackEvent}; the only difference is that the name is checked at run\n * time instead of by the compiler, because there is no compiler between the\n * interaction builder and here.\n *\n * A refused event is dropped and warned about in the console rather than\n * surfaced in the page. Nothing here can reach the author — the code is\n * running for a VISITOR of their site, and turning the author's configuration\n * mistake into something a visitor sees would be a worse bug than the missing\n * metric. The author-facing half lives in `validateInteraction`, which refuses\n * to save a name this function would refuse to send, so a silent drop should\n * only ever happen to a step authored before AGL-1587.\n */\nexport function trackAuthoredEvent(\n name: string | undefined | null,\n params?: Record<string, unknown> | null,\n): void {\n const resolved = resolveAuthoredEventName(name)\n if (!resolved.name) {\n const key = String(name ?? '')\n if (!warnedAuthoredNames.has(key)) {\n warnedAuthoredNames.add(key)\n try {\n console.warn(\n `[aglyn] analytics: the event \"${key}\" was not sent — ` +\n (resolved.reason === 'reserved'\n ? 'that name is reserved. Rename the step in the interaction builder.'\n : 'an event name must start with a letter.'),\n )\n } catch {\n // A console that throws is still not worth breaking the page for.\n }\n }\n return\n }\n deliver(resolved.name, sanitizeEventParams(params ?? undefined))\n}\n\n/** Test seam — forgets which authored names have already been warned about. */\nexport function resetAuthoredEventWarnings(): void {\n warnedAuthoredNames.clear()\n}\n"],"names":["sendAdvertisingEvent","readGaClientId","measurementId","Promise","resolve","window","gtag","settled","finish","value","setTimeout","id","configuredTransport","configureAnalyticsTransport","transport","resetAnalyticsTransport","DENIED_PARAM_KEYS","Set","EMAIL_SHAPED","ANALYTICS_PARAM_MAX_LENGTH","scrubValue","candidate","test","url","URL","origin","pathname","slice","sanitizeEventParams","params","safe","key","Object","entries","has","toLowerCase","undefined","scrubbed","Array","isArray","map","entry","trackEvent","name","options","deliver","NAVIGATION_FLUSH_TIMEOUT_MS","trackEventBeforeNavigation","delivered","then","race","catch","buildBeginCheckoutParams","input","priceItems","billingInterval","billing_interval","items","summed","reduce","total","item","price","quantity","currency","Math","round","buildViewCartParams","buildAddToCartParams","priced","isFirstPublishedRoute","routing","defaultHomeScreenId","keys","some","screenId","eventId","advertisingEventId","TAXONOMY_EVENT_NAMES","sign_up","login","generate_lead","select_content","org_created","host_created","site_published","site_start_choice","stripe_connected","begin_checkout","purchase","view_item","add_to_cart","view_cart","aglyn_overlay","aglyn_experiment","click","assistant_message_sent","assistant_feedback","assistant_proposal_shown","assistant_proposal_confirmed","ai_job_completed","ai_job_failed","ai_upsell_shown","ai_upsell_clicked","churn_survey_submitted","downsell_accepted","winback_discount_accepted","cancellation_completed","plan_downgrade_scheduled","plan_upgraded","ANALYTICS_EVENT_NAMES","SERVER_ONLY_EVENT_NAMES","isReservedAnalyticsEventName","GA4_RESERVED_EVENT_NAMES","GA4_RESERVED_PREFIXES","MAX_EVENT_NAME_LENGTH","resolveAuthoredEventName","raw","normalized","String","trim","replace","reason","prefix","startsWith","warnedAuthoredNames","trackAuthoredEvent","resolved","add","console","warn","resetAuthoredEventWarnings","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAE3D;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASC,eACdC,aAAwC;IAExC,OAAO,IAAIC,QAAQ,CAACC;QAClB,IAAI,OAAOC,WAAW,eAAe,CAACH,eAAe,OAAOE,QAAQ;QACpE,MAAME,OAAO,AAACD,OAAyCC,IAAI;QAC3D,IAAI,OAAOA,SAA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IAAW;AAC5B;AAEA;wDACwD,GACxD,MAAMO,sBAAsB,IAAI5G;AAEhC;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAAS6G,mBACdnF,IAA+B,EAC/Bd,MAAuC;IAEvC,MAAMkG,WAAWX,yBAAyBzE;IAC1C,IAAI,CAACoF,SAASpF,IAAI,EAAE;QAClB,MAAMZ,MAAMwF,OAAO5E,eAAAA,OAAQ;QAC3B,IAAI,CAACkF,oBAAoB3F,GAAG,CAACH,MAAM;YACjC8F,oBAAoBG,GAAG,CAACjG;YACxB,IAAI;gBACFkG,QAAQC,IAAI,CACV,CAAC,8BAA8B,EAAEnG,IAAI,iBAAiB,CAAC,GACpDgG,CAAAA,SAASL,MAAM,KAAK,aACjB,uEACA,yCAAwC;YAElD,EAAE,eAAM;YACN,kEAAkE;YACpE;QACF;QACA;IACF;IACA7E,QAAQkF,SAASpF,IAAI,EAAEf,oBAAoBC,iBAAAA,SAAUO;AACvD;AAEA,6EAA6E,GAC7E,OAAO,SAAS+F;IACdN,oBAAoBO,KAAK;AAC3B"}
|
|
@@ -158,6 +158,14 @@ export interface ConsentCopy {
|
|
|
158
158
|
advertisingLabel?: string;
|
|
159
159
|
advertisingDetail?: string;
|
|
160
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* The published-site wording, naming the vendors that load on the analytics
|
|
163
|
+
* grant besides Google Analytics (AGL-3698) — a live chat a merchant set to
|
|
164
|
+
* load with the page. The visitor is asked about what will actually load, so
|
|
165
|
+
* a site that adds one says so in the banner, the panel's analytics line and
|
|
166
|
+
* nowhere else. No vendors, no change: the default wording, untouched.
|
|
167
|
+
*/
|
|
168
|
+
export declare function consentCopyForAnalyticsVendors(vendors: readonly string[] | null | undefined): ConsentCopy | undefined;
|
|
161
169
|
export interface ConsentBannerUiProps {
|
|
162
170
|
hostId: string;
|
|
163
171
|
/** The visitor's recorded state; null means undecided. */
|
|
@@ -174,6 +182,12 @@ export interface ConsentBannerUiProps {
|
|
|
174
182
|
advertising?: boolean;
|
|
175
183
|
/** Per-surface wording; see {@link ConsentCopy}. */
|
|
176
184
|
copy?: ConsentCopy;
|
|
185
|
+
/**
|
|
186
|
+
* Vendors this page loads on the analytics grant besides Google Analytics
|
|
187
|
+
* (AGL-3698); the banner and the panel name them. See
|
|
188
|
+
* {@link consentCopyForAnalyticsVendors}. `copy` still wins.
|
|
189
|
+
*/
|
|
190
|
+
analyticsVendors?: readonly string[];
|
|
177
191
|
/**
|
|
178
192
|
* Links to the policies behind the choice, rendered under the copy on both
|
|
179
193
|
* the banner and the panel.
|
|
@@ -317,6 +317,27 @@ const DEFAULT_COPY = {
|
|
|
317
317
|
advertisingLabel: 'Advertising',
|
|
318
318
|
advertisingDetail: 'Personalized ads and measuring how they perform.'
|
|
319
319
|
};
|
|
320
|
+
/**
|
|
321
|
+
* The published-site wording, naming the vendors that load on the analytics
|
|
322
|
+
* grant besides Google Analytics (AGL-3698) — a live chat a merchant set to
|
|
323
|
+
* load with the page. The visitor is asked about what will actually load, so
|
|
324
|
+
* a site that adds one says so in the banner, the panel's analytics line and
|
|
325
|
+
* nowhere else. No vendors, no change: the default wording, untouched.
|
|
326
|
+
*/ export function consentCopyForAnalyticsVendors(vendors) {
|
|
327
|
+
const names = (vendors != null ? vendors : []).filter(Boolean);
|
|
328
|
+
if (!names.length) return undefined;
|
|
329
|
+
const list = [
|
|
330
|
+
'Google Analytics',
|
|
331
|
+
...names
|
|
332
|
+
];
|
|
333
|
+
const joined = list.length === 2 ? `${list[0]} and ${list[1]}` : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
|
|
334
|
+
const named = (sentence)=>sentence.replace('analytics (Google Analytics)', `analytics (${joined})`);
|
|
335
|
+
return {
|
|
336
|
+
bannerAnalyticsOnly: named(DEFAULT_COPY.bannerAnalyticsOnly),
|
|
337
|
+
bannerWithAdvertising: named(DEFAULT_COPY.bannerWithAdvertising),
|
|
338
|
+
analyticsDetail: `${DEFAULT_COPY.analyticsDetail} Also loads ${names.join(', ')} with the page.`
|
|
339
|
+
};
|
|
340
|
+
}
|
|
320
341
|
/** The card both overlays are drawn on — fixed, centred, above everything. */ const overlayCardSx = {
|
|
321
342
|
position: 'fixed',
|
|
322
343
|
left: '50%',
|
|
@@ -360,8 +381,8 @@ let preferencesDialogLoad;
|
|
|
360
381
|
preloadConsentPreferences().catch(()=>undefined);
|
|
361
382
|
}
|
|
362
383
|
export function ConsentBannerUi(props) {
|
|
363
|
-
const { hostId, stored, posture, country, advertising, copy, policyLinks, showPill = true, onDecision } = props;
|
|
364
|
-
const words = _extends({}, DEFAULT_COPY, copy);
|
|
384
|
+
const { hostId, stored, posture, country, advertising, copy, analyticsVendors, policyLinks, showPill = true, onDecision } = props;
|
|
385
|
+
const words = _extends({}, DEFAULT_COPY, consentCopyForAnalyticsVendors(analyticsVendors), copy);
|
|
365
386
|
const [preferencesOpen, setPreferencesOpen] = useState(false);
|
|
366
387
|
const [analyticsChecked, setAnalyticsChecked] = useState((stored == null ? void 0 : stored.analytics) === true);
|
|
367
388
|
// Starts UNTICKED unless the visitor previously said yes to this exact
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/consent-banner-ui.tsx"],"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// Deliberately NO 'use client' directive: inside @aglyn/aglyn the directive\n// splits the bundler into a duplicate module graph, and the second\n// canvas/emitter singleton renders the tenant site blank (AGL-52 — the\n// lint rule that enforces this). It is also unnecessary: every importer\n// (the tenant catch-all, the console preview simulator) is itself a\n// 'use client' module, so this file is already inside the client graph. A\n// future import from a SERVER component fails loudly at build time\n// (\"useState only works in a client component\"), not silently.\n\nimport { Box, Button, Paper, Stack, Typography } from '@mui/material'\nimport {\n type ReactElement,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport type { ConsentPreferencesDialog } from './consent-preferences-dialog'\nimport {\n readStoredVisitorConsent,\n refusalStatusFor,\n type StoredVisitorConsent,\n storeVisitorConsent,\n VISITOR_CONSENT_OPEN_EVENT,\n type VisitorConsentPosture,\n type VisitorConsentStatus,\n} from './visitor-consent'\n\n/**\n * The visitor consent surfaces (AGL-1498) — UI over the enforcement layer,\n * never the enforcement itself: the GA script stays unloaded until a\n * granting state is recorded, whether or not this component ever rendered.\n *\n * Three surfaces in one component, driven by the resolved state:\n *\n * - **The prior-consent banner** (opt-in posture, undecided visitor):\n * symmetric Allow / Decline plus Preferences — the peer benchmark's\n * credible shape; Decline is never buried.\n * - **The \"Your Privacy Choices\" pill**: a small, persistent, fixed control on\n * EVERY page whenever the consent machinery is active. In the implied\n * posture no banner and no notice ever renders (the Squarespace shape),\n * which makes this pill the ONE discoverable opt-out surface — that is\n * why it is platform-mounted rather than a per-template footer link a\n * theme could drop. Sites can additionally link any element to\n * `#aglyn-consent`; both open the same panel.\n * - **The preferences panel**: change the state in EITHER direction at any\n * time — accept after declining, opt out after being defaulted in.\n *\n * ## EVERY surface renders this component\n *\n * Published customer sites, the console — signed in and signed out — and the\n * console preview's region simulator. There were two implementations of these\n * three surfaces and they had already drifted into two different designs: a\n * plain card with bare checkboxes on one side, a MUI dialog with switches and\n * descriptions on the other. The dialog is the design that survived, and the\n * differences that were real turned out to be STRINGS — \"this site\" against\n * \"this console\", carts against signing in — which is what {@link ConsentCopy}\n * is for. A string is not a reason for a second component.\n *\n * MUI is available on both: the tenant runtime renders it through\n * `HostThemeProvider`, under the same `AppRouterCacheProvider` emotion cache\n * the console uses, and `membership-page.tsx` already draws MUI components a\n * folder away from the call site here. The unlayered-cache hazard is the\n * BESIGNER canvas, which no published page and no consent surface goes\n * through.\n *\n * Palette and type come from whichever theme is in scope, which on a customer\n * site is the site's own — the control belongs to the page it is asked on. The\n * two things that must NOT follow a theme are the §7015 mark, which is\n * transcribed artwork, and {@link CONSENT_OVERLAY_Z_INDEX}, which has to\n * outrank a popup backdrop no theme knows about.\n */\n\n/**\n * The title of the persistent opt-out control — **fixed by regulation, not a\n * copy choice**.\n *\n * Once a business \"shares\" personal information for cross-context behavioral\n * advertising, CCPA §1798.135(b) requires a clear and conspicuous opt-out\n * link, and CCPA regs §7015 permit a SINGLE combined link only when it is\n * titled with these exact words. Aglyn crossed that line when advertising\n * technology went onto aglyn.com, so the pill's previous label — \"Privacy\n * choices\" — stopped being compliant the moment the tag shipped.\n *\n * Capitalisation is part of the specified title. Do not sentence-case it to\n * match the rest of the overlay copy, do not shorten it to fit a narrow\n * viewport, and do not translate it away on a US-facing site: it is pinned by\n * `consent-opt-out-title.spec.tsx`, which renders the real control and reads\n * the text back.\n */\nexport const CONSENT_OPT_OUT_TITLE = 'Your Privacy Choices'\n\n/**\n * The official CCPA **opt-out icon** — the other half of §7015, and the half\n * AGL-2011's title commit deliberately left undone.\n *\n * §7015(a) requires the icon *\"in approximately the same size as any other\n * icons\"* and §7015(c) requires it to *\"be approximately the same size as\n * other icons on the business's webpage\"* and to appear immediately to the\n * left of the \"Your Privacy Choices\" text. §7015(f) is the reason the shapes\n * below are transcribed rather than drawn: the regulation points at\n * *published artwork*, not at a description of a toggle, so an approximation\n * that reads as \"close enough\" is not the mark the regulation names.\n *\n * ## Provenance — read this before touching a single coordinate\n *\n * Downloaded from the California Attorney General's own icon page,\n * `oag.ca.gov/privacy/ccpa/icons-download`, by two independent routes that\n * agree byte for byte: the `ccpa-icons.zip` bundle that page offers, and the\n * standalone `privacyoptions.svg` that page displays inline. Both are\n * sha256 `86f2eb97cc1f3909c12e4512de9e267215d94ac5aaee9393d0f007f18c34e8ba`.\n * The unmodified file is committed at\n * `apps/tenant/public/_static/images/legal/ccpa-opt-out-icon.svg` — diff it\n * against the AG's copy to re-verify at any time.\n *\n * ## Why the paths are inlined here and not `<img src>`-ed\n *\n * The AGL-1810 duplicate-with-pointer pattern, for the same reason the admin\n * bar uses it: this component renders on **every published customer site**\n * and inside the console's preview simulator, and neither an extra fetch nor\n * a broken-image glyph is acceptable where a regulator's mark is supposed to\n * be. A self-hosted deployment gets the mark with no asset pipeline at all.\n * If the AG ever republishes the artwork, change the committed file AND\n * these four constants.\n *\n * ## What was changed in transcription, and what was not\n *\n * The coordinates and the two colours are verbatim. The only change is that\n * the AG file carries its fills in a `<style>` block of `.st0`–`.st3`\n * classes, and an inline `<style>` inside a shared overlay is **document-\n * global CSS**: shipping it would define `.st0`/`.st1` on every customer's\n * page and restyle any element of theirs that happens to use those names. So\n * each class is expanded to the presentation attributes it stood for —\n * `.st0`/`.st1` are `fill-rule:evenodd; clip-rule:evenodd` plus the fill,\n * `.st2`/`.st3` are the fill alone. Paint order is the file's own; the white\n * left-hand fill is painted before the blue shell that rings it.\n */\n/** `.st0` — the white field behind the check, inside the shell's cut-out. */\nconst OPT_OUT_ICON_LEFT_FIELD_PATH =\n 'M7.4,12.8h6.8l3.1-11.6H7.4C4.2,1.2,1.6,3.8,1.6,7S4.2,12.8,7.4,12.8z'\n/** `.st1` — the blue toggle shell, evenodd so the left half reads through. */\nconst OPT_OUT_ICON_SHELL_PATH =\n 'M22.6,0H7.4c-3.9,0-7,3.1-7,7s3.1,7,7,7h15.2c3.9,0,7-3.1,7-7S26.4,0,22.6,0z M1.6,7c0-3.2,2.6-5.8,5.8-5.8' +\n ' h9.9l-3.1,11.6H7.4C4.2,12.8,1.6,10.2,1.6,7z'\n/** `.st2` (`id=\"x\"`) — the white cross on the blue half. */\nconst OPT_OUT_ICON_CROSS_PATH =\n 'M24.6,4c0.2,0.2,0.2,0.6,0,0.8l0,0L22.5,7l2.2,2.2c0.2,0.2,0.2,0.6,0,0.8c-0.2,0.2-0.6,0.2-0.8,0' +\n ' l0,0l-2.2-2.2L19.5,10c-0.2,0.2-0.6,0.2-0.8,0c-0.2-0.2-0.2-0.6,0-0.8l0,0L20.8,7l-2.2-2.2c-0.2-0.2-0.2-0.6,0-0.8' +\n ' c0.2-0.2,0.6-0.2,0.8,0l0,0l2.2,2.2L23.8,4C24,3.8,24.4,3.8,24.6,4z'\n/** `.st3` (`id=\"y\"`) — the blue check on the white half. */\nconst OPT_OUT_ICON_CHECK_PATH =\n 'M12.7,4.1c0.2,0.2,0.3,0.6,0.1,0.8l0,0L8.6,9.8C8.5,9.9,8.4,10,8.3,10c-0.2,0.1-0.5,0.1-0.7-0.1l0,0' +\n ' L5.4,7.7c-0.2-0.2-0.2-0.6,0-0.8c0.2-0.2,0.6-0.2,0.8,0l0,0L8,8.6l3.8-4.5C12,3.9,12.4,3.9,12.7,4.1z'\n\n/** The mark's own colours. Not themeable — see {@link CcpaOptOutIcon}. */\nconst OPT_OUT_ICON_BLUE = '#0066FF'\nconst OPT_OUT_ICON_WHITE = '#FFFFFF'\n\n/**\n * The opt-out icon, sized for the pill.\n *\n * `aria-hidden`, because it sits beside the words it stands for: the pill\n * already announces \"Your Privacy Choices\" as its accessible name, and a\n * labelled icon next to identical visible text makes a screen reader say the\n * title twice. Same treatment as the admin bar's mark.\n *\n * 26 × 12 against the file's own `0 0 30 14` viewBox, so the default\n * `preserveAspectRatio` scales the drawing to the 12px height — one line of\n * the pill's 12px/1.4 text — and centres it. That is what §7015's \"the same\n * size as other icons\" asks for here: the pill has no other icons, so the\n * text is the scale to match.\n *\n * **The colours are the regulation's, not the theme's.** The pill's own\n * background is a fixed near-white that no tenant palette reaches, which is\n * exactly the surface this artwork was published against — so it needs no\n * light/dark variant and must not be given one.\n */\n/**\n * Exported so a surface that renders its own opt-out control gets the\n * REGULATOR'S artwork rather than an approximation of it. §7015(f) points at\n * published artwork, and the console's unauthenticated pages need the same\n * mark this overlay draws — a second, hand-drawn toggle would be a different\n * mark wearing the same name.\n */\nexport function CcpaOptOutIcon(): ReactElement {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 30 14\"\n width={26}\n height={12}\n aria-hidden=\"true\"\n focusable=\"false\"\n style={{ flexShrink: 0, display: 'block' }}\n data-aglyn-consent-optout-icon=\"\"\n >\n <path\n d={OPT_OUT_ICON_LEFT_FIELD_PATH}\n fill={OPT_OUT_ICON_WHITE}\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n />\n <path\n d={OPT_OUT_ICON_SHELL_PATH}\n fill={OPT_OUT_ICON_BLUE}\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n />\n <path d={OPT_OUT_ICON_CROSS_PATH} fill={OPT_OUT_ICON_WHITE} />\n <path d={OPT_OUT_ICON_CHECK_PATH} fill={OPT_OUT_ICON_BLUE} />\n </svg>\n )\n}\n/**\n * The stacking context the consent surfaces must win, and why it is a number\n * rather than a theme token.\n *\n * `theme.zIndex.modal` is 1300, and on a published site the consent card has\n * to sit above the popup backdrop at 2147483200 — the consent question\n * outranks a promotional popup, and the popup's own GA mirrors are waiting on\n * the answer. Exported so the console preview's own panel can be raised\n * against the real value instead of a copy of it.\n */\nexport const CONSENT_OVERLAY_Z_INDEX = 2147483400\n\n/** The persistent control sits just below the card it can be replaced by. */\nexport const CONSENT_PILL_Z_INDEX = 2147483390\n\n/** The card both the banner and the preferences panel are drawn on. */\nconst CARD_WIDTH = 'min(680px, calc(100vw - 24px))'\n\n/** Breathing room kept between the pill and the last row it must not cover. */\nconst PILL_CLEARANCE = 8\n\n/**\n * Selector for \"the end of the page\" — the footer landmark, however the\n * template spells it. A besigner-authored footer renders as `<footer>`;\n * `[role=contentinfo]` catches a hand-rolled one. `body` is the fallback so\n * a site with no footer at all still reserves the room.\n */\nconst FOOTER_SELECTOR = 'footer, [role=\"contentinfo\"]'\n\n/**\n * Bottom padding the end of the page needs so the fixed pill cannot land on\n * top of it (AGL-2205).\n *\n * Derived from the pill's MEASURED box rather than from `PILL_STYLE`: the\n * label wraps to two lines in a narrow viewport and in a translated locale,\n * and a clearance computed from the constants would be exactly one line\n * short in precisely the case where the copyright row is already tightest.\n *\n * Pure, and exported, because the geometry is the whole fix: a spec can pin\n * \"51px of room for a 30.8px pill sitting 12px off the bottom\" without a\n * layout engine, which is the half a jsdom render cannot check.\n */\nexport function consentPillClearance(\n viewportHeight: number,\n pillTop: number,\n): number {\n if (!Number.isFinite(viewportHeight) || !Number.isFinite(pillTop)) return 0\n return Math.max(0, Math.ceil(viewportHeight - pillTop) + PILL_CLEARANCE)\n}\n\n/**\n * Reserves that room at the foot of the document while the pill is up.\n *\n * The pill is `position: fixed`, so scrolling to the end of the page parks\n * it directly on the footer's bottom row — which on every Aglyn marketing\n * page is the \"© 2026 Aglyn LLC\" line, the one piece of footer content that\n * is there for legal reasons. Measured on aglyn.com/pricing before this: the\n * pill occupied 12–126 × 680–711 and the copyright row 24–258 × 669–689, a\n * 102 × 9 px overlap at 1440 and the same again at 375.\n *\n * AGL-2205 proposed docking the pill above the footer instead. Measuring the\n * real footer ruled that out: it is 490px tall at 1440 and 1375px at 375,\n * against an 812px viewport — docking above it puts the pill in the middle\n * of the screen on desktop and clean off it on mobile, and the pill is the\n * ONLY opt-out surface a visitor in the implied posture ever sees, so it may\n * not scroll away. Reserving the pill's own footprint keeps it where people\n * expect it, costs nothing to anyone who never scrolls that far, and the\n * room appears INSIDE the footer's own background band rather than as a\n * strip of body colour underneath it.\n *\n * Only the DEFICIT is added: a template that already leaves enough room is\n * left exactly as it was, which is why the site's own padding is re-read\n * (with ours removed) on every pass instead of being captured once — it is\n * responsive, and a value cached at mount is wrong after the first resize.\n */\nfunction useConsentPillClearance(\n pillRef: { current: HTMLElement | null },\n active: boolean,\n): void {\n useEffect(() => {\n const pill = pillRef.current\n if (!active || !pill) return\n const doc = pill.ownerDocument\n const view = doc?.defaultView\n // `ownerDocument`, never the global `document`: the console preview\n // mounts this same component, and reserving room in the CONSOLE's\n // chrome because the preview happens to share its document would be a\n // fix applied to the wrong page.\n if (!doc || !view) return\n const target: HTMLElement | null =\n doc.querySelector<HTMLElement>(FOOTER_SELECTOR) ?? doc.body\n if (!target) return\n\n const previous = target.style.getPropertyValue('padding-bottom')\n const previousPriority = target.style.getPropertyPriority('padding-bottom')\n const restore = () => {\n if (previous) {\n target.style.setProperty('padding-bottom', previous, previousPriority)\n } else {\n target.style.removeProperty('padding-bottom')\n }\n }\n\n const apply = () => {\n // Ours off first: `getComputedStyle` would otherwise read back the\n // value this effect wrote on the previous pass and ratchet it upward.\n // Safe to do mid-measurement — the pill is fixed, so the reflow this\n // causes cannot move it.\n restore()\n const natural =\n Number.parseFloat(view.getComputedStyle(target).paddingBottom) || 0\n const needed = consentPillClearance(\n view.innerHeight,\n pill.getBoundingClientRect().top,\n )\n if (needed > natural) {\n target.style.setProperty('padding-bottom', `${needed}px`)\n }\n }\n\n apply()\n view.addEventListener('resize', apply)\n // The pill's own box changes without the viewport changing — a font\n // finishing loading re-wraps the label.\n const observer =\n typeof view.ResizeObserver === 'function'\n ? new view.ResizeObserver(apply)\n : undefined\n observer?.observe(pill)\n return () => {\n view.removeEventListener('resize', apply)\n observer?.disconnect()\n restore()\n }\n }, [pillRef, active])\n}\n\n/**\n * The words each surface uses, so one component serves them all.\n *\n * A console says \"this console\" and a published site says \"this site\"; the\n * strictly-necessary sentence names shopping carts on a customer site and\n * signing in on the console. Those are STRINGS, and a string is not a reason\n * for a second component — which is what the two implementations this replaces\n * had become. Every field defaults to the published-site wording, so a caller\n * that has nothing to say differently passes nothing.\n */\nexport interface ConsentCopy {\n /** Opens the preferences panel. */\n panelIntro?: string\n /** Names what runs regardless, and why it is not being asked about. */\n strictlyNecessary?: string\n /** The ask, on a site that runs analytics only. */\n bannerAnalyticsOnly?: string\n /** The ask, on a site that also asks about advertising. */\n bannerWithAdvertising?: string\n /** The analytics control's label and the line under it. */\n analyticsLabel?: string\n analyticsDetail?: string\n /** The advertising control's, where the surface asks about it. */\n advertisingLabel?: string\n advertisingDetail?: string\n}\n\nconst DEFAULT_COPY: Required<ConsentCopy> = {\n panelIntro: 'Choose what this site may use.',\n strictlyNecessary:\n 'Strictly necessary features — like shopping carts, sign-in, and ' +\n 'remembering this choice — are always on because the site cannot work ' +\n 'without them.',\n bannerAnalyticsOnly:\n 'This site would like to use analytics (Google Analytics) to understand ' +\n 'how it is used. Analytics only runs if you allow it — everything else ' +\n 'works either way.',\n bannerWithAdvertising:\n 'This site would like to use analytics (Google Analytics) to understand ' +\n 'how it is used, and advertising cookies to personalize ads and measure ' +\n 'how they perform. Neither runs unless you allow it — everything else ' +\n 'works either way. Use Preferences to choose them separately.',\n analyticsLabel: 'Analytics',\n analyticsDetail: 'Google Analytics — how the site is used.',\n advertisingLabel: 'Advertising',\n advertisingDetail: 'Personalized ads and measuring how they perform.',\n}\n\nexport interface ConsentBannerUiProps {\n hostId: string\n /** The visitor's recorded state; null means undecided. */\n stored: StoredVisitorConsent | null\n /** The resolved posture; only consulted while undecided. */\n posture: VisitorConsentPosture | null\n /** Region at decision time, recorded onto explicit choices. */\n country?: string | null\n /**\n * Whether this surface asks about advertising storage. Resolved by the\n * caller — from the host document on a published site, from the platform's\n * own consent declaration on the console.\n */\n advertising?: boolean\n /** Per-surface wording; see {@link ConsentCopy}. */\n copy?: ConsentCopy\n /**\n * Links to the policies behind the choice, rendered under the copy on both\n * the banner and the panel.\n *\n * A node rather than a pair of URLs: the console links its own published\n * Privacy and Cookie policies through its route constants, and a published\n * site links whatever its owner has. A choice offered with no way to read\n * what is being chosen is not an informed one, but neither surface's links\n * are this component's to know.\n */\n policyLinks?: ReactNode\n /**\n * Whether the persistent \"Your Privacy Choices\" control may render here.\n *\n * `true` — the default, and every published site — draws the pill whenever\n * no other surface is up. It is the ONLY opt-out surface a visitor in the\n * implied posture ever sees, so it is platform-mounted rather than left to\n * a template that could drop it.\n *\n * `false` for a page that already carries the control somewhere better. The\n * console's signed-in pages put it in the account menu, where a person looks\n * for their own settings; floating a second copy over the page would be the\n * same control drawn twice.\n */\n showPill?: boolean\n /**\n * The caller owns what a decision DOES.\n *\n * Unset — a published site — persists through `storeVisitorConsent`, which\n * is where the withdrawal behaviour lives: it re-derives both grants from\n * the status, silences any resident tag, sweeps the analytics and\n * advertising cookies and dispatches the change event.\n *\n * Set, and the caller writes instead. The console writes through\n * `storePlatformConsent` so the record also mirrors across its hostnames;\n * the console's region simulator writes nothing at all, which is what keeps\n * previewing as-if-from-the-EU from recording a real consent record.\n */\n onDecision?: (status: VisitorConsentStatus, advertising?: boolean) => void\n}\n\n/** The card both overlays are drawn on — fixed, centred, above everything. */\nconst overlayCardSx = {\n position: 'fixed',\n left: '50%',\n bottom: 16,\n transform: 'translateX(-50%)',\n zIndex: CONSENT_OVERLAY_Z_INDEX,\n width: CARD_WIDTH,\n p: 2,\n borderRadius: 3,\n textAlign: 'left',\n} as const\n\n/**\n * The preferences panel, once its module has arrived.\n *\n * The panel is the one consent surface a visit has to ask for, and its MUI\n * dialog, modal, focus trap, transitions and switches weigh more than the\n * banner and the pill together. So it is a module of its own, fetched when\n * the panel is asked for — or when the pointer or focus reaches a control\n * that opens it — rather than with the banner every first-time visitor sees.\n *\n * Module scope, not a `React.lazy`: once loaded, every later render draws it\n * synchronously, with no Suspense boundary and no fallback frame.\n */\nlet loadedPreferencesDialog: typeof ConsentPreferencesDialog | undefined\nlet preferencesDialogLoad: Promise<void> | undefined\n\n/**\n * Fetches the preferences panel's module, once. A failed fetch is forgotten\n * so the next attempt can retry it.\n *\n * Exported for callers that know the panel is about to be needed, and for\n * specs that open it and read it back in the same tick.\n */\nexport function preloadConsentPreferences(): Promise<void> {\n preferencesDialogLoad ??= import('./consent-preferences-dialog')\n .then((module) => {\n loadedPreferencesDialog = module.ConsentPreferencesDialog\n })\n .catch((error: unknown) => {\n preferencesDialogLoad = undefined\n throw error\n })\n return preferencesDialogLoad\n}\n\n/** Starts the panel's fetch on a sign of intent; a failure surfaces on open. */\nfunction warmPreferences(): void {\n preloadConsentPreferences().catch((): void => undefined)\n}\n\nexport function ConsentBannerUi(props: ConsentBannerUiProps): ReactElement | null {\n const {\n hostId,\n stored,\n posture,\n country,\n advertising,\n copy,\n policyLinks,\n showPill = true,\n onDecision,\n } = props\n const words = { ...DEFAULT_COPY, ...copy }\n const [preferencesOpen, setPreferencesOpen] = useState(false)\n const [analyticsChecked, setAnalyticsChecked] = useState(\n stored?.analytics === true,\n )\n // Starts UNTICKED unless the visitor previously said yes to this exact\n // category (AGL-1649). A pre-ticked advertising box is consent by\n // inattention, which is the thing a banner is supposed to replace.\n const [adsChecked, setAdsChecked] = useState(stored?.advertising === true)\n\n // The change-your-mind paths: the window event, and a `#aglyn-consent`\n // link click anywhere in the page (capture, so canvas link handling that\n // stops propagation cannot swallow it).\n useEffect(() => {\n const open = () => {\n const current = readStoredVisitorConsent(hostId)\n setAnalyticsChecked(current?.analytics === true)\n setAdsChecked(current?.advertising === true)\n setPreferencesOpen(true)\n }\n const onClick = (event: MouseEvent) => {\n const target = event.target as Element | null\n const anchor = target?.closest?.('a[href]')\n if (\n anchor &&\n (anchor.getAttribute('href') ?? '').endsWith('#aglyn-consent')\n ) {\n event.preventDefault()\n open()\n }\n }\n window.addEventListener(VISITOR_CONSENT_OPEN_EVENT, open)\n document.addEventListener('click', onClick, true)\n return () => {\n window.removeEventListener(VISITOR_CONSENT_OPEN_EVENT, open)\n document.removeEventListener('click', onClick, true)\n }\n }, [hostId])\n\n // `ads` is only ever passed through; `storeVisitorConsent` re-derives it\n // against the status, so a refusal cannot carry a grant however this is\n // called.\n const decide = (status: VisitorConsentStatus, ads = false) => {\n const granted = advertising === true && ads\n if (onDecision) {\n onDecision(status, granted)\n } else {\n storeVisitorConsent(hostId, { status, country, advertising: granted })\n }\n setPreferencesOpen(false)\n }\n\n // Same gate either way, distinct record — see `refusalStatusFor`.\n const refusalStatus = refusalStatusFor(stored, posture)\n\n // The panel is drawn only once its module is here. Until then the surface\n // that asked for it stays up, so a slow fetch never blanks the banner or\n // the pill; a fetch that fails puts the request down, and the next click\n // retries it.\n const [, setPreferencesArrived] = useState(false)\n useEffect(() => {\n if (!preferencesOpen || loadedPreferencesDialog) return undefined\n let active = true\n preloadConsentPreferences().then(\n () => {\n if (active) setPreferencesArrived(true)\n },\n () => {\n if (active) setPreferencesOpen(false)\n },\n )\n return () => {\n active = false\n }\n }, [preferencesOpen])\n const PreferencesDialog = preferencesOpen ? loadedPreferencesDialog : undefined\n\n const askBanner = !stored && posture === 'opt-in' && !PreferencesDialog\n\n // Before the early returns below, so the hook order never depends on which\n // of the three surfaces is up. The banner and the panel are centred cards\n // that reserve nothing — only the pill parks itself on the footer.\n const pillRef = useRef<HTMLButtonElement | null>(null)\n useConsentPillClearance(pillRef, showPill && !PreferencesDialog && !askBanner)\n\n if (PreferencesDialog) {\n return (\n <PreferencesDialog\n title={CONSENT_OPT_OUT_TITLE}\n zIndex={CONSENT_OVERLAY_Z_INDEX}\n words={words}\n advertising={advertising}\n policyLinks={policyLinks}\n analyticsChecked={analyticsChecked}\n onAnalyticsChange={setAnalyticsChecked}\n adsChecked={adsChecked}\n onAdsChange={setAdsChecked}\n onClose={() => setPreferencesOpen(false)}\n onDeclineAll={() => decide(refusalStatus)}\n onSave={() =>\n decide(\n analyticsChecked ? 'accepted' : refusalStatus,\n // Advertising cannot outlive analytics: unticking analytics and\n // leaving advertising ticked is a refusal of both, which\n // `consentModeSignals` also clamps independently.\n analyticsChecked && adsChecked,\n )\n }\n />\n )\n }\n\n if (askBanner) {\n return (\n <Paper\n elevation={8}\n role=\"region\"\n aria-label=\"Privacy choices\"\n data-aglyn-consent-banner=\"\"\n sx={overlayCardSx}\n >\n <Stack\n direction={{ xs: 'column', sm: 'row' }}\n spacing={1.5}\n sx={{ alignItems: { xs: 'stretch', sm: 'center' } }}\n >\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\">\n {advertising\n ? words.bannerWithAdvertising\n : words.bannerAnalyticsOnly}\n </Typography>\n {policyLinks ? <Box sx={{ mt: 0.5 }}>{policyLinks}</Box> : null}\n </Box>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ flexShrink: 0, flexWrap: 'wrap' }}\n >\n <Button\n size=\"small\"\n onPointerEnter={warmPreferences}\n onFocus={warmPreferences}\n onClick={() => {\n setAnalyticsChecked(stored != null && stored.analytics)\n setAdsChecked(stored != null && stored.advertising === true)\n setPreferencesOpen(true)\n }}\n >\n {'Preferences'}\n </Button>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={() => decide('declined')}\n >\n {'Decline'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => decide('accepted', advertising === true)}\n >\n {advertising ? 'Allow all' : 'Allow'}\n </Button>\n </Stack>\n </Stack>\n </Paper>\n )\n }\n\n if (!showPill) return null\n\n // The pill renders whenever no other surface is up — INCLUDING the\n // implied posture, where it is the only opt-out surface there is.\n return (\n <Button\n ref={pillRef}\n type=\"button\"\n // No ripple, and it is not cosmetic: `consent-opt-out-title.spec.tsx`\n // reads the control's LAST child to prove the §7015 title is the text\n // immediately right of the §7015 mark, and a ripple span would be the\n // last child instead.\n disableRipple\n data-aglyn-consent-pill=\"\"\n aria-label={CONSENT_OPT_OUT_TITLE}\n variant=\"outlined\"\n size=\"small\"\n onPointerEnter={warmPreferences}\n onFocus={warmPreferences}\n onClick={() => {\n const current = onDecision ? stored : readStoredVisitorConsent(hostId)\n setAnalyticsChecked(current?.analytics === true)\n setAdsChecked(current?.advertising === true)\n setPreferencesOpen(true)\n }}\n sx={{\n position: 'fixed',\n left: 12,\n bottom: 12,\n zIndex: CONSENT_PILL_Z_INDEX,\n gap: 0.75,\n flexWrap: 'wrap',\n maxWidth: 'calc(100vw - 24px)',\n borderRadius: 999,\n textTransform: 'none',\n color: 'text.secondary',\n borderColor: 'divider',\n backgroundColor: 'background.paper',\n }}\n >\n {/*\n Icon FIRST: §7015 places the opt-out icon immediately to the left of\n the title, and this is the control the regulation is about. The\n prior-consent banner deliberately gets neither the title nor the icon\n — it is a consent solicitation that disappears once answered, so\n dressing it in the regulation's mark would advertise it as the\n persistent opt-out link it cannot be.\n */}\n <CcpaOptOutIcon />\n {CONSENT_OPT_OUT_TITLE}\n </Button>\n )\n}\n\nexport default ConsentBannerUi\n"],"names":["Box","Button","Paper","Stack","Typography","useEffect","useRef","useState","readStoredVisitorConsent","refusalStatusFor","storeVisitorConsent","VISITOR_CONSENT_OPEN_EVENT","CONSENT_OPT_OUT_TITLE","OPT_OUT_ICON_LEFT_FIELD_PATH","OPT_OUT_ICON_SHELL_PATH","OPT_OUT_ICON_CROSS_PATH","OPT_OUT_ICON_CHECK_PATH","OPT_OUT_ICON_BLUE","OPT_OUT_ICON_WHITE","CcpaOptOutIcon","svg","xmlns","viewBox","width","height","aria-hidden","focusable","style","flexShrink","display","data-aglyn-consent-optout-icon","path","d","fill","fillRule","clipRule","CONSENT_OVERLAY_Z_INDEX","CONSENT_PILL_Z_INDEX","CARD_WIDTH","PILL_CLEARANCE","FOOTER_SELECTOR","consentPillClearance","viewportHeight","pillTop","Number","isFinite","Math","max","ceil","useConsentPillClearance","pillRef","active","doc","pill","current","ownerDocument","view","defaultView","target","querySelector","body","previous","getPropertyValue","previousPriority","getPropertyPriority","restore","setProperty","removeProperty","apply","natural","parseFloat","getComputedStyle","paddingBottom","needed","innerHeight","getBoundingClientRect","top","addEventListener","observer","ResizeObserver","undefined","observe","removeEventListener","disconnect","DEFAULT_COPY","panelIntro","strictlyNecessary","bannerAnalyticsOnly","bannerWithAdvertising","analyticsLabel","analyticsDetail","advertisingLabel","advertisingDetail","overlayCardSx","position","left","bottom","transform","zIndex","p","borderRadius","textAlign","loadedPreferencesDialog","preferencesDialogLoad","preloadConsentPreferences","then","module","ConsentPreferencesDialog","catch","error","warmPreferences","ConsentBannerUi","props","hostId","stored","posture","country","advertising","copy","policyLinks","showPill","onDecision","words","preferencesOpen","setPreferencesOpen","analyticsChecked","setAnalyticsChecked","analytics","adsChecked","setAdsChecked","open","onClick","event","anchor","closest","getAttribute","endsWith","preventDefault","window","document","decide","status","ads","granted","refusalStatus","setPreferencesArrived","PreferencesDialog","askBanner","title","onAnalyticsChange","onAdsChange","onClose","onDeclineAll","onSave","elevation","role","aria-label","data-aglyn-consent-banner","sx","direction","xs","sm","spacing","alignItems","flex","minWidth","variant","mt","flexWrap","size","onPointerEnter","onFocus","ref","type","disableRipple","data-aglyn-consent-pill","gap","maxWidth","textTransform","color","borderColor","backgroundColor"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,4EAA4E;AAC5E,mEAAmE;AACnE,uEAAuE;AACvE,wEAAwE;AACxE,oEAAoE;AACpE,0EAA0E;AAC1E,mEAAmE;AACnE,+DAA+D;AAE/D,SAASA,GAAG,EAAEC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACrE,SAGEC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAO;AAEd,SACEC,wBAAwB,EACxBC,gBAAgB,EAEhBC,mBAAmB,EACnBC,0BAA0B,QAGrB,uBAAmB;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,MAAMC,wBAAwB,uBAAsB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GACD,2EAA2E,GAC3E,MAAMC,+BACJ;AACF,4EAA4E,GAC5E,MAAMC,0BACJ,4GACA;AACF,0DAA0D,GAC1D,MAAMC,0BACJ,kGACA,oHACA;AACF,0DAA0D,GAC1D,MAAMC,0BACJ,qGACA;AAEF,wEAAwE,GACxE,MAAMC,oBAAoB;AAC1B,MAAMC,qBAAqB;AAE3B;;;;;;;;;;;;;;;;;;CAkBC,GACD;;;;;;CAMC,GACD,OAAO,SAASC;IACd,qBACE,MAACC;QACCC,OAAM;QACNC,SAAQ;QACRC,OAAO;QACPC,QAAQ;QACRC,eAAY;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K;oCACvDO,mBAAmB;gCACrB;0CAEC;;0CAEH,KAAC3H;gCACCwK,MAAK;gCACLH,SAAQ;gCACRnC,SAAS,IAAMS,OAAO;0CAErB;;0CAEH,KAAC3I;gCACCwK,MAAK;gCACLH,SAAQ;gCACRnC,SAAS,IAAMS,OAAO,YAAYvB,gBAAgB;0CAEjDA,cAAc,cAAc;;;;;;;IAMzC;IAEA,IAAI,CAACG,UAAU,OAAO;IAEtB,mEAAmE;IACnE,kEAAkE;IAClE,qBACE,MAACvH;QACC2K,KAAK1H;QACL2H,MAAK;QACL,sEAAsE;QACtE,sEAAsE;QACtE,sEAAsE;QACtE,sBAAsB;QACtBC,aAAa;QACbC,2BAAwB;QACxBnB,cAAYhJ;QACZ0J,SAAQ;QACRG,MAAK;QACLC,gBAAgB5D;QAChB6D,SAAS7D;QACTqB,SAAS;YACP,MAAM7E,UAAUmE,aAAaP,SAAS1G,yBAAyByG;YAC/Da,oBAAoBxE,CAAAA,2BAAAA,QAASyE,SAAS,MAAK;YAC3CE,cAAc3E,CAAAA,2BAAAA,QAAS+D,WAAW,MAAK;YACvCO,mBAAmB;QACrB;QACAkC,IAAI;YACFhE,UAAU;YACVC,MAAM;YACNC,QAAQ;YACRE,QAAQ7D;YACR2I,KAAK;YACLR,UAAU;YACVS,UAAU;YACV7E,cAAc;YACd8E,eAAe;YACfC,OAAO;YACPC,aAAa;YACbC,iBAAiB;QACnB;;0BAUA,KAAClK;YACAP;;;AAGP;AAEA,eAAemG,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/consent-banner-ui.tsx"],"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// Deliberately NO 'use client' directive: inside @aglyn/aglyn the directive\n// splits the bundler into a duplicate module graph, and the second\n// canvas/emitter singleton renders the tenant site blank (AGL-52 — the\n// lint rule that enforces this). It is also unnecessary: every importer\n// (the tenant catch-all, the console preview simulator) is itself a\n// 'use client' module, so this file is already inside the client graph. A\n// future import from a SERVER component fails loudly at build time\n// (\"useState only works in a client component\"), not silently.\n\nimport { Box, Button, Paper, Stack, Typography } from '@mui/material'\nimport {\n type ReactElement,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport type { ConsentPreferencesDialog } from './consent-preferences-dialog'\nimport {\n readStoredVisitorConsent,\n refusalStatusFor,\n type StoredVisitorConsent,\n storeVisitorConsent,\n VISITOR_CONSENT_OPEN_EVENT,\n type VisitorConsentPosture,\n type VisitorConsentStatus,\n} from './visitor-consent'\n\n/**\n * The visitor consent surfaces (AGL-1498) — UI over the enforcement layer,\n * never the enforcement itself: the GA script stays unloaded until a\n * granting state is recorded, whether or not this component ever rendered.\n *\n * Three surfaces in one component, driven by the resolved state:\n *\n * - **The prior-consent banner** (opt-in posture, undecided visitor):\n * symmetric Allow / Decline plus Preferences — the peer benchmark's\n * credible shape; Decline is never buried.\n * - **The \"Your Privacy Choices\" pill**: a small, persistent, fixed control on\n * EVERY page whenever the consent machinery is active. In the implied\n * posture no banner and no notice ever renders (the Squarespace shape),\n * which makes this pill the ONE discoverable opt-out surface — that is\n * why it is platform-mounted rather than a per-template footer link a\n * theme could drop. Sites can additionally link any element to\n * `#aglyn-consent`; both open the same panel.\n * - **The preferences panel**: change the state in EITHER direction at any\n * time — accept after declining, opt out after being defaulted in.\n *\n * ## EVERY surface renders this component\n *\n * Published customer sites, the console — signed in and signed out — and the\n * console preview's region simulator. There were two implementations of these\n * three surfaces and they had already drifted into two different designs: a\n * plain card with bare checkboxes on one side, a MUI dialog with switches and\n * descriptions on the other. The dialog is the design that survived, and the\n * differences that were real turned out to be STRINGS — \"this site\" against\n * \"this console\", carts against signing in — which is what {@link ConsentCopy}\n * is for. A string is not a reason for a second component.\n *\n * MUI is available on both: the tenant runtime renders it through\n * `HostThemeProvider`, under the same `AppRouterCacheProvider` emotion cache\n * the console uses, and `membership-page.tsx` already draws MUI components a\n * folder away from the call site here. The unlayered-cache hazard is the\n * BESIGNER canvas, which no published page and no consent surface goes\n * through.\n *\n * Palette and type come from whichever theme is in scope, which on a customer\n * site is the site's own — the control belongs to the page it is asked on. The\n * two things that must NOT follow a theme are the §7015 mark, which is\n * transcribed artwork, and {@link CONSENT_OVERLAY_Z_INDEX}, which has to\n * outrank a popup backdrop no theme knows about.\n */\n\n/**\n * The title of the persistent opt-out control — **fixed by regulation, not a\n * copy choice**.\n *\n * Once a business \"shares\" personal information for cross-context behavioral\n * advertising, CCPA §1798.135(b) requires a clear and conspicuous opt-out\n * link, and CCPA regs §7015 permit a SINGLE combined link only when it is\n * titled with these exact words. Aglyn crossed that line when advertising\n * technology went onto aglyn.com, so the pill's previous label — \"Privacy\n * choices\" — stopped being compliant the moment the tag shipped.\n *\n * Capitalisation is part of the specified title. Do not sentence-case it to\n * match the rest of the overlay copy, do not shorten it to fit a narrow\n * viewport, and do not translate it away on a US-facing site: it is pinned by\n * `consent-opt-out-title.spec.tsx`, which renders the real control and reads\n * the text back.\n */\nexport const CONSENT_OPT_OUT_TITLE = 'Your Privacy Choices'\n\n/**\n * The official CCPA **opt-out icon** — the other half of §7015, and the half\n * AGL-2011's title commit deliberately left undone.\n *\n * §7015(a) requires the icon *\"in approximately the same size as any other\n * icons\"* and §7015(c) requires it to *\"be approximately the same size as\n * other icons on the business's webpage\"* and to appear immediately to the\n * left of the \"Your Privacy Choices\" text. §7015(f) is the reason the shapes\n * below are transcribed rather than drawn: the regulation points at\n * *published artwork*, not at a description of a toggle, so an approximation\n * that reads as \"close enough\" is not the mark the regulation names.\n *\n * ## Provenance — read this before touching a single coordinate\n *\n * Downloaded from the California Attorney General's own icon page,\n * `oag.ca.gov/privacy/ccpa/icons-download`, by two independent routes that\n * agree byte for byte: the `ccpa-icons.zip` bundle that page offers, and the\n * standalone `privacyoptions.svg` that page displays inline. Both are\n * sha256 `86f2eb97cc1f3909c12e4512de9e267215d94ac5aaee9393d0f007f18c34e8ba`.\n * The unmodified file is committed at\n * `apps/tenant/public/_static/images/legal/ccpa-opt-out-icon.svg` — diff it\n * against the AG's copy to re-verify at any time.\n *\n * ## Why the paths are inlined here and not `<img src>`-ed\n *\n * The AGL-1810 duplicate-with-pointer pattern, for the same reason the admin\n * bar uses it: this component renders on **every published customer site**\n * and inside the console's preview simulator, and neither an extra fetch nor\n * a broken-image glyph is acceptable where a regulator's mark is supposed to\n * be. A self-hosted deployment gets the mark with no asset pipeline at all.\n * If the AG ever republishes the artwork, change the committed file AND\n * these four constants.\n *\n * ## What was changed in transcription, and what was not\n *\n * The coordinates and the two colours are verbatim. The only change is that\n * the AG file carries its fills in a `<style>` block of `.st0`–`.st3`\n * classes, and an inline `<style>` inside a shared overlay is **document-\n * global CSS**: shipping it would define `.st0`/`.st1` on every customer's\n * page and restyle any element of theirs that happens to use those names. So\n * each class is expanded to the presentation attributes it stood for —\n * `.st0`/`.st1` are `fill-rule:evenodd; clip-rule:evenodd` plus the fill,\n * `.st2`/`.st3` are the fill alone. Paint order is the file's own; the white\n * left-hand fill is painted before the blue shell that rings it.\n */\n/** `.st0` — the white field behind the check, inside the shell's cut-out. */\nconst OPT_OUT_ICON_LEFT_FIELD_PATH =\n 'M7.4,12.8h6.8l3.1-11.6H7.4C4.2,1.2,1.6,3.8,1.6,7S4.2,12.8,7.4,12.8z'\n/** `.st1` — the blue toggle shell, evenodd so the left half reads through. */\nconst OPT_OUT_ICON_SHELL_PATH =\n 'M22.6,0H7.4c-3.9,0-7,3.1-7,7s3.1,7,7,7h15.2c3.9,0,7-3.1,7-7S26.4,0,22.6,0z M1.6,7c0-3.2,2.6-5.8,5.8-5.8' +\n ' h9.9l-3.1,11.6H7.4C4.2,12.8,1.6,10.2,1.6,7z'\n/** `.st2` (`id=\"x\"`) — the white cross on the blue half. */\nconst OPT_OUT_ICON_CROSS_PATH =\n 'M24.6,4c0.2,0.2,0.2,0.6,0,0.8l0,0L22.5,7l2.2,2.2c0.2,0.2,0.2,0.6,0,0.8c-0.2,0.2-0.6,0.2-0.8,0' +\n ' l0,0l-2.2-2.2L19.5,10c-0.2,0.2-0.6,0.2-0.8,0c-0.2-0.2-0.2-0.6,0-0.8l0,0L20.8,7l-2.2-2.2c-0.2-0.2-0.2-0.6,0-0.8' +\n ' c0.2-0.2,0.6-0.2,0.8,0l0,0l2.2,2.2L23.8,4C24,3.8,24.4,3.8,24.6,4z'\n/** `.st3` (`id=\"y\"`) — the blue check on the white half. */\nconst OPT_OUT_ICON_CHECK_PATH =\n 'M12.7,4.1c0.2,0.2,0.3,0.6,0.1,0.8l0,0L8.6,9.8C8.5,9.9,8.4,10,8.3,10c-0.2,0.1-0.5,0.1-0.7-0.1l0,0' +\n ' L5.4,7.7c-0.2-0.2-0.2-0.6,0-0.8c0.2-0.2,0.6-0.2,0.8,0l0,0L8,8.6l3.8-4.5C12,3.9,12.4,3.9,12.7,4.1z'\n\n/** The mark's own colours. Not themeable — see {@link CcpaOptOutIcon}. */\nconst OPT_OUT_ICON_BLUE = '#0066FF'\nconst OPT_OUT_ICON_WHITE = '#FFFFFF'\n\n/**\n * The opt-out icon, sized for the pill.\n *\n * `aria-hidden`, because it sits beside the words it stands for: the pill\n * already announces \"Your Privacy Choices\" as its accessible name, and a\n * labelled icon next to identical visible text makes a screen reader say the\n * title twice. Same treatment as the admin bar's mark.\n *\n * 26 × 12 against the file's own `0 0 30 14` viewBox, so the default\n * `preserveAspectRatio` scales the drawing to the 12px height — one line of\n * the pill's 12px/1.4 text — and centres it. That is what §7015's \"the same\n * size as other icons\" asks for here: the pill has no other icons, so the\n * text is the scale to match.\n *\n * **The colours are the regulation's, not the theme's.** The pill's own\n * background is a fixed near-white that no tenant palette reaches, which is\n * exactly the surface this artwork was published against — so it needs no\n * light/dark variant and must not be given one.\n */\n/**\n * Exported so a surface that renders its own opt-out control gets the\n * REGULATOR'S artwork rather than an approximation of it. §7015(f) points at\n * published artwork, and the console's unauthenticated pages need the same\n * mark this overlay draws — a second, hand-drawn toggle would be a different\n * mark wearing the same name.\n */\nexport function CcpaOptOutIcon(): ReactElement {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 30 14\"\n width={26}\n height={12}\n aria-hidden=\"true\"\n focusable=\"false\"\n style={{ flexShrink: 0, display: 'block' }}\n data-aglyn-consent-optout-icon=\"\"\n >\n <path\n d={OPT_OUT_ICON_LEFT_FIELD_PATH}\n fill={OPT_OUT_ICON_WHITE}\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n />\n <path\n d={OPT_OUT_ICON_SHELL_PATH}\n fill={OPT_OUT_ICON_BLUE}\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n />\n <path d={OPT_OUT_ICON_CROSS_PATH} fill={OPT_OUT_ICON_WHITE} />\n <path d={OPT_OUT_ICON_CHECK_PATH} fill={OPT_OUT_ICON_BLUE} />\n </svg>\n )\n}\n/**\n * The stacking context the consent surfaces must win, and why it is a number\n * rather than a theme token.\n *\n * `theme.zIndex.modal` is 1300, and on a published site the consent card has\n * to sit above the popup backdrop at 2147483200 — the consent question\n * outranks a promotional popup, and the popup's own GA mirrors are waiting on\n * the answer. Exported so the console preview's own panel can be raised\n * against the real value instead of a copy of it.\n */\nexport const CONSENT_OVERLAY_Z_INDEX = 2147483400\n\n/** The persistent control sits just below the card it can be replaced by. */\nexport const CONSENT_PILL_Z_INDEX = 2147483390\n\n/** The card both the banner and the preferences panel are drawn on. */\nconst CARD_WIDTH = 'min(680px, calc(100vw - 24px))'\n\n/** Breathing room kept between the pill and the last row it must not cover. */\nconst PILL_CLEARANCE = 8\n\n/**\n * Selector for \"the end of the page\" — the footer landmark, however the\n * template spells it. A besigner-authored footer renders as `<footer>`;\n * `[role=contentinfo]` catches a hand-rolled one. `body` is the fallback so\n * a site with no footer at all still reserves the room.\n */\nconst FOOTER_SELECTOR = 'footer, [role=\"contentinfo\"]'\n\n/**\n * Bottom padding the end of the page needs so the fixed pill cannot land on\n * top of it (AGL-2205).\n *\n * Derived from the pill's MEASURED box rather than from `PILL_STYLE`: the\n * label wraps to two lines in a narrow viewport and in a translated locale,\n * and a clearance computed from the constants would be exactly one line\n * short in precisely the case where the copyright row is already tightest.\n *\n * Pure, and exported, because the geometry is the whole fix: a spec can pin\n * \"51px of room for a 30.8px pill sitting 12px off the bottom\" without a\n * layout engine, which is the half a jsdom render cannot check.\n */\nexport function consentPillClearance(\n viewportHeight: number,\n pillTop: number,\n): number {\n if (!Number.isFinite(viewportHeight) || !Number.isFinite(pillTop)) return 0\n return Math.max(0, Math.ceil(viewportHeight - pillTop) + PILL_CLEARANCE)\n}\n\n/**\n * Reserves that room at the foot of the document while the pill is up.\n *\n * The pill is `position: fixed`, so scrolling to the end of the page parks\n * it directly on the footer's bottom row — which on every Aglyn marketing\n * page is the \"© 2026 Aglyn LLC\" line, the one piece of footer content that\n * is there for legal reasons. Measured on aglyn.com/pricing before this: the\n * pill occupied 12–126 × 680–711 and the copyright row 24–258 × 669–689, a\n * 102 × 9 px overlap at 1440 and the same again at 375.\n *\n * AGL-2205 proposed docking the pill above the footer instead. Measuring the\n * real footer ruled that out: it is 490px tall at 1440 and 1375px at 375,\n * against an 812px viewport — docking above it puts the pill in the middle\n * of the screen on desktop and clean off it on mobile, and the pill is the\n * ONLY opt-out surface a visitor in the implied posture ever sees, so it may\n * not scroll away. Reserving the pill's own footprint keeps it where people\n * expect it, costs nothing to anyone who never scrolls that far, and the\n * room appears INSIDE the footer's own background band rather than as a\n * strip of body colour underneath it.\n *\n * Only the DEFICIT is added: a template that already leaves enough room is\n * left exactly as it was, which is why the site's own padding is re-read\n * (with ours removed) on every pass instead of being captured once — it is\n * responsive, and a value cached at mount is wrong after the first resize.\n */\nfunction useConsentPillClearance(\n pillRef: { current: HTMLElement | null },\n active: boolean,\n): void {\n useEffect(() => {\n const pill = pillRef.current\n if (!active || !pill) return\n const doc = pill.ownerDocument\n const view = doc?.defaultView\n // `ownerDocument`, never the global `document`: the console preview\n // mounts this same component, and reserving room in the CONSOLE's\n // chrome because the preview happens to share its document would be a\n // fix applied to the wrong page.\n if (!doc || !view) return\n const target: HTMLElement | null =\n doc.querySelector<HTMLElement>(FOOTER_SELECTOR) ?? doc.body\n if (!target) return\n\n const previous = target.style.getPropertyValue('padding-bottom')\n const previousPriority = target.style.getPropertyPriority('padding-bottom')\n const restore = () => {\n if (previous) {\n target.style.setProperty('padding-bottom', previous, previousPriority)\n } else {\n target.style.removeProperty('padding-bottom')\n }\n }\n\n const apply = () => {\n // Ours off first: `getComputedStyle` would otherwise read back the\n // value this effect wrote on the previous pass and ratchet it upward.\n // Safe to do mid-measurement — the pill is fixed, so the reflow this\n // causes cannot move it.\n restore()\n const natural =\n Number.parseFloat(view.getComputedStyle(target).paddingBottom) || 0\n const needed = consentPillClearance(\n view.innerHeight,\n pill.getBoundingClientRect().top,\n )\n if (needed > natural) {\n target.style.setProperty('padding-bottom', `${needed}px`)\n }\n }\n\n apply()\n view.addEventListener('resize', apply)\n // The pill's own box changes without the viewport changing — a font\n // finishing loading re-wraps the label.\n const observer =\n typeof view.ResizeObserver === 'function'\n ? new view.ResizeObserver(apply)\n : undefined\n observer?.observe(pill)\n return () => {\n view.removeEventListener('resize', apply)\n observer?.disconnect()\n restore()\n }\n }, [pillRef, active])\n}\n\n/**\n * The words each surface uses, so one component serves them all.\n *\n * A console says \"this console\" and a published site says \"this site\"; the\n * strictly-necessary sentence names shopping carts on a customer site and\n * signing in on the console. Those are STRINGS, and a string is not a reason\n * for a second component — which is what the two implementations this replaces\n * had become. Every field defaults to the published-site wording, so a caller\n * that has nothing to say differently passes nothing.\n */\nexport interface ConsentCopy {\n /** Opens the preferences panel. */\n panelIntro?: string\n /** Names what runs regardless, and why it is not being asked about. */\n strictlyNecessary?: string\n /** The ask, on a site that runs analytics only. */\n bannerAnalyticsOnly?: string\n /** The ask, on a site that also asks about advertising. */\n bannerWithAdvertising?: string\n /** The analytics control's label and the line under it. */\n analyticsLabel?: string\n analyticsDetail?: string\n /** The advertising control's, where the surface asks about it. */\n advertisingLabel?: string\n advertisingDetail?: string\n}\n\nconst DEFAULT_COPY: Required<ConsentCopy> = {\n panelIntro: 'Choose what this site may use.',\n strictlyNecessary:\n 'Strictly necessary features — like shopping carts, sign-in, and ' +\n 'remembering this choice — are always on because the site cannot work ' +\n 'without them.',\n bannerAnalyticsOnly:\n 'This site would like to use analytics (Google Analytics) to understand ' +\n 'how it is used. Analytics only runs if you allow it — everything else ' +\n 'works either way.',\n bannerWithAdvertising:\n 'This site would like to use analytics (Google Analytics) to understand ' +\n 'how it is used, and advertising cookies to personalize ads and measure ' +\n 'how they perform. Neither runs unless you allow it — everything else ' +\n 'works either way. Use Preferences to choose them separately.',\n analyticsLabel: 'Analytics',\n analyticsDetail: 'Google Analytics — how the site is used.',\n advertisingLabel: 'Advertising',\n advertisingDetail: 'Personalized ads and measuring how they perform.',\n}\n\n/**\n * The published-site wording, naming the vendors that load on the analytics\n * grant besides Google Analytics (AGL-3698) — a live chat a merchant set to\n * load with the page. The visitor is asked about what will actually load, so\n * a site that adds one says so in the banner, the panel's analytics line and\n * nowhere else. No vendors, no change: the default wording, untouched.\n */\nexport function consentCopyForAnalyticsVendors(\n vendors: readonly string[] | null | undefined,\n): ConsentCopy | undefined {\n const names = (vendors ?? []).filter(Boolean)\n if (!names.length) return undefined\n const list = ['Google Analytics', ...names]\n const joined =\n list.length === 2\n ? `${list[0]} and ${list[1]}`\n : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`\n const named = (sentence: string) =>\n sentence.replace('analytics (Google Analytics)', `analytics (${joined})`)\n return {\n bannerAnalyticsOnly: named(DEFAULT_COPY.bannerAnalyticsOnly),\n bannerWithAdvertising: named(DEFAULT_COPY.bannerWithAdvertising),\n analyticsDetail: `${DEFAULT_COPY.analyticsDetail} Also loads ${names.join(', ')} with the page.`,\n }\n}\n\nexport interface ConsentBannerUiProps {\n hostId: string\n /** The visitor's recorded state; null means undecided. */\n stored: StoredVisitorConsent | null\n /** The resolved posture; only consulted while undecided. */\n posture: VisitorConsentPosture | null\n /** Region at decision time, recorded onto explicit choices. */\n country?: string | null\n /**\n * Whether this surface asks about advertising storage. Resolved by the\n * caller — from the host document on a published site, from the platform's\n * own consent declaration on the console.\n */\n advertising?: boolean\n /** Per-surface wording; see {@link ConsentCopy}. */\n copy?: ConsentCopy\n /**\n * Vendors this page loads on the analytics grant besides Google Analytics\n * (AGL-3698); the banner and the panel name them. See\n * {@link consentCopyForAnalyticsVendors}. `copy` still wins.\n */\n analyticsVendors?: readonly string[]\n /**\n * Links to the policies behind the choice, rendered under the copy on both\n * the banner and the panel.\n *\n * A node rather than a pair of URLs: the console links its own published\n * Privacy and Cookie policies through its route constants, and a published\n * site links whatever its owner has. A choice offered with no way to read\n * what is being chosen is not an informed one, but neither surface's links\n * are this component's to know.\n */\n policyLinks?: ReactNode\n /**\n * Whether the persistent \"Your Privacy Choices\" control may render here.\n *\n * `true` — the default, and every published site — draws the pill whenever\n * no other surface is up. It is the ONLY opt-out surface a visitor in the\n * implied posture ever sees, so it is platform-mounted rather than left to\n * a template that could drop it.\n *\n * `false` for a page that already carries the control somewhere better. The\n * console's signed-in pages put it in the account menu, where a person looks\n * for their own settings; floating a second copy over the page would be the\n * same control drawn twice.\n */\n showPill?: boolean\n /**\n * The caller owns what a decision DOES.\n *\n * Unset — a published site — persists through `storeVisitorConsent`, which\n * is where the withdrawal behaviour lives: it re-derives both grants from\n * the status, silences any resident tag, sweeps the analytics and\n * advertising cookies and dispatches the change event.\n *\n * Set, and the caller writes instead. The console writes through\n * `storePlatformConsent` so the record also mirrors across its hostnames;\n * the console's region simulator writes nothing at all, which is what keeps\n * previewing as-if-from-the-EU from recording a real consent record.\n */\n onDecision?: (status: VisitorConsentStatus, advertising?: boolean) => void\n}\n\n/** The card both overlays are drawn on — fixed, centred, above everything. */\nconst overlayCardSx = {\n position: 'fixed',\n left: '50%',\n bottom: 16,\n transform: 'translateX(-50%)',\n zIndex: CONSENT_OVERLAY_Z_INDEX,\n width: CARD_WIDTH,\n p: 2,\n borderRadius: 3,\n textAlign: 'left',\n} as const\n\n/**\n * The preferences panel, once its module has arrived.\n *\n * The panel is the one consent surface a visit has to ask for, and its MUI\n * dialog, modal, focus trap, transitions and switches weigh more than the\n * banner and the pill together. So it is a module of its own, fetched when\n * the panel is asked for — or when the pointer or focus reaches a control\n * that opens it — rather than with the banner every first-time visitor sees.\n *\n * Module scope, not a `React.lazy`: once loaded, every later render draws it\n * synchronously, with no Suspense boundary and no fallback frame.\n */\nlet loadedPreferencesDialog: typeof ConsentPreferencesDialog | undefined\nlet preferencesDialogLoad: Promise<void> | undefined\n\n/**\n * Fetches the preferences panel's module, once. A failed fetch is forgotten\n * so the next attempt can retry it.\n *\n * Exported for callers that know the panel is about to be needed, and for\n * specs that open it and read it back in the same tick.\n */\nexport function preloadConsentPreferences(): Promise<void> {\n preferencesDialogLoad ??= import('./consent-preferences-dialog')\n .then((module) => {\n loadedPreferencesDialog = module.ConsentPreferencesDialog\n })\n .catch((error: unknown) => {\n preferencesDialogLoad = undefined\n throw error\n })\n return preferencesDialogLoad\n}\n\n/** Starts the panel's fetch on a sign of intent; a failure surfaces on open. */\nfunction warmPreferences(): void {\n preloadConsentPreferences().catch((): void => undefined)\n}\n\nexport function ConsentBannerUi(props: ConsentBannerUiProps): ReactElement | null {\n const {\n hostId,\n stored,\n posture,\n country,\n advertising,\n copy,\n analyticsVendors,\n policyLinks,\n showPill = true,\n onDecision,\n } = props\n const words = {\n ...DEFAULT_COPY,\n ...consentCopyForAnalyticsVendors(analyticsVendors),\n ...copy,\n }\n const [preferencesOpen, setPreferencesOpen] = useState(false)\n const [analyticsChecked, setAnalyticsChecked] = useState(\n stored?.analytics === true,\n )\n // Starts UNTICKED unless the visitor previously said yes to this exact\n // category (AGL-1649). A pre-ticked advertising box is consent by\n // inattention, which is the thing a banner is supposed to replace.\n const [adsChecked, setAdsChecked] = useState(stored?.advertising === true)\n\n // The change-your-mind paths: the window event, and a `#aglyn-consent`\n // link click anywhere in the page (capture, so canvas link handling that\n // stops propagation cannot swallow it).\n useEffect(() => {\n const open = () => {\n const current = readStoredVisitorConsent(hostId)\n setAnalyticsChecked(current?.analytics === true)\n setAdsChecked(current?.advertising === true)\n setPreferencesOpen(true)\n }\n const onClick = (event: MouseEvent) => {\n const target = event.target as Element | null\n const anchor = target?.closest?.('a[href]')\n if (\n anchor &&\n (anchor.getAttribute('href') ?? '').endsWith('#aglyn-consent')\n ) {\n event.preventDefault()\n open()\n }\n }\n window.addEventListener(VISITOR_CONSENT_OPEN_EVENT, open)\n document.addEventListener('click', onClick, true)\n return () => {\n window.removeEventListener(VISITOR_CONSENT_OPEN_EVENT, open)\n document.removeEventListener('click', onClick, true)\n }\n }, [hostId])\n\n // `ads` is only ever passed through; `storeVisitorConsent` re-derives it\n // against the status, so a refusal cannot carry a grant however this is\n // called.\n const decide = (status: VisitorConsentStatus, ads = false) => {\n const granted = advertising === true && ads\n if (onDecision) {\n onDecision(status, granted)\n } else {\n storeVisitorConsent(hostId, { status, country, advertising: granted })\n }\n setPreferencesOpen(false)\n }\n\n // Same gate either way, distinct record — see `refusalStatusFor`.\n const refusalStatus = refusalStatusFor(stored, posture)\n\n // The panel is drawn only once its module is here. Until then the surface\n // that asked for it stays up, so a slow fetch never blanks the banner or\n // the pill; a fetch that fails puts the request down, and the next click\n // retries it.\n const [, setPreferencesArrived] = useState(false)\n useEffect(() => {\n if (!preferencesOpen || loadedPreferencesDialog) return undefined\n let active = true\n preloadConsentPreferences().then(\n () => {\n if (active) setPreferencesArrived(true)\n },\n () => {\n if (active) setPreferencesOpen(false)\n },\n )\n return () => {\n active = false\n }\n }, [preferencesOpen])\n const PreferencesDialog = preferencesOpen ? loadedPreferencesDialog : undefined\n\n const askBanner = !stored && posture === 'opt-in' && !PreferencesDialog\n\n // Before the early returns below, so the hook order never depends on which\n // of the three surfaces is up. The banner and the panel are centred cards\n // that reserve nothing — only the pill parks itself on the footer.\n const pillRef = useRef<HTMLButtonElement | null>(null)\n useConsentPillClearance(pillRef, showPill && !PreferencesDialog && !askBanner)\n\n if (PreferencesDialog) {\n return (\n <PreferencesDialog\n title={CONSENT_OPT_OUT_TITLE}\n zIndex={CONSENT_OVERLAY_Z_INDEX}\n words={words}\n advertising={advertising}\n policyLinks={policyLinks}\n analyticsChecked={analyticsChecked}\n onAnalyticsChange={setAnalyticsChecked}\n adsChecked={adsChecked}\n onAdsChange={setAdsChecked}\n onClose={() => setPreferencesOpen(false)}\n onDeclineAll={() => decide(refusalStatus)}\n onSave={() =>\n decide(\n analyticsChecked ? 'accepted' : refusalStatus,\n // Advertising cannot outlive analytics: unticking analytics and\n // leaving advertising ticked is a refusal of both, which\n // `consentModeSignals` also clamps independently.\n analyticsChecked && adsChecked,\n )\n }\n />\n )\n }\n\n if (askBanner) {\n return (\n <Paper\n elevation={8}\n role=\"region\"\n aria-label=\"Privacy choices\"\n data-aglyn-consent-banner=\"\"\n sx={overlayCardSx}\n >\n <Stack\n direction={{ xs: 'column', sm: 'row' }}\n spacing={1.5}\n sx={{ alignItems: { xs: 'stretch', sm: 'center' } }}\n >\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\">\n {advertising\n ? words.bannerWithAdvertising\n : words.bannerAnalyticsOnly}\n </Typography>\n {policyLinks ? <Box sx={{ mt: 0.5 }}>{policyLinks}</Box> : null}\n </Box>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ flexShrink: 0, flexWrap: 'wrap' }}\n >\n <Button\n size=\"small\"\n onPointerEnter={warmPreferences}\n onFocus={warmPreferences}\n onClick={() => {\n setAnalyticsChecked(stored != null && stored.analytics)\n setAdsChecked(stored != null && stored.advertising === true)\n setPreferencesOpen(true)\n }}\n >\n {'Preferences'}\n </Button>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={() => decide('declined')}\n >\n {'Decline'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => decide('accepted', advertising === true)}\n >\n {advertising ? 'Allow all' : 'Allow'}\n </Button>\n </Stack>\n </Stack>\n </Paper>\n )\n }\n\n if (!showPill) return null\n\n // The pill renders whenever no other surface is up — INCLUDING the\n // implied posture, where it is the only opt-out surface there is.\n return (\n <Button\n ref={pillRef}\n type=\"button\"\n // No ripple, and it is not cosmetic: `consent-opt-out-title.spec.tsx`\n // reads the control's LAST child to prove the §7015 title is the text\n // immediately right of the §7015 mark, and a ripple span would be the\n // last child instead.\n disableRipple\n data-aglyn-consent-pill=\"\"\n aria-label={CONSENT_OPT_OUT_TITLE}\n variant=\"outlined\"\n size=\"small\"\n onPointerEnter={warmPreferences}\n onFocus={warmPreferences}\n onClick={() => {\n const current = onDecision ? stored : readStoredVisitorConsent(hostId)\n setAnalyticsChecked(current?.analytics === true)\n setAdsChecked(current?.advertising === true)\n setPreferencesOpen(true)\n }}\n sx={{\n position: 'fixed',\n left: 12,\n bottom: 12,\n zIndex: CONSENT_PILL_Z_INDEX,\n gap: 0.75,\n flexWrap: 'wrap',\n maxWidth: 'calc(100vw - 24px)',\n borderRadius: 999,\n textTransform: 'none',\n color: 'text.secondary',\n borderColor: 'divider',\n backgroundColor: 'background.paper',\n }}\n >\n {/*\n Icon FIRST: §7015 places the opt-out icon immediately to the left of\n the title, and this is the control the regulation is about. The\n prior-consent banner deliberately gets neither the title nor the icon\n — it is a consent solicitation that disappears once answered, so\n dressing it in the regulation's mark would advertise it as the\n persistent opt-out link it cannot be.\n */}\n <CcpaOptOutIcon />\n {CONSENT_OPT_OUT_TITLE}\n </Button>\n )\n}\n\nexport default ConsentBannerUi\n"],"names":["Box","Button","Paper","Stack","Typography","useEffect","useRef","useState","readStoredVisitorConsent","refusalStatusFor","storeVisitorConsent","VISITOR_CONSENT_OPEN_EVENT","CONSENT_OPT_OUT_TITLE","OPT_OUT_ICON_LEFT_FIELD_PATH","OPT_OUT_ICON_SHELL_PATH","OPT_OUT_ICON_CROSS_PATH","OPT_OUT_ICON_CHECK_PATH","OPT_OUT_ICON_BLUE","OPT_OUT_ICON_WHITE","CcpaOptOutIcon","svg","xmlns","viewBox","width","height","aria-hidden","focusable","style","flexShrink","display","data-aglyn-consent-optout-icon","path","d","fill","fillRule","clipRule","CONSENT_OVERLAY_Z_INDEX","CONSENT_PILL_Z_INDEX","CARD_WIDTH","PILL_CLEARANCE","FOOTER_SELECTOR","consentPillClearance","viewportHeight","pillTop","Number","isFinite","Math","max","ceil","useConsentPillClearance","pillRef","active","doc","pill","current","ownerDocument","view","defaultView","target","querySelector","body","previous","getPropertyValue","previousPriority","getPropertyPriority","restore","setProperty","removeProperty","apply","natural","parseFloat","getComputedStyle","paddingBottom","needed","innerHeight","getBoundingClientRect","top","addEventListener","observer","ResizeObserver","undefined","observe","removeEventListener","disconnect","DEFAULT_COPY","panelIntro","strictlyNecessary","bannerAnalyticsOnly","bannerWithAdvertising","analyticsLabel","analyticsDetail","advertisingLabel","advertisingDetail","consentCopyForAnalyticsVendors","vendors","names","filter","Boolean","length","list","joined","slice","join","named","sentence","replace","overlayCardSx","position","left","bottom","transform","zIndex","p","borderRadius","textAlign","loadedPreferencesDialog","preferencesDialogLoad","preloadConsentPreferences","then","module","ConsentPreferencesDialog","catch","error","warmPreferences","ConsentBannerUi","props","hostId","stored","posture","country","advertising","copy","analyticsVendors","policyLinks","showPill","onDecision","words","preferencesOpen","setPreferencesOpen","analyticsChecked","setAnalyticsChecked","analytics","adsChecked","setAdsChecked","open","onClick","event","anchor","closest","getAttribute","endsWith","preventDefault","window","document","decide","status","ads","granted","refusalStatus","setPreferencesArrived","PreferencesDialog","askBanner","title","onAnalyticsChange","onAdsChange","onClose","onDeclineAll","onSave","elevation","role","aria-label","data-aglyn-consent-banner","sx","direction","xs","sm","spacing","alignItems","flex","minWidth","variant","mt","flexWrap","size","onPointerEnter","onFocus","ref","type","disableRipple","data-aglyn-consent-pill","gap","maxWidth","textTransform","color","borderColor","backgroundColor"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,4EAA4E;AAC5E,mEAAmE;AACnE,uEAAuE;AACvE,wEAAwE;AACxE,oEAAoE;AACpE,0EAA0E;AAC1E,mEAAmE;AACnE,+DAA+D;AAE/D,SAASA,GAAG,EAAEC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACrE,SAGEC,SAAS,EACTC,MAAM,EACNC,QAAQ,QACH,QAAO;AAEd,SACEC,wBAAwB,EACxBC,gBAAgB,EAEhBC,mBAAmB,EACnBC,0BAA0B,QAGrB,uBAAmB;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,MAAMC,wBAAwB,uBAAsB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CC,GACD,2EAA2E,GAC3E,MAAMC,+BACJ;AACF,4EAA4E,GAC5E,MAAMC,0BACJ,4GACA;AACF,0DAA0D,GAC1D,MAAMC,0BACJ,kGACA,oHACA;AACF,0DAA0D,GAC1D,MAAMC,0BACJ,qGACA;AAEF,wEAAwE,GACxE,MAAMC,oBAAoB;AAC1B,MAAMC,qBAAqB;AAE3B;;;;;;;;;;;;;;;;;;CAkBC,GACD;;;;;;CAMC,GACD,OAAO,SAASC;IACd,qBACE,MAACC;QACCC,OAAM;QACNC,SAAQ;QACRC,OAAO;QACPC,QAAQ;QACRC,eAAY;QACZC,WAAU;QACVC,OAAO;YAAEC,YAAY;YAAGC,SAAS;QAAQ;QACzCC,kCAA+B;;0BAE/B,KAACC;gBACCC,GAAGnB;gBACHoB,MAAMf;gBACNgB,UAAS;gBACTC,UAA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