@kk-forge/artel-collector 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/storage.d.ts CHANGED
@@ -1,4 +1,7 @@
1
- /** Where the collector keeps its state between runs of the host. Every key it uses starts with `artel.`. */
1
+ /**
2
+ * Holds the collector's state between runs of the host. Every key the collector uses starts with `artel.<channel
3
+ * key>.`.
4
+ */
2
5
  export interface StorageAdapter {
3
6
  get(key: string): Promise<string | undefined>;
4
7
  set(key: string, value: string): Promise<void>;
@@ -8,3 +11,8 @@ export interface StorageAdapter {
8
11
  * to persist state.
9
12
  */
10
13
  export declare function newMemoryStorage(): StorageAdapter;
14
+ /**
15
+ * Returns `storage` with each name stored under `artel.<key>.<name>`. Then collectors of different channel keys over
16
+ * one storage share no state, and none drops the queued envelopes of another.
17
+ */
18
+ export declare function newChannelStorage(storage: StorageAdapter, key: string): StorageAdapter;
package/dist/storage.js CHANGED
@@ -11,3 +11,14 @@ export function newMemoryStorage() {
11
11
  },
12
12
  };
13
13
  }
14
+ /**
15
+ * Returns `storage` with each name stored under `artel.<key>.<name>`. Then collectors of different channel keys over
16
+ * one storage share no state, and none drops the queued envelopes of another.
17
+ */
18
+ export function newChannelStorage(storage, key) {
19
+ const prefix = `artel.${key}.`;
20
+ return {
21
+ get: (name) => storage.get(prefix + name),
22
+ set: (name, value) => storage.set(prefix + name, value),
23
+ };
24
+ }
@@ -1,13 +1,19 @@
1
1
  import { type Clock } from './clock.js';
2
+ /** What the intake answered: its HTTP status, 0 when the request did not reach it, and its `Retry-After` header. */
3
+ export interface TransportResult {
4
+ status: number;
5
+ retryAfter?: string;
6
+ }
2
7
  /**
3
- * Sends one envelope and resolves to the intake's HTTP status, or 0 on failure. It must resolve within 30 seconds. Past
4
- * a minute, the intake keeps a forgotten user's events, and the envelope's lease ends, so another context may resend
5
- * it.
8
+ * Sends one envelope and resolves to the intake's answer or its HTTP status. It must resolve within 30 seconds. After
9
+ * 35 seconds the outbox counts it as status 0 and sends the envelope again. The intake keeps a forgotten user's events
10
+ * from a request that arrives over a minute after the forget.
6
11
  */
7
- export type Transport = (body: string) => Promise<number>;
12
+ export type Transport = (body: string) => Promise<number | TransportResult>;
8
13
  /**
9
14
  * Returns a transport that posts each envelope to `endpoint` with `fetch`, the host's own by default. The transport
10
- * resolves to 0 when a request takes over 30 seconds.
15
+ * resolves to the status and the raw `Retry-After` header, or to status 0 when a request fails or takes over 30
16
+ * seconds.
11
17
  */
12
18
  export declare function newHttpTransport(endpoint: string, { fetch, clock, }?: {
13
19
  fetch?: typeof globalThis.fetch;
package/dist/transport.js CHANGED
@@ -2,7 +2,8 @@ import { systemClock } from './clock.js';
2
2
  const TIMEOUT_MS = 30_000;
3
3
  /**
4
4
  * Returns a transport that posts each envelope to `endpoint` with `fetch`, the host's own by default. The transport
5
- * resolves to 0 when a request takes over 30 seconds.
5
+ * resolves to the status and the raw `Retry-After` header, or to status 0 when a request fails or takes over 30
6
+ * seconds.
6
7
  */
7
8
  export function newHttpTransport(endpoint, {
8
9
  // The default calls `fetch` through its global. A browser refuses a `fetch` called apart from its global.
@@ -24,10 +25,11 @@ fetch = (input, init) => globalThis.fetch(input, init), clock = systemClock, } =
24
25
  keepalive: true,
25
26
  signal: timeout.signal,
26
27
  });
27
- return response.status;
28
+ const retryAfter = response.headers.get('Retry-After');
29
+ return { status: response.status, ...(retryAfter !== null && { retryAfter }) };
28
30
  }
29
31
  catch {
30
- return 0;
32
+ return { status: 0 };
31
33
  }
32
34
  finally {
33
35
  clock.clearTimeout(timer);
package/dist/web.d.ts CHANGED
@@ -1,21 +1,50 @@
1
- import type { Collector, PageFields } from './collector.js';
1
+ import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions, type PageFields, type PageOptions } from './collectorTypes.js';
2
2
  import type { Lock } from './lock.js';
3
3
  import type { StorageAdapter } from './storage.js';
