@veroxm/sdk 1.10.0 → 1.12.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.12.0
4
+
5
+ - Safe retries for writes: `content(slug).create()`, `update()`, `delete()` and `functions.call()` take an
6
+ `idempotencyKey` (any text, 1 to 255 visible characters; a new UUID per write). It is sent as `Idempotency-Key`,
7
+ and the server does the write once for that key: a repeat within 24 hours gets the first answer back. With a key, the
8
+ write is retried like a read, with the app's `retries` or the call's own `retries`, including while the first
9
+ attempt is still running (409 `idempotency_in_progress`). Without a key, writes are never retried, as before. Needs a
10
+ VeroXM server with Idempotency-Key support; an older one ignores the header.
11
+
12
+ ## 1.11.0
13
+
14
+ - Query text: `content(slug).list({ q })`, `search({ q })` and `count({ q })` take one readable line instead of `where`
15
+ and `sort`: `city = "Riyadh" AND area >= 500 ORDER BY area DESC` (`= != > >= < <= ~`, `IN`, `NOT IN`, `BETWEEN`,
16
+ `IS [NOT] EMPTY`, `AND`, `ORDER BY`, dates like `-30d`). A query that doesn't parse rejects with a `VeroXMApiError`
17
+ whose `code` is `invalid_query`. Needs a VeroXM server with query text; without `q`, requests are unchanged.
18
+
3
19
  ## 1.10.0
4
20
 
5
21
  - Timeouts, retries and cancelling, all off unless you set them. `initializeApp({ timeoutMs, retries })` sets them for
@@ -7,6 +23,11 @@
7
23
  `AbortSignal`) and their own `timeoutMs`. A request that runs out of time rejects with the new `VeroXMTimeoutError`
8
24
  (`code: 'timeout'`). Only GET and HEAD requests are retried, after a network error, a timeout, or 429, 502, 503 or
9
25
  504, with backoff and the API's `Retry-After` (up to 10 s). File uploads don't take the app's time limit.
26
+ - `graphqlRequest({ baseUrl, token, query, variables, signal, timeoutMs, retries })` sends a GraphQL document to
27
+ `/public/v2/graphql` and returns its `data`; answers with `errors` reject with the new `VeroXMGraphQLError` (a
28
+ `VeroXMApiError` with `errors`, and `code` from the first error's `extensions.code`). A document with a mutation is
29
+ never retried. `@veroxm/react-sdk` 1.5 reads through it. `fetch` sends with your own fetch (e.g. adding Next.js
30
+ cache options).
10
31
 
11
32
  ## 1.9.0
12
33
 
package/README.md CHANGED
@@ -413,6 +413,26 @@ controller.abort(); // rejects with an AbortError
413
413
  - **`signal`** (call): taken by `list`, `search`, `count`, `get`, `functions.call` and `functions.get`. A cancelled call
414
414
  rejects with the signal's reason and stops any wait for a retry.
415
415
 
416
+ ## GraphQL
417
+
418
+ From 1.10, `graphqlRequest` sends a document to the public GraphQL API and returns its `data`:
419
+
420
+ ```ts
421
+ import { graphqlRequest, VeroXMGraphQLError } from '@veroxm/sdk';
422
+
423
+ const data = await graphqlRequest<{ entries: { items: unknown[] } }>({
424
+ baseUrl: 'https://cms.example.com',
425
+ token: process.env.VEROXM_API_KEY!,
426
+ query: 'query($c: String!) { entries(collection: $c, limit: 5) { items { id data } } }',
427
+ variables: { c: 'posts' },
428
+ timeoutMs: 8000,
429
+ retries: 2, // never for a document with a mutation
430
+ });
431
+ ```
432
+
433
+ An answer with `errors` rejects with `VeroXMGraphQLError` (`errors`, and `code` from the first error's
434
+ `extensions.code`). `@veroxm/react-sdk` reads through this function.
435
+
416
436
  ## Stability
417
437
 
418
438
  Follows semantic versioning. From 1.0, breaking changes come only in a major version, after at least one minor release with the
package/dist/content.d.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  import type { VeroXMApp } from './client.js';
2
- import type { RequestControl } from './http.js';
2
+ import type { RequestControl, WriteControl } from './http.js';
3
3
  export interface ListOptions extends RequestControl {
4
4
  /** Field-value filter -- an array of `{field: value}` clauses (AND'ed together), each value either a scalar or an operator object like `{like: '...'}`, `{gte: '...'}`, `{in: 'a,b,c'}`, etc. See the project's SDK Docs tab for the full operator list. */
5
5
  where?: unknown;
6
6
  whereRelation?: Record<string, Record<string, string>>;
7
7
  /** e.g. "created_at:desc" or "title:asc,created_at:desc". */
8
8
  sort?: string;
9
+ /**
10
+ * Query text instead of `where` and `sort` (not both): `city = "Riyadh" AND area >= 500 ORDER BY area DESC`. Operators
11
+ * `= != > >= < <= ~` (contains), `IN (…)`, `NOT IN (…)`, `BETWEEN a AND b`, `IS [NOT] EMPTY`, `AND`; dates like `-30d`
12
+ * or `startOfMonth()`. A query that doesn't parse rejects with a `VeroXMApiError` whose `code` is `invalid_query`.
13
+ */
14
+ q?: string;
9
15
  /** Pass "only_draft" to include unpublished entries; anything else (including omitted) returns published-only. */
10
16
  state?: 'only_draft' | string;
11
17
  offset?: number;
@@ -74,7 +80,7 @@ export declare class ContentResource<T = Record<string, unknown>> {
74
80
  * publish immediately. A database content model that allows creating entries takes its writable fields (and `id` when
75
81
  * it takes the key from you); `userId` / `ctx` say whose row it is for a model limited to the caller's rows.
76
82
  */
77
- create(data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<T>;
83
+ create(data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<T>;
78
84
  /**
79
85
  * A partial update -- only the fields present in `data` are changed.
80
86
  * Publish state follows the same rule as create(): omitting `draft` (or
@@ -83,6 +89,6 @@ export declare class ContentResource<T = Record<string, unknown>> {
83
89
  * Pass `draft: true` explicitly to keep (or return) it unpublished.
84
90
  * (A database content model has no drafts: its writable fields only.)
85
91
  */
86
- update(id: number | string, data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<T>;
87
- delete(id: number | string, options?: Pick<ListOptions, 'userId' | 'ctx'>): Promise<void>;
92
+ update(id: number | string, data: Record<string, unknown>, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<T>;
93
+ delete(id: number | string, options?: Pick<ListOptions, 'userId' | 'ctx'> & WriteControl): Promise<void>;
88
94
  }
package/dist/content.js CHANGED
@@ -9,6 +9,14 @@ function control(options) {
9
9
  ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
10
10
  };
11
11
  }
12
+ /** control() plus a write's Idempotency-Key and its retries (only the keys that were given). */
13
+ function writeControl(options) {
14
+ return {
15
+ ...control(options),
16
+ ...(options.idempotencyKey !== undefined ? { idempotencyKey: options.idempotencyKey } : {}),
17
+ ...(options.retries !== undefined ? { retries: options.retries } : {}),
18
+ };
19
+ }
12
20
  /**
13
21
  * Typed access to one content collection's entries. `T` is whatever
14
22
  * shape you expect back (the API's actual response is a plain object per
@@ -31,6 +39,7 @@ export class ContentResource {
31
39
  limit: options.limit,
32
40
  offset: options.offset,
33
41
  sort: options.sort,
42
+ q: options.q,
34
43
  state: options.state,
35
44
  count: options.count ? '1' : undefined,
36
45
  timestamps: options.timestamps ? '1' : undefined,
@@ -82,7 +91,7 @@ export class ContentResource {
82
91
  * it takes the key from you); `userId` / `ctx` say whose row it is for a model limited to the caller's rows.
83
92
  */
84
93
  async create(data, options = {}) {
85
- return this.app.request({ method: 'POST', path: this.root(), query: callerQuery(options), json: data });
94
+ return this.app.request({ method: 'POST', path: this.root(), query: callerQuery(options), json: data, ...writeControl(options) });
86
95
  }
87
96
  /**
88
97
  * A partial update -- only the fields present in `data` are changed.
@@ -93,9 +102,9 @@ export class ContentResource {
93
102
  * (A database content model has no drafts: its writable fields only.)
94
103
  */
95
104
  async update(id, data, options = {}) {
96
- return this.app.request({ method: 'PATCH', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), json: data });
105
+ return this.app.request({ method: 'PATCH', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), json: data, ...writeControl(options) });
97
106
  }
98
107
  async delete(id, options = {}) {
99
- await this.app.request({ method: 'DELETE', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options) });
108
+ await this.app.request({ method: 'DELETE', path: `${this.root()}/${encodeURIComponent(String(id))}`, query: callerQuery(options), ...writeControl(options) });
100
109
  }
101
110
  }
package/dist/embed.d.ts CHANGED
@@ -50,6 +50,19 @@ export interface FormEmbedOptions {
50
50
  endingId: string | null;
51
51
  }) => void;
