Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .ai/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ FLAGS
-i, --input=<value> [default: ./] path to the parent directory containing the 'src' directory, which includes
API specifications and configuration files.
-k, --auth-key=<value> 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 send no events to the scripts that stay.
--zip write the generated portal as a .zip archive.

DESCRIPTION
Expand Down Expand Up @@ -347,7 +348,8 @@ FLAGS
-k, --auth-key=<value> 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 send no events to the scripts that stay.

DESCRIPTION
Preview your API Documentation Portal with live reload.
Expand Down
54 changes: 51 additions & 3 deletions apimatic.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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'.",
Expand Down Expand Up @@ -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 does not affect which scripts in 'portal.scripts' are loaded, or when.",
"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.",
Expand All @@ -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, and the token an OAuth 2.0 sign-in leaves in the browser's session storage, 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, in the four groups consent tools ask readers about. 'necessary': the portal needs it to work, or the law requires it, such as your consent tool. 'functional': a feature a reader sees or uses, which may remember their choices, such as a chat widget, a feedback form or a status banner. 'analytics': it measures how readers use the portal, such as an analytics tool, a session recorder or an A/B testing tool. 'marketing': it serves or measures advertising, or follows readers across sites, such as an ad pixel. A script that does more than one takes the last of these that applies, so a feedback widget that also records sessions is 'analytics'. --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."
}
}
},
Expand Down
2 changes: 1 addition & 1 deletion portal-template/src/components/code-copy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { analytics } from '@/lib/portal-analytics';
type Actions = NonNullable<BlockProps['Actions']>;

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 }) => (
Expand Down
10 changes: 10 additions & 0 deletions portal-template/src/components/listed-scripts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useEffect } from 'react';
import { analytics } from '@/lib/portal-analytics';

/** Rendered with a page's content, so its effect runs once React has hydrated the page a script may change. */
export function ListedScripts() {
useEffect(() => {
analytics.loadScripts();
}, []);
return null;
}
2 changes: 2 additions & 0 deletions portal-template/src/components/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { baseOptions } from '@/lib/layout.shared';
import { analytics } from '@/lib/portal-analytics';
import { HomeLayout } from 'fumadocs-ui/layouts/home';
import { DefaultNotFound } from 'fumadocs-ui/layouts/home/not-found';
import { ListedScripts } from './listed-scripts';

export function NotFound() {
// The path the router has settled on: its location alone already names the page a reader is leaving this one for.
Expand All @@ -18,6 +19,7 @@ export function NotFound() {
return (
<HomeLayout {...baseOptions()}>
<DefaultNotFound />
<ListedScripts />
</HomeLayout>
);
}
2 changes: 1 addition & 1 deletion portal-template/src/components/sdk-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function DownloadLink({ href, className, language, children }: Readonly<D
href={withBasePath(href)}
download
className={className}
onClick={() => analytics.report('docs_sdk_download', { language: languageId(language) })}
onClick={() => analytics.report('docs_sdk_download', { sdk_language: languageId(language) })}
>
{children}
</a>
Expand Down
85 changes: 69 additions & 16 deletions portal-template/src/lib/analytics.ts
Original file line number Diff line number Diff line change
@@ -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 } 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_'];
Expand All @@ -26,9 +27,10 @@ export interface PortalEvents {
docs_page_view: { page_title: string };
docs_markdown_copy: Record<string, never>;
docs_plugin_install: Record<string, never>;
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 };
Expand All @@ -37,11 +39,27 @@ export type PortalEventName = keyof PortalEvents;

type DataLayerEntry = { docs: null } | { event: PortalEventName; docs: Readonly<Record<string, string | number>> };

/** 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<string>;
}

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<EventFeed, 'subscribe'> };
}
}

Expand All @@ -59,45 +77,80 @@ export function pageLocation(href: string, keep: readonly string[]): string {

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();
// Each script the head holds already, by its src as written: a host may inject one of the portal's itself.
const head = document.head.querySelectorAll('script[src]');
const inserted = new Set(Array.from(head, (script) => script.getAttribute('src') ?? ''));
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.
// A frozen object takes none, nor one that fixed the name.
const host: unknown = window.apimatic;
const property = { value: analytics, writable: true, enumerable: true, configurable: true };
const taken = Object(host) === host && Reflect.defineProperty(host as object, 'analytics', property);
if (!taken) 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;
});
}
// The listed scripts wait for `loadScripts()`: React drops a change one makes to the page before it hydrates.
insertTags(this.live, [], inserted);
}

/** From `ListedScripts`, once the page has hydrated. */
public loadScripts(): void {
const inserted = this.windowAnalytics?.inserted;
if (inserted !== undefined) insertTags([], this.scripts, inserted);
}

/** `href` is the page the event belongs to, when the caller saw the address move on first. */
public report<E extends PortalEventName>(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 ??= []);
// GTM merges every push into what it holds, so a tag would send the last event's details without this.
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;
const inserted = this.windowAnalytics?.inserted;
// The tags a start on the OAuth callback left out, now that the reader has moved on from it.
insertTags(this.live);
if (inserted !== undefined) insertTags(this.live, [], inserted);
const page = pageLocation(window.location.href, this.settings.keepQueryParams);
if (page === this.lastPageView) return;
this.previousPageView = this.lastPageView;
Expand Down
Loading
Loading