@vulcantech/analytics 0.1.1 → 0.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.
package/dist/tags.mjs CHANGED
@@ -2,6 +2,12 @@ import Script from 'next/script';
2
2
  import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
3
3
 
4
4
  // src/tags.tsx
5
+ var FORM_CONVERSION_SEND_TO_GLOBAL = "__vtFormConversionSendTo";
6
+ var ENHANCED_CONVERSIONS_GLOBAL = "__vtEnhancedConversions";
7
+ var PHONE_CONVERSION_SEND_TO_GLOBAL = "__vtPhoneConversionSendTo";
8
+ function js(value) {
9
+ return JSON.stringify(value).replace(/</g, "\\u003c");
10
+ }
5
11
  async function fetchTrackingTags() {
6
12
  const CMS_URL = process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
7
13
  const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;
@@ -28,7 +34,12 @@ async function fetchTrackingTags() {
28
34
  const merged = {
29
35
  ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || void 0,
30
36
  googleAdsId: cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || void 0,
31
- metaPixelId: cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || void 0
37
+ metaPixelId: cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || void 0,
38
+ formConversionSendTo: cms?.formConversionSendTo || process.env.NEXT_PUBLIC_FORM_CONVERSION_SEND_TO || void 0,
39
+ phoneConversionSendTo: cms?.phoneConversionSendTo || process.env.NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO || void 0,
40
+ callConversionSendTo: cms?.callConversionSendTo || process.env.NEXT_PUBLIC_CALL_CONVERSION_SEND_TO || void 0,
41
+ callConversionNumber: cms?.callConversionNumber || process.env.NEXT_PUBLIC_CALL_CONVERSION_NUMBER || void 0,
42
+ enhancedConversions: cms?.enhancedConversions === true || process.env.NEXT_PUBLIC_ENHANCED_CONVERSIONS === "true"
32
43
  };
33
44
  if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {
34
45
  return null;
@@ -38,9 +49,35 @@ async function fetchTrackingTags() {
38
49
  async function CMSTags() {
39
50
  const tags = await fetchTrackingTags();
40
51
  if (!tags) return null;
41
- const { ga4Id, googleAdsId, metaPixelId } = tags;
52
+ const {
53
+ ga4Id,
54
+ googleAdsId,
55
+ metaPixelId,
56
+ formConversionSendTo,
57
+ phoneConversionSendTo,
58
+ callConversionSendTo,
59
+ callConversionNumber,
60
+ enhancedConversions
61
+ } = tags;
42
62
  const googleIds = [ga4Id, googleAdsId].filter(Boolean);
43
63
  const firstGoogleId = googleIds[0];
64
+ const sendToLine = formConversionSendTo ? `window.${FORM_CONVERSION_SEND_TO_GLOBAL} = ${JSON.stringify(
65
+ formConversionSendTo
66
+ ).replace(/</g, "\\u003c")};` : "";
67
+ const extraLines = [
68
+ phoneConversionSendTo ? `window.${PHONE_CONVERSION_SEND_TO_GLOBAL} = ${js(phoneConversionSendTo)};` : "",
69
+ enhancedConversions ? `window.${ENHANCED_CONVERSIONS_GLOBAL} = true;` : "",
70
+ // Google's forwarding-number swap. Runs once per page load, after the
71
+ // plain configs — never re-run on route changes (each config call on a
72
+ // GA4 id would send another page view).
73
+ callConversionSendTo && callConversionNumber ? `gtag('config', ${js(callConversionSendTo)}, {
74
+ phone_conversion_number: ${js(callConversionNumber)},
75
+ phone_conversion_callback: function (formatted, mobile) {
76
+ window.__vtPhone = { formatted: formatted, mobile: mobile };
77
+ window.dispatchEvent(new Event('vt-phone'));
78
+ }
79
+ });` : ""
80
+ ].filter(Boolean).join("\n");
44
81
  return /* @__PURE__ */ jsxs(Fragment, { children: [
45
82
  firstGoogleId && /* @__PURE__ */ jsxs(Fragment, { children: [
46
83
  /* @__PURE__ */ jsx(
@@ -55,7 +92,9 @@ async function CMSTags() {
55
92
  /* @__PURE__ */ jsx(Script, { id: "vt-gtag-init", strategy: "afterInteractive", children: `window.dataLayer = window.dataLayer || [];
56
93
  function gtag(){dataLayer.push(arguments);}
57
94
  gtag('js', new Date());
58
- ${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}` })
95
+ ${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}
96
+ ${sendToLine}
97
+ ${extraLines}` })
59
98
  ] }),
60
99
  metaPixelId && /* @__PURE__ */ jsxs(Fragment, { children: [
61
100
  /* @__PURE__ */ jsx(Script, { id: "vt-meta-pixel", strategy: "afterInteractive", children: `!function(f,b,e,v,n,t,s)
package/dist/tags.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tags.tsx"],"names":[],"mappings":";;;;AA2DA,eAAsB,iBAAA,GAAkD;AACtE,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,kBAAA,IAAsB,2BAAA;AAClD,EAAA,MAAM,UAAA,GAAa,QAAQ,GAAA,CAAI,qBAAA;AAC/B,EAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,kBAAA;AAE5B,EAAA,IAAI,GAAA,GAA2B,IAAA;AAE/B,EAAA,IAAI,cAAc,OAAA,EAAS;AACzB,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,GAAS,IAAI,eAAA,CAAgB;AAAA,QACjC,SAAA,EAAW,UAAA;AAAA,QACX,MAAA,EAAQ;AAAA,OACT,CAAA;AACD,MAAA,MAAM,IAAA,GAAqB;AAAA,QACzB,IAAA,EAAM,EAAE,UAAA,EAAY,EAAA,EAAI,MAAM,CAAC,CAAA,cAAA,EAAiB,UAAU,CAAA,CAAE,CAAA;AAAE,OAChE;AACA,MAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,sBAAA,EAAyB,MAAM,IAAI,IAAI,CAAA;AACzE,MAAA,IAAI,IAAI,EAAA,EAAI;AACV,QAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,EAAK;AAC7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ACX;AAAA,sBACA,GAAA,CAAC,MAAA,EAAA,EAAO,EAAA,EAAG,cAAA,EAAe,UAAS,kBAAA,EAChC,QAAA,EAAA,CAAA;AAAA;AAAA;AAAA,EAGX,SAAA,CAAU,GAAA,CAAI,CAAC,EAAA,KAAO,CAAA,gBAAA,EAAmB,EAAE,CAAA,GAAA,CAAK,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,EACpD;AAAA,KAAA,EACF,CAAA;AAAA,IAED,+BACC,IAAA,CAAA,QAAA,EAAA,EACE,QAAA,EAAA;AAAA,sBAAA,GAAA,CAAC,MAAA,EAAA,EAAO,EAAA,EAAG,eAAA,EAAgB,QAAA,EAAS,kBAAA,EACjC,QAAA,EAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAA,EAQE,WAAW,CAAA;AAAA,yBAAA,CAAA,EAEhB,CAAA;AAAA,0BACC,UAAA,EAAA,EACC,QAAA,kBAAA,GAAA;AAAA,QAAC,KAAA;AAAA,QAAA;AAAA,UACC,MAAA,EAAO,GAAA;AAAA,UACP,KAAA,EAAM,GAAA;AAAA,UACN,KAAA,EAAO,EAAE,OAAA,EAAS,MAAA,EAAO;AAAA,UACzB,GAAA,EAAK,kCAAkC,WAAW,CAAA,uBAAA,CAAA;AAAA,UAClD,GAAA,EAAI;AAAA;AAAA,OACN,EACF;AAAA,KAAA,EACF;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"tags.mjs","sourcesContent":["/**\n * CMS-driven third-party tracking-tag injection (server-side).\n *\n * Fetches tag IDs (GA4 / Google Ads / Meta Pixel) configured for this\n * project in vulcantech-cms and renders the corresponding third-party\n * <Script> loaders — giving consumer sites \"codeless\" tag setup with no\n * hand-rolled gtag/fbq wiring in their own layout.\n *\n * This module is a React Server Component — do NOT add \"use client\".\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)\n *\n * Optional env fallbacks (used only when the CMS omits a field):\n * NEXT_PUBLIC_GA_ID → ga4Id\n * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId\n * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId\n */\n\nimport Script from \"next/script\";\n\n/** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */\nexport interface TrackingTags {\n /** GA4 measurement ID, e.g. \"G-XXXXXXXXXX\". */\n ga4Id?: string;\n /** Google Ads conversion ID, e.g. \"AW-XXXXXXXXX\". */\n googleAdsId?: string;\n /** Meta (Facebook) Pixel ID. */\n metaPixelId?: string;\n}\n\n/** Shape returned by GET {CMS_URL}/api/analytics/config. */\ninterface ConfigResponse {\n config: TrackingTags | null;\n}\n\n/**\n * fetch init with Next's ISR options. Passed as a typed variable (not an\n * object literal) so TS won't excess-property-check the `next` key — this\n * package doesn't load Next's global RequestInit augmentation. Mirrors the\n * collections/blog packages.\n */\ntype IsrFetchInit = RequestInit & {\n next?: { revalidate?: number; tags?: string[] };\n};\n\n/**\n * Fetch the tracking-tag config for this project from the CMS, merging in\n * env fallbacks per field (CMS value wins when present).\n *\n * Never throws — tags must never break a page build. Returns `null` when\n * all three tag IDs end up empty (nothing configured anywhere), otherwise a\n * {@link TrackingTags} object.\n *\n * The fetch is ISR-cached (`revalidate: 60`) and tagged\n * `tracking-tags:{projectId}` so the CMS can purge it on config change.\n */\nexport async function fetchTrackingTags(): Promise<TrackingTags | null> {\n const CMS_URL = process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n let cms: TrackingTags | null = null;\n\n if (PROJECT_ID && API_KEY) {\n try {\n const params = new URLSearchParams({\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n });\n const init: IsrFetchInit = {\n next: { revalidate: 60, tags: [`tracking-tags:${PROJECT_ID}`] },\n };\n const res = await fetch(`${CMS_URL}/api/analytics/config?${params}`, init);\n if (res.ok) {\n const json = (await res.json()) as ConfigResponse;\n cms = json.config ?? null;\n }\n } catch {\n // Silent fail — fall through to env fallbacks below.\n cms = null;\n }\n }\n\n // CMS value wins per field; fill any gap from public env vars.\n const merged: TrackingTags = {\n ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || undefined,\n googleAdsId:\n cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,\n metaPixelId:\n cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,\n };\n\n if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {\n return null;\n }\n return merged;\n}\n\n/**\n * Drop-in server component that injects the project's tracking tags.\n *\n * Place once in your root layout's `<body>`:\n *\n * import { CMSTags } from \"@vulcantech/analytics/tags\";\n * // <body> ... <CMSTags /> ... </body>\n *\n * Renders one shared gtag.js loader + init (config'd for every present\n * Google ID: GA4 and/or Google Ads), the standard Meta Pixel bootstrap +\n * <noscript> fallback, or `null` when nothing is configured.\n */\nexport async function CMSTags() {\n const tags = await fetchTrackingTags();\n if (!tags) return null;\n\n const { ga4Id, googleAdsId, metaPixelId } = tags;\n const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];\n const firstGoogleId = googleIds[0];\n\n return (\n <>\n {firstGoogleId && (\n <>\n <Script\n id=\"vt-gtag\"\n async\n src={`https://www.googletagmanager.com/gtag/js?id=${firstGoogleId}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"vt-gtag-init\" strategy=\"afterInteractive\">\n {`window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n${googleIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\")}`}\n </Script>\n </>\n )}\n {metaPixelId && (\n <>\n <Script id=\"vt-meta-pixel\" strategy=\"afterInteractive\">\n {`!function(f,b,e,v,n,t,s)\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\nn.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];\ns.parentNode.insertBefore(t,s)}(window, document,'script',\n'https://connect.facebook.net/en_US/fbevents.js');\nfbq('init', '${metaPixelId}');\nfbq('track', 'PageView');`}\n </Script>\n <noscript>\n <img\n height=\"1\"\n width=\"1\"\n style={{ display: \"none\" }}\n src={`https://www.facebook.com/tr?id=${metaPixelId}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n )}\n </>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/tags.tsx"],"names":[],"mappings":";;;;AAyFA,IAAM,8BAAA,GAAiC,0BAAA;AAGvC,IAAM,2BAAA,GAA8B,yBAAA;AAGpC,IAAM,+BAAA,GAAkC,2BAAA;AAGxC,SAAS,GAAG,KAAA,EAAwB;AAClC,EAAA,OAAO,KAAK,SAAA,CAAU,KAAK,CAAA,CAAE,OAAA,CAAQ,MAAM,SAAS,CAAA;AACtD;AAwCA,eAAsB,iBAAA,GAAkD;AACtE,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,kBAAA,IAAsB,2BAAA;AAClD,EAAA,MAAM,UAAA,GAAa,QAAQ,GAAA,CAAI,qBAAA;AAC/B,EAAA,MAAM,OAAA,GAAU,QAAQ,GAAA,CAAI,kBAAA;AAE5B,EAAA,IAAI,GAAA,GAA2B,IAAA;AAE/B,EAAA,IAAI,cAAc,OAAA,EAAS;AACzB,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,GAAS,IAAI,eAAA,CAAgB;AAAA,QACjC,SAAA,EAAW,UAAA;AAAA,QACX,MAAA,EAAQ;AAAA,OACT,CAAA;AACD,MAAA,MAAM,IAAA,GAAqB;AAAA,QACzB,IAAA,EAAM,EAAE,UAAA,EAA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J","file":"tags.mjs","sourcesContent":["/**\n * CMS-driven third-party tracking-tag injection (server-side).\n *\n * Fetches tag IDs (GA4 / Google Ads / Meta Pixel) configured for this\n * project in vulcantech-cms and renders the corresponding third-party\n * <Script> loaders — giving consumer sites \"codeless\" tag setup with no\n * hand-rolled gtag/fbq wiring in their own layout.\n *\n * This module is a React Server Component — do NOT add \"use client\".\n *\n * Required env vars:\n * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID — project ID for this site\n * VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)\n *\n * Optional env fallbacks (used only when the CMS omits a field):\n * NEXT_PUBLIC_GA_ID → ga4Id\n * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId\n * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId\n * NEXT_PUBLIC_FORM_CONVERSION_SEND_TO → formConversionSendTo\n * NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO → phoneConversionSendTo\n * NEXT_PUBLIC_CALL_CONVERSION_SEND_TO → callConversionSendTo\n * NEXT_PUBLIC_CALL_CONVERSION_NUMBER → callConversionNumber\n * NEXT_PUBLIC_ENHANCED_CONVERSIONS=true → enhancedConversions\n *\n * All four of the last are CMS dashboard fields too (BL-1059). Note that\n * enhancedConversions is ON when either source says so — an env `true`\n * cannot be switched off from the CMS; unset the env var for that.\n */\n\nimport Script from \"next/script\";\n\n/**\n * Tracking tag IDs resolved for a project (CMS value wins, else env fallback).\n *\n * Public IDs only — the CMS strips its internal `enabled` and `updatedAt`\n * fields before returning the config to a consumer site.\n *\n * The documented formats are validated CMS-side when a staff user saves the\n * config in the dashboard. Values arriving from the NEXT_PUBLIC_* env\n * fallbacks are NOT validated by this package and are injected verbatim.\n */\nexport interface TrackingTags {\n /** GA4 measurement ID. CMS-validated against /^G-[A-Z0-9]{4,14}$/. */\n ga4Id?: string;\n /** Google Ads conversion ID. CMS-validated against /^AW-\\d{6,12}$/. */\n googleAdsId?: string;\n /** Meta (Facebook) Pixel ID — numeric string. CMS-validated against /^\\d{6,20}$/. */\n metaPixelId?: string;\n /**\n * Site-wide Google Ads `send_to` label fired when a `@vulcantech/forms`\n * form submits successfully, e.g. `\"AW-18321257894/AbC-D3fGhIjKlmNoP\"`.\n * CMS-validated against /^AW-\\d{6,12}\\/[A-Za-z0-9_-]{6,64}$/.\n *\n * Not a tag loader: {@link CMSTags} publishes it on\n * `window.__vtFormConversionSendTo`, where the forms package reads it. A\n * form's own `submitConfig.conversion.sendTo` overrides it.\n */\n formConversionSendTo?: string;\n /**\n * Google Ads `send_to` label fired on every `tel:` link tap. Published on\n * `window.__vtPhoneConversionSendTo`, where `trackPhoneClick` reads it.\n */\n phoneConversionSendTo?: string;\n /**\n * Google forwarding-number (\"website call conversion\") label, e.g.\n * `\"AW-123/AbC\"`. With {@link callConversionNumber} set, CMSTags configures\n * Google's number swap; render numbers through `PhoneLink` so the swapped\n * number survives React re-renders.\n */\n callConversionSendTo?: string;\n /**\n * The phone number exactly as the page displays it (e.g. `\"602.904.9109\"`).\n * Google only swaps a number that matches this string.\n */\n callConversionNumber?: string;\n /**\n * Opt into Google Ads enhanced conversions: `@vulcantech/forms` sends the\n * lead's email/phone (hashed by gtag) with the form conversion. The site's\n * privacy policy must disclose it.\n */\n enhancedConversions?: boolean;\n}\n\n/**\n * `window` key the site-wide form-conversion label is published on. Must stay\n * in sync with `FORM_CONVERSION_SEND_TO_GLOBAL` in `@vulcantech/forms` — the\n * two packages are independent, so this is a mirrored constant, not an import.\n */\nconst FORM_CONVERSION_SEND_TO_GLOBAL = \"__vtFormConversionSendTo\";\n\n/** Mirrors `ENHANCED_CONVERSIONS_GLOBAL` in `@vulcantech/forms`. */\nconst ENHANCED_CONVERSIONS_GLOBAL = \"__vtEnhancedConversions\";\n\n/** Read by `trackPhoneClick` in ./tracker. */\nconst PHONE_CONVERSION_SEND_TO_GLOBAL = \"__vtPhoneConversionSendTo\";\n\n/** Serialize a value into inline script source; `<` can never close the tag. */\nfunction js(value: unknown): string {\n return JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n}\n\n/** Shape returned by GET {CMS_URL}/api/analytics/config. */\ninterface ConfigResponse {\n config: TrackingTags | null;\n}\n\n/**\n * fetch init with Next's ISR options. Passed as a typed variable (not an\n * object literal) so TS won't excess-property-check the `next` key — this\n * package doesn't load Next's global RequestInit augmentation. Mirrors the\n * collections/blog packages.\n */\ntype IsrFetchInit = RequestInit & {\n next?: { revalidate?: number; tags?: string[] };\n};\n\n/**\n * Fetch the tracking-tag config for this project from the CMS, merging in\n * env fallbacks per field (CMS value wins when present).\n *\n * Server-only: reads VULCANTECH_API_KEY, so never call it from client code.\n *\n * Never throws — tags must never break a page build. CMS errors (unreachable,\n * non-2xx, missing env, key lacking the `analytics:read` scope) are swallowed\n * and the env fallbacks apply instead. Returns `null` — NOT `{}` — when all\n * three tag IDs end up empty, otherwise a {@link TrackingTags} object.\n *\n * ⚠ Turning tracking tags OFF in the CMS does not necessarily disable them.\n * The CMS returns `config: null` for \"disabled\" and \"never configured\" alike,\n * and this function then fills every field from NEXT_PUBLIC_GA_ID /\n * NEXT_PUBLIC_GOOGLE_ADS_ID / NEXT_PUBLIC_META_PIXEL_ID. A site with those env\n * vars set keeps firing its tags after the CMS switch is off; disabling it\n * there requires unsetting the env vars and redeploying. Sites with no\n * NEXT_PUBLIC_* fallbacks honor the toggle as expected.\n *\n * The fetch is ISR-cached (`revalidate: 60`) and tagged\n * `tracking-tags:{projectId}` so the CMS can purge it on config change — so a\n * CMS value change reaches the site within ~60s with no redeploy.\n */\nexport async function fetchTrackingTags(): Promise<TrackingTags | null> {\n const CMS_URL = process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;\n const API_KEY = process.env.VULCANTECH_API_KEY;\n\n let cms: TrackingTags | null = null;\n\n if (PROJECT_ID && API_KEY) {\n try {\n const params = new URLSearchParams({\n projectId: PROJECT_ID,\n apiKey: API_KEY,\n });\n const init: IsrFetchInit = {\n next: { revalidate: 60, tags: [`tracking-tags:${PROJECT_ID}`] },\n };\n const res = await fetch(`${CMS_URL}/api/analytics/config?${params}`, init);\n if (res.ok) {\n const json = (await res.json()) as ConfigResponse;\n cms = json.config ?? null;\n }\n } catch {\n // Silent fail — fall through to env fallbacks below.\n cms = null;\n }\n }\n\n // CMS value wins per field; fill any gap from public env vars.\n const merged: TrackingTags = {\n ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || undefined,\n googleAdsId:\n cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,\n metaPixelId:\n cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,\n formConversionSendTo:\n cms?.formConversionSendTo ||\n process.env.NEXT_PUBLIC_FORM_CONVERSION_SEND_TO ||\n undefined,\n phoneConversionSendTo:\n cms?.phoneConversionSendTo ||\n process.env.NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO ||\n undefined,\n callConversionSendTo:\n cms?.callConversionSendTo ||\n process.env.NEXT_PUBLIC_CALL_CONVERSION_SEND_TO ||\n undefined,\n callConversionNumber:\n cms?.callConversionNumber ||\n process.env.NEXT_PUBLIC_CALL_CONVERSION_NUMBER ||\n undefined,\n enhancedConversions:\n cms?.enhancedConversions === true ||\n process.env.NEXT_PUBLIC_ENHANCED_CONVERSIONS === \"true\",\n };\n\n // A `send_to` label on its own is not enough to render anything — it needs\n // the Google tag that `googleAdsId`/`ga4Id` loads — so it does not count\n // towards \"something is configured\".\n if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {\n return null;\n }\n return merged;\n}\n\n/**\n * Drop-in server component that injects the project's tracking tags.\n *\n * Place once in your root layout's `<body>`:\n *\n * import { CMSTags } from \"@vulcantech/analytics/tags\";\n * // <body> ... <CMSTags /> ... </body>\n *\n * Async React Server Component — do NOT wrap it in a \"use client\" component.\n *\n * Renders, via next/script with `strategy=\"afterInteractive\"`:\n * - ONE shared gtag.js loader keyed to the FIRST present Google ID, plus an\n * inline init that gtag('config', …)s every present Google ID. Google Ads\n * rides the GA4 loader — there is no separate gtag/js?id=AW-… request.\n * The same inline script publishes `formConversionSendTo` (when set) on\n * `window.__vtFormConversionSendTo`, which is where `@vulcantech/forms`\n * looks for the Ads label to fire on a successful submission. Likewise\n * `phoneConversionSendTo` → `window.__vtPhoneConversionSendTo` and\n * `enhancedConversions` → `window.__vtEnhancedConversions`. With a\n * `callConversionSendTo` + `callConversionNumber`, it also configures\n * Google's forwarding-number swap; the callback stores the number on\n * `window.__vtPhone` and dispatches `vt-phone` for `PhoneLink`.\n * - The standard inline Meta Pixel bootstrap with fbq('track','PageView')\n * and a <noscript> tracking-pixel <img>.\n * - `null` when nothing is configured (see {@link fetchTrackingTags}).\n *\n * Because it uses next/script, mounting it in <body> is correct; it does not\n * need to be in <head>.\n *\n * ⚠ NO CONSENT GATING. Tags load as soon as the page hydrates. This component\n * provides no CMP/GDPR gate and must not be mounted unconditionally on a site\n * that requires consent before loading third-party trackers.\n */\nexport async function CMSTags() {\n const tags = await fetchTrackingTags();\n if (!tags) return null;\n\n const {\n ga4Id,\n googleAdsId,\n metaPixelId,\n formConversionSendTo,\n phoneConversionSendTo,\n callConversionSendTo,\n callConversionNumber,\n enhancedConversions,\n } = tags;\n const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];\n const firstGoogleId = googleIds[0];\n // Published for @vulcantech/forms to read on submit success. Serialized\n // rather than interpolated raw because the NEXT_PUBLIC_* fallback is not\n // CMS-validated; `<` is escaped so a value can never close the <script>.\n const sendToLine = formConversionSendTo\n ? `window.${FORM_CONVERSION_SEND_TO_GLOBAL} = ${JSON.stringify(\n formConversionSendTo,\n ).replace(/</g, \"\\\\u003c\")};`\n : \"\";\n const extraLines = [\n phoneConversionSendTo\n ? `window.${PHONE_CONVERSION_SEND_TO_GLOBAL} = ${js(phoneConversionSendTo)};`\n : \"\",\n enhancedConversions ? `window.${ENHANCED_CONVERSIONS_GLOBAL} = true;` : \"\",\n // Google's forwarding-number swap. Runs once per page load, after the\n // plain configs — never re-run on route changes (each config call on a\n // GA4 id would send another page view).\n callConversionSendTo && callConversionNumber\n ? `gtag('config', ${js(callConversionSendTo)}, {\n phone_conversion_number: ${js(callConversionNumber)},\n phone_conversion_callback: function (formatted, mobile) {\n window.__vtPhone = { formatted: formatted, mobile: mobile };\n window.dispatchEvent(new Event('vt-phone'));\n }\n});`\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\");\n\n return (\n <>\n {firstGoogleId && (\n <>\n <Script\n id=\"vt-gtag\"\n async\n src={`https://www.googletagmanager.com/gtag/js?id=${firstGoogleId}`}\n strategy=\"afterInteractive\"\n />\n <Script id=\"vt-gtag-init\" strategy=\"afterInteractive\">\n {`window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n${googleIds.map((id) => `gtag('config', '${id}');`).join(\"\\n\")}\n${sendToLine}\n${extraLines}`}\n </Script>\n </>\n )}\n {metaPixelId && (\n <>\n <Script id=\"vt-meta-pixel\" strategy=\"afterInteractive\">\n {`!function(f,b,e,v,n,t,s)\n{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\nn.callMethod.apply(n,arguments):n.queue.push(arguments)};\nif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\nn.queue=[];t=b.createElement(e);t.async=!0;\nt.src=v;s=b.getElementsByTagName(e)[0];\ns.parentNode.insertBefore(t,s)}(window, document,'script',\n'https://connect.facebook.net/en_US/fbevents.js');\nfbq('init', '${metaPixelId}');\nfbq('track', 'PageView');`}\n </Script>\n <noscript>\n <img\n height=\"1\"\n width=\"1\"\n style={{ display: \"none\" }}\n src={`https://www.facebook.com/tr?id=${metaPixelId}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n )}\n </>\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vulcantech/analytics",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Lightweight first-party analytics tracker for Next.js — page views, custom events, form conversions. No cookies, no fingerprinting, <1KB gzipped.",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",
@@ -11,19 +11,19 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.mjs",
13
13
  "require": "./dist/index.js",
14
- "default": "./src/index.tsx"
14
+ "default": "./dist/index.mjs"
15
15
  },
16
16
  "./route": {
17
17
  "types": "./dist/route.d.ts",
18
18
  "import": "./dist/route.mjs",
19
19
  "require": "./dist/route.js",
20
- "default": "./src/route.ts"
20
+ "default": "./dist/route.mjs"
21
21
  },
22
22
  "./tags": {
23
23
  "types": "./dist/tags.d.ts",
24
24
  "import": "./dist/tags.mjs",
25
25
  "require": "./dist/tags.js",
26
- "default": "./src/tags.tsx"
26
+ "default": "./dist/tags.mjs"
27
27
  }
28
28
  },
29
29
  "files": [
@@ -35,7 +35,8 @@
35
35
  "build": "tsup",
36
36
  "dev": "tsup --watch",
37
37
  "prepublishOnly": "npm run build",
38
- "typecheck": "tsc --noEmit"
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "jest"
39
40
  },
40
41
  "peerDependencies": {
41
42
  "react": ">=18.0.0",
@@ -43,7 +44,7 @@
43
44
  },
44
45
  "devDependencies": {
45
46
  "@types/react": "^19",
46
- "next": "16.0.10",
47
+ "next": "16.3.7",
47
48
  "react": "^19.0.0",
48
49
  "tsup": "^8.0.0",
49
50
  "typescript": "^5.9.3"
@@ -60,7 +61,7 @@
60
61
  ],
61
62
  "repository": {
62
63
  "type": "git",
63
- "url": "https://github.com/vulcantech/vulcantech"
64
+ "url": "git+https://github.com/vulcantech/vulcantech.git"
64
65
  },
65
66
  "author": "VulcanTech <vulcantechnologies.io@gmail.com>",
66
67
  "publishConfig": {
@@ -3,9 +3,19 @@
3
3
  /**
4
4
  * Drop-in analytics component for Next.js App Router.
5
5
  *
6
- * Place in your root layout — tracks page views on every route change.
7
- * Wrapped in Suspense to satisfy Next.js 16's requirement that
8
- * useSearchParams is inside a Suspense boundary.
6
+ * Place ONCE in your root layout — tracks page views on every route change.
7
+ * Renders `null`, and wraps itself in Suspense to satisfy Next.js 16's
8
+ * requirement that useSearchParams sits inside a Suspense boundary, so it is
9
+ * safe to drop directly into a server layout despite being a client component.
10
+ *
11
+ * Firing rules: exactly ONE trackPageView() on mount (the isFirstRender guard
12
+ * below stops the mount from double-firing), then one per `pathname` OR
13
+ * `searchParams` change. Because search params are watched, `/x?page=2` counts
14
+ * as a separate pageview from `/x`.
15
+ *
16
+ * Mounting this also activates the module-level side effects in `./tracker` —
17
+ * `window.__vtTrack` (which @vulcantech/forms uses for automatic form
18
+ * conversions) and the delegated tel:/mailto: click listener.
9
19
  *
10
20
  * Usage:
11
21
  * import { AnalyticsTracker } from "@vulcantech/analytics";
@@ -0,0 +1,69 @@
1
+ "use client";
2
+
3
+ import { useSyncExternalStore, type AnchorHTMLAttributes, type ReactNode } from "react";
4
+
5
+ /** The number Google's forwarding-number swap hands back, if any. */
6
+ interface SwappedPhone {
7
+ formatted: string;
8
+ mobile: string;
9
+ }
10
+
11
+ type PhoneWindow = Window & { __vtPhone?: SwappedPhone };
12
+
13
+ function subscribe(onChange: () => void): () => void {
14
+ window.addEventListener("vt-phone", onChange);
15
+ return () => window.removeEventListener("vt-phone", onChange);
16
+ }
17
+
18
+ function getSnapshot(): SwappedPhone | null {
19
+ return (window as PhoneWindow).__vtPhone ?? null;
20
+ }
21
+
22
+ /** The server always renders the real number. */
23
+ function getServerSnapshot(): SwappedPhone | null {
24
+ return null;
25
+ }
26
+
27
+ export interface PhoneLinkProps
28
+ extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children" | "prefix"> {
29
+ /** The number as displayed, e.g. `"602.904.9109"`. */
30
+ display: string;
31
+ /** E.164 dial string without `tel:`, e.g. `"+16029049109"`. */
32
+ tel: string;
33
+ /** Rendered before the number, e.g. `"Or call · "` or an icon. */
34
+ prefix?: ReactNode;
35
+ /** Rendered after the number. */
36
+ suffix?: ReactNode;
37
+ }
38
+
39
+ /**
40
+ * A `tel:` link that shows Google's forwarding number to visitors who arrived
41
+ * from an ad.
42
+ *
43
+ * `CMSTags` configures Google's number swap (when the project has a
44
+ * `callConversionSendTo` + `callConversionNumber`) with a callback that stores
45
+ * the forwarding number on `window.__vtPhone` and fires `vt-phone`; this
46
+ * component re-renders on that event. Doing it in React rather than letting
47
+ * gtag rewrite the DOM matters: React would put the original number back on
48
+ * the next render or client-side navigation.
49
+ *
50
+ * Everyone else — and the server render — sees `display` / `tel`. Taps are
51
+ * tracked by the delegated listener `AnalyticsTracker` installs; don't add an
52
+ * `onClick` tracker here or the tap double-counts.
53
+ *
54
+ * @param props.display Number as shown on the page (must match `callConversionNumber`).
55
+ * @param props.tel E.164 dial string, without the `tel:` scheme.
56
+ * @param props.prefix Optional content before the number.
57
+ * @param props.suffix Optional content after the number.
58
+ */
59
+ export function PhoneLink({ display, tel, prefix, suffix, ...rest }: PhoneLinkProps) {
60
+ const swapped = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
61
+ const mobile = swapped?.mobile ? swapped.mobile : tel;
62
+ return (
63
+ <a {...rest} href={`tel:${mobile}`}>
64
+ {prefix}
65
+ {swapped?.formatted || display}
66
+ {suffix}
67
+ </a>
68
+ );
69
+ }
package/src/index.tsx CHANGED
@@ -4,9 +4,11 @@ export {
4
4
  trackFormView,
5
5
  trackFormSubmit,
6
6
  trackPhoneClick,
7
+ trackPhoneSwap,
7
8
  trackEmailClick,
8
9
  track404,
9
10
  type AnalyticsEvent,
10
11
  } from "./tracker";
11
12
 
12
13
  export { AnalyticsTracker } from "./AnalyticsTracker";
14
+ export { PhoneLink, type PhoneLinkProps } from "./PhoneLink";
package/src/route.ts CHANGED
@@ -9,6 +9,13 @@
9
9
  * VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
10
10
  * VULCANTECH_PROJECT_ID — project ID for this site
11
11
  * VULCANTECH_API_KEY — API key for this site
12
+ *
13
+ * The API key must carry the `analytics:write` scope — the scope the CMS's
14
+ * POST /api/analytics enforces. This is a DIFFERENT scope from the
15
+ * `analytics:read` that CMSTags needs for tag config; a site doing both needs
16
+ * both on the one key. A key missing `analytics:write` drops every event while
17
+ * this route still answers 204 (see POST below), so the misconfiguration is
18
+ * invisible from the browser — verify ingestion in the CMS dashboard.
12
19
  */
13
20
 
14
21
  import { NextRequest, NextResponse } from "next/server";
@@ -40,6 +47,26 @@ export async function OPTIONS() {
40
47
  return new NextResponse(null, { status: 204, headers: corsHeaders });
41
48
  }
42
49
 
50
+ /**
51
+ * Forward one tracker event to the CMS, stamped with this site's project ID,
52
+ * API key, any CDN-provided geo headers, and the visitor's User-Agent.
53
+ *
54
+ * Without the visitor's UA the CMS sees this server's Node fetch UA, buckets
55
+ * every proxied visit as browser/OS "Other", and its bot filter never fires
56
+ * (BL-704). It is sent twice: as the outbound `User-Agent` header (what CMS
57
+ * builds before BL-704 read, and what the hand-rolled app proxies send) and as
58
+ * `ua` in the body, which the CMS prefers and trusts only on a validated key.
59
+ *
60
+ * Status contract:
61
+ * 503 — VULCANTECH_PROJECT_ID or VULCANTECH_API_KEY is unset.
62
+ * 400 — the request body is not parseable JSON.
63
+ * 204 — EVERYTHING else, including when the CMS was unreachable, rejected
64
+ * the event, or dropped it (bad scope, bot user agent, rate limit).
65
+ *
66
+ * So a 204 is not evidence of ingestion. This is deliberate: the forward is
67
+ * awaited but its result is discarded, because analytics must never block or
68
+ * break a page.
69
+ */
43
70
  export async function POST(req: NextRequest) {
44
71
  const CMS_URL =
45
72
  process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
@@ -58,12 +85,14 @@ export async function POST(req: NextRequest) {
58
85
  }
59
86
 
60
87
  const geo = extractGeo(req);
88
+ const ua = req.headers.get("user-agent") || "";
61
89
 
62
90
  try {
63
91
  await fetch(`${CMS_URL}/api/analytics`, {
64
92
  method: "POST",
65
93
  headers: {
66
94
  "Content-Type": "application/json",
95
+ "User-Agent": ua,
67
96
  "X-Forwarded-For":
68
97
  req.headers.get("x-forwarded-for") ||
69
98
  req.headers.get("x-real-ip") ||
@@ -74,6 +103,7 @@ export async function POST(req: NextRequest) {
74
103
  projectId: PROJECT_ID,
75
104
  apiKey: API_KEY,
76
105
  geo,
106
+ ua,
77
107
  }),
78
108
  cache: "no-store",
79
109
  });
package/src/tags.tsx CHANGED
@@ -14,21 +14,90 @@
14
14
  * VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)
15
15
  *
16
16
  * Optional env fallbacks (used only when the CMS omits a field):
17
- * NEXT_PUBLIC_GA_ID → ga4Id
18
- * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId
19
- * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId
17
+ * NEXT_PUBLIC_GA_ID → ga4Id
18
+ * NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId
19
+ * NEXT_PUBLIC_META_PIXEL_ID → metaPixelId
20
+ * NEXT_PUBLIC_FORM_CONVERSION_SEND_TO → formConversionSendTo
21
+ * NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO → phoneConversionSendTo
22
+ * NEXT_PUBLIC_CALL_CONVERSION_SEND_TO → callConversionSendTo
23
+ * NEXT_PUBLIC_CALL_CONVERSION_NUMBER → callConversionNumber
24
+ * NEXT_PUBLIC_ENHANCED_CONVERSIONS=true → enhancedConversions
25
+ *
26
+ * All four of the last are CMS dashboard fields too (BL-1059). Note that
27
+ * enhancedConversions is ON when either source says so — an env `true`
28
+ * cannot be switched off from the CMS; unset the env var for that.
20
29
  */
21
30
 
22
31
  import Script from "next/script";
23
32
 
24
- /** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */
33
+ /**
34
+ * Tracking tag IDs resolved for a project (CMS value wins, else env fallback).
35
+ *
36
+ * Public IDs only — the CMS strips its internal `enabled` and `updatedAt`
37
+ * fields before returning the config to a consumer site.
38
+ *
39
+ * The documented formats are validated CMS-side when a staff user saves the
40
+ * config in the dashboard. Values arriving from the NEXT_PUBLIC_* env
41
+ * fallbacks are NOT validated by this package and are injected verbatim.
42
+ */
25
43
  export interface TrackingTags {
26
- /** GA4 measurement ID, e.g. "G-XXXXXXXXXX". */
44
+ /** GA4 measurement ID. CMS-validated against /^G-[A-Z0-9]{4,14}$/. */
27
45
  ga4Id?: string;
28
- /** Google Ads conversion ID, e.g. "AW-XXXXXXXXX". */
46
+ /** Google Ads conversion ID. CMS-validated against /^AW-\d{6,12}$/. */
29
47
  googleAdsId?: string;
30
- /** Meta (Facebook) Pixel ID. */
48
+ /** Meta (Facebook) Pixel ID — numeric string. CMS-validated against /^\d{6,20}$/. */
31
49
  metaPixelId?: string;
50
+ /**
51
+ * Site-wide Google Ads `send_to` label fired when a `@vulcantech/forms`
52
+ * form submits successfully, e.g. `"AW-18321257894/AbC-D3fGhIjKlmNoP"`.
53
+ * CMS-validated against /^AW-\d{6,12}\/[A-Za-z0-9_-]{6,64}$/.
54
+ *
55
+ * Not a tag loader: {@link CMSTags} publishes it on
56
+ * `window.__vtFormConversionSendTo`, where the forms package reads it. A
57
+ * form's own `submitConfig.conversion.sendTo` overrides it.
58
+ */
59
+ formConversionSendTo?: string;
60
+ /**
61
+ * Google Ads `send_to` label fired on every `tel:` link tap. Published on
62
+ * `window.__vtPhoneConversionSendTo`, where `trackPhoneClick` reads it.
63
+ */
64
+ phoneConversionSendTo?: string;
65
+ /**
66
+ * Google forwarding-number ("website call conversion") label, e.g.
67
+ * `"AW-123/AbC"`. With {@link callConversionNumber} set, CMSTags configures
68
+ * Google's number swap; render numbers through `PhoneLink` so the swapped
69
+ * number survives React re-renders.
70
+ */
71
+ callConversionSendTo?: string;
72
+ /**
73
+ * The phone number exactly as the page displays it (e.g. `"602.904.9109"`).
74
+ * Google only swaps a number that matches this string.
75
+ */
76
+ callConversionNumber?: string;
77
+ /**
78
+ * Opt into Google Ads enhanced conversions: `@vulcantech/forms` sends the
79
+ * lead's email/phone (hashed by gtag) with the form conversion. The site's
80
+ * privacy policy must disclose it.
81
+ */
82
+ enhancedConversions?: boolean;
83
+ }
84
+
85
+ /**
86
+ * `window` key the site-wide form-conversion label is published on. Must stay
87
+ * in sync with `FORM_CONVERSION_SEND_TO_GLOBAL` in `@vulcantech/forms` — the
88
+ * two packages are independent, so this is a mirrored constant, not an import.
89
+ */
90
+ const FORM_CONVERSION_SEND_TO_GLOBAL = "__vtFormConversionSendTo";
91
+
92
+ /** Mirrors `ENHANCED_CONVERSIONS_GLOBAL` in `@vulcantech/forms`. */
93
+ const ENHANCED_CONVERSIONS_GLOBAL = "__vtEnhancedConversions";
94
+
95
+ /** Read by `trackPhoneClick` in ./tracker. */
96
+ const PHONE_CONVERSION_SEND_TO_GLOBAL = "__vtPhoneConversionSendTo";
97
+
98
+ /** Serialize a value into inline script source; `<` can never close the tag. */
99
+ function js(value: unknown): string {
100
+ return JSON.stringify(value).replace(/</g, "\\u003c");
32
101
  }
33
102
 
34
103
  /** Shape returned by GET {CMS_URL}/api/analytics/config. */
@@ -50,12 +119,24 @@ type IsrFetchInit = RequestInit & {
50
119
  * Fetch the tracking-tag config for this project from the CMS, merging in
51
120
  * env fallbacks per field (CMS value wins when present).
52
121
  *
53
- * Never throws — tags must never break a page build. Returns `null` when
54
- * all three tag IDs end up empty (nothing configured anywhere), otherwise a
55
- * {@link TrackingTags} object.
122
+ * Server-only: reads VULCANTECH_API_KEY, so never call it from client code.
123
+ *
124
+ * Never throws — tags must never break a page build. CMS errors (unreachable,
125
+ * non-2xx, missing env, key lacking the `analytics:read` scope) are swallowed
126
+ * and the env fallbacks apply instead. Returns `null` — NOT `{}` — when all
127
+ * three tag IDs end up empty, otherwise a {@link TrackingTags} object.
128
+ *
129
+ * ⚠ Turning tracking tags OFF in the CMS does not necessarily disable them.
130
+ * The CMS returns `config: null` for "disabled" and "never configured" alike,
131
+ * and this function then fills every field from NEXT_PUBLIC_GA_ID /
132
+ * NEXT_PUBLIC_GOOGLE_ADS_ID / NEXT_PUBLIC_META_PIXEL_ID. A site with those env
133
+ * vars set keeps firing its tags after the CMS switch is off; disabling it
134
+ * there requires unsetting the env vars and redeploying. Sites with no
135
+ * NEXT_PUBLIC_* fallbacks honor the toggle as expected.
56
136
  *
57
137
  * The fetch is ISR-cached (`revalidate: 60`) and tagged
58
- * `tracking-tags:{projectId}` so the CMS can purge it on config change.
138
+ * `tracking-tags:{projectId}` so the CMS can purge it on config change — so a
139
+ * CMS value change reaches the site within ~60s with no redeploy.
59
140
  */
60
141
  export async function fetchTrackingTags(): Promise<TrackingTags | null> {
61
142
  const CMS_URL = process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
@@ -91,8 +172,30 @@ export async function fetchTrackingTags(): Promise<TrackingTags | null> {
91
172
  cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,
92
173
  metaPixelId:
93
174
  cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,
175
+ formConversionSendTo:
176
+ cms?.formConversionSendTo ||
177
+ process.env.NEXT_PUBLIC_FORM_CONVERSION_SEND_TO ||
178
+ undefined,
179
+ phoneConversionSendTo:
180
+ cms?.phoneConversionSendTo ||
181
+ process.env.NEXT_PUBLIC_PHONE_CONVERSION_SEND_TO ||
182
+ undefined,
183
+ callConversionSendTo:
184
+ cms?.callConversionSendTo ||
185
+ process.env.NEXT_PUBLIC_CALL_CONVERSION_SEND_TO ||
186
+ undefined,
187
+ callConversionNumber:
188
+ cms?.callConversionNumber ||
189
+ process.env.NEXT_PUBLIC_CALL_CONVERSION_NUMBER ||
190
+ undefined,
191
+ enhancedConversions:
192
+ cms?.enhancedConversions === true ||
193
+ process.env.NEXT_PUBLIC_ENHANCED_CONVERSIONS === "true",
94
194
  };
95
195
 
196
+ // A `send_to` label on its own is not enough to render anything — it needs
197
+ // the Google tag that `googleAdsId`/`ga4Id` loads — so it does not count
198
+ // towards "something is configured".
96
199
  if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {
97
200
  return null;
98
201
  }
@@ -107,17 +210,75 @@ export async function fetchTrackingTags(): Promise<TrackingTags | null> {
107
210
  * import { CMSTags } from "@vulcantech/analytics/tags";
108
211
  * // <body> ... <CMSTags /> ... </body>
109
212
  *
110
- * Renders one shared gtag.js loader + init (config'd for every present
111
- * Google ID: GA4 and/or Google Ads), the standard Meta Pixel bootstrap +
112
- * <noscript> fallback, or `null` when nothing is configured.
213
+ * Async React Server Component — do NOT wrap it in a "use client" component.
214
+ *
215
+ * Renders, via next/script with `strategy="afterInteractive"`:
216
+ * - ONE shared gtag.js loader keyed to the FIRST present Google ID, plus an
217
+ * inline init that gtag('config', …)s every present Google ID. Google Ads
218
+ * rides the GA4 loader — there is no separate gtag/js?id=AW-… request.
219
+ * The same inline script publishes `formConversionSendTo` (when set) on
220
+ * `window.__vtFormConversionSendTo`, which is where `@vulcantech/forms`
221
+ * looks for the Ads label to fire on a successful submission. Likewise
222
+ * `phoneConversionSendTo` → `window.__vtPhoneConversionSendTo` and
223
+ * `enhancedConversions` → `window.__vtEnhancedConversions`. With a
224
+ * `callConversionSendTo` + `callConversionNumber`, it also configures
225
+ * Google's forwarding-number swap; the callback stores the number on
226
+ * `window.__vtPhone` and dispatches `vt-phone` for `PhoneLink`.
227
+ * - The standard inline Meta Pixel bootstrap with fbq('track','PageView')
228
+ * and a <noscript> tracking-pixel <img>.
229
+ * - `null` when nothing is configured (see {@link fetchTrackingTags}).
230
+ *
231
+ * Because it uses next/script, mounting it in <body> is correct; it does not
232
+ * need to be in <head>.
233
+ *
234
+ * ⚠ NO CONSENT GATING. Tags load as soon as the page hydrates. This component
235
+ * provides no CMP/GDPR gate and must not be mounted unconditionally on a site
236
+ * that requires consent before loading third-party trackers.
113
237
  */
114
238
  export async function CMSTags() {
115
239
  const tags = await fetchTrackingTags();
116
240
  if (!tags) return null;
117
241
 
118
- const { ga4Id, googleAdsId, metaPixelId } = tags;
242
+ const {
243
+ ga4Id,
244
+ googleAdsId,
245
+ metaPixelId,
246
+ formConversionSendTo,
247
+ phoneConversionSendTo,
248
+ callConversionSendTo,
249
+ callConversionNumber,
250
+ enhancedConversions,
251
+ } = tags;
119
252
  const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];
120
253
  const firstGoogleId = googleIds[0];
254
+ // Published for @vulcantech/forms to read on submit success. Serialized
255
+ // rather than interpolated raw because the NEXT_PUBLIC_* fallback is not
256
+ // CMS-validated; `<` is escaped so a value can never close the <script>.
257
+ const sendToLine = formConversionSendTo
258
+ ? `window.${FORM_CONVERSION_SEND_TO_GLOBAL} = ${JSON.stringify(
259
+ formConversionSendTo,
260
+ ).replace(/</g, "\\u003c")};`
261
+ : "";
262
+ const extraLines = [
263
+ phoneConversionSendTo
264
+ ? `window.${PHONE_CONVERSION_SEND_TO_GLOBAL} = ${js(phoneConversionSendTo)};`
265
+ : "",
266
+ enhancedConversions ? `window.${ENHANCED_CONVERSIONS_GLOBAL} = true;` : "",
267
+ // Google's forwarding-number swap. Runs once per page load, after the
268
+ // plain configs — never re-run on route changes (each config call on a
269
+ // GA4 id would send another page view).
270
+ callConversionSendTo && callConversionNumber
271
+ ? `gtag('config', ${js(callConversionSendTo)}, {
272
+ phone_conversion_number: ${js(callConversionNumber)},
273
+ phone_conversion_callback: function (formatted, mobile) {
274
+ window.__vtPhone = { formatted: formatted, mobile: mobile };
275
+ window.dispatchEvent(new Event('vt-phone'));
276
+ }
277
+ });`
278
+ : "",
279
+ ]
280
+ .filter(Boolean)
281
+ .join("\n");
121
282
 
122
283
  return (
123
284
  <>
@@ -133,7 +294,9 @@ export async function CMSTags() {
133
294
  {`window.dataLayer = window.dataLayer || [];
134
295
  function gtag(){dataLayer.push(arguments);}
135
296
  gtag('js', new Date());
136
- ${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}`}
297
+ ${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}
298
+ ${sendToLine}
299
+ ${extraLines}`}
137
300
  </Script>
138
301
  </>
139
302
  )}