@daybook/analytics 0.2.0 → 0.4.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/browser.js CHANGED
@@ -1,30 +1,121 @@
1
+ import { Daybook, registeredModules } from '@daybook/core';
1
2
  import { DaybookAnalytics, getAnalytics, init as start, SDK_VERSION } from './index.js';
2
3
  const w = globalThis;
3
4
  const script = typeof document !== 'undefined' ? document.currentScript : null;
4
- function init(options) {
5
+ /** Analytics' own calls, which a page written for the tag before the family makes on `window.daybook`. */
6
+ const ANALYTICS = [
7
+ 'track', 'page', 'register', 'unregister', 'setPersonProperties', 'setPersonPropertiesOnce', 'optIn', 'optOut', 'flush',
8
+ ];
9
+ function queued() {
5
10
  const stub = w.daybook;
11
+ return Array.isArray(stub?.q) ? stub.q : [];
12
+ }
13
+ /** The way before the family: analytics alone, as `window.daybook`. */
14
+ function init(options) {
15
+ const calls = queued();
6
16
  const instance = start(options);
7
17
  w.daybook = instance;
8
- for (const [method, args] of Array.isArray(stub?.q) ? stub.q : []) {
18
+ for (const [method, args] of calls) {
9
19
  const fn = instance[method];
10
20
  if (typeof fn === 'function')
11
21
  fn.apply(instance, args);
12
22
  }
13
23
  return instance;
14
24
  }
25
+ /** A module that is not in this file, from the file beside it: feedback.js for `feedback`. */
26
+ function load(name) {
27
+ return new Promise((resolve) => {
28
+ try {
29
+ const tag = document.createElement('script');
30
+ tag.async = true;
31
+ tag.src = new URL(`${name}.js`, script?.src || location.href).href;
32
+ tag.onload = () => resolve();
33
+ tag.onerror = () => {
34
+ console.warn(`[daybook] ${name}: its script could not be loaded from ${tag.src}; the other modules start without it`);
35
+ resolve();
36
+ };
37
+ document.head.appendChild(tag);
38
+ }
39
+ catch {
40
+ resolve();
41
+ }
42
+ });
43
+ }
44
+ /** The family: the core as `window.daybook`, with the modules the tag names. */
45
+ async function initialize(key, options = {}) {
46
+ const calls = queued();
47
+ const names = options.modules ?? ['analytics'];
48
+ await Promise.all(names.filter((name) => /^[a-z]+$/.test(name) && !registeredModules().includes(name)).map(load));
49
+ const daybook = await Daybook.initialize(key, { ...options, modules: names });
50
+ const doors = daybook;
51
+ // A page that called daybook.track(…) with analytics' own key keeps working with the site's key.
52
+ for (const method of ANALYTICS) {
53
+ if (method in doors)
54
+ continue;
55
+ doors[method] = (...args) => call(doors.analytics, method, args);
56
+ }
57
+ w.daybook = daybook;
58
+ for (const [path, args] of calls) {
59
+ try {
60
+ const at = path.lastIndexOf('.');
61
+ call(at < 0 ? doors : doors[path.slice(0, at)], path.slice(at + 1), args);
62
+ }
63
+ catch (error) {
64
+ // One queued call that throws must not keep the rest from being played back.
65
+ console.warn(`[daybook] ${path} was queued before the script loaded and failed: ${String(error)}`);
66
+ }
67
+ }
68
+ return daybook;
69
+ }
70
+ /**
71
+ * What `window.daybook` is between the tag running and the family having started, which takes a
72
+ * moment even for a tag that is not async: calls made then are kept and played back in order. A page
73
+ * that loads the tag async puts the same stub before it (the README has it).
74
+ */
75
+ function stub() {
76
+ const q = [];
77
+ const keep = (path) => (...args) => void q.push([path, args]);
78
+ const doors = (prefix, methods) => Object.fromEntries(methods.map((method) => [method, keep(prefix + method)]));
79
+ return {
80
+ q,
81
+ ...doors('', ['identify', 'reset', 'setTrackingConsent', ...ANALYTICS]),
82
+ analytics: doors('analytics.', ANALYTICS),
83
+ feedback: doors('feedback.', ['open', 'start', 'stop', 'authenticate']),
84
+ };
85
+ }
86
+ function call(target, method, args) {
87
+ const fn = target?.[method];
88
+ return typeof fn === 'function' ? fn.apply(target, args) : undefined;
89
+ }
15
90
  w.DaybookAnalytics = { init, getAnalytics, DaybookAnalytics, version: SDK_VERSION };
91
+ w.Daybook = { initialize, version: Daybook.version };
16
92
  const data = script?.dataset;
93
+ const flag = (value) => value !== undefined && value !== 'false';
17
94
  if (data?.key) {
18
- init({
19
- key: data.key,
95
+ const analytics = {
20
96
  apiUrl: data.apiUrl,
21
97
  appVersion: data.appVersion,
22
98
  autoPageviews: data.pageviews !== 'false',
23
99
  pageleave: data.pageleave !== 'false',
24
100
  persistence: data.persistence,
25
101
  cookieDomain: data.cookieDomain,
26
- optOutByDefault: data.optOutByDefault !== undefined && data.optOutByDefault !== 'false',
27
- respectDoNotTrack: data.respectDnt !== undefined && data.respectDnt !== 'false',
28
- debug: data.debug !== undefined && data.debug !== 'false',
29
- });
102
+ respectDoNotTrack: flag(data.respectDnt),
103
+ debug: flag(data.debug),
104
+ };
105
+ if (data.key.trim().startsWith('dbk_') || data.modules !== undefined) {
106
+ if (!Array.isArray(w.daybook?.q))
107
+ w.daybook = stub();
108
+ void initialize(data.key, {
109
+ modules: (data.modules ?? 'analytics').split(',').map((name) => name.trim()).filter(Boolean),
110
+ serverUrl: data.apiUrl,
111
+ userId: data.userId,
112
+ trackingConsent: !flag(data.optOutByDefault) && data.trackingConsent !== 'false',
113
+ logging: flag(data.debug),
114
+ analytics,
115
+ feedback: { app: data.appVersion ? { version: data.appVersion } : undefined, surface: data.surface },
116
+ });
117
+ }
118
+ else {
119
+ init({ ...analytics, key: data.key, optOutByDefault: flag(data.optOutByDefault) });
120
+ }
30
121
  }
package/dist/client.d.ts CHANGED
@@ -5,6 +5,22 @@ import type { AnalyticsOptions, Properties } from './types.js';
5
5
  * inside bundles cached on other people's pages.
6
6
  */
7
7
  export declare const DEFAULT_API_URL = "https://api.daybook.team";
8
+ /**
9
+ * What ties an instance to Daybook's core when it runs as the family's analytics module (PM-T-0971):
10
+ * the core decides whether the visitor may be measured, and is told the anonymous id.
11
+ */
12
+ export interface Family {
13
+ /** Whether the visitor may be measured now. */
14
+ consent(): boolean;
15
+ /** Whether that is the visitor's own answer, which wins over Do Not Track as `optIn()` does. */
16
+ answered(): boolean;
17
+ /** The visitor answered at this instance's own door: `optIn()` and `optOut()`. */
18
+ answer(granted: boolean): void;
19
+ /** The id a browser with no state of its own starts with: the core's. */
20
+ anonymousId: string;
21
+ /** The anonymous id changed: a reset, another user, another tab. */
22
+ onAnonymousId(id: string): void;
23
+ }
8
24
  /**
9
25
  * Product analytics for one site (PM-R-0062).
10
26
  *
@@ -17,6 +33,7 @@ export declare const DEFAULT_API_URL = "https://api.daybook.team";
17
33
  */
18
34
  export declare class DaybookAnalytics {
19
35
  readonly options: AnalyticsOptions;
36
+ private readonly family?;
20
37
  private readonly browser;
21
38
  private readonly log;
22
39
  private readonly store;
@@ -30,7 +47,8 @@ export declare class DaybookAnalytics {
30
47
  /** Where the page now shown was reached from: the last page of this app, or the document's referrer. */
31
48
  private referrer;
32
49
  private ignored;
33
- constructor(options: AnalyticsOptions);
50
+ /** `family` is the core's, when this instance is its analytics module; a site never passes it. */
51
+ constructor(options: AnalyticsOptions, family?: Family | undefined);
34
52
  /** The anonymous id this browser sends events under. */
35
53
  get distinctId(): string;
36
54
  /** Who `identify()` said is signed in, or null. */
@@ -79,11 +97,18 @@ export declare class DaybookAnalytics {
79
97
  optIn(): void;
80
98
  /** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
81
99
  optOut(): void;
100
+ /**
101
+ * @internal The core's answer changed. `wasSending` is how it was before. Granted, the state is
102
+ * written and the page the visitor is on is counted; taken back, what was waiting is forgotten and
103
+ * nothing of this module's is left in storage, since the core keeps the answer.
104
+ */
105
+ consented(wasSending: boolean): void;
82
106
  /** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
83
107
  flush(): Promise<void>;
84
108
  /** Stops listening and sending; for tests and hot reload. */
85
109
  destroy(): void;
86
- private get sending();
110
+ /** @internal Whether events are sent and the state is kept. */
111
+ get sending(): boolean;
87
112
  private capture;
88
113
  /** What a session began from: the referrer of the page it began on, and that page's campaign. */
89
114
  private entry;
@@ -108,6 +133,11 @@ export declare class DaybookAnalytics {
108
133
  */
109
134
  private listen;
110
135
  private on;
136
+ /**
137
+ * What this browser kept under the hub's own key, for a site that has just moved to the family: the
138
+ * visitor stays who they were, with their session, their properties and where they first came from.
139
+ */
140
+ private earlier;
111
141
  private load;
112
142
  /**
113
143
  * Picks up what another tab of the same site wrote — its sign-in, its reset, its session — so every
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
- import { browserContext, campaign, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
1
+ import { browserContext, campaign, clientHints, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
2
2
  import { Log } from './log.js';
3
- import { memoryStore, readState, storeFor, webStore } from './storage.js';
3
+ import { earlierState, memoryStore, readState, stateNameOf, storeFor, webStore } from './storage.js';
4
4
  import { Outbox, Transport } from './transport.js';
5
5
  import { uuid } from './uuid.js';
6
6
  import { SDK_VERSION } from './version.js';
@@ -26,9 +26,11 @@ const MAX_SESSION_MS = 24 * 60 * 60000;
26
26
  * on the server (Next.js, Nuxt), where it does nothing.
27
27
  */
28
28
  export class DaybookAnalytics {
29
- constructor(options) {
29
+ /** `family` is the core's, when this instance is its analytics module; a site never passes it. */
30
+ constructor(options, family) {
30
31
  var _a;
31
32
  this.options = options;
33
+ this.family = family;
32
34
  this.context = {};
33
35
  this.browserVersion = '';
34
36
  this.outbox = null;
@@ -38,13 +40,13 @@ export class DaybookAnalytics {
38
40
  this.referrer = null;
39
41
  this.ignored = false;
40
42
  if (!options || typeof options.key !== 'string' || options.key.trim() === '')
41
- throw new Error('@daybook/analytics: `key` is required — the ingest key from Analytics → Settings.');
43
+ throw new Error("@daybook/analytics: `key` is required: the site's key from the project's settings, or the ingest key from Analytics → Settings.");
42
44
  this.log = new Log(options.debug === true);
43
45
  this.browser = typeof window !== 'undefined' && typeof document !== 'undefined';
44
46
  // 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)}`;
47
+ this.stateName = stateNameOf(options.key);
46
48
  this.store = this.browser ? storeFor(options.persistence ?? 'localStorage', options.cookieDomain) : memoryStore();
47
- this.state = { anon: uuid(), props: {} };
49
+ this.state = { anon: family?.anonymousId || uuid(), props: {} };
48
50
  if (!this.browser)
49
51
  return;
50
52
  const ua = navigator.userAgent ?? '';
@@ -55,7 +57,10 @@ export class DaybookAnalytics {
55
57
  const browser = browserContext(options.appVersion);
56
58
  this.context = browser.context;
57
59
  this.browserVersion = browser.browserVersion;
58
- this.state = this.load();
60
+ // A phone's model and the real OS version arrive a moment later, where the browser gives them;
61
+ // every event from then on carries them.
62
+ void clientHints().then((hints) => Object.assign(this.context, hints));
63
+ this.state = this.load(readState(this.store, this.stateName) ?? this.earlier());
59
64
  (_a = this.state).initial ?? (_a.initial = initialAttribution(location.href, document.referrer));
60
65
  if (options.properties)
61
66
  Object.assign(this.state.props, clean(options.properties));
@@ -210,20 +215,43 @@ export class DaybookAnalytics {
210
215
  optIn() {
211
216
  if (!this.browser)
212
217
  return;
218
+ if (this.family)
219
+ return this.family.answer(true);
213
220
  const wasSending = this.sending;
214
221
  this.state.consent = 'in';
215
- this.save();
216
- if (!wasSending && this.options.autoPageviews !== false)
217
- this.page();
222
+ this.consented(wasSending);
218
223
  }
219
224
  /** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
220
225
  optOut() {
221
226
  if (!this.browser)
222
227
  return;
228
+ if (this.family)
229
+ return this.family.answer(false);
223
230
  this.state.consent = 'out';
224
231
  this.outbox?.clear();
225
232
  this.save();
226
233
  }
234
+ /**
235
+ * @internal The core's answer changed. `wasSending` is how it was before. Granted, the state is
236
+ * written and the page the visitor is on is counted; taken back, what was waiting is forgotten and
237
+ * nothing of this module's is left in storage, since the core keeps the answer.
238
+ */
239
+ consented(wasSending) {
240
+ if (!this.browser)
241
+ return;
242
+ if (this.sending) {
243
+ this.save();
244
+ if (!wasSending && this.options.autoPageviews !== false)
245
+ this.page();
246
+ }
247
+ else {
248
+ this.outbox?.clear();
249
+ if (this.family)
250
+ this.store.remove(this.stateName);
251
+ else
252
+ this.save();
253
+ }
254
+ }
227
255
  /** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
228
256
  flush() {
229
257
  return this.outbox?.flush() ?? Promise.resolve();
@@ -234,9 +262,15 @@ export class DaybookAnalytics {
234
262
  undo();
235
263
  this.outbox?.stop();
236
264
  }
265
+ /** @internal Whether events are sent and the state is kept. */
237
266
  get sending() {
238
267
  if (this.ignored)
239
268
  return false;
269
+ if (this.family) {
270
+ if (this.options.respectDoNotTrack && doNotTrack() && !this.family.answered())
271
+ return false;
272
+ return this.family.consent();
273
+ }
240
274
  if (this.state.consent)
241
275
  return this.state.consent === 'in';
242
276
  if (this.options.optOutByDefault)
@@ -398,15 +432,23 @@ export class DaybookAnalytics {
398
432
  target.addEventListener(type, listener, options);
399
433
  this.cleanup.push(() => target.removeEventListener(type, listener, options));
400
434
  }
435
+ /**
436
+ * What this browser kept under the hub's own key, for a site that has just moved to the family: the
437
+ * visitor stays who they were, with their session, their properties and where they first came from.
438
+ */
439
+ earlier() {
440
+ return this.family ? earlierState(this.store, this.stateName) : null;
441
+ }
401
442
  load(stored = readState(this.store, this.stateName)) {
402
443
  return {
403
- anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : uuid(),
444
+ anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : this.family?.anonymousId || uuid(),
404
445
  user: typeof stored?.user === 'string' && stored.user ? stored.user : undefined,
405
446
  props: stored?.props && typeof stored.props === 'object' ? stored.props : {},
406
447
  initial: stored?.initial && typeof stored.initial === 'object' ? stored.initial : undefined,
407
448
  initialSent: stored?.initialSent === true ? true : undefined,
408
449
  session: stored?.session && typeof stored.session.id === 'string' ? stored.session : undefined,
409
- consent: stored?.consent === 'in' || stored?.consent === 'out' ? stored.consent : undefined,
450
+ // In the family the core keeps the answer.
451
+ consent: !this.family && (stored?.consent === 'in' || stored?.consent === 'out') ? stored.consent : undefined,
410
452
  };
411
453
  }
412
454
  /**
@@ -428,6 +470,7 @@ export class DaybookAnalytics {
428
470
  save() {
429
471
  if (!this.browser)
430
472
  return;
473
+ this.family?.onAnonymousId(this.state.anon);
431
474
  if (this.sending)
432
475
  this.store.set(this.stateName, JSON.stringify(this.state));
433
476
  else if (this.state.consent === 'out')
package/dist/context.d.ts CHANGED
@@ -22,6 +22,21 @@ export declare function parseUserAgent(ua: string, maxTouchPoints?: number): {
22
22
  */
23
23
  export declare function isBot(ua: string): boolean;
24
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;
25
40
  /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
26
41
  export declare function doNotTrack(): boolean;
27
42
  /** The campaign parameters in a URL, named `$utm_source` and so on. */
package/dist/context.js CHANGED
@@ -74,7 +74,91 @@ export function browserContext(appVersion) {
74
74
  };
75
75
  if (appVersion)
76
76
  context.app_version = appVersion;
77
- return { context, browserVersion: parsed.browserVersion };
77
+ return { context: { ...context, ...deviceContext() }, browserVersion: parsed.browserVersion };
78
+ }
79
+ /**
80
+ * The person's settings and what they look at (PM-T-0613): their time zone, languages, calendar, digits
81
+ * and clock; the screen, its pixel ratio, light or dark, and the connection. Each only where the
82
+ * browser says, and only what describes the device to a question — nothing that would single one out
83
+ * (no canvas, fonts, graphics card, audio or hardware counts).
84
+ */
85
+ export function deviceContext() {
86
+ const out = {};
87
+ try {
88
+ const options = Intl.DateTimeFormat().resolvedOptions();
89
+ if (options.timeZone)
90
+ out.timezone = options.timeZone;
91
+ if (options.calendar)
92
+ out.calendar = options.calendar;
93
+ if (options.numberingSystem)
94
+ out.numbering_system = options.numberingSystem;
95
+ // hourCycle is not in every TypeScript lib's types yet, though every current browser answers it.
96
+ const cycle = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions().hourCycle;
97
+ if (cycle)
98
+ out.hour_cycle = cycle;
99
+ }
100
+ catch {
101
+ // No Intl: none of these.
102
+ }
103
+ const nav = globalThis.navigator;
104
+ const languages = (nav?.languages ?? []).filter(Boolean);
105
+ if (languages.length)
106
+ out.languages = languages.join(',');
107
+ if (nav?.connection?.effectiveType)
108
+ out.network = nav.connection.effectiveType;
109
+ const screen = globalThis.screen;
110
+ if (screen?.width)
111
+ out.screen_width = screen.width;
112
+ if (screen?.height)
113
+ out.screen_height = screen.height;
114
+ const win = globalThis;
115
+ if (win.devicePixelRatio)
116
+ out.pixel_ratio = Math.round(win.devicePixelRatio * 1000) / 1000;
117
+ if (typeof win.matchMedia === 'function') {
118
+ try {
119
+ out.color_scheme = win.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
120
+ }
121
+ catch {
122
+ // A matchMedia that throws: no preference known.
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+ /**
128
+ * What Chromium tells a page that asks (User-Agent Client Hints): an Android phone's model, and the real
129
+ * OS version where the user agent string is frozen (Windows 11 still says 10, macOS 10.15.7). Safari and
130
+ * Firefox do not answer, and an iPhone's model is never given; then this is empty.
131
+ */
132
+ export async function clientHints() {
133
+ const data = globalThis.navigator
134
+ ?.userAgentData;
135
+ if (typeof data?.getHighEntropyValues !== 'function')
136
+ return {};
137
+ try {
138
+ const v = await data.getHighEntropyValues(['model', 'platformVersion']);
139
+ const out = {};
140
+ if (typeof v.model === 'string' && v.model.trim())
141
+ out.device_model = v.model.trim();
142
+ const version = osVersionOf(String(v.platform ?? ''), String(v.platformVersion ?? ''));
143
+ if (version)
144
+ out.os_version = version;
145
+ return out;
146
+ }
147
+ catch {
148
+ return {};
149
+ }
150
+ }
151
+ /** A platform's version as people name it: Windows 13.x and later is 11, macOS and the rest major.minor. */
152
+ export function osVersionOf(platform, version) {
153
+ const [major = '', minor = ''] = version.split('.');
154
+ const n = Number(major);
155
+ if (!major || Number.isNaN(n))
156
+ return null;
157
+ if (platform === 'Windows')
158
+ return n >= 13 ? '11' : n > 0 ? '10' : null;
159
+ if (n === 0)
160
+ return null;
161
+ return minor && minor !== '0' ? `${n}.${minor}` : String(n);
78
162
  }
79
163
  /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
80
164
  export function doNotTrack() {
package/dist/daybook.js CHANGED
@@ -1 +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"});})();
1
+ "use strict";(()=>{var M=class{constructor(t=!1){this.enabled=t,this.said=new Set}debug(t,e,...i){this.enabled&&console.log(`[daybook] ${t}: ${e}`,...i)}warn(t,e){let i=`[daybook] ${t}: ${e}`;this.said.has(i)||(this.said.add(i),console.warn(i))}};var nt=Symbol.for("daybook.modules");function E(){var t;let n=globalThis;return(t=n[nt])!=null?t:n[nt]=new Map}function F(n,t){let e=E();e.has(n)||e.set(n,t)}function L(){return[...E().keys()]}function st(){return[...E().values()].map(n=>n())}function rt(){E().clear()}var B="daybook";function ot(){let n={},t=()=>{try{return typeof localStorage!="undefined"?localStorage:null}catch{return null}};return{get(){var e;try{let i=(e=t())==null?void 0:e.getItem(B),s=i?JSON.parse(i):null;if(s&&typeof s=="object"&&!Array.isArray(s))return s}catch{}return{...n}},set(e){var i,s;n={...e};try{Object.keys(e).length===0?(i=t())==null||i.removeItem(B):(s=t())==null||s.setItem(B,JSON.stringify(e))}catch{}}}}function at(){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 ct="0.1.0";var ht="https://api.daybook.team",b=null,O=null,S=class n{constructor(t,e){this.context=t,this.store=e,this.started=[],this.failed={}}static initialize(t,e={}){return b?(typeof t=="string"&&t.trim()!==""&&t.trim()!==b.context.key&&b.context.log.warn("core","initialize was called again with another key; the first one is kept."),Promise.resolve(b)):O!=null?O:O=_t(t,e!=null?e:{}).then(i=>b=i)}static get instance(){if(!b)throw new Error("Daybook is not started. Call `await Daybook.initialize('dbk_\u2026')` once, before using it.");return b}static get isInitialized(){return b!==null}static resetForTesting(t={}){b=null,O=null,t.modules&&rt()}static async create(t,e,i){var Z,Q,tt;let s=e,r=new M(e.logging===!0),a=typeof window!="undefined"&&typeof document!="undefined";t=typeof t=="string"?t.trim():"",t===""?r.warn("core","initialize needs the site's key, dbk_\u2026, from the project's settings in Daybook. Nothing will be sent."):t.startsWith("dbk_")||r.warn("core","the key does not start with dbk_. Daybook takes the site's key from the project's settings, not a key of one hub (dak_ or pmi_); a hub's key works only at that hub's door."),Array.isArray(e.modules)&&(i=i.filter(u=>e.modules.includes(u.name))),i=[...i].sort((u,d)=>{var et,it;return((et=u.order)!=null?et:100)-((it=d.order)!=null?it:100)||u.name.localeCompare(d.name)});let o=ot(),c=a?o.get():{},l=m(c.visitor_id),f=typeof c.tracking_consent=="boolean"?c.tracking_consent:void 0;if(a&&l===void 0&&f===void 0)for(let u of i)try{let d=(Z=u.legacy)==null?void 0:Z.call(u,s[u.name]);l===void 0&&m(d==null?void 0:d.visitorId)!==void 0&&(l=m(d==null?void 0:d.visitorId),r.debug("core",`kept the visitor id the ${u.name} module already had`)),f===void 0&&typeof(d==null?void 0:d.trackingConsent)=="boolean"&&(f=d.trackingConsent)}catch{}l!=null||(l=at());let g=c.user,p=g&&typeof g=="object"&&m(g.id)!==void 0?{id:m(g.id),email:m(g.email),name:m(g.name)}:null,k=m(e.userId);k!==void 0&&k!==(p==null?void 0:p.id)&&(p={id:k});let y=null,G={key:t,serverUrl:((Q=m(e.serverUrl))!=null?Q:ht).replace(/\/+$/,""),visitorId:l,anonymousId:(tt=m(c.anonymous_id))!=null?tt:l,trackingConsent:f!=null?f:e.trackingConsent!==!1,trackingConsentAnswered:f!==void 0,user:p,browser:a,log:r,options:s,setTrackingConsent:u=>y==null?void 0:y.setTrackingConsent(u)};y=new n(G,o),y.save();for(let u of i)try{if(u.name in y)throw new Error(`"${u.name}" is a name of the core's own`);let d=await u.start(G);Object.defineProperty(y,u.name,{value:d,enumerable:!0,configurable:!0}),y.started.push(u),r.debug("core",`the ${u.name} module started`)}catch(d){y.failed[u.name]=J(d),r.warn(u.name,`did not start: ${J(d)}`)}return y.save(),i.length===0&&r.warn("core","no Daybook module is loaded. Import @daybook/analytics or @daybook/feedback beside @daybook/core."),y}get key(){return this.context.key}get visitorId(){return this.context.visitorId}get userId(){var t,e;return(e=(t=this.context.user)==null?void 0:t.id)!=null?e:null}get trackingConsent(){return this.context.trackingConsent}get modules(){return this.started.map(t=>t.name)}get failedModules(){return{...this.failed}}has(t){return this.started.some(e=>e.name===t)}module(t){if(this.has(t))return this[t];let e=this.failed[t];throw new Error(e!==void 0?`Daybook's ${t} module did not start: ${e}`:`Daybook's ${t} module is not loaded. Import @daybook/${t} beside @daybook/core, before Daybook.initialize.`)}identify(t,e={}){let i=typeof t=="string"||typeof t=="number"?String(t).trim():"";if(i===""){this.context.log.warn("core","identify needs the user's id; got an empty one");return}let s={id:i,email:m(e==null?void 0:e.email),name:m(e==null?void 0:e.name)};this.context.user=s,this.save(),this.each("identify",r=>{var a;return(a=r.identify)==null?void 0:a.call(r,s)}),this.save()}reset(){this.context.user=null,this.each("reset",t=>{var e;return(e=t.reset)==null?void 0:e.call(t)}),this.save()}setTrackingConsent(t){t=t===!0,this.context.trackingConsent=t,this.context.trackingConsentAnswered=!0,this.save(),this.each("setTrackingConsent",e=>{var i;return(i=e.setTrackingConsent)==null?void 0:i.call(e,t)}),this.save()}each(t,e){for(let i of this.started)try{e(i)}catch(s){this.context.log.warn(i.name,`${t} did not go through: ${J(s)}`)}}save(){let t=this.context;if(!t.browser)return;if(!t.trackingConsent){this.store.set(t.trackingConsentAnswered?{tracking_consent:!1}:{});return}let e={visitor_id:t.visitorId,anonymous_id:t.anonymousId};t.user&&(e.user=t.user),t.trackingConsentAnswered&&(e.tracking_consent=!0),this.store.set(e)}};S.version=ct;function _t(n,t){return S.create(n,t,st())}function m(n){return typeof n=="string"&&n.trim()!==""?n.trim():void 0}function J(n){return n instanceof Error?n.message:String(n)}function At(n,t=0){let e=f=>{var g,p;return(p=(g=f.exec(n))==null?void 0:g[1])!=null?p:""},i="",s="",r=(f,g)=>{var k;let p=g.exec(n);return p?(i=f,s=(k=p[1])!=null?k:"",!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="",c=/Macintosh/.test(n)&&t>1;/iPhone|iPad|iPod/.test(n)||c?(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 l=/iPad|Tablet/.test(n)||c||/Android/.test(n)&&!/Mobile/.test(n)?"tablet":/Mobi|iPhone|iPod/.test(n)?"mobile":"desktop";return{browser:i,browserVersion:s,os:a,osVersion:o,deviceType:l}}function lt(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 ut(n){var s,r,a;let t=globalThis.navigator,e=At((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,...Ot()},browserVersion:e.browserVersion}}function Ot(){var r,a;let n={};try{let o=Intl.DateTimeFormat().resolvedOptions();o.timeZone&&(n.timezone=o.timeZone),o.calendar&&(n.calendar=o.calendar),o.numberingSystem&&(n.numbering_system=o.numberingSystem);let c=new Intl.DateTimeFormat(void 0,{hour:"numeric"}).resolvedOptions().hourCycle;c&&(n.hour_cycle=c)}catch{}let t=globalThis.navigator,e=((r=t==null?void 0:t.languages)!=null?r:[]).filter(Boolean);e.length&&(n.languages=e.join(",")),(a=t==null?void 0:t.connection)!=null&&a.effectiveType&&(n.network=t.connection.effectiveType);let i=globalThis.screen;i!=null&&i.width&&(n.screen_width=i.width),i!=null&&i.height&&(n.screen_height=i.height);let s=globalThis;if(s.devicePixelRatio&&(n.pixel_ratio=Math.round(s.devicePixelRatio*1e3)/1e3),typeof s.matchMedia=="function")try{n.color_scheme=s.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch{}return n}async function ft(){var t,e,i;let n=(t=globalThis.navigator)==null?void 0:t.userAgentData;if(typeof(n==null?void 0:n.getHighEntropyValues)!="function")return{};try{let s=await n.getHighEntropyValues(["model","platformVersion"]),r={};typeof s.model=="string"&&s.model.trim()&&(r.device_model=s.model.trim());let a=It(String((e=s.platform)!=null?e:""),String((i=s.platformVersion)!=null?i:""));return a&&(r.os_version=a),r}catch{return{}}}function It(n,t){let[e="",i=""]=t.split("."),s=Number(e);return!e||Number.isNaN(s)?null:n==="Windows"?s>=13?"11":s>0?"10":null:s===0?null:i&&i!=="0"?`${s}.${i}`:String(s)}function W(){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 Tt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid"];function C(n){let t={};try{let e=new URL(n).searchParams;for(let i of Tt){let s=e.get(i);s&&(t[`$${i}`]=s.slice(0,200))}}catch{}return t}function j(n){if(!n)return"$direct";try{return new URL(n).hostname}catch{return"$direct"}}function dt(n,t){let e={$initial_referrer:t||"$direct",$initial_referring_domain:j(t)};for(let[i,s]of Object.entries(C(n)))e[`$initial_${i.slice(1)}`]=s;return e}function q(n){var e;let t=(e=n.hash)!=null?e:"";return n.pathname+(t.startsWith("#/")||t.startsWith("#!")?t.split("?")[0]:"")}var P=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 I(){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)},names:()=>[...n.keys()]}}function K(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{}},names:()=>{try{return Array.from({length:t.length},(e,i)=>t.key(i)).filter(e=>typeof e=="string")}catch{return[]}}}}function Dt(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{}},names:()=>{try{return document.cookie.split("; ").map(s=>{var r;return(r=s.split("=")[0])!=null?r:""}).filter(Boolean)}catch{return[]}}}}function U(n,t){var e,i;return n==="memory"?I():n==="cookie"||t?(e=Dt(t))!=null?e:I():(i=K("localStorage"))!=null?i:I()}function T(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}}function V(n,t){var i,s,r,a;let e=null;for(let o of n.names()){if(o===t||!/^dbk_[A-Za-z0-9]{1,8}$/.test(o))continue;let c=T(n,o);!c||typeof c.anon!="string"&&c.consent===void 0||(!e||((s=(i=c.session)==null?void 0:i.last)!=null?s:0)>((a=(r=e.session)==null?void 0:r.last)!=null?a:0))&&(e=c)}return e}function gt(n){return`dbk_${n.trim().replace(/^dak_/,"").slice(0,8)}`}var D="0.4.0";var Nt=512*1024,pt=60*1024,H=1e3,R=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<pt})}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}}},z=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>H&&(this.jobs.splice(0,this.jobs.length-H),this.log.warn(`more than ${H} 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(pt,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(Nt);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 c=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:c)/1e3)} s`),this.schedule((e=o.afterMs)!=null?e:c);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 c=JSON.stringify(o.e).length+1;if(r.length>0&&a+c>t)break;r.push(o.e),a+=c}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,c,l;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 f of r)this.log.warn(`"${(c=(o=i[f.index])==null?void 0:o.event)!=null?c:"?"}" was refused (${f.reason}): ${(l=f.message)!=null?l:""}`)}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 v(){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 mt="https://api.daybook.team",Mt="$pageview",Et="$pageleave",Ct="$session_start",jt=1440*6e4,w=class{constructor(t,e){var a,o,c,l,f,g,p;var i;if(this.options=t,this.family=e,this.context={},this.browserVersion="",this.outbox=null,this.cleanup=[],this.current=null,this.referrer=null,this.ignored=!1,!t||typeof t.key!="string"||t.key.trim()==="")throw new Error("@daybook/analytics: `key` is required: the site's key from the project's settings, or the ingest key from Analytics \u2192 Settings.");if(this.log=new P(t.debug===!0),this.browser=typeof window!="undefined"&&typeof document!="undefined",this.stateName=gt(t.key),this.store=this.browser?U((a=t.persistence)!=null?a:"localStorage",t.cookieDomain):I(),this.state={anon:(e==null?void 0:e.anonymousId)||v(),props:{}},!this.browser)return;let s=(o=navigator.userAgent)!=null?o:"";t.ignoreBots!==!1&&lt(s)&&(this.ignored=!0,this.log.debug("this browser says it is a crawler; nothing is sent from it"));let r=ut(t.appVersion);this.context=r.context,this.browserVersion=r.browserVersion,ft().then(k=>Object.assign(this.context,k)),this.state=this.load((c=T(this.store,this.stateName))!=null?c:this.earlier()),(l=(i=this.state).initial)!=null||(i.initial=dt(location.href,document.referrer)),t.properties&&Object.assign(this.state.props,$(t.properties)),this.save(),this.outbox=new z(new R((f=t.apiUrl)!=null?f:mt,t.key.trim()),K("sessionStorage"),`${this.stateName}_queue`,{batchSize:Math.max(1,Math.min(1e3,(g=t.batchSize)!=null?g:50)),flushIntervalMs:Math.max(0,(p=t.flushIntervalMs)!=null?p: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=q(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(Mt,{$title:document.title,$referrer:r||"$direct",$referring_domain:j(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,...C(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?$(e):void 0}}))}}reset(){this.browser&&(this.sync(),this.state={anon:v(),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:$(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:$(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,$(t)),this.save())}unregister(t){this.browser&&(this.sync(),delete this.state.props[t],this.save())}optIn(){if(!this.browser)return;if(this.family)return this.family.answer(!0);let t=this.sending;this.state.consent="in",this.consented(t)}optOut(){var t;if(this.browser){if(this.family)return this.family.answer(!1);this.state.consent="out",(t=this.outbox)==null||t.clear(),this.save()}}consented(t){var e;this.browser&&(this.sending?(this.save(),!t&&this.options.autoPageviews!==!1&&this.page()):((e=this.outbox)==null||e.clear(),this.family?this.store.remove(this.stateName):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.family?this.options.respectDoNotTrack&&W()&&!this.family.answered()?!1:this.family.consent():this.state.consent?this.state.consent==="in":!(this.options.optOutByDefault||this.options.respectDoNotTrack&&W())}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(Ct,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:j(t),...C(location.href)}}emit(t,e,i,s){if(!this.outbox)return;let r={event:t,event_id:v(),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:D,...this.state.initial,...this.state.props,...$(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(c){this.log.warn(`beforeSend threw, so "${t}" was dropped: ${String(c)}`);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)>jt?(this.state.session={id:v(),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(Et,{$url:e.url,$path:e.path,$duration_ms:Math.max(0,t-e.at)})}watchHistory(){let t=()=>setTimeout(()=>{!this.current||this.current.route!==q(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))}earlier(){return this.family?V(this.store,this.stateName):null}load(t=T(this.store,this.stateName)){var e;return{anon:typeof(t==null?void 0:t.anon)=="string"&&t.anon?t.anon:((e=this.family)==null?void 0:e.anonymousId)||v(),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:!this.family&&((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=T(this.store,this.stateName);typeof(t==null?void 0:t.anon)=="string"&&t.anon!==""&&(this.state=this.load(t))}save(){var t;this.browser&&((t=this.family)==null||t.onAnonymousId(this.state.anon),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 $(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 X=class{constructor(){this.name="analytics",this.order=10,this.client=null,this.sending=!1}legacy(t){var s;if(typeof window=="undefined"||typeof document=="undefined")return null;let e=t!=null?t:{},i=V(U((s=e.persistence)!=null?s:"localStorage",e.cookieDomain),"");return i?{visitorId:typeof i.anon=="string"?i.anon:void 0,trackingConsent:i.consent==="in"?!0:i.consent==="out"?!1:void 0}:null}start(t){var s,r,a;if(t.key==="")throw new Error("there is no key to send events with");let e=(s=t.options.analytics)!=null?s:{},i=new w({...e,key:t.key,apiUrl:(r=e.apiUrl)!=null?r:t.serverUrl,debug:(a=e.debug)!=null?a:t.log.enabled},{consent:()=>t.trackingConsent,answered:()=>t.trackingConsentAnswered,answer:o=>t.setTrackingConsent(o),anonymousId:t.anonymousId,onAnonymousId:o=>{t.anonymousId=o}});return this.client=i,this.sending=i.sending,t.anonymousId=i.distinctId,t.user&&i.userId!==t.user.id&&this.identify(t.user),i}identify(t){var i;let e={};t.email&&(e.$email=t.email),t.name&&(e.$name=t.name),(i=this.client)==null||i.identify(t.id,Object.keys(e).length>0?e:void 0)}reset(){var t;(t=this.client)==null||t.reset()}setTrackingConsent(){var e,i;let t=this.sending;this.sending=((e=this.client)==null?void 0:e.sending)===!0,(i=this.client)==null||i.consented(t)}};F("analytics",()=>new X);var _=null;function yt(n){return _?(n!=null&&n.key&&n.key.trim()!==_.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."),_):(_=new w(n),_)}function bt(){return _}var x=globalThis,A=typeof document!="undefined"?document.currentScript:null,Y=["track","page","register","unregister","setPersonProperties","setPersonPropertiesOnce","optIn","optOut","flush"];function xt(){let n=x.daybook;return Array.isArray(n==null?void 0:n.q)?n.q:[]}function vt(n){let t=xt(),e=yt(n);x.daybook=e;for(let[i,s]of t){let r=e[i];typeof r=="function"&&r.apply(e,s)}return e}function Pt(n){return new Promise(t=>{try{let e=document.createElement("script");e.async=!0,e.src=new URL(`${n}.js`,(A==null?void 0:A.src)||location.href).href,e.onload=()=>t(),e.onerror=()=>{console.warn(`[daybook] ${n}: its script could not be loaded from ${e.src}; the other modules start without it`),t()},document.head.appendChild(e)}catch{t()}})}async function $t(n,t={}){var a;let e=xt(),i=(a=t.modules)!=null?a:["analytics"];await Promise.all(i.filter(o=>/^[a-z]+$/.test(o)&&!L().includes(o)).map(Pt));let s=await S.initialize(n,{...t,modules:i}),r=s;for(let o of Y)o in r||(r[o]=(...c)=>wt(r.analytics,o,c));x.daybook=s;for(let[o,c]of e)try{let l=o.lastIndexOf(".");wt(l<0?r:r[o.slice(0,l)],o.slice(l+1),c)}catch(l){console.warn(`[daybook] ${o} was queued before the script loaded and failed: ${String(l)}`)}return s}function Ut(){let n=[],t=i=>(...s)=>{n.push([i,s])},e=(i,s)=>Object.fromEntries(s.map(r=>[r,t(i+r)]));return{q:n,...e("",["identify","reset","setTrackingConsent",...Y]),analytics:e("analytics.",Y),feedback:e("feedback.",["open","start","stop","authenticate"])}}function wt(n,t,e){let i=n==null?void 0:n[t];return typeof i=="function"?i.apply(n,e):void 0}x.DaybookAnalytics={init:vt,getAnalytics:bt,DaybookAnalytics:w,version:D};x.Daybook={initialize:$t,version:S.version};var h=A==null?void 0:A.dataset,N=n=>n!==void 0&&n!=="false",kt,St;if(h!=null&&h.key){let n={apiUrl:h.apiUrl,appVersion:h.appVersion,autoPageviews:h.pageviews!=="false",pageleave:h.pageleave!=="false",persistence:h.persistence,cookieDomain:h.cookieDomain,respectDoNotTrack:N(h.respectDnt),debug:N(h.debug)};h.key.trim().startsWith("dbk_")||h.modules!==void 0?(Array.isArray((kt=x.daybook)==null?void 0:kt.q)||(x.daybook=Ut()),$t(h.key,{modules:((St=h.modules)!=null?St:"analytics").split(",").map(t=>t.trim()).filter(Boolean),serverUrl:h.apiUrl,userId:h.userId,trackingConsent:!N(h.optOutByDefault)&&h.trackingConsent!=="false",logging:N(h.debug),analytics:n,feedback:{app:h.appVersion?{version:h.appVersion}:void 0,surface:h.surface}})):vt({...n,key:h.key,optOutByDefault:N(h.optOutByDefault)})}})();
package/dist/index.d.ts CHANGED
@@ -1,16 +1,26 @@
1
1
  import { DaybookAnalytics } from './client.js';
2
+ import './module.js';
2
3
  import type { AnalyticsOptions } from './types.js';
4
+ export type { AnalyticsModuleOptions } from './module.js';
3
5
  export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
4
6
  export { SDK_VERSION } from './version.js';
5
7
  export type { AnalyticsEvent, AnalyticsOptions, EventContext, Persistence, Properties, PropertyValue, } from './types.js';
6
8
  /**
7
- * Starts analytics for this site, once:
9
+ * Starts analytics by itself, once: the way before Daybook's core, kept for sites that use it.
8
10
  *
9
11
  * import { init } from '@daybook/analytics'
10
12
  *
11
13
  * const analytics = init({ key: 'dak_…' })
12
14
  * analytics.track('signed_up', { plan: 'pro' })
13
15
  *
16
+ * A new site starts the core instead, with the site's one key, and analytics starts with it:
17
+ *
18
+ * import { Daybook } from '@daybook/core'
19
+ * import '@daybook/analytics'
20
+ *
21
+ * const daybook = await Daybook.initialize('dbk_…')
22
+ * daybook.analytics.track('signed_up', { plan: 'pro' })
23
+ *
14
24
  * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
15
25
  * mounted twice cannot start a second one that sends every page view again.
16
26
  */
package/dist/index.js CHANGED
@@ -1,15 +1,24 @@
1
1
  import { DaybookAnalytics } from './client.js';
2
+ import './module.js';
2
3
  export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
3
4
  export { SDK_VERSION } from './version.js';
4
5
  let shared = null;
5
6
  /**
6
- * Starts analytics for this site, once:
7
+ * Starts analytics by itself, once: the way before Daybook's core, kept for sites that use it.
7
8
  *
8
9
  * import { init } from '@daybook/analytics'
9
10
  *
10
11
  * const analytics = init({ key: 'dak_…' })
11
12
  * analytics.track('signed_up', { plan: 'pro' })
12
13
  *
14
+ * A new site starts the core instead, with the site's one key, and analytics starts with it:
15
+ *
16
+ * import { Daybook } from '@daybook/core'
17
+ * import '@daybook/analytics'
18
+ *
19
+ * const daybook = await Daybook.initialize('dbk_…')
20
+ * daybook.analytics.track('signed_up', { plan: 'pro' })
21
+ *
13
22
  * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
14
23
  * mounted twice cannot start a second one that sends every page view again.
15
24
  */