@kk-forge/artel-collector 0.6.1 → 0.8.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/README.md +43 -7
- package/dist/infra/desktop.d.ts +1 -1
- package/dist/infra/desktop.js +2 -1
- package/dist/infra/exports.d.ts +1 -1
- package/dist/infra/exports.js +1 -1
- package/dist/infra/web.d.ts +20 -3
- package/dist/infra/web.js +57 -10
- package/dist/shared/collector.js +4 -1
- package/dist/shared/outbox.js +7 -3
- package/dist/shared/page.d.ts +11 -1
- package/dist/shared/page.js +28 -6
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -130,7 +130,7 @@ Each constructor throws a `TypeError` that names the option when the options wou
|
|
|
130
130
|
|
|
131
131
|
- `lock`: a function that takes an async operation, runs it while no other context that shares `storage` runs one, and resolves or rejects as the operation does. It must run the operation exactly once and hold the lock until the operation's promise settles, as `navigator.locks.request` does. The collector never asks for it while it holds it. The collector runs each method, and each queue change of a send, under it. Without it, two contexts recording at once may both mark the first event of a day, overwrite each other's queued events or send one envelope twice. The rule that no event goes under another user's id then holds only within one context, and so does the opt-out: an event another context records during `setState('opted_out')` may still leave. Each collector runs one of its own operations at a time with or without a lock.
|
|
132
132
|
- `sessionIdleMinutes`: minutes without events that end a session, 10 by default. A value that is not a finite number from 0 takes the default, and so does one of `sendDelaySeconds`.
|
|
133
|
-
- `sendDelaySeconds`: the longest an event waits in the queue before a send starts, 5 by default.
|
|
133
|
+
- `sendDelaySeconds`: the longest an event waits in the queue before a send starts, 5 by default. A collector's first event does not wait, as "Sending" describes.
|
|
134
134
|
- `clock`: time and timers, the host's own by default. Tests pass a fake. A `Clock` has `now()`, which returns milliseconds since the epoch, and `setTimeout(callback, delayMs)`, which returns the function that cancels that timer. A cancel after the timer ran does nothing. The port names no timer handle, whose type is a number in the DOM typings and an object in the Node ones. A clock written for 0.4 drops `clearTimeout` and returns the cancel from `setTimeout` instead, and `TimerHandle` is no longer exported.
|
|
135
135
|
- `onError`: receives each failure the collector does not retry. An `onError` that throws is ignored. A report quotes at most 64 characters of host or stored text, and never a page. It receives:
|
|
136
136
|
- an event `track` refuses;
|
|
@@ -168,7 +168,7 @@ Every method returns a promise that resolves and never rejects. A failure goes t
|
|
|
168
168
|
- From `pseudonymous` or `identified`, to any other state: forgets the last id, as `forget(id)` does, and drops the queued events of that state, those waiting for an id included. A change between `pseudonymous` and `identified` thus counts as another user. The collector also deletes the install id when the user leaves `pseudonymous`. A change to a state without an id stores the state first. A run that stops after that forgets the last id on the first call of its next run. A change between `pseudonymous` and `identified` forgets the last id first, so a run that stops in between keeps the old state with its id forgotten.
|
|
169
169
|
- A state above the channel's mode is refused: a type error, and `onError` in untyped code.
|
|
170
170
|
- `getState()` resolves to the stored state, `anonymous` until the user chose. It also resolves to `anonymous` when the storage fails, whatever the user chose, and reports the failure. On the first call of any method, a stored state above the channel's mode becomes `anonymous`, as `setState('anonymous')` would make it, as after the admin lowered the mode.
|
|
171
|
-
- `flush()` sends what is queued now and resolves once that send ends. While the wait after a failed request runs, it schedules the send for the end of the wait instead. The collector sends within `sendDelaySeconds` without it, as "Sending" describes
|
|
171
|
+
- `flush()` sends what is queued now and resolves once that send ends. While the wait after a failed request runs, it schedules the send for the end of the wait instead. The collector sends within `sendDelaySeconds` without it, and the web and desktop collectors flush when the page turns hidden, as "Sending" describes. So `flush()` is only for a product that wants to send sooner.
|
|
172
172
|
- `forget(id)` drops the queued events of this id and asks the intake to delete the id's events, with `{ key, id }` to its `/v1/public/forget`. The product calls it for an account id the collector does not hold, such as one `getId` no longer gives. Leaving a state with an id does the same for the last id by itself. An `id` that is not a string of 1 to 64 characters, which the intake refuses, is reported and drops nothing. When this id is the last one `getId` gave, it also drops the events that wait for an id. The next id `getId` gives then counts as another user, so the events that waited after the forget never go under it. The collector stores the request until the intake answers it, and sends it after this collector's request in flight, which may carry the id, and before the queued envelopes. It resolves once that send ends. A forget answered 0, 429 or 5xx goes again under the wait rules of "Sending", and any other status outside 2xx drops it and reports it. The intake checks the request's `Origin` as it checks a relay request. With a test key the collector forgets the id and drops its events here but sends no request and reports nothing: the intake answers a test key's forget 403, since it would delete the user's live events too, and test events go when the channel's test data is cleared. The collector stores only the ids of its forget requests, and sends each with its own key. It drops a stored id that is not 1 to 64 characters unsent. The intake deletes the id's events in every channel of the product within a minute, and those that arrive up to a minute after the forget. A request another context sent arrives within its 30-second limit.
|
|
173
173
|
- `uninstallParams()` resolves to the query of an uninstall page. It resolves to `undefined` in the `opted_out` state, and when the storage fails. The query is `{ platform, version, browser_language, ui_language, age_days, active_days }`, each shaped by the state as an envelope is. `age_days` is days since install, and `active_days` the bucket of active days, the local days whose first event is queued or sent: `0`, `1`, `2-5`, `6-20` or `21+`, the values of `ActiveDaysBucket`. The uninstall page that `uninstallPage` sets carries the values of its last refresh. The extension's collector refreshes it after it queues the first event of a local day, such as `installed` on the install day, so `active_days` includes that day. A day leaves the count when the event that took its first-of-day mark gives its marks back, as "Sending" describes. The next event of that day counts it again. The uninstall page is a page of the product's site. It sends `uninstalled` from its own `site` channel, with the params `age_days`, as a JSON number, and `active_days`. `track('uninstalled')` sends `age_days` shaped by the state as `uninstallParams()` gives it. The `platform`, `version` and languages in the query are for the page itself and are not params of the event.
|
|
174
174
|
|
|
@@ -180,9 +180,9 @@ Every method returns a promise that resolves and never rejects. A failure goes t
|
|
|
180
180
|
|
|
181
181
|
## Sending
|
|
182
182
|
|
|
183
|
-
The collector writes each event to the queue in storage at once.
|
|
183
|
+
The collector writes each event to the queue in storage at once. The first event a collector queues goes at once, so a page closed a second after its load has its `page_view` on the way. After that, a send starts at most `sendDelaySeconds` after the first event waiting, so the events of those seconds share one request. An envelope of 100 events goes at once. An event that would take an envelope past 60 kB starts a new one.
|
|
184
184
|
|
|
185
|
-
The queue lives in storage, so every event outlives the page that recorded it. A page or a window that closes within the send delay after its last events leaves them queued. A later visit or launch sends them. A collector that finds events or forget requests stored when it is built sends them within the send delay, or after any retry wait, without waiting for a call. In the `opted_out` state it drops the stored events but a queued `opted_out`, and sends that and the forget requests. The
|
|
185
|
+
The queue lives in storage, so every event outlives the page that recorded it. A page or a window that closes within the send delay after its last events leaves them queued. A later visit or launch sends them. A collector that finds events or forget requests stored when it is built sends them within the send delay, or after any retry wait, without waiting for a call. In the `opted_out` state it drops the stored events but a queued `opted_out`, and sends that and the forget requests. The web and desktop collectors flush each time the page or window turns hidden, as on a switch to another tab or app, or when the window is minimized. The page lives on then, so that send ends, even on a mobile browser that freezes a hidden page soon after. A page that closes or navigates away also turns hidden, but its flush does not get to its request: a send reads the storage and takes the lock first, and the closing page runs nothing after that. So events queued within the send delay before a close, and the first event of a page closed before its request started, wait in storage and go with the next visit or launch. None is lost. In an extension, the service worker sends what its pages queue, even after a page closed. It listens to `chrome.storage.onChanged` for the channel's queue and sends within the send delay of the page's write. A page still sends on its own as well, and the leases keep an envelope from going twice.
|
|
186
186
|
|
|
187
187
|
An envelope leaves the queue once the intake answered it, or by a drop rule, so a host stopped at any point keeps its queued events. Its next run sends the queue. A context that sends an envelope holds a one-minute lease on it and renews the lease before each request, so no other context sends it at the same time. An envelope whose sender stopped goes with the first send after that lease runs out. A lease that ends more than a minute ahead, as after the clock was set back, counts as run out. A failed request ends the lease, so the first send of any context after the retry wait below takes the envelope. Each envelope carries a `batch` key, and every attempt sends the body of the first attempt byte for byte. Events tracked after the first attempt go into a new envelope. The intake drops a repeat of an envelope it stored in the last 72 hours. The collector stops repeating an envelope within that time, by the rule for old events below. A 503 can also come back after the intake wrote part of an envelope. The intake catches the repeat of such an envelope only while it remembers that write among its last 10 000 inserts. Past that, part of the envelope is stored twice.
|
|
188
188
|
|
|
@@ -219,11 +219,12 @@ An extension imports `infra/chrome` only in its entrypoints, the scripts that st
|
|
|
219
219
|
|
|
220
220
|
`@kk-forge/artel-collector/infra` exports the code for a website or a web app. The desktop collector uses the same storage adapter and lock.
|
|
221
221
|
|
|
222
|
-
- `newWebCollector(options)` makes a collector for a website or a web app, as in "Usage".
|
|
222
|
+
- `newWebCollector(options)` makes a collector for a website or a web app, as in "Usage". It sends what is queued each time the page turns hidden, as "Sending" describes.
|
|
223
223
|
- `newLocalStorageAdapter()` returns a `storage` over `localStorage`. Every script of the origin can read it, the queued events with their `id`, the last id and the install id included, and no other storage of the origin hides them from its scripts. A site that runs untrusted scripts uses an anonymous channel.
|
|
224
224
|
- `newWebLock()` returns a `lock` over the Web Lock named `artel`, shared by the tabs and workers of one origin. Without Web Locks, operations run unguarded.
|
|
225
225
|
- `pageFields()` gives the page's address without its query string and fragment, and `document.referrer`. `newWebCollector`'s default `getPage` takes it, and the collector shapes both as "Options" describes under `getPage`.
|
|
226
|
-
- `trackPageViews(collector)` sends `page_view` for the page now and for each later navigation: `history.pushState` and `replaceState`, `popstate`, and the Navigation API's `currententrychange` where the browser has it.
|
|
226
|
+
- `trackPageViews(collector)` sends `page_view` for the page now and for each later navigation: `history.pushState` and `replaceState`, `popstate`, `hashchange`, and the Navigation API's `currententrychange` where the browser has it. By the HTML standard a change of the hash, from a link or from setting `location.hash`, fires `popstate` and then `hashchange`. The tracker listens to `hashchange` as well, for a browser that skips the `popstate`. A navigation sends a `page_view` only when it leads to another page, the page the collector would send, as `getPage` gives it. So a navigation that several of these events report sends one. With the default `getPage` the page is the path, so a change of the query or the hash alone sends none. A router that keeps its routes in the hash passes a `getPage` that reads the route from the hash, as below, and gets a `page_view` for each route. Where the collector reads no page, as on another platform than `web`, or `getPage` gives none, the page is `location.pathname`. The trackers of one collector and its calls of `trackPageView` share the last page, so two trackers send one `page_view` per navigation, and a navigation back to the page a call left sends one. They count a page whether or not the collector records its `page_view`, so a page loaded in the `opted_out` state sends a `page_view` at the first navigation to another page after the user leaves that state. A tracker sends the page it starts on even when another tracker of the collector counted it, and the collector drops it if its last recorded `page_view` sent that page. To read the page, the tracker calls `getPage` at each of these events, and `trackPageView` calls it once more than the `page_view` itself does. Leaving `opted_out` sends none by itself. `page_view` is a system event, which the intake counts without the product's allowlist. It returns the function that stops it. Once every tracker stopped, in any order, `history` is as they found it: a method the page inherited from `History.prototype` is inherited again. A product that wraps a method after the tracker keeps its wrapper, and the stopped tracker's wrapper under it stays and only passes calls on.
|
|
227
|
+
- `trackPageView(collector)` sends `page_view` for the page `getPage` gives now, unless the last recorded `page_view` sent that page, whether a navigation or a call sent it. A router that changes the screen without changing the address calls it after each change, with a `getPage` that reads the screen. So does a product that decides itself when a view counts. It works with or without `trackPageViews`. It resolves once the collector queued or dropped the event, and never rejects.
|
|
227
228
|
|
|
228
229
|
`newWebCollector` needs `localStorage`, which a Web Worker lacks, so a worker passes its own `storage`. Its default `getPage` sends no page where there is no `document` or `location`.
|
|
229
230
|
|
|
@@ -236,6 +237,41 @@ const analytics = newWebCollector({ key, version, endpoint, mode: "anonymous" })
|
|
|
236
237
|
trackPageViews(analytics);
|
|
237
238
|
```
|
|
238
239
|
|
|
240
|
+
A web app that keeps its routes in the hash, such as `#/ideas/123`, sends its route pattern as the page. The pattern has `:id` in place of the record's number and leaves out the query, so a move between records of one route sends no `page_view`. A hash can carry a secret, as an OAuth redirect's `#access_token=…` does, so this `getPage` sends only the routes in its list and `/other` for any other hash:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
const routes = new Set(["/", "/ideas", "/ideas/:id", "/projects", "/projects/:id"]);
|
|
244
|
+
|
|
245
|
+
function routeOf(hash: string): string {
|
|
246
|
+
const route = `/${hash.replace(/^#\/?/, "").split("?")[0] ?? ""}`.replaceAll(/\/\d+/g, "/:id");
|
|
247
|
+
return routes.has(route) ? route : "/other";
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const analytics = newWebCollector({
|
|
251
|
+
key,
|
|
252
|
+
version,
|
|
253
|
+
endpoint,
|
|
254
|
+
mode: "anonymous",
|
|
255
|
+
getPage: () => ({ page: routeOf(location.hash), referrer: document.referrer }),
|
|
256
|
+
});
|
|
257
|
+
trackPageViews(analytics);
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
A web app that changes its screen without changing the address reads the screen in `getPage` and calls `trackPageView` after each change:
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
import { newWebCollector, trackPageView } from "@kk-forge/artel-collector/infra";
|
|
264
|
+
|
|
265
|
+
const analytics = newWebCollector({
|
|
266
|
+
key,
|
|
267
|
+
version,
|
|
268
|
+
endpoint,
|
|
269
|
+
mode: "anonymous",
|
|
270
|
+
getPage: () => ({ page: `/${router.screen}`, referrer: document.referrer }),
|
|
271
|
+
});
|
|
272
|
+
router.afterEach(() => trackPageView(analytics));
|
|
273
|
+
```
|
|
274
|
+
|
|
239
275
|
### Chrome extension
|
|
240
276
|
|
|
241
277
|
`@kk-forge/artel-collector/infra/chrome` exports the code for a Chrome extension. The extension's service worker and its pages each make a collector with `newExtensionCollector`. They share `chrome.storage.local` and Web Locks, so they keep one queue and one state.
|
|
@@ -270,7 +306,7 @@ void analytics.track("link_shared", { target: "clipboard" });
|
|
|
270
306
|
|
|
271
307
|
`@kk-forge/artel-collector/infra` exports the code for a window of a desktop app, such as a Tauri webview.
|
|
272
308
|
|
|
273
|
-
- `newDesktopCollector(options)` makes a collector for a desktop window, as in "Usage". It takes `platform` as `'macos'`, `'windows'` or `'linux'`, the platforms a `desktop` channel takes. Its windows share the webview's `localStorage` through `newLocalStorageAdapter()` and its Web Locks through `newWebLock()`, so they keep one queue and one state. It sends `installed` and `updated` when it is built, each only when due, so every window may build one. Events of the last seconds before the app closes go at its next launch, as "Sending" describes. It names no browser and sends no page.
|
|
309
|
+
- `newDesktopCollector(options)` makes a collector for a desktop window, as in "Usage". It takes `platform` as `'macos'`, `'windows'` or `'linux'`, the platforms a `desktop` channel takes. Its windows share the webview's `localStorage` through `newLocalStorageAdapter()` and its Web Locks through `newWebLock()`, so they keep one queue and one state. It sends `installed` and `updated` when it is built, each only when due, so every window may build one. It sends what is queued when the window turns hidden. Events of the last seconds before the app closes go at its next launch, as "Sending" describes. It names no browser and sends no page.
|
|
274
310
|
|
|
275
311
|
## What is sent
|
|
276
312
|
|
package/dist/infra/desktop.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export type DesktopCollectorOptions = Omit<CommonOptions, "storage"> & {
|
|
|
19
19
|
* Returns a collector for a window of a desktop app, such as a Tauri webview. Its windows share the webview's
|
|
20
20
|
* `localStorage` and Web Locks, so they keep one queue and one state. It sends the user's language from
|
|
21
21
|
* `navigator.language`. The app passes its own `uiLanguage`. It sends `installed` and `updated` itself when they are
|
|
22
|
-
* due.
|
|
22
|
+
* due, and sends what is queued each time the window turns hidden, as `flushWhenHidden` in `src/infra/web.ts` describes.
|
|
23
23
|
*/
|
|
24
24
|
export declare function newDesktopCollector<M extends Mode>(options: DesktopCollectorOptions & {
|
|
25
25
|
mode: M;
|
package/dist/infra/desktop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { newCollector } from "./systemCollector.js";
|
|
2
|
-
import { newLocalStorageAdapter, newWebLock } from "./web.js";
|
|
2
|
+
import { flushWhenHidden, newLocalStorageAdapter, newWebLock } from "./web.js";
|
|
3
3
|
export function newDesktopCollector(options) {
|
|
4
4
|
const collector = newCollector({
|
|
5
5
|
...options,
|
|
@@ -11,5 +11,6 @@ export function newDesktopCollector(options) {
|
|
|
11
11
|
// lock, so every window may build a collector. The collector runs its calls in this order.
|
|
12
12
|
void collector.installed();
|
|
13
13
|
void collector.updated();
|
|
14
|
+
flushWhenHidden(collector);
|
|
14
15
|
return collector;
|
|
15
16
|
}
|
package/dist/infra/exports.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { newCollector, newHttpTransport } from "./systemCollector.js";
|
|
2
2
|
export { systemClock } from "./system.js";
|
|
3
|
-
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageViews, type WebCollectorOptions, } from "./web.js";
|
|
3
|
+
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageView, trackPageViews, type WebCollectorOptions, } from "./web.js";
|
|
4
4
|
export { newDesktopCollector, type DesktopCollectorOptions } from "./desktop.js";
|
package/dist/infra/exports.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { newCollector, newHttpTransport } from "./systemCollector.js";
|
|
2
2
|
export { systemClock } from "./system.js";
|
|
3
|
-
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageViews, } from "./web.js";
|
|
3
|
+
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageView, trackPageViews, } from "./web.js";
|
|
4
4
|
export { newDesktopCollector } from "./desktop.js";
|
package/dist/infra/web.d.ts
CHANGED
|
@@ -11,11 +11,19 @@ export type WebCollectorOptions = Omit<CommonOptions, "storage"> & {
|
|
|
11
11
|
/**
|
|
12
12
|
* Returns a collector for a website or a web app. It runs over `localStorage` and Web Locks, and sends the user's
|
|
13
13
|
* language from `navigator.language`, the page from `pageFields` and, in a state with an id, the browser from
|
|
14
|
-
* `detectBrowser`.
|
|
14
|
+
* `detectBrowser`. It sends what is queued each time the page turns hidden, as `flushWhenHidden` describes. The site
|
|
15
|
+
* passes its own `uiLanguage`. A desktop window uses `newDesktopCollector`.
|
|
15
16
|
*/
|
|
16
17
|
export declare function newWebCollector<M extends Mode>(options: WebCollectorOptions & {
|
|
17
18
|
mode: M;
|
|
18
19
|
}): Collector<M>;
|
|
20
|
+
/**
|
|
21
|
+
* Flushes `collector` each time the document turns hidden, as when the user switches to another tab or app or
|
|
22
|
+
* minimizes the window. The page lives on then, so the send ends, and a mobile browser that freezes a hidden page soon
|
|
23
|
+
* after finds the queue sent. A page that closes or navigates away gets no further than the lock, so its events wait
|
|
24
|
+
* for the next visit. A Web Worker has no document, so the function does nothing there.
|
|
25
|
+
*/
|
|
26
|
+
export declare function flushWhenHidden(collector: Collector): void;
|
|
19
27
|
/**
|
|
20
28
|
* Returns a storage adapter over `localStorage`, which every tab of the origin shares. A Web Worker has no
|
|
21
29
|
* `localStorage`, so a collector there passes its own storage.
|
|
@@ -33,7 +41,16 @@ export declare function newWebLock(): Lock;
|
|
|
33
41
|
*/
|
|
34
42
|
export declare function pageFields(): PageFields;
|
|
35
43
|
/**
|
|
36
|
-
* Sends `page_view` for the current page and after each navigation
|
|
37
|
-
*
|
|
44
|
+
* Sends `page_view` for the current page and after each navigation to another page, and returns the function that
|
|
45
|
+
* stops it. The page is the one the collector would send, as its `getPage` gives it: with the default `getPage` the
|
|
46
|
+
* path, so a change of the query or the hash alone sends none, and with a `getPage` that reads a route from the hash, the
|
|
47
|
+
* route. Where the collector reads no page, as on another platform than web, or `getPage` gives none, the page is
|
|
48
|
+
* `location.pathname`. Once every tracker stops, `history` is as they found it.
|
|
38
49
|
*/
|
|
39
50
|
export declare function trackPageViews(collector: Collector): () => void;
|
|
51
|
+
/**
|
|
52
|
+
* Sends `page_view` for the page `getPage` gives now, unless the last recorded `page_view` sent that page. A router
|
|
53
|
+
* that changes the screen without changing the address calls it after each change, with a `getPage` that reads the
|
|
54
|
+
* screen. It resolves once the collector has queued or dropped the event, and never rejects.
|
|
55
|
+
*/
|
|
56
|
+
export declare function trackPageView(collector: Collector): Promise<void>;
|
package/dist/infra/web.js
CHANGED
|
@@ -2,6 +2,7 @@ import { detectBrowser } from "../shared/browser.js";
|
|
|
2
2
|
import { newCollector } from "./systemCollector.js";
|
|
3
3
|
import { Mode, } from "../shared/collectorTypes.js";
|
|
4
4
|
import { PAGE_VIEW, Platform } from "../shared/envelope.js";
|
|
5
|
+
import { currentPage } from "../shared/page.js";
|
|
5
6
|
export function newWebCollector(options) {
|
|
6
7
|
const defaults = {
|
|
7
8
|
platform: Platform.Web,
|
|
@@ -10,13 +11,31 @@ export function newWebCollector(options) {
|
|
|
10
11
|
browserLanguage: options.browserLanguage ?? navigator.language,
|
|
11
12
|
getPage: options.getPage ?? pageFieldsWherePageIs,
|
|
12
13
|
};
|
|
13
|
-
|
|
14
|
+
const collector = options.mode === Mode.Anonymous
|
|
14
15
|
? newCollector({ ...options, ...defaults })
|
|
15
16
|
: newCollector({
|
|
16
17
|
...options,
|
|
17
18
|
...defaults,
|
|
18
19
|
browser: options.browser ?? (() => detectBrowser(navigator)),
|
|
19
20
|
});
|
|
21
|
+
flushWhenHidden(collector);
|
|
22
|
+
return collector;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Flushes `collector` each time the document turns hidden, as when the user switches to another tab or app or
|
|
26
|
+
* minimizes the window. The page lives on then, so the send ends, and a mobile browser that freezes a hidden page soon
|
|
27
|
+
* after finds the queue sent. A page that closes or navigates away gets no further than the lock, so its events wait
|
|
28
|
+
* for the next visit. A Web Worker has no document, so the function does nothing there.
|
|
29
|
+
*/
|
|
30
|
+
export function flushWhenHidden(collector) {
|
|
31
|
+
if (typeof document === "undefined") {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
document.addEventListener("visibilitychange", () => {
|
|
35
|
+
if (document.visibilityState === "hidden") {
|
|
36
|
+
void collector.flush();
|
|
37
|
+
}
|
|
38
|
+
});
|
|
20
39
|
}
|
|
21
40
|
/**
|
|
22
41
|
* Returns a storage adapter over `localStorage`, which every tab of the origin shares. A Web Worker has no
|
|
@@ -59,32 +78,60 @@ function pageFieldsWherePageIs() {
|
|
|
59
78
|
: pageFields();
|
|
60
79
|
}
|
|
61
80
|
/**
|
|
62
|
-
* Sends `page_view` for the current page and after each navigation
|
|
63
|
-
*
|
|
81
|
+
* Sends `page_view` for the current page and after each navigation to another page, and returns the function that
|
|
82
|
+
* stops it. The page is the one the collector would send, as its `getPage` gives it: with the default `getPage` the
|
|
83
|
+
* path, so a change of the query or the hash alone sends none, and with a `getPage` that reads a route from the hash, the
|
|
84
|
+
* route. Where the collector reads no page, as on another platform than web, or `getPage` gives none, the page is
|
|
85
|
+
* `location.pathname`. Once every tracker stops, `history` is as they found it.
|
|
64
86
|
*/
|
|
65
87
|
export function trackPageViews(collector) {
|
|
66
|
-
let lastPath;
|
|
67
88
|
const onNavigation = () => {
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
|
|
89
|
+
// One navigation can reach the tracker up to three times: as a `pushState` and a `currententrychange`, or as a
|
|
90
|
+
// `popstate`, a `hashchange` and a `currententrychange`. All of them find the same page.
|
|
91
|
+
if (pageNow(collector) !== trackedPages.get(collector)) {
|
|
92
|
+
void trackPageView(collector);
|
|
71
93
|
}
|
|
72
|
-
lastPath = location.pathname;
|
|
73
|
-
void collector.track(PAGE_VIEW);
|
|
74
94
|
};
|
|
75
95
|
const unwrapPushState = callAfter("pushState", onNavigation);
|
|
76
96
|
const unwrapReplaceState = callAfter("replaceState", onNavigation);
|
|
97
|
+
// By the HTML standard, a browser reports a change of the hash as a `popstate` and then a `hashchange`. The tracker
|
|
98
|
+
// listens to `hashchange` as well, so a change still counts in a browser that skips the `popstate`.
|
|
77
99
|
window.addEventListener("popstate", onNavigation);
|
|
100
|
+
window.addEventListener("hashchange", onNavigation);
|
|
78
101
|
const navigation = navigationApi();
|
|
79
102
|
navigation?.addEventListener("currententrychange", onNavigation);
|
|
80
|
-
|
|
103
|
+
// The page it starts on counts even when an earlier tracker of the collector counted it, as one stopped and started
|
|
104
|
+
// again after the user left `opted_out`. The collector drops it if its last recorded `page_view` sent that page.
|
|
105
|
+
void trackPageView(collector);
|
|
81
106
|
return () => {
|
|
82
107
|
unwrapPushState();
|
|
83
108
|
unwrapReplaceState();
|
|
84
109
|
window.removeEventListener("popstate", onNavigation);
|
|
110
|
+
window.removeEventListener("hashchange", onNavigation);
|
|
85
111
|
navigation?.removeEventListener("currententrychange", onNavigation);
|
|
86
112
|
};
|
|
87
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Sends `page_view` for the page `getPage` gives now, unless the last recorded `page_view` sent that page. A router
|
|
116
|
+
* that changes the screen without changing the address calls it after each change, with a `getPage` that reads the
|
|
117
|
+
* screen. It resolves once the collector has queued or dropped the event, and never rejects.
|
|
118
|
+
*/
|
|
119
|
+
export function trackPageView(collector) {
|
|
120
|
+
trackedPages.set(collector, pageNow(collector));
|
|
121
|
+
return collector.track(PAGE_VIEW);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* The page of the last `page_view` each collector was asked for, whether or not it recorded one. The trackers of a
|
|
125
|
+
* collector and its calls of `trackPageView` share it, so a navigation back to a page after a call counts.
|
|
126
|
+
*/
|
|
127
|
+
const trackedPages = new WeakMap();
|
|
128
|
+
/**
|
|
129
|
+
* Returns the page a `page_view` of `collector` would send now, or `location.pathname` where it reads none, or
|
|
130
|
+
* undefined where there is no `location`.
|
|
131
|
+
*/
|
|
132
|
+
function pageNow(collector) {
|
|
133
|
+
return (currentPage(collector) ?? (typeof location === "undefined" ? undefined : location.pathname));
|
|
134
|
+
}
|
|
88
135
|
/** The wrappers `callAfter` installed, by the wrapper function. */
|
|
89
136
|
const wrappings = new WeakMap();
|
|
90
137
|
/**
|
package/dist/shared/collector.js
CHANGED
|
@@ -8,7 +8,7 @@ import { acceptedEvent } from "./eventCheck.js";
|
|
|
8
8
|
import { newInstallState } from "./installState.js";
|
|
9
9
|
import { exclusive } from "./lock.js";
|
|
10
10
|
import { newOutbox } from "./outbox.js";
|
|
11
|
-
import { newPageReader } from "./page.js";
|
|
11
|
+
import { newPageReader, notePageReader } from "./page.js";
|
|
12
12
|
import { carriesPage, channelTakes, fieldsForState, isAnalyticsState, } from "./stateFields.js";
|
|
13
13
|
import { newThrottle } from "./throttle.js";
|
|
14
14
|
import { transportsOf } from "./transport.js";
|
|
@@ -375,6 +375,9 @@ export function newCollectorOn({ host, options, onNewDay, }) {
|
|
|
375
375
|
};
|
|
376
376
|
}, undefined),
|
|
377
377
|
};
|
|
378
|
+
if (pages !== undefined) {
|
|
379
|
+
notePageReader(collector, pages);
|
|
380
|
+
}
|
|
378
381
|
void sendWhatIsLeft();
|
|
379
382
|
return collector;
|
|
380
383
|
}
|
package/dist/shared/outbox.js
CHANGED
|
@@ -31,6 +31,8 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
31
31
|
/** Cancels the timer of the pending retry. Set only while a retry is pending. */
|
|
32
32
|
let cancelRetryTimer;
|
|
33
33
|
let retryDelay = RETRY_DELAY_MS;
|
|
34
|
+
/** Whether this outbox queued an event yet. */
|
|
35
|
+
let hasAdded = false;
|
|
34
36
|
/** Chains the sends, so that one runs at a time and queued envelopes leave in the order they were made. */
|
|
35
37
|
let sending = Promise.resolve();
|
|
36
38
|
function reportDropped(count) {
|
|
@@ -227,9 +229,11 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
227
229
|
return {
|
|
228
230
|
add: async (fields, event, options) => {
|
|
229
231
|
const { isFull, dropped } = await queue.add(fields, event, options);
|
|
230
|
-
// A full envelope goes at once
|
|
231
|
-
// request.
|
|
232
|
-
|
|
232
|
+
// A full envelope goes at once, and so does the first event of this outbox, so that a page closed within the
|
|
233
|
+
// send delay of its load has its request on the way. Otherwise the send waits, so that the events of the next few
|
|
234
|
+
// seconds share one request.
|
|
235
|
+
sendWithin(isFull || !hasAdded ? 0 : sendDelayMs);
|
|
236
|
+
hasAdded = true;
|
|
233
237
|
return dropped;
|
|
234
238
|
},
|
|
235
239
|
sendSoon: () => sendWithin(sendDelayMs),
|
package/dist/shared/page.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageFields } from "./collectorTypes.js";
|
|
1
|
+
import type { Collector, PageFields } from "./collectorTypes.js";
|
|
2
2
|
/** What `getPage` gave when a method was called, shaped as the collector sends it. */
|
|
3
3
|
export interface PageRead {
|
|
4
4
|
name: string;
|
|
@@ -17,7 +17,17 @@ interface PageView {
|
|
|
17
17
|
export interface PageReader {
|
|
18
18
|
read(name: string): PageRead;
|
|
19
19
|
view(read: PageRead): PageView;
|
|
20
|
+
/** Returns the page a `page_view` would send now, or undefined for none. It reports nothing: the event reports it. */
|
|
21
|
+
pageNow(): string | undefined;
|
|
20
22
|
}
|
|
23
|
+
/** Notes `reader` as the page reader of `collector`, for `currentPage`. */
|
|
24
|
+
export declare function notePageReader(collector: Collector, reader: PageReader): void;
|
|
25
|
+
/**
|
|
26
|
+
* Returns the page a `page_view` of `collector` would send now, as its `getPage` gives it. It returns undefined for a
|
|
27
|
+
* collector that reads no page, as one of another platform than web or a product's own `Collector`, and where `getPage`
|
|
28
|
+
* gives no page it can read.
|
|
29
|
+
*/
|
|
30
|
+
export declare function currentPage(collector: Collector): string | undefined;
|
|
21
31
|
/**
|
|
22
32
|
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
23
33
|
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
package/dist/shared/page.js
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
import { PAGE_VIEW } from "./envelope.js";
|
|
2
2
|
import { pagePath, referrerHost } from "./pagePath.js";
|
|
3
|
+
/** The page reader of each collector that reads pages, for `currentPage`. */
|
|
4
|
+
const readers = new WeakMap();
|
|
5
|
+
/** Notes `reader` as the page reader of `collector`, for `currentPage`. */
|
|
6
|
+
export function notePageReader(collector, reader) {
|
|
7
|
+
readers.set(collector, reader);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Returns the page a `page_view` of `collector` would send now, as its `getPage` gives it. It returns undefined for a
|
|
11
|
+
* collector that reads no page, as one of another platform than web or a product's own `Collector`, and where `getPage`
|
|
12
|
+
* gives no page it can read.
|
|
13
|
+
*/
|
|
14
|
+
export function currentPage(collector) {
|
|
15
|
+
return readers.get(collector)?.pageNow();
|
|
16
|
+
}
|
|
3
17
|
/**
|
|
4
18
|
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
5
19
|
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
|
@@ -8,15 +22,15 @@ import { pagePath, referrerHost } from "./pagePath.js";
|
|
|
8
22
|
export function newPageReader({ getPage, reportError, }) {
|
|
9
23
|
let isPageViewRecorded = false;
|
|
10
24
|
let lastViewedPage;
|
|
11
|
-
function fieldsOf(name, mayCarryReferrer) {
|
|
25
|
+
function fieldsOf({ name, mayCarryReferrer, report, }) {
|
|
12
26
|
// A host outside TypeScript can return any value, or fields whose getters throw.
|
|
13
27
|
try {
|
|
14
28
|
const fields = getPage?.(name);
|
|
15
|
-
const page = stringField("page", fields?.page,
|
|
29
|
+
const page = stringField("page", fields?.page, report);
|
|
16
30
|
const referrer = mayCarryReferrer
|
|
17
|
-
? stringField("referrer", fields?.referrer,
|
|
31
|
+
? stringField("referrer", fields?.referrer, report)
|
|
18
32
|
: undefined;
|
|
19
|
-
const path = page === undefined ? undefined : checkedPath(page,
|
|
33
|
+
const path = page === undefined ? undefined : checkedPath(page, report);
|
|
20
34
|
const host = referrer === undefined ? undefined : referrerHost(referrer);
|
|
21
35
|
const isPageHost = page !== undefined && host === referrerHost(page);
|
|
22
36
|
return {
|
|
@@ -25,12 +39,20 @@ export function newPageReader({ getPage, reportError, }) {
|
|
|
25
39
|
};
|
|
26
40
|
}
|
|
27
41
|
catch (error) {
|
|
28
|
-
|
|
42
|
+
report(error);
|
|
29
43
|
return undefined;
|
|
30
44
|
}
|
|
31
45
|
}
|
|
32
46
|
return {
|
|
33
|
-
|
|
47
|
+
pageNow: () => fieldsOf({ name: PAGE_VIEW, mayCarryReferrer: false, report: () => undefined })?.page,
|
|
48
|
+
read: (name) => ({
|
|
49
|
+
name,
|
|
50
|
+
fields: fieldsOf({
|
|
51
|
+
name,
|
|
52
|
+
mayCarryReferrer: name === PAGE_VIEW && !isPageViewRecorded,
|
|
53
|
+
report: reportError,
|
|
54
|
+
}),
|
|
55
|
+
}),
|
|
34
56
|
view: ({ name, fields }) => {
|
|
35
57
|
if (name !== PAGE_VIEW) {
|
|
36
58
|
return { fields, isRepeatedView: false, recorded: () => undefined };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kk-forge/artel-collector",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Sends a product's analytics events to the intake service",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "KK Forge",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"main": "./dist/shared/exports.js",
|
|
17
17
|
"types": "./dist/shared/exports.d.ts",
|
|
18
18
|
"imports": {
|
|
19
|
-
"
|
|
19
|
+
"#src/*": "./src/*",
|
|
20
20
|
"#tests/*": "./tests/*"
|
|
21
21
|
},
|
|
22
22
|
"exports": {
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"test:ci": "vitest run --coverage"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@kk-forge/oxlint-config": "^
|
|
58
|
+
"@kk-forge/oxlint-config": "^15.0.0",
|
|
59
59
|
"@types/node": "^26.6.6",
|
|
60
60
|
"@vitest/coverage-v8": "^5.0.5",
|
|
61
61
|
"oxfmt": "^0.73.0",
|