From 1c18336c81e518337f1b8b5183c53b9eb7d67468 Mon Sep 17 00:00:00 2001 From: Mariano Mino Date: Sat, 21 Nov 2026 17:51:24 +0100 Subject: [PATCH 1/4] feat: MetricRaven Co-Authored-By: Claude Opus 5.5 --- FIRST_PARTY.md | 2 +- docs/content/docs/1.guides/2.first-party.md | 1 + docs/content/scripts/metricraven-analytics.md | 113 ++++++++++++++ packages/script/src/registry-logos.ts | 4 + packages/script/src/registry-types.json | 133 +++++++++++++++++ packages/script/src/registry.ts | 25 ++++ .../runtime/registry/metricraven-analytics.ts | 136 +++++++++++++++++ .../script/src/runtime/registry/schemas.ts | 93 +++++++++++- packages/script/src/runtime/types.ts | 4 +- packages/script/src/script-meta.ts | 4 + packages/script/src/script-sizes.json | 69 +++++++++ playground/nuxt.config.ts | 2 + playground/pages/index.vue | 1 + .../third-parties/metricraven-analytics.vue | 105 +++++++++++++ test/e2e-dev/first-party.test.ts | 10 ++ test/e2e/metricraven-analytics.test.ts | 31 ++++ test/fixtures/first-party/nuxt.config.ts | 2 + test/fixtures/first-party/pages/index.vue | 1 + .../first-party/pages/metricraven.vue | 32 ++++ .../metricraven-analytics/nuxt.config.ts | 11 ++ .../metricraven-analytics/pages/index.vue | 11 ++ test/types/types.test-d.ts | 1 + test/unit/metricraven-analytics.test.ts | 140 ++++++++++++++++++ test/unit/metricraven-bundle-resolve.test.ts | 55 +++++++ test/unit/proxy-configs.test.ts | 8 + 25 files changed, 991 insertions(+), 3 deletions(-) create mode 100644 docs/content/scripts/metricraven-analytics.md create mode 100644 packages/script/src/runtime/registry/metricraven-analytics.ts create mode 100644 playground/pages/third-parties/metricraven-analytics.vue create mode 100644 test/e2e/metricraven-analytics.test.ts create mode 100644 test/fixtures/first-party/pages/metricraven.vue create mode 100644 test/fixtures/metricraven-analytics/nuxt.config.ts create mode 100644 test/fixtures/metricraven-analytics/pages/index.vue create mode 100644 test/unit/metricraven-analytics.test.ts create mode 100644 test/unit/metricraven-bundle-resolve.test.ts diff --git a/FIRST_PARTY.md b/FIRST_PARTY.md index 00eb40325..58b8d5a95 100644 --- a/FIRST_PARTY.md +++ b/FIRST_PARTY.md @@ -138,7 +138,7 @@ Four presets in `proxy-configs.ts` cover all proxy-enabled scripts: | `PRIVACY_HEATMAP` | ip, language, hardware | GA, Clarity, Hotjar | | `PRIVACY_IP_ONLY` | ip only | PostHog, Plausible, Umami, Rybbit, Databuddy, Ahrefs, Fathom, Vercel, Matomo, Carbon Ads, Lemon Squeezy, Intercom, Gravatar, YouTube, Vimeo, Calendly | -Note: Cloudflare Web Analytics, TikTok, GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, and Statable have no proxy capability, so no privacy transforms are applied. +Note: Cloudflare Web Analytics, TikTok, GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, Statable, and MetricRaven have no proxy capability, so no privacy transforms are applied. ## Script Support diff --git a/docs/content/docs/1.guides/2.first-party.md b/docs/content/docs/1.guides/2.first-party.md index b2d5d372d..7df9757f1 100644 --- a/docs/content/docs/1.guides/2.first-party.md +++ b/docs/content/docs/1.guides/2.first-party.md @@ -312,6 +312,7 @@ These integrations serve their main loader from your domain, but some runtime re | [Fathom](/scripts/fathom-analytics) | Fathom's bot detection rejects beacons from the server's IP, so Nuxt Scripts bundles the SDK but leaves beacons direct. | | [Pulse](/scripts/pulse-analytics) | Pulse identifies visitors from the connecting IP, so proxied beacons would merge everyone into one visitor. Nuxt Scripts bundles the tracker but leaves beacons direct. | | [Statable](/scripts/statable-analytics) | Statable identifies visitors from the connecting IP and user agent, so proxied beacons would merge everyone into one visitor. Nuxt Scripts bundles the tracker but leaves beacons direct. | +| [MetricRaven](/scripts/metricraven-analytics) | Without storage consent, MetricRaven derives a daily visitor ID from the client IP, which a proxy has to forward in an `x-visitor-ip` header. Nuxt Scripts bundles the tracker but leaves beacons direct. | | [Segment](/scripts/segment) | SDK constructs API URLs dynamically, bypassing request interception. | | [Crisp](/scripts/crisp) | SDK loads secondary scripts and CSS at runtime from `client.crisp.chat`. | | [Mixpanel](/scripts/mixpanel-analytics) | No proxy integration yet. | diff --git a/docs/content/scripts/metricraven-analytics.md b/docs/content/scripts/metricraven-analytics.md new file mode 100644 index 000000000..6306b66ac --- /dev/null +++ b/docs/content/scripts/metricraven-analytics.md @@ -0,0 +1,113 @@ +--- +title: MetricRaven +description: Load the MetricRaven tracker, record goals and identify users. +seoTitle: MetricRaven Setup for Nuxt +seoDescription: Add the MetricRaven tracking script to a Nuxt app, record goals, identify users and pass the visitor ID to your checkout from a typed composable. +links: + - label: Source + icon: i-simple-icons-github + to: https://github.com/nuxt/scripts/blob/main/packages/script/src/runtime/registry/metricraven-analytics.ts + size: xs +--- + +[MetricRaven](https://metricraven.com/) is web analytics that attributes revenue from your payment provider to the visit that brought each customer. It sets no cookies until you grant storage consent. The [install guide](https://metricraven.com/docs/install) lists the tracker's options. + +::script-stats +:: + +::script-docs +:: + +## Proxying is not supported + +Without storage consent, MetricRaven derives a daily visitor ID from the client IP. A proxy has to forward that IP in an `x-visitor-ip` header, which the Nuxt Scripts proxy does not do, so beacons sent through it would merge every visitor into one. + +You can bundle the tracker on your Nuxt origin. Events still go to MetricRaven. The composable sets `data-api` and `data-addons` on the script tag, so the bundled copy keeps sending to the tracker's origin. + +To serve everything from your own domain, use MetricRaven's [managed proxy](https://metricraven.com/docs/managed-proxy) and set `apiHost`, or a [server route](https://metricraven.com/docs/proxy-vue-nuxt) of your own and set `scriptUrl` and `endpoint`: + +::code-group + +```ts [Managed proxy] +useScriptMetricRavenAnalytics({ + siteId: 'ana_pub_…', + apiHost: 'https://a.example.com', +}) +``` + +```ts [Server route] +useScriptMetricRavenAnalytics({ + siteId: 'ana_pub_…', + scriptUrl: '/a/script', + endpoint: '/a/event', +}) +``` + +:: + +## Goals + +Use `proxy.track(name, props)`{lang="ts"} to record a goal. Calls made before the tracker loads run once it is ready. Properties can be strings, numbers or booleans. + +::code-group + +```ts [Proxy] +const { proxy } = useScriptMetricRavenAnalytics() +function trackSignup() { + proxy.track('signup', { plan: 'pro' }) +} +``` + +```ts [onLoaded] +const { onLoaded } = useScriptMetricRavenAnalytics() +onLoaded(({ track }) => { + track('newsletter_signup') +}) +``` + +:: + +Elements with a `data-goal="name"` attribute are tracked on click without code. See [Goals & funnels](https://metricraven.com/docs/goals-funnels). + +## Identify users + +`identify` labels the current visitor with your user ID and traits. For a verified identity, pass a token your server signed, either with `identify({ token })`{lang="ts"} or the `identityToken` option. See [Identify users](https://metricraven.com/docs/identify-users). + +```ts +const { proxy } = useScriptMetricRavenAnalytics() +proxy.identify(user.id, { name: user.name, email: user.email }) +``` + +## Revenue attribution + +To credit a payment to the visit, send the visitor ID to your checkout and on to your payment provider's metadata. See [Connect a payment provider](https://metricraven.com/docs/connect-payment-provider). + +```ts +const { onLoaded } = useScriptMetricRavenAnalytics() +onLoaded(({ getVisitorId }) => { + checkoutMetadata.metricraven_visitor_id = getVisitorId() +}) +``` + +## Consent + +Until storage consent is granted, the tracker stores nothing in the browser. Set `consent: true` when your banner's saved choice already allows it, or call `proxy.setConsent(true)`{lang="ts"} when the visitor accepts. See [Consent](https://metricraven.com/docs/consent). + +## Page views in Nuxt + +The tracker records client-side navigation without extra setup. Set `autoPageviews: false` to call `proxy.pageview(path)`{lang="ts"} yourself, and `hashRouting: true` for hash-mode routers. + +::script-types +:: + +## Example + +The default trigger waits until Nuxt is ready: + +```vue [app.vue] + +``` diff --git a/packages/script/src/registry-logos.ts b/packages/script/src/registry-logos.ts index 61f53b013..a2f88b615 100644 --- a/packages/script/src/registry-logos.ts +++ b/packages/script/src/registry-logos.ts @@ -15,6 +15,10 @@ export const LOGOS = { light: ``, dark: ``, }, + metricravenAnalytics: { + light: ``, + dark: ``, + }, matomoAnalytics: ``, rybbitAnalytics: { light: ``, diff --git a/packages/script/src/registry-types.json b/packages/script/src/registry-types.json index edfe16f41..b64e8da96 100644 --- a/packages/script/src/registry-types.json +++ b/packages/script/src/registry-types.json @@ -989,6 +989,33 @@ "code": "export interface MetaPixelConsent {\n /** Call `fbq('consent','grant')`. */\n grant: () => void\n /** Call `fbq('consent','revoke')`. */\n revoke: () => void\n}" } ], + "metricraven-analytics": [ + { + "name": "MetricRavenAnalyticsOptions", + "kind": "const", + "code": "export const MetricRavenAnalyticsOptions = object({\n /**\n * Your site's public ID (`ana_pub_…`), from Settings in MetricRaven.\n * @see https://metricraven.com/docs/install\n */\n siteId: pipe(string(), regex(/^ana_pub_[\\w-]+$/)),\n /**\n * Origin that serves the tracker and receives events, such as a managed\n * proxy subdomain. The tracker loads from `/js/script.js`.\n * @default 'https://metricraven.com'\n * @see https://metricraven.com/docs/managed-proxy\n */\n apiHost: optional(string()),\n /**\n * Full tracker URL, such as a same-origin proxy path (`/a/script`). Overrides `apiHost`.\n * @see https://metricraven.com/docs/proxy\n */\n scriptUrl: optional(string()),\n /**\n * URL the tracker sends events to, for a proxy on your own server (`data-api`).\n * Defaults to `/api/v1/collect` on the tracker's origin.\n * @see https://metricraven.com/docs/proxy\n */\n endpoint: optional(string()),\n /**\n * Where the tracker loads its optional add-ons from (`data-addons`).\n * Defaults to `/js/addons/` next to the tracker, or metricraven.com.\n */\n addonsUrl: optional(string()),\n /**\n * Record pageviews on load and on client-side navigation. Set to `false` to\n * call `pageview()` yourself.\n * @default true\n * @see https://metricraven.com/docs/spa-virtual-pages\n */\n autoPageviews: optional(boolean()),\n /**\n * Count `#/` and `#!/` routes as pages (`true`), or also plain anchors such as `#pricing` (`'all'`).\n * @default false\n */\n hashRouting: optional(union([boolean(), literal('all')])),\n /**\n * Drop query strings from recorded URLs.\n * @default false\n */\n stripQuery: optional(boolean()),\n /**\n * Storage consent already granted. Without it, nothing is stored in the browser\n * and the server derives a daily visitor ID. Call `setConsent(true)` to grant it later.\n * @default false\n * @see https://metricraven.com/docs/consent\n */\n consent: optional(boolean()),\n /**\n * Advertising consent already granted, so ad clicks can be sent back to ad networks\n * with conversions (`data-ad-consent=\"granted\"`).\n * @default false\n */\n adConsent: optional(boolean()),\n /**\n * Share the visitor cookie (after consent) across this domain and its subdomains.\n */\n domain: optional(string()),\n /**\n * Also track `localhost` and `*.test` pages, which are skipped by default.\n * @default false\n */\n allowLocalhost: optional(boolean()),\n /**\n * Extra hosts for cross-domain linking. The site's own domains are linked automatically.\n * @see https://metricraven.com/docs/cross-domain\n */\n allowedHostnames: optional(array(string())),\n /**\n * A signed identity token from your server: identifies the signed-in visitor as the tracker loads.\n * @see https://metricraven.com/docs/identify-users\n */\n identityToken: optional(string()),\n /**\n * Narrow the automatic events switched on in Settings: `false` turns them off on\n * this page, a list keeps only those kinds.\n * @see https://metricraven.com/docs/automatic-events\n */\n autocapture: optional(union([literal(false), array(picklist(['clicks', 'forms', 'downloads', 'scroll']))])),\n /**\n * Log to the console what is sent and why anything is skipped.\n * @default false\n */\n debug: optional(boolean()),\n})" + }, + { + "name": "MetricRavenPropValue", + "kind": "type", + "code": "export type MetricRavenPropValue = string | number | boolean" + }, + { + "name": "MetricRavenTraits", + "kind": "interface", + "code": "export interface MetricRavenTraits {\n name?: string\n email?: string\n /** An https:// profile picture URL. */\n image?: string\n [trait: string]: MetricRavenPropValue | null | undefined\n}" + }, + { + "name": "MetricRavenAnalyticsApi", + "kind": "interface", + "code": "export interface MetricRavenAnalyticsApi {\n /**\n * Records a custom event (a goal).\n * @param name Event name.\n * @param props Up to 10 properties: strings, numbers or booleans.\n * @see https://metricraven.com/docs/goals-funnels\n */\n track: (name: string, props?: Record) => void\n /**\n * Links this visitor to your user ID, with optional traits. Pass `{ token }` for a\n * signed identify made with a site secret key on your server.\n * @see https://metricraven.com/docs/identify-users\n */\n identify: ((userId: string | number, traits?: MetricRavenTraits, options?: { token?: string }) => boolean)\n & ((signed: { token: string }) => boolean)\n /**\n * Records a pageview. Needed only with `autoPageviews: false` or for virtual pages.\n * @param path A path on this origin. Defaults to the current URL.\n */\n pageview: (path?: string) => boolean\n /**\n * Credits a payment made with this email within the hour to this visitor, for\n * checkouts that can't carry the visitor ID.\n * @see https://metricraven.com/docs/attribute-by-email\n */\n payment: (claim: { email: string }) => boolean\n /** Grants or withdraws storage consent. */\n setConsent: (granted: boolean) => void\n /** Grants or withdraws advertising consent (ad clicks sent back with conversions). */\n setAdConsent: (granted: boolean) => void\n /** Starts a new visitor ID on logout (only when consent was granted). */\n reset: () => void\n /**\n * The current visitor ID. Pass it to your checkout to attribute revenue to the visit.\n * @see https://metricraven.com/docs/payments-api\n */\n getVisitorId: () => string | null\n /** The URL with cross-domain linking added, for links built in code. */\n linkUrl: (url: string) => string\n /** The cross-domain linking parameter (`{ mr_link }`), or `{}`. */\n linkParams: () => Record\n}" + }, + { + "name": "METRICRAVEN_DEFAULT_HOST", + "kind": "const", + "code": "export const METRICRAVEN_DEFAULT_HOST = 'https://metricraven.com'" + } + ], "mixpanel-analytics": [ { "name": "MixpanelAnalyticsOptions", @@ -3131,6 +3158,112 @@ "description": "Custom properties attached to every event from the page load, rendered as `data-statable-*` attributes on the script tag." } ], + "MetricRavenAnalyticsOptions": [ + { + "name": "siteId", + "type": "string", + "required": true, + "description": "Your site's public ID (`ana_pub_…`), from Settings in MetricRaven." + }, + { + "name": "apiHost", + "type": "string", + "required": false, + "description": "Origin that serves the tracker and receives events, such as a managed proxy subdomain. The tracker loads from `/js/script.js`.", + "defaultValue": "'https://metricraven.com'" + }, + { + "name": "scriptUrl", + "type": "string", + "required": false, + "description": "Full tracker URL, such as a same-origin proxy path (`/a/script`). Overrides `apiHost`." + }, + { + "name": "endpoint", + "type": "string", + "required": false, + "description": "URL the tracker sends events to, for a proxy on your own server (`data-api`). Defaults to `/api/v1/collect` on the tracker's origin." + }, + { + "name": "addonsUrl", + "type": "string", + "required": false, + "description": "Where the tracker loads its optional add-ons from (`data-addons`). Defaults to `/js/addons/` next to the tracker, or metricraven.com." + }, + { + "name": "autoPageviews", + "type": "boolean", + "required": false, + "description": "Record pageviews on load and on client-side navigation. Set to `false` to call `pageview()` yourself.", + "defaultValue": "true" + }, + { + "name": "hashRouting", + "type": "boolean | 'all'", + "required": false, + "description": "Count `#/` and `#!/` routes as pages (`true`), or also plain anchors such as `#pricing` (`'all'`).", + "defaultValue": "false" + }, + { + "name": "stripQuery", + "type": "boolean", + "required": false, + "description": "Drop query strings from recorded URLs.", + "defaultValue": "false" + }, + { + "name": "consent", + "type": "boolean", + "required": false, + "description": "Storage consent already granted. Without it, nothing is stored in the browser and the server derives a daily visitor ID. Call `setConsent(true)` to grant it later.", + "defaultValue": "false" + }, + { + "name": "adConsent", + "type": "boolean", + "required": false, + "description": "Advertising consent already granted, so ad clicks can be sent back to ad networks with conversions (`data-ad-consent=\"granted\"`).", + "defaultValue": "false" + }, + { + "name": "domain", + "type": "string", + "required": false, + "description": "Share the visitor cookie (after consent) across this domain and its subdomains." + }, + { + "name": "allowLocalhost", + "type": "boolean", + "required": false, + "description": "Also track `localhost` and `*.test` pages, which are skipped by default.", + "defaultValue": "false" + }, + { + "name": "allowedHostnames", + "type": "string[]", + "required": false, + "description": "Extra hosts for cross-domain linking. The site's own domains are linked automatically." + }, + { + "name": "identityToken", + "type": "string", + "required": false, + "description": "A signed identity token from your server: identifies the signed-in visitor as the tracker loads." + }, + { + "name": "autocapture", + "type": "false | unknown[]", + "required": false, + "description": "Narrow the automatic events switched on in Settings: `false` turns them off on this page, a list keeps only those kinds." + }, + { + "name": "debug", + "type": "boolean", + "required": false, + "description": "Log to the console what is sent and why anything is skipped.", + "defaultValue": "false" + } + ], "ScriptGoogleMapsProps": [ { "name": "trigger", diff --git a/packages/script/src/registry.ts b/packages/script/src/registry.ts index ddff5a0fd..c73e5cfad 100644 --- a/packages/script/src/registry.ts +++ b/packages/script/src/registry.ts @@ -2,6 +2,7 @@ import type { ClarityInput } from './runtime/registry/clarity' import type { GoogleAdsenseInput } from './runtime/registry/google-adsense' import type { HotjarInput } from './runtime/registry/hotjar' import type { IntercomInput } from './runtime/registry/intercom' +import type { MetricRavenAnalyticsInput } from './runtime/registry/metricraven-analytics' import type { MixpanelAnalyticsInput } from './runtime/registry/mixpanel-analytics' import type { NpmInput } from './runtime/registry/npm' import type { PlausibleAnalyticsInput } from './runtime/registry/plausible-analytics' @@ -38,6 +39,7 @@ import { MapLibreOptions, MatomoAnalyticsOptions, MetaPixelOptions, + MetricRavenAnalyticsOptions, MixpanelAnalyticsOptions, NpmOptions, PostHogOptions, @@ -151,6 +153,10 @@ export const registryMeta: RegistryScriptMeta[] = [ // visitor identity, so proxied beacons would collapse every visitor into // one. Same family as Fathom (#720) and Pulse. m('statableAnalytics', 'Statable Analytics', 'analytics', 'useScriptStatableAnalytics', { bundle: true }, null), + // No proxy: without storage consent MetricRaven derives a daily visitor ID + // from the client IP, which a proxy must forward in `x-visitor-ip`. Proxied + // beacons would collapse every visitor into one, as with Fathom (#720). + m('metricravenAnalytics', 'MetricRaven', 'analytics', 'useScriptMetricRavenAnalytics', { bundle: true }, null), // ad m('bingUet', 'Bing UET', 'ad', 'useScriptBingUet', { bundle: true, partytown: true }, null), m('metaPixel', 'Meta Pixel', 'ad', 'useScriptMetaPixel', { bundle: true, proxy: true, partytown: true }, PRIVACY_FULL), @@ -499,6 +505,25 @@ export async function registry(resolve?: (path: string) => Promise): Pro }, }, }), + def('metricravenAnalytics', { + composableName: 'useScriptMetricRavenAnalytics', + schema: MetricRavenAnalyticsOptions, + label: 'MetricRaven', + category: 'analytics', + envDefaults: { siteId: '' }, + // Bundling needs no SDK patch: the composable pins `data-api` and + // `data-addons` on the script element, so the bundled copy keeps + // reporting to the tracker's origin instead of the Nuxt origin. + bundle: { + resolve: (options?: MetricRavenAnalyticsInput) => { + if (!options?.siteId) + return false + if (options.scriptUrl) + return /^https?:\/\//i.test(options.scriptUrl) ? options.scriptUrl : false + return `${(options.apiHost || 'https://metricraven.com').replace(/\/+$/, '')}/js/script.js` + }, + }, + }), // ad def('bingUet', { schema: BingUetOptions, diff --git a/packages/script/src/runtime/registry/metricraven-analytics.ts b/packages/script/src/runtime/registry/metricraven-analytics.ts new file mode 100644 index 000000000..94608708d --- /dev/null +++ b/packages/script/src/runtime/registry/metricraven-analytics.ts @@ -0,0 +1,136 @@ +import type { RegistryScriptInput } from '#nuxt-scripts/types' +import { useRegistryScript } from '../utils' +import { MetricRavenAnalyticsOptions } from './schemas' + +export { MetricRavenAnalyticsOptions } + +export type MetricRavenAnalyticsInput = RegistryScriptInput + +export type MetricRavenPropValue = string | number | boolean + +export interface MetricRavenTraits { + name?: string + email?: string + /** An https:// profile picture URL. */ + image?: string + [trait: string]: MetricRavenPropValue | null | undefined +} + +export interface MetricRavenAnalyticsApi { + /** + * Records a custom event (a goal). + * @param name Event name. + * @param props Up to 10 properties: strings, numbers or booleans. + * @see https://metricraven.com/docs/goals-funnels + */ + track: (name: string, props?: Record) => void + /** + * Links this visitor to your user ID, with optional traits. Pass `{ token }` for a + * signed identify made with a site secret key on your server. + * @see https://metricraven.com/docs/identify-users + */ + identify: ((userId: string | number, traits?: MetricRavenTraits, options?: { token?: string }) => boolean) + & ((signed: { token: string }) => boolean) + /** + * Records a pageview. Needed only with `autoPageviews: false` or for virtual pages. + * @param path A path on this origin. Defaults to the current URL. + */ + pageview: (path?: string) => boolean + /** + * Credits a payment made with this email within the hour to this visitor, for + * checkouts that can't carry the visitor ID. + * @see https://metricraven.com/docs/attribute-by-email + */ + payment: (claim: { email: string }) => boolean + /** Grants or withdraws storage consent. */ + setConsent: (granted: boolean) => void + /** Grants or withdraws advertising consent (ad clicks sent back with conversions). */ + setAdConsent: (granted: boolean) => void + /** Starts a new visitor ID on logout (only when consent was granted). */ + reset: () => void + /** + * The current visitor ID. Pass it to your checkout to attribute revenue to the visit. + * @see https://metricraven.com/docs/payments-api + */ + getVisitorId: () => string | null + /** The URL with cross-domain linking added, for links built in code. */ + linkUrl: (url: string) => string + /** The cross-domain linking parameter (`{ mr_link }`), or `{}`. */ + linkParams: () => Record +} + +declare global { + interface Window { + metricraven: MetricRavenAnalyticsApi + metricravenConsent?: boolean + } +} + +export const METRICRAVEN_DEFAULT_HOST = 'https://metricraven.com' + +const ABSOLUTE_URL_RE = /^https?:\/\//i + +/** Where the tracker loads from: `scriptUrl`, else `/js/script.js`. */ +export function metricRavenScriptUrl(options: { apiHost?: string, scriptUrl?: string }): string { + if (options.scriptUrl) + return options.scriptUrl + return `${(options.apiHost || METRICRAVEN_DEFAULT_HOST).replace(/\/+$/, '')}/js/script.js` +} + +/** + * The event endpoint and add-on base the tracker would derive from its own src. + * Pinned on the tag so a bundled copy served from the Nuxt origin keeps them. + * Relative script URLs are left to the tracker. + */ +function trackerDefaults(src: string): { endpoint?: string, addons?: string } { + if (!ABSOLUTE_URL_RE.test(src)) + return {} + const url = new URL(src) + return { + endpoint: new URL('/api/v1/collect', url).toString(), + addons: url.pathname.endsWith('/js/script.js') + ? new URL('addons/', url).toString() + : `${METRICRAVEN_DEFAULT_HOST}/js/addons/`, + } +} + +export function useScriptMetricRavenAnalytics(_options?: MetricRavenAnalyticsInput) { + return useRegistryScript('metricravenAnalytics', (options) => { + const src = metricRavenScriptUrl(options) + const defaults = trackerDefaults(src) + const hosts = (options.allowedHostnames || []).map(h => h.trim()).filter(Boolean) + return { + scriptInput: { + 'src': src, + 'data-site-id': options.siteId, + 'data-api': options.endpoint || defaults.endpoint, + 'data-addons': options.addonsUrl || defaults.addons, + 'data-auto-pageviews': options.autoPageviews === false ? 'false' : undefined, + 'data-track-hash': options.hashRouting === 'all' ? 'all' : options.hashRouting ? 'true' : undefined, + 'data-strip-query': options.stripQuery ? 'true' : undefined, + 'data-ad-consent': options.adConsent ? 'granted' : undefined, + 'data-domain': options.domain, + // The tracker checks for the attribute's presence. + 'data-allow-localhost': options.allowLocalhost ? 'true' : undefined, + 'data-allowed-hostnames': hosts.length ? hosts.join(',') : undefined, + 'data-identity-token': options.identityToken, + 'data-autocapture': options.autocapture === false + ? 'false' + : Array.isArray(options.autocapture) ? (options.autocapture.join(',') || 'false') : undefined, + 'data-debug': options.debug ? 'true' : undefined, + }, + schema: import.meta.dev ? MetricRavenAnalyticsOptions : undefined, + scriptOptions: { + use() { + return window.metricraven + }, + }, + clientInit: import.meta.server || !options.consent + ? undefined + : () => { + // Read by the tracker when it starts. + window.metricravenConsent = true + }, + } + }, _options) +} diff --git a/packages/script/src/runtime/registry/schemas.ts b/packages/script/src/runtime/registry/schemas.ts index ff839da5f..49016a639 100644 --- a/packages/script/src/runtime/registry/schemas.ts +++ b/packages/script/src/runtime/registry/schemas.ts @@ -1,4 +1,4 @@ -import { any, array, boolean, custom, function_, literal, maxValue, minLength, minValue, number, object, optional, pipe, record, regex, string, union } from 'valibot' +import { any, array, boolean, custom, function_, literal, maxValue, minLength, minValue, number, object, optional, picklist, pipe, record, regex, string, union } from 'valibot' // Shared GCMv2 consent category value. const consentCategoryValue = union([literal('granted'), literal('denied')]) @@ -1407,3 +1407,94 @@ export const StatableAnalyticsOptions = object({ */ props: optional(record(string(), string())), }) + +export const MetricRavenAnalyticsOptions = object({ + /** + * Your site's public ID (`ana_pub_…`), from Settings in MetricRaven. + * @see https://metricraven.com/docs/install + */ + siteId: pipe(string(), regex(/^ana_pub_[\w-]+$/)), + /** + * Origin that serves the tracker and receives events, such as a managed + * proxy subdomain. The tracker loads from `/js/script.js`. + * @default 'https://metricraven.com' + * @see https://metricraven.com/docs/managed-proxy + */ + apiHost: optional(string()), + /** + * Full tracker URL, such as a same-origin proxy path (`/a/script`). Overrides `apiHost`. + * @see https://metricraven.com/docs/proxy + */ + scriptUrl: optional(string()), + /** + * URL the tracker sends events to, for a proxy on your own server (`data-api`). + * Defaults to `/api/v1/collect` on the tracker's origin. + * @see https://metricraven.com/docs/proxy + */ + endpoint: optional(string()), + /** + * Where the tracker loads its optional add-ons from (`data-addons`). + * Defaults to `/js/addons/` next to the tracker, or metricraven.com. + */ + addonsUrl: optional(string()), + /** + * Record pageviews on load and on client-side navigation. Set to `false` to + * call `pageview()` yourself. + * @default true + * @see https://metricraven.com/docs/spa-virtual-pages + */ + autoPageviews: optional(boolean()), + /** + * Count `#/` and `#!/` routes as pages (`true`), or also plain anchors such as `#pricing` (`'all'`). + * @default false + */ + hashRouting: optional(union([boolean(), literal('all')])), + /** + * Drop query strings from recorded URLs. + * @default false + */ + stripQuery: optional(boolean()), + /** + * Storage consent already granted. Without it, nothing is stored in the browser + * and the server derives a daily visitor ID. Call `setConsent(true)` to grant it later. + * @default false + * @see https://metricraven.com/docs/consent + */ + consent: optional(boolean()), + /** + * Advertising consent already granted, so ad clicks can be sent back to ad networks + * with conversions (`data-ad-consent="granted"`). + * @default false + */ + adConsent: optional(boolean()), + /** + * Share the visitor cookie (after consent) across this domain and its subdomains. + */ + domain: optional(string()), + /** + * Also track `localhost` and `*.test` pages, which are skipped by default. + * @default false + */ + allowLocalhost: optional(boolean()), + /** + * Extra hosts for cross-domain linking. The site's own domains are linked automatically. + * @see https://metricraven.com/docs/cross-domain + */ + allowedHostnames: optional(array(string())), + /** + * A signed identity token from your server: identifies the signed-in visitor as the tracker loads. + * @see https://metricraven.com/docs/identify-users + */ + identityToken: optional(string()), + /** + * Narrow the automatic events switched on in Settings: `false` turns them off on + * this page, a list keeps only those kinds. + * @see https://metricraven.com/docs/automatic-events + */ + autocapture: optional(union([literal(false), array(picklist(['clicks', 'forms', 'downloads', 'scroll']))])), + /** + * Log to the console what is sent and why anything is skipped. + * @default false + */ + debug: optional(boolean()), +}) diff --git a/packages/script/src/runtime/types.ts b/packages/script/src/runtime/types.ts index 24793ba54..746b3ec9c 100644 --- a/packages/script/src/runtime/types.ts +++ b/packages/script/src/runtime/types.ts @@ -31,6 +31,7 @@ import type { LinkedInInsightInput } from './registry/linkedin-insight' import type { MapLibreInput } from './registry/maplibre' import type { MatomoAnalyticsInput } from './registry/matomo-analytics' import type { MetaPixelInput } from './registry/meta-pixel' +import type { MetricRavenAnalyticsInput } from './registry/metricraven-analytics' import type { MixpanelAnalyticsInput } from './registry/mixpanel-analytics' import type { NpmInput } from './registry/npm' import type { PayPalInput } from './registry/paypal' @@ -305,6 +306,7 @@ export interface ScriptRegistry { posthog?: PostHogInput pulseAnalytics?: PulseAnalyticsInput matomoAnalytics?: MatomoAnalyticsInput + metricravenAnalytics?: MetricRavenAnalyticsInput mixpanelAnalytics?: MixpanelAnalyticsInput rybbitAnalytics?: RybbitAnalyticsInput redditPixel?: RedditPixelInput @@ -337,7 +339,7 @@ export type BuiltInRegistryScriptKey | 'plausibleAnalytics' | 'googleAdsense' | 'googleAnalytics' | 'googleMaps' | 'leaflet' | 'maplibre' | 'googleRecaptcha' | 'googleSignIn' | 'lemonSqueezy' | 'googleTagManager' | 'hotjar' | 'intercom' | 'linkedinInsight' | 'paypal' | 'posthog' | 'pulseAnalytics' | 'matomoAnalytics' - | 'mixpanelAnalytics' | 'rybbitAnalytics' | 'redditPixel' | 'segment' | 'statableAnalytics' | 'stripe' | 'tawkTo' | 'tiktokPixel' + | 'metricravenAnalytics' | 'mixpanelAnalytics' | 'rybbitAnalytics' | 'redditPixel' | 'segment' | 'statableAnalytics' | 'stripe' | 'tawkTo' | 'tiktokPixel' | 'xEmbed' | 'xPixel' | 'snapchatPixel' | 'speedcurve' | 'youtubePlayer' | 'vercelAnalytics' | 'vimeoPlayer' | 'umamiAnalytics' | 'usercentrics' | 'gravatar' | 'npm' diff --git a/packages/script/src/script-meta.ts b/packages/script/src/script-meta.ts index f20c2fed8..c58f9f8d1 100644 --- a/packages/script/src/script-meta.ts +++ b/packages/script/src/script-meta.ts @@ -56,6 +56,10 @@ export const scriptMeta = { urls: ['https://statable.com/js/3078194/s.js'], trackedData: ['page-views', 'events', 'conversions', 'scrolls'], }, + metricravenAnalytics: { + urls: ['https://metricraven.com/js/script.js'], + trackedData: ['page-views', 'events', 'conversions', 'user-identity', 'transactions', 'scrolls', 'errors', 'performance-timings'], + }, databuddyAnalytics: { urls: ['https://cdn.databuddy.cc/databuddy.js'], trackedData: ['page-views', 'events'], diff --git a/packages/script/src/script-sizes.json b/packages/script/src/script-sizes.json index 29af1dfe9..201cc356d 100644 --- a/packages/script/src/script-sizes.json +++ b/packages/script/src/script-sizes.json @@ -597,6 +597,75 @@ } ] }, + "metricravenAnalytics": { + "totalTransferKb": 8.9, + "totalDecodedKb": 19.3, + "loadTimeMs": 142, + "collectsWebVitals": false, + "apis": { + "cookies": true, + "localStorage": true, + "sessionStorage": true, + "indexedDB": false, + "canvas": false, + "webgl": false, + "audioContext": false, + "userAgent": true, + "doNotTrack": false, + "hardwareConcurrency": false, + "deviceMemory": false, + "plugins": false, + "languages": true, + "screen": true, + "timezone": false, + "platform": false, + "vendor": false, + "connection": false, + "maxTouchPoints": false, + "devicePixelRatio": false, + "mediaDevices": false, + "getBattery": false, + "referrer": true, + "windowName": false, + "rtcPeerConnection": false, + "geolocation": false, + "serviceWorker": false, + "cacheApi": false, + "sendBeacon": true, + "fetch": true, + "xhr": false, + "websocket": false, + "mutationObserver": true, + "performanceObserver": false, + "intersectionObserver": true + }, + "cookies": [], + "network": { + "requestCount": 1, + "domains": [ + "metricraven.com" + ], + "outboundBytes": 0, + "inboundBytes": 9131, + "injectedElements": [] + }, + "performance": { + "taskDurationMs": 33, + "scriptDurationMs": 0, + "heapDeltaKb": 746 + }, + "scripts": [ + { + "url": "https://metricraven.com/js/script.js", + "transferKb": 8.9, + "decodedKb": 19.3, + "encoding": "gzip", + "durationMs": 142, + "initiatorType": "script", + "protocol": "unknown" + } + ] + }, "databuddyAnalytics": { "totalTransferKb": 10.8, "totalDecodedKb": 29.4, diff --git a/playground/nuxt.config.ts b/playground/nuxt.config.ts index 919a5593c..18fec9409 100644 --- a/playground/nuxt.config.ts +++ b/playground/nuxt.config.ts @@ -38,6 +38,7 @@ export default defineNuxtConfig({ fathomAnalytics: { site: 'BRDEJWKJ' }, pulseAnalytics: { domain: 'example.com' }, statableAnalytics: { siteId: '123456' }, + metricravenAnalytics: { siteId: 'ana_pub_example' }, posthog: { apiKey: 'phc_CkMaDU6dr11eJoQdAiSJb1rC324dogk3T952gJ6fD9W' }, intercom: { app_id: 'akg5rmxb' }, crisp: { id: 'b1021910-7ace-425a-9ef5-07f49e5ce417' }, @@ -91,6 +92,7 @@ export default defineNuxtConfig({ fathomAnalytics: { site: 'BRDEJWKJ', trigger: 'manual' }, pulseAnalytics: { domain: 'example.com', trigger: 'manual' }, statableAnalytics: { siteId: '123456', trigger: 'manual' }, + metricravenAnalytics: { siteId: 'ana_pub_example', trigger: 'manual' }, cloudflareWebAnalytics: { token: 'ade278253a19413c9bd923b079870902', trigger: 'manual' }, matomoAnalytics: { matomoUrl: 'https://cdn.matomo.cloud', siteId: '1', trigger: 'manual' }, vercelAnalytics: { trigger: 'manual' }, diff --git a/playground/pages/index.vue b/playground/pages/index.vue index 30ce9ec03..6bae642d6 100644 --- a/playground/pages/index.vue +++ b/playground/pages/index.vue @@ -26,6 +26,7 @@ function getPlaygroundPath(script: any): string | null { 'rybbit-analytics': '/third-parties/rybbit-analytics', 'pulse-analytics': '/third-parties/pulse-analytics', 'statable-analytics': '/third-parties/statable-analytics', + 'metricraven-analytics': '/third-parties/metricraven-analytics', 'databuddy-analytics': '/third-parties/databuddy-analytics', 'umami-analytics': '/third-parties/umami-analytics', 'segment': '/third-parties/segment', diff --git a/playground/pages/third-parties/metricraven-analytics.vue b/playground/pages/third-parties/metricraven-analytics.vue new file mode 100644 index 000000000..2f3c20673 --- /dev/null +++ b/playground/pages/third-parties/metricraven-analytics.vue @@ -0,0 +1,105 @@ + + + diff --git a/test/e2e-dev/first-party.test.ts b/test/e2e-dev/first-party.test.ts index cdfe601cc..2bd634e66 100644 --- a/test/e2e-dev/first-party.test.ts +++ b/test/e2e-dev/first-party.test.ts @@ -666,6 +666,7 @@ describe('first-party privacy stripping', () => { // fathomAnalytics — bundle/proxy disabled (Fathom bot-detection flags self-hosted/proxied traffic, see #720) // pulseAnalytics — bundle only, no proxy (server-side visitor identity needs the real client IP) // statableAnalytics — bundle only, no proxy (server-side visitor identity needs the real client IP) + // metricravenAnalytics — bundle only, no proxy (cookieless visitor identity needs the real client IP) ]) /** @@ -940,6 +941,7 @@ describe('first-party privacy stripping', () => { // fathomAnalytics — bundle/proxy disabled in registry (see #720), script loads directly from CDN // pulseAnalytics — bundle only, no proxy in registry; beacons go direct to pulse-api.ciphera.net // statableAnalytics — bundle only, no proxy in registry; beacons go direct to statable.com/api/event + // metricravenAnalytics — bundle only, no proxy in registry; beacons go direct to metricraven.com/api/v1/collect it('intercom', async () => { const { captures, rawCaptures, proxyRequests, externalRequests, preClickProxyCount, postClickProxyCount } = await testProvider('intercom', '/intercom-test') @@ -1005,6 +1007,7 @@ describe('first-party privacy stripping', () => { { name: 'fathomAnalytics', path: '/fathom' }, { name: 'pulseAnalytics', path: '/pulse' }, { name: 'statableAnalytics', path: '/statable' }, + { name: 'metricravenAnalytics', path: '/metricraven' }, { name: 'intercom', path: '/intercom-test' }, { name: 'crisp', path: '/crisp-test' }, { name: 'posthog', path: '/posthog' }, @@ -1192,6 +1195,7 @@ describe('first-party privacy stripping', () => { { name: 'fathomAnalytics', path: '/fathom' }, { name: 'pulseAnalytics', path: '/pulse' }, { name: 'statableAnalytics', path: '/statable' }, + { name: 'metricravenAnalytics', path: '/metricraven' }, { name: 'intercom', path: '/intercom-test' }, { name: 'crisp', path: '/crisp-test' }, { name: 'posthog', path: '/posthog' }, @@ -1244,6 +1248,12 @@ describe('first-party privacy stripping', () => { expect(await script.getAttribute('src')).toContain('/_scripts/assets/') } + if (name === 'metricravenAnalytics') { + const script = page.locator('script[data-site-id="ana_pub_example"][data-api="https://metricraven.com/api/v1/collect"]') + expect(await script.count()).toBe(1) + expect(await script.getAttribute('src')).toContain('/_scripts/assets/') + } + // Click all buttons to trigger SDK interactions and generate proxy requests const buttons = await page.$$('button') for (const btn of buttons) { diff --git a/test/e2e/metricraven-analytics.test.ts b/test/e2e/metricraven-analytics.test.ts new file mode 100644 index 000000000..bb259e3eb --- /dev/null +++ b/test/e2e/metricraven-analytics.test.ts @@ -0,0 +1,31 @@ +import { createResolver } from '@nuxt/kit' +import { getBrowser, url } from '@nuxt/test-utils/e2e' +import { describe, expect, it } from 'vitest' +import { setupFixture } from '../utils/setup-fixture' + +const { resolve } = createResolver(import.meta.url) + +describe('metricraven analytics bundled script', async () => { + await setupFixture({ + rootDir: resolve('../fixtures/metricraven-analytics'), + browser: true, + build: true, + }) + + it('keeps the site ID, event endpoint and add-on base on the bundled script', async () => { + const page = await (await getBrowser()).newPage() + try { + await page.goto(url('/'), { waitUntil: 'domcontentloaded' }) + await page.waitForSelector('#status:has-text("loaded")', { timeout: 10000 }) + + const script = page.locator('script[data-site-id="ana_pub_example"][data-api="https://metricraven.com/api/v1/collect"][data-addons="https://metricraven.com/js/addons/"]') + expect(await script.count()).toBe(1) + expect(await script.getAttribute('src')).toContain('/_scripts/assets/') + // The tracker exposes its API even when it skips the visit (automated browser). + expect(await page.evaluate(() => typeof (window as any).metricraven?.track)).toBe('function') + } + finally { + await page.close() + } + }) +}) diff --git a/test/fixtures/first-party/nuxt.config.ts b/test/fixtures/first-party/nuxt.config.ts index 1a31691dc..23c8adc05 100644 --- a/test/fixtures/first-party/nuxt.config.ts +++ b/test/fixtures/first-party/nuxt.config.ts @@ -26,6 +26,7 @@ export default defineNuxtConfig({ fathomAnalytics: { site: 'BRDEJWKJ' }, pulseAnalytics: { domain: 'example.com' }, statableAnalytics: { siteId: '123456' }, + metricravenAnalytics: { siteId: 'ana_pub_example' }, posthog: { apiKey: 'phc_CkMaDU6dr11eJoQdAiSJb1rC324dogk3T952gJ6fD9W' }, intercom: { app_id: 'akg5rmxb' }, crisp: { id: 'b1021910-7ace-425a-9ef5-07f49e5ce417' }, @@ -73,6 +74,7 @@ export default defineNuxtConfig({ fathomAnalytics: { site: 'BRDEJWKJ', trigger: 'manual' }, pulseAnalytics: { domain: 'example.com', trigger: 'manual' }, statableAnalytics: { siteId: '123456', trigger: 'manual' }, + metricravenAnalytics: { siteId: 'ana_pub_example', trigger: 'manual' }, posthog: { apiKey: 'phc_CkMaDU6dr11eJoQdAiSJb1rC324dogk3T952gJ6fD9W', trigger: 'manual' }, intercom: { app_id: 'akg5rmxb', trigger: 'manual' }, crisp: { id: 'b1021910-7ace-425a-9ef5-07f49e5ce417', trigger: 'manual' }, diff --git a/test/fixtures/first-party/pages/index.vue b/test/fixtures/first-party/pages/index.vue index 556e5e5c1..8b63c4d2d 100644 --- a/test/fixtures/first-party/pages/index.vue +++ b/test/fixtures/first-party/pages/index.vue @@ -10,6 +10,7 @@
  • Fathom Analytics
  • Pulse Analytics
  • Statable Analytics
  • +
  • MetricRaven
  • Umami Analytics
  • PostHog
  • Rybbit Analytics
  • diff --git a/test/fixtures/first-party/pages/metricraven.vue b/test/fixtures/first-party/pages/metricraven.vue new file mode 100644 index 000000000..c2e2ad4bc --- /dev/null +++ b/test/fixtures/first-party/pages/metricraven.vue @@ -0,0 +1,32 @@ + + + diff --git a/test/fixtures/metricraven-analytics/nuxt.config.ts b/test/fixtures/metricraven-analytics/nuxt.config.ts new file mode 100644 index 000000000..8dbba7419 --- /dev/null +++ b/test/fixtures/metricraven-analytics/nuxt.config.ts @@ -0,0 +1,11 @@ +import { defineNuxtConfig } from 'nuxt/config' + +export default defineNuxtConfig({ + modules: ['@nuxt/scripts'], + scripts: { + registry: { + metricravenAnalytics: { siteId: 'ana_pub_example', trigger: 'manual' }, + }, + }, + compatibilityDate: '2024-07-05', +}) diff --git a/test/fixtures/metricraven-analytics/pages/index.vue b/test/fixtures/metricraven-analytics/pages/index.vue new file mode 100644 index 000000000..90610c995 --- /dev/null +++ b/test/fixtures/metricraven-analytics/pages/index.vue @@ -0,0 +1,11 @@ + + + diff --git a/test/types/types.test-d.ts b/test/types/types.test-d.ts index 4dfb4539b..ea1729cb5 100644 --- a/test/types/types.test-d.ts +++ b/test/types/types.test-d.ts @@ -44,6 +44,7 @@ describe('module options registry', () => { expectTypeOf().not.toBeAny() expectTypeOf().not.toBeAny() expectTypeOf().not.toBeAny() + expectTypeOf().not.toBeAny() expectTypeOf().not.toBeAny() expectTypeOf().not.toBeAny() expectTypeOf().not.toBeAny() diff --git a/test/unit/metricraven-analytics.test.ts b/test/unit/metricraven-analytics.test.ts new file mode 100644 index 000000000..74146ff35 --- /dev/null +++ b/test/unit/metricraven-analytics.test.ts @@ -0,0 +1,140 @@ +/** + * @vitest-environment happy-dom + */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { ref } from 'vue' +import { useScriptMetricRavenAnalytics } from '../../packages/script/src/runtime/registry/metricraven-analytics' + +const mocks = vi.hoisted(() => ({ + definition: undefined as any, + useRegistryScript: vi.fn(), +})) + +vi.mock('@unhead/vue', () => ({ useHead: vi.fn() })) + +vi.mock('../../packages/script/src/runtime/utils', () => ({ + useRegistryScript: mocks.useRegistryScript, +})) + +const SITE_ID = 'ana_pub_AbC123-xyz_9' + +function setup(options: Record = { siteId: SITE_ID }) { + mocks.useRegistryScript.mockImplementation((_key: string, factory: (o: any) => any) => { + mocks.definition = factory(options) + return { status: ref('awaitingLoad'), signal: new AbortController().signal, load: vi.fn() } + }) + useScriptMetricRavenAnalytics(options as any) + return { + scriptInput: mocks.definition.scriptInput as Record, + use: mocks.definition.scriptOptions.use as () => Record any>, + clientInit: mocks.definition.clientInit as (() => void) | undefined, + } +} + +function dataAttributes(scriptInput: Record) { + return Object.fromEntries(Object.entries(scriptInput).filter(([key, value]) => key.startsWith('data-') && value !== undefined)) +} + +describe('metricraven analytics', () => { + beforeEach(() => { + vi.clearAllMocks() + delete (window as any).metricraven + delete (window as any).metricravenConsent + }) + + it('loads the hosted tracker with the site id', () => { + const { scriptInput } = setup() + expect(scriptInput.src).toBe('https://metricraven.com/js/script.js') + expect(scriptInput['data-site-id']).toBe(SITE_ID) + }) + + it('pins the event endpoint and add-on base so bundling does not change them', () => { + // The tracker derives both from its own src. A bundled copy is served from + // the Nuxt origin, so the attributes have to carry them instead. + const { scriptInput } = setup() + expect(scriptInput['data-api']).toBe('https://metricraven.com/api/v1/collect') + expect(scriptInput['data-addons']).toBe('https://metricraven.com/js/addons/') + }) + + it('follows apiHost for the script, the endpoint and the add-ons', () => { + const { scriptInput } = setup({ siteId: SITE_ID, apiHost: 'https://a.example.com/' }) + expect(scriptInput.src).toBe('https://a.example.com/js/script.js') + expect(scriptInput['data-api']).toBe('https://a.example.com/api/v1/collect') + expect(scriptInput['data-addons']).toBe('https://a.example.com/js/addons/') + }) + + it('leaves a relative scriptUrl to the tracker and sends events to endpoint', () => { + const { scriptInput } = setup({ siteId: SITE_ID, scriptUrl: '/a/script', endpoint: '/a/event' }) + expect(scriptInput.src).toBe('/a/script') + expect(scriptInput['data-api']).toBe('/a/event') + expect(scriptInput['data-addons']).toBeUndefined() + }) + + it('uses metricraven.com add-ons for an absolute scriptUrl not served as /js/script.js', () => { + const { scriptInput } = setup({ siteId: SITE_ID, scriptUrl: 'https://example.com/stats/mr.js' }) + expect(scriptInput['data-api']).toBe('https://example.com/api/v1/collect') + expect(scriptInput['data-addons']).toBe('https://metricraven.com/js/addons/') + }) + + it('renders only the defaults without options', () => { + const { scriptInput } = setup() + expect(Object.keys(dataAttributes(scriptInput)).sort()).toEqual(['data-addons', 'data-api', 'data-site-id']) + }) + + it('maps every option to the tracker attribute', () => { + const { scriptInput } = setup({ + siteId: SITE_ID, + addonsUrl: '/a/addons/', + autoPageviews: false, + hashRouting: 'all', + stripQuery: true, + adConsent: true, + domain: 'example.com', + allowLocalhost: true, + allowedHostnames: ['app.example.io', ' shop.example.net ', ''], + identityToken: 'h.p.s', + autocapture: ['clicks', 'downloads'], + debug: true, + }) + expect(dataAttributes(scriptInput)).toEqual({ + 'data-site-id': SITE_ID, + 'data-api': 'https://metricraven.com/api/v1/collect', + 'data-addons': '/a/addons/', + 'data-auto-pageviews': 'false', + 'data-track-hash': 'all', + 'data-strip-query': 'true', + 'data-ad-consent': 'granted', + 'data-domain': 'example.com', + 'data-allow-localhost': 'true', + 'data-allowed-hostnames': 'app.example.io,shop.example.net', + 'data-identity-token': 'h.p.s', + 'data-autocapture': 'clicks,downloads', + 'data-debug': 'true', + }) + }) + + it('renders hashRouting true and autocapture false', () => { + const { scriptInput } = setup({ siteId: SITE_ID, hashRouting: true, autocapture: false }) + expect(scriptInput['data-track-hash']).toBe('true') + expect(scriptInput['data-autocapture']).toBe('false') + }) + + it('grants storage consent before the tracker starts when consent is set', () => { + expect(setup().clientInit).toBeUndefined() + const { clientInit } = setup({ siteId: SITE_ID, consent: true }) + clientInit!() + expect((window as any).metricravenConsent).toBe(true) + }) + + it('exposes the tracker global once loaded', () => { + const track = vi.fn() + const identify = vi.fn() + ;(window as any).metricraven = { track, identify, getVisitorId: () => 'v1' } + const api = setup().use() + api.track!('signup', { plan: 'pro' }) + api.identify!('42', { email: 'a@example.com' }) + expect(track).toHaveBeenCalledWith('signup', { plan: 'pro' }) + expect(identify).toHaveBeenCalledWith('42', { email: 'a@example.com' }) + expect(api.getVisitorId!()).toBe('v1') + }) +}) diff --git a/test/unit/metricraven-bundle-resolve.test.ts b/test/unit/metricraven-bundle-resolve.test.ts new file mode 100644 index 000000000..69af11638 --- /dev/null +++ b/test/unit/metricraven-bundle-resolve.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { getBundleResolve, registry } from '../../packages/script/src/registry' +import { MetricRavenAnalyticsOptions } from '../../packages/script/src/runtime/registry/schemas' + +async function getMetricRavenResolve() { + const all = await registry() + const script = all.find(s => s.registryKey === 'metricravenAnalytics')! + const resolve = getBundleResolve(script) + if (!resolve) + throw new Error('metricravenAnalytics bundle.resolve missing') + return resolve +} + +describe('metricravenAnalytics bundle.resolve', () => { + it('returns false for a missing siteId instead of throwing', async () => { + const resolve = await getMetricRavenResolve() + expect(resolve(undefined)).toBe(false) + expect(resolve({})).toBe(false) + }) + + it('bundles the hosted tracker', async () => { + const resolve = await getMetricRavenResolve() + expect(resolve({ siteId: 'ana_pub_x' })).toBe('https://metricraven.com/js/script.js') + }) + + it('bundles from apiHost', async () => { + const resolve = await getMetricRavenResolve() + expect(resolve({ siteId: 'ana_pub_x', apiHost: 'https://a.example.com/' })).toBe('https://a.example.com/js/script.js') + }) + + it('bundles an absolute scriptUrl and skips a relative one', async () => { + const resolve = await getMetricRavenResolve() + expect(resolve({ siteId: 'ana_pub_x', scriptUrl: 'https://cdn.example.com/mr.js' })).toBe('https://cdn.example.com/mr.js') + expect(resolve({ siteId: 'ana_pub_x', scriptUrl: '/a/script' })).toBe(false) + }) +}) + +describe('metricravenAnalytics dev validation', () => { + function validate(options: Record) { + return (MetricRavenAnalyticsOptions as any)['~standard'].validate(options) as { issues?: unknown[] } + } + + it('accepts a public site id', () => { + expect(validate({ siteId: 'ana_pub_AbC123-xyz_9' }).issues).toBeUndefined() + }) + + it.each(['', 'ana_pub_', 'abc', 'ana_sk_123', ' ana_pub_123 '])('rejects an invalid siteId: %s', (siteId) => { + expect(validate({ siteId }).issues?.length).toBeGreaterThan(0) + }) + + it('rejects an unknown autocapture kind', () => { + expect(validate({ siteId: 'ana_pub_x', autocapture: ['clicks', 'hovers'] }).issues?.length).toBeGreaterThan(0) + expect(validate({ siteId: 'ana_pub_x', autocapture: ['clicks', 'forms'] }).issues).toBeUndefined() + }) +}) diff --git a/test/unit/proxy-configs.test.ts b/test/unit/proxy-configs.test.ts index 8c9306e95..64af3a58a 100644 --- a/test/unit/proxy-configs.test.ts +++ b/test/unit/proxy-configs.test.ts @@ -386,6 +386,13 @@ describe('proxy configs', () => { expect(config).toBeUndefined() }) + it('does not return proxy config for metricravenAnalytics (cookieless visitor identity needs the real client IP)', async () => { + // Without storage consent MetricRaven derives the visitor ID from the client IP, + // which a proxy must pass in x-visitor-ip; the generic proxy would merge every visitor into one. + const config = (await getProxyConfigs()).metricravenAnalytics + expect(config).toBeUndefined() + }) + it('returns proxy config for intercom', async () => { const config = (await getProxyConfigs()).intercom expect(config).toBeDefined() @@ -465,6 +472,7 @@ describe('proxy configs', () => { expect(configs).not.toHaveProperty('fathomAnalytics') expect(configs).not.toHaveProperty('pulseAnalytics') expect(configs).not.toHaveProperty('statableAnalytics') + expect(configs).not.toHaveProperty('metricravenAnalytics') expect(configs).toHaveProperty('intercom') expect(configs).not.toHaveProperty('crisp') expect(configs).not.toHaveProperty('deskcrew') From 55ee49dcd10f4a9c891ed2c868772a9f6970ef42 Mon Sep 17 00:00:00 2001 From: Mariano Mino Date: Sat, 21 Nov 2026 18:02:07 +0100 Subject: [PATCH 2/4] fix(metricraven): derive endpoint defaults from a scriptInput.src override; playground key Co-Authored-By: Claude Opus 5.5 --- packages/script/src/registry.ts | 5 +++-- .../src/runtime/registry/metricraven-analytics.ts | 5 +++-- playground/pages/index.vue | 2 +- test/unit/metricraven-analytics.test.ts | 10 ++++++++-- test/unit/metricraven-bundle-resolve.test.ts | 1 + 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/script/src/registry.ts b/packages/script/src/registry.ts index c73e5cfad..1ff8afaf2 100644 --- a/packages/script/src/registry.ts +++ b/packages/script/src/registry.ts @@ -518,8 +518,9 @@ export async function registry(resolve?: (path: string) => Promise): Pro resolve: (options?: MetricRavenAnalyticsInput) => { if (!options?.siteId) return false - if (options.scriptUrl) - return /^https?:\/\//i.test(options.scriptUrl) ? options.scriptUrl : false + const custom = (options as any).scriptInput?.src || options.scriptUrl + if (custom) + return /^https?:\/\//i.test(custom) ? custom : false return `${(options.apiHost || 'https://metricraven.com').replace(/\/+$/, '')}/js/script.js` }, }, diff --git a/packages/script/src/runtime/registry/metricraven-analytics.ts b/packages/script/src/runtime/registry/metricraven-analytics.ts index 94608708d..9db41fcbf 100644 --- a/packages/script/src/runtime/registry/metricraven-analytics.ts +++ b/packages/script/src/runtime/registry/metricraven-analytics.ts @@ -95,9 +95,10 @@ function trackerDefaults(src: string): { endpoint?: string, addons?: string } { } export function useScriptMetricRavenAnalytics(_options?: MetricRavenAnalyticsInput) { - return useRegistryScript('metricravenAnalytics', (options) => { + return useRegistryScript('metricravenAnalytics', (options, ctx) => { const src = metricRavenScriptUrl(options) - const defaults = trackerDefaults(src) + // A `scriptInput.src` override replaces `src`, so derive the defaults from it. + const defaults = trackerDefaults(ctx.scriptInput?.src || src) const hosts = (options.allowedHostnames || []).map(h => h.trim()).filter(Boolean) return { scriptInput: { diff --git a/playground/pages/index.vue b/playground/pages/index.vue index 6bae642d6..9d427e95b 100644 --- a/playground/pages/index.vue +++ b/playground/pages/index.vue @@ -26,7 +26,7 @@ function getPlaygroundPath(script: any): string | null { 'rybbit-analytics': '/third-parties/rybbit-analytics', 'pulse-analytics': '/third-parties/pulse-analytics', 'statable-analytics': '/third-parties/statable-analytics', - 'metricraven-analytics': '/third-parties/metricraven-analytics', + 'metricraven': '/third-parties/metricraven-analytics', 'databuddy-analytics': '/third-parties/databuddy-analytics', 'umami-analytics': '/third-parties/umami-analytics', 'segment': '/third-parties/segment', diff --git a/test/unit/metricraven-analytics.test.ts b/test/unit/metricraven-analytics.test.ts index 74146ff35..7811cbc8f 100644 --- a/test/unit/metricraven-analytics.test.ts +++ b/test/unit/metricraven-analytics.test.ts @@ -19,8 +19,8 @@ vi.mock('../../packages/script/src/runtime/utils', () => ({ const SITE_ID = 'ana_pub_AbC123-xyz_9' function setup(options: Record = { siteId: SITE_ID }) { - mocks.useRegistryScript.mockImplementation((_key: string, factory: (o: any) => any) => { - mocks.definition = factory(options) + mocks.useRegistryScript.mockImplementation((_key: string, factory: (o: any, ctx: any) => any) => { + mocks.definition = factory(options, { scriptInput: options.scriptInput }) return { status: ref('awaitingLoad'), signal: new AbortController().signal, load: vi.fn() } }) useScriptMetricRavenAnalytics(options as any) @@ -76,6 +76,12 @@ describe('metricraven analytics', () => { expect(scriptInput['data-addons']).toBe('https://metricraven.com/js/addons/') }) + it('derives the defaults from an absolute scriptInput.src override', () => { + const { scriptInput } = setup({ siteId: SITE_ID, scriptInput: { src: 'https://a.example.com/js/script.js' } }) + expect(scriptInput['data-api']).toBe('https://a.example.com/api/v1/collect') + expect(scriptInput['data-addons']).toBe('https://a.example.com/js/addons/') + }) + it('renders only the defaults without options', () => { const { scriptInput } = setup() expect(Object.keys(dataAttributes(scriptInput)).sort()).toEqual(['data-addons', 'data-api', 'data-site-id']) diff --git a/test/unit/metricraven-bundle-resolve.test.ts b/test/unit/metricraven-bundle-resolve.test.ts index 69af11638..fb82223f0 100644 --- a/test/unit/metricraven-bundle-resolve.test.ts +++ b/test/unit/metricraven-bundle-resolve.test.ts @@ -32,6 +32,7 @@ describe('metricravenAnalytics bundle.resolve', () => { const resolve = await getMetricRavenResolve() expect(resolve({ siteId: 'ana_pub_x', scriptUrl: 'https://cdn.example.com/mr.js' })).toBe('https://cdn.example.com/mr.js') expect(resolve({ siteId: 'ana_pub_x', scriptUrl: '/a/script' })).toBe(false) + expect(resolve({ siteId: 'ana_pub_x', scriptInput: { src: 'https://a.example.com/js/script.js' } })).toBe('https://a.example.com/js/script.js') }) }) From ceb410c3abe7e4cda55e855bff4940de845bd3f7 Mon Sep 17 00:00:00 2001 From: Mariano Mino Date: Sat, 21 Nov 2026 18:10:06 +0100 Subject: [PATCH 3/4] fix(metricraven): keep endpoint defaults off scriptInput.src, which bundling rewrites Co-Authored-By: Claude Opus 5.5 --- packages/script/src/registry.ts | 5 ++--- .../src/runtime/registry/metricraven-analytics.ts | 7 ++++--- test/unit/metricraven-analytics.test.ts | 10 ++-------- test/unit/metricraven-bundle-resolve.test.ts | 1 - 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/packages/script/src/registry.ts b/packages/script/src/registry.ts index 1ff8afaf2..c73e5cfad 100644 --- a/packages/script/src/registry.ts +++ b/packages/script/src/registry.ts @@ -518,9 +518,8 @@ export async function registry(resolve?: (path: string) => Promise): Pro resolve: (options?: MetricRavenAnalyticsInput) => { if (!options?.siteId) return false - const custom = (options as any).scriptInput?.src || options.scriptUrl - if (custom) - return /^https?:\/\//i.test(custom) ? custom : false + if (options.scriptUrl) + return /^https?:\/\//i.test(options.scriptUrl) ? options.scriptUrl : false return `${(options.apiHost || 'https://metricraven.com').replace(/\/+$/, '')}/js/script.js` }, }, diff --git a/packages/script/src/runtime/registry/metricraven-analytics.ts b/packages/script/src/runtime/registry/metricraven-analytics.ts index 9db41fcbf..c327ddae8 100644 --- a/packages/script/src/runtime/registry/metricraven-analytics.ts +++ b/packages/script/src/runtime/registry/metricraven-analytics.ts @@ -95,10 +95,11 @@ function trackerDefaults(src: string): { endpoint?: string, addons?: string } { } export function useScriptMetricRavenAnalytics(_options?: MetricRavenAnalyticsInput) { - return useRegistryScript('metricravenAnalytics', (options, ctx) => { + return useRegistryScript('metricravenAnalytics', (options) => { const src = metricRavenScriptUrl(options) - // A `scriptInput.src` override replaces `src`, so derive the defaults from it. - const defaults = trackerDefaults(ctx.scriptInput?.src || src) + // Not derived from `scriptInput.src`: bundling rewrites it to the local + // asset path. A custom tracker URL goes through `scriptUrl` or `apiHost`. + const defaults = trackerDefaults(src) const hosts = (options.allowedHostnames || []).map(h => h.trim()).filter(Boolean) return { scriptInput: { diff --git a/test/unit/metricraven-analytics.test.ts b/test/unit/metricraven-analytics.test.ts index 7811cbc8f..74146ff35 100644 --- a/test/unit/metricraven-analytics.test.ts +++ b/test/unit/metricraven-analytics.test.ts @@ -19,8 +19,8 @@ vi.mock('../../packages/script/src/runtime/utils', () => ({ const SITE_ID = 'ana_pub_AbC123-xyz_9' function setup(options: Record = { siteId: SITE_ID }) { - mocks.useRegistryScript.mockImplementation((_key: string, factory: (o: any, ctx: any) => any) => { - mocks.definition = factory(options, { scriptInput: options.scriptInput }) + mocks.useRegistryScript.mockImplementation((_key: string, factory: (o: any) => any) => { + mocks.definition = factory(options) return { status: ref('awaitingLoad'), signal: new AbortController().signal, load: vi.fn() } }) useScriptMetricRavenAnalytics(options as any) @@ -76,12 +76,6 @@ describe('metricraven analytics', () => { expect(scriptInput['data-addons']).toBe('https://metricraven.com/js/addons/') }) - it('derives the defaults from an absolute scriptInput.src override', () => { - const { scriptInput } = setup({ siteId: SITE_ID, scriptInput: { src: 'https://a.example.com/js/script.js' } }) - expect(scriptInput['data-api']).toBe('https://a.example.com/api/v1/collect') - expect(scriptInput['data-addons']).toBe('https://a.example.com/js/addons/') - }) - it('renders only the defaults without options', () => { const { scriptInput } = setup() expect(Object.keys(dataAttributes(scriptInput)).sort()).toEqual(['data-addons', 'data-api', 'data-site-id']) diff --git a/test/unit/metricraven-bundle-resolve.test.ts b/test/unit/metricraven-bundle-resolve.test.ts index fb82223f0..69af11638 100644 --- a/test/unit/metricraven-bundle-resolve.test.ts +++ b/test/unit/metricraven-bundle-resolve.test.ts @@ -32,7 +32,6 @@ describe('metricravenAnalytics bundle.resolve', () => { const resolve = await getMetricRavenResolve() expect(resolve({ siteId: 'ana_pub_x', scriptUrl: 'https://cdn.example.com/mr.js' })).toBe('https://cdn.example.com/mr.js') expect(resolve({ siteId: 'ana_pub_x', scriptUrl: '/a/script' })).toBe(false) - expect(resolve({ siteId: 'ana_pub_x', scriptInput: { src: 'https://a.example.com/js/script.js' } })).toBe('https://a.example.com/js/script.js') }) }) From 0ac20839f7510c336106ec1c3c5023f7d8db3873 Mon Sep 17 00:00:00 2001 From: Mariano Mino Date: Sat, 21 Nov 2026 18:24:37 +0100 Subject: [PATCH 4/4] chore: retrigger CI (reCAPTCHA e2e flake) Co-Authored-By: Claude Opus 5.5