@getvitops/astro 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +824 -33
  2. package/dist/config-adapters-CbTywgEY.mjs +71 -0
  3. package/dist/config-adapters-CbTywgEY.mjs.map +1 -0
  4. package/dist/exports/tracking.d.mts +1 -1
  5. package/dist/exports/tracking.mjs +1 -1
  6. package/dist/index.d.mts +65 -48
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +240 -32
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/middleware.d.mts +23 -0
  11. package/dist/middleware.d.mts.map +1 -0
  12. package/dist/middleware.mjs +34 -0
  13. package/dist/middleware.mjs.map +1 -0
  14. package/dist/routes/conversion.d.mts +131 -16
  15. package/dist/routes/conversion.d.mts.map +1 -1
  16. package/dist/routes/conversion.mjs +133 -28
  17. package/dist/routes/conversion.mjs.map +1 -1
  18. package/dist/{tracking-CmSfxWC3.mjs → tracking-Cb3A0BrC.mjs} +3 -4
  19. package/dist/tracking-Cb3A0BrC.mjs.map +1 -0
  20. package/dist/{tracking-DdEKExlE.d.mts → tracking-D2xOzjFD.d.mts} +6 -26
  21. package/dist/tracking-D2xOzjFD.d.mts.map +1 -0
  22. package/package.json +12 -8
  23. package/src/ads.ts +52 -16
  24. package/src/analytics.ts +98 -11
  25. package/src/components/Analytics.astro +5 -1
  26. package/src/components/CookieConsent.astro +2 -1
  27. package/src/components/Icon.astro +8 -1
  28. package/src/components/ReviewCardBody.astro +5 -2
  29. package/src/components/Tracking.astro +2 -1
  30. package/src/schemas/Article.astro +2 -1
  31. package/src/schemas/BookActions.astro +2 -1
  32. package/src/schemas/Breadcrumb.astro +2 -1
  33. package/src/schemas/Carousel.astro +2 -1
  34. package/src/schemas/CourseList.astro +2 -1
  35. package/src/schemas/Dataset.astro +2 -1
  36. package/src/schemas/DiscussionForum.astro +2 -1
  37. package/src/schemas/EducationQA.astro +2 -1
  38. package/src/schemas/EmployerAggregateRating.astro +2 -1
  39. package/src/schemas/Event.astro +2 -1
  40. package/src/schemas/FAQ.astro +2 -1
  41. package/src/schemas/FactCheck.astro +2 -1
  42. package/src/schemas/ImageMetadata.astro +2 -1
  43. package/src/schemas/JobPosting.astro +2 -1
  44. package/src/schemas/LocalBusiness.astro +2 -1
  45. package/src/schemas/MathSolver.astro +2 -1
  46. package/src/schemas/MovieCarousel.astro +2 -1
  47. package/src/schemas/Organization.astro +2 -1
  48. package/src/schemas/Product.astro +2 -1
  49. package/src/schemas/ProfilePage.astro +2 -1
  50. package/src/schemas/QAPage.astro +2 -1
  51. package/src/schemas/Recipe.astro +2 -1
  52. package/src/schemas/Review.astro +2 -1
  53. package/src/schemas/SoftwareApp.astro +2 -1
  54. package/src/scripts/tracking.ts +114 -21
  55. package/src/seo.ts +6 -5
  56. package/src/tracking.ts +6 -10
  57. package/virtual.d.ts +17 -1
  58. package/dist/tracking-CmSfxWC3.mjs.map +0 -1
  59. package/dist/tracking-DdEKExlE.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"conversion.mjs","names":[],"sources":["../../src/routes/conversion.ts"],"sourcesContent":["/**\n * The conversion endpoint, as a factory.\n *\n * A site's contact form and its `tel:` beacon both mean the same thing — someone\n * got in touch — and both want the same treatment: read the attribution cookie\n * off the request, build the event, notify whoever the config says. That is the\n * same three lines in every project, so it ships here.\n *\n * What deliberately does **not** ship here is field-level validation and business\n * rules — a consumer's form has its own required fields and its own response\n * shape, and baking a guess at those in would make the factory something to\n * fight rather than mount. The handler takes the parsed body and an optional\n * `validate`; that part is the caller's. What **does** ship here is generic abuse\n * resistance (honeypot, origin, rate limit, body size): this is a public,\n * unauthenticated endpoint that sends email, so leaving it wide open makes it a\n * relay and a cost amplifier regardless of whose form is behind it.\n *\n * The path matters: the capture script beacons `tel:` conversions at\n * `TRACKING_ENDPOINT` (`/api/track`, exported from `@getvitops/astro/tracking`),\n * and the integration warns at build if no route answers it.\n *\n * ```ts\n * // src/pages/api/track.ts\n * export const prerender = false;\n * import { env } from 'cloudflare:workers';\n * import { createConversionRoute } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: {\n * // A bare address is shorthand for `{ provider: 'cloudflare', to }`.\n * notifications: { email: 'sales@acme.ca' },\n * canonical: 'https://acme.ca',\n * organizationName: 'Acme',\n * },\n * binding: () => env.EMAIL,\n * // A no-JS <form method=\"post\"> submission never sees a JSON response body —\n * // it's a full navigation, so send it somewhere real.\n * redirectTo: '/thanks',\n * });\n * ```\n *\n * Cloudflare Turnstile is a separate, opt-in layer on top of the checks above —\n * pass `turnstile: { secretKey }` and a submission carrying a\n * `cf-turnstile-response` token gets it verified server-side via\n * `verifyTurnstileToken` (`@getvitops/utils/security`). The widget itself is the\n * consumer's own markup (`<script src=\"https://challenges.cloudflare.com/\n * turnstile/v0/api.js\" async defer></script>` + `<div class=\"cf-turnstile\"\n * data-sitekey=\"…\">` on their form) — there is no `FormRenderer` for this to hook\n * into generically, matching how the rest of the form is already hand-written.\n * `site.security.turnstile.siteKey` is what the generated privacy policy reads to\n * name Turnstile as a processor; wiring this option up is what makes that true\n * rather than an assertion nothing checks.\n *\n * Two things this example used to get wrong, both of which cost a consumer real\n * time. It read the binding off `locals.runtime.env`, which Astro removed in v6\n * — and because the resulting throw precedes the response, Astro re-reads the\n * request and reports a misleading \"Body has already been used\" instead of the\n * actual error. This package peers on `astro >= 7`, so that form could not work\n * for any supported consumer; `import { env } from 'cloudflare:workers'` is the\n * current one. It also called a `toNotifyContext(config)` helper that does not\n * exist — `context` is a plain `NotifyContext`, built however you like.\n */\nimport { type EmailBinding, notify, type NotifyContext } from '@getvitops/utils/notify';\nimport { verifyTurnstileToken } from '@getvitops/utils/security';\nimport { parseTrackingCookie } from '@getvitops/utils/tracking';\nimport type { ConversionEvent } from '@getvitops/utils/tracking';\n\n/** The subset of Astro's `APIContext` this needs — typed structurally so the\n * factory does not pin an Astro version. */\nexport interface ConversionRequestContext {\n request: Request;\n locals?: unknown;\n}\n\n/**\n * Records a hit for `id` at time `at` (ms) and returns the ms since the previous\n * hit for that `id`, or `null` if this is the first. Pure interface — a store\n * decides nothing, it only remembers.\n */\nexport interface RateLimitStore {\n hit(id: string, at: number): Promise<number | null> | number | null;\n}\n\n/**\n * Per-isolate, in-memory default. Good enough for a single Worker instance\n * fielding occasional contact-form spam; not durable across a fleet, and not\n * shared with other routes. Inject a KV- or Durable-Object-backed `store` for\n * real cross-instance limiting — the interface is one method wide on purpose.\n */\nclass MemoryRateLimitStore implements RateLimitStore {\n private lastHit = new Map<string, number>();\n hit(id: string, at: number): number | null {\n const prev = this.lastHit.get(id);\n this.lastHit.set(id, at);\n return prev === undefined ? null : at - prev;\n }\n}\n\nexport interface ConversionRouteOptions {\n /** Where notifications go. Build it from your site config. */\n context: NotifyContext;\n /**\n * The Workers `send_email` binding for this request, e.g. `() => env.EMAIL`\n * with `env` imported from `cloudflare:workers`. Omit it in dev and the\n * notification is printed instead of sent.\n *\n * Not `(locals) => locals.runtime.env.EMAIL` — Astro removed `locals.runtime`\n * in v6, and this package peers on `>= 7`.\n */\n binding?: (locals: unknown) => EmailBinding | undefined;\n /**\n * Reject a submission before anything is sent. Return a message to refuse.\n * This is where a consumer puts required-field checks.\n */\n validate?: (body: Record<string, unknown>) => string | null;\n /** Called with every channel outcome, delivered or not. Defaults to console. */\n onResult?: (result: Awaited<ReturnType<typeof notify>>) => void;\n /** Injected in tests. */\n now?: () => number;\n /**\n * Where to send a no-JS `<form method=\"post\">` submission on success. Without\n * this, that visitor's browser navigates to the raw `{\"success\":true}` JSON\n * body as its next page — functional, but not a page anyone should see. Has\n * no effect on the beacon/fetch (JSON) path, which always gets a JSON response.\n */\n redirectTo?: string;\n /**\n * Where to send a refused no-JS submission (validation, spam checks, malformed\n * body). Falls back to `redirectTo` if omitted, and to the JSON error response\n * if neither is set.\n */\n errorRedirectTo?: string;\n /**\n * Field names treated as honeypots: a bot fills every input it finds, a person\n * never sees these (hidden by CSS in the form markup). A non-empty value is\n * silently treated as spam — the response looks identical to a real success,\n * denying the bot the signal it needs to know the trick worked, but nothing is\n * notified and the field never reaches `notify()`. Defaults to the same names\n * `render.ts`'s `OMIT_FIELDS` already knows about (`website`, `_honeypot`,\n * `honeypot`), so the two lists don't need to be kept in sync by hand.\n */\n honeypotFields?: string[];\n /**\n * Reject a submission whose `Content-Length` exceeds this many bytes. Default\n * 25_000 — generous for a contact form with no file upload, tiny for anything\n * meant to relay large payloads. Best-effort: `Content-Length` can be absent\n * or spoofed, same caveat as the origin check below.\n */\n maxBodyBytes?: number;\n /**\n * Reject a submission whose `Origin` header doesn't match this origin.\n * Defaults to `context.canonical`'s origin. Pass `false` to disable.\n *\n * Best-effort, not a CSRF guard: browsers omit `Origin` on plenty of\n * legitimate same-origin requests, so its *absence* is never treated as a\n * mismatch — only a present-and-different value is rejected. That still stops\n * the common case (a script hitting the endpoint directly from elsewhere)\n * without breaking real submissions from older or privacy-hardened browsers.\n */\n allowedOrigin?: string | false;\n /**\n * Minimum interval between accepted submissions from the same IP. Pass\n * `false` to disable. `windowMs` defaults to 10 seconds — enough to blunt a\n * script firing in a loop without troubling someone who fat-fingers a form\n * and resubmits.\n */\n rateLimit?: { windowMs?: number; store?: RateLimitStore } | false;\n /**\n * Verify a Cloudflare Turnstile token server-side. The **secret** key —\n * unlike `site.security.turnstile.siteKey`, which is public config — must come\n * from an env var, never a config file (the same rule as every other\n * credential in this toolchain).\n */\n turnstile?: {\n secretKey: string;\n /** The submitted field carrying the token. Default `cf-turnstile-response`\n * — the name Cloudflare's widget submits under. */\n fieldName?: string;\n /**\n * Reject a submission with no token at all, rather than only a present-and-\n * invalid one. Default `false`: an absent token is the ordinary shape of a\n * visitor with JS disabled, and this factory is built around that path\n * staying usable. Set `true` only for a form where verified-human matters\n * enough to accept that trade-off — doing so means that form no longer\n * works without JS, on purpose.\n */\n required?: boolean;\n };\n}\n\n/** Fields that are never part of a submission's meaning. `cf-turnstile-response`\n * is excluded unconditionally, matching `render.ts`'s `OMIT_FIELDS` — the field\n * carries a verification token, not something the visitor wrote. */\nconst CONTROL_FIELDS = new Set(['event', 'phone', 'cf-turnstile-response']);\nconst DEFAULT_HONEYPOT_FIELDS = ['website', '_honeypot', 'honeypot'];\nconst DEFAULT_MAX_BODY_BYTES = 25_000;\nconst DEFAULT_RATE_LIMIT_WINDOW_MS = 10_000;\n\nfunction toFormData(\n body: Record<string, unknown>,\n honeypotFields: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(body)) {\n if (CONTROL_FIELDS.has(key) || honeypotFields.includes(key)) continue;\n if (value === undefined || value === null) continue;\n out[key] = String(value);\n }\n return out;\n}\n\nfunction hasHoneypot(body: Record<string, unknown>, honeypotFields: string[]): boolean {\n return honeypotFields.some((field) => {\n const value = body[field];\n return typeof value === 'string' && value.trim() !== '';\n });\n}\n\nfunction originOf(url: string | undefined): string | null {\n if (!url) return null;\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n\n/** A `Location` header response — used for the no-JS form path instead of\n * `Response.redirect()`, which requires a base URL this factory doesn't have. */\nfunction redirectTo(location: string, status = 303): Response {\n return new Response(null, { status, headers: { Location: location } });\n}\n\n/**\n * Build a POST handler for conversions.\n *\n * Returns 204 for a beacon and 200 with `{ success }` for a JSON (fetch-based)\n * form submission, matching what `navigator.sendBeacon` and a fetch-submitting\n * form each expect. A no-JS `<form method=\"post\">` — `application/\n * x-www-form-urlencoded` or `multipart/form-data` — is parsed the same way and,\n * on success, redirected to `redirectTo` if one is configured.\n *\n * **A failed notification does not fail the request.** The visitor has already\n * submitted; refusing them because our mail did not go out turns a lost\n * notification into a lost conversion. Failures are reported through `onResult`.\n */\nexport function createConversionRoute(options: ConversionRouteOptions) {\n const {\n context,\n binding,\n validate,\n onResult,\n now = Date.now,\n redirectTo: successRedirect,\n errorRedirectTo = successRedirect,\n honeypotFields = DEFAULT_HONEYPOT_FIELDS,\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n } = options;\n\n const allowedOrigin =\n options.allowedOrigin === false ? null : (options.allowedOrigin ?? originOf(context.canonical));\n\n const rateLimit =\n options.rateLimit === false\n ? null\n : {\n windowMs: options.rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS,\n store: options.rateLimit?.store ?? new MemoryRateLimitStore(),\n };\n\n return async ({ request, locals }: ConversionRequestContext): Promise<Response> => {\n const contentType = request.headers.get('content-type') ?? '';\n const isFormPost =\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded');\n\n const respondError = (error: string, status: number): Response =>\n isFormPost && errorRedirectTo\n ? redirectTo(errorRedirectTo)\n : Response.json({ success: false, error }, { status });\n\n const contentLength = Number(request.headers.get('content-length') ?? 0);\n if (contentLength > maxBodyBytes) {\n return respondError('Request too large.', 413);\n }\n\n if (allowedOrigin) {\n const requestOrigin = request.headers.get('origin');\n if (requestOrigin && requestOrigin !== allowedOrigin) {\n return respondError('Origin not allowed.', 403);\n }\n }\n\n let body: Record<string, unknown>;\n try {\n if (isFormPost) {\n const formData = await request.formData();\n body = {};\n for (const [key, value] of formData.entries()) {\n if (typeof value === 'string') body[key] = value;\n }\n } else {\n // Not just `application/json`: `navigator.sendBeacon` sends a bare\n // string as `text/plain`, and this must keep accepting that body.\n const parsed: unknown = await request.json();\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return respondError('Malformed request.', 400);\n }\n body = parsed as Record<string, unknown>;\n }\n } catch {\n return respondError('Malformed request.', 400);\n }\n\n const ip =\n request.headers.get('cf-connecting-ip') ??\n request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??\n undefined;\n\n if (rateLimit && ip) {\n const sinceLastHit = await rateLimit.store.hit(ip, now());\n if (sinceLastHit !== null && sinceLastHit < rateLimit.windowMs) {\n return respondError('Too many requests.', 429);\n }\n }\n\n const isCall = body['event'] === 'call';\n if (isCall && typeof body['phone'] !== 'string') {\n return respondError('Missing phone.', 400);\n }\n\n const spam = !isCall && hasHoneypot(body, honeypotFields);\n\n if (!isCall && !spam && options.turnstile) {\n const {\n secretKey,\n fieldName = 'cf-turnstile-response',\n required = false,\n } = options.turnstile;\n const token = body[fieldName];\n if (typeof token === 'string' && token) {\n const verification = await verifyTurnstileToken(token, secretKey, ip);\n if (!verification.success) return respondError('Verification failed.', 400);\n } else if (required) {\n return respondError('Verification required.', 400);\n }\n }\n\n const refusal = !spam && validate?.(body);\n if (refusal) return respondError(refusal, 400);\n\n const respondSuccess = (): Response =>\n isCall\n ? new Response(null, { status: 204 })\n : isFormPost && successRedirect\n ? redirectTo(successRedirect)\n : Response.json({ success: true });\n\n // A honeypot trip never reaches `notify()` — the response is identical to a\n // real success, so a bot gets no signal that it was caught.\n if (spam) {\n onResult?.({\n results: [{ channel: 'email', sent: false, reason: 'Skipped: honeypot triggered.' }],\n delivered: false,\n });\n return respondSuccess();\n }\n\n const turnstileFieldName = options.turnstile?.fieldName;\n const excludedFields = turnstileFieldName\n ? [...honeypotFields, turnstileFieldName]\n : honeypotFields;\n\n const event: ConversionEvent = {\n type: isCall ? 'call' : 'form',\n ...(isCall\n ? { phone: String(body['phone']).replace(/^tel:/, '') }\n : { formData: toFormData(body, excludedFields) }),\n tracking: parseTrackingCookie(request.headers.get('cookie')),\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip,\n at: now(),\n };\n\n const result = await notify(event, context, { email: binding?.(locals) });\n\n if (onResult) onResult(result);\n else\n for (const r of result.results) {\n if (!r.sent) console.warn(`[vitops] notification not sent (${r.channel}): ${r.reason}`);\n }\n\n return respondSuccess();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAM,uBAAN,MAAqD;CACnD,AAAQ,0BAAU,IAAI,IAAoB;CAC1C,IAAI,IAAY,IAA2B;EACzC,MAAM,OAAO,KAAK,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AAQ,CAAC;GAC3D,WAAW,QAAQ,QAAQ,IAAI,YAAY,KAAK;GAChD;GACA,IAAI,IAAI;EAGsB,GAAG,SAAS,EAAE,OAAO,UAAU,MAAM,EAAE,CAAC;EAExE,IAAI,UAAU,SAAS,MAAM;OAE3B,KAAK,MAAM,KAAK,OAAO,SACrB,IAAI,CAAC,EAAE,MAAM,QAAQ,KAAK,mCAAmC,EAAE,QAAQ,KAAK,EAAE,QAAQ;EAG1F,OAAO,eAAe;CACxB;AACF"}
