@kk-forge/artel-collector 0.1.0 → 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/extension.js CHANGED
@@ -1,25 +1,84 @@
1
+ import { detectBrowser } from './browser.js';
1
2
  import { systemClock } from './clock.js';
2
- import { LifecycleEvent } from './envelope.js';
3
+ import { newCollector } from './collector.js';
4
+ import { Mode } from './collectorTypes.js';
5
+ import { Platform, SYSTEM_EVENTS } from './envelope.js';
6
+ import { eventProblem } from './eventCheck.js';
7
+ import { reportTo } from './hostInput.js';
8
+ import { newWebLock } from './web.js';
9
+ /** The message in each of the extension's `_locales` that holds that locale's code, such as `pt-BR`. */
10
+ const UI_LANGUAGE_MESSAGE = 'ui_language';
3
11
  const FORWARD_TYPE = 'artel.track';
4
- // The intake refuses an event past these limits. The worker refuses such a forwarded event, so the queue never holds an
5
- // event the intake rejects.
6
- const MAX_NAME_LENGTH = 40;
7
- const MAX_PARAMS = 16;
8
- const MAX_PARAM_STRING_LENGTH = 64;
12
+ /**
13
+ * The event names the worker refuses from a content script: every system event, which the intake counts from any page
14
+ * without the product's allowlist.
15
+ */
16
+ const REFUSED_NAMES = new Set(SYSTEM_EVENTS);
9
17
  /**
10
18
  * The forwarded events the worker tracks in a minute from every tab and frame together. A page can open any number of
11
- * frames that run the content script, so only a budget in the worker bounds how fast a page can fill the queue and push
19
+ * frames that run the content script, so only a limit in the worker bounds how fast a page can fill the queue and push
12
20
  * out what waits in it.
13
21
  */
14
22
  const FORWARDS_PER_MINUTE = 60;
15
- /** The bytes of forwarded names and params the worker tracks in a minute, about one envelope. */
16
- const FORWARD_BYTES_PER_MINUTE = 60_000;
17
23
  const MINUTE_MS = 60_000;
24
+ export function newExtensionCollector(options) {
25
+ const closed = isServiceWorker() ? closeToContentScripts(options.onError) : Promise.resolve();
26
+ const defaults = {
27
+ platform: Platform.Extension,
28
+ // The function reads each default only when the caller leaves the option out. A test's fake browser may lack the
29
+ // manifest and `chrome.i18n`.
30
+ version: options.version ?? chromeApi().runtime.getManifest().version,
31
+ storage: after(closed, options.storage ?? newChromeStorageAdapter()),
32
+ lock: options.lock ?? newWebLock(),
33
+ browserLanguage: options.browserLanguage ?? navigator.language,
34
+ uiLanguage: options.uiLanguage ?? localeOfExtension(),
35
+ };
36
+ return options.mode === Mode.Identified
37
+ ? newCollector({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) })
38
+ : newCollector({ ...options, ...defaults });
39
+ }
40
+ /** Tells whether the caller runs in the extension's service worker, the one context that may set the access level. */
41
+ function isServiceWorker() {
42
+ const scope = Reflect.get(globalThis, 'ServiceWorkerGlobalScope');
43
+ return typeof scope === 'function' && globalThis instanceof scope;
44
+ }
45
+ /**
46
+ * Lets only the extension's own pages and worker read and write `chrome.storage.local`, and resolves once Chrome has
47
+ * answered. It never rejects. A failure, such as a Chrome without the call, goes to `onError`.
48
+ */
49
+ async function closeToContentScripts(onError) {
50
+ try {
51
+ const local = chromeApi().storage.local;
52
+ if (typeof local.setAccessLevel !== 'function') {
53
+ throw new TypeError('artel: chrome.storage.local.setAccessLevel is missing, so content scripts can write it');
54
+ }
55
+ await local.setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' });
56
+ }
57
+ catch (error) {
58
+ reportTo(onError, error);
59
+ }
60
+ }
61
+ /** Returns `storage` whose every read and write waits for `ready` first. */
62
+ function after(ready, storage) {
63
+ return {
64
+ get: async (key) => {
65
+ await ready;
66
+ return storage.get(key);
67
+ },
68
+ set: async (key, value) => {
69
+ await ready;
70
+ await storage.set(key, value);
71
+ },
72
+ };
73
+ }
18
74
  /**
19
- * The `chrome.storage.session` key the worker keeps the budget under, so the budget outlasts a restart of the service
20
- * worker, which a page can bring about by going quiet.
75
+ * Returns the locale Chrome picked from the extension's `_locales`, which each locale names in its `ui_language`
76
+ * message, or undefined when the extension has no such message. Chrome gives no other way to read that choice.
21
77
  */
