@veroxm/sdk 1.8.0 → 1.10.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/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) {
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 fetch(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
125
  export async function rawRequest(apiBase, opts) {
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,18 @@ 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
+ const retries = REPEATABLE.has(method.toUpperCase()) ? (opts.retries ?? 0) : 0;
148
+ const control = { signal: opts.signal, timeoutMs: opts.timeoutMs };
149
+ for (let n = 0;; n++) {
150
+ try {
151
+ return await attempt(url.toString(), init, control);
152
+ }
153
+ catch (e) {
154
+ if (n >= retries || !isRetryable(e) || opts.signal?.aborted)
155
+ throw e;
156
+ await wait(backoff(n, e), opts.signal);
157
+ }
40
158
  }
41
- return parsed;
42
159
  }
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  export { VeroXMApp } from './client.js';
2
2
  export type { VeroXMAppOptions } from './client.js';
3
3
  export { VeroXMAuth } from './auth.js';
4
- export type { Account, AuthenticatorSetup, EmailCode, Passkey, PendingStore, SecondStep, SocialProvider, SocialSignInStart, TwoStepStatus, WithTicket, } from './auth.js';
4
+ export type { Account, AuthConfig, AuthenticatorSetup, BotCheck, BotProtectionConfig, EmailCode, Passkey, PendingStore, SecondStep, SocialProvider, SocialSignInStart, TwoStepStatus, WithTicket, } from './auth.js';
5
5
  export { browserPasskeys, creationOptionsFromJSON, credentialToJSON, requestOptionsFromJSON } from './passkeys.js';
6
6
  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';
10
11
  export { MediaResource } from './media.js';
11
12
  export type { MediaItem, MediaPage, UploadableFile } from './media.js';
12
13
  export { FunctionsResource } from './functions.js';
@@ -20,9 +21,10 @@ export { embedForm, embedFormsFromPage } from './embed.js';
20
21
  export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions } from './embed.js';
21
22
  export type { Schemas } from './schemas.js';
22
23
  export type { paths as ApiPaths, components as ApiComponents, operations as ApiOperations } from './generated/api.js';
23
- export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTwoStepRequiredError } from './errors.js';
24
+ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
24
25
  export type { TwoStepMethod } from './errors.js';
25
26
  export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
26
27
  export type { TokenStorage, StoredSession, AuthUser } from './token-storage.js';
27
28
  export { VeroxmTracker, createTracker } from './tracker.js';
28
29
  export type { TrackerOptions, TrackerStorage, ConsentChoices, ConsentValue, StoredConsent, ExperienceDecision, GetExperienceOptions, Recommendations, } from './tracker.js';
30
+ export type { PostHogLike, PosthogExposureHint } from './posthog.js';
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ export { ProcessesResource } from './processes.js';
10
10
  export { FormsResource } from './forms.js';
11
11
  // Showing forms in a page: inline, popup, full page or toast.
12
12
  export { embedForm, embedFormsFromPage } from './embed.js';
13
- export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTwoStepRequiredError } from './errors.js';
13
+ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
14
14
  export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
15
15
  // Experience OS visitor tracking (page views, actions, consent, identify).
16
16
  export { VeroxmTracker, createTracker } from './tracker.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