1
+ {"version":3,"file":"conversion.mjs","names":[],"sources":["../../src/routes/conversion.ts"],"sourcesContent":["/**\n * The conversion endpoint, as a factory.\n *\n * A site's contact form and its `tel:`/`mailto:` beacons all mean the same\n * thing — someone got in touch — and all want the same treatment: read the\n * attribution cookie off the request, build the event, notify whoever the\n * config says. That is the same three lines in every project, so it ships\n * here.\n *\n * What deliberately does **not** ship here is field-level validation and business\n * rules — a consumer's form has its own required fields and its own response\n * shape, and baking a guess at those in would make the factory something to\n * fight rather than mount. The handler takes the parsed body and an optional\n * `validate`; that part is the caller's. What **does** ship here is generic abuse\n * resistance (honeypot, origin, rate limit, body size): this is a public,\n * unauthenticated endpoint that sends email, so leaving it wide open makes it a\n * relay and a cost amplifier regardless of whose form is behind it.\n *\n * The path matters: the capture script beacons `tel:`/`mailto:` conversions at\n * `TRACKING_ENDPOINT` (`/api/track`, exported from `@getvitops/astro/tracking`),\n * and the integration warns at build if no route answers it.\n *\n * ```ts\n * // src/pages/api/track.ts\n * export const prerender = false;\n * import { env } from 'cloudflare:workers';\n * import { createConversionRoute } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: {\n * // A bare address is shorthand for `{ provider: 'cloudflare', to }`.\n * notifications: { email: 'sales@acme.ca' },\n * canonical: 'https://acme.ca',\n * organizationName: 'Acme',\n * },\n * binding: () => env.EMAIL,\n * // A no-JS <form method=\"post\"> submission never sees a JSON response body —\n * // it's a full navigation, so send it somewhere real.\n * redirectTo: '/thanks',\n * });\n * ```\n *\n * Cloudflare Turnstile is a separate, opt-in layer on top of the checks above —\n * pass `turnstile: { secretKey }` and a submission carrying a\n * `cf-turnstile-response` token gets it verified server-side via\n * `verifyTurnstileToken` (`@getvitops/utils/security`). The widget itself is the\n * consumer's own markup (`<script src=\"https://challenges.cloudflare.com/\n * turnstile/v0/api.js\" async defer></script>` + `<div class=\"cf-turnstile\"\n * data-sitekey=\"…\">` on their form) — there is no `FormRenderer` for this to hook\n * into generically, matching how the rest of the form is already hand-written.\n * `site.security.turnstile.siteKey` is what the generated privacy policy reads to\n * name Turnstile as a processor; wiring this option up is what makes that true\n * rather than an assertion nothing checks.\n *\n * Two things this example used to get wrong, both of which cost a consumer real\n * time. It read the binding off `locals.runtime.env`, which Astro removed in v6\n * — and because the resulting throw precedes the response, Astro re-reads the\n * request and reports a misleading \"Body has already been used\" instead of the\n * actual error. This package peers on `astro >= 7`, so that form could not work\n * for any supported consumer; `import { env } from 'cloudflare:workers'` is the\n * current one. It also called a `toNotifyContext(config)` helper that used to\n * not exist — `context` can now be built with `toNotifyContext(config)` (also\n * exported from this module), rather than every consumer hand-writing a\n * `NotifyContext` literal:\n *\n * ```ts\n * import config from '../../site.json' with { type: 'json' };\n * import { createConversionRoute, toNotifyContext, toCrmConfig } from '@getvitops/astro/routes';\n *\n * export const POST = createConversionRoute({\n * context: toNotifyContext(config),\n * crm: toCrmConfig(config) && { config: toCrmConfig(config)!, credentials: () => ({ ... }) },\n * binding: () => env.EMAIL,\n * redirectTo: '/thanks',\n * });\n * ```\n */\nimport { AD_PLATFORMS, normalizeConversionActionIds } from '@getvitops/utils/ads';\nimport type { AdPropertySetup } from '@getvitops/utils/ads';\nimport { deliverToCrm, describeCrmResult } from '@getvitops/utils/crm';\nimport type { CrmConfig, CrmCredentials, CrmResult } from '@getvitops/utils/crm';\nimport {\n describeGoogleAdsOfflineResult,\n type EmailBinding,\n notify,\n type NotifyContext,\n uploadClickConversion,\n type GoogleAdsCredentials,\n type GoogleAdsUploadResult,\n} from '@getvitops/utils/notify';\nimport { verifyTurnstileToken } from '@getvitops/utils/security';\nimport { parseTrackingCookie, readCookie } from '@getvitops/utils/tracking';\nimport type { ConversionEvent, TrackingData } from '@getvitops/utils/tracking';\nexport {\n resolveOrganizationName,\n toCrmConfig,\n toGoogleAdsConfig,\n toNotifyContext,\n} from './config-adapters.ts';\n\n/** The subset of Astro's `APIContext` this needs — typed structurally so the\n * factory does not pin an Astro version. */\nexport interface ConversionRequestContext {\n request: Request;\n locals?: unknown;\n}\n\n/**\n * Records a hit for `id` at time `at` (ms) and returns the ms since the previous\n * hit for that `id`, or `null` if this is the first. Pure interface — a store\n * decides nothing, it only remembers.\n */\nexport interface RateLimitStore {\n hit(id: string, at: number): Promise<number | null> | number | null;\n}\n\n/**\n * Per-isolate, in-memory default. Good enough for a single Worker instance\n * fielding occasional contact-form spam; not durable across a fleet, and not\n * shared with other routes. Inject a KV- or Durable-Object-backed `store` for\n * real cross-instance limiting — the interface is one method wide on purpose.\n */\nclass MemoryRateLimitStore implements RateLimitStore {\n private lastHit = new Map<string, number>();\n hit(id: string, at: number): number | null {\n const prev = this.lastHit.get(id);\n this.lastHit.set(id, at);\n return prev === undefined ? null : at - prev;\n }\n}\n\nexport interface ConversionRouteOptions {\n /** Where notifications go. Build it from your site config. */\n context: NotifyContext;\n /**\n * The Workers `send_email` binding for this request, e.g. `() => env.EMAIL`\n * with `env` imported from `cloudflare:workers`. Omit it in dev and the\n * notification is printed instead of sent.\n *\n * Not `(locals) => locals.runtime.env.EMAIL` — Astro removed `locals.runtime`\n * in v6, and this package peers on `>= 7`.\n */\n binding?: (locals: unknown) => EmailBinding | undefined;\n /**\n * Push the submission into a CRM (HubSpot, Zoho Bigin or Jobber) before notifying.\n * Credentials arrive as a function of `locals`, exactly like `binding` above\n * — the consumer reads them from `import { env } from 'cloudflare:workers'`.\n * Credentials are never config; that rule is absolute in this toolchain.\n *\n * A failed CRM write never fails the request and never blocks the honeypot/\n * Turnstile gates above it — those run first, so a bot never reaches the\n * CRM. The outcome is folded into the notification email's \"Delivery\"\n * section (via `describeCrmResult`) so a failed write is never silent.\n */\n crm?: {\n config: CrmConfig;\n credentials?: (locals: unknown) => CrmCredentials | undefined;\n fetch?: typeof fetch;\n timeoutMs?: number;\n };\n /**\n * Upload the conversion to Google Ads server-side instead of relying on the\n * visitor's browser to fire `gtag.js` — see `site.ads.google.reporting` and\n * `conversionActionId`. Credentials arrive as a function of `locals`, same\n * shape as `crm.credentials` and `binding` above.\n *\n * Only fires for an action whose `conversionActionId` is actually set (via\n * `toGoogleAdsConfig(config)`, or hand-built the same shape) **and** whose\n * event carries a Google click id (`gclid`/`gbraid`/`wbraid` on `_ac`) —\n * an organic conversion has nothing for the Ads API to attribute, so it's\n * silently skipped rather than reported as a failure. A failed upload never\n * fails the request, matching `crm` above; the outcome folds into the same\n * \"Delivery\" section via `describeGoogleAdsOfflineResult`.\n */\n googleAdsOffline?: {\n config: Pick<AdPropertySetup, 'accountId' | 'conversionActionId' | 'reporting'>;\n credentials?: (locals: unknown) => GoogleAdsCredentials | undefined;\n fetch?: typeof fetch;\n };\n /**\n * Reject a submission before anything is sent. Return a message to refuse.\n * This is where a consumer puts required-field checks.\n */\n validate?: (body: Record<string, unknown>) => string | null;\n /** Called with every channel outcome, delivered or not, plus the CRM\n * outcome when `crm` is configured. Defaults to console. */\n onResult?: (result: ConversionResult) => void;\n /** Injected in tests. */\n now?: () => number;\n /**\n * Where to send a no-JS `<form method=\"post\">` submission on success. Without\n * this, that visitor's browser navigates to the raw `{\"success\":true}` JSON\n * body as its next page — functional, but not a page anyone should see. Has\n * no effect on the beacon/fetch (JSON) path, which always gets a JSON response.\n */\n redirectTo?: string;\n /**\n * Where to send a refused no-JS submission (validation, spam checks, malformed\n * body). Falls back to `redirectTo` if omitted, and to the JSON error response\n * if neither is set.\n */\n errorRedirectTo?: string;\n /**\n * Field names treated as honeypots: a bot fills every input it finds, a person\n * never sees these (hidden by CSS in the form markup). A non-empty value is\n * silently treated as spam — the response looks identical to a real success,\n * denying the bot the signal it needs to know the trick worked, but nothing is\n * notified and the field never reaches `notify()`. Defaults to the same names\n * `render.ts`'s `OMIT_FIELDS` already knows about (`website`, `_honeypot`,\n * `honeypot`), so the two lists don't need to be kept in sync by hand.\n */\n honeypotFields?: string[];\n /**\n * Reject a submission whose `Content-Length` exceeds this many bytes. Default\n * 25_000 — generous for a contact form with no file upload, tiny for anything\n * meant to relay large payloads. The header is only a fast path: a chunked\n * request carries none, so the body is also read through a byte-capped\n * reader and refused the moment it passes the cap.\n */\n maxBodyBytes?: number;\n /**\n * Fall back to the first `X-Forwarded-For` hop as the client IP when\n * `CF-Connecting-IP` is absent. Default `false`: off Cloudflare the header is\n * whatever the client sent, so honouring it lets a script mint a fresh\n * rate-limit bucket per request. Turn on only behind a proxy that overwrites\n * it. With neither header trusted there is no IP, and rate limiting is skipped.\n */\n trustForwardedFor?: boolean;\n /**\n * Reject a submission whose `Origin` header doesn't match this origin.\n * Defaults to `context.canonical`'s origin. Pass `false` to disable.\n *\n * Best-effort, not a CSRF guard: browsers omit `Origin` on plenty of\n * legitimate same-origin requests, so its *absence* is never treated as a\n * mismatch — only a present-and-different value is rejected. That still stops\n * the common case (a script hitting the endpoint directly from elsewhere)\n * without breaking real submissions from older or privacy-hardened browsers.\n */\n allowedOrigin?: string | false;\n /**\n * Minimum interval between accepted submissions from the same IP. Pass\n * `false` to disable. `windowMs` defaults to 10 seconds — enough to blunt a\n * script firing in a loop without troubling someone who fat-fingers a form\n * and resubmits.\n */\n rateLimit?: { windowMs?: number; store?: RateLimitStore } | false;\n /**\n * Verify a Cloudflare Turnstile token server-side. The **secret** key —\n * unlike `site.security.turnstile.siteKey`, which is public config — must come\n * from an env var, never a config file (the same rule as every other\n * credential in this toolchain).\n */\n turnstile?: {\n secretKey: string;\n /** The submitted field carrying the token. Default `cf-turnstile-response`\n * — the name Cloudflare's widget submits under. */\n fieldName?: string;\n /**\n * Reject a submission with no token at all, rather than only a present-and-\n * invalid one. Default `false`: an absent token is the ordinary shape of a\n * visitor with JS disabled, and this factory is built around that path\n * staying usable. Set `true` only for a form where verified-human matters\n * enough to accept that trade-off — doing so means that form no longer\n * works without JS, on purpose.\n */\n required?: boolean;\n };\n}\n\n/** `notify()`'s own result, plus the CRM and Google Ads offline-upload\n * outcomes when those are configured. Additive over\n * `Awaited<ReturnType<typeof notify>>` — a consumer's existing `onResult`\n * reading `.results`/`.delivered` keeps compiling unchanged. */\nexport interface ConversionResult extends Awaited<ReturnType<typeof notify>> {\n crm?: CrmResult | undefined;\n googleAds?: GoogleAdsUploadResult | undefined;\n}\n\n/** The click id to report to Google Ads, checked in the same order as\n * `AD_PLATFORMS.google.clickIdParams` rather than `getPrimaryClickId()` —\n * that helper returns whichever platform's click id happens to appear first\n * in the *cross-platform* precedence table, which may not be Google's even\n * when a `gclid` is present. */\nfunction googleClickId(tracking: TrackingData | null): { param: string; value: string } | null {\n if (!tracking) return null;\n for (const param of AD_PLATFORMS.google.clickIdParams) {\n const value = tracking[param];\n if (value) return { param, value: String(value) };\n }\n return null;\n}\n\n/** Fields that are never part of a submission's meaning. `cf-turnstile-response`\n * is excluded unconditionally, matching `render.ts`'s `OMIT_FIELDS` — the field\n * carries a verification token, not something the visitor wrote. */\nconst CONTROL_FIELDS = new Set(['event', 'phone', 'cf-turnstile-response']);\n/** The capture script sends `link.href` as-is: `tel:` + digits and the punctuation people type\n * (a space arrives as `%20`). Not free text. */\nconst PHONE_RE = /^(?:tel:)?\\+?[\\d\\s().%-]{3,40}$/i;\n/** `mailto:` + an address, with an optional `?subject=…` query. A shape check, not deliverability. */\nconst EMAIL_RE = /^(?:mailto:)?[^\\s@<>\"?]{1,64}@[^\\s@<>\"?]{1,255}(?:\\?[^\\s<>\"]{0,256})?$/i;\n\nconst DEFAULT_HONEYPOT_FIELDS = ['website', '_honeypot', 'honeypot'];\nconst DEFAULT_MAX_BODY_BYTES = 25_000;\n\n/**\n * Read a request body, giving up as soon as it exceeds `max` bytes. Returns `null` when over\n * the cap. `Content-Length` is optional on chunked requests, so it cannot be the only guard.\n */\nasync function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer> | null> {\n if (!request.body) return new Uint8Array();\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > max) {\n await reader.cancel();\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\nconst DEFAULT_RATE_LIMIT_WINDOW_MS = 10_000;\n\nfunction toFormData(\n body: Record<string, unknown>,\n honeypotFields: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(body)) {\n if (CONTROL_FIELDS.has(key) || honeypotFields.includes(key)) continue;\n if (value === undefined || value === null) continue;\n out[key] = String(value);\n }\n return out;\n}\n\nfunction hasHoneypot(body: Record<string, unknown>, honeypotFields: string[]): boolean {\n return honeypotFields.some((field) => {\n const value = body[field];\n return typeof value === 'string' && value.trim() !== '';\n });\n}\n\nfunction originOf(url: string | undefined): string | null {\n if (!url) return null;\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n}\n\n/** A `Location` header response — used for the no-JS form path instead of\n * `Response.redirect()`, which requires a base URL this factory doesn't have. */\nfunction redirectTo(location: string, status = 303): Response {\n return new Response(null, { status, headers: { Location: location } });\n}\n\n/**\n * Build a POST handler for conversions.\n *\n * Returns 204 for a beacon and 200 with `{ success }` for a JSON (fetch-based)\n * form submission, matching what `navigator.sendBeacon` and a fetch-submitting\n * form each expect. A no-JS `<form method=\"post\">` — `application/\n * x-www-form-urlencoded` or `multipart/form-data` — is parsed the same way and,\n * on success, redirected to `redirectTo` if one is configured.\n *\n * **A failed notification does not fail the request.** The visitor has already\n * submitted; refusing them because our mail did not go out turns a lost\n * notification into a lost conversion. Failures are reported through `onResult`.\n */\nexport function createConversionRoute(options: ConversionRouteOptions) {\n const {\n context,\n binding,\n validate,\n onResult,\n now = Date.now,\n redirectTo: successRedirect,\n errorRedirectTo = successRedirect,\n honeypotFields = DEFAULT_HONEYPOT_FIELDS,\n maxBodyBytes = DEFAULT_MAX_BODY_BYTES,\n trustForwardedFor = false,\n } = options;\n\n const allowedOrigin =\n options.allowedOrigin === false ? null : (options.allowedOrigin ?? originOf(context.canonical));\n\n const rateLimit =\n options.rateLimit === false\n ? null\n : {\n windowMs: options.rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS,\n store: options.rateLimit?.store ?? new MemoryRateLimitStore(),\n };\n\n return async ({ request, locals }: ConversionRequestContext): Promise<Response> => {\n const contentType = request.headers.get('content-type') ?? '';\n const isFormPost =\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded');\n\n const respondError = (error: string, status: number): Response =>\n isFormPost && errorRedirectTo\n ? redirectTo(errorRedirectTo)\n : Response.json({ success: false, error }, { status });\n\n const contentLength = Number(request.headers.get('content-length') ?? 0);\n if (contentLength > maxBodyBytes) {\n return respondError('Request too large.', 413);\n }\n\n if (allowedOrigin) {\n const requestOrigin = request.headers.get('origin');\n if (requestOrigin && requestOrigin !== allowedOrigin) {\n return respondError('Origin not allowed.', 403);\n }\n }\n\n // A chunked request has no Content-Length to check above, so cap the stream itself.\n const bytes = await readCapped(request, maxBodyBytes);\n if (!bytes) return respondError('Request too large.', 413);\n\n let body: Record<string, unknown>;\n try {\n if (isFormPost) {\n const formData = await new Response(bytes, {\n headers: { 'content-type': contentType },\n }).formData();\n body = {};\n for (const [key, value] of formData.entries()) {\n if (typeof value === 'string') body[key] = value;\n }\n } else {\n // Not just `application/json`: `navigator.sendBeacon` sends a bare\n // string as `text/plain`, and this must keep accepting that body.\n const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return respondError('Malformed request.', 400);\n }\n body = parsed as Record<string, unknown>;\n }\n } catch {\n return respondError('Malformed request.', 400);\n }\n\n const ip =\n request.headers.get('cf-connecting-ip') ??\n (trustForwardedFor ? request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() : null) ??\n undefined;\n\n // Classified before rate limiting, not read raw off the client — see the key\n // below. `phone`/`email` presence is still checked after limiting, since that\n // check just rejects a malformed beacon rather than deciding the bucket.\n const isCall = body['event'] === 'call';\n const isEmailClick = body['event'] === 'email';\n\n // Keyed on IP *and* the server's own classification (`call` | `email` |\n // `form`), never the raw `event` string the client sent. A call beacon and an\n // email-click beacon from the same visitor are two distinct, legitimate\n // conversions, not a repeat of one, so they need separate buckets — but\n // trusting the raw string for that also let a client dodge the form rate\n // limit entirely by varying `event` on every request (any value other than\n // exactly `'call'`/`'email'` used to get its own bucket). Collapsing\n // everything else to `'form'` closes that without losing the call/email split.\n if (rateLimit && ip) {\n const rlKey = `${ip}:${isCall ? 'call' : isEmailClick ? 'email' : 'form'}`;\n const sinceLastHit = await rateLimit.store.hit(rlKey, now());\n if (sinceLastHit !== null && sinceLastHit < rateLimit.windowMs) {\n return respondError('Too many requests.', 429);\n }\n }\n\n // A beacon skips every form check, so its one payload field is format-checked instead:\n // the value is interpolated into a notification someone reads, and an unauthenticated\n // caller should not be able to put arbitrary text there.\n if (isCall && !(typeof body['phone'] === 'string' && PHONE_RE.test(body['phone']))) {\n return respondError('Missing phone.', 400);\n }\n\n if (isEmailClick && !(typeof body['email'] === 'string' && EMAIL_RE.test(body['email']))) {\n return respondError('Missing email.', 400);\n }\n\n // A call and an email-click beacon are the same shape of thing: a fire-and-\n // forget ping with no form fields to validate, honeypot, verify or map into\n // a CRM — both skip every check below that exists for a form submission.\n const isBeacon = isCall || isEmailClick;\n\n const spam = !isBeacon && hasHoneypot(body, honeypotFields);\n\n if (!isBeacon && !spam && options.turnstile) {\n const {\n secretKey,\n fieldName = 'cf-turnstile-response',\n required = false,\n } = options.turnstile;\n const token = body[fieldName];\n if (typeof token === 'string' && token) {\n const verification = await verifyTurnstileToken(token, secretKey, ip);\n if (!verification.success) return respondError('Verification failed.', 400);\n } else if (required) {\n return respondError('Verification required.', 400);\n }\n }\n\n const refusal = !spam && validate?.(body);\n if (refusal) return respondError(refusal, 400);\n\n const respondSuccess = (): Response =>\n isBeacon\n ? new Response(null, { status: 204 })\n : isFormPost && successRedirect\n ? redirectTo(successRedirect)\n : Response.json({ success: true });\n\n // A honeypot trip never reaches `notify()` — the response is identical to a\n // real success, so a bot gets no signal that it was caught.\n if (spam) {\n onResult?.({\n results: [{ channel: 'email', sent: false, reason: 'Skipped: honeypot triggered.' }],\n delivered: false,\n });\n return respondSuccess();\n }\n\n const turnstileFieldName = options.turnstile?.fieldName;\n const excludedFields = turnstileFieldName\n ? [...honeypotFields, turnstileFieldName]\n : honeypotFields;\n\n const event: ConversionEvent = {\n type: isCall ? 'call' : isEmailClick ? 'email' : 'form',\n ...(isCall\n ? { phone: String(body['phone']).replace(/^tel:/, '') }\n : isEmailClick\n ? { email: String(body['email']).replace(/^mailto:/, '') }\n : { formData: toFormData(body, excludedFields) }),\n tracking: parseTrackingCookie(request.headers.get('cookie')),\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip,\n at: now(),\n };\n\n // CRM before notify: the notification email states the CRM outcome, which\n // is only possible once it's known. Never attempted for a `tel:`/`mailto:`\n // beacon — a CRM contact comes from submitted form fields, and neither\n // event has any to map.\n let crmResult: CrmResult | null = null;\n if (!isBeacon && options.crm) {\n crmResult = await deliverToCrm(event, options.crm.config, {\n credentials: options.crm.credentials?.(locals),\n fetch: options.crm.fetch,\n timeoutMs: options.crm.timeoutMs,\n // Provider-neutral: HubSpot reads `hutk` to stitch the submission to\n // its own tracking; Jobber reads `pageUri` for its note body. Neither\n // is HubSpot-specific to build, so this is passed unconditionally\n // rather than gated on `options.crm.config.provider`.\n pageContext: {\n hutk: readCookie(request.headers.get('cookie'), 'hubspotutk') ?? undefined,\n pageUri: request.headers.get('referer') ?? undefined,\n },\n });\n }\n const crmNote = describeCrmResult(crmResult);\n\n // Unlike CRM, this runs for a `tel:`/`mailto:` beacon too — those are\n // exactly the actions the client-side gtag handler would otherwise fire\n // for. Skipped, not failed, when there's no click id to attribute, no\n // `conversionActionId` configured for this action, or no credentials for\n // this environment (e.g. local dev) — none of those is a real failure.\n let googleAdsResult: GoogleAdsUploadResult | null = null;\n const adsCfg = options.googleAdsOffline?.config;\n if (adsCfg?.reporting === 'server' && adsCfg.accountId) {\n const actionId = normalizeConversionActionIds(adsCfg.conversionActionId)[event.type];\n const clickId = googleClickId(event.tracking);\n const credentials = options.googleAdsOffline?.credentials?.(locals);\n if (actionId && clickId && credentials) {\n googleAdsResult = await uploadClickConversion(\n { customerId: adsCfg.accountId, conversionActionId: actionId, clickId, at: event.at },\n credentials,\n options.googleAdsOffline?.fetch,\n );\n }\n }\n const googleAdsNote = describeGoogleAdsOfflineResult(googleAdsResult);\n\n const result: ConversionResult = {\n ...(await notify(\n event,\n context,\n { email: binding?.(locals) },\n {\n notes: [crmNote, googleAdsNote].filter((n): n is string => n != null),\n },\n )),\n ...(crmResult ? { crm: crmResult } : {}),\n ...(googleAdsResult ? { googleAds: googleAdsResult } : {}),\n };\n\n if (onResult) onResult(result);\n else {\n for (const r of result.results) {\n if (!r.sent) console.warn(`[vitops] notification not sent (${r.channel}): ${r.reason}`);\n }\n if (crmResult && !crmResult.ok) {\n console.warn(\n `[vitops] CRM write not delivered (${crmResult.provider}): ${crmResult.reason}`,\n );\n }\n if (googleAdsResult && !googleAdsResult.ok) {\n console.warn(`[vitops] Google Ads offline upload not delivered: ${googleAdsResult.reason}`);\n }\n }\n\n return respondSuccess();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HA,IAAM,uBAAN,MAAqD;CACnD,AAAQ,0BAAU,IAAI,IAAoB;CAC1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AAU,IAAI,CAAC;GACtC,GAAI,kBAAkB,EAAE,WAAW,gBAAgB,IAAI,CAAC;EAC1D;EAEA,IAAI,UAAU,SAAS,MAAM;OACxB;GACH,KAAK,MAAM,KAAK,OAAO,SACrB,IAAI,CAAC,EAAE,MAAM,QAAQ,KAAK,mCAAmC,EAAE,QAAQ,KAAK,EAAE,QAAQ;GAExF,IAAI,aAAa,CAAC,UAAU,IAC1B,QAAQ,KACN,qCAAqC,UAAU,SAAS,KAAK,UAAU,QACzE;GAEF,IAAI,mBAAmB,CAAC,gBAAgB,IACtC,QAAQ,KAAK,qDAAqD,gBAAgB,QAAQ;EAE9F;EAEA,OAAO,eAAe;CACxB;AACF"}
@@ -1,8 +1,8 @@
1
- //#region src/tracking.ts
1
+ // src/tracking.ts
2
2
  /** The cookie the capture script writes. Mirrors `TRACKING_COOKIE` in utils. */
3
3
  const TRACKING_COOKIE = "_ac";
4
4
  /**
5
- * Where the capture script sends its `tel:` conversion beacon.
5
+ * Where the capture script sends its `tel:`/`mailto:` conversion beacons.
6
6
  *
7
7
  * The route itself is the consumer's to write (`createConversionRoute()` in
8
8
  * `@getvitops/astro/routes`), so this is the one place the two halves agree on
@@ -42,6 +42,5 @@ function resolveTracking(opts, ctx = {}) {
42
42
  };
43
43
  }
44
44
 
45
- //#endregion
46
45
  export { TRACKING_ENDPOINT as n, resolveTracking as r, TRACKING_COOKIE as t };
47
- //# sourceMappingURL=tracking-CmSfxWC3.mjs.map
46
+ //# sourceMappingURL=tracking-Cb3A0BrC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracking-Cb3A0BrC.mjs","names":[],"sources":["../src/tracking.ts"],"sourcesContent":["/**\n * The `<Tracking />` resolution layer — tracking config in, what to emit out.\n *\n * Separate from `Tracking.astro` for the same reason `analytics.ts` is separate\n * from `Analytics.astro`: everything decidable is a pure function asserted in\n * `tracking.test.ts`, and the component only renders what this returns.\n *\n * The one decision here is **which consent category the `_ac` cookie waits on**,\n * and it is stated rather than inferred. `_ac` is a 90-day identifier tying a\n * visitor to the ad that brought them, so `marketing` is the default — but a site\n * using click IDs purely for its own campaign reporting may reasonably file it\n * under `analytics`, and that is the consumer's call to make, not ours to guess.\n */\n\nimport type { TrackingConfig } from '@getvitops/config';\n\n/** Which consent category the attribution cookie waits on. */\nexport type TrackingCategory = NonNullable<TrackingConfig['category']>;\n\n/** The `site.tracking` block — the schema's own type from `@getvitops/config`, not a copy. */\nexport type GetvitopsTrackingOptions = TrackingConfig;\n\n/** The cookie the capture script writes. Mirrors `TRACKING_COOKIE` in utils. */\nexport const TRACKING_COOKIE = '_ac';\n\n/**\n * Where the capture script sends its `tel:`/`mailto:` conversion beacons.\n *\n * The route itself is the consumer's to write (`createConversionRoute()` in\n * `@getvitops/astro/routes`), so this is the one place the two halves agree on\n * a path. It was a bare literal inside the inlined script: a consumer who named\n * the file anything else got a silent 404 on every beacon and lost conversions\n * with no error anywhere to explain it. Exported so a consumer can assert\n * against it, mirrored in `scripts/tracking.ts` because that file is inlined\n * into the document and cannot import, and pinned by `tracking.test.ts`.\n */\nexport const TRACKING_ENDPOINT = '/api/track';\n\nexport interface ResolvedTracking {\n enabled: boolean;\n category: TrackingCategory;\n /** Cookie names to clear on revoke — rides on `data-consent-cookies`. */\n cookies: string[];\n /** Configuration problems, as prose. The integration logs these. */\n warnings: string[];\n}\n\nexport interface ResolveTrackingContext {\n /** Is the consent gate enabled on this site (`vitops({ consent })`)? */\n consent?: boolean;\n /** Categories the banner offers, so we can catch a demand with no row. */\n consentCategories?: readonly string[];\n}\n\n/**\n * Resolve the tracking config into what the component emits.\n *\n * Two warnings, both about the same failure — a persistent identifier written\n * with no way for the visitor to decline, or a permission asked for with no way\n * to answer. Returned as data rather than logged here so the check is a test\n * rather than a line someone might scroll past, exactly as `resolveAnalytics`\n * does.\n */\nexport function resolveTracking(\n opts: GetvitopsTrackingOptions | undefined,\n ctx: ResolveTrackingContext = {},\n): ResolvedTracking {\n const warnings: string[] = [];\n const category: TrackingCategory = opts?.category ?? 'marketing';\n const enabled = opts?.enabled === true;\n\n if (!enabled) return { enabled: false, category, cookies: [], warnings };\n\n if (!ctx.consent) {\n warnings.push(\n `tracking is on, so this site writes the \\`${TRACKING_COOKIE}\\` cookie — a 90-day ` +\n 'identifier tying a visitor to the ad that brought them — and `consent` is off, so it ' +\n 'is written for every visitor with no way to decline. Set `consent: true`.',\n );\n } else if (ctx.consentCategories && !ctx.consentCategories.includes(category)) {\n // The banner would be raised for a category it renders no row for: the\n // visitor is asked a question the form does not show them.\n warnings.push(\n `tracking demands the \\`${category}\\` consent category, but the banner offers ` +\n `${ctx.consentCategories.join(', ') || 'nothing'}. Add \\`${category}\\` to ` +\n '`consent.categories`, or the visitor is asked about something the banner never names.',\n );\n }\n\n return { enabled, category, cookies: [TRACKING_COOKIE], warnings };\n}\n"],"mappings":";;AAuBA,MAAa,kBAAkB;;;;;;;;;;;;AAa/B,MAAa,oBAAoB;;;;;;;;;;AA2BjC,SAAgB,gBACd,MACA,MAA8B,CAAC,GACb;CAClB,MAAM,WAAqB,CAAC;CAC5B,MAAM,WAA6B,MAAM,YAAY;CACrD,MAAM,UAAU,MAAM,YAAY;CAElC,IAAI,CAAC,SAAS,OAAO;EAAE,SAAS;EAAO;EAAU,SAAS,CAAC;EAAG;CAAS;CAEvE,IAAI,CAAC,IAAI,SACP,SAAS,KACP,mDAA6D,wLAG/D;MACK,IAAI,IAAI,qBAAqB,CAAC,IAAI,kBAAkB,SAAS,QAAQ,GAG1E,SAAS,KACP,0BAA0B,SAAS,6CAC9B,IAAI,kBAAkB,KAAK,IAAI,KAAK,UAAU,UAAU,SAAS,8FAExE;CAGF,OAAO;EAAE;EAAS;EAAU,SAAS,MAAgB;EAAG;CAAS;AACnE"}
@@ -1,31 +1,12 @@
1
- //#region src/tracking.d.ts
2
- /**
3
- * The `<Tracking />` resolution layer — tracking config in, what to emit out.
4
- *
5
- * Separate from `Tracking.astro` for the same reason `analytics.ts` is separate
6
- * from `Analytics.astro`: everything decidable is a pure function asserted in
7
- * `tracking.test.ts`, and the component only renders what this returns.
8
- *
9
- * The one decision here is **which consent category the `_ac` cookie waits on**,
10
- * and it is stated rather than inferred. `_ac` is a 90-day identifier tying a
11
- * visitor to the ad that brought them, so `marketing` is the default — but a site
12
- * using click IDs purely for its own campaign reporting may reasonably file it
13
- * under `analytics`, and that is the consumer's call to make, not ours to guess.
14
- */
1
+ import { TrackingConfig } from "@getvitops/config";
15
2
  /** Which consent category the attribution cookie waits on. */
16
- type TrackingCategory = 'marketing' | 'analytics';
17
- interface GetvitopsTrackingOptions {
18
- /** Capture ad click IDs and UTMs into `_ac`. */
19
- enabled?: boolean;
20
- /** Default `marketing`. */
21
- category?: TrackingCategory;
22
- /** Informational; capture recognises every known click-ID parameter regardless. */
23
- platforms?: string[];
24
- }
3
+ type TrackingCategory = NonNullable<TrackingConfig['category']>;
4
+ /** The `site.tracking` block — the schema's own type from `@getvitops/config`, not a copy. */
5
+ type GetvitopsTrackingOptions = TrackingConfig;
25
6
  /** The cookie the capture script writes. Mirrors `TRACKING_COOKIE` in utils. */
26
7
  declare const TRACKING_COOKIE = "_ac";
27
8
  /**
28
- * Where the capture script sends its `tel:` conversion beacon.
9
+ * Where the capture script sends its `tel:`/`mailto:` conversion beacons.
29
10
  *
30
11
  * The route itself is the consumer's to write (`createConversionRoute()` in
31
12
  * `@getvitops/astro/routes`), so this is the one place the two halves agree on
@@ -60,6 +41,5 @@ interface ResolveTrackingContext {
60
41
  * does.
61
42
  */
62
43
  declare function resolveTracking(opts: GetvitopsTrackingOptions | undefined, ctx?: ResolveTrackingContext): ResolvedTracking;
63
- //#endregion
64
44
  export { TRACKING_ENDPOINT as a, TRACKING_COOKIE as i, ResolveTrackingContext as n, TrackingCategory as o, ResolvedTracking as r, resolveTracking as s, GetvitopsTrackingOptions as t };
65
- //# sourceMappingURL=tracking-DdEKExlE.d.mts.map
45
+ //# sourceMappingURL=tracking-D2xOzjFD.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracking-D2xOzjFD.d.mts","names":[],"sources":["../src/tracking.ts"],"mappings":";;KAiBY,mBAAmB,YAAY;;KAG/B,2BAA2B;;cAG1B;;;;;;;;;;;;cAaA;UAEI;EACf;EACA,UAAU;;EAEV;;EAEA;;UAGe;;EAEf;;EAEA;;;;;;;;;;;iBAYc,gBACd,MAAM,sCACN,MAAK,yBACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getvitops/astro",
3
- "version": "8.1.0",
3
+ "version": "8.2.0",
4
4
  "description": "Astro integration for the Vitops design system — favicons/PWA, web-component scripts, and CSS, via a getvitops() integration + <Head /> component.",
5
5
  "homepage": "https://docs.vitops.ca",
6
6
  "bugs": "https://github.com/getvitops/design-system/issues",
@@ -64,6 +64,10 @@
64
64
  "types": "./dist/exports/tracking.d.mts",
65
65
  "import": "./dist/exports/tracking.mjs"
66
66
  },
67
+ "./middleware": {
68
+ "types": "./dist/middleware.d.mts",
69
+ "import": "./dist/middleware.mjs"
70
+ },
67
71
  "./Head.astro": "./src/components/Head.astro",
68
72
  "./Seo.astro": "./src/components/Seo.astro",
69
73
  "./Analytics.astro": "./src/components/Analytics.astro",
@@ -94,17 +98,17 @@
94
98
  "access": "public"
95
99
  },
96
100
  "dependencies": {
97
- "@getvitops/core": "8.1.0",
98
- "@getvitops/vite": "8.1.0",
99
- "@getvitops/utils": "8.1.0",
100
- "@getvitops/generator": "8.1.0"
101
+ "@getvitops/config": "8.2.0",
102
+ "@getvitops/core": "8.2.0",
103
+ "@getvitops/generator": "8.2.0",
104
+ "@getvitops/utils": "8.2.0",
105
+ "@getvitops/vite": "8.2.0"
101
106
  },
102
107
  "devDependencies": {
103
108
  "@astrojs/sitemap": "^3.7.3",
104
109
  "@tailwindcss/vite": "^4.3.3",
105
- "astro": "^7.1.2",
106
- "tailwindcss": "^4.3.3",
107
- "vitest": "4.1.9"
110
+ "astro": "^7.4.4",
111
+ "tailwindcss": "^4.3.3"
108
112
  },
109
113
  "peerDependencies": {
110
114
  "@astrojs/sitemap": ">=3.6",
package/src/ads.ts CHANGED
@@ -25,25 +25,32 @@
25
25
  * Everything decidable is here and unit-tested; `Ads.astro` renders what this
26
26
  * returns and chooses nothing.
27
27
  */
28
- import { AD_PLATFORMS, AD_PROVIDER_KEYS, type AdProvider } from '@getvitops/utils/ads';
28
+ import {
29
+ AD_PLATFORMS,
30
+ AD_PROVIDER_KEYS,
31
+ normalizeConversionLabels,
32
+ type AdProvider,
33
+ type ConversionLabelMap,
34
+ } from '@getvitops/utils/ads';
35
+ import type { AdPropertyConfig } from '@getvitops/config';
29
36
  import type { AnalyticsStrategy, ConsentCategory, GatedTag } from './analytics.ts';
30
37
 
31
38
  /**
32
- * One ad property, mirroring a `site.ads` entry field for field.
33
- *
34
- * Structural rather than `SiteAdProperty` imported from the generator, matching
35
- * how `GetvitopsSeoOptions` and `GetvitopsTrackingOptions` already work: the
36
- * component surface must stay usable by a consumer who passes a plain object.
39
+ * One ad property, as `<Ads />` reads it: the fields of a `site.ads` entry that decide what is
40
+ * emitted. A subset of `AdPropertyConfig` from `@getvitops/config` — the schema's own inferred
41
+ * type, not a copy — so a plain object is still enough for a consumer to pass, and a field the
42
+ * schema renames fails here instead of silently reading `undefined`.
37
43
  */
38
- export interface GetvitopsAdProperty {
39
- accountId?: string;
40
- pixelId?: string;
41
- conversionLabel?: string;
42
- /** Default `marketing`. `analytics` for a property used purely for measurement. */
43
- category?: 'marketing' | 'analytics';
44
- /** False keeps the property on record without emitting its tag. */
45
- enabled?: boolean;
46
- }
44
+ export type GetvitopsAdProperty = Pick<
45
+ AdPropertyConfig,
46
+ | 'accountId'
47
+ | 'pixelId'
48
+ | 'conversionLabel'
49
+ | 'conversionActionId'
50
+ | 'reporting'
51
+ | 'category'
52
+ | 'enabled'
53
+ >;
47
54
 
48
55
  export type GetvitopsAdsOptions = Partial<Record<AdProvider, GetvitopsAdProperty>>;
49
56
 
@@ -113,6 +120,35 @@ export function resolveAds(
113
120
  continue;
114
121
  }
115
122
 
123
+ // `conversionLabel` lands inside the same inline `<script>` as `id` (Google's
124
+ // bootstrap embeds it to expose a conversion `send_to` target per action) —
125
+ // same injection surface, so every configured label gets the same check.
126
+ // Unlike an invalid `id`, an invalid label doesn't sink the whole tag: it
127
+ // just means that one action's conversion doesn't fire, which is worth a
128
+ // warning rather than dropping every other configured action too.
129
+ let safeEntry = entry;
130
+ const labels = normalizeConversionLabels(entry.conversionLabel);
131
+ const invalidActions = Object.entries(labels)
132
+ .filter(([, label]) => label && !SAFE_ID.test(label))
133
+ .map(([action]) => action);
134
+ if (invalidActions.length) {
135
+ for (const action of invalidActions) {
136
+ warnings.push(
137
+ `ads: ${provider} conversionLabel.${action} "${labels[action as keyof ConversionLabelMap]}" ` +
138
+ 'is not a valid label. Conversion firing skipped for that action.',
139
+ );
140
+ }
141
+ const cleanLabels = Object.fromEntries(
142
+ Object.entries(labels).filter(([action]) => !invalidActions.includes(action)),
143
+ );
144
+ // Omit the key entirely rather than setting it `undefined` —
145
+ // `exactOptionalPropertyTypes` treats the two differently.
146
+ const { conversionLabel: _drop, ...rest } = entry;
147
+ safeEntry = Object.keys(cleanLabels).length
148
+ ? { ...rest, conversionLabel: cleanLabels }
149
+ : rest;
150
+ }
151
+
116
152
  const category: ConsentCategory = entry.category ?? 'marketing';
117
153
  tags.push({
118
154
  key: provider,
@@ -125,7 +161,7 @@ export function resolveAds(
125
161
  cookies: platform.tag.cookies,
126
162
  strategy,
127
163
  gated: ctx.consent === true,
128
- inline: platform.tag.bootstrap(id, { provider, ...entry }),
164
+ inline: platform.tag.bootstrap(id, { provider, ...safeEntry }),
129
165
  src: platform.tag.src ? platform.tag.src(id) : null,
130
166
  attrs: {},
131
167
  });
package/src/analytics.ts CHANGED
@@ -156,6 +156,39 @@ export interface ResolvedAnalytics {
156
156
  export interface ResolveAnalyticsContext {
157
157
  /** Is the consent gate enabled on this site (`vitops({ consent })`)? */
158
158
  consent?: boolean;
159
+ /**
160
+ * Enabled `site.experiments` entries, keyed the same way, each carrying the
161
+ * resolved cookie name `vitopsAbTesting()`'s middleware assigns
162
+ * (`_ab_<key>` unless overridden). When set, each provider's bootstrap
163
+ * reads these cookies client-side and reports the assignment via that
164
+ * provider's own custom-dimension/property mechanism — a no-op when this
165
+ * is empty, so a site not using experiments sees no behavior change.
166
+ */
167
+ experiments?: Record<string, { cookieName: string }>;
168
+ /** `site.analytics.matomo.abVariantDimensions` — Matomo's pre-created custom-dimension index per experiment key. */
169
+ matomoAbVariantDimensions?: Record<string, number>;
170
+ }
171
+
172
+ /**
173
+ * A small inline snippet reading each experiment's cookie into a plain
174
+ * object, skipping any experiment whose cookie isn't set (visitor not yet
175
+ * assigned, or the experiment disabled after this page was cached). Shared
176
+ * across providers so the cookie-parsing logic — and its `SAFE_ID` guard on
177
+ * both the experiment key and cookie name, the same discipline `bad()`
178
+ * already applies to provider IDs landing in an inline `<script>` — exists
179
+ * exactly once.
180
+ */
181
+ function experimentCookieReads(experiments: Record<string, { cookieName: string }>): string {
182
+ const entries = Object.entries(experiments).filter(([key, e]) => !bad(key) && !bad(e.cookieName));
183
+ if (!entries.length) return '';
184
+ return (
185
+ `function _abrc(n){var m=document.cookie.match(new RegExp('(?:^|; )'+n+'=([^;]*)'));return m?decodeURIComponent(m[1]):null;}` +
186
+ `var _ab={};` +
187
+ entries
188
+ .map(([key, e]) => `_ab[${JSON.stringify(key)}]=_abrc(${JSON.stringify(e.cookieName)});`)
189
+ .join('') +
190
+ `for(var _k in _ab){if(_ab[_k]==null)delete _ab[_k];}`
191
+ );
159
192
  }
160
193
 
161
194
  /**
@@ -175,10 +208,23 @@ function literal(value: Record<string, string | number | boolean>): string {
175
208
  return JSON.stringify(value).replaceAll('<', '\\u003c');
176
209
  }
177
210
 
178
- function googleAnalytics(input: string | GoogleAnalyticsOptions): ResolvedTag | string {
211
+ function googleAnalytics(
212
+ input: string | GoogleAnalyticsOptions,
213
+ experiments: Record<string, { cookieName: string }> = {},
214
+ ): ResolvedTag | string {
179
215
  const opts = typeof input === 'string' ? { id: input } : input;
180
216
  if (bad(opts.id)) return `googleAnalytics: "${opts.id}" is not a valid measurement ID. Skipped.`;
181
- const config = opts.config ? `,${literal(opts.config)}` : '';
217
+ const staticConfig = opts.config ?? {};
218
+ const reads = experimentCookieReads(experiments);
219
+ // With no experiments configured, the config object is static, exactly as
220
+ // before — same output byte-for-byte, no runtime cost added. With
221
+ // experiments, the automatic pageview's `gtag('config', …)` call is built
222
+ // at runtime instead, merging each assigned variant in under its
223
+ // experiment key so it reaches GA4 as a custom parameter on that same hit
224
+ // (registered as a custom dimension in GA4 Admin by parameter name).
225
+ const gtagConfig = reads
226
+ ? `${reads}gtag('config','${opts.id}',Object.assign(${literal(staticConfig)},_ab));`
227
+ : `gtag('config','${opts.id}'${opts.config ? `,${literal(staticConfig)}` : ''});`;
182
228
  return {
183
229
  key: 'googleAnalytics',
184
230
  provider: 'Google Analytics',
@@ -191,7 +237,7 @@ function googleAnalytics(input: string | GoogleAnalyticsOptions): ResolvedTag |
191
237
  `window.dataLayer=window.dataLayer||[];` +
192
238
  `function gtag(){dataLayer.push(arguments)}` +
193
239
  `gtag('js',new Date());` +
194
- `gtag('config','${opts.id}'${config});`,
240
+ gtagConfig,
195
241
  src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(opts.id)}`,
196
242
  attrs: {},
197
243
  };
@@ -230,7 +276,11 @@ function clarity(input: string | ClarityOptions): ResolvedTag | string {
230
276
  };
231
277
  }
232
278
 
233
- function matomo(opts: MatomoOptions): ResolvedTag | string {
279
+ function matomo(
280
+ opts: MatomoOptions,
281
+ experiments: Record<string, { cookieName: string }> = {},
282
+ dimensions: Record<string, number> = {},
283
+ ): ResolvedTag | string {
234
284
  const siteId = String(opts.siteId);
235
285
  if (bad(siteId)) return `matomo: "${siteId}" is not a valid site ID. Skipped.`;
236
286
  let base: URL;
@@ -242,8 +292,26 @@ function matomo(opts: MatomoOptions): ResolvedTag | string {
242
292
  const url = `${base.origin}${base.pathname.replace(/\/*$/, '')}/`;
243
293
  const cookies = opts.cookies === true;
244
294
 
245
- // `disableCookies` must be pushed *before* trackPageView, or the first request
246
- // of the visit sets the cookies this option exists to avoid.
295
+ // Only experiments with a recorded dimension index push anything — one
296
+ // with no index is silently skipped here (validateConfig's
297
+ // `experimentDimensionWarnings` is what surfaces that as a build-time
298
+ // warning, not a hard error: the pageview still ships correctly).
299
+ const dimensionEntries = Object.entries(experiments).filter(([key]) => dimensions[key] != null);
300
+ const reads = experimentCookieReads(Object.fromEntries(dimensionEntries));
301
+ const dimensionPushes = reads
302
+ ? reads +
303
+ dimensionEntries
304
+ .map(
305
+ ([key]) =>
306
+ `if(_ab[${JSON.stringify(key)}]!=null)_paq.push(['setCustomDimension',${dimensions[key]},_ab[${JSON.stringify(key)}]]);`,
307
+ )
308
+ .join('')
309
+ : '';
310
+
311
+ // `disableCookies` and the experiment dimension pushes must both land
312
+ // *before* trackPageView — the former so the first request of the visit
313
+ // doesn't set the cookies it exists to avoid, the latter because a
314
+ // dimension pushed after trackPageView misses that pageview entirely.
247
315
  return {
248
316
  key: 'matomo',
249
317
  provider: 'Matomo',
@@ -255,6 +323,7 @@ function matomo(opts: MatomoOptions): ResolvedTag | string {
255
323
  inline:
256
324
  `var _paq=window._paq=window._paq||[];` +
257
325
  (cookies ? '' : `_paq.push(['disableCookies']);`) +
326
+ dimensionPushes +
258
327
  `_paq.push(['trackPageView']);_paq.push(['enableLinkTracking']);` +
259
328
  `(function(){var u="${url}";` +
260
329
  `_paq.push(['setTrackerUrl',u+'matomo.php']);_paq.push(['setSiteId','${siteId}']);` +
@@ -265,9 +334,24 @@ function matomo(opts: MatomoOptions): ResolvedTag | string {
265
334
  };
266
335
  }
267
336
 
268
- function plausible(input: string | PlausibleOptions): ResolvedTag | string {
337
+ function plausible(
338
+ input: string | PlausibleOptions,
339
+ experiments: Record<string, { cookieName: string }> = {},
340
+ ): ResolvedTag | string {
269
341
  const opts = typeof input === 'string' ? { domain: input } : input;
270
342
  if (bad(opts.domain)) return `plausible: "${opts.domain}" is not a valid domain. Skipped.`;
343
+ // Plausible's current API (plausible.init({customProperties})) needs no
344
+ // special script variant and no manual-pageview mode — customProperties
345
+ // attaches to every tracked event, including the automatic pageview, so
346
+ // there's no double-counting risk to design around. The queueing stub
347
+ // mirrors gtag's own inline bootstrap above: the real script (loaded via
348
+ // `src`, async) picks up this call once it's ready, regardless of which
349
+ // one finishes loading first.
350
+ const reads = experimentCookieReads(experiments);
351
+ const inline = reads
352
+ ? `window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};` +
353
+ `plausible.init({customProperties:function(){${reads}return _ab;}});`
354
+ : '';
271
355
  return {
272
356
  key: 'plausible',
273
357
  provider: 'Plausible Analytics',
@@ -278,7 +362,7 @@ function plausible(input: string | PlausibleOptions): ResolvedTag | string {
278
362
  cookies: [],
279
363
  strategy: 'idle',
280
364
  gated: true,
281
- inline: '',
365
+ inline,
282
366
  src: opts.src ?? 'https://plausible.io/js/script.js',
283
367
  attrs: { 'data-domain': opts.domain },
284
368
  };
@@ -300,11 +384,14 @@ export function resolveAnalytics(
300
384
  if (!opts) return { tags, needsRuntime: false, warnings };
301
385
 
302
386
  const strategy = opts.strategy ?? 'idle';
387
+ const experiments = ctx.experiments ?? {};
303
388
  const results = [
304
- opts.googleAnalytics === undefined ? null : googleAnalytics(opts.googleAnalytics),
389
+ opts.googleAnalytics === undefined ? null : googleAnalytics(opts.googleAnalytics, experiments),
305
390
  opts.clarity === undefined ? null : clarity(opts.clarity),
306
- opts.matomo === undefined ? null : matomo(opts.matomo),
307
- opts.plausible === undefined ? null : plausible(opts.plausible),
391
+ opts.matomo === undefined
392
+ ? null
393
+ : matomo(opts.matomo, experiments, ctx.matomoAbVariantDimensions ?? {}),
394
+ opts.plausible === undefined ? null : plausible(opts.plausible, experiments),
308
395
  ];
309
396
 
310
397
  for (const result of results) {
@@ -29,7 +29,11 @@ const { enabled = true, strategy } = Astro.props;
29
29
 
30
30
  const options = strategy ? { ...head.analytics, strategy } : head.analytics;
31
31
  const { tags } = enabled
32
- ? resolveAnalytics(options, { consent: head.consent })
32
+ ? resolveAnalytics(options, {
33
+ consent: head.consent,
34
+ experiments: head.experiments,
35
+ matomoAbVariantDimensions: head.matomoAbVariantDimensions,
36
+ })
33
37
  : { tags: [] };
34
38
  ---
35
39
 
@@ -28,6 +28,7 @@
28
28
  * `<Analytics />`.
29
29
  */
30
30
  // @ts-ignore — virtual module provided by the vitops() integration at build time
31
+ import { safeHref } from '@getvitops/utils/url';
31
32
  import head from 'virtual:getvitops/head';
32
33
  import type { OptionalConsentCategory } from '../analytics.ts';
33
34
 
@@ -87,7 +88,7 @@ const wording = { ...DEFAULT_LABELS, ...labels };
87
88
  losing any functionality.
88
89
  </p>
89
90
  </slot>
90
- {policyUrl && <a class="link" href={policyUrl}>{policyLabel}</a>}
91
+ {safeHref(policyUrl) && <a class="link" href={safeHref(policyUrl)}>{policyLabel}</a>}
91
92
  </div>
92
93
 
93
94
  {/*
@@ -27,8 +27,15 @@
27
27
  * `inline-flex` with a `gap` — is a matter of child order, not a new class.
28
28
  * Don't confuse this with `.icon-mask`, the CSS-only adornment path (see
29
29
  * `.link--icon::before` in anchor-link.css).
30
+ *
31
+ * **Imports from `@getvitops/generator/icons-sprite`, never the root entry.**
32
+ * The root entry also re-exports `generate.ts`, which reaches lightningcss —
33
+ * a native binary Cloudflare Workers cannot `require()`. A *static* import of
34
+ * the root here dragged that into every SSR bundle rendering this component,
35
+ * regardless of `icons.engine`, and 500'd every request on a real consumer.
36
+ * The `icons-sprite` subpath has no such dependency — see its own docblock.
30
37
  */
31
- import { loadIconSvg, spriteId } from '@getvitops/generator';
38
+ import { loadIconSvg, spriteId } from '@getvitops/generator/icons-sprite';
32
39
  import { resolveIcon } from '@getvitops/utils';
33
40
  import icons from 'virtual:getvitops/icons';
34
41
 
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { HTMLAttributes } from 'astro/types';
9
9
  import type { Review } from '@getvitops/utils/reviews';
10
+ import { safeHref } from '@getvitops/utils/url';
10
11
  import Icon from './Icon.astro';
11
12
 
12
13
  export interface Props extends Omit<HTMLAttributes<'article'>, 'slot'> {
@@ -23,6 +24,8 @@ const initials = review.author
23
24
  .map((w) => w[0]?.toUpperCase())
24
25
  .join('');
25
26
 
27
+ // Google-hosted and fetched from outside the repo, so never trusted as a URL.
28
+ const authorPhoto = safeHref(review.authorPhoto);
26
29
  const full = Math.floor(review.rating);
27
30
  const hasHalf = review.rating - full >= 0.5;
28
31
  ---
@@ -30,8 +33,8 @@ const hasHalf = review.rating - full >= 0.5;
30
33
  <article class:list={['review', className]} {...rest}>
31
34
  <header class="review__header">
32
35
  {
33
- avatar && review.authorPhoto ? (
34
- <img class="review__avatar" src={review.authorPhoto} alt="" loading="lazy" />
36
+ avatar && authorPhoto ? (
37
+ <img class="review__avatar" src={authorPhoto} alt="" loading="lazy" />
35
38
  ) : (
36
39
  <span class="review__initials" aria-hidden="true">{initials}</span>
37
40
  )
@@ -25,7 +25,7 @@
25
25
  // @ts-ignore — virtual module provided by the vitops() integration at build time
26
26
  import head from 'virtual:getvitops/head';
27
27
 
28
- const { enabled, category, cookies } = head.tracking ?? { enabled: false };
28
+ const { enabled, category, cookies, abVariantCookie } = head.tracking ?? { enabled: false };
29
29
  ---
30
30
 
31
31
  {enabled && (
@@ -35,6 +35,7 @@ const { enabled, category, cookies } = head.tracking ?? { enabled: false };
35
35
  data-vitops-tracking
36
36
  data-consent={category}
37
37
  data-consent-cookies={cookies?.length ? cookies.join(',') : undefined}
38
+ data-ab-cookie={abVariantCookie ?? undefined}
38
39
  />
39
40
  <script>
40
41
  import '../scripts/tracking.ts';