@daybook/analytics 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ import type { AnalyticsEvent } from './types.js';
2
+ import type { Log } from './log.js';
3
+ import type { Store } from './storage.js';
4
+ export interface IdentifyBody {
5
+ distinct_id: string;
6
+ user_id: string;
7
+ properties?: Record<string, unknown>;
8
+ }
9
+ export interface PeopleBody {
10
+ distinct_id?: string;
11
+ user_id?: string;
12
+ set?: Record<string, unknown>;
13
+ /** Written only where the person has no value yet, under any of their ids. */
14
+ set_once?: Record<string, unknown>;
15
+ unset?: string[];
16
+ }
17
+ /** One thing waiting to be sent: an event (sent in batches), an identify, or a person's properties. */
18
+ export type Job = {
19
+ t: 'e';
20
+ e: AnalyticsEvent;
21
+ } | {
22
+ t: 'i';
23
+ b: IdentifyBody;
24
+ } | {
25
+ t: 'p';
26
+ b: PeopleBody;
27
+ };
28
+ type Outcome = {
29
+ kind: 'ok';
30
+ body: unknown;
31
+ } | {
32
+ kind: 'retry';
33
+ afterMs?: number;
34
+ } | {
35
+ kind: 'too_large';
36
+ } | {
37
+ kind: 'drop';
38
+ status: number;
39
+ detail: string;
40
+ };
41
+ /**
42
+ * Talks to `/analytics/v1` the way a page can (PM-T-0528): the key and the SDK's name in the query
43
+ * string and the body as `text/plain`, so every request is CORS-simple — no preflight — and the one
44
+ * sent while the page is going away can be a beacon, which cannot set headers at all.
45
+ */
46
+ export declare class Transport {
47
+ private readonly apiUrl;
48
+ private readonly key;
49
+ constructor(apiUrl: string, key: string);
50
+ url(path: string): string;
51
+ post(path: string, text: string): Promise<Outcome>;
52
+ /** True when the browser took it; it sends it after the page is gone, and no answer ever comes back. */
53
+ beacon(path: string, text: string): boolean;
54
+ }
55
+ export interface OutboxOptions {
56
+ batchSize: number;
57
+ flushIntervalMs: number;
58
+ }
59
+ /**
60
+ * Everything waiting to be sent, in order, and the sending of it (PM-R-0062 criterion 4).
61
+ *
62
+ * <p>
63
+ * Kept in sessionStorage, which outlives a reload and a crash of the page but is one tab's own. A
64
+ * queue in localStorage would be every tab's, and two tabs would each send the other's events; with
65
+ * this one a closed tab loses what it could not send while offline, which is the smaller harm.
66
+ * </p>
67
+ *
68
+ * <p>
69
+ * A batch that fails is sent again exactly as it was — the same events, not the same events plus
70
+ * whatever arrived since — so the API's deduplication token, made from the batch's event ids,
71
+ * recognises it and stores it once.
72
+ * </p>
73
+ *
74
+ * <p>
75
+ * Every batch says when it left, as <code>sent_at</code> by this device's clock (PM-R-0068). The API
76
+ * moves each event by the gap between that and when the batch arrived, so a clock that is wrong, or an
77
+ * event that waited offline for hours, still lands at the time it happened. It is stamped as the
78
+ * request is made — each retry and each beacon anew — never when the events were queued.
79
+ * </p>
80
+ */
81
+ export declare class Outbox {
82
+ private readonly transport;
83
+ private readonly store;
84
+ private readonly name;
85
+ private readonly options;
86
+ private readonly log;
87
+ private jobs;
88
+ private timer;
89
+ private sending;
90
+ private failures;
91
+ private retrySize;
92
+ private inFlight;
93
+ private stopped;
94
+ constructor(transport: Transport, store: Store | null, name: string, options: OutboxOptions, log: Log);
95
+ get size(): number;
96
+ push(job: Job): void;
97
+ /** Sends everything now, and resolves when the queue is empty or the API cannot be reached. */
98
+ flush(): Promise<void>;
99
+ /**
100
+ * The page is going away: hand everything to the browser as beacons, which it sends after the page
101
+ * is gone. A batch already on its way was sent with keepalive and stays queued until it is answered.
102
+ */
103
+ beaconAll(): void;
104
+ clear(): void;
105
+ stop(): void;
106
+ /** Online again: whatever is waiting goes now rather than at the end of its backoff. */
107
+ resume(): void;
108
+ private schedule;
109
+ private drain;
110
+ /** The next request from `from` on: one identify or person update, or as many events in a row as fit. */
111
+ private next;
112
+ /** The API stores the good events of a batch and says which it refused and why. */
113
+ private report;
114
+ private refused;
115
+ private load;
116
+ private save;
117
+ }
118
+ export {};
@@ -0,0 +1,255 @@
1
+ import { SDK_NAME } from './version.js';
2
+ /** The API takes 1 MB a batch; staying well under it leaves room for what JSON adds. */
3
+ const MAX_BATCH_BYTES = 512 * 1024;
4
+ /** What a browser lets a beacon or a keepalive request carry, all of them together. */
5
+ const MAX_BEACON_BYTES = 60 * 1024;
6
+ const MAX_QUEUE = 1000;
7
+ /**
8
+ * Talks to `/analytics/v1` the way a page can (PM-T-0528): the key and the SDK's name in the query
9
+ * string and the body as `text/plain`, so every request is CORS-simple — no preflight — and the one
10
+ * sent while the page is going away can be a beacon, which cannot set headers at all.
11
+ */
12
+ export class Transport {
13
+ constructor(apiUrl, key) {
14
+ this.apiUrl = apiUrl;
15
+ this.key = key;
16
+ }
17
+ url(path) {
18
+ return `${this.apiUrl.replace(/\/+$/, '')}/analytics/v1/${path}?key=${encodeURIComponent(this.key)}&sdk=${SDK_NAME}`;
19
+ }
20
+ async post(path, text) {
21
+ let response;
22
+ try {
23
+ response = await fetch(this.url(path), {
24
+ method: 'POST',
25
+ body: text,
26
+ headers: { 'Content-Type': 'text/plain' },
27
+ credentials: 'omit',
28
+ keepalive: text.length < MAX_BEACON_BYTES,
29
+ });
30
+ }
31
+ catch {
32
+ return { kind: 'retry' };
33
+ }
34
+ if (response.ok)
35
+ return { kind: 'ok', body: await response.json().catch(() => null) };
36
+ if (response.status === 413)
37
+ return { kind: 'too_large' };
38
+ if (response.status === 408 || response.status === 429 || response.status >= 500) {
39
+ const seconds = Number(response.headers.get('Retry-After'));
40
+ return { kind: 'retry', afterMs: Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : undefined };
41
+ }
42
+ const body = (await response.json().catch(() => null));
43
+ return { kind: 'drop', status: response.status, detail: body?.message ?? body?.code ?? '' };
44
+ }
45
+ /** True when the browser took it; it sends it after the page is gone, and no answer ever comes back. */
46
+ beacon(path, text) {
47
+ const url = this.url(path);
48
+ try {
49
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function')
50
+ return navigator.sendBeacon(url, new Blob([text], { type: 'text/plain' }));
51
+ void fetch(url, { method: 'POST', body: text, headers: { 'Content-Type': 'text/plain' }, credentials: 'omit', keepalive: true })
52
+ .catch(() => undefined);
53
+ return true;
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ }
59
+ }
60
+ /**
61
+ * Everything waiting to be sent, in order, and the sending of it (PM-R-0062 criterion 4).
62
+ *
63
+ * <p>
64
+ * Kept in sessionStorage, which outlives a reload and a crash of the page but is one tab's own. A
65
+ * queue in localStorage would be every tab's, and two tabs would each send the other's events; with
66
+ * this one a closed tab loses what it could not send while offline, which is the smaller harm.
67
+ * </p>
68
+ *
69
+ * <p>
70
+ * A batch that fails is sent again exactly as it was — the same events, not the same events plus
71
+ * whatever arrived since — so the API's deduplication token, made from the batch's event ids,
72
+ * recognises it and stores it once.
73
+ * </p>
74
+ *
75
+ * <p>
76
+ * Every batch says when it left, as <code>sent_at</code> by this device's clock (PM-R-0068). The API
77
+ * moves each event by the gap between that and when the batch arrived, so a clock that is wrong, or an
78
+ * event that waited offline for hours, still lands at the time it happened. It is stamped as the
79
+ * request is made — each retry and each beacon anew — never when the events were queued.
80
+ * </p>
81
+ */
82
+ export class Outbox {
83
+ constructor(transport, store, name, options, log) {
84
+ this.transport = transport;
85
+ this.store = store;
86
+ this.name = name;
87
+ this.options = options;
88
+ this.log = log;
89
+ this.timer = null;
90
+ this.sending = null;
91
+ this.failures = 0;
92
+ this.retrySize = null;
93
+ this.inFlight = 0;
94
+ this.stopped = false;
95
+ this.jobs = this.load();
96
+ if (this.jobs.length > 0)
97
+ this.schedule(0);
98
+ }
99
+ get size() {
100
+ return this.jobs.length;
101
+ }
102
+ push(job) {
103
+ this.jobs.push(job);
104
+ // A page that cannot reach the API for hours must not grow without end; the oldest go first.
105
+ if (this.jobs.length > MAX_QUEUE) {
106
+ this.jobs.splice(0, this.jobs.length - MAX_QUEUE);
107
+ this.log.warn(`more than ${MAX_QUEUE} events are waiting to be sent; the oldest were dropped`);
108
+ }
109
+ this.save();
110
+ this.schedule(this.options.flushIntervalMs);
111
+ }
112
+ /** Sends everything now, and resolves when the queue is empty or the API cannot be reached. */
113
+ flush() {
114
+ if (this.timer !== null) {
115
+ clearTimeout(this.timer);
116
+ this.timer = null;
117
+ }
118
+ this.sending ?? (this.sending = this.drain().finally(() => { this.sending = null; }));
119
+ return this.sending;
120
+ }
121
+ /**
122
+ * The page is going away: hand everything to the browser as beacons, which it sends after the page
123
+ * is gone. A batch already on its way was sent with keepalive and stays queued until it is answered.
124
+ */
125
+ beaconAll() {
126
+ while (this.jobs.length > this.inFlight) {
127
+ const { path, text, count } = this.next(MAX_BEACON_BYTES, this.inFlight);
128
+ if (!this.transport.beacon(path, text))
129
+ break;
130
+ this.jobs.splice(this.inFlight, count);
131
+ }
132
+ if (this.inFlight === 0)
133
+ this.retrySize = null;
134
+ this.save();
135
+ }
136
+ clear() {
137
+ this.jobs = [];
138
+ this.retrySize = null;
139
+ this.save();
140
+ }
141
+ stop() {
142
+ this.stopped = true;
143
+ if (this.timer !== null)
144
+ clearTimeout(this.timer);
145
+ this.timer = null;
146
+ }
147
+ /** Online again: whatever is waiting goes now rather than at the end of its backoff. */
148
+ resume() {
149
+ if (this.jobs.length > 0 && !this.sending)
150
+ void this.flush();
151
+ }
152
+ schedule(delayMs) {
153
+ if (this.stopped || this.timer !== null)
154
+ return;
155
+ this.timer = setTimeout(() => {
156
+ this.timer = null;
157
+ void this.flush();
158
+ }, delayMs);
159
+ }
160
+ async drain() {
161
+ while (this.jobs.length > 0 && !this.stopped) {
162
+ const { path, text, count, events } = this.next(MAX_BATCH_BYTES);
163
+ this.inFlight = count;
164
+ const outcome = await this.transport.post(path, text).finally(() => { this.inFlight = 0; });
165
+ if (outcome.kind === 'retry') {
166
+ this.retrySize = count;
167
+ this.failures++;
168
+ // 1 s, 2 s, 4 s … up to five minutes, with jitter so a fleet of pages does not return at once.
169
+ const backoff = Math.min(300000, 1000 * 2 ** Math.min(this.failures - 1, 9)) * (0.75 + Math.random() / 2);
170
+ this.log.debug(`could not reach the API; trying again in ${Math.round((outcome.afterMs ?? backoff) / 1000)} s`);
171
+ this.schedule(outcome.afterMs ?? backoff);
172
+ return;
173
+ }
174
+ if (outcome.kind === 'too_large' && count > 1) {
175
+ this.retrySize = Math.ceil(count / 2);
176
+ continue;
177
+ }
178
+ this.jobs.splice(0, count);
179
+ this.retrySize = null;
180
+ this.failures = 0;
181
+ this.save();
182
+ if (outcome.kind === 'ok')
183
+ this.report(path, outcome.body, events, count);
184
+ else if (outcome.kind === 'too_large')
185
+ this.log.warn('an event was too large for the API and was dropped');
186
+ else
187
+ this.refused(outcome.status, outcome.detail, path, count);
188
+ }
189
+ }
190
+ /** The next request from `from` on: one identify or person update, or as many events in a row as fit. */
191
+ next(maxBytes, from = 0) {
192
+ const first = this.jobs[from];
193
+ if (first.t === 'i')
194
+ return { path: 'identify', text: JSON.stringify(first.b), count: 1, events: [] };
195
+ if (first.t === 'p')
196
+ return { path: 'people', text: JSON.stringify(first.b), count: 1, events: [] };
197
+ const limit = from === 0 && this.retrySize !== null ? this.retrySize : this.options.batchSize;
198
+ const events = [];
199
+ let bytes = 16;
200
+ for (const job of this.jobs.slice(from)) {
201
+ if (job.t !== 'e' || events.length >= limit)
202
+ break;
203
+ const size = JSON.stringify(job.e).length + 1;
204
+ if (events.length > 0 && bytes + size > maxBytes)
205
+ break;
206
+ events.push(job.e);
207
+ bytes += size;
208
+ }
209
+ return { path: 'batch', text: JSON.stringify({ sent_at: new Date().toISOString(), events }), count: events.length, events };
210
+ }
211
+ /** The API stores the good events of a batch and says which it refused and why. */
212
+ report(path, body, events, count) {
213
+ if (path !== 'batch') {
214
+ this.log.debug(`${path} sent`);
215
+ return;
216
+ }
217
+ const refused = body?.refused ?? [];
218
+ this.log.debug(`${count - refused.length} of ${count} events stored`);
219
+ for (const r of refused)
220
+ this.log.warn(`"${events[r.index]?.event ?? '?'}" was refused (${r.reason}): ${r.message ?? ''}`);
221
+ }
222
+ refused(status, detail, path, count) {
223
+ if (status === 401) {
224
+ this.log.warn('the ingest key was refused; check the key in Analytics → Settings. Nothing more is sent from this page.');
225
+ this.clear();
226
+ this.stop();
227
+ return;
228
+ }
229
+ if (status === 409 && path === 'identify') {
230
+ this.log.warn(`identify was refused: ${detail}`);
231
+ return;
232
+ }
233
+ this.log.warn(`${count} ${path === 'batch' ? 'events were' : path + ' request was'} refused (${status}): ${detail}`);
234
+ }
235
+ load() {
236
+ const text = this.store?.get(this.name);
237
+ if (!text)
238
+ return [];
239
+ try {
240
+ const jobs = JSON.parse(text);
241
+ return Array.isArray(jobs) ? jobs.filter((j) => j && (j.t === 'e' || j.t === 'i' || j.t === 'p')) : [];
242
+ }
243
+ catch {
244
+ return [];
245
+ }
246
+ }
247
+ save() {
248
+ if (!this.store)
249
+ return;
250
+ if (this.jobs.length === 0)
251
+ this.store.remove(this.name);
252
+ else
253
+ this.store.set(this.name, JSON.stringify(this.jobs));
254
+ }
255
+ }
@@ -0,0 +1,106 @@
1
+ /** What a property can hold: anything JSON can carry. A `Date` is sent as ISO 8601 text. */
2
+ export type PropertyValue = string | number | boolean | null | Date | PropertyValue[] | {
3
+ [key: string]: PropertyValue | undefined;
4
+ };
5
+ /** An event's or a person's properties. `undefined` values are left out. */
6
+ export type Properties = Record<string, PropertyValue | undefined>;
7
+ /**
8
+ * Where an event happened. Each one is a typed column in the Analytics hub, so a breakdown by browser
9
+ * or OS reads one small column instead of the event's properties.
10
+ */
11
+ export interface EventContext {
12
+ app_version?: string;
13
+ os?: string;
14
+ os_version?: string;
15
+ device_type?: string;
16
+ device_model?: string;
17
+ browser?: string;
18
+ locale?: string;
19
+ /** Every language the person prefers, in their order, comma-separated: `pl-PL,en-US`. */
20
+ languages?: string;
21
+ /** The device's time zone setting, IANA: `Europe/Warsaw`. */
22
+ timezone?: string;
23
+ /** The calendar the person's dates are written in: `gregory`, `buddhist`, `islamic`… */
24
+ calendar?: string;
25
+ /** The digits their numbers are written with: `latn`, `arab`… */
26
+ numbering_system?: string;
27
+ /** A 12- or 24-hour clock: `h12`, `h23`. */
28
+ hour_cycle?: string;
29
+ /** The screen, in CSS pixels. */
30
+ screen_width?: number;
31
+ screen_height?: number;
32
+ /** Device pixels to a CSS pixel: 2 on most phones and Retina screens. */
33
+ pixel_ratio?: number;
34
+ /** `light` or `dark`, as the person prefers. */
35
+ color_scheme?: string;
36
+ /** The connection as the browser rates it, where it says: `4g`, `3g`, `2g`, `slow-2g`. */
37
+ network?: string;
38
+ }
39
+ /**
40
+ * One event exactly as it is sent to `/analytics/v1/batch`, which is also what `beforeSend` is given.
41
+ * Field names are the API's.
42
+ */
43
+ export interface AnalyticsEvent {
44
+ event: string;
45
+ /** A UUID made for this event; a retry carries the same one, so the store keeps it once. */
46
+ event_id: string;
47
+ /** The browser's anonymous id, kept across visits until `reset()`. */
48
+ distinct_id: string;
49
+ /** Who signed in, once `identify()` has been called. */
50
+ user_id?: string;
51
+ /** ISO 8601, from the browser's clock. */
52
+ timestamp: string;
53
+ session_id: string;
54
+ properties: Record<string, unknown>;
55
+ context: EventContext;
56
+ }
57
+ /** Where the SDK keeps the anonymous id, the session, registered properties and the consent choice. */
58
+ export type Persistence = 'localStorage' | 'cookie' | 'memory';
59
+ export interface AnalyticsOptions {
60
+ /** The project's ingest key, `dak_…`, from Analytics → Settings. It is public: it only says which project events are for. */
61
+ key: string;
62
+ /** Where Daybook's API is. Only for a self-hosted Daybook or a proxy of your own. */
63
+ apiUrl?: string;
64
+ /** Your site's own version or build, kept as the `app_version` of every event. */
65
+ appVersion?: string;
66
+ /**
67
+ * Page views without a line of code: one on load and one on every navigation of a single-page app
68
+ * (History API and `#/` routes). On by default. Set `false` to call `page()` yourself — the Vue
69
+ * plugin does that when it is given the router.
70
+ */
71
+ autoPageviews?: boolean;
72
+ /** A `$pageleave`, with the time the page was open, when a page is left. On by default. */
73
+ pageleave?: boolean;
74
+ /**
75
+ * `localStorage` (the default) keeps the anonymous id per site. `cookie` shares it across
76
+ * subdomains — set `cookieDomain` to `.example.com` so `www.` and `app.` count one visitor. `memory`
77
+ * keeps nothing past the page: every page load is a new visitor.
78
+ */
79
+ persistence?: Persistence;
80
+ /** With `persistence: 'cookie'`: the domain the cookie is set for, such as `.example.com`. */
81
+ cookieDomain?: string;
82
+ /** Minutes without an event after which the next one starts a new session. 30 by default. */
83
+ sessionTimeoutMinutes?: number;
84
+ /** How long events wait to be sent together, in milliseconds. 2,000 by default. */
85
+ flushIntervalMs?: number;
86
+ /** Events per request, at most 1,000. 50 by default. */
87
+ batchSize?: number;
88
+ /** Properties sent with every event from the start, as `register()` would. */
89
+ properties?: Properties;
90
+ /**
91
+ * Send and store nothing until `optIn()` — for a site that asks for consent first. The anonymous id
92
+ * is not written to storage before then either.
93
+ */
94
+ optOutByDefault?: boolean;
95
+ /** Send nothing from a browser with Do Not Track or Global Privacy Control on, unless `optIn()` is called. */
96
+ respectDoNotTrack?: boolean;
97
+ /** Leave out browsers whose user agent says they are a crawler. On by default. */
98
+ ignoreBots?: boolean;
99
+ /**
100
+ * Sees every event just before it is queued. Return it (changed or not) to send it, or `null` to
101
+ * drop it — to take a token out of a URL, say.
102
+ */
103
+ beforeSend?: (event: AnalyticsEvent) => AnalyticsEvent | null | undefined | false;
104
+ /** Log what is sent and why anything is not. */
105
+ debug?: boolean;
106
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/uuid.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A random (v4) UUID. `crypto.randomUUID` exists only in a secure context, so a page served over
3
+ * plain http — a local dev server on a LAN address — falls back to `getRandomValues`, which does not.
4
+ */
5
+ export declare function uuid(): string;
package/dist/uuid.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A random (v4) UUID. `crypto.randomUUID` exists only in a secure context, so a page served over
3
+ * plain http — a local dev server on a LAN address — falls back to `getRandomValues`, which does not.
4
+ */
5
+ export function uuid() {
6
+ const c = globalThis.crypto;
7
+ if (typeof c?.randomUUID === 'function')
8
+ return c.randomUUID();
9
+ const b = new Uint8Array(16);
10
+ if (typeof c?.getRandomValues === 'function')
11
+ c.getRandomValues(b);
12
+ else
13
+ for (let i = 0; i < 16; i++)
14
+ b[i] = Math.floor(Math.random() * 256);
15
+ b[6] = (b[6] & 0x0f) | 0x40;
16
+ b[8] = (b[8] & 0x3f) | 0x80;
17
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
18
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
19
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This build's own version, sent as `$lib_version` on every event so a project can see which builds
3
+ * of the SDK its pages run. A constant rather than read from package.json at build time, because the
4
+ * npm build is plain tsc; test/version.test.js refuses a build where the two disagree.
5
+ */
6
+ export declare const SDK_VERSION = "0.3.0";
7
+ /**
8
+ * What the API records as every event's `source`, and one of the names it knows as a Daybook SDK
9
+ * (PM-T-0528): only those may send `$pageview` and `$pageleave`.
10
+ */
11
+ export declare const SDK_NAME = "js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This build's own version, sent as `$lib_version` on every event so a project can see which builds
3
+ * of the SDK its pages run. A constant rather than read from package.json at build time, because the
4
+ * npm build is plain tsc; test/version.test.js refuses a build where the two disagree.
5
+ */
6
+ export const SDK_VERSION = '0.3.0';
7
+ /**
8
+ * What the API records as every event's `source`, and one of the names it knows as a Daybook SDK
9
+ * (PM-T-0528): only those may send `$pageview` and `$pageleave`.
10
+ */
11
+ export const SDK_NAME = 'js';
package/dist/vue.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type App, type InjectionKey } from 'vue';
2
+ import { DaybookAnalytics } from './index.js';
3
+ import type { AnalyticsOptions } from './types.js';
4
+ export { DaybookAnalytics } from './index.js';
5
+ export type { AnalyticsEvent, AnalyticsOptions, Properties } from './index.js';
6
+ /** As much of Vue Router as page views need, so the package does not depend on it. */
7
+ export interface RouterLike {
8
+ afterEach(guard: (to: unknown, from: unknown, failure?: unknown) => unknown): () => void;
9
+ }
10
+ export interface VueAnalyticsOptions extends AnalyticsOptions {
11
+ /**
12
+ * The app's router. Page views then come from each finished navigation, after the new route's
13
+ * component has rendered, instead of from the History API.
14
+ */
15
+ router?: RouterLike;
16
+ }
17
+ export declare const AnalyticsKey: InjectionKey<DaybookAnalytics>;
18
+ /**
19
+ * Analytics for a Vue app (PM-R-0062 criterion 6):
20
+ *
21
+ * app.use(createAnalytics({ key: 'dak_…', router }))
22
+ *
23
+ * Then `useAnalytics()` in a component's setup, or `$daybook` in a template.
24
+ */
25
+ export declare function createAnalytics(options: VueAnalyticsOptions | {
26
+ client: DaybookAnalytics;
27
+ }): {
28
+ client: DaybookAnalytics;
29
+ install(app: App): void;
30
+ };
31
+ /** The app's analytics, in a component's setup. */
32
+ export declare function useAnalytics(): DaybookAnalytics;
33
+ declare module 'vue' {
34
+ interface ComponentCustomProperties {
35
+ $daybook: DaybookAnalytics;
36
+ }
37
+ }
package/dist/vue.js ADDED
@@ -0,0 +1,47 @@
1
+ import { inject, nextTick } from 'vue';
2
+ import { DaybookAnalytics, init } from './index.js';
3
+ export { DaybookAnalytics } from './index.js';
4
+ export const AnalyticsKey = Symbol('daybook-analytics');
5
+ /**
6
+ * Analytics for a Vue app (PM-R-0062 criterion 6):
7
+ *
8
+ * app.use(createAnalytics({ key: 'dak_…', router }))
9
+ *
10
+ * Then `useAnalytics()` in a component's setup, or `$daybook` in a template.
11
+ */
12
+ export function createAnalytics(options) {
13
+ const client = 'client' in options ? options.client : start(options);
14
+ return {
15
+ client,
16
+ install(app) {
17
+ app.provide(AnalyticsKey, client);
18
+ app.config.globalProperties.$daybook = client;
19
+ },
20
+ };
21
+ }
22
+ function start({ router, ...options }) {
23
+ if (!router)
24
+ return init(options);
25
+ const client = init({ ...options, autoPageviews: false });
26
+ // A failed or cancelled navigation is not a page view, and neither is one that only changed the
27
+ // query or the hash of the same route. nextTick: the route's component and any title it sets are on
28
+ // the page by then.
29
+ let last = null;
30
+ router.afterEach((to, _from, failure) => {
31
+ if (failure)
32
+ return;
33
+ const path = to?.path ?? null;
34
+ if (path !== null && path === last)
35
+ return;
36
+ last = path;
37
+ void nextTick(() => client.page());
38
+ });
39
+ return client;
40
+ }
41
+ /** The app's analytics, in a component's setup. */
42
+ export function useAnalytics() {
43
+ const client = inject(AnalyticsKey, null);
44
+ if (!client)
45
+ throw new Error('@daybook/analytics/vue: useAnalytics needs app.use(createAnalytics({ key })) first.');
46
+ return client;
47
+ }