52
52
  onClose?: () => void;
53
+ /**
54
+ * Records the send as `$form_submitted` (usable as an experience's goal): your @veroxm/sdk tracker. The script-tag
55
+ * embed uses the VeroXM script tag's tracker (window.veroxm) when the page has it. Pass `false` to not record it.
56
+ * @since 1.10.0
57
+ */
58
+ tracker?: FormEmbedTracker | false;
59
+ }
60
+ /** The part of a VeroxmTracker the embed uses (structural: this file has no imports). */
61
+ export interface FormEmbedTracker {
62
+ formSubmitted(form: string, submission: {
63
+ responseId?: string;
64
+ endingId?: string | null;
65
+ }): void;
53
66
  }
54
67
  export interface FormEmbed {
55
68
  readonly iframe: HTMLIFrameElement;
package/dist/embed.js CHANGED
@@ -32,6 +32,15 @@ function el(tag, className) {
32
32
  e.className = className;
33
33
  return e;
34
34
  }
35
+ /** The tracker a send is recorded with: the option, else the VeroXM script tag's (window.veroxm.tracker), else none. */
36
+ function submitTracker(options) {
37
+ if (options.tracker === false)
38
+ return null;
39
+ if (options.tracker)
40
+ return options.tracker;
41
+ const global = window.veroxm?.tracker;
42
+ return global && typeof global.formSubmitted === 'function' ? global : null;
43
+ }
35
44
  function resolve(target) {
36
45
  if (!target)
37
46
  return null;
@@ -177,6 +186,12 @@ export function embedForm(options) {
177
186
  options.onStarted?.();
178
187
  else if (m.type === 'submitted' && m.responseId) {
179
188
  options.onSubmit?.({ responseId: m.responseId, endingId: m.endingId ?? null });
189
+ try {
190
+ submitTracker(options)?.formSubmitted(options.form, { responseId: m.responseId, endingId: m.endingId ?? null });
191
+ }
192
+ catch {
193
+ // tracking never breaks the form
194
+ }
180
195
  if (mode === 'toast')
181
196
  storageSet(dismissKey, String(Date.now() + 3650 * 86400000));
182
197
  if (options.autoCloseSeconds !== undefined && mode !== 'inline') {
@@ -1,5 +1,5 @@
1
1
  import type { VeroXMApp } from './client.js';
2
- import type { RequestControl } from './http.js';
2
+ import type { RequestControl, WriteControl } from './http.js';
3
3
  type Query = Record<string, string | number | boolean | undefined>;
4
4
  /**
5
5
  * Project functions with an HTTP trigger (Developer > Functions). Who may call one is the function's own setting:
@@ -12,10 +12,13 @@ type Query = Record<string, string | number | boolean | undefined>;
12
12
  export declare class FunctionsResource {
13
13
  private readonly app;
14
14
  constructor(app: VeroXMApp);
15
- /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
15
+ /**
16
+ * POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. With
17
+ * `idempotencyKey` the function runs once for that key, and the call is retried like a GET.
18
+ */
16
19
  call<T = unknown>(name: string, body?: Record<string, unknown> | unknown[], options?: {
17
20
  query?: Query;
18
- } & RequestControl): Promise<T>;
21
+ } & WriteControl): Promise<T>;
19
22
  /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
20
23
  get<T = unknown>(name: string, query?: Query, options?: RequestControl): Promise<T>;
21
24
  }
package/dist/functions.js CHANGED
@@ -10,10 +10,22 @@ export class FunctionsResource {
10
10
  constructor(app) {
11
11
  this.app = app;
12
12
  }
13
- /** POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. */
13
+ /**
14
+ * POST /functions/:name with `body` (an object or array) as JSON; the function reads it as `request.body`. With
15
+ * `idempotencyKey` the function runs once for that key, and the call is retried like a GET.
16
+ */
14
17
  async call(name, body, options = {}) {
15
- const { query, signal, timeoutMs } = options;
16
- return (await this.app.request({ method: 'POST', path: path(name), json: body, query, signal, timeoutMs }));
18
+ const { query, signal, timeoutMs, idempotencyKey, retries } = options;
19
+ return (await this.app.request({
20
+ method: 'POST',
21
+ path: path(name),
22
+ json: body,
23
+ query,
24
+ signal,
25
+ timeoutMs,
26
+ ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
27
+ ...(retries !== undefined ? { retries } : {}),
28
+ }));
17
29
  }
18
30
  /** GET /functions/:name (the function reads `query` as `request.query`). Retried with the app's `retries`. */
19
31
  async get(name, query = {}, options = {}) {
@@ -829,6 +829,26 @@ export interface paths {
829
829
  patch?: never;
830
830
  trace?: never;
831
831
  };
832
+ "/projects/{uuid}/files/{token}": {
833
+ parameters: {
834
+ query?: never;
835
+ header?: never;
836
+ path?: never;
837
+ cookie?: never;
838
+ };
839
+ /**
840
+ * A file kept in a connected database, by the signed link an entry carries
841
+ * @description A database model field marked as a file comes back as `{ url, expiresAt }` (or null): this is that `url`. No token: the link is the credential, for one file, one caller's view of one row, for an hour, so it works in `<img src>`. The type comes from the bytes (images and PDF are shown, anything else downloaded); never larger than 10 MB. Each use is checked again, metered and logged like any read.
842
+ */
843
+ get: operations["getDatabaseFile"];
844
+ put?: never;
845
+ post?: never;
846
+ delete?: never;
847
+ options?: never;
848
+ head?: never;
849
+ patch?: never;
850
+ trace?: never;
851
+ };
832
852
  "/projects/{uuid}/setup": {
833
853
  parameters: {
834
854
  query?: never;
@@ -900,6 +920,26 @@ export interface paths {
900
920
  patch?: never;
901
921
  trace?: never;
902
922
  };
923
+ "/projects/{uuid}/setup/types": {
924
+ parameters: {
925
+ query?: never;
926
+ header?: never;
927
+ path?: never;
928
+ cookie?: never;
929
+ };
930
+ /**
931
+ * The project's collections and database models with their types, for `veroxm types` (setup keys)
932
+ * @description Names and types only: no entries, secret values or database hosts. Each model field says how its values come back, which filter operators fit it, and whether it can be written.
933
+ */
934
+ get: operations["getProjectTypes"];
935
+ put?: never;
936
+ post?: never;
937
+ delete?: never;
938
+ options?: never;
939
+ head?: never;
940
+ patch?: never;
941
+ trace?: never;
942
+ };
903
943
  "/projects/{uuid}/setup/environment": {
904
944
  parameters: {
905
945
  query?: never;
@@ -1096,6 +1136,26 @@ export interface paths {
1096
1136
  patch?: never;
1097
1137
  trace?: never;
1098
1138
  };
1139
+ "/projects/{uuid}/queries/{slug}": {
1140
+ parameters: {
1141
+ query?: never;
1142
+ header?: never;
1143
+ path?: never;
1144
+ cookie?: never;
1145
+ };
1146
+ /**
1147
+ * A named query's entries
1148
+ * @description The entries of a query saved in the dashboard (Settings > Named queries), by its slug: its content model, filter and sort are fixed, and the answer is the same as the content list's. The key needs `read`, and database:<db>:read when the query reads a database content model. Page with `limit` and `offset` (`limit` up to the query's page limit, which is also the default). Sending `q`, `where`, `sort` or `filter.*` is 400 `fixed_query`. The `X-VeroXM-Query` header names the query.
1149
+ */
1150
+ get: operations["runNamedQuery"];
1151
+ put?: never;
1152
+ post?: never;
1153
+ delete?: never;
1154
+ options?: never;
1155
+ head?: never;
1156
+ patch?: never;
1157
+ trace?: never;
1158
+ };
1099
1159
  "/forms/{publicId}": {
1100
1160
  parameters: {
1101
1161
  query?: never;
@@ -1265,6 +1325,8 @@ export interface components {
1265
1325
  errors?: unknown;
1266
1326
  statusCode?: number;
1267
1327
  retryAfterSeconds?: number;
1328
+ /** @description With code `invalid_query`: where in the query text (`q`) the problem is, counting from 0. */
1329
+ at?: number;
1268
1330
  /** @description With code `two_step_required` or `two_step_setup_required`: send it to /auth/two-step (or /auth/two-step/setup/...) to finish signing in. Good for 10 minutes. */
1269
1331
  ticket?: string;
1270
1332
  /** @description With a ticket: the ways the person can take the second step (or set one up). */
@@ -1551,6 +1613,8 @@ export interface components {
1551
1613
  };
1552
1614
  /** @description For example "created_at:desc" or "title:asc,created_at:desc". */
1553
1615
  sort?: string;
1616
+ /** @description Query text instead of `where` and `sort` (not both): `city = "Riyadh" AND area >= 500 AND deleted_at IS EMPTY ORDER BY area DESC`. Operators `= != > >= < <= ~` (contains), `IN (…)`, `NOT IN (…)`, `BETWEEN a AND b`, `IS [NOT] EMPTY`; `OR` between values of one field; dates `-30d`, `-6h`, `now()`, `today()`, `startOfMonth()`, `startOfYear()` (UTC). A query that doesn't parse is 400 `invalid_query` with `at`, its position. */
1617
+ q?: string;
1554
1618
  /** @description "only_draft" for unpublished entries. */
1555
1619
  state?: string;
1556
1620
  offset?: number;
@@ -1784,6 +1848,7 @@ export interface components {
1784
1848
  * @enum {string}
1785
1849
  */
1786
1850
  type: "page" | "track" | "page_end" | "click" | "rage" | "submit" | "scroll" | "vitals";
1851
+ /** @description Required for track. Standard events have checked properties: `$slot_impression` ({ slot, experienceId?, variantId?, path? }) and `$form_submitted` ({ form, responseId?, endingId? }). */
1787
1852
  name?: string;
1788
1853
  properties?: {
1789
1854
  [key: string]: unknown;
@@ -1928,6 +1993,89 @@ export interface components {
1928
1993
  /** @description As in the preview. */
1929
1994
  codeManaged?: boolean;
1930
1995
  };
1996
+ TypedModelField: {
1997
+ name: string;
1998
+ /**
1999
+ * @description How values come back: string, number, number|string (a number when it fits exactly, otherwise text), boolean, json or unknown.
2000
+ * @enum {string}
2001
+ */
2002
+ kind: "string" | "number" | "number|string" | "boolean" | "json" | "unknown";
2003
+ nullable: boolean;
2004
+ /**
2005
+ * @description What the column holds, for the filter operators that make sense on it.
2006
+ * @enum {string}
2007
+ */
2008
+ family: "text" | "number" | "date" | "boolean" | "other";
2009
+ /** @description Callers may filter on it. */
2010
+ filter: boolean;
2011
+ sort: boolean;
2012
+ /** @description Callers may set it on create or update. */
2013
+ write: boolean;
2014
+ /** @description Returned as ••••<last 4> unless asked for in full. */
2015
+ masked: boolean;
2016
+ /** @description Accepted on writes, never returned. */
2017
+ writeOnly: boolean;
2018
+ /** @description Binary data, as base64 text. */
2019
+ binary?: boolean;
2020
+ /** @description A file: returned as a signed link `{ url, expiresAt }` (GET /projects/{uuid}/files/{token}) or null, never its bytes. */
2021
+ file?: boolean;
2022
+ /** @description The values an ENUM column lists. */
2023
+ values?: string[];
2024
+ };
2025
+ ProjectTypes: {
2026
+ /** @enum {string} */
2027
+ format: "veroxm.types";
2028
+ /** @enum {integer} */
2029
+ version: 1;
2030
+ project: {
2031
+ name: string;
2032
+ uuid: string;
2033
+ };
2034
+ collections: {
2035
+ slug: string;
2036
+ name: string;
2037
+ fields: {
2038
+ name: string;
2039
+ /** @description The field type: text, number, boolean, relation, media, enumeration... */
2040
+ type: string;
2041
+ /** @description relation and media: a list (true) or one (false). */
2042
+ many?: boolean;
2043
+ /** @description relation: the related collection's slug. */
2044
+ target?: string | null;
2045
+ /** @description enumeration and multi_enumeration: the listed values. */
2046
+ values?: string[];
2047
+ }[];
2048
+ }[];
2049
+ models: {
2050
+ slug: string;
2051
+ name: string;
2052
+ /** @description The connected database's slug. */
2053
+ database: string;
2054
+ key: {
2055
+ kind: string;
2056
+ family: string;
2057
+ };
2058
+ fields: components["schemas"]["TypedModelField"][];
2059
+ relations: {
2060
+ name: string;
2061
+ /** @enum {string} */
2062
+ kind: "one" | "many";
2063
+ fields: components["schemas"]["TypedModelField"][];
2064
+ }[];
2065
+ writes: {
2066
+ create: boolean;
2067
+ update: boolean;
2068
+ delete: boolean;
2069
+ };
2070
+ }[];
2071
+ databases: string[];
2072
+ processes: string[];
2073
+ /** @description Secret names, never values. */
2074
+ secrets: string[];
2075
+ allowedHosts: string[];
2076
+ /** @description The end-user roles the project lists (sign-in settings). */
2077
+ roles: string[];
2078
+ };
1931
2079
  ProjectEnvironment: {
1932
2080
  /** @description The project's name. */
1933
2081
  project: string;
@@ -3418,6 +3566,8 @@ export interface operations {
3418
3566
  listEntries: {
3419
3567
  parameters: {
3420
3568
  query?: {
3569
+ /** @description Query text instead of `where` and `sort` (not both): `city = "Riyadh" AND area >= 500 AND deleted_at IS EMPTY ORDER BY area DESC`. Operators `= != > >= < <= ~` (contains), `IN (…)`, `NOT IN (…)`, `BETWEEN a AND b`, `IS [NOT] EMPTY`; `OR` between values of one field; dates `-30d`, `-6h`, `now()`, `today()`, `startOfMonth()`, `startOfYear()` (UTC). A query that doesn't parse is 400 `invalid_query` with `at`, its position. */
3570
+ q?: string;
3421
3571
  sort?: string;
3422
3572
  state?: string;
3423
3573
  offset?: number;
@@ -3464,7 +3614,10 @@ export interface operations {
3464
3614
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3465
3615
  userId?: string;
3466
3616
  };
3467
- header?: never;
3617
+ header?: {
3618
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3619
+ "Idempotency-Key"?: string;
3620
+ };
3468
3621
  path: {
3469
3622
  /** @description The project's UUID. */
3470
3623
  uuid: string;
@@ -3584,7 +3737,10 @@ export interface operations {
3584
3737
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3585
3738
  userId?: string;
3586
3739
  };
3587
- header?: never;
3740
+ header?: {
3741
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3742
+ "Idempotency-Key"?: string;
3743
+ };
3588
3744
  path: {
3589
3745
  /** @description The project's UUID. */
3590
3746
  uuid: string;
@@ -3623,7 +3779,10 @@ export interface operations {
3623
3779
  /** @description A database content model limited to the caller's rows: whose (project keys). */
3624
3780
  userId?: string;
3625
3781
  };
3626
- header?: never;
3782
+ header?: {
3783
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3784
+ "Idempotency-Key"?: string;
3785
+ };
3627
3786
  path: {
3628
3787
  /** @description The project's UUID. */
3629
3788
  uuid: string;
@@ -3692,7 +3851,10 @@ export interface operations {
3692
3851
  uploadMedia: {
3693
3852
  parameters: {
3694
3853
  query?: never;
3695
- header?: never;
3854
+ header?: {
3855
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3856
+ "Idempotency-Key"?: string;
3857
+ };
3696
3858
  path: {
3697
3859
  /** @description The project's UUID. */
3698
3860
  uuid: string;
@@ -3724,7 +3886,10 @@ export interface operations {
3724
3886
  deleteMedia: {
3725
3887
  parameters: {
3726
3888
  query?: never;
3727
- header?: never;
3889
+ header?: {
3890
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3891
+ "Idempotency-Key"?: string;
3892
+ };
3728
3893
  path: {
3729
3894
  /** @description The project's UUID. */
3730
3895
  uuid: string;
@@ -3752,7 +3917,10 @@ export interface operations {
3752
3917
  updateMediaCaption: {
3753
3918
  parameters: {
3754
3919
  query?: never;
3755
- header?: never;
3920
+ header?: {
3921
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
3922
+ "Idempotency-Key"?: string;
3923
+ };
3756
3924
  path: {
3757
3925
  /** @description The project's UUID. */
3758
3926
  uuid: string;
@@ -3848,7 +4016,10 @@ export interface operations {
3848
4016
  callFunction: {
3849
4017
  parameters: {
3850
4018
  query?: never;
3851
- header?: never;
4019
+ header?: {
4020
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4021
+ "Idempotency-Key"?: string;
4022
+ };
3852
4023
  path: {
3853
4024
  /** @description The project's UUID. */
3854
4025
  uuid: string;
@@ -3974,7 +4145,10 @@ export interface operations {
3974
4145
  completeTask: {
3975
4146
  parameters: {
3976
4147
  query?: never;
3977
- header?: never;
4148
+ header?: {
4149
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4150
+ "Idempotency-Key"?: string;
4151
+ };
3978
4152
  path: {
3979
4153
  /** @description The project's UUID. */
3980
4154
  uuid: string;
@@ -4008,7 +4182,10 @@ export interface operations {
4008
4182
  startProcess: {
4009
4183
  parameters: {
4010
4184
  query?: never;
4011
- header?: never;
4185
+ header?: {
4186
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
4187
+ "Idempotency-Key"?: string;
4188
+ };
4012
4189
  path: {
4013
4190
  /** @description The project's UUID. */
4014
4191
  uuid: string;
@@ -4182,6 +4359,64 @@ export interface operations {
4182
4359
  504: components["responses"]["E504"];
4183
4360
  };
4184
4361
  };
4362
+ getDatabaseFile: {
4363
+ parameters: {
4364
+ query?: never;
4365
+ header?: never;
4366
+ path: {
4367
+ /** @description The project's UUID. */
4368
+ uuid: string;
4369
+ /** @description The last part of the link, as the entry gave it. */
4370
+ token: string;
4371
+ };
4372
+ cookie?: never;
4373
+ };
4374
+ requestBody?: never;
4375
+ responses: {
4376
+ /** @description The file */
4377
+ 200: {
4378
+ headers: {
4379
+ [name: string]: unknown;
4380
+ };
4381
+ content: {
4382
+ "image/png": string;
4383
+ "image/jpeg": string;
4384
+ "image/gif": string;
4385
+ "image/webp": string;
4386
+ "image/bmp": string;
4387
+ "image/avif": string;
4388
+ "application/pdf": string;
4389
+ "image/svg+xml": string;
4390
+ "application/zip": string;
4391
+ "application/octet-stream": string;
4392
+ };
4393
+ };
4394
+ 403: components["responses"]["E403"];
4395
+ 404: components["responses"]["E404"];
4396
+ /** @description The file is over 10 MB */
4397
+ 413: {
4398
+ headers: {
4399
+ [name: string]: unknown;
4400
+ };
4401
+ content: {
4402
+ "application/json": components["schemas"]["Error"];
4403
+ };
4404
+ };
4405
+ /** @description The column's value isn't a file (binary data, a data URL or base64) */
4406
+ 422: {
4407
+ headers: {
4408
+ [name: string]: unknown;
4409
+ };
4410
+ content: {
4411
+ "application/json": components["schemas"]["Error"];
4412
+ };
4413
+ };
4414
+ 429: components["responses"]["E429"];
4415
+ 502: components["responses"]["E502"];
4416
+ 503: components["responses"]["E503"];
4417
+ 504: components["responses"]["E504"];
4418
+ };
4419
+ };
4185
4420
  exportSetup: {
4186
4421
  parameters: {
4187
4422
  query?: never;
@@ -4310,6 +4545,33 @@ export interface operations {
4310
4545
  429: components["responses"]["E429"];
4311
4546
  };
4312
4547
  };
4548
+ getProjectTypes: {
4549
+ parameters: {
4550
+ query?: never;
4551
+ header?: never;
4552
+ path: {
4553
+ /** @description The project's UUID. */
4554
+ uuid: string;
4555
+ };
4556
+ cookie?: never;
4557
+ };
4558
+ requestBody?: never;
4559
+ responses: {
4560
+ /** @description OK */
4561
+ 200: {
4562
+ headers: {
4563
+ [name: string]: unknown;
4564
+ };
4565
+ content: {
4566
+ "application/json": components["schemas"]["ProjectTypes"];
4567
+ };
4568
+ };
4569
+ 401: components["responses"]["E401"];
4570
+ 403: components["responses"]["E403"];
4571
+ 404: components["responses"]["E404"];
4572
+ 429: components["responses"]["E429"];
4573
+ };
4574
+ };
4313
4575
  getProjectEnvironment: {
4314
4576
  parameters: {
4315
4577
  query?: never;
@@ -4664,6 +4926,48 @@ export interface operations {
4664
4926
  429: components["responses"]["E429"];
4665
4927
  };
4666
4928
  };
4929
+ runNamedQuery: {
4930
+ parameters: {
4931
+ query?: {
4932
+ offset?: number;
4933
+ limit?: number;
4934
+ count?: string;
4935
+ timestamps?: string;
4936
+ locale?: string;
4937
+ state?: string;
4938
+ /** @description A database content model limited to the caller's rows: whose (project keys). `ctx.<name>=` likewise. */
4939
+ userId?: string;
4940
+ };
4941
+ header?: never;
4942
+ path: {
4943
+ /** @description The project's UUID. */
4944
+ uuid: string;
4945
+ /** @description The named query's slug. */
4946
+ slug: string;
4947
+ };
4948
+ cookie?: never;
4949
+ };
4950
+ requestBody?: never;
4951
+ responses: {
4952
+ /** @description OK */
4953
+ 200: {
4954
+ headers: {
4955
+ [name: string]: unknown;
4956
+ };
4957
+ content: {
4958
+ "application/json": components["schemas"]["Entry"][] | number;
4959
+ };
4960
+ };
4961
+ 400: components["responses"]["E400"];
4962
+ 401: components["responses"]["E401"];
4963
+ 403: components["responses"]["E403"];
4964
+ 404: components["responses"]["E404"];
4965
+ 429: components["responses"]["E429"];
4966
+ 502: components["responses"]["E502"];
4967
+ 503: components["responses"]["E503"];
4968
+ 504: components["responses"]["E504"];
4969
+ };
4970
+ };
4667
4971
  getPublicForm: {
4668
4972
  parameters: {
4669
4973
  query?: never;
@@ -4692,7 +4996,10 @@ export interface operations {
4692
4996
  submitFormResponse: {
4693
4997
  parameters: {
4694
4998
  query?: never;
4695
- header?: never;
4999
+ header?: {
5000
+ /** @description Makes a retry safe: the same key with the same request, within 24 hours, gets the first answer again (with `Idempotent-Replayed: true`) and the write is not done twice. The same key with a different request is a 422 `idempotency_key_reused`; while the first is still running, a 409 `idempotency_in_progress` with Retry-After. Use a new random value (a UUID) for each new write. */
5001
+ "Idempotency-Key"?: string;
5002
+ };
4696
5003
  path: {
4697
5004
  /** @description The form id (f_...). */
4698
5005
  publicId: string;
@@ -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
@@ -18,7 +18,26 @@ export interface RawRequestOptions extends RequestControl {
18
18
  /** Sent as a `multipart/form-data` body (file uploads) -- fetch sets the boundary Content-Type itself, so never set one manually alongside this. */
19
19
  form?: FormData;
20
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. */
21
+ /**
22
+ * Extra attempts for a GET or HEAD that fails in a way worth retrying (see `isRetryable`), or for a write sent with
23
+ * an `idempotencyKey`. Ignored for other writes.
24
+ */
25
+ retries?: number;
26
+ /**
27
+ * Sent as `Idempotency-Key`: the server does the write once, and answers a repeat of it (same key, same request,
28
+ * within 24 hours) with the first answer. A write with a key is retried like a GET.
29
+ */
30
+ idempotencyKey?: string;
31
+ }
32
+ /** Writes a retry can't double: the ones that take an `idempotencyKey`. */
33
+ export interface WriteControl extends RequestControl {
34
+ /**
35
+ * Makes retries safe: the server does the write once for this key (any text, 1 to 255 visible characters; a new
36
+ * UUID per write), and a repeat gets the first answer. With a key the write is retried like a GET, with the app's
37
+ * `retries` or this call's.
38
+ */
39
+ idempotencyKey?: string;
40
+ /** Extra attempts, from 0 to 5; only used with `idempotencyKey`. Overrides the app's `retries` for this call. */
22
41
  retries?: number;
23
42
  }
24
43
  /** Throws a RangeError for a `retries` that isn't a whole number from 0 to 5. */
@@ -34,4 +53,7 @@ export declare function checkTimeout(value: number | undefined): void;
34
53
  *
35
54
  * Without `timeoutMs`, `signal` or `retries` this is a single plain fetch, exactly as before those options existed.
36
55
  */
37
- export declare function rawRequest(apiBase: string, opts: RawRequestOptions): Promise<unknown>;
56
+ export declare function rawRequest(apiBase: string, opts: RawRequestOptions, internal?: {
57
+ repeatable?: boolean;
58
+ fetch?: typeof fetch;
59
+ }): Promise<unknown>;
package/dist/http.js CHANGED
@@ -29,8 +29,9 @@ function parseRetryAfter(value) {
29
29
  function isRetryable(err) {
30
30
  if (err instanceof VeroXMTimeoutError)
31
31
  return true;
32
+ // 409 idempotency_in_progress: the first request with the key is still running.
32
33
  if (err instanceof VeroXMApiError)
33
- return RETRY_STATUSES.has(err.status);
34
+ return RETRY_STATUSES.has(err.status) || (err.status === 409 && err.code === 'idempotency_in_progress');
34
35
  // fetch rejects with a TypeError when the network fails (browsers, Node's undici, React Native).
35
36
  return err instanceof TypeError;
36
37
  }
@@ -75,7 +76,7 @@ export function checkTimeout(value) {
75
76
  checkPositive('timeoutMs', value);
76
77
  }
77
78
  /** 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
+ async function attempt(url, init, control, fetchImpl) {
79
80
  const { signal, timeoutMs } = control;
80
81
  if (signal?.aborted)
81
82
  throw abortReason(signal);
@@ -90,7 +91,7 @@ async function attempt(url, init, control) {
90
91
  }, timeoutMs)
91
92
  : undefined;
92
93
  try {
93
- const res = await fetch(url, controller ? { ...init, signal: controller.signal } : init);
94
+ const res = await fetchImpl(url, controller ? { ...init, signal: controller.signal } : init);
94
95
  const text = await res.text();
95
96
  const parsed = text ? safeJsonParse(text) : null;
96
97
  if (!res.ok) {
@@ -122,7 +123,7 @@ async function attempt(url, init, control) {
122
123
  *
123
124
  * Without `timeoutMs`, `signal` or `retries` this is a single plain fetch, exactly as before those options existed.
124
125
  */
125
- export async function rawRequest(apiBase, opts) {
126
+ export async function rawRequest(apiBase, opts, internal = {}) {
126
127
  checkTimeout(opts.timeoutMs);
127
128
  checkRetries(opts.retries);
128
129
  const base = apiBase.endsWith('/') ? apiBase : `${apiBase}/`;
@@ -133,7 +134,10 @@ export async function rawRequest(apiBase, opts) {
133
134
  url.searchParams.set(key, String(value));
134
135
  }
135
136
  }
136
- const headers = { ...opts.headers };
137
+ if (opts.idempotencyKey !== undefined && !/^[\x21-\x7e]{1,255}$/.test(opts.idempotencyKey)) {
138
+ throw new RangeError('idempotencyKey must be 1 to 255 visible characters (no spaces)');
139
+ }
140
+ const headers = { ...opts.headers, ...(opts.idempotencyKey !== undefined ? { 'Idempotency-Key': opts.idempotencyKey } : {}) };
137
141
  let body;
138
142
  if (opts.form) {
139
143
  body = opts.form;
@@ -144,11 +148,14 @@ export async function rawRequest(apiBase, opts) {
144
148
  }
145
149
  const method = opts.method ?? 'GET';
146
150
  const init = { method, headers, body };
147
- const retries = REPEATABLE.has(method.toUpperCase()) ? (opts.retries ?? 0) : 0;
151
+ // `repeatable` lets a caller vouch for a POST that changes nothing (a GraphQL query). A write with an
152
+ // Idempotency-Key is done once by the server however often it is sent.
153
+ const repeatable = internal.repeatable ?? (REPEATABLE.has(method.toUpperCase()) || opts.idempotencyKey !== undefined);
154
+ const retries = repeatable ? (opts.retries ?? 0) : 0;
148
155
  const control = { signal: opts.signal, timeoutMs: opts.timeoutMs };
149
156
  for (let n = 0;; n++) {
150
157
  try {
151
- return await attempt(url.toString(), init, control);
158
+ return await attempt(url.toString(), init, control, internal.fetch ?? fetch);
152
159
  }
153
160
  catch (e) {
154
161
  if (n >= retries || !isRetryable(e) || opts.signal?.aborted)
package/dist/index.d.ts CHANGED
@@ -7,7 +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';
10
+ export type { RequestControl, WriteControl } from './http.js';
11
+ export { graphqlRequest, VeroXMGraphQLError } from './graphql.js';
12
+ export type { GraphQLErrorItem, GraphQLRequestOptions } from './graphql.js';
11
13
  export { MediaResource } from './media.js';
12
14
  export type { MediaItem, MediaPage, UploadableFile } from './media.js';
13
15
  export { FunctionsResource } from './functions.js';
@@ -18,7 +20,7 @@ export type { ProcessRun, ProcessRunDetail, ProcessRunListOptions } from './proc
18
20
  export { FormsResource } from './forms.js';
19
21
  export type { FormDetail, FormResponse, FormResponseListOptions, FormResponsePage, FormSummary } from './forms.js';
20
22
  export { embedForm, embedFormsFromPage } from './embed.js';
21
- export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions } from './embed.js';
23
+ export type { FormEmbed, FormEmbedMode, FormEmbedOpenTrigger, FormEmbedOptions, FormEmbedTracker } from './embed.js';
22
24
  export type { Schemas } from './schemas.js';
23
25
  export type { paths as ApiPaths, components as ApiComponents, operations as ApiOperations } from './generated/api.js';
24
26
  export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
@@ -28,3 +30,5 @@ export type { TokenStorage, StoredSession, AuthUser } from './token-storage.js';
28
30
  export { VeroxmTracker, createTracker } from './tracker.js';
29
31
  export type { TrackerOptions, TrackerStorage, ConsentChoices, ConsentValue, StoredConsent, ExperienceDecision, GetExperienceOptions, Recommendations, } from './tracker.js';
30
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';
@@ -14,3 +16,5 @@ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXM
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,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,6 +1,7 @@
1
1
  import type { Schemas } from './schemas.js';
2
2
  import { type Vitals } from './autocapture.js';
3
3
  import { type PostHogLike, type PosthogExposureHint } from './posthog.js';
4
+ import { type FormSubmission, type SlotTestVariant } from './standard-events.js';
4
5
  export interface TrackerStorage {
5
6
  get(key: string): string | null;
6
7
  set(key: string, value: string): void;
@@ -129,6 +130,8 @@ export declare class VeroxmTracker {
129
130
  private session;
130
131
  private pageState;
131
132
  private pagesSeen;
133
+ /** Slot impressions sent for this page view (slot:variant). */
134
+ private readonly impressions;
132
135
  private readonly vitals;
133
136
  private scrollCheckedAt;
134
137
  private scrollTimer;
@@ -150,6 +153,18 @@ export declare class VeroxmTracker {
150
153
  getConsent(): StoredConsent;
151
154
  /** Records an action, e.g. track('demo_requested', { plan: 'enterprise' }). */
152
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;
153
168
  /** Records a page or screen view. In a browser, path/url/title/referrer are added automatically. */
154
169
  page(properties?: Record<string, unknown>): void;
155
170
  /** Saves the visitor's consent answers (true = granted, false = denied, omitted = unchanged). */
package/dist/tracker.js CHANGED
@@ -48,10 +48,14 @@
48
48
  // data-veroxm-ignore on an element (or an ancestor) leaves it out;
49
49
  // data-veroxm-mask keeps its text out. Held until consent like everything else.
50
50
  //
51
+ // Standard events (increment 8): slotImpression() and formSubmitted() send `$slot_impression` and `$form_submitted`,
52
+ // `track` events with checked properties (standard-events.ts).
53
+ //
51
54
  // PostHog (Insights I1): when the project sends test exposures to PostHog, a decision carries `posthog` and the
52
55
  // tracker sends the exposure to the page's PostHog (window.posthog, or the `posthog` option) -- see posthog.ts.
53
56
  import { ClsWindow, MAX_PATH, RageDetector, campaignKey, clickTarget, fraction, hrefFor, isIgnored, labelFor, nextSession, parseSession, scrollBucket, selectorFor, shortText, vitalsReport, } from './autocapture.js';
54
57
  import { findPosthog, readHint, sendPosthogExposure } from './posthog.js';
58
+ import { STANDARD_EVENTS, standardEventProblem } from './standard-events.js';
55
59
  const BATCH_SIZE = 20;
56
60
  const MAX_QUEUE = 1000;
57
61
  const MAX_BACKOFF_MS = 5 * 60 * 1000;
@@ -127,6 +131,8 @@ export class VeroxmTracker {
127
131
  this.session = null;
128
132
  this.pageState = null;
129
133
  this.pagesSeen = 0;
134
+ /** Slot impressions sent for this page view (slot:variant). */
135
+ this.impressions = new Set();
130
136
  this.vitals = {};
131
137
  this.scrollCheckedAt = 0;
132
138
  this.scrollTimer = null;
@@ -203,8 +209,43 @@ export class VeroxmTracker {
203
209
  }
204
210
  /** Records an action, e.g. track('demo_requested', { plan: 'enterprise' }). */
205
211
  track(name, properties) {
212
+ // A standard event the API would refuse is dropped here, so it can't get the rest of its batch rejected.
213
+ const problem = standardEventProblem(name, properties);
214
+ if (problem) {
215
+ this.onError(new Error(`VeroXM: ${name} not sent: ${problem}`));
216
+ return;
217
+ }
206
218
  this.enqueue({ type: 'track', name, properties });
207
219
  }
220
+ /**
221
+ * Records that a slot was shown (`$slot_impression`), with the visitor's variant when the slot is under test.
222
+ * Sent once per slot and variant per page view, however often it is called (re-renders don't count again).
223
+ * @since 1.10.0
224
+ */
225
+ slotImpression(slot, test) {
226
+ const key = `${slot}:${test?.variantId ?? ''}`;
227
+ if (this.impressions.has(key))
228
+ return;
229
+ this.impressions.add(key);
230
+ const path = typeof window !== 'undefined' && window.location ? window.location.pathname.slice(0, MAX_PATH) : undefined;
231
+ this.track(STANDARD_EVENTS.slotImpression, {
232
+ slot,
233
+ ...(test ? { experienceId: test.experienceId, variantId: test.variantId } : {}),
234
+ ...(path ? { path } : {}),
235
+ });
236
+ }
237
+ /**
238
+ * Records that a VeroXM form was sent (`$form_submitted`). `embedForm` and `<VeroxmForm>` call this for you when
239
+ * given a tracker. Use `$form_submitted` as an experience's goal to measure form sends.
240
+ * @since 1.10.0
241
+ */
242
+ formSubmitted(form, submission = {}) {
243
+ this.track(STANDARD_EVENTS.formSubmitted, {
244
+ form,
245
+ ...(submission.responseId ? { responseId: submission.responseId } : {}),
246
+ ...(submission.endingId !== undefined ? { endingId: submission.endingId } : {}),
247
+ });
248
+ }
208
249
  /** Records a page or screen view. In a browser, path/url/title/referrer are added automatically. */
209
250
  page(properties) {
210
251
  const auto = {};
@@ -218,6 +259,10 @@ export class VeroxmTracker {
218
259
  auto.referrer = document.referrer;
219
260
  }
220
261
  }
262
+ // A later page view (a single-page app moving on): slots shown on it count again. Impressions recorded before the
263
+ // first page() of a load belong to that first page view.
264
+ if (this.pagesSeen > 0)
265
+ this.impressions.clear();
221
266
  // A single-page app moving on: the page before it is done.
222
267
  if (this.pageState) {
223
268
  this.pausePage();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/sdk",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "VeroXM client for JavaScript and TypeScript: content, media, experiences, events and the visitor tracker.",
5
5
  "keywords": [
6
6
  "veroxm",