4
+ /**
5
+ * The options of `newWebCollector`: those of `newCollector` without `platform`, with `storage` optional. An option left
6
+ * out or `undefined` takes its default.
7
+ */
8
+ export type WebCollectorOptions = Omit<CommonOptions, 'storage'> & {
9
+ storage?: StorageAdapter | undefined;
10
+ } & PageOptions & Delivery & ModeOptions;
11
+ /**
12
+ * Returns a collector for a website or a web app. It runs over `localStorage` and Web Locks, and sends the user's
13
+ * language from `navigator.language`, the page from `pageFields` and, in the identified state, the browser from
14
+ * `detectBrowser`. The site passes its own `uiLanguage`. A Tauri desktop window builds its own with `newCollector` and
15
+ * this module's helpers.
16
+ */
17
+ export declare function newWebCollector(options: WebCollectorOptions & {
18
+ mode: typeof Mode.Identified;
19
+ }): Collector<'identified'>;
20
+ export declare function newWebCollector(options: WebCollectorOptions & {
21
+ mode: typeof Mode.Anonymous;
22
+ }): Collector<'anonymous'>;
23
+ export declare function newWebCollector(options: WebCollectorOptions): Collector;
24
+ /**
25
+ * Returns a storage adapter over `localStorage`, which every tab of the origin shares. A Web Worker has no
26
+ * `localStorage`, so a collector there passes its own storage.
27
+ */
4
28
  export declare function newLocalStorageAdapter(): StorageAdapter;
5
29
  /**
6
- * Returns a lock that uses Web Locks over the origin, so that its tabs and workers do not send one queued envelope at
7
- * the same time. Where a browser lacks Web Locks, the operation runs unguarded.
30
+ * Returns a lock that uses Web Locks over the origin, so that its tabs and workers run one collector operation at a
31
+ * time. Where a browser lacks Web Locks, the operation runs unguarded.
8
32
  */
9
33
  export declare function newWebLock(): Lock;
10
34
  /**
11
- * Returns the current page's path without the query string, and the referring host only when it is another site. A site
12
- * whose paths carry a secret or a person, such as `/share/<token>`, passes its own `getPage` with the route pattern
13
- * instead.
35
+ * Returns the page's address without query and fragment, and the raw referrer. The collector sends only the path and
36
+ * the referrer's host. A site with a secret or a personal ID in its paths, such as `/share/<token>`, passes its own
37
+ * `getPage` that returns the route pattern instead.
14
38
  */
15
39
  export declare function pageFields(): PageFields;
16
40
  /**
17
- * Flushes the queue when the page is hidden, since the user may not return. The collector's fetch uses `keepalive`, so
18
- * a send started before the tab closes still finishes. A send not yet started waits for the next visit. Returns the
19
- * function that removes the listener.
41
+ * Sends `page_view` for the current page and after each navigation that changes `location.pathname`, and returns the
42
+ * function that stops it. A query change alone sends none. Once every tracker stops, `history` is as they found it.
43
+ */
44
+ export declare function trackPageViews(collector: Collector): () => void;
45
+ /**
46
+ * Flushes the queue when the page is hidden, since the user may not return. A request to `endpoint` that started
47
+ * before the tab closes still finishes. A send not yet started waits for the next visit. Returns the function that
48
+ * removes the listener.
20
49
  */
21
50
  export declare function flushWhenHidden(collector: Collector): () => void;