22
- const BUDGET_KEY = 'artel.forwardBudget';
78
+ function localeOfExtension() {
79
+ const locale = chromeApi().i18n?.getMessage(UI_LANGUAGE_MESSAGE);
80
+ return locale === undefined || locale === '' ? undefined : locale;
81
+ }
23
82
  /**
24
83
  * Returns a storage adapter over `chrome.storage.local`, which the service worker and the extension pages share. It
25
84
  * needs the `storage` permission.
@@ -48,109 +107,50 @@ export async function forwardTrack(name, params) {
48
107
  }
49
108
  }
50
109
  /**
51
- * Tracks the events content scripts forward with `forwardTrack`, at most 60 or 60 kB a minute. It takes them only from
52
- * this extension, and never the collector's own lifecycle events, which a content script has no reason to send. Returns
53
- * the function that stops it.
110
+ * Tracks the events content scripts forward with `forwardTrack`, at most 60 a minute. It takes them only from this
111
+ * extension, and only the product's own events: never a system event of the intake, such as `installed` or
112
+ * `uninstalled`, which a content script has no reason to send. Returns the function that stops it.
54
113
  */
55
114
  export function acceptForwarded(collector, { clock = systemClock } = {}) {
56
- let budget;
57
- /** The chain the messages take their turn on, one by one, so each reads the budget the one before it left. */
58
- let turn = Promise.resolve();
59
- /**
60
- * The number of messages waiting their turn. Two minutes' budget is the most the waiting ones could use: what is left
61
- * of the minute they arrived in, and the next minute once it starts.
62
- */
63
- let waiting = 0;
64
- async function spend(now, bytes) {
65
- budget ??= await readBudget();
66
- if (!isWithinMinute(budget, now)) {
67
- budget = { minuteStart: now, tracked: 0, bytes: 0 };
68
- }
69
- if (budget.tracked >= FORWARDS_PER_MINUTE || budget.bytes + bytes > FORWARD_BYTES_PER_MINUTE) {
70
- return false;
71
- }
72
- budget = { minuteStart: budget.minuteStart, tracked: budget.tracked + 1, bytes: budget.bytes + bytes };
73
- await writeBudget(budget);
74
- return true;
75
- }
115
+ let minuteStart = Number.NEGATIVE_INFINITY;
116
+ let tracked = 0;
76
117
  const onMessage = (message, sender) => {
77
118
  if (sender.id !== chromeApi().runtime.id || !isForwarded(message)) {
78
119
  return undefined;
79
120
  }
80
121
  const now = clock.now();
81
- // A message that finds this minute's count spent, or the queue full, is dropped at once rather than queued.
82
- if ((budget !== undefined && isSpent(budget, now)) || waiting >= 2 * FORWARDS_PER_MINUTE) {
83
- return undefined;
122
+ // A clock set back by a minute or more starts a new window too, so forwarding never stops until it catches up.
123
+ if (Math.abs(now - minuteStart) >= MINUTE_MS) {
124
+ minuteStart = now;
125
+ tracked = 0;
126
+ }
127
+ if (tracked < FORWARDS_PER_MINUTE) {
128
+ tracked++;
129
+ void collector.track(message.name, message.params);
84
130
  }
85
- waiting++;
86
- // The turn keeps only the checked fields, not whatever else the message carries.
87
- const { name, params } = message;
88
- const bytes = new TextEncoder().encode(JSON.stringify({ name, params })).length;
89
- turn = turn
90
- .then(() => spend(now, bytes))
91
- .then((isWithinBudget) => (isWithinBudget ? collector.track(name, params) : undefined))
92
- .finally(() => {
93
- waiting--;
94
- });
95
131
  return undefined;
96
132
  };
97
133
  chromeApi().runtime.onMessage.addListener(onMessage);
98
134
  return () => chromeApi().runtime.onMessage.removeListener(onMessage);
99
135
  }
100
136
  /**
101
- * Sets the uninstall page with `uninstallParams()` in its query. Chrome keeps the address as it was set, so the service
102
- * worker calls this on each start to keep the age and the active days current.
137
+ * Sets the uninstall page to `pageUrl` with the fields of `uninstallParams()` added to its query, or to `pageUrl` alone
138
+ * when `uninstallParams()` resolves to undefined. Chrome keeps the address as it was set, so the service worker calls
139
+ * this on each start and after each change of state. It resolves and never rejects. A failure of `uninstallParams()`
140
+ * goes to the collector's `onError`, and any other failure to its own `onError`.
103
141
  */
104
- export async function refreshUninstallUrl(collector, pageUrl) {
105
- const url = new URL(pageUrl);
106
- for (const [name, value] of Object.entries(await collector.uninstallParams())) {
107
- url.searchParams.set(name, String(value));
108
- }
109
- await chromeApi().runtime.setUninstallURL(url.toString());
110
- }
111
- /** A wall clock set back starts a new minute too, or the budget would stay spent until the clock caught up. */
112
- function isWithinMinute(budget, now) {
113
- return now >= budget.minuteStart && now - budget.minuteStart < MINUTE_MS;
114
- }
115
- function isSpent(budget, now) {
116
- return isWithinMinute(budget, now) && budget.tracked >= FORWARDS_PER_MINUTE;
117
- }
118
- /** Reads the budget a worker before this one left. Without `chrome.storage.session` the budget starts empty. */
119
- async function readBudget() {
142
+ export async function refreshUninstallUrl(collector, pageUrl, { onError } = {}) {
120
143
  try {
121
- const stored = (await chromeApi().storage.session.get(BUDGET_KEY))[BUDGET_KEY];
122
- if (isForwardBudget(stored)) {
123
- return stored;
144
+ const url = new URL(pageUrl);
145
+ const params = await collector.uninstallParams();
146
+ for (const [name, value] of Object.entries(params ?? {})) {
147
+ url.searchParams.set(name, String(value));
124
148
  }
149
+ await chromeApi().runtime.setUninstallURL(url.toString());
125
150
  }
126
- catch {
127
- // The budget then lives only as long as this worker.
128
- }
129
- return { minuteStart: 0, tracked: 0, bytes: 0 };
130
- }
131
- async function writeBudget(budget) {
132
- try {
133
- await chromeApi().storage.session.set({ [BUDGET_KEY]: budget });
134
- }
135
- catch {
136
- // The budget then lives only as long as this worker.
137
- }
138
- }
139
- /** Checks a stored budget, including that its counts stay within the limits, so a tampered one cannot widen them. */
140
- function isForwardBudget(value) {
141
- if (typeof value !== 'object' || value === null) {
142
- return false;
151
+ catch (error) {
152
+ reportTo(onError, error);
143
153
  }
144
- const [minuteStart, tracked, bytes] = ['minuteStart', 'tracked', 'bytes'].map((key) => Reflect.get(value, key));
145
- return (Number.isFinite(minuteStart) &&
146
- typeof tracked === 'number' &&
147
- Number.isInteger(tracked) &&
148
- tracked >= 0 &&
149
- tracked <= FORWARDS_PER_MINUTE &&
150
- typeof bytes === 'number' &&
151
- Number.isInteger(bytes) &&
152
- bytes >= 0 &&
153
- bytes <= FORWARD_BYTES_PER_MINUTE);
154
154
  }
155
155
  /** Returns the global `chrome` API, or throws outside an extension context. */
156
156
  function chromeApi() {
@@ -165,32 +165,15 @@ function isChromeApi(value) {
165
165
  return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'runtime') === 'object';
166
166
  }
167
167
  /**
168
- * Checks the shape of a forwarded message and its sizes against the intake's limits, and refuses lifecycle event names.
169
- * Content scripts run among the page's scripts, so the worker cannot trust what they send.
168
+ * Checks a forwarded message against what the intake takes, as `track` does, and refuses the names in
169
+ * `REFUSED_NAMES`. Content scripts run among the page's scripts, so the worker cannot trust what they send.
170
170
  */
171
171
  function isForwarded(message) {
172
172
  if (typeof message !== 'object' || message === null || Reflect.get(message, 'type') !== FORWARD_TYPE) {
173
173
  return false;
174
174
  }
175
175
  const name = Reflect.get(message, 'name');
176
- const params = Reflect.get(message, 'params');
177
- const lifecycleEvents = Object.values(LifecycleEvent);
178
176
  return (typeof name === 'string' &&
179
- characters(name) <= MAX_NAME_LENGTH &&
180
- !lifecycleEvents.includes(name) &&
181
- (params === undefined || isEventParams(params)));
182
- }
183
- function isEventParams(value) {
184
- return (typeof value === 'object' &&
185
- value !== null &&
186
- !Array.isArray(value) &&
187
- Object.keys(value).length <= MAX_PARAMS &&
188
- Object.keys(value).every((key) => characters(key) <= MAX_NAME_LENGTH) &&
189
- Object.values(value).every((item) => (typeof item === 'string' && characters(item) <= MAX_PARAM_STRING_LENGTH) ||
190
- typeof item === 'number' ||
191
- typeof item === 'boolean'));
192
- }
193
- /** Counts characters as the intake does, so a character outside the basic plane counts once. */
194
- function characters(text) {
195
- return Array.from(text).length;
177
+ !REFUSED_NAMES.has(name) &&
178
+ eventProblem(name, Reflect.get(message, 'params')) === undefined);
196
179
  }
@@ -0,0 +1,34 @@
1
+ import { ActiveDaysBucket, type PageFields } from './collectorTypes.js';
2
+ import type { EventParams, UsageEvent } from './envelope.js';
3
+ import type { EventStamp } from './installState.js';
4
+ /** Checks a product version, such as `1.2.3` or `1.2.3-beta.1`, against the format and length the intake takes. */
5
+ export declare function isVersion(value: unknown): value is string;
6
+ /** Checks a language tag, such as `en`, `pt-BR` or `zh-Hant-TW`, against the format and length the intake takes. */
7
+ export declare function isLanguage(value: unknown): value is string;
8
+ /** Returns the tag with `-` for each `_`, as `en_US` becomes `en-US`. The intake reads the tag this way too. */
9
+ export declare function languageTag(value: string | undefined): string | undefined;
10
+ export declare function primaryLanguage(tag: string): string;
11
+ /** Returns the age capped at 31 days when `isExact`, and its bucket otherwise. */
12
+ export declare function ageInDays(days: number, { isExact }: {
13
+ isExact: boolean;
14
+ }): number;
15
+ /**
16
+ * Returns the params of an `uninstalled` event with `age_days` shaped as an envelope's age: capped at 31 days when
17
+ * `isExact`, and its bucket otherwise.
18
+ */
19
+ export declare function uninstalledParams(params: EventParams | undefined, { isExact }: {
20
+ isExact: boolean;
21
+ }): EventParams | undefined;
22
+ /** Returns the bucket for the number of days with at least one event. */
23
+ export declare function activeDaysBucket(days: number): ActiveDaysBucket;
24
+ /**
25
+ * Returns the event to queue. It carries install ages only on the first event of a day or a month, exact or as buckets
26
+ * by `isAgeExact`.
27
+ */
28
+ export declare function newEvent({ name, params, stamp: { today, installDay, first }, page, isAgeExact, }: {
29
+ name: string;
30
+ params: EventParams | undefined;
31
+ stamp: EventStamp;
32
+ page: PageFields | undefined;
33
+ isAgeExact: boolean;
34
+ }): UsageEvent;
package/dist/fields.js ADDED
@@ -0,0 +1,103 @@
1
+ import { Period, daysBetween, formatDay, monthsBetween } from './calendar.js';
2
+ import { ActiveDaysBucket } from './collectorTypes.js';
3
+ // The intake takes `version` and the language fields only in these formats. The intake refuses an envelope with a field
4
+ // that breaks them, and all its events are lost. So the collector drops a bad language, and its constructor throws for
5
+ // a bad version.
6
+ const VERSION_FORMAT = /^\d+(\.\d+){0,3}(-[0-9A-Za-z.]+)?(\+[0-9A-Za-z.]+)?$/;
7
+ const MAX_VERSION_LENGTH = 32;
8
+ const LANGUAGE_FORMAT = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$/;
9
+ const MAX_LANGUAGE_LENGTH = 16;
10
+ /** Checks a product version, such as `1.2.3` or `1.2.3-beta.1`, against the format and length the intake takes. */
11
+ export function isVersion(value) {
12
+ return typeof value === 'string' && value.length <= MAX_VERSION_LENGTH && VERSION_FORMAT.test(value);
13
+ }
14
+ /** Checks a language tag, such as `en`, `pt-BR` or `zh-Hant-TW`, against the format and length the intake takes. */
15
+ export function isLanguage(value) {
16
+ return typeof value === 'string' && value.length <= MAX_LANGUAGE_LENGTH && LANGUAGE_FORMAT.test(value);
17
+ }
18
+ /** Returns the tag with `-` for each `_`, as `en_US` becomes `en-US`. The intake reads the tag this way too. */
19
+ export function languageTag(value) {
20
+ return typeof value === 'string' ? value.replaceAll('_', '-') : value;
21
+ }
22
+ export function primaryLanguage(tag) {
23
+ return tag.split('-')[0] ?? tag;
24
+ }
25
+ /** The highest exact age in days. The intake reads 31 as 31 days or more. */
26
+ const MAX_AGE_DAYS = 31;
27
+ /** The highest exact age in months. The intake reads 25 as over 24 months. */
28
+ const MAX_AGE_MONTHS = 25;
29
+ /**
30
+ * The age buckets in days for an anonymous event. Each bucket covers the days up to the next one: 2 means 2 to 6 days.
31
+ */
32
+ const AGE_DAYS_BUCKETS = [0, 1, 2, 7, 14, 30];
33
+ /**
34
+ * The age buckets in months for an anonymous event. Each bucket covers the months up to the next one: 3 means 3 to 5
35
+ * months.
36
+ */
37
+ const AGE_MONTHS_BUCKETS = [0, 1, 2, 3, 6, 12, 24];
38
+ /** Returns the age capped at 31 days when `isExact`, and its bucket otherwise. */
39
+ export function ageInDays(days, { isExact }) {
40
+ return isExact ? clamp(days, MAX_AGE_DAYS) : bucketOf(days, AGE_DAYS_BUCKETS);
41
+ }
42
+ /**
43
+ * Returns the params of an `uninstalled` event with `age_days` shaped as an envelope's age: capped at 31 days when
44
+ * `isExact`, and its bucket otherwise.
45
+ */
46
+ export function uninstalledParams(params, { isExact }) {
47
+ const age = params?.age_days;
48
+ return typeof age === 'number' ? { ...params, age_days: ageInDays(age, { isExact }) } : params;
49
+ }
50
+ /** Returns the age capped at 25 months when `isExact`, and its bucket otherwise. */
51
+ function ageInMonths(months, { isExact }) {
52
+ return isExact ? clamp(months, MAX_AGE_MONTHS) : bucketOf(months, AGE_MONTHS_BUCKETS);
53
+ }
54
+ /** Returns `value` limited to the range from 0 to `max`. */
55
+ function clamp(value, max) {
56
+ return Math.min(Math.max(0, value), max);
57
+ }
58
+ /** Returns the highest bucket at or below `value`, or the lowest bucket for a negative value. */
59
+ function bucketOf(value, buckets) {
60
+ let bucket = buckets[0] ?? 0;
61
+ for (const candidate of buckets) {
62
+ if (candidate <= value) {
63
+ bucket = candidate;
64
+ }
65
+ }
66
+ return bucket;
67
+ }
68
+ /** Returns the bucket for the number of days with at least one event. */
69
+ export function activeDaysBucket(days) {
70
+ if (days <= 0) {
71
+ return ActiveDaysBucket.None;
72
+ }
73
+ if (days === 1) {
74
+ return ActiveDaysBucket.One;
75
+ }
76
+ if (days <= 5) {
77
+ return ActiveDaysBucket.TwoToFive;
78
+ }
79
+ return days <= 20 ? ActiveDaysBucket.SixToTwenty : ActiveDaysBucket.TwentyOneOrMore;
80
+ }
81
+ /**
82
+ * Returns the event to queue. It carries install ages only on the first event of a day or a month, exact or as buckets
83
+ * by `isAgeExact`.
84
+ */
85
+ export function newEvent({ name, params, stamp: { today, installDay, first }, page, isAgeExact, }) {
86
+ const event = { name, day: formatDay(today), ...(first.length > 0 && { first }) };
87
+ if (first.includes(Period.Day)) {
88
+ event.age_days = ageInDays(daysBetween(installDay, today), { isExact: isAgeExact });
89
+ }
90
+ if (first.includes(Period.Month)) {
91
+ event.age_months = ageInMonths(monthsBetween(installDay, today), { isExact: isAgeExact });
92
+ }
93
+ if (params !== undefined) {
94
+ event.params = params;
95
+ }
96
+ if (page?.page !== undefined) {
97
+ event.page = page.page;
98
+ }
99
+ if (page?.referrer !== undefined) {
100
+ event.referrer = page.referrer;
101
+ }
102
+ return event;
103
+ }
@@ -0,0 +1,39 @@
1
+ import { type Browser } from './browser.js';
2
+ import type { CollectorOptions, GetId } from './collectorTypes.js';
3
+ import type { Build } from './stateFields.js';
4
+ import type { StorageAdapter } from './storage.js';
5
+ type ReportError = (error: unknown) => void;
6
+ /**
7
+ * Returns `value` as JSON, cut to its first 64 characters with `…` after a cut, or its type where JSON cannot write it,
8
+ * such as a symbol, a bigint or a circular object. A report that quotes host input uses it, so no value makes the report
9
+ * throw or grow past a line.
10
+ */
11
+ export declare function quoted(value: unknown): string;
12
+ /** Hands `error` to the host's `onError` as an Error. A handler that throws reaches no caller. */
13
+ export declare function reportTo(onError: ((error: Error) => void) | undefined, error: unknown): void;
14
+ /** Returns `value` when it passes `check`, or reports it and returns undefined. */
15
+ export declare function accepted(name: string, value: string | undefined, check: (candidate: unknown) => candidate is string, reportError: ReportError): string | undefined;
16
+ /**
17
+ * Returns the platform and the version of the options. Throws a `TypeError` that names the option for options the
18
+ * intake would refuse every envelope of, or that only a host outside TypeScript passes: a platform, a key or a version
19
+ * the intake does not take, an endpoint that is not https, a transport that is not a function, and a browser on a
20
+ * platform that names none. A mistake in the build then fails its first run and its tests.
21
+ */
22
+ export declare function checkedBuild(options: CollectorOptions): Build;
23
+ /**
24
+ * Returns a function that gives the host's browser as the intake keeps it, or undefined when there is none. A function
25
+ * the host passes runs only at the first call, which the collector makes only for an event with an id. Reports and
26
+ * leaves out a value that is not a browser, which only a host outside TypeScript passes.
27
+ */
28
+ export declare function newBrowserReader(browser: Browser | (() => Browser | undefined) | undefined, reportError: ReportError): () => Browser | undefined;
29
+ /**
30
+ * Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
31
+ * return null or an empty string, which then reads as an id the product does not know yet.
32
+ */
33
+ export declare function usableId(getId: GetId, reportError: ReportError): GetId;
34
+ /**
35
+ * Returns the storage with every value that is not a string read as absent. A product's own storage may resolve null
36
+ * for a missing key, which would read as a stored install mark or another user's id.
37
+ */
38
+ export declare function newStringStorage(storage: StorageAdapter): StorageAdapter;
39
+ export {};
@@ -0,0 +1,182 @@
1
+ import { copyBrowser } from './browser.js';
2
+ import { Platform } from './envelope.js';
3
+ import { isVersion } from './fields.js';
4
+ /** The most characters an id may have for the intake to take it. */
5
+ const MAX_ID_LENGTH = 64;
6
+ /** The hosts an http endpoint may name: this machine, as `URL` writes its hostname. */
7
+ const DEVELOPMENT_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
8
+ /** The most characters of host or stored text a report quotes. A planted value can be megabytes long. */
9
+ const MAX_QUOTED_LENGTH = 64;
10
+ /**
11
+ * The channel kinds, each with the form of its key and the platforms it takes. A key is the kind, `test-` for a test
12
+ * key, then 10 characters of `[0-9a-z]`. The intake refuses an envelope of a platform its channel's kind does not take.
13
+ */
14
+ const CHANNEL_KINDS = [
15
+ { kind: 'extension', platforms: [Platform.Extension] },
16
+ { kind: 'desktop', platforms: [Platform.MacOs, Platform.Windows, Platform.Linux] },
17
+ { kind: 'site', platforms: [Platform.Web] },
18
+ ].map(({ kind, platforms }) => ({
19
+ kind,
20
+ keyFormat: new RegExp(String.raw `^${kind}-(?:test-)?[\da-z]{10}$`),
21
+ platforms: platforms,
22
+ }));
23
+ /**
24
+ * Returns `value` as JSON, cut to its first 64 characters with `…` after a cut, or its type where JSON cannot write it,
25
+ * such as a symbol, a bigint or a circular object. A report that quotes host input uses it, so no value makes the report
26
+ * throw or grow past a line.
27
+ */
28
+ export function quoted(value) {
29
+ let text;
30
+ try {
31
+ text = JSON.stringify(value) ?? typeof value;
32
+ }
33
+ catch {
34
+ return typeof value;
35
+ }
36
+ const characters = Array.from(text.slice(0, 2 * MAX_QUOTED_LENGTH));
37
+ return characters.length > MAX_QUOTED_LENGTH ? `${characters.slice(0, MAX_QUOTED_LENGTH).join('')}…` : text;
38
+ }
39
+ /** Hands `error` to the host's `onError` as an Error. A handler that throws reaches no caller. */
40
+ export function reportTo(onError, error) {
41
+ try {
42
+ onError?.(error instanceof Error ? error : new Error(String(error)));
43
+ }
44
+ catch {
45
+ // The host's own handler failing must not make the caller reject or throw.
46
+ }
47
+ }
48
+ /** Returns `value` when it passes `check`, or reports it and returns undefined. */
49
+ export function accepted(name, value, check, reportError) {
50
+ if (value === undefined || check(value)) {
51
+ return value;
52
+ }
53
+ reportError(new Error(`artel: ${name} ${quoted(value)} is not one the intake takes, left out`));
54
+ return undefined;
55
+ }
56
+ /**
57
+ * Returns the platform and the version of the options. Throws a `TypeError` that names the option for options the
58
+ * intake would refuse every envelope of, or that only a host outside TypeScript passes: a platform, a key or a version
59
+ * the intake does not take, an endpoint that is not https, a transport that is not a function, and a browser on a
60
+ * platform that names none. A mistake in the build then fails its first run and its tests.
61
+ */
62
+ export function checkedBuild(options) {
63
+ checkDelivery(options);
64
+ const { platform, version } = options;
65
+ if (!Object.values(Platform).includes(platform)) {
66
+ throw new TypeError(`artel: platform ${quoted(platform)} is not one the intake takes`);
67
+ }
68
+ checkKey(options.key, platform);
69
+ if (!isVersion(version)) {
70
+ throw new TypeError(`artel: version ${quoted(version)} is not one the intake takes`);
71
+ }
72
+ if (options.browser !== undefined && platform !== Platform.Web && platform !== Platform.Extension) {
73
+ throw new TypeError(`artel: platform ${platform} names no browser`);
74
+ }
75
+ return { platform, version };
76
+ }
77
+ /**
78
+ * Throws unless the options name a transport that is a function, or an endpoint that is an https URL, or an http URL of
79
+ * a development host, without a user or a password. Plain http would send ids and events readable on the way, `fetch`
80
+ * refuses every URL with credentials, and a request to any other address never reaches the intake. The message quotes
81
+ * no endpoint, so it never carries a password.
82
+ */
83
+ function checkDelivery({ endpoint, transport }) {
84
+ if (transport !== undefined) {
85
+ if (typeof transport !== 'function') {
86
+ throw new TypeError(`artel: transport is a ${typeof transport}, not a function`);
87
+ }
88
+ return;
89
+ }
90
+ let url;
91
+ try {
92
+ url = typeof endpoint === 'string' ? new URL(endpoint) : undefined;
93
+ }
94
+ catch {
95
+ // The throw below covers an endpoint that is no URL.
96
+ }
97
+ const isHttps = url?.protocol === 'https:' || (url?.protocol === 'http:' && isDevelopmentHost(url.hostname));
98
+ if (!isHttps || url?.username !== '' || url.password !== '') {
99
+ throw new TypeError('artel: endpoint is not an https URL without a user or password, or http to a development host');
100
+ }
101
+ }
102
+ /** Tells whether a URL's host is one only this machine or a development setup serves. */
103
+ function isDevelopmentHost(hostname) {
104
+ return DEVELOPMENT_HOSTS.has(hostname) || hostname.endsWith('.localhost') || hostname.endsWith('.test');
105
+ }
106
+ /** Throws unless `key` has the intake's form, and its channel kind takes `platform`. */
107
+ function checkKey(key, platform) {
108
+ const channel = typeof key === 'string' ? CHANNEL_KINDS.find(({ keyFormat }) => keyFormat.test(key)) : undefined;
109
+ if (channel === undefined) {
110
+ throw new TypeError(`artel: key ${quoted(key)} is not <kind>-<10 characters> or <kind>-test-<10 characters>`);
111
+ }
112
+ if (!channel.platforms.includes(platform)) {
113
+ throw new TypeError(`artel: a key of kind ${channel.kind} does not take platform ${platform}`);
114
+ }
115
+ }
116
+ /**
117
+ * Returns a function that gives the host's browser as the intake keeps it, or undefined when there is none. A function
118
+ * the host passes runs only at the first call, which the collector makes only for an event with an id. Reports and
119
+ * leaves out a value that is not a browser, which only a host outside TypeScript passes.
120
+ */
121
+ export function newBrowserReader(browser, reportError) {
122
+ if (typeof browser !== 'function') {
123
+ const copy = acceptedBrowser(browser, reportError);
124
+ return () => copy;
125
+ }
126
+ let read;
127
+ return () => {
128
+ read ??= { browser: acceptedBrowser(callBrowser(browser, reportError), reportError) };
129
+ return read.browser;
130
+ };
131
+ }
132
+ function callBrowser(browser, reportError) {
133
+ try {
134
+ return browser();
135
+ }
136
+ catch (error) {
137
+ reportError(error);
138
+ return undefined;
139
+ }
140
+ }
141
+ /** Returns a copy of the browser as the intake keeps it, or reports and drops a value that is not a browser. */
142
+ function acceptedBrowser(browser, reportError) {
143
+ if (browser === undefined) {
144
+ return undefined;
145
+ }
146
+ const copy = copyBrowser(browser);
147
+ if (copy === undefined) {
148
+ reportError(new Error(`artel: browser ${quoted(browser)} is not a browser, left out`));
149
+ }
150
+ return copy;
151
+ }
152
+ /**
153
+ * Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
154
+ * return null or an empty string, which then reads as an id the product does not know yet.
155
+ */
156
+ export function usableId(getId, reportError) {
157
+ return async () => {
158
+ const id = await getId();
159
+ if (typeof id !== 'string' || id === '') {
160
+ return undefined;
161
+ }
162
+ // The intake refuses the whole envelope of an id past 64 characters. The event waits as for an unknown id instead.
163
+ if (Array.from(id).length > MAX_ID_LENGTH) {
164
+ reportError(new Error(`artel: an id past ${MAX_ID_LENGTH} characters is not one the intake takes`));
165
+ return undefined;
166
+ }
167
+ return id;
168
+ };
169
+ }
170
+ /**
171
+ * Returns the storage with every value that is not a string read as absent. A product's own storage may resolve null
172
+ * for a missing key, which would read as a stored install mark or another user's id.
173
+ */
174
+ export function newStringStorage(storage) {
175
+ return {
176
+ get: async (key) => {
177
+ const value = await storage.get(key);
178
+ return typeof value === 'string' ? value : undefined;
179
+ },
180
+ set: (key, value) => storage.set(key, value),
181
+ };
182
+ }