@daybook/analytics 0.0.0-stage → 0.3.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 +47 -0
- package/LICENSE +21 -0
- package/README.md +447 -3
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +30 -0
- package/dist/client.d.ts +123 -0
- package/dist/client.js +451 -0
- package/dist/context.d.ts +55 -0
- package/dist/context.js +217 -0
- package/dist/daybook.js +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +28 -0
- package/dist/log.d.ts +11 -0
- package/dist/log.js +20 -0
- package/dist/react.d.ts +27 -0
- package/dist/react.js +36 -0
- package/dist/storage.d.ts +44 -0
- package/dist/storage.js +102 -0
- package/dist/transport.d.ts +118 -0
- package/dist/transport.js +255 -0
- package/dist/types.d.ts +106 -0
- package/dist/types.js +1 -0
- package/dist/uuid.d.ts +5 -0
- package/dist/uuid.js +19 -0
- package/dist/version.d.ts +11 -0
- package/dist/version.js +11 -0
- package/dist/vue.d.ts +37 -0
- package/dist/vue.js +47 -0
- package/package.json +80 -6
package/dist/client.js
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { browserContext, campaign, clientHints, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
|
|
2
|
+
import { Log } from './log.js';
|
|
3
|
+
import { memoryStore, readState, storeFor, webStore } from './storage.js';
|
|
4
|
+
import { Outbox, Transport } from './transport.js';
|
|
5
|
+
import { uuid } from './uuid.js';
|
|
6
|
+
import { SDK_VERSION } from './version.js';
|
|
7
|
+
/**
|
|
8
|
+
* Where events go unless the site says otherwise: Daybook's hosted API, which serves
|
|
9
|
+
* `/analytics/v1` beside the feedback ingest. As permanent as the wire itself, because it ships
|
|
10
|
+
* inside bundles cached on other people's pages.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_API_URL = 'https://api.daybook.team';
|
|
13
|
+
const PAGEVIEW = '$pageview';
|
|
14
|
+
const PAGELEAVE = '$pageleave';
|
|
15
|
+
const SESSION_START = '$session_start';
|
|
16
|
+
/** However busy, a session ends after a day (PM-R-0069, as PostHog). */
|
|
17
|
+
const MAX_SESSION_MS = 24 * 60 * 60000;
|
|
18
|
+
/**
|
|
19
|
+
* Product analytics for one site (PM-R-0062).
|
|
20
|
+
*
|
|
21
|
+
* const analytics = new DaybookAnalytics({ key: 'dak_…' })
|
|
22
|
+
* analytics.track('signed_up', { plan: 'pro' })
|
|
23
|
+
*
|
|
24
|
+
* Everything a product person needs from a page without a line of code — page views, sessions, where
|
|
25
|
+
* the visitor came from, browser and device — and `track` for the rest. Every method is safe to call
|
|
26
|
+
* on the server (Next.js, Nuxt), where it does nothing.
|
|
27
|
+
*/
|
|
28
|
+
export class DaybookAnalytics {
|
|
29
|
+
constructor(options) {
|
|
30
|
+
var _a;
|
|
31
|
+
this.options = options;
|
|
32
|
+
this.context = {};
|
|
33
|
+
this.browserVersion = '';
|
|
34
|
+
this.outbox = null;
|
|
35
|
+
this.cleanup = [];
|
|
36
|
+
this.current = null;
|
|
37
|
+
/** Where the page now shown was reached from: the last page of this app, or the document's referrer. */
|
|
38
|
+
this.referrer = null;
|
|
39
|
+
this.ignored = false;
|
|
40
|
+
if (!options || typeof options.key !== 'string' || options.key.trim() === '')
|
|
41
|
+
throw new Error('@daybook/analytics: `key` is required — the ingest key from Analytics → Settings.');
|
|
42
|
+
this.log = new Log(options.debug === true);
|
|
43
|
+
this.browser = typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
44
|
+
// Two projects on one site keep apart: the stored names carry the key's first letters.
|
|
45
|
+
this.stateName = `dbk_${options.key.trim().replace(/^dak_/, '').slice(0, 8)}`;
|
|
46
|
+
this.store = this.browser ? storeFor(options.persistence ?? 'localStorage', options.cookieDomain) : memoryStore();
|
|
47
|
+
this.state = { anon: uuid(), props: {} };
|
|
48
|
+
if (!this.browser)
|
|
49
|
+
return;
|
|
50
|
+
const ua = navigator.userAgent ?? '';
|
|
51
|
+
if (options.ignoreBots !== false && isBot(ua)) {
|
|
52
|
+
this.ignored = true;
|
|
53
|
+
this.log.debug('this browser says it is a crawler; nothing is sent from it');
|
|
54
|
+
}
|
|
55
|
+
const browser = browserContext(options.appVersion);
|
|
56
|
+
this.context = browser.context;
|
|
57
|
+
this.browserVersion = browser.browserVersion;
|
|
58
|
+
// A phone's model and the real OS version arrive a moment later, where the browser gives them;
|
|
59
|
+
// every event from then on carries them.
|
|
60
|
+
void clientHints().then((hints) => Object.assign(this.context, hints));
|
|
61
|
+
this.state = this.load();
|
|
62
|
+
(_a = this.state).initial ?? (_a.initial = initialAttribution(location.href, document.referrer));
|
|
63
|
+
if (options.properties)
|
|
64
|
+
Object.assign(this.state.props, clean(options.properties));
|
|
65
|
+
this.save();
|
|
66
|
+
this.outbox = new Outbox(new Transport(options.apiUrl ?? DEFAULT_API_URL, options.key.trim()), webStore('sessionStorage'), `${this.stateName}_queue`, {
|
|
67
|
+
batchSize: Math.max(1, Math.min(1000, options.batchSize ?? 50)),
|
|
68
|
+
flushIntervalMs: Math.max(0, options.flushIntervalMs ?? 2000),
|
|
69
|
+
}, this.log);
|
|
70
|
+
this.listen();
|
|
71
|
+
if (options.autoPageviews !== false)
|
|
72
|
+
this.watchHistory();
|
|
73
|
+
}
|
|
74
|
+
/** The anonymous id this browser sends events under. */
|
|
75
|
+
get distinctId() {
|
|
76
|
+
return this.state.anon;
|
|
77
|
+
}
|
|
78
|
+
/** Who `identify()` said is signed in, or null. */
|
|
79
|
+
get userId() {
|
|
80
|
+
return this.state.user ?? null;
|
|
81
|
+
}
|
|
82
|
+
/** The current session's id; a new one starts after the session timeout without events. */
|
|
83
|
+
get sessionId() {
|
|
84
|
+
return this.state.session?.id ?? null;
|
|
85
|
+
}
|
|
86
|
+
/** Whether events are being kept back: opted out, waiting for consent, Do Not Track, or a crawler. */
|
|
87
|
+
get optedOut() {
|
|
88
|
+
return !this.sending;
|
|
89
|
+
}
|
|
90
|
+
/** Properties sent with every event, from `register()`. */
|
|
91
|
+
get registered() {
|
|
92
|
+
return { ...this.state.props };
|
|
93
|
+
}
|
|
94
|
+
/** Something the visitor did, with what describes it: `track('checkout_started', { plan: 'pro', seats: 3 })`. */
|
|
95
|
+
track(event, properties) {
|
|
96
|
+
const name = typeof event === 'string' ? event.trim() : '';
|
|
97
|
+
if (name === '' || name.length > 200) {
|
|
98
|
+
this.log.warn(`an event needs a name of 1 to 200 characters; got ${JSON.stringify(event)}`);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (name.startsWith('$')) {
|
|
102
|
+
this.log.warn(`"${name}": names starting with $ are Daybook's own. For a page view call page().`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.capture(name, properties);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* A page view, with its URL, path, title, referrer and campaign. Sent by itself on load and on every
|
|
109
|
+
* navigation unless `autoPageviews` is false; call it yourself then, after the route has changed.
|
|
110
|
+
*/
|
|
111
|
+
page(properties) {
|
|
112
|
+
if (!this.browser)
|
|
113
|
+
return;
|
|
114
|
+
const now = Date.now();
|
|
115
|
+
const route = routeOf(location);
|
|
116
|
+
const previous = this.current;
|
|
117
|
+
// A navigation in a single-page app leaves the page it came from.
|
|
118
|
+
if (previous && previous.route !== route)
|
|
119
|
+
this.leave(now);
|
|
120
|
+
const referrer = previous ? previous.url : document.referrer;
|
|
121
|
+
this.referrer = referrer;
|
|
122
|
+
this.current = { route, url: location.href, path: location.pathname, at: now };
|
|
123
|
+
this.capture(PAGEVIEW, {
|
|
124
|
+
$title: document.title,
|
|
125
|
+
$referrer: referrer || '$direct',
|
|
126
|
+
$referring_domain: referringDomain(referrer),
|
|
127
|
+
$screen_width: globalThis.screen?.width,
|
|
128
|
+
$screen_height: globalThis.screen?.height,
|
|
129
|
+
$viewport_width: window.innerWidth,
|
|
130
|
+
$viewport_height: window.innerHeight,
|
|
131
|
+
...campaign(location.href),
|
|
132
|
+
...properties,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The visitor signed in as `userId`: their events from now on are theirs, and so is everything this
|
|
137
|
+
* browser sent before, without anything being sent again. Call it after every sign-in, and on every
|
|
138
|
+
* page load while they are signed in — a repeat costs nothing.
|
|
139
|
+
*
|
|
140
|
+
* A different user signing in on the same browser starts a new anonymous id first, because one
|
|
141
|
+
* anonymous id belongs to one person.
|
|
142
|
+
*/
|
|
143
|
+
identify(userId, properties) {
|
|
144
|
+
const id = typeof userId === 'string' || typeof userId === 'number' ? String(userId).trim() : '';
|
|
145
|
+
if (id === '' || id.length > 200) {
|
|
146
|
+
this.log.warn(`identify needs a user id of 1 to 200 characters; got ${JSON.stringify(userId)}`);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (!this.browser)
|
|
150
|
+
return;
|
|
151
|
+
this.sync();
|
|
152
|
+
if (this.state.user === id) {
|
|
153
|
+
if (properties)
|
|
154
|
+
this.setPersonProperties(properties);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (this.state.user)
|
|
158
|
+
this.reset();
|
|
159
|
+
this.state.user = id;
|
|
160
|
+
this.save();
|
|
161
|
+
if (this.sending)
|
|
162
|
+
this.outbox?.push({ t: 'i', b: { distinct_id: this.state.anon, user_id: id, properties: properties ? clean(properties) : undefined } });
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The visitor signed out: a new anonymous id and session, and the registered properties forgotten,
|
|
166
|
+
* so whoever uses this browser next is somebody new. Where the browser first came from is kept, and
|
|
167
|
+
* goes to the new person with their first event, as it went to the last.
|
|
168
|
+
*/
|
|
169
|
+
reset() {
|
|
170
|
+
if (!this.browser)
|
|
171
|
+
return;
|
|
172
|
+
this.sync();
|
|
173
|
+
this.state = { anon: uuid(), props: {}, initial: this.state.initial, consent: this.state.consent };
|
|
174
|
+
this.save();
|
|
175
|
+
}
|
|
176
|
+
/** Sets (and unsets) properties of the person: their plan, their company, their role. */
|
|
177
|
+
setPersonProperties(set, unset) {
|
|
178
|
+
if (!this.browser || !this.sending)
|
|
179
|
+
return;
|
|
180
|
+
this.sync();
|
|
181
|
+
this.outbox?.push({ t: 'p', b: { ...this.who(), set: clean(set ?? {}), unset: unset?.filter((k) => typeof k === 'string') } });
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Sets properties of the person only where they have no value yet — under this browser's ids or any
|
|
185
|
+
* other the person signed in with — so the first value stays: `{ first_plan: 'free', signed_up_at: new Date() }`.
|
|
186
|
+
* A later `setPersonProperties` still changes them.
|
|
187
|
+
*/
|
|
188
|
+
setPersonPropertiesOnce(properties) {
|
|
189
|
+
if (!this.browser || !this.sending)
|
|
190
|
+
return;
|
|
191
|
+
this.sync();
|
|
192
|
+
this.outbox?.push({ t: 'p', b: { ...this.who(), set_once: clean(properties ?? {}) } });
|
|
193
|
+
}
|
|
194
|
+
who() {
|
|
195
|
+
return this.state.user ? { user_id: this.state.user } : { distinct_id: this.state.anon };
|
|
196
|
+
}
|
|
197
|
+
/** Properties sent with every later event from this browser, kept across visits until `reset()`. */
|
|
198
|
+
register(properties) {
|
|
199
|
+
if (!this.browser)
|
|
200
|
+
return;
|
|
201
|
+
this.sync();
|
|
202
|
+
Object.assign(this.state.props, clean(properties));
|
|
203
|
+
this.save();
|
|
204
|
+
}
|
|
205
|
+
unregister(name) {
|
|
206
|
+
if (!this.browser)
|
|
207
|
+
return;
|
|
208
|
+
this.sync();
|
|
209
|
+
delete this.state.props[name];
|
|
210
|
+
this.save();
|
|
211
|
+
}
|
|
212
|
+
/** The visitor agreed: send from now on, and remember it. The page they are on is counted then. */
|
|
213
|
+
optIn() {
|
|
214
|
+
if (!this.browser)
|
|
215
|
+
return;
|
|
216
|
+
const wasSending = this.sending;
|
|
217
|
+
this.state.consent = 'in';
|
|
218
|
+
this.save();
|
|
219
|
+
if (!wasSending && this.options.autoPageviews !== false)
|
|
220
|
+
this.page();
|
|
221
|
+
}
|
|
222
|
+
/** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
|
|
223
|
+
optOut() {
|
|
224
|
+
if (!this.browser)
|
|
225
|
+
return;
|
|
226
|
+
this.state.consent = 'out';
|
|
227
|
+
this.outbox?.clear();
|
|
228
|
+
this.save();
|
|
229
|
+
}
|
|
230
|
+
/** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
|
|
231
|
+
flush() {
|
|
232
|
+
return this.outbox?.flush() ?? Promise.resolve();
|
|
233
|
+
}
|
|
234
|
+
/** Stops listening and sending; for tests and hot reload. */
|
|
235
|
+
destroy() {
|
|
236
|
+
for (const undo of this.cleanup.splice(0))
|
|
237
|
+
undo();
|
|
238
|
+
this.outbox?.stop();
|
|
239
|
+
}
|
|
240
|
+
get sending() {
|
|
241
|
+
if (this.ignored)
|
|
242
|
+
return false;
|
|
243
|
+
if (this.state.consent)
|
|
244
|
+
return this.state.consent === 'in';
|
|
245
|
+
if (this.options.optOutByDefault)
|
|
246
|
+
return false;
|
|
247
|
+
if (this.options.respectDoNotTrack && doNotTrack())
|
|
248
|
+
return false;
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
capture(name, properties) {
|
|
252
|
+
if (!this.browser || !this.sending || !this.outbox)
|
|
253
|
+
return;
|
|
254
|
+
this.sync();
|
|
255
|
+
const now = Date.now();
|
|
256
|
+
const session = this.session(now);
|
|
257
|
+
// A session opens with $session_start (PM-R-0069): the page it began on, where the visitor came
|
|
258
|
+
// from and the campaign that brought them, whatever the first event of the session was.
|
|
259
|
+
if (session.fresh)
|
|
260
|
+
this.emit(SESSION_START, this.entry(), now, session.id);
|
|
261
|
+
this.emit(name, properties, now, session.id);
|
|
262
|
+
}
|
|
263
|
+
/** What a session began from: the referrer of the page it began on, and that page's campaign. */
|
|
264
|
+
entry() {
|
|
265
|
+
const referrer = this.referrer ?? document.referrer;
|
|
266
|
+
return { $referrer: referrer || '$direct', $referring_domain: referringDomain(referrer), ...campaign(location.href) };
|
|
267
|
+
}
|
|
268
|
+
emit(name, properties, now, sessionId) {
|
|
269
|
+
if (!this.outbox)
|
|
270
|
+
return;
|
|
271
|
+
const event = {
|
|
272
|
+
event: name,
|
|
273
|
+
event_id: uuid(),
|
|
274
|
+
distinct_id: this.state.anon,
|
|
275
|
+
timestamp: new Date(now).toISOString(),
|
|
276
|
+
session_id: sessionId,
|
|
277
|
+
properties: {
|
|
278
|
+
$url: location.href,
|
|
279
|
+
$path: location.pathname,
|
|
280
|
+
$host: location.host,
|
|
281
|
+
$browser_version: this.browserVersion,
|
|
282
|
+
$lib_version: SDK_VERSION,
|
|
283
|
+
...this.state.initial,
|
|
284
|
+
...this.state.props,
|
|
285
|
+
...clean(properties ?? {}),
|
|
286
|
+
},
|
|
287
|
+
context: { ...this.context },
|
|
288
|
+
};
|
|
289
|
+
if (this.state.user)
|
|
290
|
+
event.user_id = this.state.user;
|
|
291
|
+
// Where this browser first came from is its person's too (PM-T-0540): carried once, on the first
|
|
292
|
+
// event, as $set_once, which Daybook writes as set_once person properties and keeps off the event.
|
|
293
|
+
const first = !this.state.initialSent && this.state.initial !== undefined;
|
|
294
|
+
if (first)
|
|
295
|
+
event.properties.$set_once = { ...this.state.initial };
|
|
296
|
+
let final = event;
|
|
297
|
+
if (this.options.beforeSend) {
|
|
298
|
+
try {
|
|
299
|
+
final = this.options.beforeSend(event);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
this.log.warn(`beforeSend threw, so "${name}" was dropped: ${String(error)}`);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (!final) {
|
|
306
|
+
this.log.debug(`beforeSend dropped "${name}"`);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
JSON.stringify(final);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
this.log.warn(`"${name}" has properties that cannot be sent as JSON (a circular object?); it was dropped`);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
this.log.debug(`queued "${name}"`, final);
|
|
318
|
+
this.outbox.push({ t: 'e', e: final });
|
|
319
|
+
if (first)
|
|
320
|
+
this.state.initialSent = true;
|
|
321
|
+
this.save();
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* The session an event at `now` belongs to (PM-R-0069 criterion 1): the current one, or a new one
|
|
325
|
+
* after the idle timeout or once the current one is a day old. It is kept with the rest of the state,
|
|
326
|
+
* so every tab of the site shares it, and `reset()` starts a new one.
|
|
327
|
+
*/
|
|
328
|
+
session(now) {
|
|
329
|
+
const timeout = Math.max(1, this.options.sessionTimeoutMinutes ?? 30) * 60000;
|
|
330
|
+
const s = this.state.session;
|
|
331
|
+
if (!s || now - s.last > timeout || now - (s.start ?? s.last) > MAX_SESSION_MS) {
|
|
332
|
+
this.state.session = { id: uuid(), start: now, last: now };
|
|
333
|
+
return { id: this.state.session.id, fresh: true };
|
|
334
|
+
}
|
|
335
|
+
s.last = now;
|
|
336
|
+
return { id: s.id, fresh: false };
|
|
337
|
+
}
|
|
338
|
+
leave(now) {
|
|
339
|
+
const left = this.current;
|
|
340
|
+
this.current = null;
|
|
341
|
+
if (!left || this.options.pageleave === false)
|
|
342
|
+
return;
|
|
343
|
+
this.capture(PAGELEAVE, { $url: left.url, $path: left.path, $duration_ms: Math.max(0, now - left.at) });
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Page views from the History API (PM-R-0062 criterion 3): every router of a single-page app moves
|
|
347
|
+
* through pushState, replaceState or popstate. A change of the query string alone is not a new page.
|
|
348
|
+
* The view is sent a moment later, so the router has set the new page's title.
|
|
349
|
+
*/
|
|
350
|
+
watchHistory() {
|
|
351
|
+
const check = () => setTimeout(() => {
|
|
352
|
+
if (!this.current || this.current.route !== routeOf(location))
|
|
353
|
+
this.page();
|
|
354
|
+
// The same page with another query: still the page, but the address the next one came from.
|
|
355
|
+
else
|
|
356
|
+
this.current.url = location.href;
|
|
357
|
+
}, 0);
|
|
358
|
+
const patch = (method) => {
|
|
359
|
+
const original = history[method];
|
|
360
|
+
const patched = function (...args) {
|
|
361
|
+
const result = original.apply(this, args);
|
|
362
|
+
check();
|
|
363
|
+
return result;
|
|
364
|
+
};
|
|
365
|
+
history[method] = patched;
|
|
366
|
+
this.cleanup.push(() => { if (history[method] === patched)
|
|
367
|
+
history[method] = original; });
|
|
368
|
+
};
|
|
369
|
+
patch('pushState');
|
|
370
|
+
patch('replaceState');
|
|
371
|
+
this.on(window, 'popstate', check);
|
|
372
|
+
this.on(window, 'hashchange', check);
|
|
373
|
+
if (document.readyState === 'loading')
|
|
374
|
+
this.on(document, 'DOMContentLoaded', () => this.page(), { once: true });
|
|
375
|
+
else
|
|
376
|
+
this.page();
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Before the page goes away, everything waiting is handed to the browser as beacons
|
|
380
|
+
* (PM-R-0062 criterion 4). Hidden comes first and is the last moment a phone reliably gives a page;
|
|
381
|
+
* pagehide is the page really leaving, which is also when it is left.
|
|
382
|
+
*/
|
|
383
|
+
listen() {
|
|
384
|
+
this.on(document, 'visibilitychange', () => {
|
|
385
|
+
if (document.visibilityState === 'hidden')
|
|
386
|
+
this.outbox?.beaconAll();
|
|
387
|
+
});
|
|
388
|
+
this.on(window, 'pagehide', () => {
|
|
389
|
+
this.leave(Date.now());
|
|
390
|
+
this.outbox?.beaconAll();
|
|
391
|
+
});
|
|
392
|
+
this.on(window, 'online', () => this.outbox?.resume());
|
|
393
|
+
// Back from the browser's back-forward cache: the page was left when it was hidden, so this is a
|
|
394
|
+
// new view of it.
|
|
395
|
+
this.on(window, 'pageshow', (e) => {
|
|
396
|
+
if (e.persisted && this.options.autoPageviews !== false)
|
|
397
|
+
this.page();
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
on(target, type, listener, options) {
|
|
401
|
+
target.addEventListener(type, listener, options);
|
|
402
|
+
this.cleanup.push(() => target.removeEventListener(type, listener, options));
|
|
403
|
+
}
|
|
404
|
+
load(stored = readState(this.store, this.stateName)) {
|
|
405
|
+
return {
|
|
406
|
+
anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : uuid(),
|
|
407
|
+
user: typeof stored?.user === 'string' && stored.user ? stored.user : undefined,
|
|
408
|
+
props: stored?.props && typeof stored.props === 'object' ? stored.props : {},
|
|
409
|
+
initial: stored?.initial && typeof stored.initial === 'object' ? stored.initial : undefined,
|
|
410
|
+
initialSent: stored?.initialSent === true ? true : undefined,
|
|
411
|
+
session: stored?.session && typeof stored.session.id === 'string' ? stored.session : undefined,
|
|
412
|
+
consent: stored?.consent === 'in' || stored?.consent === 'out' ? stored.consent : undefined,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Picks up what another tab of the same site wrote — its sign-in, its reset, its session — so every
|
|
417
|
+
* tab sends as the same visitor. Only from storage that is being written; a page that keeps nothing
|
|
418
|
+
* has nothing to pick up.
|
|
419
|
+
*/
|
|
420
|
+
sync() {
|
|
421
|
+
if (!this.sending)
|
|
422
|
+
return;
|
|
423
|
+
const stored = readState(this.store, this.stateName);
|
|
424
|
+
if (typeof stored?.anon === 'string' && stored.anon !== '')
|
|
425
|
+
this.state = this.load(stored);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Writes the state, only once the visitor may be tracked: before consent nothing identifying is
|
|
429
|
+
* stored, and after an opt-out only the choice is.
|
|
430
|
+
*/
|
|
431
|
+
save() {
|
|
432
|
+
if (!this.browser)
|
|
433
|
+
return;
|
|
434
|
+
if (this.sending)
|
|
435
|
+
this.store.set(this.stateName, JSON.stringify(this.state));
|
|
436
|
+
else if (this.state.consent === 'out')
|
|
437
|
+
this.store.set(this.stateName, JSON.stringify({ consent: 'out' }));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/** Properties as JSON will carry them: dates as ISO text, `undefined` and functions left out. */
|
|
441
|
+
function clean(properties) {
|
|
442
|
+
const out = {};
|
|
443
|
+
if (!properties || typeof properties !== 'object')
|
|
444
|
+
return out;
|
|
445
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
446
|
+
if (value === undefined || typeof value === 'function')
|
|
447
|
+
continue;
|
|
448
|
+
out[key] = value instanceof Date ? value.toISOString() : value;
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { EventContext } from './types.js';
|
|
2
|
+
/** What the user agent says about the browser, read once per page. */
|
|
3
|
+
export interface Browser {
|
|
4
|
+
context: EventContext;
|
|
5
|
+
browserVersion: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The browser, OS and kind of device, from the user agent. Deliberately small: these are the values a
|
|
9
|
+
* breakdown is useful by, and a full parser would be most of the bundle. Chromium freezes parts of the
|
|
10
|
+
* string (macOS stays 10.15.7, Windows 11 says 10), so those versions are what the browser claims.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseUserAgent(ua: string, maxTouchPoints?: number): {
|
|
13
|
+
browser: string;
|
|
14
|
+
browserVersion: string;
|
|
15
|
+
os: string;
|
|
16
|
+
osVersion: string;
|
|
17
|
+
deviceType: string;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Crawlers, link previews and uptime checks: what `ignoreBots` leaves out. Named rather than matched on
|
|
21
|
+
* "bot" anywhere, because phones such as Cubot carry those letters in a real browser's user agent.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isBot(ua: string): boolean;
|
|
24
|
+
export declare function browserContext(appVersion?: string): Browser;
|
|
25
|
+
/**
|
|
26
|
+
* The person's settings and what they look at (PM-T-0613): their time zone, languages, calendar, digits
|
|
27
|
+
* and clock; the screen, its pixel ratio, light or dark, and the connection. Each only where the
|
|
28
|
+
* browser says, and only what describes the device to a question — nothing that would single one out
|
|
29
|
+
* (no canvas, fonts, graphics card, audio or hardware counts).
|
|
30
|
+
*/
|
|
31
|
+
export declare function deviceContext(): EventContext;
|
|
32
|
+
/**
|
|
33
|
+
* What Chromium tells a page that asks (User-Agent Client Hints): an Android phone's model, and the real
|
|
34
|
+
* OS version where the user agent string is frozen (Windows 11 still says 10, macOS 10.15.7). Safari and
|
|
35
|
+
* Firefox do not answer, and an iPhone's model is never given; then this is empty.
|
|
36
|
+
*/
|
|
37
|
+
export declare function clientHints(): Promise<EventContext>;
|
|
38
|
+
/** A platform's version as people name it: Windows 13.x and later is 11, macOS and the rest major.minor. */
|
|
39
|
+
export declare function osVersionOf(platform: string, version: string): string | null;
|
|
40
|
+
/** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
|
|
41
|
+
export declare function doNotTrack(): boolean;
|
|
42
|
+
/** The campaign parameters in a URL, named `$utm_source` and so on. */
|
|
43
|
+
export declare function campaign(href: string): Record<string, string>;
|
|
44
|
+
/** The host a referrer came from, or `$direct` for none. */
|
|
45
|
+
export declare function referringDomain(referrer: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Where this browser first came from, kept for good on its first page (PM-R-0062 criterion 3), so a
|
|
48
|
+
* signup weeks later can still be broken down by the campaign that brought the visitor.
|
|
49
|
+
*/
|
|
50
|
+
export declare function initialAttribution(href: string, referrer: string): Record<string, string>;
|
|
51
|
+
/**
|
|
52
|
+
* A page's route, for telling a navigation from a page that only changed its query string: the path,
|
|
53
|
+
* plus the hash when a router keeps its routes there (`#/settings`, `#!/settings`).
|
|
54
|
+
*/
|
|
55
|
+
export declare function routeOf(location: Pick<Location, 'pathname' | 'hash'>): string;
|