@veroxm/sdk 1.9.0 → 1.11.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.
@@ -0,0 +1,42 @@
1
+ import { VeroXMApiError } from './errors.js';
2
+ import { type RequestControl } from './http.js';
3
+ /** One entry of a GraphQL response's `errors` array. */
4
+ export interface GraphQLErrorItem {
5
+ message: string;
6
+ extensions?: Record<string, unknown>;
7
+ }
8
+ /**
9
+ * A GraphQL response that came back with `errors` (the HTTP status is usually 200). `errors` is the response's array;
10
+ * `code` is the first error's `extensions.code` when it has one, such as `QUERY_TOO_COMPLEX`.
11
+ */
12
+ export declare class VeroXMGraphQLError extends VeroXMApiError {
13
+ readonly errors: readonly GraphQLErrorItem[];
14
+ constructor(status: number, body: {
15
+ errors: readonly GraphQLErrorItem[];
16
+ });
17
+ }
18
+ export interface GraphQLRequestOptions extends RequestControl {
19
+ /** Your VeroXM deployment's origin, e.g. "https://cms.example.com". The endpoint is `/public/v2/graphql`. */
20
+ baseUrl: string;
21
+ /** Sent as `Authorization: Bearer <token>`: a project API key, or a signed-in end user's access token. */
22
+ token: string;
23
+ query: string;
24
+ /** Any object (an interface works too); sent as JSON. */
25
+ variables?: object;
26
+ /**
27
+ * Extra attempts (0 to 5) after a network error, a timeout, or 429, 502, 503 or 504, as for `VeroXMApp`'s
28
+ * `retries`. Only for documents without a mutation: a document containing `mutation` is sent once.
29
+ */
30
+ retries?: number;
31
+ /**
32
+ * The fetch to send with, instead of the global one: e.g. one that adds Next.js's `{ cache: 'force-cache', next: {
33
+ * tags } }`, or a test double. It gets the same (url, init) the SDK would pass to fetch.
34
+ */
35
+ fetch?: typeof fetch;
36
+ }
37
+ /**
38
+ * Sends one GraphQL document to the public API and returns its `data`. Rejects with `VeroXMGraphQLError` when the
39
+ * response has `errors`, `VeroXMApiError` for any other non-2xx answer, `VeroXMTimeoutError` after `timeoutMs`, and the
40
+ * signal's reason when `signal` aborts. Used by `@veroxm/react-sdk`; usable on its own for a custom query.
41
+ */
42
+ export declare function graphqlRequest<T = unknown>(options: GraphQLRequestOptions): Promise<T>;
@@ -0,0 +1,50 @@
1
+ import { VeroXMApiError } from './errors.js';
2
+ import { rawRequest } from './http.js';
3
+ /**
4
+ * A GraphQL response that came back with `errors` (the HTTP status is usually 200). `errors` is the response's array;
5
+ * `code` is the first error's `extensions.code` when it has one, such as `QUERY_TOO_COMPLEX`.
6
+ */
7
+ export class VeroXMGraphQLError extends VeroXMApiError {
8
+ constructor(status, body) {
9
+ super(status, body);
10
+ this.name = 'VeroXMGraphQLError';
11
+ this.errors = body.errors;
12
+ if (body.errors[0]?.message)
13
+ this.message = body.errors[0].message;
14
+ const code = body.errors[0]?.extensions?.code;
15
+ if (typeof code === 'string')
16
+ this.code = code;
17
+ }
18
+ }
19
+ /** True when the document has no mutation, so sending it twice changes nothing. Errs towards "not safe". */
20
+ function readOnly(query) {
21
+ return !/\bmutation\b/.test(query);
22
+ }
23
+ /**
24
+ * Sends one GraphQL document to the public API and returns its `data`. Rejects with `VeroXMGraphQLError` when the
25
+ * response has `errors`, `VeroXMApiError` for any other non-2xx answer, `VeroXMTimeoutError` after `timeoutMs`, and the
26
+ * signal's reason when `signal` aborts. Used by `@veroxm/react-sdk`; usable on its own for a custom query.
27
+ */
28
+ export async function graphqlRequest(options) {
29
+ const apiBase = `${options.baseUrl.replace(/\/$/, '')}/public/v2`;
30
+ const body = (await rawRequest(apiBase, {
31
+ method: 'POST',
32
+ path: '/graphql',
33
+ json: { query: options.query, ...(options.variables !== undefined ? { variables: options.variables } : {}) },
34
+ headers: { Authorization: `Bearer ${options.token}` },
35
+ signal: options.signal,
36
+ timeoutMs: options.timeoutMs,
37
+ retries: options.retries,
38
+ }, { repeatable: readOnly(options.query), fetch: options.fetch }).catch((e) => {
39
+ // The API answers a failed GraphQL request with its errors array, whatever the status.
40
+ if (e instanceof VeroXMApiError && hasErrors(e.body))
41
+ throw new VeroXMGraphQLError(e.status, e.body);
42
+ throw e;
43
+ }));
44
+ if (hasErrors(body))
45
+ throw new VeroXMGraphQLError(200, body);
46
+ return (body?.data ?? null);
47
+ }
48
+ function hasErrors(body) {
49
+ return !!body && typeof body === 'object' && Array.isArray(body.errors) && body.errors.length > 0;
50
+ }
package/dist/http.d.ts CHANGED
@@ -1,4 +1,14 @@
1
- export interface RawRequestOptions {
1
+ /**
2
+ * Per-call control over one request: cancel it, or give up after a time. Accepted by `content(slug).list()`,
3
+ * `search()`, `count()`, `get()` and `functions.call()` / `functions.get()`.
4
+ */
5
+ export interface RequestControl {
6
+ /** Cancels the request when it aborts: the call rejects with the signal's reason (an `AbortError` by default). */
7
+ signal?: AbortSignal;
8
+ /** Gives up after this many milliseconds with `VeroXMTimeoutError`. Overrides the app's `timeoutMs` for this call. */
9
+ timeoutMs?: number;
10
+ }
11
+ export interface RawRequestOptions extends RequestControl {
2
12
  method?: string;
3
13
  /** Path relative to the client's api base, e.g. "/auth/token" or "/collections/posts/content". */
4
14
  path: string;
@@ -8,12 +18,23 @@ export interface RawRequestOptions {
8
18
  /** Sent as a `multipart/form-data` body (file uploads) -- fetch sets the boundary Content-Type itself, so never set one manually alongside this. */
9
19
  form?: FormData;
10
20
  headers?: Record<string, string>;
21
+ /** Extra attempts for a GET or HEAD that fails in a way worth retrying (see `isRetryable`). Ignored for other methods. */
22
+ retries?: number;
11
23
  }
24
+ /** Throws a RangeError for a `retries` that isn't a whole number from 0 to 5. */
25
+ export declare function checkRetries(value: number | undefined): void;
26
+ /** Throws a RangeError for a `timeoutMs` that isn't a positive number. */
27
+ export declare function checkTimeout(value: number | undefined): void;
12
28
  /**
13
29
  * The one place an HTTP request actually goes out. Deliberately built on
14
30
  * the platform's own global `fetch`/`FormData` -- available in every
15
31
  * environment this SDK targets (browsers, Node 18+, React Native 0.71+)
16
32
  * without adding a runtime dependency the way `axios` or `dio`-equivalent
17
33
  * libraries would.
34
+ *
35
+ * Without `timeoutMs`, `signal` or `retries` this is a single plain fetch, exactly as before those options existed.
18
36
  */
19
- export declare function rawRequest(apiBase: string, opts: RawRequestOptions): Promise<unknown>;
37
+ export declare function rawRequest(apiBase: string, opts: RawRequestOptions, internal?: {
38
+ repeatable?: boolean;
39
+ fetch?: typeof fetch;
40
+ }): Promise<unknown>;
package/dist/http.js CHANGED
@@ -1,4 +1,4 @@
1
- import { apiError } from './errors.js';
1
+ import { apiError, VeroXMApiError, VeroXMTimeoutError } from './errors.js';
2
2
  function safeJsonParse(text) {
3
3
  try {
4
4
  return JSON.parse(text);
@@ -7,14 +7,124 @@ function safeJsonParse(text) {
7
7
  return text;
8
8
  }
9
9
  }
10
+ /** Only requests that change nothing are repeated: a POST that timed out may still have been carried out. */
11
+ const REPEATABLE = new Set(['GET', 'HEAD']);
12
+ /** Answers that usually mean "try again shortly": rate limited, or the API is restarting or overloaded. */
13
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
14
+ const BASE_DELAY_MS = 300;
15
+ const MAX_DELAY_MS = 10000;
16
+ // How long the API asked us to wait (Retry-After), kept beside the error rather than on it so the
17
+ // VeroXMApiError surface doesn't change.
18
+ const retryAfterMs = new WeakMap();
19
+ function parseRetryAfter(value) {
20
+ if (!value)
21
+ return undefined;
22
+ const seconds = Number(value);
23
+ if (Number.isFinite(seconds) && seconds >= 0)
24
+ return seconds * 1000;
25
+ const at = Date.parse(value);
26
+ return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());
27
+ }
28
+ /** A failure worth another attempt: a network error, a timeout, or one of RETRY_STATUSES. Never a cancel. */
29
+ function isRetryable(err) {
30
+ if (err instanceof VeroXMTimeoutError)
31
+ return true;
32
+ if (err instanceof VeroXMApiError)
33
+ return RETRY_STATUSES.has(err.status);
34
+ // fetch rejects with a TypeError when the network fails (browsers, Node's undici, React Native).
35
+ return err instanceof TypeError;
36
+ }
37
+ function backoff(attempt, err) {
38
+ const asked = typeof err === 'object' && err !== null ? retryAfterMs.get(err) : undefined;
39
+ if (asked !== undefined)
40
+ return Math.min(asked, MAX_DELAY_MS);
41
+ const base = Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS);
42
+ return base / 2 + Math.random() * (base / 2); // jitter, so many clients don't retry in step
43
+ }
44
+ function abortReason(signal) {
45
+ return signal.reason ?? Object.assign(new Error('The operation was aborted.'), { name: 'AbortError' });
46
+ }
47
+ function wait(ms, signal) {
48
+ return new Promise((resolve, reject) => {
49
+ if (signal?.aborted)
50
+ return reject(abortReason(signal));
51
+ const onAbort = () => {
52
+ clearTimeout(timer);
53
+ reject(abortReason(signal));
54
+ };
55
+ const timer = setTimeout(() => {
56
+ signal?.removeEventListener('abort', onAbort);
57
+ resolve();
58
+ }, ms);
59
+ signal?.addEventListener('abort', onAbort, { once: true });
60
+ });
61
+ }
62
+ function checkPositive(name, value) {
63
+ if (value !== undefined && !(Number.isFinite(value) && value > 0)) {
64
+ throw new RangeError(`${name} must be a positive number of milliseconds, got ${String(value)}`);
65
+ }
66
+ }
67
+ /** Throws a RangeError for a `retries` that isn't a whole number from 0 to 5. */
68
+ export function checkRetries(value) {
69
+ if (value !== undefined && !(Number.isInteger(value) && value >= 0 && value <= 5)) {
70
+ throw new RangeError(`retries must be a whole number from 0 to 5, got ${String(value)}`);
71
+ }
72
+ }
73
+ /** Throws a RangeError for a `timeoutMs` that isn't a positive number. */
74
+ export function checkTimeout(value) {
75
+ checkPositive('timeoutMs', value);
76
+ }
77
+ /** One attempt. A timeout or the caller's signal aborts the fetch and the reading of the body. */
78
+ async function attempt(url, init, control, fetchImpl) {
79
+ const { signal, timeoutMs } = control;
80
+ if (signal?.aborted)
81
+ throw abortReason(signal);
82
+ const controller = signal || timeoutMs ? new AbortController() : undefined;
83
+ let timedOut = false;
84
+ const onAbort = () => controller.abort(signal.reason);
85
+ signal?.addEventListener('abort', onAbort, { once: true });
86
+ const timer = timeoutMs
87
+ ? setTimeout(() => {
88
+ timedOut = true;
89
+ controller.abort();
90
+ }, timeoutMs)
91
+ : undefined;
92
+ try {
93
+ const res = await fetchImpl(url, controller ? { ...init, signal: controller.signal } : init);
94
+ const text = await res.text();
95
+ const parsed = text ? safeJsonParse(text) : null;
96
+ if (!res.ok) {
97
+ const err = apiError(res.status, parsed ?? text);
98
+ const after = parseRetryAfter(res.headers?.get?.('retry-after'));
99
+ if (after !== undefined)
100
+ retryAfterMs.set(err, after);
101
+ throw err;
102
+ }
103
+ return parsed;
104
+ }
105
+ catch (e) {
106
+ if (timedOut)
107
+ throw new VeroXMTimeoutError(timeoutMs);
108
+ throw e;
109
+ }
110
+ finally {
111
+ if (timer)
112
+ clearTimeout(timer);
113
+ signal?.removeEventListener('abort', onAbort);
114
+ }
115
+ }
10
116
  /**
11
117
  * The one place an HTTP request actually goes out. Deliberately built on
12
118
  * the platform's own global `fetch`/`FormData` -- available in every
13
119
  * environment this SDK targets (browsers, Node 18+, React Native 0.71+)
14
120
  * without adding a runtime dependency the way `axios` or `dio`-equivalent
15
121
  * libraries would.
122
+ *
123
+ * Without `timeoutMs`, `signal` or `retries` this is a single plain fetch, exactly as before those options existed.
16
124
  */
17
- export async function rawRequest(apiBase, opts) {
125
+ export async function rawRequest(apiBase, opts, internal = {}) {
126
+ checkTimeout(opts.timeoutMs);
127
+ checkRetries(opts.retries);
18
128
  const base = apiBase.endsWith('/') ? apiBase : `${apiBase}/`;
19
129
  const url = new URL(opts.path.replace(/^\//, ''), base);
20
130
  if (opts.query) {
@@ -32,11 +142,20 @@ export async function rawRequest(apiBase, opts) {
32
142
  headers['Content-Type'] = 'application/json';
33
143
  body = JSON.stringify(opts.json);
34
144
  }
35
- const res = await fetch(url.toString(), { method: opts.method ?? 'GET', headers, body });
36
- const text = await res.text();
37
- const parsed = text ? safeJsonParse(text) : null;
38
- if (!res.ok) {
39
- throw apiError(res.status, parsed ?? text);
145
+ const method = opts.method ?? 'GET';
146
+ const init = { method, headers, body };
147
+ // `repeatable` lets a caller vouch for a POST that changes nothing (a GraphQL query).
148
+ const repeatable = internal.repeatable ?? REPEATABLE.has(method.toUpperCase());
149
+ const retries = repeatable ? (opts.retries ?? 0) : 0;
150
+ const control = { signal: opts.signal, timeoutMs: opts.timeoutMs };
151
+ for (let n = 0;; n++) {
152
+ try {
153
+ return await attempt(url.toString(), init, control, internal.fetch ?? fetch);
154
+ }
155
+ catch (e) {
156
+ if (n >= retries || !isRetryable(e) || opts.signal?.aborted)
157
+ throw e;
158
+ await wait(backoff(n, e), opts.signal);
159
+ }
40
160
  }
41
- return parsed;
42
161
  }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,9 @@ export type { PasskeyOptionsJSON, PasskeyProvider } from './passkeys.js';
7
7
  export { createPkce } from './pkce.js';
8
8
  export { ContentResource } from './content.js';
9
9
  export type { ListOptions } from './content.js';
10
+ export type { RequestControl } from './http.js';
11
+ export { graphqlRequest, VeroXMGraphQLError } from './graphql.js';
12
+ export type { GraphQLErrorItem, GraphQLRequestOptions } from './graphql.js';
10
13
  export { MediaResource } from './media.js';
11
14
  export type { MediaItem, MediaPage, UploadableFile } from './media.js';
12
15
  export { FunctionsResource } from './functions.js';
@@ -17,12 +20,15 @@ export type { ProcessRun, ProcessRunDetail, ProcessRunListOptions } from './proc
17
20
  export { FormsResource } from './forms.js';
18
21
  export type { FormDetail, FormResponse, FormResponseListOptions, FormResponsePage, FormSummary } from './forms.js';
19
22
  export { embedForm, embedFormsFromPage } from './embed.js';
20
- export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions } from './embed.js';
23
+ export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions, FormEmbedTracker } from './embed.js';
21
24
  export type { Schemas } from './schemas.js';
22
25
  export type { paths as ApiPaths, components as ApiComponents, operations as ApiOperations } from './generated/api.js';
23
- export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTwoStepRequiredError } from './errors.js';
26
+ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
24
27
  export type { TwoStepMethod } from './errors.js';
25
28
  export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
26
29
  export type { TokenStorage, StoredSession, AuthUser } from './token-storage.js';
27
30
  export { VeroxmTracker, createTracker } from './tracker.js';
28
31
  export type { TrackerOptions, TrackerStorage, ConsentChoices, ConsentValue, StoredConsent, ExperienceDecision, GetExperienceOptions, Recommendations, } from './tracker.js';
32
+ export type { PostHogLike, PosthogExposureHint } from './posthog.js';
33
+ export { STANDARD_EVENTS } from './standard-events.js';
34
+ export type { FormSubmission, SlotTestVariant, StandardEventName } from './standard-events.js';
package/dist/index.js CHANGED
@@ -3,6 +3,8 @@ export { VeroXMAuth } from './auth.js';
3
3
  export { browserPasskeys, creationOptionsFromJSON, credentialToJSON, requestOptionsFromJSON } from './passkeys.js';
4
4
  export { createPkce } from './pkce.js';
5
5
  export { ContentResource } from './content.js';
6
+ // GraphQL (/public/v2/graphql), the transport @veroxm/react-sdk reads through.
7
+ export { graphqlRequest, VeroXMGraphQLError } from './graphql.js';
6
8
  export { MediaResource } from './media.js';
7
9
  export { FunctionsResource } from './functions.js';
8
10
  export { TasksResource } from './tasks.js';
@@ -10,7 +12,9 @@ export { ProcessesResource } from './processes.js';
10
12
  export { FormsResource } from './forms.js';
11
13
  // Showing forms in a page: inline, popup, full page or toast.
12
14
  export { embedForm, embedFormsFromPage } from './embed.js';
13
- export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTwoStepRequiredError } from './errors.js';
15
+ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
14
16
  export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
15
17
  // Experience OS visitor tracking (page views, actions, consent, identify).
16
18
  export { VeroxmTracker, createTracker } from './tracker.js';
19
+ // Standard events: `$slot_impression` and `$form_submitted` (tracker.slotImpression, tracker.formSubmitted).
20
+ export { STANDARD_EVENTS } from './standard-events.js';
@@ -0,0 +1,27 @@
1
+ /** The part of posthog-js the tracker uses (the snippet's stub queues these calls until PostHog has loaded). */
2
+ export interface PostHogLike {
3
+ capture(event: string, properties?: Record<string, unknown>): unknown;
4
+ register(properties: Record<string, unknown>): unknown;
5
+ }
6
+ /** What VeroXM says to send for an exposure (`posthog` on a decision). */
7
+ export interface PosthogExposureHint {
8
+ /** `$feature_flag`: veroxm-<experience id>. */
9
+ flag: string;
10
+ /** `$feature_flag_response`: "control", or the variant's label as a key. */
11
+ variant: string;
12
+ }
13
+ export declare const POSTHOG_EXPOSURE_EVENT = "$feature_flag_called";
14
+ /** The PostHog instance to send to: the one given, else the page's window.posthog; null when there is none. */
15
+ export declare function findPosthog(given?: PostHogLike | false | null): PostHogLike | null;
16
+ /** A hint as the API sends it, or null when it isn't one. */
17
+ export declare function readHint(raw: unknown): PosthogExposureHint | null;
18
+ /**
19
+ * Sends one exposure to PostHog, at most once per test for this `sent` set (one per page load). Returns whether it
20
+ * sent. Never throws: PostHog's problems never break the page.
21
+ */
22
+ export declare function sendPosthogExposure(ph: PostHogLike | null, exposure: {
23
+ hint: PosthogExposureHint;
24
+ experienceId: number;
25
+ variantId: number;
26
+ placement: string;
27
+ }, sent: Set<number>): boolean;
@@ -0,0 +1,54 @@
1
+ // Insights I1 (docs/INSIGHTS-SCOPE.md, D5): experiment exposures in the site's own PostHog.
2
+ //
3
+ // When the project's "Send test exposures to PostHog" is on, VeroXM's answers (GET /decide, and /slots for the
4
+ // script tag) carry `posthog: { flag, variant }`. If the page has PostHog (window.posthog, or the instance passed as
5
+ // the tracker's `posthog` option), the tracker sends the exposure there, so it lands on the visitor's own PostHog
6
+ // distinct id:
7
+ //
8
+ // posthog.capture('$feature_flag_called', { $feature_flag: 'veroxm-12', $feature_flag_response: 'b', ... })
9
+ // posthog.register({ '$feature/veroxm-12': 'b', veroxm_12: 'b' })
10
+ //
11
+ // `$feature_flag_called` (not `$exposure`) because it is the exposure event PostHog's own SDKs send for a flag, the
12
+ // default exposure event of PostHog experiments, and what its flag breakdowns read. The super properties make every
13
+ // later PostHog event of the visitor carry the variant: `$feature/<flag>` is how PostHog attributes events to a flag
14
+ // variant; `veroxm_<id>` is a plain property that is easy to find in any breakdown. Once per test per page load,
15
+ // only after VeroXM's analytics consent, and nothing about the person: test and variant ids and keys, the placement.
16
+ export const POSTHOG_EXPOSURE_EVENT = '$feature_flag_called';
17
+ /** The PostHog instance to send to: the one given, else the page's window.posthog; null when there is none. */
18
+ export function findPosthog(given) {
19
+ if (given === false || given === null)
20
+ return null;
21
+ const candidate = given ?? (typeof window !== 'undefined' ? window.posthog : undefined);
22
+ const ph = candidate;
23
+ return ph && typeof ph.capture === 'function' && typeof ph.register === 'function' ? ph : null;
24
+ }
25
+ /** A hint as the API sends it, or null when it isn't one. */
26
+ export function readHint(raw) {
27
+ const h = raw;
28
+ return h && typeof h.flag === 'string' && typeof h.variant === 'string' && h.flag && h.variant ? { flag: h.flag, variant: h.variant } : null;
29
+ }
30
+ /**
31
+ * Sends one exposure to PostHog, at most once per test for this `sent` set (one per page load). Returns whether it
32
+ * sent. Never throws: PostHog's problems never break the page.
33
+ */
34
+ export function sendPosthogExposure(ph, exposure, sent) {
35
+ if (!ph || sent.has(exposure.experienceId))
36
+ return false;
37
+ sent.add(exposure.experienceId);
38
+ const { flag, variant } = exposure.hint;
39
+ try {
40
+ ph.capture(POSTHOG_EXPOSURE_EVENT, {
41
+ $feature_flag: flag,
42
+ $feature_flag_response: variant,
43
+ [`$feature/${flag}`]: variant,
44
+ veroxm_experience_id: exposure.experienceId,
45
+ veroxm_variant_id: exposure.variantId,
46
+ veroxm_placement: exposure.placement,
47
+ });
48
+ ph.register({ [`$feature/${flag}`]: variant, [`veroxm_${exposure.experienceId}`]: variant });
49
+ return true;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
@@ -0,0 +1,24 @@
1
+ /** The names of VeroXM's standard events. */
2
+ export declare const STANDARD_EVENTS: {
3
+ /** A slot was shown on a page. Properties: `slot`, and `experienceId` + `variantId` for a slot test's variant. */
4
+ readonly slotImpression: "$slot_impression";
5
+ /** A VeroXM form in the page was sent. Properties: `form` (f_...), `responseId`, `endingId`. */
6
+ readonly formSubmitted: "$form_submitted";
7
+ };
8
+ export type StandardEventName = (typeof STANDARD_EVENTS)[keyof typeof STANDARD_EVENTS];
9
+ /** A slot test's variant, as slot reads and `getExperience` return it. */
10
+ export interface SlotTestVariant {
11
+ experienceId: number;
12
+ variantId: number;
13
+ }
14
+ /** What a form embed reports when the form is sent. */
15
+ export interface FormSubmission {
16
+ responseId?: string;
17
+ endingId?: string | null;
18
+ }
19
+ /**
20
+ * Why the API would refuse this standard event ('' when it wouldn't, or for any other name). The tracker drops a
21
+ * standard event that would be refused, so one bad event can't get a whole batch rejected.
22
+ * @internal
23
+ */
24
+ export declare function standardEventProblem(name: string, p?: Record<string, unknown>): string;
@@ -0,0 +1,40 @@
1
+ // Standard events: `track` events whose name VeroXM defines and whose properties the API checks
2
+ // (apps/api/src/events/standard-events.ts -- keep the two in step). Being `track` events, they work as an
3
+ // experience's goal like any other name: `$form_submitted` as the goal of a test measures form sends.
4
+ /** The names of VeroXM's standard events. */
5
+ export const STANDARD_EVENTS = {
6
+ /** A slot was shown on a page. Properties: `slot`, and `experienceId` + `variantId` for a slot test's variant. */
7
+ slotImpression: '$slot_impression',
8
+ /** A VeroXM form in the page was sent. Properties: `form` (f_...), `responseId`, `endingId`. */
9
+ formSubmitted: '$form_submitted',
10
+ };
11
+ const SLOT_NAME = /^[a-z0-9][a-z0-9._-]{0,119}$/;
12
+ const FORM_ID = /^f_[A-Za-z0-9]{6,40}$/;
13
+ const PUBLIC_ID = /^[A-Za-z0-9_-]{1,64}$/;
14
+ const isId = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 4294967295;
15
+ /**
16
+ * Why the API would refuse this standard event ('' when it wouldn't, or for any other name). The tracker drops a
17
+ * standard event that would be refused, so one bad event can't get a whole batch rejected.
18
+ * @internal
19
+ */
20
+ export function standardEventProblem(name, p = {}) {
21
+ if (name === STANDARD_EVENTS.slotImpression) {
22
+ if (typeof p.slot !== 'string' || !SLOT_NAME.test(p.slot))
23
+ return '"slot" must be a slot name';
24
+ if ((p.experienceId === undefined) !== (p.variantId === undefined))
25
+ return '"experienceId" and "variantId" go together';
26
+ if (p.experienceId !== undefined && (!isId(p.experienceId) || !isId(p.variantId)))
27
+ return '"experienceId" and "variantId" must be positive integers';
28
+ if (p.path !== undefined && (typeof p.path !== 'string' || p.path.length > 500))
29
+ return '"path" must be text of at most 500 characters';
30
+ }
31
+ else if (name === STANDARD_EVENTS.formSubmitted) {
32
+ if (typeof p.form !== 'string' || !FORM_ID.test(p.form))
33
+ return '"form" must be a form id (f_...)';
34
+ if (p.responseId !== undefined && (typeof p.responseId !== 'string' || !PUBLIC_ID.test(p.responseId)))
35
+ return '"responseId" must be a response id';
36
+ if (p.endingId !== undefined && p.endingId !== null && (typeof p.endingId !== 'string' || !PUBLIC_ID.test(p.endingId)))
37
+ return '"endingId" must be an ending id or null';
38
+ }
39
+ return '';
40
+ }
package/dist/tracker.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import type { Schemas } from './schemas.js';
2
+ import { type Vitals } from './autocapture.js';
3
+ import { type PostHogLike, type PosthogExposureHint } from './posthog.js';
4
+ import { type FormSubmission, type SlotTestVariant } from './standard-events.js';
2
5
  export interface TrackerStorage {
3
6
  get(key: string): string | null;
4
7
  set(key: string, value: string): void;
@@ -19,6 +22,43 @@ export interface TrackerOptions {
19
22
  storage?: TrackerStorage;
20
23
  /** Called when a request fails for good (a rejected batch, a bad key). Defaults to console.warn. */
21
24
  onError?: (error: Error) => void;
25
+ /**
26
+ * Record clicks, rage clicks, form submits, scroll depth and page speed automatically (browsers only; default
27
+ * false). Held until analytics consent like every other event.
28
+ * @since 1.9.0
29
+ */
30
+ autocapture?: boolean;
31
+ /**
32
+ * For autocapture: the A/B test a clicked element is part of (e.g. a slot under test), so clicks can be split by
33
+ * variant. Return null when it isn't in one.
34
+ * @since 1.9.0
35
+ */
36
+ slotTest?: (element: Element) => {
37
+ experienceId: number;
38
+ variantId: number;
39
+ } | null;
40
+ /**
41
+ * Where test exposures go when the project sends them to PostHog: your posthog-js instance. By default the page's
42
+ * `window.posthog`; pass `false` to never send them from this tracker.
43
+ * @since 1.9.0
44
+ */
45
+ posthog?: PostHogLike | false;
46
+ }
47
+ /** What an automatic capture or page-end report carries (sent as `interaction`). */
48
+ export interface InteractionData {
49
+ path: string;
50
+ selector?: string;
51
+ label?: string;
52
+ href?: string;
53
+ x?: number;
54
+ y?: number;
55
+ pageY?: number;
56
+ depth?: number;
57
+ viewportW?: number;
58
+ experienceId?: number;
59
+ variantId?: number;
60
+ engagedMs?: number;
61
+ metrics?: Vitals;
22
62
  }
23
63
  export interface ConsentChoices {
24
64
  analytics?: boolean;
@@ -53,6 +93,12 @@ export interface ExperienceDecision<TContent = Record<string, unknown>, TConfig
53
93
  config: TConfig | null;
54
94
  /** True when no request was made because analytics consent isn't granted yet. */
55
95
  waitingForConsent?: boolean;
96
+ /**
97
+ * When the project sends test exposures to PostHog: the flag and variant the tracker sent there (`$feature_flag`,
98
+ * `$feature_flag_response`). Only on a test's answer.
99
+ * @since 1.9.0
100
+ */
101
+ posthog?: PosthogExposureHint;
56
102
  /** Set when the request failed or timed out (the decision is then "none"). */
57
103
  error?: string;
58
104
  }
@@ -76,6 +122,19 @@ export declare class VeroxmTracker {
76
122
  private readonly memory;
77
123
  private readonly onError;
78
124
  private readonly keys;
125
+ private readonly autocapture;
126
+ private readonly slotTest;
127
+ private readonly posthogOption;
128
+ /** Tests whose exposure went to PostHog on this page load. */
129
+ private readonly posthogSent;
130
+ private session;
131
+ private pageState;
132
+ private pagesSeen;
133
+ /** Slot impressions sent for this page view (slot:variant). */
134
+ private readonly impressions;
135
+ private readonly vitals;
136
+ private scrollCheckedAt;
137
+ private scrollTimer;
79
138
  private visitorId;
80
139
  private consentState;
81
140
  private queue;
@@ -94,6 +153,18 @@ export declare class VeroxmTracker {
94
153
  getConsent(): StoredConsent;
95
154
  /** Records an action, e.g. track('demo_requested', { plan: 'enterprise' }). */
96
155
  track(name: string, properties?: Record<string, unknown>): void;
156
+ /**
157
+ * Records that a slot was shown (`$slot_impression`), with the visitor's variant when the slot is under test.
158
+ * Sent once per slot and variant per page view, however often it is called (re-renders don't count again).
159
+ * @since 1.10.0
160
+ */
161
+ slotImpression(slot: string, test?: SlotTestVariant | null): void;
162
+ /**
163
+ * Records that a VeroXM form was sent (`$form_submitted`). `embedForm` and `<VeroxmForm>` call this for you when
164
+ * given a tracker. Use `$form_submitted` as an experience's goal to measure form sends.
165
+ * @since 1.10.0
166
+ */
167
+ formSubmitted(form: string, submission?: FormSubmission): void;
97
168
  /** Records a page or screen view. In a browser, path/url/title/referrer are added automatically. */
98
169
  page(properties?: Record<string, unknown>): void;
99
170
  /** Saves the visitor's consent answers (true = granted, false = denied, omitted = unchanged). */
@@ -145,6 +216,8 @@ export declare class VeroxmTracker {
145
216
  * `config.newCheckout` of this visitor's variant, else the fallback.
146
217
  */
147
218
  getFlag<T>(placement: string, key: string, fallback: T): Promise<T>;
219
+ /** A test's exposure to the page's PostHog, once per test per page load (see posthog.ts). Consent is checked by getExperience. */
220
+ private sendToPosthog;
148
221
  /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
149
222
  subscribe(listener: () => void): () => void;
150
223
  /** Sends queued events now. Resolves when done (or deferred by a backoff). */
@@ -155,7 +228,24 @@ export declare class VeroxmTracker {
155
228
  shutdown(): void;
156
229
  private changed;
157
230
  private sendAll;
231
+ /**
232
+ * Queues an event; returns its session id. Reports (page end, scroll, vitals) pass their page's fixed id, time and
233
+ * session: an unsent copy in the queue is replaced, and a re-sent one replaces the stored one (same id and time).
234
+ */
158
235
  private enqueue;
236
+ /** The session an event now belongs to (D4), kept on the device only when allowed. */
237
+ private sessionFor;
238
+ private saveSession;
239
+ /** Stops the page's visible-time clock (the tab was hidden or left). */
240
+ private pausePage;
241
+ /** The page's reports: engaged time, and with autocapture its scroll depth and page speed. Safe to call repeatedly. */
242
+ private reportPage;
243
+ /** Updates the page's deepest scroll bucket (at most every 250 ms unless forced). */
244
+ private checkScroll;
245
+ private startAutocapture;
246
+ private clickData;
247
+ /** LCP, INP (approximated by the longest interaction), CLS -- where the browser measures them. */
248
+ private observeVitals;
159
249
  private post;
160
250
  private canSend;
161
251
  /** Whether anything may be written to the device. */