+ }
package/dist/tracker.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { Schemas } from './schemas.js';
2
+ import { type Vitals } from './autocapture.js';
3
+ import { type PostHogLike, type PosthogExposureHint } from './posthog.js';
2
4
  export interface TrackerStorage {
3
5
  get(key: string): string | null;
4
6
  set(key: string, value: string): void;
@@ -19,6 +21,43 @@ export interface TrackerOptions {
19
21
  storage?: TrackerStorage;
20
22
  /** Called when a request fails for good (a rejected batch, a bad key). Defaults to console.warn. */
21
23
  onError?: (error: Error) => void;
24
+ /**
25
+ * Record clicks, rage clicks, form submits, scroll depth and page speed automatically (browsers only; default
26
+ * false). Held until analytics consent like every other event.
27
+ * @since 1.9.0
28
+ */
29
+ autocapture?: boolean;
30
+ /**
31
+ * For autocapture: the A/B test a clicked element is part of (e.g. a slot under test), so clicks can be split by
32
+ * variant. Return null when it isn't in one.
33
+ * @since 1.9.0
34
+ */
35
+ slotTest?: (element: Element) => {
36
+ experienceId: number;
37
+ variantId: number;
38
+ } | null;
39
+ /**
40
+ * Where test exposures go when the project sends them to PostHog: your posthog-js instance. By default the page's
41
+ * `window.posthog`; pass `false` to never send them from this tracker.
42
+ * @since 1.9.0
43
+ */
44
+ posthog?: PostHogLike | false;
45
+ }
46
+ /** What an automatic capture or page-end report carries (sent as `interaction`). */
47
+ export interface InteractionData {
48
+ path: string;
49
+ selector?: string;
50
+ label?: string;
51
+ href?: string;
52
+ x?: number;
53
+ y?: number;
54
+ pageY?: number;
55
+ depth?: number;
56
+ viewportW?: number;
57
+ experienceId?: number;
58
+ variantId?: number;
59
+ engagedMs?: number;
60
+ metrics?: Vitals;
22
61
  }
23
62
  export interface ConsentChoices {
24
63
  analytics?: boolean;
@@ -53,6 +92,12 @@ export interface ExperienceDecision<TContent = Record<string, unknown>, TConfig
53
92
  config: TConfig | null;
54
93
  /** True when no request was made because analytics consent isn't granted yet. */
55
94
  waitingForConsent?: boolean;
95
+ /**
96
+ * When the project sends test exposures to PostHog: the flag and variant the tracker sent there (`$feature_flag`,
97
+ * `$feature_flag_response`). Only on a test's answer.
98
+ * @since 1.9.0
99
+ */
100
+ posthog?: PosthogExposureHint;
56
101
  /** Set when the request failed or timed out (the decision is then "none"). */
57
102
  error?: string;
58
103
  }
@@ -76,6 +121,17 @@ export declare class VeroxmTracker {
76
121
  private readonly memory;
77
122
  private readonly onError;
78
123
  private readonly keys;
124
+ private readonly autocapture;
125
+ private readonly slotTest;
126
+ private readonly posthogOption;
127
+ /** Tests whose exposure went to PostHog on this page load. */
128
+ private readonly posthogSent;
129
+ private session;
130
+ private pageState;
131
+ private pagesSeen;
132
+ private readonly vitals;
133
+ private scrollCheckedAt;
134
+ private scrollTimer;
79
135
  private visitorId;
80
136
  private consentState;
81
137
  private queue;
@@ -145,6 +201,8 @@ export declare class VeroxmTracker {
145
201
  * `config.newCheckout` of this visitor's variant, else the fallback.
146
202
  */
147
203
  getFlag<T>(placement: string, key: string, fallback: T): Promise<T>;
204
+ /** A test's exposure to the page's PostHog, once per test per page load (see posthog.ts). Consent is checked by getExperience. */
205
+ private sendToPosthog;
148
206
  /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
149
207
  subscribe(listener: () => void): () => void;
150
208
  /** Sends queued events now. Resolves when done (or deferred by a backoff). */
@@ -155,7 +213,24 @@ export declare class VeroxmTracker {
155
213
  shutdown(): void;
156
214
  private changed;
157
215
  private sendAll;
216
+ /**
217
+ * Queues an event; returns its session id. Reports (page end, scroll, vitals) pass their page's fixed id, time and
218
+ * session: an unsent copy in the queue is replaced, and a re-sent one replaces the stored one (same id and time).
219
+ */
158
220
  private enqueue;
221
+ /** The session an event now belongs to (D4), kept on the device only when allowed. */
222
+ private sessionFor;
223
+ private saveSession;
224
+ /** Stops the page's visible-time clock (the tab was hidden or left). */
225
+ private pausePage;
226
+ /** The page's reports: engaged time, and with autocapture its scroll depth and page speed. Safe to call repeatedly. */
227
+ private reportPage;
228
+ /** Updates the page's deepest scroll bucket (at most every 250 ms unless forced). */
229
+ private checkScroll;
230
+ private startAutocapture;
231
+ private clickData;
232
+ /** LCP, INP (approximated by the longest interaction), CLS -- where the browser measures them. */
233
+ private observeVitals;
159
234
  private post;
160
235
  private canSend;
161
236
  /** Whether anything may be written to the device. */