diff --git a/.ai/instructions.md b/.ai/instructions.md index 5239d30df..afc70d8bb 100644 --- a/.ai/instructions.md +++ b/.ai/instructions.md @@ -106,7 +106,7 @@ Supporting: **Types** (`src/types/`) for value objects, context objects, and dom - **No private instance methods** — a class has `private readonly` fields and public methods; a helper is a `private static` method or a module-level function. - **No middlemen** — a method does something with each argument (reads it, transforms it, or combines it with the object's own state); no method only forwards to another call, and no layer re-exposes a service one to one. - **Functional core, imperative shell** — a step reads every fact it needs first, decides as a pure function over that data, then does its I/O. `execute` is the script of the run and the only place that speaks; prompts word the data they are handed and decide nothing; a value with several outcomes (`ShareHook`, `SnapshotFetch`, `ActionResult`) offers `match` over named handlers, so a caller that leaves one out fails to compile; contexts answer data and never print. -- **Good code is not more functions** — a step's logic stays together where it reads as one thing; a function is split out only when it is used twice, when it separates a decision from I/O, or when its name says something the reader would otherwise work out. A one-line call does not get a wrapper. +- **Good code is not more functions** — a step's logic stays together where it reads as one thing; a function is split out only when it is used twice, when it separates a decision from I/O, or when its name says something the reader would otherwise work out. Even then, a function or method whose boilerplate (its doc comment, signature and closing brace) has more characters than its body is an unnecessary abstraction, such as a wrapper around a one-line call: inline it. - **One prompts class per action** — wording is repeated per class rather than shared through a prompt module. - **Flag descriptions match the docs** — a flag's `description` (which the generated README carries) and its row in apimatic-docs' CLI Reference (`v4/src/content/apimatic-cli/cli-reference.mdx`) say the same words; change both, or flag the mismatch. - **Telemetry** — After `outro(result)`, commands optionally track failures via `result.match({ success: () => {}, failed: async () => { await new TelemetryService(configDir).trackEvent(new SomeFailedEvent(...), shell) }, cancelled: () => {}, actionRequired: () => {} })`. Event classes extend `DomainEvent` (`src/types/events/`). Only the `failed` handler is populated; the others are no-ops. diff --git a/README.md b/README.md index 8ee8c6b4f..799856540 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,8 @@ FLAGS -i, --input= [default: ./] path to the parent directory containing the 'src' directory, which includes API specifications and configuration files. -k, --auth-key= override current authentication state with an authentication key. - --no-analytics leave out the Google Tag Manager and Google Analytics tags set in 'portal.analytics'. + --no-analytics leave out the tags set in 'portal.analytics' and each script in 'portal.scripts' whose + category is 'analytics' or 'marketing', and hand no event to the scripts that stay. --zip write the generated portal as a .zip archive. DESCRIPTION @@ -347,7 +348,8 @@ FLAGS -k, --auth-key= override current authentication state with an authentication key. -o, --open open the portal in the default browser. -p, --port=23513 [default: 23513] port to serve the portal on. - --no-analytics leave out the Google Tag Manager and Google Analytics tags set in 'portal.analytics'. + --no-analytics leave out the tags set in 'portal.analytics' and each script in 'portal.scripts' whose + category is 'analytics' or 'marketing', and hand no event to the scripts that stay. DESCRIPTION Preview your API Documentation Portal with live reload. diff --git a/apimatic.schema.json b/apimatic.schema.json index 78ea007da..dcdd3da61 100644 --- a/apimatic.schema.json +++ b/apimatic.schema.json @@ -38,6 +38,11 @@ "description": "A path relative to 'src' inside the 'static' directory, for example 'static/images/logo.png'.", "pattern": "^\\s*(?:\\.[\\\\/])?static(?:[\\\\/](?!\\.{1,2}(?:[\\\\/]|\\s*$))[^\\\\/]*[^\\\\/\\s][^\\\\/]*)+\\s*$" }, + "httpsAddress": { + "type": "string", + "description": "An address starting with 'https://' and a host, with no spaces.", + "pattern": "^[hH][tT][tT][pP][sS]://[^\\s/\\\\?#]+(?:[/?#]\\S*)?$" + }, "color": { "type": "string", "description": "#rgb or #rrggbb, for example '#1d4ed8'.", @@ -226,6 +231,19 @@ } } }, + "googleConsentMode": { + "type": "object", + "description": "Starts Google's own tags in Google's Consent Mode: they load at once, set no cookies and mark every hit as denied until your consent tool calls gtag('consent', 'update'). Other vendors' tags inside a Google Tag Manager container need consent checks of their own there. Set it when a consent banner decides what is tracked. It holds back no script listed in 'scripts'.", + "additionalProperties": false, + "required": ["default"], + "properties": { + "default": { + "type": "string", + "enum": ["denied"], + "description": "What the tags take a reader's answer to be until your consent tool gives one." + } + } + }, "keepQueryParams": { "type": "array", "description": "Your own link tags to keep in reported page addresses. Campaign (utm_), ad-click and cross-domain tags are kept already; every other query parameter is dropped.", @@ -250,10 +268,40 @@ } } }, + "scripts": { + "type": "array", + "description": "Other vendors' scripts and widgets, loaded on every page in the listed order, except the OAuth callback page. They get the portal's events from window.apimatic.analytics.subscribe(). Any listed script can read what readers type into the API playground, so list only vendors you trust.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["src", "category"], + "properties": { + "src": { + "description": "An address starting with 'https://' and a host, with no spaces, or a file in the 'static' directory, for example 'static/analytics.js'.", + "anyOf": [ + { + "$ref": "#/definitions/httpsAddress" + }, + { + "$ref": "#/definitions/staticPath" + } + ] + }, + "category": { + "type": "string", + "description": "What the script is for. --no-analytics leaves out the 'analytics' and 'marketing' scripts.", + "enum": ["necessary", "functional", "analytics", "marketing"] + } + } + } + }, "pluginUrl": { - "type": "string", - "description": "Where the context plugin is hosted, starting with 'https://' and with no spaces. The Context Plugin page installs it from here, and the portal carries no copy of its own.", - "pattern": "^[hH][tT][tT][pP][sS]://[^\\s/?#]+(?:[/?#]\\S*)?$" + "allOf": [ + { + "$ref": "#/definitions/httpsAddress" + } + ], + "description": "Where the context plugin is hosted, starting with 'https://' and with no spaces. The Context Plugin page installs it from here, and the portal carries no copy of its own." } } }, diff --git a/portal-template/src/components/code-copy.tsx b/portal-template/src/components/code-copy.tsx index 4414d5388..4c57b2f72 100644 --- a/portal-template/src/components/code-copy.tsx +++ b/portal-template/src/components/code-copy.tsx @@ -7,7 +7,7 @@ import { analytics } from '@/lib/portal-analytics'; type Actions = NonNullable; export const reportCodeCopy = (language: string) => - analytics.report('docs_code_copy', { language: languageId(language) }); + analytics.report('docs_code_copy', { code_language: languageId(language) }); // Fumadocs' own, which any Actions a block is given replaces. const DefaultActions: Actions = ({ className, children }) => ( diff --git a/portal-template/src/components/sdk-actions.tsx b/portal-template/src/components/sdk-actions.tsx index 541e21229..32393a6c1 100644 --- a/portal-template/src/components/sdk-actions.tsx +++ b/portal-template/src/components/sdk-actions.tsx @@ -77,7 +77,7 @@ export function DownloadLink({ href, className, language, children }: Readonly analytics.report('docs_sdk_download', { language: languageId(language) })} + onClick={() => analytics.report('docs_sdk_download', { sdk_language: languageId(language) })} > {children} diff --git a/portal-template/src/lib/analytics.ts b/portal-template/src/lib/analytics.ts index 5d5a9b922..4f3a64d04 100644 --- a/portal-template/src/lib/analytics.ts +++ b/portal-template/src/lib/analytics.ts @@ -1,6 +1,7 @@ +import { EventFeed } from './event-feed'; import { isOAuthCallbackPath } from './oauth-callback'; -import type { PortalAnalytics } from './portal-types'; -import { type Adapter, adapters, insertTags } from './vendor-tags'; +import type { PortalAnalytics, PortalScript } from './portal-types'; +import { type Adapter, adapters, insertTags, queueConsentDefaults, scriptsInHead } from './vendor-tags'; /** The query parameters an ad or mail platform reads from an address itself; a customer adds names and removes none. */ const KEPT_PREFIXES = ['utm_', 'hsa_']; @@ -26,9 +27,10 @@ export interface PortalEvents { docs_page_view: { page_title: string }; docs_markdown_copy: Record; docs_plugin_install: Record; - docs_sdk_download: { language: string }; - docs_code_copy: { language: string }; - docs_search: { search_term: string; result: string; result_count: number }; + // Neither is named `language`: gtag takes that name on an event for the reader's own language. + docs_sdk_download: { sdk_language: string }; + docs_code_copy: { code_language: string }; + docs_search: { search_term: string; picked_result: string; result_count: number }; docs_not_found: { page_referrer: string }; /** `status` is always text: the HTTP status in digits, or `client_error` for a request that never reached the API. */ docs_api_request: { endpoint: string; status: string; duration_ms: number }; @@ -37,11 +39,27 @@ export type PortalEventName = keyof PortalEvents; type DataLayerEntry = { docs: null } | { event: PortalEventName; docs: Readonly> }; +/** A symbol, so the window holds it under no name a script comes across and builds on. */ +const WINDOW_ANALYTICS = Symbol.for('apimatic.portal.analytics'); + +/** + * One per `Window` object (https://developer.mozilla.org/en-US/docs/Web/API/Window), which a reload replaces. + * Every instance in it shares this one: a config save under `portal serve` makes a second. + */ +interface WindowAnalytics { + /** The settings and scripts the window started with. */ + started: string; + feed: EventFeed; + /** The address of every script the head held at the start, and of each tag and script inserted since. */ + inserted: Set; +} + declare global { interface Window { dataLayer?: unknown[]; - /** Held by the window: a config save under `portal serve` evaluates this module again. */ - portalAnalyticsStarted?: string; + [WINDOW_ANALYTICS]?: WindowAnalytics; + /** What customers' scripts are given: `subscribe()` and nothing else. */ + apimatic?: { analytics?: Pick }; } } @@ -57,34 +75,60 @@ export function pageLocation(href: string, keep: readonly string[]): string { return url.href; } +/** Whether `host` took `analytics` as its own property: a frozen object does not, nor one that fixed the name. */ +function putOn(host: unknown, analytics: Pick): boolean { + const property = { value: analytics, writable: true, enumerable: true, configurable: true }; + return Object(host) === host && Reflect.defineProperty(host as object, 'analytics', property); +} + export class Analytics { private readonly live: Adapter[]; + /** The window's, once `start()` has made it or joined it: no other method reads the global. */ + private windowAnalytics: WindowAnalytics | undefined; private lastPageView: string | null = null; private previousPageView: string | null = null; private lastNotFound: string | null = null; - public constructor(private readonly settings: PortalAnalytics) { + public constructor(private readonly settings: PortalAnalytics, private readonly scripts: PortalScript[]) { this.live = Object.values(adapters) .map((build) => build(settings)) .filter((adapter) => adapter !== null); } public start(): void { - const settings = JSON.stringify(this.settings); - if (window.portalAnalyticsStarted === settings) return; - // Other vendors after a config save: only a fresh page holds exactly their tags. - if (window.portalAnalyticsStarted !== undefined) { - window.location.reload(); + const started = JSON.stringify([this.settings, this.scripts]); + const existing = window[WINDOW_ANALYTICS]; + if (existing !== undefined) { + // Other vendors or scripts after a config save: only a fresh window holds exactly their tags. + if (existing.started === started) this.windowAnalytics = existing; + else window.location.reload(); return; } - window.portalAnalyticsStarted = settings; + const feed = new EventFeed(); + const inserted = new Set(scriptsInHead()); + this.windowAnalytics = { started, feed, inserted }; + window[WINDOW_ANALYTICS] = this.windowAnalytics; const dataLayer = (window.dataLayer ??= []); + if (this.settings.googleConsentMode !== null) queueConsentDefaults(dataLayer); for (const adapter of this.live) adapter.setup(dataLayer); - insertTags(this.live); + // Ours whatever the window held there first, and `subscribe` alone, bound so a script may call it on its own. + const analytics = Object.freeze({ subscribe: feed.subscribe.bind(feed) }); + try { + // On the host's own object if it takes one: a copy lacks its class's methods and is not the object it holds. + if (!putOn(window.apimatic, analytics)) window.apimatic = { ...window.apimatic, analytics }; + } catch (error) { + // A host may have locked the name. Thrown later, so it shows in the console and the bundle goes on loading. + setTimeout(() => { + throw error; + }); + } + insertTags(this.live, this.scripts, inserted); } /** `href` is the page the event belongs to, when the caller saw the address move on first. */ public report(name: E, params: PortalEvents[E], href = window.location.href): void { + // A `--no-analytics` build reports nothing, even to the data layer: a container a kept script loads reads it. + if (this.settings.events === 'off') return; if (isOAuthCallbackPath(new URL(href).pathname)) return; const docs = { ...params, page_location: pageLocation(href, this.settings.keepQueryParams) }; const dataLayer = (window.dataLayer ??= []); @@ -92,12 +136,14 @@ export class Analytics { dataLayer.push({ docs: null } satisfies DataLayerEntry); dataLayer.push({ event: name, docs } satisfies DataLayerEntry); for (const adapter of this.live) adapter.send?.(name, docs); + this.windowAnalytics?.feed.publish(name, docs); } public reportPageView(): void { if (isOAuthCallbackPath(window.location.pathname)) return; - // The tags a start on the OAuth callback left out, now that the reader has moved on from it. - insertTags(this.live); + const inserted = this.windowAnalytics?.inserted; + // The tags and scripts a start on the OAuth callback left out, now that the reader has moved on from it. + if (inserted !== undefined) insertTags(this.live, this.scripts, inserted); const page = pageLocation(window.location.href, this.settings.keepQueryParams); if (page === this.lastPageView) return; this.previousPageView = this.lastPageView; diff --git a/portal-template/src/lib/event-feed.ts b/portal-template/src/lib/event-feed.ts new file mode 100644 index 000000000..d168c21d6 --- /dev/null +++ b/portal-template/src/lib/event-feed.ts @@ -0,0 +1,60 @@ +/** One portal event as a subscriber receives it. Customers' scripts read these keys, so `version` moves if one ever changes. */ +export interface PortalEvent { + readonly name: string; + /** The event's details, with `page_location` among them. */ + readonly params: Readonly>; + /** When it was reported, in milliseconds since the epoch. */ + readonly time: number; + readonly version: 1; +} + +type Subscriber = (event: PortalEvent) => void; +type Unsubscribe = () => void; + +interface Subscription { + callback: Subscriber; + deliveredCount: number; +} + +/** A window's events, for the scripts in it: a subscriber gets every one reported so far, then each new one. */ +export class EventFeed { + private readonly events: PortalEvent[] = []; + private readonly subscriptions = new Set(); + + public subscribe(callback: Subscriber): Unsubscribe { + if (typeof callback !== 'function') { + throw new TypeError('window.apimatic.analytics.subscribe() takes a function.'); + } + const subscription: Subscription = { callback, deliveredCount: 0 }; + this.subscriptions.add(subscription); + // Once this has returned, so a callback can call the function it returns, even for an earlier event. + queueMicrotask(() => EventFeed.deliver(this, subscription)); + return () => { + this.subscriptions.delete(subscription); + }; + } + + public publish(name: string, params: Record): void { + // A copy, frozen, so no subscriber changes what the next one gets, or what the data layer was handed. + this.events.push(Object.freeze({ name, params: Object.freeze({ ...params }), time: Date.now(), version: 1 })); + // The set itself: one a callback adds is reached in this same pass, and one it removes is skipped. + for (const subscription of this.subscriptions) EventFeed.deliver(this, subscription); + } + + private static deliver(feed: EventFeed, subscription: Subscription): void { + // Called on its own, so a callback written without strict mode finds the window as `this`, never this record. + const { callback } = subscription; + while (feed.subscriptions.has(subscription) && subscription.deliveredCount < feed.events.length) { + const event = feed.events[subscription.deliveredCount]; + subscription.deliveredCount += 1; + try { + callback(event); + } catch (error) { + // Thrown later, so it shows in the console and stops neither the next event nor the next subscriber. + setTimeout(() => { + throw error; + }); + } + } + } +} diff --git a/portal-template/src/lib/portal-analytics.ts b/portal-template/src/lib/portal-analytics.ts index d23527eb9..83f6aebbe 100644 --- a/portal-template/src/lib/portal-analytics.ts +++ b/portal-template/src/lib/portal-analytics.ts @@ -2,7 +2,7 @@ import { Analytics } from './analytics'; import { portal } from './portal'; import { markPlaygroundDialogs } from './replay-markers'; -export const analytics = new Analytics(portal.analytics); +export const analytics = new Analytics(portal.analytics, portal.scripts); // When the bundle starts, before React and before any vendor tag. Never during prerendering. if (typeof window !== 'undefined') { markPlaygroundDialogs(); diff --git a/portal-template/src/lib/portal-types.ts b/portal-template/src/lib/portal-types.ts index cbc8cc0e1..bb119d739 100644 --- a/portal-template/src/lib/portal-types.ts +++ b/portal-template/src/lib/portal-types.ts @@ -36,11 +36,19 @@ export interface GoogleAnalyticsSetting { measurementId: string; } +export interface GoogleConsentModeSetting { + /** What Google's tags take a reader's answer to be until a consent tool gives one. */ + default: 'denied'; +} + /** Public values: they sit in every page's scripts. */ export interface PortalAnalytics { googleTagManager: GoogleTagManagerSetting | null; googleAnalytics: GoogleAnalyticsSetting | null; + googleConsentMode: GoogleConsentModeSetting | null; keepQueryParams: string[]; + /** Off in a build made with `--no-analytics`, which reports no event: none to the data layer, none to a script. */ + events: 'on' | 'off'; } export interface PortalSeo { @@ -48,6 +56,10 @@ export interface PortalSeo { googleSiteVerification: string | null; } +export interface PortalScript { + src: string; +} + export interface Portal { name: string; description: string | null; @@ -61,4 +73,6 @@ export interface Portal { pageActions: boolean; analytics: PortalAnalytics; seo: PortalSeo; + /** In the order the block lists them, which is the order the browser runs them in. */ + scripts: PortalScript[]; } diff --git a/portal-template/src/lib/search-report.ts b/portal-template/src/lib/search-report.ts index 2b347b3ae..ec4692d77 100644 --- a/portal-template/src/lib/search-report.ts +++ b/portal-template/src/lib/search-report.ts @@ -23,6 +23,6 @@ export function searchOutcome(state: SearchDialogState): SearchOutcome { const search_term = state.term.trim().slice(0, TERM_LIMIT); const counted = (state.typed || state.picked !== '') && search_term !== ''; // In the shape of `page_location`, so a report joins the two: a heading hit loses its `#` part. - const result = state.picked === '' ? '' : pageLocation(state.picked, []); - return { ended: true, report: counted ? { search_term, result, result_count: state.resultCount } : null }; + const picked_result = state.picked === '' ? '' : pageLocation(state.picked, []); + return { ended: true, report: counted ? { search_term, picked_result, result_count: state.resultCount } : null }; } diff --git a/portal-template/src/lib/vendor-tags.ts b/portal-template/src/lib/vendor-tags.ts index bd0d92128..379c9b636 100644 --- a/portal-template/src/lib/vendor-tags.ts +++ b/portal-template/src/lib/vendor-tags.ts @@ -1,5 +1,6 @@ +import { withBasePath } from './base-path'; import { isOAuthCallbackPath } from './oauth-callback'; -import type { PortalAnalytics } from './portal-types'; +import type { PortalAnalytics, PortalScript } from './portal-types'; type Gtag = (...command: unknown[]) => void; @@ -16,9 +17,40 @@ export interface Adapter { send?(name: string, params: Record): void; } -type Vendor = Exclude; +type Vendor = Exclude; const GOOGLE = 'https://www.googletagmanager.com'; +/** + * The window's gtag, when it is one. For an element whose id is `gtag`, such as a guide's heading, the browser + * answers `window.gtag` with that element, and calling it stopped the whole bundle. + */ +function windowGtag(): Gtag | undefined { + return typeof window.gtag === 'function' ? window.gtag : undefined; +} + +/** The window's own, or one made here: Google reads only Arguments objects from the data layer, never arrays. */ +function gtagFor(dataLayer: unknown[]): Gtag { + const gtag = + windowGtag() ?? + function () { + dataLayer.push(arguments); + }; + window.gtag = gtag; + return gtag; +} + +/** Ahead of every vendor's setup: Google reads a reader's answer from what is queued before its first event. */ +export function queueConsentDefaults(dataLayer: unknown[]): void { + gtagFor(dataLayer)('consent', 'default', { + ad_storage: 'denied', + ad_user_data: 'denied', + ad_personalization: 'denied', + analytics_storage: 'denied', + // Time for a consent tool to hand over a returning reader's answer, before the first hit goes out as denied. + wait_for_update: 500 + }); +} + /** Keyed by every vendor `PortalAnalytics` names, so a vendor without an adapter does not compile. */ export const adapters: { [V in Vendor]: (settings: PortalAnalytics) => Adapter | null } = { googleTagManager: ({ googleTagManager: setting }) => { @@ -36,36 +68,47 @@ export const adapters: { [V in Vendor]: (settings: PortalAnalytics) => Adapter | if (setting === null) return null; return { setup: (dataLayer) => { - // gtag.js reads only Arguments objects from the data layer, never an array of the same values. - const gtag = (window.gtag ??= function () { - dataLayer.push(arguments); - }); + const gtag = gtagFor(dataLayer); gtag('js', new Date()); gtag('config', setting.measurementId, { send_page_view: false }); }, script: `${GOOGLE}/gtag/js?id=${encodeURIComponent(setting.measurementId)}`, send: (name, params) => { // GA4's own events, such as a scroll, read this instead of the address, which may hold more. - if (name === 'docs_page_view') window.gtag?.('set', { page_location: params.page_location }); - // The page's gtag, since a second instance under `portal serve` never runs its setup. - window.gtag?.('event', name.replace(/^docs_/, ''), params); + if (name === 'docs_page_view') windowGtag()?.('set', { page_location: params.page_location }); + // The window's gtag, since a second instance under `portal serve` never runs its setup. + windowGtag()?.('event', name.replace(/^docs_/, ''), params); } }; } }; +/** The address of every script the head already holds, as written: a host may inject one of the portal's itself. */ +export function scriptsInHead(): string[] { + return Array.from(document.head.querySelectorAll('script[src]'), (script) => script.getAttribute('src') ?? ''); +} + /** * None on the OAuth callback, whose address holds the provider's answer; each once, so a later call adds the rest. * The page a sign-in returns to loads them at once, although the answer waits in the tab's session storage until - * a playground reads it: tags read the address, not the storage, so that window is accepted. On a page that mounts - * no playground the answer stays until one mounts in the tab or the tab closes, as with Fumadocs' own handler. + * a playground reads it: tags read the address, not the storage, so that window is accepted. A listed script could + * read it there, as it could anything else on the page. On a page that mounts no playground the answer stays until + * one mounts in the tab or the tab closes, as with Fumadocs' own handler. */ -export function insertTags(live: Adapter[]): void { +export function insertTags(live: Adapter[], scripts: PortalScript[], inserted: Set): void { if (isOAuthCallbackPath(window.location.pathname)) return; - for (const { script: src } of live) { - if (document.head.querySelector(`script[src="${src}"]`) !== null) continue; + // A listed script is not async, so the browser runs them in the order listed, whichever arrives first. + const wanted = [ + ...live.map(({ script: src }) => ({ src, async: true })), + // A file of the portal's own is named from its root, which a host may serve under a path. + ...scripts.map(({ src }) => ({ src: src.startsWith('/') ? withBasePath(src) : src, async: false })) + ]; + for (const { src, async } of wanted) { + // Remembered, not looked up in the head: a vendor's loader may take its own element out once it has run. + if (inserted.has(src)) continue; + inserted.add(src); const script = document.createElement('script'); - script.async = true; + script.async = async; script.src = src; document.head.append(script); } diff --git a/src/types/flags-provider.ts b/src/types/flags-provider.ts index 899b955c0..1b8472e7c 100644 --- a/src/types/flags-provider.ts +++ b/src/types/flags-provider.ts @@ -36,7 +36,8 @@ export class FlagsProvider { public static readonly noAnalytics = { 'no-analytics': Flags.boolean({ default: false, - description: "leave out the Google Tag Manager and Google Analytics tags set in 'portal.analytics'." + description: + "leave out the tags set in 'portal.analytics' and each script in 'portal.scripts' whose category is 'analytics' or 'marketing', and hand no event to the scripts that stay." }) }; diff --git a/src/types/portal-source-context.ts b/src/types/portal-source-context.ts index 8dd06d313..a57c9b007 100644 --- a/src/types/portal-source-context.ts +++ b/src/types/portal-source-context.ts @@ -306,7 +306,9 @@ export class PortalSourceContext { if (missingFiles.length > 0) { return err({ kind: 'missingStaticFiles', files: missingFiles }); } - return ok(build.analytics ? settings.value : { ...settings.value, config: settings.value.config.withoutVendors() }); + return ok( + build.analytics ? settings.value : { ...settings.value, config: settings.value.config.withoutAnalytics() } + ); } private async readConfigDocument(): Promise> { diff --git a/src/types/portal/config/analytics-config.ts b/src/types/portal/config/analytics-config.ts index 76ec59d2b..341d27f83 100644 --- a/src/types/portal/config/analytics-config.ts +++ b/src/types/portal/config/analytics-config.ts @@ -17,23 +17,33 @@ export interface GoogleAnalyticsSetting { measurementId: string; } +export interface GoogleConsentModeSetting { + /** What Google's tags take a reader's answer to be until a consent tool gives one. */ + default: 'denied'; +} + /** Public values: they sit in every page's scripts. */ export interface PortalAnalytics { googleTagManager: GoogleTagManagerSetting | null; googleAnalytics: GoogleAnalyticsSetting | null; + googleConsentMode: GoogleConsentModeSetting | null; keepQueryParams: string[]; + /** Off in a build made with `--no-analytics`, which reports no event: none to the data layer, none to a script. */ + events: 'on' | 'off'; } -const KNOWN = ['googleTagManager', 'googleAnalytics', 'keepQueryParams']; +const KNOWN = ['googleTagManager', 'googleAnalytics', 'googleConsentMode', 'keepQueryParams']; export class AnalyticsConfig { private constructor( private readonly googleTagManager: GoogleTagManagerSetting | null, private readonly googleAnalytics: GoogleAnalyticsSetting | null, - private readonly keepQueryParams: string[] + private readonly googleConsentMode: GoogleConsentModeSetting | null, + private readonly keepQueryParams: string[], + private readonly events: 'on' | 'off' ) {} - public static readonly defaults = new AnalyticsConfig(null, null, []); + public static readonly defaults = new AnalyticsConfig(null, null, null, [], 'on'); public static parse(value: unknown, path: string): Parsed { return namespace(value, path).andThen((data) => @@ -42,9 +52,10 @@ export class AnalyticsConfig { Result.combineWithAllErrors([ optional(data.googleTagManager, (vendor) => googleTagManager(vendor, `${path}.googleTagManager`)), optional(data.googleAnalytics, (vendor) => googleAnalytics(vendor, `${path}.googleAnalytics`)), + optional(data.googleConsentMode, (mode) => googleConsentMode(mode, `${path}.googleConsentMode`)), keptQueryParams(data.keepQueryParams, `${path}.keepQueryParams`) ]) - ).map(([gtm, ga, keep]) => new AnalyticsConfig(gtm, ga, keep)) + ).map(([gtm, ga, consent, keep]) => new AnalyticsConfig(gtm, ga, consent, keep, 'on')) ); } @@ -57,13 +68,19 @@ export class AnalyticsConfig { return { googleTagManager: this.googleTagManager, googleAnalytics: this.googleAnalytics, - keepQueryParams: this.keepQueryParams + googleConsentMode: this.googleConsentMode, + keepQueryParams: this.keepQueryParams, + events: this.events }; } - /** For a staging build: neither vendor tag loads, while a reported address still keeps the same names. */ - public withoutVendors(): AnalyticsConfig { - return new AnalyticsConfig(null, null, this.keepQueryParams); + /** + * For a staging build: no tag, and no event in the data layer or for a script; an address keeps the same names. + * The consent default stays, since a script the build keeps may load a Google tag of its own, which has to start + * as denied there too. + */ + public withoutAnalytics(): AnalyticsConfig { + return new AnalyticsConfig(null, null, this.googleConsentMode, this.keepQueryParams, 'off'); } } @@ -104,6 +121,21 @@ function googleAnalytics(value: unknown, path: string): Parsed ({ measurementId })); } +// An object with one key, so a key added later (a wait, regions) changes no config written today. +function googleConsentMode(value: unknown, path: string): Parsed { + if (!isJsonObject(value)) { + return err([`'${path}' must be a JSON object with 'default'.`]); + } + return allOf( + unknownKeys(value, ['default'], path), + Result.combineWithAllErrors([required(value.default, `${path}.default`, denied)]) + ).map(([given]) => ({ default: given })); +} + +function denied(value: unknown, path: string): Parsed<'denied'> { + return value === 'denied' ? ok('denied') : err([`'${path}' must be 'denied'.`]); +} + /** Names a reported address keeps, beyond the campaign names it always keeps. */ function keptQueryParams(value: unknown, path: string): Parsed { if (value === undefined) { diff --git a/src/types/portal/config/brand-config.ts b/src/types/portal/config/brand-config.ts index 0cf5cb9d2..04225c901 100644 --- a/src/types/portal/config/brand-config.ts +++ b/src/types/portal/config/brand-config.ts @@ -91,9 +91,12 @@ export class BrandConfig { optional(data.logo, (logo) => Logo.parse(logo, `${path}.logo`)), optional(data.favicon, (favicon) => StaticAsset.parse(favicon, `${path}.favicon`)), BrandColors.parse(data.colors, `${path}.colors`), - oneOf(data.colorMode, `${path}.colorMode`, COLOR_MODES, BrandConfig.defaults.colorMode) + optional(data.colorMode, (colorMode) => oneOf(colorMode, `${path}.colorMode`, COLOR_MODES)) ]) - ).map(([logo, favicon, colors, colorMode]) => new BrandConfig(logo, favicon, colors, colorMode)) + ).map( + ([logo, favicon, colors, colorMode]) => + new BrandConfig(logo, favicon, colors, colorMode ?? BrandConfig.defaults.colorMode) + ) ); } diff --git a/src/types/portal/config/fields.ts b/src/types/portal/config/fields.ts index ef581704a..9e24487c9 100644 --- a/src/types/portal/config/fields.ts +++ b/src/types/portal/config/fields.ts @@ -81,10 +81,7 @@ export function optionalBoolean(value: unknown, path: string, fallback: boolean) return typeof value === 'boolean' ? ok(value) : err([`'${path}' must be true or false.`]); } -export function oneOf(value: unknown, path: string, allowed: readonly T[], fallback: T): Parsed { - if (value === undefined) { - return ok(fallback); - } +export function oneOf(value: unknown, path: string, allowed: readonly T[]): Parsed { if (typeof value === 'string' && (allowed as readonly string[]).includes(value)) { return ok(value as T); } @@ -104,3 +101,17 @@ export function nonEmptyString(value: unknown, path: string): Parsed { ? ok(value.trim()) : err([`'${path}' must be a non-empty string.`]); } + +// The same addresses as `httpsAddress` in the schema, so an editor and a build give one verdict on a missing host. +// No backslash in the host: an address parser reads one as a slash, and takes what follows it for the host. +const HTTPS_ADDRESS = /^https:\/\/[^\s/\\?#]+(?:[/?#]\S*)?$/i; + +// https, since what it names is fetched and run; parsed, so it holds no space or quote wherever it is written out. +export function httpsAddress(value: unknown, path: string, example: string): Parsed { + const url = typeof value === 'string' && HTTPS_ADDRESS.test(value) ? URL.parse(value) : null; + return url === null + ? err([ + `'${path}' must be an address starting with 'https://' and a host, with no spaces, for example '${example}'.` + ]) + : ok(new UrlPath(url.href)); +} diff --git a/src/types/portal/config/script.ts b/src/types/portal/config/script.ts new file mode 100644 index 000000000..05226835d --- /dev/null +++ b/src/types/portal/config/script.ts @@ -0,0 +1,76 @@ +import { err, ok, Result } from 'neverthrow'; +import { isJsonObject } from '../../../utils/json-utils.js'; +import { UrlPath } from '../../file/urlPath.js'; +import { allOf, httpsAddress, oneOf, Parsed, required, unknownKeys } from './fields.js'; +import { StaticAsset } from './static-asset.js'; + +const KNOWN = ['src', 'category']; + +export const SCRIPT_CATEGORIES = ['necessary', 'functional', 'analytics', 'marketing'] as const; + +const ADDRESS_EXAMPLE = 'https://cdn.example.com/widget.js'; + +const FILE_EXAMPLE = 'static/analytics.js'; + +export interface PortalScript { + /** An https address, or the portal-relative path of a file in the static directory. */ + src: string; +} + +/** A script of the customer's own, which the portal loads on every page. */ +export class Script { + private constructor( + private readonly source: UrlPath | StaticAsset, + private readonly category: (typeof SCRIPT_CATEGORIES)[number] + ) {} + + public static parseList(value: unknown, path: string): Parsed { + if (value === undefined) { + return ok([]); + } + if (!Array.isArray(value)) { + return err([`'${path}' must be a list of scripts.`]); + } + return Result.combineWithAllErrors(value.map((script, index) => Script.parse(script, `${path}[${index}]`))).mapErr( + (errors) => errors.flat() + ); + } + + /** The file it names in the static directory; none for an address. */ + public staticFiles(): StaticAsset[] { + return this.source instanceof StaticAsset ? [this.source] : []; + } + + /** Whether a portal built with `--no-analytics` still loads it. */ + public loadsWithoutAnalytics(): boolean { + return this.category === 'necessary' || this.category === 'functional'; + } + + public identity(): PortalScript { + return { src: this.source instanceof StaticAsset ? this.source.portalPath() : this.source.toString() }; + } + + private static parse(value: unknown, path: string): Parsed