@veroxm/sdk 1.9.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.
@@ -1,4 +1,5 @@
1
1
  import type { VeroXMApp } from './client.js';
2
+ import type { RequestControl } from './http.js';
2
3
  type Query = Record<string, string | number | boolean | undefined>;
3
4
  /**
4
5
  * Project functions with an HTTP trigger (Developer > Functions). Who may call one is the function's own setting:
@@ -14,8 +15,8 @@ export declare class FunctionsResource {
14
15
  /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
15
16
  call<T = unknown>(name: string, body?: Record<string, unknown> | unknown[], options?: {
16
17
  query?: Query;
17
- }): Promise<T>;
18
- /** GET /functions/:name (the function reads `query` as `request.query`). */
19
- get<T = unknown>(name: string, query?: Query): Promise<T>;
18
+ } & RequestControl): Promise<T>;
19
+ /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
20
+ get<T = unknown>(name: string, query?: Query, options?: RequestControl): Promise<T>;
20
21
  }
21
22
  export {};
package/dist/functions.js CHANGED
@@ -12,11 +12,12 @@ export class FunctionsResource {
12
12
  }
13
13
  /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
14
14
  async call(name, body, options = {}) {
15
- return (await this.app.request({ method: 'POST', path: path(name), json: body, query: options.query }));
15
+ const { query, signal, timeoutMs } = options;
16
+ return (await this.app.request({ method: 'POST', path: path(name), json: body, query, signal, timeoutMs }));
16
17
  }
17
- /** GET /functions/:name (the function reads `query` as `request.query`). */
18
- async get(name, query = {}) {
19
- return (await this.app.request({ path: path(name), query }));
18
+ /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
19
+ async get(name, query = {}, options = {}) {
20
+ return (await this.app.request({ path: path(name), query, signal: options.signal, timeoutMs: options.timeoutMs }));
20
21
  }
21
22
  }
