@daybook/analytics 0.0.0-stage → 0.2.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/dist/client.js ADDED
@@ -0,0 +1,448 @@
1
+ import { browserContext, campaign, 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
+ this.state = this.load();
59
+ (_a = this.state).initial ?? (_a.initial = initialAttribution(location.href, document.referrer));
60
+ if (options.properties)
61
+ Object.assign(this.state.props, clean(options.properties));
62
+ this.save();
63
+ this.outbox = new Outbox(new Transport(options.apiUrl ?? DEFAULT_API_URL, options.key.trim()), webStore('sessionStorage'), `${this.stateName}_queue`, {
64
+ batchSize: Math.max(1, Math.min(1000, options.batchSize ?? 50)),
65
+ flushIntervalMs: Math.max(0, options.flushIntervalMs ?? 2000),
66
+ }, this.log);
67
+ this.listen();
68
+ if (options.autoPageviews !== false)
69
+ this.watchHistory();
70
+ }
71
+ /** The anonymous id this browser sends events under. */
72
+ get distinctId() {
73
+ return this.state.anon;
74
+ }
75
+ /** Who `identify()` said is signed in, or null. */
76
+ get userId() {
77
+ return this.state.user ?? null;
78
+ }
79
+ /** The current session's id; a new one starts after the session timeout without events. */
80
+ get sessionId() {
81
+ return this.state.session?.id ?? null;
82
+ }
83
+ /** Whether events are being kept back: opted out, waiting for consent, Do Not Track, or a crawler. */
84
+ get optedOut() {
85
+ return !this.sending;
86
+ }
87
+ /** Properties sent with every event, from `register()`. */
88
+ get registered() {
89
+ return { ...this.state.props };
90
+ }
91
+ /** Something the visitor did, with what describes it: `track('checkout_started', { plan: 'pro', seats: 3 })`. */
92
+ track(event, properties) {
93
+ const name = typeof event === 'string' ? event.trim() : '';
94
+ if (name === '' || name.length > 200) {
95
+ this.log.warn(`an event needs a name of 1 to 200 characters; got ${JSON.stringify(event)}`);
96
+ return;
97
+ }
98
+ if (name.startsWith('$')) {
99
+ this.log.warn(`"${name}": names starting with $ are Daybook's own. For a page view call page().`);
100
+ return;
101
+ }
102
+ this.capture(name, properties);
103
+ }
104
+ /**
105
+ * A page view, with its URL, path, title, referrer and campaign. Sent by itself on load and on every
106
+ * navigation unless `autoPageviews` is false; call it yourself then, after the route has changed.
107
+ */
108
+ page(properties) {
109
+ if (!this.browser)
110
+ return;
111
+ const now = Date.now();
112
+ const route = routeOf(location);
113
+ const previous = this.current;
114
+ // A navigation in a single-page app leaves the page it came from.
115
+ if (previous && previous.route !== route)
116
+ this.leave(now);
117
+ const referrer = previous ? previous.url : document.referrer;
118
+ this.referrer = referrer;
119
+ this.current = { route, url: location.href, path: location.pathname, at: now };
120
+ this.capture(PAGEVIEW, {
121
+ $title: document.title,
122
+ $referrer: referrer || '$direct',
123
+ $referring_domain: referringDomain(referrer),
124
+ $screen_width: globalThis.screen?.width,
125
+ $screen_height: globalThis.screen?.height,
126
+ $viewport_width: window.innerWidth,
127
+ $viewport_height: window.innerHeight,
128
+ ...campaign(location.href),
129
+ ...properties,
130
+ });
131
+ }
132
+ /**
133
+ * The visitor signed in as `userId`: their events from now on are theirs, and so is everything this
134
+ * browser sent before, without anything being sent again. Call it after every sign-in, and on every
135
+ * page load while they are signed in — a repeat costs nothing.
136
+ *
137
+ * A different user signing in on the same browser starts a new anonymous id first, because one
138
+ * anonymous id belongs to one person.
139
+ */
140
+ identify(userId, properties) {
141
+ const id = typeof userId === 'string' || typeof userId === 'number' ? String(userId).trim() : '';
142
+ if (id === '' || id.length > 200) {
143
+ this.log.warn(`identify needs a user id of 1 to 200 characters; got ${JSON.stringify(userId)}`);
144
+ return;
145
+ }
146
+ if (!this.browser)
147
+ return;
148
+ this.sync();
149
+ if (this.state.user === id) {
150
+ if (properties)
151
+ this.setPersonProperties(properties);
152
+ return;
153
+ }
154
+ if (this.state.user)
155
+ this.reset();
156
+ this.state.user = id;
157
+ this.save();
158
+ if (this.sending)
159
+ this.outbox?.push({ t: 'i', b: { distinct_id: this.state.anon, user_id: id, properties: properties ? clean(properties) : undefined } });
160
+ }
161
+ /**
162
+ * The visitor signed out: a new anonymous id and session, and the registered properties forgotten,
163
+ * so whoever uses this browser next is somebody new. Where the browser first came from is kept, and
164
+ * goes to the new person with their first event, as it went to the last.
165
+ */
166
+ reset() {
167
+ if (!this.browser)
168
+ return;
169
+ this.sync();
170
+ this.state = { anon: uuid(), props: {}, initial: this.state.initial, consent: this.state.consent };
171
+ this.save();
172
+ }
173
+ /** Sets (and unsets) properties of the person: their plan, their company, their role. */
174
+ setPersonProperties(set, unset) {
175
+ if (!this.browser || !this.sending)
176
+ return;
177
+ this.sync();
178
+ this.outbox?.push({ t: 'p', b: { ...this.who(), set: clean(set ?? {}), unset: unset?.filter((k) => typeof k === 'string') } });
179
+ }
180
+ /**
181
+ * Sets properties of the person only where they have no value yet — under this browser's ids or any
182
+ * other the person signed in with — so the first value stays: `{ first_plan: 'free', signed_up_at: new Date() }`.
183
+ * A later `setPersonProperties` still changes them.
184
+ */
185
+ setPersonPropertiesOnce(properties) {
186
+ if (!this.browser || !this.sending)
187
+ return;
188
+ this.sync();
189
+ this.outbox?.push({ t: 'p', b: { ...this.who(), set_once: clean(properties ?? {}) } });
190
+ }
191
+ who() {
192
+ return this.state.user ? { user_id: this.state.user } : { distinct_id: this.state.anon };
193
+ }
194
+ /** Properties sent with every later event from this browser, kept across visits until `reset()`. */
195
+ register(properties) {
196
+ if (!this.browser)
197
+ return;
198
+ this.sync();
199
+ Object.assign(this.state.props, clean(properties));
200
+ this.save();
201
+ }
202
+ unregister(name) {
203
+ if (!this.browser)
204
+ return;
205
+ this.sync();
206
+ delete this.state.props[name];
207
+ this.save();
208
+ }
209
+ /** The visitor agreed: send from now on, and remember it. The page they are on is counted then. */
210
+ optIn() {
211
+ if (!this.browser)
212
+ return;
213
+ const wasSending = this.sending;
214
+ this.state.consent = 'in';
215
+ this.save();
216
+ if (!wasSending && this.options.autoPageviews !== false)
217
+ this.page();
218
+ }
219
+ /** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
220
+ optOut() {
221
+ if (!this.browser)
222
+ return;
223
+ this.state.consent = 'out';
224
+ this.outbox?.clear();
225
+ this.save();
226
+ }
227
+ /** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
228
+ flush() {
229
+ return this.outbox?.flush() ?? Promise.resolve();
230
+ }
231
+ /** Stops listening and sending; for tests and hot reload. */
232
+ destroy() {
233
+ for (const undo of this.cleanup.splice(0))
234
+ undo();
235
+ this.outbox?.stop();
236
+ }
237
+ get sending() {
238
+ if (this.ignored)
239
+ return false;
240
+ if (this.state.consent)
241
+ return this.state.consent === 'in';
242
+ if (this.options.optOutByDefault)
243
+ return false;
244
+ if (this.options.respectDoNotTrack && doNotTrack())
245
+ return false;
246
+ return true;
247
+ }
248
+ capture(name, properties) {
249
+ if (!this.browser || !this.sending || !this.outbox)
250
+ return;
251
+ this.sync();
252
+ const now = Date.now();
253
+ const session = this.session(now);
254
+ // A session opens with $session_start (PM-R-0069): the page it began on, where the visitor came
255
+ // from and the campaign that brought them, whatever the first event of the session was.
256
+ if (session.fresh)
257
+ this.emit(SESSION_START, this.entry(), now, session.id);
258
+ this.emit(name, properties, now, session.id);
259
+ }
260
+ /** What a session began from: the referrer of the page it began on, and that page's campaign. */
261
+ entry() {
262
+ const referrer = this.referrer ?? document.referrer;
263
+ return { $referrer: referrer || '$direct', $referring_domain: referringDomain(referrer), ...campaign(location.href) };
264
+ }
265
+ emit(name, properties, now, sessionId) {
266
+ if (!this.outbox)
267
+ return;
268
+ const event = {
269
+ event: name,
270
+ event_id: uuid(),
271
+ distinct_id: this.state.anon,
272
+ timestamp: new Date(now).toISOString(),
273
+ session_id: sessionId,
274
+ properties: {
275
+ $url: location.href,
276
+ $path: location.pathname,
277
+ $host: location.host,
278
+ $browser_version: this.browserVersion,
279
+ $lib_version: SDK_VERSION,
280
+ ...this.state.initial,
281
+ ...this.state.props,
282
+ ...clean(properties ?? {}),
283
+ },
284
+ context: { ...this.context },
285
+ };
286
+ if (this.state.user)
287
+ event.user_id = this.state.user;
288
+ // Where this browser first came from is its person's too (PM-T-0540): carried once, on the first
289
+ // event, as $set_once, which Daybook writes as set_once person properties and keeps off the event.
290
+ const first = !this.state.initialSent && this.state.initial !== undefined;
291
+ if (first)
292
+ event.properties.$set_once = { ...this.state.initial };
293
+ let final = event;
294
+ if (this.options.beforeSend) {
295
+ try {
296
+ final = this.options.beforeSend(event);
297
+ }
298
+ catch (error) {
299
+ this.log.warn(`beforeSend threw, so "${name}" was dropped: ${String(error)}`);
300
+ return;
301
+ }
302
+ if (!final) {
303
+ this.log.debug(`beforeSend dropped "${name}"`);
304
+ return;
305
+ }
306
+ }
307
+ try {
308
+ JSON.stringify(final);
309
+ }
310
+ catch {
311
+ this.log.warn(`"${name}" has properties that cannot be sent as JSON (a circular object?); it was dropped`);
312
+ return;
313
+ }
314
+ this.log.debug(`queued "${name}"`, final);
315
+ this.outbox.push({ t: 'e', e: final });
316
+ if (first)
317
+ this.state.initialSent = true;
318
+ this.save();
319
+ }
320
+ /**
321
+ * The session an event at `now` belongs to (PM-R-0069 criterion 1): the current one, or a new one
322
+ * after the idle timeout or once the current one is a day old. It is kept with the rest of the state,
323
+ * so every tab of the site shares it, and `reset()` starts a new one.
324
+ */
325
+ session(now) {
326
+ const timeout = Math.max(1, this.options.sessionTimeoutMinutes ?? 30) * 60000;
327
+ const s = this.state.session;
328
+ if (!s || now - s.last > timeout || now - (s.start ?? s.last) > MAX_SESSION_MS) {
329
+ this.state.session = { id: uuid(), start: now, last: now };
330
+ return { id: this.state.session.id, fresh: true };
331
+ }
332
+ s.last = now;
333
+ return { id: s.id, fresh: false };
334
+ }
335
+ leave(now) {
336
+ const left = this.current;
337
+ this.current = null;
338
+ if (!left || this.options.pageleave === false)
339
+ return;
340
+ this.capture(PAGELEAVE, { $url: left.url, $path: left.path, $duration_ms: Math.max(0, now - left.at) });
341
+ }
342
+ /**
343
+ * Page views from the History API (PM-R-0062 criterion 3): every router of a single-page app moves
344
+ * through pushState, replaceState or popstate. A change of the query string alone is not a new page.
345
+ * The view is sent a moment later, so the router has set the new page's title.
346
+ */
347
+ watchHistory() {
348
+ const check = () => setTimeout(() => {
349
+ if (!this.current || this.current.route !== routeOf(location))
350
+ this.page();
351
+ // The same page with another query: still the page, but the address the next one came from.
352
+ else
353
+ this.current.url = location.href;
354
+ }, 0);
355
+ const patch = (method) => {
356
+ const original = history[method];
357
+ const patched = function (...args) {
358
+ const result = original.apply(this, args);
359
+ check();
360
+ return result;
361
+ };
362
+ history[method] = patched;
363
+ this.cleanup.push(() => { if (history[method] === patched)
364
+ history[method] = original; });
365
+ };
366
+ patch('pushState');
367
+ patch('replaceState');
368
+ this.on(window, 'popstate', check);
369
+ this.on(window, 'hashchange', check);
370
+ if (document.readyState === 'loading')
371
+ this.on(document, 'DOMContentLoaded', () => this.page(), { once: true });
372
+ else
373
+ this.page();
374
+ }
375
+ /**
376
+ * Before the page goes away, everything waiting is handed to the browser as beacons
377
+ * (PM-R-0062 criterion 4). Hidden comes first and is the last moment a phone reliably gives a page;
378
+ * pagehide is the page really leaving, which is also when it is left.
379
+ */
380
+ listen() {
381
+ this.on(document, 'visibilitychange', () => {
382
+ if (document.visibilityState === 'hidden')
383
+ this.outbox?.beaconAll();
384
+ });
385
+ this.on(window, 'pagehide', () => {
386
+ this.leave(Date.now());
387
+ this.outbox?.beaconAll();
388
+ });
389
+ this.on(window, 'online', () => this.outbox?.resume());
390
+ // Back from the browser's back-forward cache: the page was left when it was hidden, so this is a
391
+ // new view of it.
392
+ this.on(window, 'pageshow', (e) => {
393
+ if (e.persisted && this.options.autoPageviews !== false)
394
+ this.page();
395
+ });
396
+ }
397
+ on(target, type, listener, options) {
398
+ target.addEventListener(type, listener, options);
399
+ this.cleanup.push(() => target.removeEventListener(type, listener, options));
400
+ }
401
+ load(stored = readState(this.store, this.stateName)) {
402
+ return {
403
+ anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : uuid(),
404
+ user: typeof stored?.user === 'string' && stored.user ? stored.user : undefined,
405
+ props: stored?.props && typeof stored.props === 'object' ? stored.props : {},
406
+ initial: stored?.initial && typeof stored.initial === 'object' ? stored.initial : undefined,
407
+ initialSent: stored?.initialSent === true ? true : undefined,
408
+ session: stored?.session && typeof stored.session.id === 'string' ? stored.session : undefined,
409
+ consent: stored?.consent === 'in' || stored?.consent === 'out' ? stored.consent : undefined,
410
+ };
411
+ }
412
+ /**
413
+ * Picks up what another tab of the same site wrote — its sign-in, its reset, its session — so every
414
+ * tab sends as the same visitor. Only from storage that is being written; a page that keeps nothing
415
+ * has nothing to pick up.
416
+ */
417
+ sync() {
418
+ if (!this.sending)
419
+ return;
420
+ const stored = readState(this.store, this.stateName);
421
+ if (typeof stored?.anon === 'string' && stored.anon !== '')
422
+ this.state = this.load(stored);
423
+ }
424
+ /**
425
+ * Writes the state, only once the visitor may be tracked: before consent nothing identifying is
426
+ * stored, and after an opt-out only the choice is.
427
+ */
428
+ save() {
429
+ if (!this.browser)
430
+ return;
431
+ if (this.sending)
432
+ this.store.set(this.stateName, JSON.stringify(this.state));
433
+ else if (this.state.consent === 'out')
434
+ this.store.set(this.stateName, JSON.stringify({ consent: 'out' }));
435
+ }
436
+ }
437
+ /** Properties as JSON will carry them: dates as ISO text, `undefined` and functions left out. */
438
+ function clean(properties) {
439
+ const out = {};
440
+ if (!properties || typeof properties !== 'object')
441
+ return out;
442
+ for (const [key, value] of Object.entries(properties)) {
443
+ if (value === undefined || typeof value === 'function')
444
+ continue;
445
+ out[key] = value instanceof Date ? value.toISOString() : value;
446
+ }
447
+ return out;
448
+ }
@@ -0,0 +1,40 @@
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
+ /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
26
+ export declare function doNotTrack(): boolean;
27
+ /** The campaign parameters in a URL, named `$utm_source` and so on. */
28
+ export declare function campaign(href: string): Record<string, string>;
29
+ /** The host a referrer came from, or `$direct` for none. */
30
+ export declare function referringDomain(referrer: string): string;
31
+ /**
32
+ * Where this browser first came from, kept for good on its first page (PM-R-0062 criterion 3), so a
33
+ * signup weeks later can still be broken down by the campaign that brought the visitor.
34
+ */
35
+ export declare function initialAttribution(href: string, referrer: string): Record<string, string>;
36
+ /**
37
+ * A page's route, for telling a navigation from a page that only changed its query string: the path,
38
+ * plus the hash when a router keeps its routes there (`#/settings`, `#!/settings`).
39
+ */
40
+ export declare function routeOf(location: Pick<Location, 'pathname' | 'hash'>): string;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The browser, OS and kind of device, from the user agent. Deliberately small: these are the values a
3
+ * breakdown is useful by, and a full parser would be most of the bundle. Chromium freezes parts of the
4
+ * string (macOS stays 10.15.7, Windows 11 says 10), so those versions are what the browser claims.
5
+ */
6
+ export function parseUserAgent(ua, maxTouchPoints = 0) {
7
+ const match = (re) => re.exec(ua)?.[1] ?? '';
8
+ let browser = '';
9
+ let browserVersion = '';
10
+ const pick = (name, re) => {
11
+ const v = re.exec(ua);
12
+ if (!v)
13
+ return false;
14
+ browser = name;
15
+ browserVersion = v[1] ?? '';
16
+ return true;
17
+ };
18
+ // Order matters: Edge, Opera and Samsung say "Chrome" too, and every iOS browser says "Safari".
19
+ void (pick('Edge', /Edg(?:e|A|iOS)?\/([\d.]+)/)
20
+ || pick('Opera', /(?:OPR|OPT)\/([\d.]+)/)
21
+ || pick('Samsung Internet', /SamsungBrowser\/([\d.]+)/)
22
+ || pick('Firefox', /(?:Firefox|FxiOS)\/([\d.]+)/)
23
+ || pick('Chrome', /(?:Chrome|CriOS)\/([\d.]+)/)
24
+ || pick('Safari', /Version\/([\d.]+).*Safari/));
25
+ let os = '';
26
+ let osVersion = '';
27
+ // An iPad asks for the desktop site and says "Macintosh"; touch is what gives it away.
28
+ const iPadAsMac = /Macintosh/.test(ua) && maxTouchPoints > 1;
29
+ if (/iPhone|iPad|iPod/.test(ua) || iPadAsMac) {
30
+ os = 'iOS';
31
+ osVersion = match(/OS (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g, '.');
32
+ }
33
+ else if (/Android/.test(ua)) {
34
+ os = 'Android';
35
+ osVersion = match(/Android (\d+(?:\.\d+)*)/);
36
+ }
37
+ else if (/Windows/.test(ua)) {
38
+ os = 'Windows';
39
+ osVersion = match(/Windows NT (\d+\.\d+)/);
40
+ }
41
+ else if (/CrOS/.test(ua)) {
42
+ os = 'Chrome OS';
43
+ }
44
+ else if (/Mac OS X|Macintosh/.test(ua)) {
45
+ os = 'macOS';
46
+ osVersion = match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g, '.');
47
+ }
48
+ else if (/Linux/.test(ua)) {
49
+ os = 'Linux';
50
+ }
51
+ const deviceType = /iPad|Tablet/.test(ua) || iPadAsMac || (/Android/.test(ua) && !/Mobile/.test(ua))
52
+ ? 'tablet'
53
+ : /Mobi|iPhone|iPod/.test(ua)
54
+ ? 'mobile'
55
+ : 'desktop';
56
+ return { browser, browserVersion, os, osVersion, deviceType };
57
+ }
58
+ /**
59
+ * Crawlers, link previews and uptime checks: what `ignoreBots` leaves out. Named rather than matched on
60
+ * "bot" anywhere, because phones such as Cubot carry those letters in a real browser's user agent.
61
+ */
62
+ export function isBot(ua) {
63
+ return /\bbot\b|crawler|spider|\b(?:googlebot|bingbot|yandexbot|duckduckbot|applebot|petalbot|ahrefsbot|semrushbot|mj12bot|gptbot|claudebot|ccbot|bytespider|twitterbot|linkedinbot|slackbot|discordbot|telegrambot|slurp|facebookexternalhit|whatsapp|embedly|headlesschrome|lighthouse|pingdom|uptimerobot)\b/i.test(ua);
64
+ }
65
+ export function browserContext(appVersion) {
66
+ const nav = globalThis.navigator;
67
+ const parsed = parseUserAgent(nav?.userAgent ?? '', nav?.maxTouchPoints ?? 0);
68
+ const context = {
69
+ browser: parsed.browser,
70
+ os: parsed.os,
71
+ os_version: parsed.osVersion,
72
+ device_type: parsed.deviceType,
73
+ locale: nav?.language ?? '',
74
+ };
75
+ if (appVersion)
76
+ context.app_version = appVersion;
77
+ return { context, browserVersion: parsed.browserVersion };
78
+ }
79
+ /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
80
+ export function doNotTrack() {
81
+ const nav = globalThis.navigator;
82
+ const win = globalThis;
83
+ const dnt = nav?.doNotTrack ?? win.doNotTrack ?? nav?.msDoNotTrack;
84
+ return dnt === '1' || dnt === 'yes' || nav?.globalPrivacyControl === true;
85
+ }
86
+ /** The campaign parameters kept from a landing URL. */
87
+ const CAMPAIGN = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
88
+ /** The campaign parameters in a URL, named `$utm_source` and so on. */
89
+ export function campaign(href) {
90
+ const found = {};
91
+ try {
92
+ const params = new URL(href).searchParams;
93
+ for (const name of CAMPAIGN) {
94
+ const value = params.get(name);
95
+ if (value)
96
+ found[`$${name}`] = value.slice(0, 200);
97
+ }
98
+ }
99
+ catch { /* not a URL */ }
100
+ return found;
101
+ }
102
+ /** The host a referrer came from, or `$direct` for none. */
103
+ export function referringDomain(referrer) {
104
+ if (!referrer)
105
+ return '$direct';
106
+ try {
107
+ return new URL(referrer).hostname;
108
+ }
109
+ catch {
110
+ return '$direct';
111
+ }
112
+ }
113
+ /**
114
+ * Where this browser first came from, kept for good on its first page (PM-R-0062 criterion 3), so a
115
+ * signup weeks later can still be broken down by the campaign that brought the visitor.
116
+ */
117
+ export function initialAttribution(href, referrer) {
118
+ const initial = {
119
+ $initial_referrer: referrer || '$direct',
120
+ $initial_referring_domain: referringDomain(referrer),
121
+ };
122
+ for (const [name, value] of Object.entries(campaign(href)))
123
+ initial[`$initial_${name.slice(1)}`] = value;
124
+ return initial;
125
+ }
126
+ /**
127
+ * A page's route, for telling a navigation from a page that only changed its query string: the path,
128
+ * plus the hash when a router keeps its routes there (`#/settings`, `#!/settings`).
129
+ */
130
+ export function routeOf(location) {
131
+ const hash = location.hash ?? '';
132
+ return location.pathname + (hash.startsWith('#/') || hash.startsWith('#!') ? hash.split('?')[0] : '');
133
+ }
@@ -0,0 +1 @@
1
+ "use strict";(()=>{function J(n,t=0){let e=h=>{var v,y;return(y=(v=h.exec(n))==null?void 0:v[1])!=null?y:""},i="",s="",r=(h,v)=>{var N;let y=v.exec(n);return y?(i=h,s=(N=y[1])!=null?N:"",!0):!1};r("Edge",/Edg(?:e|A|iOS)?\/([\d.]+)/)||r("Opera",/(?:OPR|OPT)\/([\d.]+)/)||r("Samsung Internet",/SamsungBrowser\/([\d.]+)/)||r("Firefox",/(?:Firefox|FxiOS)\/([\d.]+)/)||r("Chrome",/(?:Chrome|CriOS)\/([\d.]+)/)||r("Safari",/Version\/([\d.]+).*Safari/);let a="",o="",l=/Macintosh/.test(n)&&t>1;/iPhone|iPad|iPod/.test(n)||l?(a="iOS",o=e(/OS (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g,".")):/Android/.test(n)?(a="Android",o=e(/Android (\d+(?:\.\d+)*)/)):/Windows/.test(n)?(a="Windows",o=e(/Windows NT (\d+\.\d+)/)):/CrOS/.test(n)?a="Chrome OS":/Mac OS X|Macintosh/.test(n)?(a="macOS",o=e(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g,".")):/Linux/.test(n)&&(a="Linux");let u=/iPad|Tablet/.test(n)||l||/Android/.test(n)&&!/Mobile/.test(n)?"tablet":/Mobi|iPhone|iPod/.test(n)?"mobile":"desktop";return{browser:i,browserVersion:s,os:a,osVersion:o,deviceType:u}}function j(n){return/\bbot\b|crawler|spider|\b(?:googlebot|bingbot|yandexbot|duckduckbot|applebot|petalbot|ahrefsbot|semrushbot|mj12bot|gptbot|claudebot|ccbot|bytespider|twitterbot|linkedinbot|slackbot|discordbot|telegrambot|slurp|facebookexternalhit|whatsapp|embedly|headlesschrome|lighthouse|pingdom|uptimerobot)\b/i.test(n)}function D(n){var s,r,a;let t=globalThis.navigator,e=J((s=t==null?void 0:t.userAgent)!=null?s:"",(r=t==null?void 0:t.maxTouchPoints)!=null?r:0),i={browser:e.browser,os:e.os,os_version:e.osVersion,device_type:e.deviceType,locale:(a=t==null?void 0:t.language)!=null?a:""};return n&&(i.app_version=n),{context:i,browserVersion:e.browserVersion}}function M(){var i,s;let n=globalThis.navigator,t=globalThis,e=(s=(i=n==null?void 0:n.doNotTrack)!=null?i:t.doNotTrack)!=null?s:n==null?void 0:n.msDoNotTrack;return e==="1"||e==="yes"||(n==null?void 0:n.globalPrivacyControl)===!0}var F=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid"];function w(n){let t={};try{let e=new URL(n).searchParams;for(let i of F){let s=e.get(i);s&&(t[`$${i}`]=s.slice(0,200))}}catch{}return t}function S(n){if(!n)return"$direct";try{return new URL(n).hostname}catch{return"$direct"}}function R(n,t){let e={$initial_referrer:t||"$direct",$initial_referring_domain:S(t)};for(let[i,s]of Object.entries(w(n)))e[`$initial_${i.slice(1)}`]=s;return e}function $(n){var e;let t=(e=n.hash)!=null?e:"";return n.pathname+(t.startsWith("#/")||t.startsWith("#!")?t.split("?")[0]:"")}var k=class{constructor(t){this.enabled=t;this.said=new Set}debug(t,...e){this.enabled&&console.log(`[daybook] ${t}`,...e)}warn(t){this.said.has(t)||(this.said.add(t),console.warn(`[daybook] ${t}`))}};function b(){let n=new Map;return{get:t=>{var e;return(e=n.get(t))!=null?e:null},set:(t,e)=>{n.set(t,e)},remove:t=>{n.delete(t)}}}function A(n){let t;try{t=globalThis[n];let e="__daybook_probe__";t.setItem(e,"1"),t.removeItem(e)}catch{return null}return{get:e=>{try{return t.getItem(e)}catch{return null}},set:(e,i)=>{try{t.setItem(e,i)}catch{}},remove:e=>{try{t.removeItem(e)}catch{}}}}function z(n){var i;if(typeof document=="undefined")return null;let t=((i=globalThis.location)==null?void 0:i.protocol)==="https:"?"; Secure":"",e=`; path=/${n?`; domain=${n}`:""}; SameSite=Lax${t}`;return{get:s=>{try{let r=`${s}=`,a=document.cookie.split("; ").find(o=>o.startsWith(r));return a?decodeURIComponent(a.slice(r.length)):null}catch{return null}},set:(s,r)=>{try{document.cookie=`${s}=${encodeURIComponent(r)}; max-age=31536000${e}`}catch{}},remove:s=>{try{document.cookie=`${s}=; max-age=0${e}`}catch{}}}}function I(n,t){var e,i;return n==="memory"?b():n==="cookie"||t?(e=z(t))!=null?e:b():(i=A("localStorage"))!=null?i:b()}function O(n,t){let e=n.get(t);if(!e)return null;try{let i=JSON.parse(e);return i&&typeof i=="object"?i:null}catch{return null}}var m="0.2.0";var W=512*1024,C=60*1024,P=1e3,x=class{constructor(t,e){this.apiUrl=t;this.key=e}url(t){return`${this.apiUrl.replace(/\/+$/,"")}/analytics/v1/${t}?key=${encodeURIComponent(this.key)}&sdk=${"js"}`}async post(t,e){var r,a;let i;try{i=await fetch(this.url(t),{method:"POST",body:e,headers:{"Content-Type":"text/plain"},credentials:"omit",keepalive:e.length<C})}catch{return{kind:"retry"}}if(i.ok)return{kind:"ok",body:await i.json().catch(()=>null)};if(i.status===413)return{kind:"too_large"};if(i.status===408||i.status===429||i.status>=500){let o=Number(i.headers.get("Retry-After"));return{kind:"retry",afterMs:Number.isFinite(o)&&o>0?o*1e3:void 0}}let s=await i.json().catch(()=>null);return{kind:"drop",status:i.status,detail:(a=(r=s==null?void 0:s.message)!=null?r:s==null?void 0:s.code)!=null?a:""}}beacon(t,e){let i=this.url(t);try{return typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function"?navigator.sendBeacon(i,new Blob([e],{type:"text/plain"})):(fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},credentials:"omit",keepalive:!0}).catch(()=>{}),!0)}catch{return!1}}},_=class{constructor(t,e,i,s,r){this.transport=t;this.store=e;this.name=i;this.options=s;this.log=r;this.timer=null;this.sending=null;this.failures=0;this.retrySize=null;this.inFlight=0;this.stopped=!1;this.jobs=this.load(),this.jobs.length>0&&this.schedule(0)}get size(){return this.jobs.length}push(t){this.jobs.push(t),this.jobs.length>P&&(this.jobs.splice(0,this.jobs.length-P),this.log.warn(`more than ${P} events are waiting to be sent; the oldest were dropped`)),this.save(),this.schedule(this.options.flushIntervalMs)}flush(){var t;return this.timer!==null&&(clearTimeout(this.timer),this.timer=null),(t=this.sending)!=null||(this.sending=this.drain().finally(()=>{this.sending=null})),this.sending}beaconAll(){for(;this.jobs.length>this.inFlight;){let{path:t,text:e,count:i}=this.next(C,this.inFlight);if(!this.transport.beacon(t,e))break;this.jobs.splice(this.inFlight,i)}this.inFlight===0&&(this.retrySize=null),this.save()}clear(){this.jobs=[],this.retrySize=null,this.save()}stop(){this.stopped=!0,this.timer!==null&&clearTimeout(this.timer),this.timer=null}resume(){this.jobs.length>0&&!this.sending&&this.flush()}schedule(t){this.stopped||this.timer!==null||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},t))}async drain(){var t,e;for(;this.jobs.length>0&&!this.stopped;){let{path:i,text:s,count:r,events:a}=this.next(W);this.inFlight=r;let o=await this.transport.post(i,s).finally(()=>{this.inFlight=0});if(o.kind==="retry"){this.retrySize=r,this.failures++;let l=Math.min(3e5,1e3*2**Math.min(this.failures-1,9))*(.75+Math.random()/2);this.log.debug(`could not reach the API; trying again in ${Math.round(((t=o.afterMs)!=null?t:l)/1e3)} s`),this.schedule((e=o.afterMs)!=null?e:l);return}if(o.kind==="too_large"&&r>1){this.retrySize=Math.ceil(r/2);continue}this.jobs.splice(0,r),this.retrySize=null,this.failures=0,this.save(),o.kind==="ok"?this.report(i,o.body,a,r):o.kind==="too_large"?this.log.warn("an event was too large for the API and was dropped"):this.refused(o.status,o.detail,i,r)}}next(t,e=0){let i=this.jobs[e];if(i.t==="i")return{path:"identify",text:JSON.stringify(i.b),count:1,events:[]};if(i.t==="p")return{path:"people",text:JSON.stringify(i.b),count:1,events:[]};let s=e===0&&this.retrySize!==null?this.retrySize:this.options.batchSize,r=[],a=16;for(let o of this.jobs.slice(e)){if(o.t!=="e"||r.length>=s)break;let l=JSON.stringify(o.e).length+1;if(r.length>0&&a+l>t)break;r.push(o.e),a+=l}return{path:"batch",text:JSON.stringify({sent_at:new Date().toISOString(),events:r}),count:r.length,events:r}}report(t,e,i,s){var a,o,l,u;if(t!=="batch"){this.log.debug(`${t} sent`);return}let r=(a=e==null?void 0:e.refused)!=null?a:[];this.log.debug(`${s-r.length} of ${s} events stored`);for(let h of r)this.log.warn(`"${(l=(o=i[h.index])==null?void 0:o.event)!=null?l:"?"}" was refused (${h.reason}): ${(u=h.message)!=null?u:""}`)}refused(t,e,i,s){if(t===401){this.log.warn("the ingest key was refused; check the key in Analytics \u2192 Settings. Nothing more is sent from this page."),this.clear(),this.stop();return}if(t===409&&i==="identify"){this.log.warn(`identify was refused: ${e}`);return}this.log.warn(`${s} ${i==="batch"?"events were":i+" request was"} refused (${t}): ${e}`)}load(){var e;let t=(e=this.store)==null?void 0:e.get(this.name);if(!t)return[];try{let i=JSON.parse(t);return Array.isArray(i)?i.filter(s=>s&&(s.t==="e"||s.t==="i"||s.t==="p")):[]}catch{return[]}}save(){this.store&&(this.jobs.length===0?this.store.remove(this.name):this.store.set(this.name,JSON.stringify(this.jobs)))}};function p(){let n=globalThis.crypto;if(typeof(n==null?void 0:n.randomUUID)=="function")return n.randomUUID();let t=new Uint8Array(16);if(typeof(n==null?void 0:n.getRandomValues)=="function")n.getRandomValues(t);else for(let i=0;i<16;i++)t[i]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var V="https://api.daybook.team",q="$pageview",H="$pageleave",K="$session_start",X=1440*6e4,d=class{constructor(t){this.options=t;this.context={};this.browserVersion="";this.outbox=null;this.cleanup=[];this.current=null;this.referrer=null;this.ignored=!1;var s,r,a,o,l,u,h;if(!t||typeof t.key!="string"||t.key.trim()==="")throw new Error("@daybook/analytics: `key` is required \u2014 the ingest key from Analytics \u2192 Settings.");if(this.log=new k(t.debug===!0),this.browser=typeof window!="undefined"&&typeof document!="undefined",this.stateName=`dbk_${t.key.trim().replace(/^dak_/,"").slice(0,8)}`,this.store=this.browser?I((s=t.persistence)!=null?s:"localStorage",t.cookieDomain):b(),this.state={anon:p(),props:{}},!this.browser)return;let e=(r=navigator.userAgent)!=null?r:"";t.ignoreBots!==!1&&j(e)&&(this.ignored=!0,this.log.debug("this browser says it is a crawler; nothing is sent from it"));let i=D(t.appVersion);this.context=i.context,this.browserVersion=i.browserVersion,this.state=this.load(),(o=(a=this.state).initial)!=null||(a.initial=R(location.href,document.referrer)),t.properties&&Object.assign(this.state.props,f(t.properties)),this.save(),this.outbox=new _(new x((l=t.apiUrl)!=null?l:V,t.key.trim()),A("sessionStorage"),`${this.stateName}_queue`,{batchSize:Math.max(1,Math.min(1e3,(u=t.batchSize)!=null?u:50)),flushIntervalMs:Math.max(0,(h=t.flushIntervalMs)!=null?h:2e3)},this.log),this.listen(),t.autoPageviews!==!1&&this.watchHistory()}get distinctId(){return this.state.anon}get userId(){var t;return(t=this.state.user)!=null?t:null}get sessionId(){var t,e;return(e=(t=this.state.session)==null?void 0:t.id)!=null?e:null}get optedOut(){return!this.sending}get registered(){return{...this.state.props}}track(t,e){let i=typeof t=="string"?t.trim():"";if(i===""||i.length>200){this.log.warn(`an event needs a name of 1 to 200 characters; got ${JSON.stringify(t)}`);return}if(i.startsWith("$")){this.log.warn(`"${i}": names starting with $ are Daybook's own. For a page view call page().`);return}this.capture(i,e)}page(t){var a,o;if(!this.browser)return;let e=Date.now(),i=$(location),s=this.current;s&&s.route!==i&&this.leave(e);let r=s?s.url:document.referrer;this.referrer=r,this.current={route:i,url:location.href,path:location.pathname,at:e},this.capture(q,{$title:document.title,$referrer:r||"$direct",$referring_domain:S(r),$screen_width:(a=globalThis.screen)==null?void 0:a.width,$screen_height:(o=globalThis.screen)==null?void 0:o.height,$viewport_width:window.innerWidth,$viewport_height:window.innerHeight,...w(location.href),...t})}identify(t,e){var s;let i=typeof t=="string"||typeof t=="number"?String(t).trim():"";if(i===""||i.length>200){this.log.warn(`identify needs a user id of 1 to 200 characters; got ${JSON.stringify(t)}`);return}if(this.browser){if(this.sync(),this.state.user===i){e&&this.setPersonProperties(e);return}this.state.user&&this.reset(),this.state.user=i,this.save(),this.sending&&((s=this.outbox)==null||s.push({t:"i",b:{distinct_id:this.state.anon,user_id:i,properties:e?f(e):void 0}}))}}reset(){this.browser&&(this.sync(),this.state={anon:p(),props:{},initial:this.state.initial,consent:this.state.consent},this.save())}setPersonProperties(t,e){var i;!this.browser||!this.sending||(this.sync(),(i=this.outbox)==null||i.push({t:"p",b:{...this.who(),set:f(t!=null?t:{}),unset:e==null?void 0:e.filter(s=>typeof s=="string")}}))}setPersonPropertiesOnce(t){var e;!this.browser||!this.sending||(this.sync(),(e=this.outbox)==null||e.push({t:"p",b:{...this.who(),set_once:f(t!=null?t:{})}}))}who(){return this.state.user?{user_id:this.state.user}:{distinct_id:this.state.anon}}register(t){this.browser&&(this.sync(),Object.assign(this.state.props,f(t)),this.save())}unregister(t){this.browser&&(this.sync(),delete this.state.props[t],this.save())}optIn(){if(!this.browser)return;let t=this.sending;this.state.consent="in",this.save(),!t&&this.options.autoPageviews!==!1&&this.page()}optOut(){var t;this.browser&&(this.state.consent="out",(t=this.outbox)==null||t.clear(),this.save())}flush(){var t,e;return(e=(t=this.outbox)==null?void 0:t.flush())!=null?e:Promise.resolve()}destroy(){var t;for(let e of this.cleanup.splice(0))e();(t=this.outbox)==null||t.stop()}get sending(){return this.ignored?!1:this.state.consent?this.state.consent==="in":!(this.options.optOutByDefault||this.options.respectDoNotTrack&&M())}capture(t,e){if(!this.browser||!this.sending||!this.outbox)return;this.sync();let i=Date.now(),s=this.session(i);s.fresh&&this.emit(K,this.entry(),i,s.id),this.emit(t,e,i,s.id)}entry(){var e;let t=(e=this.referrer)!=null?e:document.referrer;return{$referrer:t||"$direct",$referring_domain:S(t),...w(location.href)}}emit(t,e,i,s){if(!this.outbox)return;let r={event:t,event_id:p(),distinct_id:this.state.anon,timestamp:new Date(i).toISOString(),session_id:s,properties:{$url:location.href,$path:location.pathname,$host:location.host,$browser_version:this.browserVersion,$lib_version:m,...this.state.initial,...this.state.props,...f(e!=null?e:{})},context:{...this.context}};this.state.user&&(r.user_id=this.state.user);let a=!this.state.initialSent&&this.state.initial!==void 0;a&&(r.properties.$set_once={...this.state.initial});let o=r;if(this.options.beforeSend){try{o=this.options.beforeSend(r)}catch(l){this.log.warn(`beforeSend threw, so "${t}" was dropped: ${String(l)}`);return}if(!o){this.log.debug(`beforeSend dropped "${t}"`);return}}try{JSON.stringify(o)}catch{this.log.warn(`"${t}" has properties that cannot be sent as JSON (a circular object?); it was dropped`);return}this.log.debug(`queued "${t}"`,o),this.outbox.push({t:"e",e:o}),a&&(this.state.initialSent=!0),this.save()}session(t){var s,r;let e=Math.max(1,(s=this.options.sessionTimeoutMinutes)!=null?s:30)*6e4,i=this.state.session;return!i||t-i.last>e||t-((r=i.start)!=null?r:i.last)>X?(this.state.session={id:p(),start:t,last:t},{id:this.state.session.id,fresh:!0}):(i.last=t,{id:i.id,fresh:!1})}leave(t){let e=this.current;this.current=null,!(!e||this.options.pageleave===!1)&&this.capture(H,{$url:e.url,$path:e.path,$duration_ms:Math.max(0,t-e.at)})}watchHistory(){let t=()=>setTimeout(()=>{!this.current||this.current.route!==$(location)?this.page():this.current.url=location.href},0),e=i=>{let s=history[i],r=function(...a){let o=s.apply(this,a);return t(),o};history[i]=r,this.cleanup.push(()=>{history[i]===r&&(history[i]=s)})};e("pushState"),e("replaceState"),this.on(window,"popstate",t),this.on(window,"hashchange",t),document.readyState==="loading"?this.on(document,"DOMContentLoaded",()=>this.page(),{once:!0}):this.page()}listen(){this.on(document,"visibilitychange",()=>{var t;document.visibilityState==="hidden"&&((t=this.outbox)==null||t.beaconAll())}),this.on(window,"pagehide",()=>{var t;this.leave(Date.now()),(t=this.outbox)==null||t.beaconAll()}),this.on(window,"online",()=>{var t;return(t=this.outbox)==null?void 0:t.resume()}),this.on(window,"pageshow",t=>{t.persisted&&this.options.autoPageviews!==!1&&this.page()})}on(t,e,i,s){t.addEventListener(e,i,s),this.cleanup.push(()=>t.removeEventListener(e,i,s))}load(t=O(this.store,this.stateName)){return{anon:typeof(t==null?void 0:t.anon)=="string"&&t.anon?t.anon:p(),user:typeof(t==null?void 0:t.user)=="string"&&t.user?t.user:void 0,props:t!=null&&t.props&&typeof t.props=="object"?t.props:{},initial:t!=null&&t.initial&&typeof t.initial=="object"?t.initial:void 0,initialSent:(t==null?void 0:t.initialSent)===!0?!0:void 0,session:t!=null&&t.session&&typeof t.session.id=="string"?t.session:void 0,consent:(t==null?void 0:t.consent)==="in"||(t==null?void 0:t.consent)==="out"?t.consent:void 0}}sync(){if(!this.sending)return;let t=O(this.store,this.stateName);typeof(t==null?void 0:t.anon)=="string"&&t.anon!==""&&(this.state=this.load(t))}save(){this.browser&&(this.sending?this.store.set(this.stateName,JSON.stringify(this.state)):this.state.consent==="out"&&this.store.set(this.stateName,JSON.stringify({consent:"out"})))}};function f(n){let t={};if(!n||typeof n!="object")return t;for(let[e,i]of Object.entries(n))i===void 0||typeof i=="function"||(t[e]=i instanceof Date?i.toISOString():i);return t}var g=null;function U(n){return g?(n!=null&&n.key&&n.key.trim()!==g.options.key.trim()&&console.warn("[daybook] init was called again with another key; the first instance is kept. Use new DaybookAnalytics() for a second project."),g):(g=new d(n),g)}function B(){return g}var E=globalThis,T=typeof document!="undefined"?document.currentScript:null;function L(n){let t=E.daybook,e=U(n);E.daybook=e;for(let[i,s]of Array.isArray(t==null?void 0:t.q)?t.q:[]){let r=e[i];typeof r=="function"&&r.apply(e,s)}return e}E.DaybookAnalytics={init:L,getAnalytics:B,DaybookAnalytics:d,version:m};var c=T==null?void 0:T.dataset;c!=null&&c.key&&L({key:c.key,apiUrl:c.apiUrl,appVersion:c.appVersion,autoPageviews:c.pageviews!=="false",pageleave:c.pageleave!=="false",persistence:c.persistence,cookieDomain:c.cookieDomain,optOutByDefault:c.optOutByDefault!==void 0&&c.optOutByDefault!=="false",respectDoNotTrack:c.respectDnt!==void 0&&c.respectDnt!=="false",debug:c.debug!==void 0&&c.debug!=="false"});})();