package/dist/web.js CHANGED
@@ -1,3 +1,23 @@
1
+ import { detectBrowser } from './browser.js';
2
+ import { newCollector } from './collector.js';
3
+ import { Mode, } from './collectorTypes.js';
4
+ import { PAGE_VIEW, Platform } from './envelope.js';
5
+ export function newWebCollector(options) {
6
+ const defaults = {
7
+ platform: Platform.Web,
8
+ storage: options.storage ?? newLocalStorageAdapter(),
9
+ lock: options.lock ?? newWebLock(),
10
+ browserLanguage: options.browserLanguage ?? navigator.language,
11
+ getPage: options.getPage ?? pageFieldsWherePageIs,
12
+ };
13
+ return options.mode === Mode.Identified
14
+ ? newCollector({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) })
15
+ : newCollector({ ...options, ...defaults });
16
+ }
17
+ /**
18
+ * Returns a storage adapter over `localStorage`, which every tab of the origin shares. A Web Worker has no
19
+ * `localStorage`, so a collector there passes its own storage.
20
+ */
1
21
  export function newLocalStorageAdapter() {
2
22
  return {
3
23
  get: async (key) => localStorage.getItem(key) ?? undefined,
@@ -7,8 +27,8 @@ export function newLocalStorageAdapter() {
7
27
  };
8
28
  }
9
29
  /**
10
- * Returns a lock that uses Web Locks over the origin, so that its tabs and workers do not send one queued envelope at
11
- * the same time. Where a browser lacks Web Locks, the operation runs unguarded.
30
+ * Returns a lock that uses Web Locks over the origin, so that its tabs and workers run one collector operation at a
31
+ * time. Where a browser lacks Web Locks, the operation runs unguarded.
12
32
  */
13
33
  export function newWebLock() {
14
34
  return (operation) => {
@@ -18,18 +38,82 @@ export function newWebLock() {
18
38
  };
19
39
  }
20
40
  /**
21
- * Returns the current page's path without the query string, and the referring host only when it is another site. A site
22
- * whose paths carry a secret or a person, such as `/share/<token>`, passes its own `getPage` with the route pattern
23
- * instead.
41
+ * Returns the page's address without query and fragment, and the raw referrer. The collector sends only the path and
42
+ * the referrer's host. A site with a secret or a personal ID in its paths, such as `/share/<token>`, passes its own
43
+ * `getPage` that returns the route pattern instead.
24
44
  */
25
45
  export function pageFields() {
26
- const referrer = referrerHost(document.referrer);
27
- return { page: location.pathname, ...(referrer !== undefined && referrer !== location.hostname && { referrer }) };
46
+ return { page: `${location.protocol}//${location.host}${location.pathname}`, referrer: document.referrer };
47
+ }
48
+ /** Returns `pageFields`, or undefined in a Web Worker, which has no page. */
49
+ function pageFieldsWherePageIs() {
50
+ return typeof document === 'undefined' || typeof location === 'undefined' ? undefined : pageFields();
51
+ }
52
+ /**
53
+ * Sends `page_view` for the current page and after each navigation that changes `location.pathname`, and returns the
54
+ * function that stops it. A query change alone sends none. Once every tracker stops, `history` is as they found it.
55
+ */
56
+ export function trackPageViews(collector) {
57
+ let lastPath;
58
+ const onNavigation = () => {
59
+ // A navigation can reach the tracker twice, as a `pushState` and as a `currententrychange`.
60
+ if (location.pathname === lastPath) {
61
+ return;
62
+ }
63
+ lastPath = location.pathname;
64
+ void collector.track(PAGE_VIEW);
65
+ };
66
+ const unwrapPushState = callAfter('pushState', onNavigation);
67
+ const unwrapReplaceState = callAfter('replaceState', onNavigation);
68
+ window.addEventListener('popstate', onNavigation);
69
+ const navigation = navigationApi();
70
+ navigation?.addEventListener('currententrychange', onNavigation);
71
+ onNavigation();
72
+ return () => {
73
+ unwrapPushState();
74
+ unwrapReplaceState();
75
+ window.removeEventListener('popstate', onNavigation);
76
+ navigation?.removeEventListener('currententrychange', onNavigation);
77
+ };
78
+ }
79
+ /** The wrappers `callAfter` installed, by the wrapper function. */
80
+ const wrappings = new WeakMap();
81
+ /**
82
+ * Wraps a history method so `listener` runs after each call, and returns the undo. The undo removes stopped wrappers
83
+ * from the top down, so trackers that stop in any order leave `history` as they found it. A stopped wrapper under an
84
+ * active one or under a product's own wrapper stays and passes calls on.
85
+ */
86
+ function callAfter(method, listener) {
87
+ const wrapping = { found: history[method], wasOwn: Object.hasOwn(history, method), isActive: true };
88
+ const wrapper = function (...args) {
89
+ wrapping.found.apply(this, args);
90
+ if (wrapping.isActive) {
91
+ listener();
92
+ }
93
+ };
94
+ wrappings.set(wrapper, wrapping);
95
+ history[method] = wrapper;
96
+ return () => {
97
+ wrapping.isActive = false;
98
+ for (let top = wrappings.get(history[method]); top?.isActive === false; top = wrappings.get(history[method])) {
99
+ if (top.wasOwn) {
100
+ history[method] = top.found;
101
+ }
102
+ else {
103
+ Reflect.deleteProperty(history, method);
104
+ }
105
+ }
106
+ };
107
+ }
108
+ /** Returns the Navigation API, or undefined where the browser lacks it. */
109
+ function navigationApi() {
110
+ const navigation = Reflect.get(globalThis, 'navigation');
111
+ return navigation instanceof EventTarget ? navigation : undefined;
28
112
  }
29
113
  /**
30
- * Flushes the queue when the page is hidden, since the user may not return. The collector's fetch uses `keepalive`, so
31
- * a send started before the tab closes still finishes. A send not yet started waits for the next visit. Returns the
32
- * function that removes the listener.
114
+ * Flushes the queue when the page is hidden, since the user may not return. A request to `endpoint` that started
115
+ * before the tab closes still finishes. A send not yet started waits for the next visit. Returns the function that
116
+ * removes the listener.
33
117
  */
34
118
  export function flushWhenHidden(collector) {
35
119
  const onChange = () => {
@@ -40,11 +124,3 @@ export function flushWhenHidden(collector) {
40
124
  document.addEventListener('visibilitychange', onChange);
41
125
  return () => document.removeEventListener('visibilitychange', onChange);
42
126
  }
43
- function referrerHost(referrer) {
44
- try {
45
- return referrer === '' ? undefined : new URL(referrer).hostname;
46
- }
47
- catch {
48
- return undefined;
49
- }
50
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kk-forge/artel-collector",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Sends a product's usage events to the intake service",
5
5
  "license": "MIT",
6
6
  "author": "KK Forge",