@aglyn/aglyn 1.0.0-beta.225 → 1.0.0-beta.227
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/account-acquisition.d.ts +7 -0
- package/src/lib/app-utils/account-acquisition.js +11 -3
- package/src/lib/app-utils/account-acquisition.js.map +1 -1
- package/src/lib/app-utils/after-response.d.ts +32 -0
- package/src/lib/app-utils/after-response.js +98 -0
- package/src/lib/app-utils/after-response.js.map +1 -0
- package/src/lib/app-utils/analytics-events.d.ts +7 -0
- package/src/lib/app-utils/analytics-events.js +1 -0
- package/src/lib/app-utils/analytics-events.js.map +1 -1
- package/src/lib/app-utils/api-adapter.d.ts +10 -0
- package/src/lib/app-utils/api-adapter.js +18 -0
- package/src/lib/app-utils/api-adapter.js.map +1 -1
- package/src/lib/app-utils/binding-token-catalog.js +5 -0
- package/src/lib/app-utils/binding-token-catalog.js.map +1 -1
- package/src/lib/app-utils/collection-entries.d.ts +21 -0
- package/src/lib/app-utils/collection-entries.js +20 -1
- package/src/lib/app-utils/collection-entries.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
- package/src/lib/app-utils/docs-help.generated.js +1 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +22 -15
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/notifications.d.ts +3 -2
- package/src/lib/app-utils/notifications.js +11 -3
- package/src/lib/app-utils/notifications.js.map +1 -1
- package/src/lib/foundation/definitions/platform.types.d.ts +8 -0
- package/src/lib/foundation/definitions/platform.types.js.map +1 -1
- package/src/lib/plugin-manager/feature-plugins.d.ts +38 -5
- package/src/lib/plugin-manager/feature-plugins.js +11 -1
- package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
|
@@ -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 /** 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 // --- 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 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 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","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","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,CAACH,eAAe,OAAOE,QAAQ;QACpE,MAAME,OAAO,AAACD,OAAyCC,IAAI;QAC3D,IAAI,OAAOA,SAAS,YAAY,OAAOF,QAAQ;QAC/C,IAAIG,UAAU;QACd,MAAMC,SAAS,CAACC;YACd,IAAIF,SAAS;YACbA,UAAU;YACVH,QAAQK;QACV;QACA,oDAAoD;QACpDC,WAAW,IAAMF,OAAO,OAAO;QAC/B,IAAI;;YACAF,KACA,OACAJ,eACA,aACA,CAACS,KAAgBH,OAAO,OAAOG,OAAO,YAAYA,KAAKA,KAAK;QAEhE,EAAE,eAAM;YACNH,OAAO;QACT;IACF;AACF;AAgXA,IAAII,sBAAiD;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,4BACdC,SAAoC;IAEpCF,sBAAsBE;AACxB;AAEA,gDAAgD,GAChD,OAAO,SAAS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AW,EACZ,iEAAiE;KAChEgF,OAAO,CAAC,gBAAgB,IACzB,qEAAqE;KACpEA,OAAO,CAAC,YAAY,IACpBA,OAAO,CAAC,UAAU,KAClBxF,KAAK,CAAC,GAAGkF,sBACV,uEAAuE;KACtEM,OAAO,CAAC,OAAO;IAClB,IAAI,CAACH,YAAY,OAAO;QAAErE,MAAM;QAAMyE,QAAQ;IAAW;IACzD,IACEV,6BAA6BM,eAC7BL,yBAAyBzE,GAAG,CAAC8E,eAC7BJ,sBAAsBnC,IAAI,CAAC,CAAC4C,SAAWL,WAAWM,UAAU,CAACD,UAC7D;QACA,OAAO;YAAE1E,MAAM;YAAMyE,QAAQ;QAAW;IAC1C;IACA,OAAO;QAAEzE,MAAMqE;IAAW;AAC5B;AAEA;wDACwD,GACxD,MAAMO,sBAAsB,IAAItG;AAEhC;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASuG,mBACd7E,IAA+B,EAC/Bd,MAAuC;IAEvC,MAAM4F,WAAWX,yBAAyBnE;IAC1C,IAAI,CAAC8E,SAAS9E,IAAI,EAAE;QAClB,MAAMZ,MAAMkF,OAAOtE,eAAAA,OAAQ;QAC3B,IAAI,CAAC4E,oBAAoBrF,GAAG,CAACH,MAAM;YACjCwF,oBAAoBG,GAAG,CAAC3F;YACxB,IAAI;gBACF4F,QAAQC,IAAI,CACV,CAAC,8BAA8B,EAAE7F,IAAI,iBAAiB,CAAC,GACpD0F,CAAAA,SAASL,MAAM,KAAK,aACjB,uEACA,yCAAwC;YAElD,EAAE,eAAM;YACN,kEAAkE;YACpE;QACF;QACA;IACF;IACAxE,QAAQ6E,SAAS9E,IAAI,EAAEf,oBAAoBC,iBAAAA,SAAUO;AACvD;AAEA,6EAA6E,GAC7E,OAAO,SAASyF;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\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 // --- 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 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","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,CAACH,eAAe,OAAOE,QAAQ;QACpE,MAAME,OAAO,AAACD,OAAyCC,IAAI;QAC3D,IAAI,OAAOA,SAAS,YAAY,OAAOF,QAAQ;QAC/C,IAAIG,UAAU;QACd,MAAMC,SAAS,CAACC;YACd,IAAIF,SAAS;YACbA,UAAU;YACVH,QAAQK;QACV;QACA,oDAAoD;QACpDC,WAAW,IAAMF,OAAO,OAAO;QAC/B,IAAI;;YACAF,KACA,OACAJ,eACA,aACA,CAACS,KAAgBH,OAAO,OAAOG,OAAO,YAAYA,KAAKA,KAAK;QAEhE,EAAE,eAAM;YACNH,OAAO;QACT;IACF;AACF;AAqXA,IAAII,sBAAiD;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC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 @@ export declare function pluginRequestFromWeb(request: Request, params?: Record<s
|
|
|
43
43
|
* streams gets its `Response` back at the first chunk while it keeps writing;
|
|
44
44
|
* if it fails after that, the body fails with it (see
|
|
45
45
|
* {@link PluginResponseCollector}).
|
|
46
|
+
*
|
|
47
|
+
* ## What a streaming handler does after its last byte
|
|
48
|
+
*
|
|
49
|
+
* The request ends when the streamed body closes, and the platform may
|
|
50
|
+
* freeze the instance then, while the handler is still awaiting what it
|
|
51
|
+
* started: the media CDN's serve count and bandwidth evaluation. A write
|
|
52
|
+
* frozen in flight resumes on the instance's next request and fails there
|
|
53
|
+
* with a 60-second deadline, so the serve goes uncounted. The rest of such
|
|
54
|
+
* a handler is therefore handed to `after()`, which keeps the invocation
|
|
55
|
+
* alive until it settles.
|
|
46
56
|
*/
|
|
47
57
|
export declare function runLegacyHandler(handler: LegacyApiHandler, request: Request, params?: Record<string, string | string[]>): Promise<Response>;
|
|
@@ -15,7 +15,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { Writable } from "node:stream";
|
|
18
|
+
import { loadAfterResponse, scheduleAfterResponse } from "./after-response.js";
|
|
18
19
|
import { readClientIp } from "./request-ip.js";
|
|
20
|
+
/** What this adapter's `after()` drops are logged under. */ const AFTER_RESPONSE_LABEL = '[api-adapter]';
|
|
19
21
|
/**
|
|
20
22
|
* App Router ↔ node-style handler adapter (AGL-407). The plugin API contract
|
|
21
23
|
* (`PluginApiHandler`) and a few shared handlers (`serveMediaCdn`,
|
|
@@ -337,12 +339,25 @@ import { readClientIp } from "./request-ip.js";
|
|
|
337
339
|
* streams gets its `Response` back at the first chunk while it keeps writing;
|
|
338
340
|
* if it fails after that, the body fails with it (see
|
|
339
341
|
* {@link PluginResponseCollector}).
|
|
342
|
+
*
|
|
343
|
+
* ## What a streaming handler does after its last byte
|
|
344
|
+
*
|
|
345
|
+
* The request ends when the streamed body closes, and the platform may
|
|
346
|
+
* freeze the instance then, while the handler is still awaiting what it
|
|
347
|
+
* started: the media CDN's serve count and bandwidth evaluation. A write
|
|
348
|
+
* frozen in flight resumes on the instance's next request and fails there
|
|
349
|
+
* with a 60-second deadline, so the serve goes uncounted. The rest of such
|
|
350
|
+
* a handler is therefore handed to `after()`, which keeps the invocation
|
|
351
|
+
* alive until it settles.
|
|
340
352
|
*/ export async function runLegacyHandler(handler, request, params = {}) {
|
|
353
|
+
// Loaded ahead of the handler, so `after()` is in hand by the first chunk.
|
|
354
|
+
void loadAfterResponse(AFTER_RESPONSE_LABEL);
|
|
341
355
|
const req = await pluginRequestFromWeb(request, params);
|
|
342
356
|
const res = new PluginResponseCollector();
|
|
343
357
|
const failure = {
|
|
344
358
|
failed: false
|
|
345
359
|
};
|
|
360
|
+
let settled = false;
|
|
346
361
|
const handled = (async ()=>{
|
|
347
362
|
try {
|
|
348
363
|
await handler(req, res);
|
|
@@ -354,6 +369,8 @@ import { readClientIp } from "./request-ip.js";
|
|
|
354
369
|
}
|
|
355
370
|
failure.failed = true;
|
|
356
371
|
failure.error = error;
|
|
372
|
+
} finally{
|
|
373
|
+
settled = true;
|
|
357
374
|
}
|
|
358
375
|
})();
|
|
359
376
|
await Promise.race([
|
|
@@ -361,6 +378,7 @@ import { readClientIp } from "./request-ip.js";
|
|
|
361
378
|
res.firstChunkWritten
|
|
362
379
|
]);
|
|
363
380
|
if (failure.failed) throw failure.error;
|
|
381
|
+
if (!settled) void scheduleAfterResponse(()=>handled, AFTER_RESPONSE_LABEL);
|
|
364
382
|
return res.toResponse();
|
|
365
383
|
}
|
|
366
384
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/api-adapter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Writable } from 'node:stream'\nimport type { PluginApiRequest, PluginApiResponse } from './api-plugins'\nimport { readClientIp } from './request-ip'\n\n/**\n * A node-style API handler runnable through {@link runLegacyHandler}. Both\n * the framework-light `PluginApiHandler` and the shared handlers typed with\n * `NextApiRequest`/`NextApiResponse` (serveMediaCdn/servePluginFetch) satisfy\n * it — their parameter types differ (contravariance), so the boundary is\n * intentionally loose. The runtime shapes we pass (below) cover what each\n * handler actually touches.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LegacyApiHandler = (req: any, res: any) => unknown\n\n/**\n * App Router ↔ node-style handler adapter (AGL-407). The plugin API contract\n * (`PluginApiHandler`) and a few shared handlers (`serveMediaCdn`,\n * `servePluginFetch`) are deliberately framework-light `(req, res)` functions\n * — that structural shape is what keeps plugins decoupled from any Next\n * router. This module lets an App Router `route.ts` invoke them from a Web\n * `Request`, so the tenant's API surface moves to the App Router with **zero\n * changes to plugin handlers** (they still run unchanged on the console's\n * Pages Router too). The response collector is a real `Writable`, so a\n * handler that pipes a read stream into `res` streams its body to the client\n * rather than handing it over whole — see {@link PluginResponseCollector}.\n */\n\n/**\n * The address a node-style handler reads as `req.socket.remoteAddress`.\n *\n * There is no real socket behind an App Router `Request`, so this stands in\n * for one — which makes it a client-address reader wearing a socket's name,\n * and every plugin handler that falls back to `req.socket?.remoteAddress`\n * inherits whatever it decides. It goes through the shared reader for exactly\n * that reason: the fallback has to be the same trusted hop as the header\n * reading it falls back FROM, or a handler could be steered onto a\n * caller-supplied value by omitting a header.\n *\n * `undefined` rather than a placeholder when nothing is readable — node leaves\n * `remoteAddress` undefined on a destroyed socket, so handlers already have to\n * cope with its absence.\n */\nfunction clientIp(headers: Headers): string | undefined {\n return readClientIp(headers) ?? undefined\n}\n\n/** Parse a `Cookie` header into a flat record. */\nfunction parseCookies(headers: Headers): Record<string, string> {\n const raw = headers.get('cookie')\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(';')) {\n const index = pair.indexOf('=')\n if (index < 0) continue\n const key = pair.slice(0, index).trim()\n if (key) out[key] = decodeURIComponent(pair.slice(index + 1).trim())\n }\n return out\n}\n\n/**\n * Builds a `PluginApiRequest` from a Web `Request` plus the App Router route\n * `params` (awaited by the caller). Body parsing mirrors Next's default\n * body parser: JSON for `application/json`, form fields for urlencoded,\n * raw text otherwise; GET/HEAD carry no body.\n */\nexport async function pluginRequestFromWeb(\n request: Request,\n params: Record<string, string | string[]> = {},\n): Promise<PluginApiRequest> {\n const url = new URL(request.url)\n const query: Record<string, string | string[]> = { ...params }\n for (const key of url.searchParams.keys()) {\n if (key in query) continue\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : (all[0] ?? '')\n }\n\n const method = request.method ?? 'GET'\n let body: unknown\n let rawBody: string | undefined\n if (method !== 'GET' && method !== 'HEAD') {\n const raw = await request.text()\n rawBody = raw || undefined\n if (raw) {\n const contentType = request.headers.get('content-type') ?? ''\n if (contentType.includes('application/json')) {\n try {\n body = JSON.parse(raw)\n } catch {\n body = raw\n }\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n body = raw\n }\n }\n }\n\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n return {\n method,\n query,\n body,\n rawBody,\n headers,\n cookies: parseCookies(request.headers),\n socket: { remoteAddress: clientIp(request.headers) },\n }\n}\n\ntype WriteCallback = (error?: Error | null) => void\n\n/** A promise and the function that settles it. */\nfunction signal(): { promise: Promise<void>; resolve: () => void } {\n let resolve: () => void = () => undefined\n const promise = new Promise<void>((settle) => {\n resolve = settle\n })\n return { promise, resolve }\n}\n\n/** Statuses a `Response` may not carry a body on (Fetch §2.2.4). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])\n\n/**\n * A `PluginApiResponse` that turns a node-style handler's output into a Web\n * `Response`, in one of two shapes.\n *\n * - **A complete body** — `json`, `send`, `redirect`, or `end()` with nothing\n * written. It is kept whole and becomes a buffered `Response` once the\n * handler returns, which is the shape every plugin handler relies on.\n * - **A streamed body** — anything written through the `Writable` side:\n * `write()`, `stream.pipe(res)`, `pipeline(source, res)`. The `Response` is\n * handed back at the FIRST chunk, carrying the status and headers set by\n * then, and its body is a `ReadableStream` the client pulls one chunk at a\n * time (AGL-2810).\n *\n * ## Why a streamed body is never collected\n *\n * The media CDN pipes whole Storage objects into `res`. Collected, each\n * request held its entire file in function memory — briefly twice, while the\n * chunks were concatenated — and sent nothing until the last byte had been\n * read, so a player's opening `bytes=0-` on a large video pulled the whole\n * file before playback could start.\n *\n * ## Backpressure\n *\n * The body stream holds one chunk. A write is acknowledged only when the\n * client has taken the chunk before it, so `pipe`/`pipeline` pause the source\n * while the client is slow and a response never holds more than a few chunks\n * in memory, whatever the size of the file behind it.\n *\n * ## Failure after the first chunk\n *\n * Once the status line is gone the only honest signal left is to fail the\n * body. `destroy(error)` errors the stream, so the client sees a broken\n * transfer. Closing it instead would present a truncated file as complete —\n * which, for a video player, is a corrupt file it has no reason to doubt.\n *\n * ## A client that stops reading\n *\n * Canceling the body destroys this writer, and `pipeline` answers a\n * destination that closed early by destroying its source. An abandoned\n * response therefore stops reading from Storage instead of leaving the read\n * open behind a client that has gone.\n */\nclass PluginResponseCollector extends Writable implements PluginApiResponse {\n private statusCode = 200\n private readonly outHeaders: Record<string, string | number | readonly string[]> =\n {}\n /** What `json`/`send` produced, when nothing was streamed. */\n private completeBody: Buffer | null = null\n private body: ReadableStream<Uint8Array> | null = null\n private controller: ReadableStreamDefaultController<Uint8Array> | null = null\n /** The acknowledgement for the chunk the client has not taken yet. */\n private awaitingPull: WriteCallback | null = null\n /** Set by `_final`: the body ended, so a later teardown is not a failure. */\n private bodyEnded = false\n private readonly ended = signal()\n private readonly firstChunk = signal()\n headersSent = false\n\n constructor() {\n super()\n this.once('finish', this.ended.resolve)\n // `close` as well as `finish`: a writer destroyed before it wrote or\n // ended must still let `toResponse` return rather than wait forever.\n this.once('close', this.ended.resolve)\n // A streamed failure reaches the client through the body (`_destroy`).\n // Without a listener, `destroy(error)` would also emit an `error` event\n // nothing handles, and an unhandled `error` takes the process down.\n this.on('error', () => undefined)\n }\n\n /** True once a chunk has been written, so the `Response` is committed. */\n get streaming(): boolean {\n return this.body !== null\n }\n\n /** Settles at the first streamed chunk. */\n get firstChunkWritten(): Promise<void> {\n return this.firstChunk.promise\n }\n\n override _write(\n chunk: unknown,\n encoding: BufferEncoding,\n callback: WriteCallback,\n ): void {\n this.headersSent = true\n const controller = this.controller ?? this.openBody()\n try {\n controller.enqueue(\n chunk instanceof Uint8Array ? chunk : Buffer.from(String(chunk), encoding),\n )\n } catch (error) {\n // The client already canceled or the body already failed: the write\n // fails the way a write to a closed socket does.\n callback(error instanceof Error ? error : new Error(String(error)))\n return\n }\n if ((controller.desiredSize ?? 0) > 0) callback()\n else this.awaitingPull = callback\n }\n\n override _final(callback: WriteCallback): void {\n this.bodyEnded = true\n try {\n this.controller?.close()\n } catch {\n // Canceled by the client; nothing is waiting for the end.\n }\n callback()\n }\n\n override _destroy(error: Error | null, callback: WriteCallback): void {\n this.awaitingPull = null\n if (this.controller && !this.bodyEnded) {\n try {\n this.controller.error(\n error ?? new Error('Response body closed before it ended'),\n )\n } catch {\n // Already closed or errored.\n }\n }\n callback(error)\n }\n\n /** Commits the response: the status and headers set so far are final. */\n private openBody(): ReadableStreamDefaultController<Uint8Array> {\n const started: { controller?: ReadableStreamDefaultController<Uint8Array> } =\n {}\n this.body = new ReadableStream<Uint8Array>(\n {\n start: (controller) => {\n started.controller = controller\n },\n pull: () => {\n const acknowledge = this.awaitingPull\n this.awaitingPull = null\n acknowledge?.()\n },\n cancel: () => {\n this.awaitingPull = null\n this.destroy()\n },\n },\n { highWaterMark: 1 },\n )\n // `start` runs synchronously inside the constructor (Streams §4.2.4).\n if (!started.controller) {\n throw new Error('ReadableStream did not start synchronously')\n }\n this.controller = started.controller\n this.firstChunk.resolve()\n return started.controller\n }\n\n status(code: number): this {\n this.statusCode = code\n return this\n }\n\n setHeader(name: string, value: string | number | readonly string[]): void {\n this.outHeaders[name.toLowerCase()] = value\n }\n\n removeHeader(name: string): void {\n delete this.outHeaders[name.toLowerCase()]\n }\n\n json(body: unknown): void {\n if (this.outHeaders['content-type'] === undefined) {\n this.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.endWith(Buffer.from(JSON.stringify(body)))\n }\n\n send(body: unknown): void {\n if (body === undefined || body === null) return void this.end()\n if (Buffer.isBuffer(body)) return void this.endWith(body)\n if (typeof body === 'string') return void this.endWith(Buffer.from(body))\n return this.json(body)\n }\n\n redirect(statusOrUrl: number | string, maybeUrl?: string): void {\n const status = typeof statusOrUrl === 'number' ? statusOrUrl : 302\n const location = typeof statusOrUrl === 'number' ? (maybeUrl ?? '') : statusOrUrl\n this.statusCode = status\n this.setHeader('location', location)\n this.end()\n }\n\n /**\n * Ends the response with a complete body. After a streamed chunk the body\n * is already a stream, so the bytes can only join it.\n */\n private endWith(body: Buffer): void {\n if (this.body) {\n this.end(body)\n return\n }\n this.completeBody = body\n this.end()\n }\n\n /**\n * The Web `Response`, as soon as it is decided: at the first streamed chunk,\n * or once the handler has ended the response with a complete body.\n */\n async toResponse(): Promise<Response> {\n await Promise.race([this.ended.promise, this.firstChunk.promise])\n const headers = new Headers()\n for (const [key, value] of Object.entries(this.outHeaders)) {\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, String(item))\n } else {\n headers.set(key, String(value))\n }\n }\n const bodyless = NULL_BODY_STATUSES.has(this.statusCode)\n if (this.body) {\n if (bodyless) {\n void this.body.cancel()\n return new Response(null, { status: this.statusCode, headers })\n }\n return new Response(this.body, { status: this.statusCode, headers })\n }\n const body = this.completeBody\n return new Response(\n bodyless || !body || body.length === 0 ? null : (body as BodyInit),\n { status: this.statusCode, headers },\n )\n }\n}\n\n/**\n * Runs a node-style `(req, res)` handler against a Web `Request` and returns\n * the Web `Response` it produced. The entry point for App Router `route.ts`\n * files that dispatch to plugin handlers or the shared `serveMediaCdn` /\n * `servePluginFetch` handlers. Runs on the Node.js runtime (streams,\n * firebase-admin) — not edge.\n *\n * A handler that responds with a complete body is awaited to the end, and a\n * throw before it responds rejects exactly as it always has. A handler that\n * streams gets its `Response` back at the first chunk while it keeps writing;\n * if it fails after that, the body fails with it (see\n * {@link PluginResponseCollector}).\n */\nexport async function runLegacyHandler(\n handler: LegacyApiHandler,\n request: Request,\n params: Record<string, string | string[]> = {},\n): Promise<Response> {\n const req = await pluginRequestFromWeb(request, params)\n const res = new PluginResponseCollector()\n const failure: { error?: unknown; failed: boolean } = { failed: false }\n const handled = (async (): Promise<void> => {\n try {\n await handler(req, res)\n } catch (error) {\n if (res.streaming) {\n // The status line is already out, so only the body can carry this.\n res.destroy(error instanceof Error ? error : new Error(String(error)))\n return\n }\n failure.failed = true\n failure.error = error\n }\n })()\n await Promise.race([handled, res.firstChunkWritten])\n if (failure.failed) throw failure.error\n return res.toResponse()\n}\n"],"names":["Writable","readClientIp","clientIp","headers","undefined","parseCookies","raw","get","out","pair","split","index","indexOf","key","slice","trim","decodeURIComponent","pluginRequestFromWeb","request","params","url","URL","query","searchParams","keys","all","getAll","length","method","body","rawBody","text","contentType","includes","JSON","parse","Object","fromEntries","URLSearchParams","forEach","value","cookies","socket","remoteAddress","signal","resolve","promise","Promise","settle","NULL_BODY_STATUSES","Set","PluginResponseCollector","streaming","firstChunkWritten","firstChunk","_write","chunk","encoding","callback","controller","headersSent","openBody","enqueue","Uint8Array","Buffer","from","String","error","Error","desiredSize","awaitingPull","_final","bodyEnded","close","_destroy","started","ReadableStream","start","pull","acknowledge","cancel","destroy","highWaterMark","status","code","statusCode","setHeader","name","outHeaders","toLowerCase","removeHeader","json","endWith","stringify","send","end","isBuffer","redirect","statusOrUrl","maybeUrl","location","completeBody","toResponse","race","ended","Headers","entries","Array","isArray","item","append","set","bodyless","has","Response","once","on","runLegacyHandler","handler","req","res","failure","failed","handled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC,YAAY,QAAQ,kBAAc;AAa3C;;;;;;;;;;;CAWC,GAED;;;;;;;;;;;;;;CAcC,GACD,SAASC,SAASC,OAAgB;QACzBF;IAAP,QAAOA,gBAAAA,aAAaE,oBAAbF,gBAAyBG;AAClC;AAEA,gDAAgD,GAChD,SAASC,aAAaF,OAAgB;IACpC,MAAMG,MAAMH,QAAQI,GAAG,CAAC;IACxB,IAAI,CAACD,KAAK,OAAO,CAAC;IAClB,MAAME,MAA8B,CAAC;IACrC,KAAK,MAAMC,QAAQH,IAAII,KAAK,CAAC,KAAM;QACjC,MAAMC,QAAQF,KAAKG,OAAO,CAAC;QAC3B,IAAID,QAAQ,GAAG;QACf,MAAME,MAAMJ,KAAKK,KAAK,CAAC,GAAGH,OAAOI,IAAI;QACrC,IAAIF,KAAKL,GAAG,CAACK,IAAI,GAAGG,mBAAmBP,KAAKK,KAAK,CAACH,QAAQ,GAAGI,IAAI;IACnE;IACA,OAAOP;AACT;AAEA;;;;;CAKC,GACD,OAAO,eAAeS,qBACpBC,OAAgB,EAChBC,SAA4C,CAAC,CAAC;QAU/BD;IARf,MAAME,MAAM,IAAIC,IAAIH,QAAQE,GAAG;IAC/B,MAAME,QAA2C,aAAKH;IACtD,KAAK,MAAMN,OAAOO,IAAIG,YAAY,CAACC,IAAI,GAAI;YAGJC;QAFrC,IAAIZ,OAAOS,OAAO;QAClB,MAAMG,MAAML,IAAIG,YAAY,CAACG,MAAM,CAACb;QACpCS,KAAK,CAACT,IAAI,GAAGY,IAAIE,MAAM,GAAG,IAAIF,OAAOA,QAAAA,GAAG,CAAC,EAAE,YAANA,QAAU;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QAAQtD,KAAK,GAAGA;QAClB;IACF,CAAA;IACA,MAAMpB,QAAQwD,IAAI,CAAC;QAACoB;QAASH,IAAInE,iBAAiB;KAAC;IACnD,IAAIoE,QAAQC,MAAM,EAAE,MAAMD,QAAQtD,KAAK;IACvC,OAAOqD,IAAIlB,UAAU;AACvB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/api-adapter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Writable } from 'node:stream'\nimport { loadAfterResponse, scheduleAfterResponse } from './after-response'\nimport type { PluginApiRequest, PluginApiResponse } from './api-plugins'\nimport { readClientIp } from './request-ip'\n\n/** What this adapter's `after()` drops are logged under. */\nconst AFTER_RESPONSE_LABEL = '[api-adapter]'\n\n/**\n * A node-style API handler runnable through {@link runLegacyHandler}. Both\n * the framework-light `PluginApiHandler` and the shared handlers typed with\n * `NextApiRequest`/`NextApiResponse` (serveMediaCdn/servePluginFetch) satisfy\n * it — their parameter types differ (contravariance), so the boundary is\n * intentionally loose. The runtime shapes we pass (below) cover what each\n * handler actually touches.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LegacyApiHandler = (req: any, res: any) => unknown\n\n/**\n * App Router ↔ node-style handler adapter (AGL-407). The plugin API contract\n * (`PluginApiHandler`) and a few shared handlers (`serveMediaCdn`,\n * `servePluginFetch`) are deliberately framework-light `(req, res)` functions\n * — that structural shape is what keeps plugins decoupled from any Next\n * router. This module lets an App Router `route.ts` invoke them from a Web\n * `Request`, so the tenant's API surface moves to the App Router with **zero\n * changes to plugin handlers** (they still run unchanged on the console's\n * Pages Router too). The response collector is a real `Writable`, so a\n * handler that pipes a read stream into `res` streams its body to the client\n * rather than handing it over whole — see {@link PluginResponseCollector}.\n */\n\n/**\n * The address a node-style handler reads as `req.socket.remoteAddress`.\n *\n * There is no real socket behind an App Router `Request`, so this stands in\n * for one — which makes it a client-address reader wearing a socket's name,\n * and every plugin handler that falls back to `req.socket?.remoteAddress`\n * inherits whatever it decides. It goes through the shared reader for exactly\n * that reason: the fallback has to be the same trusted hop as the header\n * reading it falls back FROM, or a handler could be steered onto a\n * caller-supplied value by omitting a header.\n *\n * `undefined` rather than a placeholder when nothing is readable — node leaves\n * `remoteAddress` undefined on a destroyed socket, so handlers already have to\n * cope with its absence.\n */\nfunction clientIp(headers: Headers): string | undefined {\n return readClientIp(headers) ?? undefined\n}\n\n/** Parse a `Cookie` header into a flat record. */\nfunction parseCookies(headers: Headers): Record<string, string> {\n const raw = headers.get('cookie')\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(';')) {\n const index = pair.indexOf('=')\n if (index < 0) continue\n const key = pair.slice(0, index).trim()\n if (key) out[key] = decodeURIComponent(pair.slice(index + 1).trim())\n }\n return out\n}\n\n/**\n * Builds a `PluginApiRequest` from a Web `Request` plus the App Router route\n * `params` (awaited by the caller). Body parsing mirrors Next's default\n * body parser: JSON for `application/json`, form fields for urlencoded,\n * raw text otherwise; GET/HEAD carry no body.\n */\nexport async function pluginRequestFromWeb(\n request: Request,\n params: Record<string, string | string[]> = {},\n): Promise<PluginApiRequest> {\n const url = new URL(request.url)\n const query: Record<string, string | string[]> = { ...params }\n for (const key of url.searchParams.keys()) {\n if (key in query) continue\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : (all[0] ?? '')\n }\n\n const method = request.method ?? 'GET'\n let body: unknown\n let rawBody: string | undefined\n if (method !== 'GET' && method !== 'HEAD') {\n const raw = await request.text()\n rawBody = raw || undefined\n if (raw) {\n const contentType = request.headers.get('content-type') ?? ''\n if (contentType.includes('application/json')) {\n try {\n body = JSON.parse(raw)\n } catch {\n body = raw\n }\n } else if (contentType.includes('application/x-www-form-urlencoded')) {\n body = Object.fromEntries(new URLSearchParams(raw))\n } else {\n body = raw\n }\n }\n }\n\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n return {\n method,\n query,\n body,\n rawBody,\n headers,\n cookies: parseCookies(request.headers),\n socket: { remoteAddress: clientIp(request.headers) },\n }\n}\n\ntype WriteCallback = (error?: Error | null) => void\n\n/** A promise and the function that settles it. */\nfunction signal(): { promise: Promise<void>; resolve: () => void } {\n let resolve: () => void = () => undefined\n const promise = new Promise<void>((settle) => {\n resolve = settle\n })\n return { promise, resolve }\n}\n\n/** Statuses a `Response` may not carry a body on (Fetch §2.2.4). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304])\n\n/**\n * A `PluginApiResponse` that turns a node-style handler's output into a Web\n * `Response`, in one of two shapes.\n *\n * - **A complete body** — `json`, `send`, `redirect`, or `end()` with nothing\n * written. It is kept whole and becomes a buffered `Response` once the\n * handler returns, which is the shape every plugin handler relies on.\n * - **A streamed body** — anything written through the `Writable` side:\n * `write()`, `stream.pipe(res)`, `pipeline(source, res)`. The `Response` is\n * handed back at the FIRST chunk, carrying the status and headers set by\n * then, and its body is a `ReadableStream` the client pulls one chunk at a\n * time (AGL-2810).\n *\n * ## Why a streamed body is never collected\n *\n * The media CDN pipes whole Storage objects into `res`. Collected, each\n * request held its entire file in function memory — briefly twice, while the\n * chunks were concatenated — and sent nothing until the last byte had been\n * read, so a player's opening `bytes=0-` on a large video pulled the whole\n * file before playback could start.\n *\n * ## Backpressure\n *\n * The body stream holds one chunk. A write is acknowledged only when the\n * client has taken the chunk before it, so `pipe`/`pipeline` pause the source\n * while the client is slow and a response never holds more than a few chunks\n * in memory, whatever the size of the file behind it.\n *\n * ## Failure after the first chunk\n *\n * Once the status line is gone the only honest signal left is to fail the\n * body. `destroy(error)` errors the stream, so the client sees a broken\n * transfer. Closing it instead would present a truncated file as complete —\n * which, for a video player, is a corrupt file it has no reason to doubt.\n *\n * ## A client that stops reading\n *\n * Canceling the body destroys this writer, and `pipeline` answers a\n * destination that closed early by destroying its source. An abandoned\n * response therefore stops reading from Storage instead of leaving the read\n * open behind a client that has gone.\n */\nclass PluginResponseCollector extends Writable implements PluginApiResponse {\n private statusCode = 200\n private readonly outHeaders: Record<string, string | number | readonly string[]> =\n {}\n /** What `json`/`send` produced, when nothing was streamed. */\n private completeBody: Buffer | null = null\n private body: ReadableStream<Uint8Array> | null = null\n private controller: ReadableStreamDefaultController<Uint8Array> | null = null\n /** The acknowledgement for the chunk the client has not taken yet. */\n private awaitingPull: WriteCallback | null = null\n /** Set by `_final`: the body ended, so a later teardown is not a failure. */\n private bodyEnded = false\n private readonly ended = signal()\n private readonly firstChunk = signal()\n headersSent = false\n\n constructor() {\n super()\n this.once('finish', this.ended.resolve)\n // `close` as well as `finish`: a writer destroyed before it wrote or\n // ended must still let `toResponse` return rather than wait forever.\n this.once('close', this.ended.resolve)\n // A streamed failure reaches the client through the body (`_destroy`).\n // Without a listener, `destroy(error)` would also emit an `error` event\n // nothing handles, and an unhandled `error` takes the process down.\n this.on('error', () => undefined)\n }\n\n /** True once a chunk has been written, so the `Response` is committed. */\n get streaming(): boolean {\n return this.body !== null\n }\n\n /** Settles at the first streamed chunk. */\n get firstChunkWritten(): Promise<void> {\n return this.firstChunk.promise\n }\n\n override _write(\n chunk: unknown,\n encoding: BufferEncoding,\n callback: WriteCallback,\n ): void {\n this.headersSent = true\n const controller = this.controller ?? this.openBody()\n try {\n controller.enqueue(\n chunk instanceof Uint8Array ? chunk : Buffer.from(String(chunk), encoding),\n )\n } catch (error) {\n // The client already canceled or the body already failed: the write\n // fails the way a write to a closed socket does.\n callback(error instanceof Error ? error : new Error(String(error)))\n return\n }\n if ((controller.desiredSize ?? 0) > 0) callback()\n else this.awaitingPull = callback\n }\n\n override _final(callback: WriteCallback): void {\n this.bodyEnded = true\n try {\n this.controller?.close()\n } catch {\n // Canceled by the client; nothing is waiting for the end.\n }\n callback()\n }\n\n override _destroy(error: Error | null, callback: WriteCallback): void {\n this.awaitingPull = null\n if (this.controller && !this.bodyEnded) {\n try {\n this.controller.error(\n error ?? new Error('Response body closed before it ended'),\n )\n } catch {\n // Already closed or errored.\n }\n }\n callback(error)\n }\n\n /** Commits the response: the status and headers set so far are final. */\n private openBody(): ReadableStreamDefaultController<Uint8Array> {\n const started: { controller?: ReadableStreamDefaultController<Uint8Array> } =\n {}\n this.body = new ReadableStream<Uint8Array>(\n {\n start: (controller) => {\n started.controller = controller\n },\n pull: () => {\n const acknowledge = this.awaitingPull\n this.awaitingPull = null\n acknowledge?.()\n },\n cancel: () => {\n this.awaitingPull = null\n this.destroy()\n },\n },\n { highWaterMark: 1 },\n )\n // `start` runs synchronously inside the constructor (Streams §4.2.4).\n if (!started.controller) {\n throw new Error('ReadableStream did not start synchronously')\n }\n this.controller = started.controller\n this.firstChunk.resolve()\n return started.controller\n }\n\n status(code: number): this {\n this.statusCode = code\n return this\n }\n\n setHeader(name: string, value: string | number | readonly string[]): void {\n this.outHeaders[name.toLowerCase()] = value\n }\n\n removeHeader(name: string): void {\n delete this.outHeaders[name.toLowerCase()]\n }\n\n json(body: unknown): void {\n if (this.outHeaders['content-type'] === undefined) {\n this.setHeader('content-type', 'application/json; charset=utf-8')\n }\n this.endWith(Buffer.from(JSON.stringify(body)))\n }\n\n send(body: unknown): void {\n if (body === undefined || body === null) return void this.end()\n if (Buffer.isBuffer(body)) return void this.endWith(body)\n if (typeof body === 'string') return void this.endWith(Buffer.from(body))\n return this.json(body)\n }\n\n redirect(statusOrUrl: number | string, maybeUrl?: string): void {\n const status = typeof statusOrUrl === 'number' ? statusOrUrl : 302\n const location = typeof statusOrUrl === 'number' ? (maybeUrl ?? '') : statusOrUrl\n this.statusCode = status\n this.setHeader('location', location)\n this.end()\n }\n\n /**\n * Ends the response with a complete body. After a streamed chunk the body\n * is already a stream, so the bytes can only join it.\n */\n private endWith(body: Buffer): void {\n if (this.body) {\n this.end(body)\n return\n }\n this.completeBody = body\n this.end()\n }\n\n /**\n * The Web `Response`, as soon as it is decided: at the first streamed chunk,\n * or once the handler has ended the response with a complete body.\n */\n async toResponse(): Promise<Response> {\n await Promise.race([this.ended.promise, this.firstChunk.promise])\n const headers = new Headers()\n for (const [key, value] of Object.entries(this.outHeaders)) {\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, String(item))\n } else {\n headers.set(key, String(value))\n }\n }\n const bodyless = NULL_BODY_STATUSES.has(this.statusCode)\n if (this.body) {\n if (bodyless) {\n void this.body.cancel()\n return new Response(null, { status: this.statusCode, headers })\n }\n return new Response(this.body, { status: this.statusCode, headers })\n }\n const body = this.completeBody\n return new Response(\n bodyless || !body || body.length === 0 ? null : (body as BodyInit),\n { status: this.statusCode, headers },\n )\n }\n}\n\n/**\n * Runs a node-style `(req, res)` handler against a Web `Request` and returns\n * the Web `Response` it produced. The entry point for App Router `route.ts`\n * files that dispatch to plugin handlers or the shared `serveMediaCdn` /\n * `servePluginFetch` handlers. Runs on the Node.js runtime (streams,\n * firebase-admin) — not edge.\n *\n * A handler that responds with a complete body is awaited to the end, and a\n * throw before it responds rejects exactly as it always has. A handler that\n * streams gets its `Response` back at the first chunk while it keeps writing;\n * if it fails after that, the body fails with it (see\n * {@link PluginResponseCollector}).\n *\n * ## What a streaming handler does after its last byte\n *\n * The request ends when the streamed body closes, and the platform may\n * freeze the instance then, while the handler is still awaiting what it\n * started: the media CDN's serve count and bandwidth evaluation. A write\n * frozen in flight resumes on the instance's next request and fails there\n * with a 60-second deadline, so the serve goes uncounted. The rest of such\n * a handler is therefore handed to `after()`, which keeps the invocation\n * alive until it settles.\n */\nexport async function runLegacyHandler(\n handler: LegacyApiHandler,\n request: Request,\n params: Record<string, string | string[]> = {},\n): Promise<Response> {\n // Loaded ahead of the handler, so `after()` is in hand by the first chunk.\n void loadAfterResponse(AFTER_RESPONSE_LABEL)\n const req = await pluginRequestFromWeb(request, params)\n const res = new PluginResponseCollector()\n const failure: { error?: unknown; failed: boolean } = { failed: false }\n let settled = false\n const handled = (async (): Promise<void> => {\n try {\n await handler(req, res)\n } catch (error) {\n if (res.streaming) {\n // The status line is already out, so only the body can carry this.\n res.destroy(error instanceof Error ? error : new Error(String(error)))\n return\n }\n failure.failed = true\n failure.error = error\n } finally {\n settled = true\n }\n })()\n await Promise.race([handled, res.firstChunkWritten])\n if (failure.failed) throw failure.error\n if (!settled) void scheduleAfterResponse(() => handled, AFTER_RESPONSE_LABEL)\n return res.toResponse()\n}\n"],"names":["Writable","loadAfterResponse","scheduleAfterResponse","readClientIp","AFTER_RESPONSE_LABEL","clientIp","headers","undefined","parseCookies","raw","get","out","pair","split","index","indexOf","key","slice","trim","decodeURIComponent","pluginRequestFromWeb","request","params","url","URL","query","searchParams","keys","all","getAll","length","method","body","rawBody","text","contentType","includes","JSON","parse","Object","fromEntries","URLSearchParams","forEach","value","cookies","socket","remoteAddress","signal","resolve","promise","Promise","settle","NULL_BODY_STATUSES","Set","PluginResponseCollector","streaming","firstChunkWritten","firstChunk","_write","chunk","encoding","callback","controller","headersSent","openBody","enqueue","Uint8Array","Buffer","from","String","error","Error","desiredSize","awaitingPull","_final","bodyEnded","close","_destroy","started","ReadableStream","start","pull","acknowledge","cancel","destroy","highWaterMark","status","code","statusCode","setHeader","name","outHeaders","toLowerCase","removeHeader","json","endWith","stringify","send","end","isBuffer","redirect","statusOrUrl","maybeUrl","location","completeBody","toResponse","race","ended","Headers","entries","Array","isArray","item","append","set","bodyless","has","Response","once","on","runLegacyHandler","handler","req","res","failure","failed","settled","handled"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,iBAAiB,EAAEC,qBAAqB,QAAQ,sBAAkB;AAE3E,SAASC,YAAY,QAAQ,kBAAc;AAE3C,0DAA0D,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,EAAE,MAAMD,QAAQtD,KAAK;IACvC,IAAI,CAACwD,SAAS,KAAK5H,sBAAsB,IAAM6H,SAAS3H;IACxD,OAAOuH,IAAIlB,UAAU;AACvB"}
|
|
@@ -125,6 +125,11 @@
|
|
|
125
125
|
label: 'Featured video',
|
|
126
126
|
description: 'The featured video’s source — a library film, a video file link or ' + 'a video host’s link — for a Video element.'
|
|
127
127
|
},
|
|
128
|
+
{
|
|
129
|
+
token: '{{entry.coverVideoDuration}}',
|
|
130
|
+
label: 'Featured video length',
|
|
131
|
+
description: 'How long the featured video runs, in seconds, for a Video element’s ' + 'duration field. Blank when the entry does not say.'
|
|
132
|
+
},
|
|
128
133
|
{
|
|
129
134
|
token: '{{entry.category}}',
|
|
130
135
|
label: 'Category',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/binding-token-catalog.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 * Browsable data-placeholder catalogs for the designer's insert picker\n * (AGL-583). Hand-typing `{{entry.title}}` stays the advanced path; these\n * catalogs give every token a friendly label + description so editors can\n * browse and insert instead of memorizing the grammar.\n *\n * The token STRINGS are owned elsewhere — `collectionEntryTokens`\n * (collection-entries.ts) and the tenant compose pipeline resolve them —\n * this module only names them for pickers. The spec cross-checks the entry\n * catalog against the resolver so the two can never drift.\n */\nexport interface BindingTokenCatalogEntry {\n /** The literal token inserted into the prop, e.g. `{{entry.title}}`. */\n token: string\n /** Friendly picker label, e.g. `Title`. */\n label: string\n /** One-line description shown as the option's secondary text. */\n description?: string\n}\n\n/**\n * `{{entry.*}}` tokens (AGL-105/551/582) — resolve per entry inside a\n * Collection entries block and page-wide on entry-template screens.\n * Mirrors {@link collectionEntryTokens}; the spec enforces the mirror.\n */\nexport const ENTRY_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n { token: '{{entry.title}}', label: 'Title', description: 'The entry headline.' },\n {\n token: '{{entry.excerpt}}',\n label: 'Excerpt',\n description: 'Short summary text.',\n },\n {\n token: '{{entry.body}}',\n label: 'Body',\n description: 'The full entry body.',\n },\n {\n token: '{{entry.url}}',\n label: 'Link URL',\n description: 'Auto-route to the entry page.',\n },\n {\n token: '{{entry.date}}',\n label: 'Published date',\n description: 'Formatted publish date.',\n },\n /*\n Beside the readable date on purpose: a designer reaching for \"the date\" in\n a Video element's Publication date field has to see that the readable one\n is the wrong pick there, and why.\n */\n {\n token: '{{entry.publishedAt}}',\n label: 'Publish timestamp',\n description:\n 'The publish date and time in ISO 8601, for a field that needs a ' +\n 'machine-readable date, such as a Video element’s publication date.',\n },\n {\n token: '{{entry.author}}',\n label: 'Author',\n description: 'The byline set on the entry.',\n },\n {\n token: '{{entry.authorBio}}',\n label: 'Author bio',\n description: 'Blurb from the author’s record.',\n },\n {\n token: '{{entry.authorImage}}',\n label: 'Author portrait',\n description: 'Portrait or logo from the author’s record.',\n },\n {\n token: '{{entry.authorUrl}}',\n label: 'Author link',\n description: 'The author’s own page.',\n },\n {\n token: '{{entry.authorPageUrl}}',\n label: 'Author page',\n description:\n 'This author’s page on this site — everything they wrote, across every ' +\n 'collection. Separate from Author link, which is their own site.',\n },\n {\n token: '{{entry.slug}}',\n label: 'Slug',\n description: 'URL-safe entry identifier.',\n },\n /*\n Named \"Its collection…\" rather than \"Collection…\", which is what these\n describe and also exactly what the `{{collection.*}}` entries below are\n called. The picker groups options by heading, so the two sets sit apart —\n but a designer scanning it reads the LABEL, and two options reading\n \"Collection name\" three lines apart is a choice made by guessing. The\n pronoun is doing real work: on the one page where both resolve, they mean\n different collections.\n */\n {\n token: '{{entry.collection}}',\n label: 'Its collection',\n description:\n 'Which section this entry belongs to. Worth binding on a listing that ' +\n 'MIXES collections — an author page — where a card otherwise cannot ' +\n 'tell a release note from an essay.',\n },\n {\n token: '{{entry.collectionSlug}}',\n label: 'Its collection slug',\n description: 'That collection’s URL segment.',\n },\n {\n token: '{{entry.collectionUrl}}',\n label: 'Its collection link',\n description: 'The listing this entry belongs to.',\n },\n {\n token: '{{entry.coverImage}}',\n label: 'Cover image',\n description: 'Cover image URL.',\n },\n {\n token: '{{entry.coverVideo}}',\n label: 'Featured video',\n description:\n 'The featured video’s source — a library film, a video file link or ' +\n 'a video host’s link — for a Video element.',\n },\n {\n token: '{{entry.category}}',\n label: 'Category',\n description: 'The entry category.',\n },\n {\n token: '{{entry.tags}}',\n label: 'Tags',\n description: 'Tags, comma separated.',\n },\n {\n token: '{{entry.seoTitle}}',\n label: 'SEO title',\n description: 'Search title; falls back to Title.',\n },\n {\n token: '{{entry.seoDescription}}',\n label: 'SEO description',\n description: 'Meta description; falls back to Excerpt.',\n },\n]\n\n/**\n * `{{collection.*}}` and `{{pagination.*}}` tokens (AGL-551/1321/1386) —\n * resolve on collection list/entry template screens (see the tenant compose\n * pipeline's collection tokens).\n *\n * The category and pagination tokens all resolve to the empty string where\n * they do not apply, so they are safe to bind unconditionally: ONE list\n * screen serves the bare listing, every `/page/{n}` and every\n * `/category/{slug}`, and a template has no runtime conditional to vary\n * itself with.\n */\nexport const COLLECTION_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n {\n token: '{{collection.name}}',\n label: 'Collection name',\n description: 'Display name of the routed collection.',\n },\n {\n token: '{{collection.slug}}',\n label: 'Collection slug',\n description: 'URL slug of the routed collection.',\n },\n {\n token: '{{collection.category}}',\n label: 'Filtered category',\n description: 'Category the URL filtered on; empty when unfiltered.',\n },\n {\n token: '{{collection.categorySlug}}',\n label: 'Filtered category slug',\n description: 'That category’s URL segment; empty when unfiltered.',\n },\n {\n token: '{{pagination.page}}',\n label: 'Current page',\n description: 'Page number this URL is showing.',\n },\n {\n token: '{{pagination.totalPages}}',\n label: 'Total pages',\n // A listing bigger than one read cannot be counted honestly (AGL-3219):\n // the count and the entries were read at two different moments, and the\n // pager built from them disagreed with itself at the page boundary. It\n // still resolves, so a template binding it keeps rendering.\n description:\n 'Pages in the listing, after any category filter. Empty on a listing too large to count — bind the next link instead.',\n },\n {\n token: '{{pagination.prevUrl}}',\n label: 'Previous page link',\n description: 'Keeps the category; empty on the first page.',\n },\n {\n token: '{{pagination.nextUrl}}',\n label: 'Next page link',\n // The reliable \"is there more\" (AGL-3219): it is set from a read that\n // asked for one entry more than the page needed, so empty means there was\n // no such entry rather than that a total said so.\n description:\n 'Keeps the category; empty when there is nothing older to show.',\n },\n]\n\n/**\n * `{{author.*}}` tokens (AGL-2518) — resolve on an author's own page,\n * `/author/{slug}`.\n *\n * Empty everywhere else, like the category tokens above and for the same\n * reason: a template has no runtime conditional, so the tokens have to be the\n * thing that varies. A heading bound to `{{author.name}}` prints a name on an\n * author page and nothing anywhere else.\n *\n * The `{{pagination.*}}` tokens resolve HERE TOO, over this author's own\n * archive — deliberately the same four names a collection listing uses, so a\n * pager built once works on both.\n */\nexport const AUTHOR_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n {\n token: '{{author.name}}',\n label: 'Name',\n description: 'The byline this page collects.',\n },\n {\n token: '{{author.bio}}',\n label: 'Bio',\n description: 'Their blurb, from the author record.',\n },\n {\n token: '{{author.image}}',\n label: 'Portrait',\n description: 'Their portrait or logo, from the author record.',\n },\n {\n token: '{{author.jobTitle}}',\n label: 'Role',\n description: 'Their job title; empty for an Organization author.',\n },\n {\n token: '{{author.worksFor}}',\n label: 'Organization',\n description: 'Who they write for; empty for an Organization author.',\n },\n {\n token: '{{author.url}}',\n label: 'Their own site',\n description:\n 'The url on their record — a personal site, not this page. Empty when ' +\n 'they have none.',\n },\n {\n token: '{{author.pageUrl}}',\n label: 'This page',\n description: 'The canonical address of the page you are designing.',\n },\n {\n token: '{{author.entryCount}}',\n label: 'Post count',\n description: 'How many entries they have published, across every collection.',\n },\n {\n token: '{{author.entryCountLabel}}',\n label: 'Post count, worded',\n description:\n '\"1 post\" or \"12 posts\" — pluralized for you, because a template has no ' +\n 'conditional to do it with.',\n },\n]\n\n/**\n * The `{{item.*}}` token for one field of the record a repeat is rendering,\n * optionally hopping one reference to a field of the referenced record\n * (AGL-180). Always takes the stable field id — display names are labels\n * only, so renaming a field never breaks a binding (AGL-578).\n */\nexport function repeatItemToken(\n fieldId: string,\n targetFieldId?: string,\n): string {\n return targetFieldId\n ? `{{item.${fieldId}.${targetFieldId}}}`\n : `{{item.${fieldId}}}`\n}\n"],"names":["ENTRY_TOKEN_CATALOG","token","label","description","COLLECTION_TOKEN_CATALOG","AUTHOR_TOKEN_CATALOG","repeatItemToken","fieldId","targetFieldId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAUD;;;;CAIC,GACD,OAAO,MAAMA,sBAA2D;IACtE;QAAEC,OAAO;QAAmBC,OAAO;QAASC,aAAa;IAAsB;IAC/E;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;;;;EAIA,GACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,qEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,2EACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;;;;;;;;EAQA,GACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,0EACA,wEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,wEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;CACD,CAAA;AAED;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,2BAAgE;IAC3E;QACEH,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACP,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,4DAA4D;QAC5DC,aACE;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACP,sEAAsE;QACtE,0EAA0E;QAC1E,kDAAkD;QAClDC,aACE;IACJ;CACD,CAAA;AAED;;;;;;;;;;;;CAYC,GACD,OAAO,MAAME,uBAA4D;IACvE;QACEJ,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,0EACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,4EACA;IACJ;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,SAASG,gBACdC,OAAe,EACfC,aAAsB;IAEtB,OAAOA,gBACH,CAAC,OAAO,EAAED,QAAQ,CAAC,EAAEC,cAAc,EAAE,CAAC,GACtC,CAAC,OAAO,EAAED,QAAQ,EAAE,CAAC;AAC3B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/binding-token-catalog.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 * Browsable data-placeholder catalogs for the designer's insert picker\n * (AGL-583). Hand-typing `{{entry.title}}` stays the advanced path; these\n * catalogs give every token a friendly label + description so editors can\n * browse and insert instead of memorizing the grammar.\n *\n * The token STRINGS are owned elsewhere — `collectionEntryTokens`\n * (collection-entries.ts) and the tenant compose pipeline resolve them —\n * this module only names them for pickers. The spec cross-checks the entry\n * catalog against the resolver so the two can never drift.\n */\nexport interface BindingTokenCatalogEntry {\n /** The literal token inserted into the prop, e.g. `{{entry.title}}`. */\n token: string\n /** Friendly picker label, e.g. `Title`. */\n label: string\n /** One-line description shown as the option's secondary text. */\n description?: string\n}\n\n/**\n * `{{entry.*}}` tokens (AGL-105/551/582) — resolve per entry inside a\n * Collection entries block and page-wide on entry-template screens.\n * Mirrors {@link collectionEntryTokens}; the spec enforces the mirror.\n */\nexport const ENTRY_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n { token: '{{entry.title}}', label: 'Title', description: 'The entry headline.' },\n {\n token: '{{entry.excerpt}}',\n label: 'Excerpt',\n description: 'Short summary text.',\n },\n {\n token: '{{entry.body}}',\n label: 'Body',\n description: 'The full entry body.',\n },\n {\n token: '{{entry.url}}',\n label: 'Link URL',\n description: 'Auto-route to the entry page.',\n },\n {\n token: '{{entry.date}}',\n label: 'Published date',\n description: 'Formatted publish date.',\n },\n /*\n Beside the readable date on purpose: a designer reaching for \"the date\" in\n a Video element's Publication date field has to see that the readable one\n is the wrong pick there, and why.\n */\n {\n token: '{{entry.publishedAt}}',\n label: 'Publish timestamp',\n description:\n 'The publish date and time in ISO 8601, for a field that needs a ' +\n 'machine-readable date, such as a Video element’s publication date.',\n },\n {\n token: '{{entry.author}}',\n label: 'Author',\n description: 'The byline set on the entry.',\n },\n {\n token: '{{entry.authorBio}}',\n label: 'Author bio',\n description: 'Blurb from the author’s record.',\n },\n {\n token: '{{entry.authorImage}}',\n label: 'Author portrait',\n description: 'Portrait or logo from the author’s record.',\n },\n {\n token: '{{entry.authorUrl}}',\n label: 'Author link',\n description: 'The author’s own page.',\n },\n {\n token: '{{entry.authorPageUrl}}',\n label: 'Author page',\n description:\n 'This author’s page on this site — everything they wrote, across every ' +\n 'collection. Separate from Author link, which is their own site.',\n },\n {\n token: '{{entry.slug}}',\n label: 'Slug',\n description: 'URL-safe entry identifier.',\n },\n /*\n Named \"Its collection…\" rather than \"Collection…\", which is what these\n describe and also exactly what the `{{collection.*}}` entries below are\n called. The picker groups options by heading, so the two sets sit apart —\n but a designer scanning it reads the LABEL, and two options reading\n \"Collection name\" three lines apart is a choice made by guessing. The\n pronoun is doing real work: on the one page where both resolve, they mean\n different collections.\n */\n {\n token: '{{entry.collection}}',\n label: 'Its collection',\n description:\n 'Which section this entry belongs to. Worth binding on a listing that ' +\n 'MIXES collections — an author page — where a card otherwise cannot ' +\n 'tell a release note from an essay.',\n },\n {\n token: '{{entry.collectionSlug}}',\n label: 'Its collection slug',\n description: 'That collection’s URL segment.',\n },\n {\n token: '{{entry.collectionUrl}}',\n label: 'Its collection link',\n description: 'The listing this entry belongs to.',\n },\n {\n token: '{{entry.coverImage}}',\n label: 'Cover image',\n description: 'Cover image URL.',\n },\n {\n token: '{{entry.coverVideo}}',\n label: 'Featured video',\n description:\n 'The featured video’s source — a library film, a video file link or ' +\n 'a video host’s link — for a Video element.',\n },\n {\n token: '{{entry.coverVideoDuration}}',\n label: 'Featured video length',\n description:\n 'How long the featured video runs, in seconds, for a Video element’s ' +\n 'duration field. Blank when the entry does not say.',\n },\n {\n token: '{{entry.category}}',\n label: 'Category',\n description: 'The entry category.',\n },\n {\n token: '{{entry.tags}}',\n label: 'Tags',\n description: 'Tags, comma separated.',\n },\n {\n token: '{{entry.seoTitle}}',\n label: 'SEO title',\n description: 'Search title; falls back to Title.',\n },\n {\n token: '{{entry.seoDescription}}',\n label: 'SEO description',\n description: 'Meta description; falls back to Excerpt.',\n },\n]\n\n/**\n * `{{collection.*}}` and `{{pagination.*}}` tokens (AGL-551/1321/1386) —\n * resolve on collection list/entry template screens (see the tenant compose\n * pipeline's collection tokens).\n *\n * The category and pagination tokens all resolve to the empty string where\n * they do not apply, so they are safe to bind unconditionally: ONE list\n * screen serves the bare listing, every `/page/{n}` and every\n * `/category/{slug}`, and a template has no runtime conditional to vary\n * itself with.\n */\nexport const COLLECTION_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n {\n token: '{{collection.name}}',\n label: 'Collection name',\n description: 'Display name of the routed collection.',\n },\n {\n token: '{{collection.slug}}',\n label: 'Collection slug',\n description: 'URL slug of the routed collection.',\n },\n {\n token: '{{collection.category}}',\n label: 'Filtered category',\n description: 'Category the URL filtered on; empty when unfiltered.',\n },\n {\n token: '{{collection.categorySlug}}',\n label: 'Filtered category slug',\n description: 'That category’s URL segment; empty when unfiltered.',\n },\n {\n token: '{{pagination.page}}',\n label: 'Current page',\n description: 'Page number this URL is showing.',\n },\n {\n token: '{{pagination.totalPages}}',\n label: 'Total pages',\n // A listing bigger than one read cannot be counted honestly (AGL-3219):\n // the count and the entries were read at two different moments, and the\n // pager built from them disagreed with itself at the page boundary. It\n // still resolves, so a template binding it keeps rendering.\n description:\n 'Pages in the listing, after any category filter. Empty on a listing too large to count — bind the next link instead.',\n },\n {\n token: '{{pagination.prevUrl}}',\n label: 'Previous page link',\n description: 'Keeps the category; empty on the first page.',\n },\n {\n token: '{{pagination.nextUrl}}',\n label: 'Next page link',\n // The reliable \"is there more\" (AGL-3219): it is set from a read that\n // asked for one entry more than the page needed, so empty means there was\n // no such entry rather than that a total said so.\n description:\n 'Keeps the category; empty when there is nothing older to show.',\n },\n]\n\n/**\n * `{{author.*}}` tokens (AGL-2518) — resolve on an author's own page,\n * `/author/{slug}`.\n *\n * Empty everywhere else, like the category tokens above and for the same\n * reason: a template has no runtime conditional, so the tokens have to be the\n * thing that varies. A heading bound to `{{author.name}}` prints a name on an\n * author page and nothing anywhere else.\n *\n * The `{{pagination.*}}` tokens resolve HERE TOO, over this author's own\n * archive — deliberately the same four names a collection listing uses, so a\n * pager built once works on both.\n */\nexport const AUTHOR_TOKEN_CATALOG: readonly BindingTokenCatalogEntry[] = [\n {\n token: '{{author.name}}',\n label: 'Name',\n description: 'The byline this page collects.',\n },\n {\n token: '{{author.bio}}',\n label: 'Bio',\n description: 'Their blurb, from the author record.',\n },\n {\n token: '{{author.image}}',\n label: 'Portrait',\n description: 'Their portrait or logo, from the author record.',\n },\n {\n token: '{{author.jobTitle}}',\n label: 'Role',\n description: 'Their job title; empty for an Organization author.',\n },\n {\n token: '{{author.worksFor}}',\n label: 'Organization',\n description: 'Who they write for; empty for an Organization author.',\n },\n {\n token: '{{author.url}}',\n label: 'Their own site',\n description:\n 'The url on their record — a personal site, not this page. Empty when ' +\n 'they have none.',\n },\n {\n token: '{{author.pageUrl}}',\n label: 'This page',\n description: 'The canonical address of the page you are designing.',\n },\n {\n token: '{{author.entryCount}}',\n label: 'Post count',\n description: 'How many entries they have published, across every collection.',\n },\n {\n token: '{{author.entryCountLabel}}',\n label: 'Post count, worded',\n description:\n '\"1 post\" or \"12 posts\" — pluralized for you, because a template has no ' +\n 'conditional to do it with.',\n },\n]\n\n/**\n * The `{{item.*}}` token for one field of the record a repeat is rendering,\n * optionally hopping one reference to a field of the referenced record\n * (AGL-180). Always takes the stable field id — display names are labels\n * only, so renaming a field never breaks a binding (AGL-578).\n */\nexport function repeatItemToken(\n fieldId: string,\n targetFieldId?: string,\n): string {\n return targetFieldId\n ? `{{item.${fieldId}.${targetFieldId}}}`\n : `{{item.${fieldId}}}`\n}\n"],"names":["ENTRY_TOKEN_CATALOG","token","label","description","COLLECTION_TOKEN_CATALOG","AUTHOR_TOKEN_CATALOG","repeatItemToken","fieldId","targetFieldId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GAUD;;;;CAIC,GACD,OAAO,MAAMA,sBAA2D;IACtE;QAAEC,OAAO;QAAmBC,OAAO;QAASC,aAAa;IAAsB;IAC/E;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;;;;EAIA,GACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,qEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,2EACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;;;;;;;;EAQA,GACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,0EACA,wEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,wEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,yEACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;CACD,CAAA;AAED;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,2BAAgE;IAC3E;QACEH,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACP,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,4DAA4D;QAC5DC,aACE;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACP,sEAAsE;QACtE,0EAA0E;QAC1E,kDAAkD;QAClDC,aACE;IACJ;CACD,CAAA;AAED;;;;;;;;;;;;CAYC,GACD,OAAO,MAAME,uBAA4D;IACvE;QACEJ,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,0EACA;IACJ;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aAAa;IACf;IACA;QACEF,OAAO;QACPC,OAAO;QACPC,aACE,4EACA;IACJ;CACD,CAAA;AAED;;;;;CAKC,GACD,OAAO,SAASG,gBACdC,OAAe,EACfC,aAAsB;IAEtB,OAAOA,gBACH,CAAC,OAAO,EAAED,QAAQ,CAAC,EAAEC,cAAc,EAAE,CAAC,GACtC,CAAC,OAAO,EAAED,QAAQ,EAAE,CAAC;AAC3B"}
|
|
@@ -317,6 +317,15 @@ export interface CollectionEntryRecord {
|
|
|
317
317
|
* the built-in entry page plays it with no template at all.
|
|
318
318
|
*/
|
|
319
319
|
coverVideo?: string;
|
|
320
|
+
/**
|
|
321
|
+
* How long {@link coverVideo} runs, in whole seconds (AGL-3584) — the unit
|
|
322
|
+
* the Video element's `durationSeconds` takes, because an author types 63
|
|
323
|
+
* and not 63000. The page's `VideoObject` publishes it as `duration`, which
|
|
324
|
+
* Google recommends, and nothing else knows it for a hosted player's link.
|
|
325
|
+
* Read through {@link collectionEntryVideoDurationSeconds}, so a value that
|
|
326
|
+
* is not a positive number is no duration at all.
|
|
327
|
+
*/
|
|
328
|
+
coverVideoDuration?: number;
|
|
320
329
|
/** Search-result title override (AGL-582); falls back to `title`. */
|
|
321
330
|
seoTitle?: string;
|
|
322
331
|
/** Meta description override (AGL-582); falls back to `excerpt`. */
|
|
@@ -444,6 +453,18 @@ export declare function collectionEntryAuthorValues(entry: CollectionEntryRecord
|
|
|
444
453
|
pageUrl: string;
|
|
445
454
|
links: ContentAuthorLink[];
|
|
446
455
|
};
|
|
456
|
+
/**
|
|
457
|
+
* A featured video's stored length as whole seconds, or `undefined` when it
|
|
458
|
+
* names none (AGL-3584).
|
|
459
|
+
*
|
|
460
|
+
* The one reading of `coverVideoDuration` for every side that touches it: the
|
|
461
|
+
* console's save, the loader, the token and the built-in page. A number or a
|
|
462
|
+
* numeric string (a form field, an import) counts when it is finite and
|
|
463
|
+
* positive; it is rounded to the second, never down to `0`, because a stored
|
|
464
|
+
* `0` reads as "no duration" downstream — the rule `videoMediaProps` applies
|
|
465
|
+
* to a library film's own length.
|
|
466
|
+
*/
|
|
467
|
+
export declare function collectionEntryVideoDurationSeconds(value: unknown): number | undefined;
|
|
447
468
|
/**
|
|
448
469
|
* The `{{entry.*}}` token map for one entry (AGL-105/551): substituted
|
|
449
470
|
* globally on entry-template screens and per-clone inside the Collection
|