@veroxm/sdk 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +50 -1
- package/dist/autocapture.d.ts +108 -0
- package/dist/autocapture.js +323 -0
- package/dist/client.d.ts +13 -0
- package/dist/client.js +18 -5
- package/dist/content.d.ts +9 -2
- package/dist/content.js +12 -1
- package/dist/embed.d.ts +13 -0
- package/dist/embed.js +15 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +13 -0
- package/dist/functions.d.ts +4 -3
- package/dist/functions.js +5 -4
- package/dist/generated/api.d.ts +590 -2
- package/dist/graphql.d.ts +42 -0
- package/dist/graphql.js +50 -0
- package/dist/http.d.ts +23 -2
- package/dist/http.js +127 -8
- package/dist/index.d.ts +8 -2
- package/dist/index.js +5 -1
- package/dist/posthog.d.ts +27 -0
- package/dist/posthog.js +54 -0
- package/dist/standard-events.d.ts +24 -0
- package/dist/standard-events.js +40 -0
- package/dist/tracker.d.ts +90 -0
- package/dist/tracker.js +322 -14
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.11.0
|
|
4
|
+
|
|
5
|
+
- Query text: `content(slug).list({ q })`, `search({ q })` and `count({ q })` take one readable line instead of `where`
|
|
6
|
+
and `sort`: `city = "Riyadh" AND area >= 500 ORDER BY area DESC` (`= != > >= < <= ~`, `IN`, `NOT IN`, `BETWEEN`,
|
|
7
|
+
`IS [NOT] EMPTY`, `AND`, `ORDER BY`, dates like `-30d`). A query that doesn't parse rejects with a `VeroXMApiError`
|
|
8
|
+
whose `code` is `invalid_query`. Needs a VeroXM server with query text; without `q`, requests are unchanged.
|
|
9
|
+
|
|
10
|
+
## 1.10.0
|
|
11
|
+
|
|
12
|
+
- Timeouts, retries and cancelling, all off unless you set them. `initializeApp({ timeoutMs, retries })` sets them for
|
|
13
|
+
every request. `list`, `search`, `count`, `get`, `functions.call` and `functions.get` take a `signal` (an
|
|
14
|
+
`AbortSignal`) and their own `timeoutMs`. A request that runs out of time rejects with the new `VeroXMTimeoutError`
|
|
15
|
+
(`code: 'timeout'`). Only GET and HEAD requests are retried, after a network error, a timeout, or 429, 502, 503 or
|
|
16
|
+
504, with backoff and the API's `Retry-After` (up to 10 s). File uploads don't take the app's time limit.
|
|
17
|
+
- `graphqlRequest({ baseUrl, token, query, variables, signal, timeoutMs, retries })` sends a GraphQL document to
|
|
18
|
+
`/public/v2/graphql` and returns its `data`; answers with `errors` reject with the new `VeroXMGraphQLError` (a
|
|
19
|
+
`VeroXMApiError` with `errors`, and `code` from the first error's `extensions.code`). A document with a mutation is
|
|
20
|
+
never retried. `@veroxm/react-sdk` 1.5 reads through it. `fetch` sends with your own fetch (e.g. adding Next.js
|
|
21
|
+
cache options).
|
|
22
|
+
|
|
3
23
|
## 1.9.0
|
|
4
24
|
|
|
5
25
|
- Bot protection (public API 2.12): `auth.getConfig()` says what a sign-in page should show (sign-up, social sign-in,
|
package/README.md
CHANGED
|
@@ -370,7 +370,8 @@ Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, a
|
|
|
370
370
|
`.message` extracted from whichever error shape the API used, and `.code`
|
|
371
371
|
when the API gave a reason, such as `email_not_verified`, `invalid_code`,
|
|
372
372
|
`sign_up_closed` or `too_many_attempts`). A request
|
|
373
|
-
made before any sign-in call throws `VeroXMNotAuthenticatedError`.
|
|
373
|
+
made before any sign-in call throws `VeroXMNotAuthenticatedError`. A request that
|
|
374
|
+
runs past its `timeoutMs` throws `VeroXMTimeoutError` (see below).
|
|
374
375
|
|
|
375
376
|
```ts
|
|
376
377
|
import { VeroXMApiError } from '@veroxm/sdk';
|
|
@@ -384,6 +385,54 @@ try {
|
|
|
384
385
|
}
|
|
385
386
|
```
|
|
386
387
|
|
|
388
|
+
## Timeouts, retries and cancelling
|
|
389
|
+
|
|
390
|
+
From 1.10. All three are off unless you set them, so a request behaves as before until you do.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
const app = VeroXMApp.initializeApp({
|
|
394
|
+
baseUrl: 'https://cms.example.com',
|
|
395
|
+
projectId: 'YOUR-PROJECT-UUID',
|
|
396
|
+
timeoutMs: 8000, // give up after 8 s with VeroXMTimeoutError
|
|
397
|
+
retries: 2, // try a failed read twice more
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// Per call: its own time limit, or cancel it (a React effect's cleanup, a route change).
|
|
401
|
+
const controller = new AbortController();
|
|
402
|
+
const posts = await app.content('posts').list({ limit: 10, signal: controller.signal, timeoutMs: 3000 });
|
|
403
|
+
controller.abort(); // rejects with an AbortError
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
- **`timeoutMs`** (app or call): rejects with `VeroXMTimeoutError` (`code: 'timeout'`, `timeoutMs`). The API may still
|
|
407
|
+
have received the request. File uploads get no limit from the app setting; pass `timeoutMs` on the call if you want
|
|
408
|
+
one.
|
|
409
|
+
- **`retries`** (0 to 5, app only): only GET and HEAD requests are repeated, after a network error, a timeout, or a
|
|
410
|
+
429, 502, 503 or 504 answer. The SDK waits 300 ms, 600 ms, 1.2 s and so on, with jitter, or as long as the API's
|
|
411
|
+
`Retry-After` asks, up to 10 s. Writes (`create`, `update`, `delete`, `search`, `functions.call`) are never
|
|
412
|
+
repeated. `functions.get` is, so keep functions that answer GET safe to run twice.
|
|
413
|
+
- **`signal`** (call): taken by `list`, `search`, `count`, `get`, `functions.call` and `functions.get`. A cancelled call
|
|
414
|
+
rejects with the signal's reason and stops any wait for a retry.
|
|
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
|
+
|
|
387
436
|
## Stability
|
|
388
437
|
|
|
389
438
|
Follows semantic versioning. From 1.0, breaking changes come only in a major version, after at least one minor release with the
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** The parts of a DOM Element these helpers read (a real Element satisfies it). */
|
|
2
|
+
export interface ElementLike {
|
|
3
|
+
tagName: string;
|
|
4
|
+
id?: string;
|
|
5
|
+
textContent?: string | null;
|
|
6
|
+
parentElement: ElementLike | null;
|
|
7
|
+
getAttribute(name: string): string | null;
|
|
8
|
+
hasAttribute(name: string): boolean;
|
|
9
|
+
/** Space-separated classes (SVG elements have an object here; it is then ignored). */
|
|
10
|
+
className?: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Clicks count for the closest of these (with the target itself): links, buttons and marked elements. */
|
|
13
|
+
export declare const CLICK_TARGETS = "a, button, [role=button], input[type=submit], input[type=button], [data-veroxm-slot], [data-veroxm-id]";
|
|
14
|
+
/** Longest selector, label and path kept (the api enforces the same caps). */
|
|
15
|
+
export declare const MAX_SELECTOR = 300;
|
|
16
|
+
export declare const MAX_LABEL = 40;
|
|
17
|
+
export declare const MAX_PATH = 500;
|
|
18
|
+
/** True when the element or an ancestor has data-veroxm-ignore. */
|
|
19
|
+
export declare function isIgnored(el: ElementLike | null): boolean;
|
|
20
|
+
/** The link, button or marked element a click on `el` counts for (itself or the closest ancestor), else null. */
|
|
21
|
+
export declare function clickTarget(el: ElementLike | null): ElementLike | null;
|
|
22
|
+
/** Ids that change between page loads or builds (React useId, numbered, hashes) aren't stable enough to select by. */
|
|
23
|
+
export declare function isGeneratedId(id: string): boolean;
|
|
24
|
+
/** Classes worth keeping in a selector: readable names, not hashes (css-1x2y3z, sc-abc, _a1b2c), state or utility variants. */
|
|
25
|
+
export declare function isStableClass(c: string): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* A stable selector for an element (D3): its own anchor if it has one, else a
|
|
28
|
+
* short CSS path (tag, up to two stable classes, :nth-of-type when it has
|
|
29
|
+
* same-tag siblings) of at most 5 levels, starting at the nearest anchored
|
|
30
|
+
* ancestor when one is close. Capped at MAX_SELECTOR characters.
|
|
31
|
+
*/
|
|
32
|
+
export declare function selectorFor(el: ElementLike): string;
|
|
33
|
+
/** Whitespace collapsed, trimmed and cut to `max` characters (whole characters, not halves of an emoji). */
|
|
34
|
+
export declare function shortText(text: string | null | undefined, max?: number): string;
|
|
35
|
+
/** True inside data-veroxm-mask, an input, a textarea, a select or an editable region. */
|
|
36
|
+
export declare function isMasked(el: ElementLike | null): boolean;
|
|
37
|
+
/** The text of a link or button (≤ 40 characters), or '' for anything else and anything masked. Never an input's value. */
|
|
38
|
+
export declare function labelFor(el: ElementLike): string;
|
|
39
|
+
/** A link's target for the report: its path on this site, or host + path elsewhere; never the query or hash. */
|
|
40
|
+
export declare function hrefFor(href: string | null, base: string): string;
|
|
41
|
+
/** A value as a fraction 0..1 (non-finite -> 0). */
|
|
42
|
+
export declare function fraction(part: number, whole: number): number;
|
|
43
|
+
/**
|
|
44
|
+
* Rage clicks: 3 or more clicks within 1 second, all within 30 px of the
|
|
45
|
+
* latest. hit() returns true once per burst, on the click that makes it one.
|
|
46
|
+
*/
|
|
47
|
+
export declare class RageDetector {
|
|
48
|
+
private readonly count;
|
|
49
|
+
private readonly windowMs;
|
|
50
|
+
private readonly radiusPx;
|
|
51
|
+
private clicks;
|
|
52
|
+
constructor(count?: number, windowMs?: number, radiusPx?: number);
|
|
53
|
+
hit(x: number, y: number, t: number): boolean;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The deepest 25/50/75/100 % bucket of the page seen, from how far down the
|
|
57
|
+
* viewport's bottom edge has been (px) and the page's height. A page that
|
|
58
|
+
* fits in the window counts as 100.
|
|
59
|
+
*/
|
|
60
|
+
export declare function scrollBucket(viewportBottom: number, pageHeight: number): 0 | 25 | 50 | 75 | 100;
|
|
61
|
+
export interface SessionState {
|
|
62
|
+
id: string;
|
|
63
|
+
/** When the session last saw an event (ms). */
|
|
64
|
+
last: number;
|
|
65
|
+
/** The campaign touch that started it (campaignKey), or ''. */
|
|
66
|
+
campaign: string;
|
|
67
|
+
}
|
|
68
|
+
/** 30 minutes without an event ends a session. */
|
|
69
|
+
export declare const SESSION_IDLE_MS: number;
|
|
70
|
+
/**
|
|
71
|
+
* What makes a page view a new campaign touch, as a short key: its utm tags,
|
|
72
|
+
* an ad click id, or a link from another site. '' for a direct or internal
|
|
73
|
+
* visit (which never starts a session by itself).
|
|
74
|
+
*/
|
|
75
|
+
export declare function campaignKey(url: string, referrer: string): string;
|
|
76
|
+
/**
|
|
77
|
+
* The session an event at `now` belongs to (D4): the current one, unless
|
|
78
|
+
* there is none, it was idle 30 minutes, the UTC day changed, or this page
|
|
79
|
+
* view is a new campaign touch (a non-empty key different from the
|
|
80
|
+
* session's). Returns the state to keep; `newId` makes ids.
|
|
81
|
+
*/
|
|
82
|
+
export declare function nextSession(prev: SessionState | null, now: number, touch: string, newId: () => string): SessionState;
|
|
83
|
+
/** A stored session, read leniently (anything unreadable -> null). */
|
|
84
|
+
export declare function parseSession(raw: string | null): SessionState | null;
|
|
85
|
+
/**
|
|
86
|
+
* Cumulative Layout Shift as Google defines it: the largest "session
|
|
87
|
+
* window" of shifts (each less than 1 s after the previous, at most 5 s
|
|
88
|
+
* long), ignoring shifts right after input. Feed it layout-shift entries.
|
|
89
|
+
*/
|
|
90
|
+
export declare class ClsWindow {
|
|
91
|
+
value: number;
|
|
92
|
+
private current;
|
|
93
|
+
private first;
|
|
94
|
+
private lastAt;
|
|
95
|
+
add(entry: {
|
|
96
|
+
value: number;
|
|
97
|
+
startTime: number;
|
|
98
|
+
hadRecentInput?: boolean;
|
|
99
|
+
}): void;
|
|
100
|
+
}
|
|
101
|
+
export interface Vitals {
|
|
102
|
+
lcp?: number;
|
|
103
|
+
inp?: number;
|
|
104
|
+
cls?: number;
|
|
105
|
+
ttfb?: number;
|
|
106
|
+
}
|
|
107
|
+
/** Rounded vitals with only what was measured (ms, CLS to 3 decimals); null when nothing was. */
|
|
108
|
+
export declare function vitalsReport(v: Vitals): Vitals | null;
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// Insights I0 (docs/INSIGHTS-SCOPE.md): the pure parts of automatic capture
|
|
2
|
+
// -- which element a click counts for, its selector (decision D3), its
|
|
3
|
+
// label, rage clicks, scroll depth, sessions (D4) and CLS windows. The
|
|
4
|
+
// tracker wires them to the page (tracker.ts); everything here works on
|
|
5
|
+
// plain values or a minimal element shape, so it is unit-tested without a
|
|
6
|
+
// DOM.
|
|
7
|
+
//
|
|
8
|
+
// Privacy rules kept here (INSIGHTS-SCOPE "Principles"): never an input's
|
|
9
|
+
// value; text only for links and buttons, shortened, and never inside
|
|
10
|
+
// data-veroxm-mask, inputs, textareas or contenteditable; nothing at all
|
|
11
|
+
// for an element inside data-veroxm-ignore.
|
|
12
|
+
/** Clicks count for the closest of these (with the target itself): links, buttons and marked elements. */
|
|
13
|
+
export const CLICK_TARGETS = 'a, button, [role=button], input[type=submit], input[type=button], [data-veroxm-slot], [data-veroxm-id]';
|
|
14
|
+
/** Longest selector, label and path kept (the api enforces the same caps). */
|
|
15
|
+
export const MAX_SELECTOR = 300;
|
|
16
|
+
export const MAX_LABEL = 40;
|
|
17
|
+
export const MAX_PATH = 500;
|
|
18
|
+
const tag = (el) => el.tagName.toLowerCase();
|
|
19
|
+
function isClickTarget(el) {
|
|
20
|
+
const t = tag(el);
|
|
21
|
+
if (t === 'a' || t === 'button')
|
|
22
|
+
return true;
|
|
23
|
+
if (t === 'input') {
|
|
24
|
+
const type = (el.getAttribute('type') ?? '').toLowerCase();
|
|
25
|
+
return type === 'submit' || type === 'button';
|
|
26
|
+
}
|
|
27
|
+
return el.getAttribute('role') === 'button' || el.hasAttribute('data-veroxm-slot') || el.hasAttribute('data-veroxm-id');
|
|
28
|
+
}
|
|
29
|
+
/** True when the element or an ancestor has data-veroxm-ignore. */
|
|
30
|
+
export function isIgnored(el) {
|
|
31
|
+
for (let e = el; e; e = e.parentElement)
|
|
32
|
+
if (e.hasAttribute('data-veroxm-ignore'))
|
|
33
|
+
return true;
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
/** The link, button or marked element a click on `el` counts for (itself or the closest ancestor), else null. */
|
|
37
|
+
export function clickTarget(el) {
|
|
38
|
+
for (let e = el, depth = 0; e && depth < 25; e = e.parentElement, depth++) {
|
|
39
|
+
if (tag(e) === 'body' || tag(e) === 'html')
|
|
40
|
+
return null;
|
|
41
|
+
if (isClickTarget(e))
|
|
42
|
+
return e;
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
/** Ids that change between page loads or builds (React useId, numbered, hashes) aren't stable enough to select by. */
|
|
47
|
+
export function isGeneratedId(id) {
|
|
48
|
+
return !id || id.length > 64 || /[:\s]|\d{3,}|^[a-f0-9-]{8,}$|^(ember|react|radix|headlessui|mui|rc-|__next|veroxm-)/i.test(id);
|
|
49
|
+
}
|
|
50
|
+
/** Classes worth keeping in a selector: readable names, not hashes (css-1x2y3z, sc-abc, _a1b2c), state or utility variants. */
|
|
51
|
+
export function isStableClass(c) {
|
|
52
|
+
if (!/^[a-zA-Z][\w-]{0,40}$/.test(c))
|
|
53
|
+
return false; // also drops tailwind variants (hover:..., md:...)
|
|
54
|
+
if (/\d{3,}|^(css|sc|jsx|svelte|emotion|tw)-|__[a-z0-9]{5,}$|^_/.test(c))
|
|
55
|
+
return false;
|
|
56
|
+
if (/^(is|has)-|^(active|hover|focus|focused|open|selected|disabled|visible|hidden|show|current)$/i.test(c))
|
|
57
|
+
return false;
|
|
58
|
+
return !/[A-Z].*\d|\d.*[A-Z]/.test(c) || c.length < 8; // mixed-case hashes like "aB3dE9fG"
|
|
59
|
+
}
|
|
60
|
+
const cssString = (v) => `"${v.replace(/["\\]/g, '\\$&').slice(0, 120)}"`;
|
|
61
|
+
const cssIdent = (v) => v.replace(/[^\w-]/g, (ch) => `\\${ch}`);
|
|
62
|
+
/** The element's own anchor (D3, in order): data-veroxm-id, data-veroxm-slot, a stable id, a data-testid. */
|
|
63
|
+
function anchorOf(el) {
|
|
64
|
+
for (const attr of ['data-veroxm-id', 'data-veroxm-slot']) {
|
|
65
|
+
const v = el.getAttribute(attr);
|
|
66
|
+
if (v)
|
|
67
|
+
return `[${attr}=${cssString(v)}]`;
|
|
68
|
+
}
|
|
69
|
+
const id = el.id || el.getAttribute('id') || '';
|
|
70
|
+
if (id && !isGeneratedId(id))
|
|
71
|
+
return `#${cssIdent(id)}`;
|
|
72
|
+
const testId = el.getAttribute('data-testid');
|
|
73
|
+
if (testId)
|
|
74
|
+
return `[data-testid=${cssString(testId)}]`;
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
function classesOf(el) {
|
|
78
|
+
const raw = typeof el.className === 'string' ? el.className : el.getAttribute('class') ?? '';
|
|
79
|
+
return raw.split(/\s+/).filter(isStableClass).slice(0, 2);
|
|
80
|
+
}
|
|
81
|
+
/** 1-based position among same-tag siblings, or 0 when it is the only one. Needs `children` on the parent (real DOM). */
|
|
82
|
+
function nthOfType(el) {
|
|
83
|
+
const parent = el.parentElement;
|
|
84
|
+
const kids = parent?.children;
|
|
85
|
+
if (!kids)
|
|
86
|
+
return 0;
|
|
87
|
+
let n = 0;
|
|
88
|
+
let at = 0;
|
|
89
|
+
for (let i = 0; i < kids.length; i++) {
|
|
90
|
+
if (kids[i].tagName === el.tagName) {
|
|
91
|
+
n++;
|
|
92
|
+
if (kids[i] === el)
|
|
93
|
+
at = n;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return n > 1 ? at : 0;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A stable selector for an element (D3): its own anchor if it has one, else a
|
|
100
|
+
* short CSS path (tag, up to two stable classes, :nth-of-type when it has
|
|
101
|
+
* same-tag siblings) of at most 5 levels, starting at the nearest anchored
|
|
102
|
+
* ancestor when one is close. Capped at MAX_SELECTOR characters.
|
|
103
|
+
*/
|
|
104
|
+
export function selectorFor(el) {
|
|
105
|
+
const own = anchorOf(el);
|
|
106
|
+
if (own)
|
|
107
|
+
return own.slice(0, MAX_SELECTOR);
|
|
108
|
+
const parts = [];
|
|
109
|
+
for (let e = el; e && parts.length < 5; e = e.parentElement) {
|
|
110
|
+
const t = tag(e);
|
|
111
|
+
if (t === 'html' || t === 'body')
|
|
112
|
+
break;
|
|
113
|
+
const anchor = e === el ? null : anchorOf(e);
|
|
114
|
+
if (anchor) {
|
|
115
|
+
parts.unshift(anchor);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
const nth = nthOfType(e);
|
|
119
|
+
parts.unshift(t + classesOf(e).map((c) => `.${c}`).join('') + (nth ? `:nth-of-type(${nth})` : ''));
|
|
120
|
+
}
|
|
121
|
+
let sel = parts.join(' > ');
|
|
122
|
+
// Too long: drop levels from the top (the element's own part is what matters most).
|
|
123
|
+
while (sel.length > MAX_SELECTOR && parts.length > 1) {
|
|
124
|
+
parts.shift();
|
|
125
|
+
sel = parts.join(' > ');
|
|
126
|
+
}
|
|
127
|
+
return sel.slice(0, MAX_SELECTOR);
|
|
128
|
+
}
|
|
129
|
+
/** Whitespace collapsed, trimmed and cut to `max` characters (whole characters, not halves of an emoji). */
|
|
130
|
+
export function shortText(text, max = MAX_LABEL) {
|
|
131
|
+
const t = (text ?? '').replace(/\s+/g, ' ').trim();
|
|
132
|
+
const chars = Array.from(t);
|
|
133
|
+
return chars.length > max ? chars.slice(0, max).join('').trimEnd() : t;
|
|
134
|
+
}
|
|
135
|
+
/** True inside data-veroxm-mask, an input, a textarea, a select or an editable region. */
|
|
136
|
+
export function isMasked(el) {
|
|
137
|
+
for (let e = el; e; e = e.parentElement) {
|
|
138
|
+
if (e.hasAttribute('data-veroxm-mask'))
|
|
139
|
+
return true;
|
|
140
|
+
const t = tag(e);
|
|
141
|
+
if (t === 'input' || t === 'textarea' || t === 'select')
|
|
142
|
+
return true;
|
|
143
|
+
const ce = e.getAttribute('contenteditable');
|
|
144
|
+
if (ce !== null && ce !== 'false')
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
/** The text of a link or button (≤ 40 characters), or '' for anything else and anything masked. Never an input's value. */
|
|
150
|
+
export function labelFor(el) {
|
|
151
|
+
const t = tag(el);
|
|
152
|
+
const isButtonish = t === 'a' || t === 'button' || el.getAttribute('role') === 'button';
|
|
153
|
+
if (!isButtonish || isMasked(el))
|
|
154
|
+
return '';
|
|
155
|
+
return shortText(el.textContent) || shortText(el.getAttribute('aria-label'));
|
|
156
|
+
}
|
|
157
|
+
/** A link's target for the report: its path on this site, or host + path elsewhere; never the query or hash. */
|
|
158
|
+
export function hrefFor(href, base) {
|
|
159
|
+
if (!href)
|
|
160
|
+
return '';
|
|
161
|
+
try {
|
|
162
|
+
const u = new URL(href, base);
|
|
163
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:')
|
|
164
|
+
return '';
|
|
165
|
+
const own = new URL(base);
|
|
166
|
+
return (u.host === own.host ? u.pathname : `${u.host}${u.pathname}`).slice(0, MAX_PATH);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return '';
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** A value as a fraction 0..1 (non-finite -> 0). */
|
|
173
|
+
export function fraction(part, whole) {
|
|
174
|
+
if (!(whole > 0) || !Number.isFinite(part))
|
|
175
|
+
return 0;
|
|
176
|
+
return Math.round(Math.min(1, Math.max(0, part / whole)) * 1000) / 1000;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Rage clicks: 3 or more clicks within 1 second, all within 30 px of the
|
|
180
|
+
* latest. hit() returns true once per burst, on the click that makes it one.
|
|
181
|
+
*/
|
|
182
|
+
export class RageDetector {
|
|
183
|
+
constructor(count = 3, windowMs = 1000, radiusPx = 30) {
|
|
184
|
+
this.count = count;
|
|
185
|
+
this.windowMs = windowMs;
|
|
186
|
+
this.radiusPx = radiusPx;
|
|
187
|
+
this.clicks = [];
|
|
188
|
+
}
|
|
189
|
+
hit(x, y, t) {
|
|
190
|
+
const r2 = this.radiusPx * this.radiusPx;
|
|
191
|
+
this.clicks = this.clicks.filter((c) => t - c.t <= this.windowMs && (c.x - x) ** 2 + (c.y - y) ** 2 <= r2);
|
|
192
|
+
this.clicks.push({ x, y, t });
|
|
193
|
+
if (this.clicks.length >= this.count) {
|
|
194
|
+
this.clicks = [];
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The deepest 25/50/75/100 % bucket of the page seen, from how far down the
|
|
202
|
+
* viewport's bottom edge has been (px) and the page's height. A page that
|
|
203
|
+
* fits in the window counts as 100.
|
|
204
|
+
*/
|
|
205
|
+
export function scrollBucket(viewportBottom, pageHeight) {
|
|
206
|
+
if (!(pageHeight > 0) || viewportBottom >= pageHeight - 2)
|
|
207
|
+
return 100;
|
|
208
|
+
const pct = (viewportBottom / pageHeight) * 100;
|
|
209
|
+
return pct >= 75 ? 75 : pct >= 50 ? 50 : pct >= 25 ? 25 : 0;
|
|
210
|
+
}
|
|
211
|
+
/** 30 minutes without an event ends a session. */
|
|
212
|
+
export const SESSION_IDLE_MS = 30 * 60 * 1000;
|
|
213
|
+
const CLICK_IDS = ['gclid', 'gbraid', 'wbraid', 'msclkid', 'fbclid', 'ttclid', 'li_fat_id', 'twclid', 'dclid'];
|
|
214
|
+
/** Small non-cryptographic hash, so a stored campaign key never keeps a click id itself. */
|
|
215
|
+
function hash(s) {
|
|
216
|
+
let h = 5381;
|
|
217
|
+
for (let i = 0; i < s.length; i++)
|
|
218
|
+
h = ((h << 5) + h + s.charCodeAt(i)) | 0;
|
|
219
|
+
return (h >>> 0).toString(36);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* What makes a page view a new campaign touch, as a short key: its utm tags,
|
|
223
|
+
* an ad click id, or a link from another site. '' for a direct or internal
|
|
224
|
+
* visit (which never starts a session by itself).
|
|
225
|
+
*/
|
|
226
|
+
export function campaignKey(url, referrer) {
|
|
227
|
+
let u;
|
|
228
|
+
try {
|
|
229
|
+
u = new URL(url);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return '';
|
|
233
|
+
}
|
|
234
|
+
const q = u.searchParams;
|
|
235
|
+
const utm = ['utm_source', 'utm_medium', 'utm_campaign'].map((k) => q.get(k) ?? '');
|
|
236
|
+
if (utm.some(Boolean))
|
|
237
|
+
return `u${hash(utm.join('|'))}`;
|
|
238
|
+
const click = CLICK_IDS.find((k) => q.get(k));
|
|
239
|
+
if (click)
|
|
240
|
+
return `c${hash(`${click}=${q.get(click)}`)}`;
|
|
241
|
+
if (referrer) {
|
|
242
|
+
try {
|
|
243
|
+
const host = new URL(referrer).host;
|
|
244
|
+
if (host && host !== u.host)
|
|
245
|
+
return `r${hash(host)}`;
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
/* not a URL */
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return '';
|
|
252
|
+
}
|
|
253
|
+
const utcDay = (ms) => Math.floor(ms / 86400000);
|
|
254
|
+
/**
|
|
255
|
+
* The session an event at `now` belongs to (D4): the current one, unless
|
|
256
|
+
* there is none, it was idle 30 minutes, the UTC day changed, or this page
|
|
257
|
+
* view is a new campaign touch (a non-empty key different from the
|
|
258
|
+
* session's). Returns the state to keep; `newId` makes ids.
|
|
259
|
+
*/
|
|
260
|
+
export function nextSession(prev, now, touch, newId) {
|
|
261
|
+
const fresh = !prev ||
|
|
262
|
+
!prev.id ||
|
|
263
|
+
now - prev.last > SESSION_IDLE_MS ||
|
|
264
|
+
utcDay(now) !== utcDay(prev.last) ||
|
|
265
|
+
(touch !== '' && touch !== prev.campaign);
|
|
266
|
+
if (fresh)
|
|
267
|
+
return { id: newId(), last: now, campaign: touch };
|
|
268
|
+
return { id: prev.id, last: Math.max(prev.last, now), campaign: prev.campaign };
|
|
269
|
+
}
|
|
270
|
+
/** A stored session, read leniently (anything unreadable -> null). */
|
|
271
|
+
export function parseSession(raw) {
|
|
272
|
+
if (!raw)
|
|
273
|
+
return null;
|
|
274
|
+
try {
|
|
275
|
+
const s = JSON.parse(raw);
|
|
276
|
+
return typeof s.id === 'string' && /^[\w-]{1,64}$/.test(s.id) && typeof s.last === 'number'
|
|
277
|
+
? { id: s.id, last: s.last, campaign: typeof s.campaign === 'string' ? s.campaign : '' }
|
|
278
|
+
: null;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// ---------------------------------------------------------------- page speed
|
|
285
|
+
/**
|
|
286
|
+
* Cumulative Layout Shift as Google defines it: the largest "session
|
|
287
|
+
* window" of shifts (each less than 1 s after the previous, at most 5 s
|
|
288
|
+
* long), ignoring shifts right after input. Feed it layout-shift entries.
|
|
289
|
+
*/
|
|
290
|
+
export class ClsWindow {
|
|
291
|
+
constructor() {
|
|
292
|
+
this.value = 0;
|
|
293
|
+
this.current = 0;
|
|
294
|
+
this.first = 0;
|
|
295
|
+
this.lastAt = 0;
|
|
296
|
+
}
|
|
297
|
+
add(entry) {
|
|
298
|
+
if (entry.hadRecentInput)
|
|
299
|
+
return;
|
|
300
|
+
if (this.current && entry.startTime - this.lastAt < 1000 && entry.startTime - this.first < 5000) {
|
|
301
|
+
this.current += entry.value;
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
this.current = entry.value;
|
|
305
|
+
this.first = entry.startTime;
|
|
306
|
+
}
|
|
307
|
+
this.lastAt = entry.startTime;
|
|
308
|
+
this.value = Math.max(this.value, this.current);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** Rounded vitals with only what was measured (ms, CLS to 3 decimals); null when nothing was. */
|
|
312
|
+
export function vitalsReport(v) {
|
|
313
|
+
const out = {};
|
|
314
|
+
if (v.lcp !== undefined && v.lcp >= 0)
|
|
315
|
+
out.lcp = Math.round(v.lcp);
|
|
316
|
+
if (v.inp !== undefined && v.inp >= 0)
|
|
317
|
+
out.inp = Math.round(v.inp);
|
|
318
|
+
if (v.cls !== undefined && v.cls >= 0)
|
|
319
|
+
out.cls = Math.round(v.cls * 1000) / 1000;
|
|
320
|
+
if (v.ttfb !== undefined && v.ttfb >= 0)
|
|
321
|
+
out.ttfb = Math.round(v.ttfb);
|
|
322
|
+
return Object.keys(out).length ? out : null;
|
|
323
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -16,6 +16,17 @@ export interface VeroXMAppOptions {
|
|
|
16
16
|
tokenStorage?: TokenStorage;
|
|
17
17
|
/** Where a social sign-in keeps its verifier while the person is at the provider. Defaults to sessionStorage in a browser. */
|
|
18
18
|
pendingStore?: PendingStore;
|
|
19
|
+
/**
|
|
20
|
+
* Gives up on a request after this many milliseconds with `VeroXMTimeoutError`. A call can set its own `timeoutMs`.
|
|
21
|
+
* Default: no limit. File uploads aren't limited by this.
|
|
22
|
+
*/
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Extra attempts (0 to 5) for GET and HEAD requests that fail with a network error, a timeout, or 429, 502, 503 or
|
|
26
|
+
* 504, waiting 300 ms, 600 ms, 1.2 s... (or the API's Retry-After, up to 10 s) in between. Writes are never retried.
|
|
27
|
+
* Default: 0. A function answering GET runs again on a retry, so keep those safe to repeat.
|
|
28
|
+
*/
|
|
29
|
+
retries?: number;
|
|
19
30
|
}
|
|
20
31
|
/**
|
|
21
32
|
* The SDK's entry point -- one `initializeApp()` call, Firebase-style,
|
|
@@ -33,6 +44,8 @@ export declare class VeroXMApp {
|
|
|
33
44
|
/** The project's forms and responses (server keys with forms:read). */
|
|
34
45
|
readonly forms: FormsResource;
|
|
35
46
|
private readonly apiBase;
|
|
47
|
+
private readonly timeoutMs;
|
|
48
|
+
private readonly retries;
|
|
36
49
|
private constructor();
|
|
37
50
|
static initializeApp(options: VeroXMAppOptions): VeroXMApp;
|
|
38
51
|
/** Typed access to one content collection's entries (list/get/create/update/delete/search). */
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { rawRequest } from './http.js';
|
|
1
|
+
import { checkRetries, checkTimeout, rawRequest } from './http.js';
|
|
2
2
|
import { VeroXMApiError } from './errors.js';
|
|
3
3
|
import { VeroXMAuth } from './auth.js';
|
|
4
4
|
import { ContentResource } from './content.js';
|
|
@@ -20,8 +20,10 @@ function defaultTokenStorage(projectId) {
|
|
|
20
20
|
* `app.tasks` and `app.processes` for everything else. See this package's README for a full quickstart.
|
|
21
21
|
*/
|
|
22
22
|
export class VeroXMApp {
|
|
23
|
-
constructor(apiBase, tokenStorage, pendingStore) {
|
|
23
|
+
constructor(apiBase, tokenStorage, pendingStore, control = {}) {
|
|
24
24
|
this.apiBase = apiBase;
|
|
25
|
+
this.timeoutMs = control.timeoutMs;
|
|
26
|
+
this.retries = control.retries;
|
|
25
27
|
this.auth = new VeroXMAuth(apiBase, tokenStorage, pendingStore);
|
|
26
28
|
this.functions = new FunctionsResource(this);
|
|
27
29
|
this.tasks = new TasksResource(this);
|
|
@@ -29,9 +31,14 @@ export class VeroXMApp {
|
|
|
29
31
|
this.forms = new FormsResource(this);
|
|
30
32
|
}
|
|
31
33
|
static initializeApp(options) {
|
|
34
|
+
checkTimeout(options.timeoutMs);
|
|
35
|
+
checkRetries(options.retries);
|
|
32
36
|
const base = options.baseUrl.replace(/\/$/, '');
|
|
33
37
|
const apiBase = `${base}/public/v2/projects/${options.projectId}`;
|
|
34
|
-
return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId), options.pendingStore
|
|
38
|
+
return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId), options.pendingStore, {
|
|
39
|
+
timeoutMs: options.timeoutMs,
|
|
40
|
+
retries: options.retries,
|
|
41
|
+
});
|
|
35
42
|
}
|
|
36
43
|
/** Typed access to one content collection's entries (list/get/create/update/delete/search). */
|
|
37
44
|
content(collectionSlug) {
|
|
@@ -52,14 +59,20 @@ export class VeroXMApp {
|
|
|
52
59
|
* resources (`content`, `media`, `functions`, `tasks`, `processes`), or `ApiPaths` with a typed fetch helper.
|
|
53
60
|
*/
|
|
54
61
|
async request(opts) {
|
|
62
|
+
// The app's defaults, unless the call set its own. Uploads (form bodies) keep no time limit unless the call sets one.
|
|
63
|
+
const sent = {
|
|
64
|
+
...opts,
|
|
65
|
+
timeoutMs: opts.timeoutMs ?? (opts.form ? undefined : this.timeoutMs),
|
|
66
|
+
retries: opts.retries ?? this.retries,
|
|
67
|
+
};
|
|
55
68
|
const token = await this.auth.getAccessToken();
|
|
56
69
|
try {
|
|
57
|
-
return await rawRequest(this.apiBase, withAuth(
|
|
70
|
+
return await rawRequest(this.apiBase, withAuth(sent, token));
|
|
58
71
|
}
|
|
59
72
|
catch (e) {
|
|
60
73
|
if (e instanceof VeroXMApiError && e.status === 401 && this.auth.canRefresh()) {
|
|
61
74
|
const retryToken = await this.auth.forceRefreshAndGetToken();
|
|
62
|
-
return rawRequest(this.apiBase, withAuth(
|
|
75
|
+
return rawRequest(this.apiBase, withAuth(sent, retryToken));
|
|
63
76
|
}
|
|
64
77
|
throw e;
|
|
65
78
|
}
|
package/dist/content.d.ts
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import type { VeroXMApp } from './client.js';
|
|
2
|
-
|
|
2
|
+
import type { RequestControl } from './http.js';
|
|
3
|
+
export interface ListOptions extends RequestControl {
|
|
3
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. */
|
|
4
5
|
where?: unknown;
|
|
5
6
|
whereRelation?: Record<string, Record<string, string>>;
|
|
6
7
|
/** e.g. "created_at:desc" or "title:asc,created_at:desc". */
|
|
7
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;
|
|
8
15
|
/** Pass "only_draft" to include unpublished entries; anything else (including omitted) returns published-only. */
|
|
9
16
|
state?: 'only_draft' | string;
|
|
10
17
|
offset?: number;
|
|
@@ -67,7 +74,7 @@ export declare class ContentResource<T = Record<string, unknown>> {
|
|
|
67
74
|
*/
|
|
68
75
|
get(id: number | string, options?: {
|
|
69
76
|
timestamps?: boolean;
|
|
70
|
-
} & Pick<ListOptions, 'userId' | 'ctx'>): Promise<T>;
|
|
77
|
+
} & Pick<ListOptions, 'userId' | 'ctx'> & RequestControl): Promise<T>;
|
|
71
78
|
/**
|
|
72
79
|
* Fields are sent flat (no wrapper). Pass `draft: true` to create without publishing; omit it (or pass false) to
|
|
73
80
|
* publish immediately. A database content model that allows creating entries takes its writable fields (and `id` when
|