22
23
  function path(name) {
@@ -900,6 +900,97 @@ export interface paths {
900
900
  patch?: never;
901
901
  trace?: never;
902
902
  };
903
+ "/projects/{uuid}/setup/environment": {
904
+ parameters: {
905
+ query?: never;
906
+ header?: never;
907
+ path?: never;
908
+ cookie?: never;
909
+ };
910
+ /** The project's environment, and whether it counts as production (any project key) */
911
+ get: operations["getProjectEnvironment"];
912
+ put?: never;
913
+ post?: never;
914
+ delete?: never;
915
+ options?: never;
916
+ head?: never;
917
+ patch?: never;
918
+ trace?: never;
919
+ };
920
+ "/projects/{uuid}/setup/functions/{name}/calls": {
921
+ parameters: {
922
+ query?: never;
923
+ header?: never;
924
+ path?: never;
925
+ cookie?: never;
926
+ };
927
+ /**
928
+ * A function's call log, oldest first (setup keys)
929
+ * @description Without `after`: the latest `limit` calls. With it: the calls after that id, to follow new ones. The latest 200 calls of each function are kept.
930
+ */
931
+ get: operations["listFunctionCallLog"];
932
+ put?: never;
933
+ post?: never;
934
+ delete?: never;
935
+ options?: never;
936
+ head?: never;
937
+ patch?: never;
938
+ trace?: never;
939
+ };
940
+ "/projects/{uuid}/setup/functions/{name}/versions": {
941
+ parameters: {
942
+ query?: never;
943
+ header?: never;
944
+ path?: never;
945
+ cookie?: never;
946
+ };
947
+ /** A function's kept versions, newest first, without their code (setup keys) */
948
+ get: operations["listFunctionVersions"];
949
+ put?: never;
950
+ post?: never;
951
+ delete?: never;
952
+ options?: never;
953
+ head?: never;
954
+ patch?: never;
955
+ trace?: never;
956
+ };
957
+ "/projects/{uuid}/setup/functions/{name}/versions/{version}": {
958
+ parameters: {
959
+ query?: never;
960
+ header?: never;
961
+ path?: never;
962
+ cookie?: never;
963
+ };
964
+ /** One version of a function, with its code (setup keys) */
965
+ get: operations["getFunctionVersion"];
966
+ put?: never;
967
+ post?: never;
968
+ delete?: never;
969
+ options?: never;
970
+ head?: never;
971
+ patch?: never;
972
+ trace?: never;
973
+ };
974
+ "/projects/{uuid}/setup/functions/{name}/rollback": {
975
+ parameters: {
976
+ query?: never;
977
+ header?: never;
978
+ path?: never;
979
+ cookie?: never;
980
+ };
981
+ get?: never;
982
+ put?: never;
983
+ /**
984
+ * Make an earlier version of a function current again, as a new version (setup keys)
985
+ * @description Restores its code and settings (not whether it's on). A function managed in Git answers 409 (`code: "managed_in_git"`) unless `force` is true.
986
+ */
987
+ post: operations["rollbackFunction"];
988
+ delete?: never;
989
+ options?: never;
990
+ head?: never;
991
+ patch?: never;
992
+ trace?: never;
993
+ };
903
994
  "/projects/{uuid}/setup/apply": {
904
995
  parameters: {
905
996
  query?: never;
@@ -1686,15 +1777,47 @@ export interface components {
1686
1777
  */
1687
1778
  eventId?: string;
1688
1779
  visitorId: string;
1689
- /** @enum {string} */
1690
- type: "page" | "track";
1780
+ /** @description The tracker's session id (Insights). */
1781
+ sessionId?: string;
1782
+ /**
1783
+ * @description page or track; the others are Insights interactions, sent by the tracker with `interaction`.
1784
+ * @enum {string}
1785
+ */
1786
+ type: "page" | "track" | "page_end" | "click" | "rage" | "submit" | "scroll" | "vitals";
1691
1787
  name?: string;
1692
1788
  properties?: {
1693
1789
  [key: string]: unknown;
1694
1790
  };
1791
+ interaction?: components["schemas"]["InteractionInput"];
1695
1792
  /** Format: date-time */
1696
1793
  occurredAt?: string;
1697
1794
  };
1795
+ InteractionInput: {
1796
+ /** @description The page path, no query string. */
1797
+ path: string;
1798
+ selector?: string;
1799
+ /** @description Link or button text; empty when masked. */
1800
+ label?: string;
1801
+ href?: string;
1802
+ /** @description Click position as a fraction of the element (0-1). */
1803
+ x?: number;
1804
+ y?: number;
1805
+ /** @description Click position as a fraction of the page height (0-1). */
1806
+ pageY?: number;
1807
+ /** @description Scroll: the deepest 25/50/75/100 % bucket seen. */
1808
+ depth?: number;
1809
+ viewportW?: number;
1810
+ experienceId?: number;
1811
+ variantId?: number;
1812
+ /** @description Page end: visible time on the page. */
1813
+ engagedMs?: number;
1814
+ metrics?: {
1815
+ lcp?: number;
1816
+ inp?: number;
1817
+ cls?: number;
1818
+ ttfb?: number;
1819
+ };
1820
+ };
1698
1821
  EventBatch: {
1699
1822
  events: components["schemas"]["EventInput"][];
1700
1823
  };
@@ -1750,6 +1873,13 @@ export interface components {
1750
1873
  content: unknown;
1751
1874
  /** @description The variant's config (copy, flags); null when it has none. */
1752
1875
  config: unknown;
1876
+ /** @description When the project sends test exposures to PostHog (Insights): what the page sends to its own PostHog as `$feature_flag_called`. Only on a test's answer. */
1877
+ posthog?: {
1878
+ /** @description `$feature_flag`: veroxm-<experience id>. */
1879
+ flag: string;
1880
+ /** @description `$feature_flag_response`: "control", or the variant's label as a key. */
1881
+ variant: string;
1882
+ };
1753
1883
  };
1754
1884
  Recommendations: {
1755
1885
  /** @enum {string} */
@@ -1786,6 +1916,8 @@ export interface components {
1786
1916
  config: components["schemas"]["SetupFile"];
1787
1917
  /** @description Also list (and, for webhooks, functions and sign-in providers, remove) what the project has and the file doesn't. */
1788
1918
  prune?: boolean;
1919
+ /** @description The file's functions are deployed from a repository (veroxm push): they become managed in Git, read-only in the dashboard until taken over there. */
1920
+ codeManaged?: boolean;
1789
1921
  };
1790
1922
  SetupApplyRequest: {
1791
1923
  config: components["schemas"]["SetupFile"];
@@ -1793,6 +1925,91 @@ export interface components {
1793
1925
  baseHash: string;
1794
1926
  /** @description As in the preview. */
1795
1927
  prune?: boolean;
1928
+ /** @description As in the preview. */
1929
+ codeManaged?: boolean;
1930
+ };
1931
+ ProjectEnvironment: {
1932
+ /** @description The project's name. */
1933
+ project: string;
1934
+ uuid: string;
1935
+ environment: {
1936
+ name: string;
1937
+ /** @description Its place among the linked environments (production is usually 60). */
1938
+ position: number;
1939
+ /** @description Whether no environment comes after it. */
1940
+ last: boolean;
1941
+ } | null;
1942
+ /** @description True unless it is a linked environment that isn't production: tools that must stay away from production (the CLI's --remote) refuse it. */
1943
+ production: boolean;
1944
+ };
1945
+ FunctionCallRecord: {
1946
+ /** @description Increasing: send the last one seen as `after` to get newer calls. */
1947
+ id: number;
1948
+ /** @description The function version that ran. */
1949
+ version: number;
1950
+ /** @description http, test, before_save, event, process or schedule. */
1951
+ trigger: string;
1952
+ /** @enum {string} */
1953
+ status: "ok" | "error" | "timeout" | "limited";
1954
+ durationMs: number;
1955
+ /** @description The error, secret values blanked out. */
1956
+ error: string | null;
1957
+ /** @description Its log lines, secret values blanked out. */
1958
+ logs: string | null;
1959
+ caller: string | null;
1960
+ /** Format: date-time */
1961
+ createdAt: string;
1962
+ };
1963
+ FunctionCalls: {
1964
+ function: string;
1965
+ /** @description The current version. */
1966
+ version: number;
1967
+ /** @enum {string} */
1968
+ managedBy: "dashboard" | "code";
1969
+ /** @description Oldest first. */
1970
+ calls: components["schemas"]["FunctionCallRecord"][];
1971
+ };
1972
+ FunctionVersionSettings: {
1973
+ access: string;
1974
+ timeLimitMs: number;
1975
+ triggers: Record<string, never>[];
1976
+ description: string | null;
1977
+ enabled: boolean;
1978
+ };
1979
+ FunctionVersionInfo: {
1980
+ version: number;
1981
+ /** @enum {string} */
1982
+ source: "dashboard" | "code" | "rollback";
1983
+ createdBy: number | null;
1984
+ /** Format: date-time */
1985
+ createdAt: string;
1986
+ settings: components["schemas"]["FunctionVersionSettings"] | null;
1987
+ /** @description Size of its code (in the list). */
1988
+ bytes?: number;
1989
+ /** @description Its code (one version only). */
1990
+ code?: string;
1991
+ };
1992
+ FunctionVersions: {
1993
+ function: string;
1994
+ /** @description The current version. */
1995
+ version: number;
1996
+ /** @enum {string} */
1997
+ managedBy: "dashboard" | "code";
1998
+ /** @description Newest first (the newest 20 are kept). */
1999
+ versions: components["schemas"]["FunctionVersionInfo"][];
2000
+ };
2001
+ FunctionRollbackRequest: {
2002
+ /** @description The version to make current again. */
2003
+ version: number;
2004
+ /** @description Needed for a function managed in Git: the repository is behind afterwards. */
2005
+ force?: boolean;
2006
+ };
2007
+ FunctionRolledBack: {
2008
+ function: string;
2009
+ /** @description The new current version. */
2010
+ version: number;
2011
+ managedBy: string;
2012
+ rolledBackTo: number;
1796
2013
  };
1797
2014
  SetupApplied: {
1798
2015
  /** @description How many changes were made. */
@@ -4093,6 +4310,160 @@ export interface operations {
4093
4310
  429: components["responses"]["E429"];
4094
4311
  };
4095
4312
  };
4313
+ getProjectEnvironment: {
4314
+ parameters: {
4315
+ query?: never;
4316
+ header?: never;
4317
+ path: {
4318
+ /** @description The project's UUID. */
4319
+ uuid: string;
4320
+ };
4321
+ cookie?: never;
4322
+ };
4323
+ requestBody?: never;
4324
+ responses: {
4325
+ /** @description OK */
4326
+ 200: {
4327
+ headers: {
4328
+ [name: string]: unknown;
4329
+ };
4330
+ content: {
4331
+ "application/json": components["schemas"]["ProjectEnvironment"];
4332
+ };
4333
+ };
4334
+ 401: components["responses"]["E401"];
4335
+ 403: components["responses"]["E403"];
4336
+ 404: components["responses"]["E404"];
4337
+ 429: components["responses"]["E429"];
4338
+ };
4339
+ };
4340
+ listFunctionCallLog: {
4341
+ parameters: {
4342
+ query?: {
4343
+ /** @description The last call id seen. */
4344
+ after?: number;
4345
+ /** @description Only calls from this time. */
4346
+ since?: string;
4347
+ /** @description At most this many (100 by default). */
4348
+ limit?: number;
4349
+ };
4350
+ header?: never;
4351
+ path: {
4352
+ /** @description The project's UUID. */
4353
+ uuid: string;
4354
+ name: string;
4355
+ };
4356
+ cookie?: never;
4357
+ };
4358
+ requestBody?: never;
4359
+ responses: {
4360
+ /** @description OK */
4361
+ 200: {
4362
+ headers: {
4363
+ [name: string]: unknown;
4364
+ };
4365
+ content: {
4366
+ "application/json": components["schemas"]["FunctionCalls"];
4367
+ };
4368
+ };
4369
+ 400: components["responses"]["E400"];
4370
+ 401: components["responses"]["E401"];
4371
+ 403: components["responses"]["E403"];
4372
+ 404: components["responses"]["E404"];
4373
+ 429: components["responses"]["E429"];
4374
+ };
4375
+ };
4376
+ listFunctionVersions: {
4377
+ parameters: {
4378
+ query?: never;
4379
+ header?: never;
4380
+ path: {
4381
+ /** @description The project's UUID. */
4382
+ uuid: string;
4383
+ name: string;
4384
+ };
4385
+ cookie?: never;
4386
+ };
4387
+ requestBody?: never;
4388
+ responses: {
4389
+ /** @description OK */
4390
+ 200: {
4391
+ headers: {
4392
+ [name: string]: unknown;
4393
+ };
4394
+ content: {
4395
+ "application/json": components["schemas"]["FunctionVersions"];
4396
+ };
4397
+ };
4398
+ 401: components["responses"]["E401"];
4399
+ 403: components["responses"]["E403"];
4400
+ 404: components["responses"]["E404"];
4401
+ 429: components["responses"]["E429"];
4402
+ };
4403
+ };
4404
+ getFunctionVersion: {
4405
+ parameters: {
4406
+ query?: never;
4407
+ header?: never;
4408
+ path: {
4409
+ /** @description The project's UUID. */
4410
+ uuid: string;
4411
+ name: string;
4412
+ version: number;
4413
+ };
4414
+ cookie?: never;
4415
+ };
4416
+ requestBody?: never;
4417
+ responses: {
4418
+ /** @description OK */
4419
+ 200: {
4420
+ headers: {
4421
+ [name: string]: unknown;
4422
+ };
4423
+ content: {
4424
+ "application/json": components["schemas"]["FunctionVersionInfo"];
4425
+ };
4426
+ };
4427
+ 401: components["responses"]["E401"];
4428
+ 403: components["responses"]["E403"];
4429
+ 404: components["responses"]["E404"];
4430
+ 429: components["responses"]["E429"];
4431
+ };
4432
+ };
4433
+ rollbackFunction: {
4434
+ parameters: {
4435
+ query?: never;
4436
+ header?: never;
4437
+ path: {
4438
+ /** @description The project's UUID. */
4439
+ uuid: string;
4440
+ name: string;
4441
+ };
4442
+ cookie?: never;
4443
+ };
4444
+ requestBody: {
4445
+ content: {
4446
+ "application/json": components["schemas"]["FunctionRollbackRequest"];
4447
+ };
4448
+ };
4449
+ responses: {
4450
+ /** @description OK */
4451
+ 200: {
4452
+ headers: {
4453
+ [name: string]: unknown;
4454
+ };
4455
+ content: {
4456
+ "application/json": components["schemas"]["FunctionRolledBack"];
4457
+ };
4458
+ };
4459
+ 400: components["responses"]["E400"];
4460
+ 401: components["responses"]["E401"];
4461
+ 403: components["responses"]["E403"];
4462
+ 404: components["responses"]["E404"];
4463
+ 409: components["responses"]["E409"];
4464
+ 429: components["responses"]["E429"];
4465
+ };
4466
+ };
4096
4467
  applySetup: {
4097
4468
  parameters: {
4098
4469
  query?: never;
@@ -4233,6 +4604,8 @@ export interface operations {
4233
4604
  url?: string;
4234
4605
  /** @description The page that linked to it. */
4235
4606
  referrer?: string;
4607
+ /** @description The page sends test exposures to PostHog itself (the SDK sends it when the page has PostHog), so VeroXM's server doesn't. */
4608
+ posthog?: "browser";
4236
4609
  };
4237
4610
  header?: never;
4238
4611
  path: {
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,20 @@ 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
37
  export declare function rawRequest(apiBase: string, opts: RawRequestOptions): 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) {
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
@@ -7,6 +7,7 @@ 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';