@veroxm/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,461 @@
1
+ // Experience OS visitor tracking -- page views, actions, consent and
2
+ // identify, sent to POST /events, /consent and /identify
3
+ // (docs/EXPERIENCE-OS-ARCHITECTURE.md §5). Use a key with ONLY the
4
+ // "Send events" (events:write) permission: it ships in browser code.
5
+ //
6
+ // const tracker = createTracker({ baseUrl, projectId, eventsKey });
7
+ // tracker.consent({ analytics: true }); // from your consent banner
8
+ // tracker.page();
9
+ // tracker.track('demo_requested', { plan: 'enterprise' });
10
+ // tracker.identify(user.id, { plan: 'pro' });
11
+ //
12
+ // Consent first (requireConsent, the default): until analytics consent is
13
+ // granted nothing is stored on the device and nothing is sent; events are
14
+ // held in memory and sent once consent is granted, or dropped if it's
15
+ // denied. Set requireConsent: false only where you may count visitors
16
+ // without consent -- events then stay anonymous on the server until the
17
+ // visitor consents.
18
+ //
19
+ // Experiences (Phase 2): getExperience('home.hero') asks GET /decide which
20
+ // variant this visitor sees -- the variant's entry content and config, or
21
+ // reason "none" (show your default). It needs analytics consent like
22
+ // everything else (a sticky assignment needs a stored visitor id, and the
23
+ // server records an exposure); before consent it resolves to "none"
24
+ // without a request. Targeting by segment also needs personalization
25
+ // consent (the server checks). Answers are cached per placement until
26
+ // consent, identify() or reset() changes who the visitor is; subscribe()
27
+ // tells UI code when to ask again. Errors and timeouts resolve to "none"
28
+ // -- an experience never breaks the page.
29
+ //
30
+ // Recommendations: viewContent(id) records which entries a visitor reads;
31
+ // getRecommendations('articles') returns a collection's entries ranked for
32
+ // them (personal with personalization consent and some history, otherwise
33
+ // the most read).
34
+ //
35
+ // Delivery: events are batched (every flushIntervalMs or 20 events, and
36
+ // when the page is hidden), retried with backoff on network/server errors
37
+ // with the same eventId and occurredAt (so the server counts them once),
38
+ // and -- with consent -- kept in storage across page loads until sent.
39
+ const BATCH_SIZE = 20;
40
+ const MAX_QUEUE = 1000;
41
+ const MAX_BACKOFF_MS = 5 * 60 * 1000;
42
+ class MemoryStorage {
43
+ constructor() {
44
+ this.data = new Map();
45
+ }
46
+ get(key) {
47
+ return this.data.get(key) ?? null;
48
+ }
49
+ set(key, value) {
50
+ this.data.set(key, value);
51
+ }
52
+ remove(key) {
53
+ this.data.delete(key);
54
+ }
55
+ }
56
+ function browserStorage() {
57
+ try {
58
+ if (typeof window === 'undefined' || !window.localStorage)
59
+ return null;
60
+ const ls = window.localStorage;
61
+ return {
62
+ get: (k) => ls.getItem(k),
63
+ set: (k, v) => ls.setItem(k, v),
64
+ remove: (k) => ls.removeItem(k),
65
+ };
66
+ }
67
+ catch {
68
+ return null; // storage blocked (privacy mode, sandboxed iframe)
69
+ }
70
+ }
71
+ /**
72
+ * The visitor id is also kept in a first-party cookie (veroxm_vid) while
73
+ * the visitor allows it, so the site's own server can show slot A/B test
74
+ * variants on the first render. Same lifetime and consent rules as the
75
+ * id in storage; no other data goes in it.
76
+ */
77
+ const VISITOR_COOKIE = 'veroxm_vid';
78
+ function setVisitorCookie(id) {
79
+ if (typeof document === 'undefined')
80
+ return;
81
+ try {
82
+ const secure = typeof location !== 'undefined' && location.protocol === 'https:' ? '; Secure' : '';
83
+ document.cookie = id
84
+ ? `${VISITOR_COOKIE}=${encodeURIComponent(id)}; Path=/; Max-Age=31536000; SameSite=Lax${secure}`
85
+ : `${VISITOR_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
86
+ }
87
+ catch {
88
+ /* cookies blocked */
89
+ }
90
+ }
91
+ function uuid() {
92
+ const c = globalThis.crypto;
93
+ if (c?.randomUUID)
94
+ return c.randomUUID();
95
+ const bytes = new Uint8Array(16);
96
+ if (c?.getRandomValues)
97
+ c.getRandomValues(bytes);
98
+ else
99
+ for (let i = 0; i < 16; i++)
100
+ bytes[i] = Math.floor(Math.random() * 256);
101
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
102
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
103
+ const h = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
104
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
105
+ }
106
+ export class VeroxmTracker {
107
+ constructor(options) {
108
+ this.memory = new MemoryStorage();
109
+ this.queue = [];
110
+ this.timer = null;
111
+ this.sending = null;
112
+ this.backoffMs = 0;
113
+ this.retryAt = 0;
114
+ this.decisions = new Map();
115
+ this.listeners = new Set();
116
+ this.apiBase = `${options.baseUrl.replace(/\/$/, '')}/public/v2/projects/${options.projectId}`;
117
+ this.key = options.eventsKey;
118
+ this.requireConsent = options.requireConsent ?? true;
119
+ this.storage = options.storage ?? browserStorage() ?? this.memory;
120
+ this.onError = options.onError ?? ((e) => console.warn(`[veroxm] ${e.message}`));
121
+ this.keys = {
122
+ visitor: `veroxm:${options.projectId}:visitor`,
123
+ consent: `veroxm:${options.projectId}:consent`,
124
+ queue: `veroxm:${options.projectId}:queue`,
125
+ };
126
+ this.consentState = this.readConsent();
127
+ this.visitorId = this.store().get(this.keys.visitor) ?? uuid();
128
+ if (this.canPersist()) {
129
+ this.store().set(this.keys.visitor, this.visitorId);
130
+ setVisitorCookie(this.visitorId);
131
+ this.queue = this.readQueue();
132
+ }
133
+ const interval = options.flushIntervalMs ?? 5000;
134
+ if (interval > 0) {
135
+ this.timer = setInterval(() => void this.flush(), interval);
136
+ this.timer.unref?.();
137
+ }
138
+ if (typeof document !== 'undefined' && typeof window !== 'undefined') {
139
+ // The last chance to send before the tab goes away.
140
+ document.addEventListener('visibilitychange', () => {
141
+ if (document.visibilityState === 'hidden')
142
+ void this.flush({ keepalive: true });
143
+ });
144
+ window.addEventListener('pagehide', () => void this.flush({ keepalive: true }));
145
+ }
146
+ }
147
+ /** The anonymous id for this browser/app install. */
148
+ getVisitorId() {
149
+ return this.visitorId;
150
+ }
151
+ /** The visitor's stored answers, so you know whether to show your consent banner (`'unknown'` = not asked yet). */
152
+ getConsent() {
153
+ return { ...this.consentState };
154
+ }
155
+ /** Records an action, e.g. track('demo_requested', { plan: 'enterprise' }). */
156
+ track(name, properties) {
157
+ this.enqueue({ type: 'track', name, properties });
158
+ }
159
+ /** Records a page or screen view. In a browser, path/url/title/referrer are added automatically. */
160
+ page(properties) {
161
+ const auto = {};
162
+ if (typeof window !== 'undefined' && window.location) {
163
+ auto.path = window.location.pathname;
164
+ auto.url = window.location.href;
165
+ if (typeof document !== 'undefined') {
166
+ if (document.title)
167
+ auto.title = document.title;
168
+ if (document.referrer)
169
+ auto.referrer = document.referrer;
170
+ }
171
+ }
172
+ this.enqueue({ type: 'page', properties: { ...auto, ...properties } });
173
+ }
174
+ /** Saves the visitor's consent answers (true = granted, false = denied, omitted = unchanged). */
175
+ async consent(choices) {
176
+ const next = { ...this.consentState };
177
+ if (choices.analytics !== undefined)
178
+ next.analytics = choices.analytics ? 'granted' : 'denied';
179
+ if (choices.personalization !== undefined)
180
+ next.personalization = choices.personalization ? 'granted' : 'denied';
181
+ if (choices.marketing !== undefined)
182
+ next.marketing = choices.marketing ? 'granted' : 'denied';
183
+ const wasPersisting = this.canPersist();
184
+ const hadAnalytics = this.consentState.analytics === 'granted';
185
+ this.consentState = next;
186
+ if (this.canPersist()) {
187
+ this.storage.set(this.keys.consent, JSON.stringify(next));
188
+ this.storage.set(this.keys.visitor, this.visitorId);
189
+ setVisitorCookie(this.visitorId);
190
+ if (!wasPersisting)
191
+ this.saveQueue();
192
+ }
193
+ else if (next.analytics === 'denied') {
194
+ // Denied: forget everything this tracker kept about the visitor.
195
+ this.queue = [];
196
+ this.storage.remove(this.keys.queue);
197
+ this.storage.remove(this.keys.visitor);
198
+ setVisitorCookie(null);
199
+ this.storage.set(this.keys.consent, JSON.stringify(next)); // remember the answer itself
200
+ }
201
+ // A first-time "no" needs no request at all; a withdrawal must reach the
202
+ // server so the visitor's profile stops collecting.
203
+ if (next.analytics === 'denied' && this.requireConsent && !hadAnalytics) {
204
+ this.changed();
205
+ return;
206
+ }
207
+ await this.post('/consent', { visitorId: this.visitorId, ...choices }).catch((e) => this.onError(e));
208
+ this.changed(); // after the server knows: targeting depends on personalization consent
209
+ if (this.canSend())
210
+ void this.flush();
211
+ }
212
+ /** Links this visitor to your own user id (e.g. after sign-in) and updates their traits. Needs analytics consent. */
213
+ async identify(userId, traits) {
214
+ if (!this.canSend())
215
+ return;
216
+ await this.flush(); // events before the sign-in still belong to the anonymous visitor
217
+ await this.post('/identify', { visitorId: this.visitorId, userId, ...(traits ? { traits } : {}) }).catch((e) => this.onError(e));
218
+ this.changed(); // traits can change which segment the visitor is in
219
+ }
220
+ /** Call on sign-out: starts a new anonymous visitor on this device. Consent answers are kept. */
221
+ reset() {
222
+ this.queue = [];
223
+ this.visitorId = uuid();
224
+ if (this.canPersist()) {
225
+ this.storage.set(this.keys.visitor, this.visitorId);
226
+ setVisitorCookie(this.visitorId);
227
+ this.storage.remove(this.keys.queue);
228
+ }
229
+ this.changed();
230
+ }
231
+ /**
232
+ * Which variant of a placement this visitor sees, e.g.
233
+ * `const d = await tracker.getExperience('home.hero')` -- then render
234
+ * `d.content` / `d.config`, or your default when `d.reason === 'none'`.
235
+ * Never rejects. Cached per placement until the visitor changes.
236
+ */
237
+ getExperience(placement, options = {}) {
238
+ const none = (extra) => ({
239
+ placement,
240
+ experienceId: null,
241
+ variantId: null,
242
+ variant: null,
243
+ reason: 'none',
244
+ content: null,
245
+ config: null,
246
+ ...extra,
247
+ });
248
+ if (!this.canSend())
249
+ return Promise.resolve(none({ waitingForConsent: true }));
250
+ const cached = this.decisions.get(placement);
251
+ if (cached)
252
+ return cached;
253
+ const timeoutMs = options.timeoutMs ?? 1500;
254
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
255
+ const timer = setTimeout(() => controller?.abort(), timeoutMs);
256
+ const qs = `placement=${encodeURIComponent(placement)}&visitorId=${encodeURIComponent(this.visitorId)}`;
257
+ const request = fetch(`${this.apiBase}/decide?${qs}`, {
258
+ headers: { Authorization: `Bearer ${this.key}` },
259
+ ...(controller ? { signal: controller.signal } : {}),
260
+ })
261
+ .then(async (res) => {
262
+ if (!res.ok)
263
+ throw new Error(`VeroXM /decide failed with ${res.status}`);
264
+ return (await res.json());
265
+ })
266
+ .catch((err) => {
267
+ this.decisions.delete(placement); // try again next time
268
+ const message = err.name === 'AbortError' ? `VeroXM /decide timed out after ${timeoutMs} ms` : err.message;
269
+ this.onError(new Error(message));
270
+ return none({ error: message });
271
+ })
272
+ .finally(() => clearTimeout(timer));
273
+ this.decisions.set(placement, request);
274
+ return request;
275
+ }
276
+ /**
277
+ * Records that the visitor viewed a CMS entry -- the signal behind
278
+ * personal recommendations ("people who read this also read").
279
+ */
280
+ viewContent(contentId, properties) {
281
+ this.track('content_viewed', { ...properties, contentId });
282
+ }
283
+ /**
284
+ * Entries of a collection for this visitor: ranked from what they and
285
+ * similar visitors viewed when they allowed personalisation (and have
286
+ * some history), otherwise the most read. Never rejects. Works before
287
+ * consent too -- it then returns the popular ranking.
288
+ */
289
+ async getRecommendations(collection, options = {}) {
290
+ const qs = new URLSearchParams({ collection, visitorId: this.visitorId });
291
+ if (options.limit)
292
+ qs.set('limit', String(options.limit));
293
+ if (options.exclude?.length)
294
+ qs.set('exclude', options.exclude.join(','));
295
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
296
+ const timeoutMs = options.timeoutMs ?? 3000;
297
+ const timer = setTimeout(() => controller?.abort(), timeoutMs);
298
+ try {
299
+ const res = await fetch(`${this.apiBase}/recommendations?${qs}`, {
300
+ headers: { Authorization: `Bearer ${this.key}` },
301
+ ...(controller ? { signal: controller.signal } : {}),
302
+ });
303
+ if (!res.ok)
304
+ throw new Error(`VeroXM /recommendations failed with ${res.status}`);
305
+ return (await res.json());
306
+ }
307
+ catch (err) {
308
+ const message = err.name === 'AbortError' ? `VeroXM /recommendations timed out after ${timeoutMs} ms` : err.message;
309
+ this.onError(new Error(message));
310
+ return { strategy: 'popular', items: [], error: message };
311
+ }
312
+ finally {
313
+ clearTimeout(timer);
314
+ }
315
+ }
316
+ /**
317
+ * A feature flag or setting from a config-only experience:
318
+ * `await tracker.getFlag('checkout.flags', 'newCheckout', false)` reads
319
+ * `config.newCheckout` of this visitor's variant, else the fallback.
320
+ */
321
+ async getFlag(placement, key, fallback) {
322
+ const decision = await this.getExperience(placement);
323
+ const value = decision.config?.[key];
324
+ return value === undefined ? fallback : value;
325
+ }
326
+ /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
327
+ subscribe(listener) {
328
+ this.listeners.add(listener);
329
+ return () => this.listeners.delete(listener);
330
+ }
331
+ /** Sends queued events now. Resolves when done (or deferred by a backoff). */
332
+ flush(opts = {}) {
333
+ if (this.sending)
334
+ return this.sending;
335
+ if (!this.canSend() || this.queue.length === 0 || Date.now() < this.retryAt)
336
+ return Promise.resolve();
337
+ this.sending = this.sendAll(opts.keepalive ?? false).finally(() => {
338
+ this.sending = null;
339
+ });
340
+ return this.sending;
341
+ }
342
+ /** Stops the timer (tests, or a single-page app tearing the tracker down). */
343
+ shutdown() {
344
+ if (this.timer)
345
+ clearInterval(this.timer);
346
+ this.timer = null;
347
+ }
348
+ changed() {
349
+ this.decisions.clear();
350
+ for (const listener of Array.from(this.listeners)) {
351
+ try {
352
+ listener();
353
+ }
354
+ catch {
355
+ // a listener's error is the listener's problem
356
+ }
357
+ }
358
+ }
359
+ async sendAll(keepalive) {
360
+ while (this.queue.length > 0) {
361
+ const batch = this.queue.slice(0, BATCH_SIZE);
362
+ try {
363
+ await this.post('/events', { events: batch }, keepalive);
364
+ }
365
+ catch (err) {
366
+ const status = err.status;
367
+ if (status === undefined || status === 429 || status >= 500) {
368
+ // Network or server trouble: keep the events (same ids) and back off.
369
+ this.backoffMs = Math.min(this.backoffMs ? this.backoffMs * 2 : 2000, MAX_BACKOFF_MS);
370
+ this.retryAt = Date.now() + this.backoffMs;
371
+ return;
372
+ }
373
+ // 4xx: this batch will never be accepted (bad key, invalid events) -- drop it.
374
+ this.onError(err);
375
+ }
376
+ this.queue = this.queue.slice(batch.length);
377
+ this.saveQueue();
378
+ this.backoffMs = 0;
379
+ this.retryAt = 0;
380
+ }
381
+ }
382
+ enqueue(e) {
383
+ if (this.requireConsent && this.consentState.analytics === 'denied')
384
+ return;
385
+ this.queue.push({
386
+ eventId: uuid(),
387
+ visitorId: this.visitorId,
388
+ type: e.type,
389
+ ...(e.name ? { name: e.name } : {}),
390
+ ...(e.properties && Object.keys(e.properties).length ? { properties: e.properties } : {}),
391
+ occurredAt: new Date().toISOString(),
392
+ });
393
+ if (this.queue.length > MAX_QUEUE)
394
+ this.queue = this.queue.slice(-MAX_QUEUE);
395
+ this.saveQueue();
396
+ if (this.queue.length >= BATCH_SIZE)
397
+ void this.flush();
398
+ }
399
+ async post(path, body, keepalive = false) {
400
+ const res = await fetch(`${this.apiBase}${path}`, {
401
+ method: 'POST',
402
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.key}` },
403
+ body: JSON.stringify(body),
404
+ keepalive,
405
+ });
406
+ if (!res.ok) {
407
+ const text = await res.text().catch(() => '');
408
+ throw Object.assign(new Error(`VeroXM ${path} failed with ${res.status}${text ? `: ${text.slice(0, 200)}` : ''}`), {
409
+ status: res.status,
410
+ });
411
+ }
412
+ }
413
+ canSend() {
414
+ return !this.requireConsent || this.consentState.analytics === 'granted';
415
+ }
416
+ /** Whether anything may be written to the device. */
417
+ canPersist() {
418
+ return this.consentState.analytics === 'granted' || (!this.requireConsent && this.consentState.analytics !== 'denied');
419
+ }
420
+ store() {
421
+ return this.canPersist() ? this.storage : this.memory;
422
+ }
423
+ readConsent() {
424
+ try {
425
+ const raw = this.storage.get(this.keys.consent);
426
+ const parsed = raw ? JSON.parse(raw) : {};
427
+ const v = (x) => (x === 'granted' || x === 'denied' ? x : 'unknown');
428
+ return { analytics: v(parsed.analytics), personalization: v(parsed.personalization), marketing: v(parsed.marketing) };
429
+ }
430
+ catch {
431
+ return { analytics: 'unknown', personalization: 'unknown', marketing: 'unknown' };
432
+ }
433
+ }
434
+ readQueue() {
435
+ try {
436
+ const raw = this.storage.get(this.keys.queue);
437
+ const parsed = raw ? JSON.parse(raw) : [];
438
+ return Array.isArray(parsed) ? parsed.slice(-MAX_QUEUE) : [];
439
+ }
440
+ catch {
441
+ return [];
442
+ }
443
+ }
444
+ saveQueue() {
445
+ if (!this.canPersist())
446
+ return;
447
+ try {
448
+ if (this.queue.length)
449
+ this.storage.set(this.keys.queue, JSON.stringify(this.queue));
450
+ else
451
+ this.storage.remove(this.keys.queue);
452
+ }
453
+ catch {
454
+ // storage full -- events still go out from memory
455
+ }
456
+ }
457
+ }
458
+ /** Creates a tracker. One per page/app; see VeroxmTracker for the API. */
459
+ export function createTracker(options) {
460
+ return new VeroxmTracker(options);
461
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@veroxm/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "VeroXM client for JavaScript and TypeScript: content, media, experiences, events and the visitor tracker.",
5
+ "keywords": [
6
+ "veroxm",
7
+ "cms",
8
+ "headless-cms",
9
+ "experience-management",
10
+ "a-b-testing",
11
+ "personalization",
12
+ "sdk"
13
+ ],
14
+ "homepage": "https://docs.veroxm.com/sdks#veroxm-sdk",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/codewithsyedz/VeroXM.git",
18
+ "directory": "packages/sdk-js"
19
+ },
20
+ "license": "MIT",
21
+ "author": "VeroXM",
22
+ "type": "module",
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "CHANGELOG.md",
35
+ "LICENSE"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18.18"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "test": "vitest run"
46
+ },
47
+ "devDependencies": {
48
+ "vitest": "^4.1.2"
49
+ }
50
+ }