@kk-forge/artel-collector 0.3.0 → 0.4.1

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.
@@ -1,31 +1,36 @@
1
- import { type Clock } from './clock.js';
2
- import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions } from './collectorTypes.js';
3
- import { type EventParams } from './envelope.js';
4
- import type { StorageAdapter } from './storage.js';
1
+ import { type Clock } from "./clock.js";
2
+ import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions } from "./collectorTypes.js";
3
+ import { type EventParams } from "./envelope.js";
4
+ import type { StorageAdapter } from "./storage.js";
5
5
  /**
6
6
  * The options of `newExtensionCollector`: those of `newCollector` without `platform`, with `storage` and `version`
7
7
  * optional. An option left out or `undefined` takes its default.
8
8
  */
9
- export type ExtensionCollectorOptions = Omit<CommonOptions, 'storage' | 'version'> & {
9
+ export type ExtensionCollectorOptions = Omit<CommonOptions, "storage" | "version"> & {
10
10
  /** The storage, `chrome.storage.local` by default. */
11
11
  storage?: StorageAdapter | undefined;
12
12
  /** The product version, the manifest's by default. */
13
13
  version?: string | undefined;
14
+ /**
15
+ * The address of the page Chrome opens when the user removes the extension. The collector sets it with the fields of
16
+ * `uninstallParams()` in its query at construction, after each `setState` and after the first event of a local day.
17
+ * Left out, the collector sets none.
18
+ */
19
+ uninstallPage?: string | undefined;
14
20
  /** An extension sends no page. */
15
21
  getPage?: never;
16
22
  } & Delivery & ModeOptions;
17
23
  /**
18
24
  * Returns a collector for an extension's worker or page. It needs the `storage` permission. In the worker it first
19
- * closes the storage to content scripts, which could otherwise change the user's choice and the queue. The product
20
- * builds it at the worker's top level, so the call runs at each worker start.
25
+ * closes the storage to content scripts, which could otherwise change the user's analytics state and the queue. The
26
+ * worker's collector also sends `installed` and `updated` at Chrome's `onInstalled`, and tracks the events content
27
+ * scripts forward. Chrome needs these listeners registered synchronously at the worker's top level on every start of
28
+ * the worker, so the product builds it there. The worker's collector also sends what the pages queue, even after the
29
+ * page closed.
21
30
  */
22
- export declare function newExtensionCollector(options: ExtensionCollectorOptions & {
23
- mode: typeof Mode.Identified;
24
- }): Collector<'identified'>;
25
- export declare function newExtensionCollector(options: ExtensionCollectorOptions & {
26
- mode: typeof Mode.Anonymous;
27
- }): Collector<'anonymous'>;
28
- export declare function newExtensionCollector(options: ExtensionCollectorOptions): Collector;
31
+ export declare function newExtensionCollector<M extends Mode>(options: ExtensionCollectorOptions & {
32
+ mode: M;
33
+ }): Collector<M>;
29
34
  /**
30
35
  * Returns a storage adapter over `chrome.storage.local`, which the service worker and the extension pages share. It
31
36
  * needs the `storage` permission.
@@ -36,29 +41,14 @@ export declare function newChromeStorageAdapter(): StorageAdapter;
36
41
  * script's own requests, which carry the page's origin.
37
42
  */
38
43
  export declare function forwardTrack(name: string, params?: EventParams): Promise<void>;
39
- /** The part of the collector a content script uses: it tracks events, and the worker keeps the user's choice. */
40
- export type ContentScriptCollector = Pick<Collector, 'track' | 'flush'>;
44
+ /** The part of the collector a content script uses: it tracks events, and the worker keeps the analytics state. */
45
+ export type ContentScriptCollector = Pick<Collector, "track">;
41
46
  /**
42
- * Returns the collector of a content script. Its `track` hands each event to the service worker with `forwardTrack`,
43
- * and the worker's collector checks, queues and sends it under the user's choice, so `flush` does nothing here. The
44
- * user's choice lives in the worker and the extension pages, so a content script can neither read nor change it. It
45
- * reads no storage, needs no key, version or endpoint, and never throws.
47
+ * Returns the collector of a content script. Its `track` applies a call's `throttleMs` in the script's memory, by
48
+ * `clock`, then hands the event to the worker with `forwardTrack`. The worker checks, queues and sends it under the
49
+ * user's analytics state, which a content script can neither read nor change. It reads no storage, needs no key,
50
+ * version or endpoint, never throws, and drops a call with a bad `throttleMs` without a report, having no `onError`.
46
51
  */
47
- export declare function newContentScriptCollector(): ContentScriptCollector;
48
- /**
49
- * Tracks the events content scripts forward with `forwardTrack`, at most 60 a minute. It takes them only from this
50
- * extension, and only the product's own events: never a system event of the intake, such as `installed` or
51
- * `uninstalled`, which a content script has no reason to send. Returns the function that stops it.
52
- */
53
- export declare function acceptForwarded(collector: Collector, { clock }?: {
52
+ export declare function newContentScriptCollector({ clock, }?: {
54
53
  clock?: Clock;
55
- }): () => void;
56
- /**
57
- * Sets the uninstall page to `pageUrl` with the fields of `uninstallParams()` added to its query, or to `pageUrl` alone
58
- * when `uninstallParams()` resolves to undefined. Chrome keeps the address as it was set, so the service worker calls
59
- * this on each start and after each change of state. It resolves and never rejects. A failure of `uninstallParams()`
60
- * goes to the collector's `onError`, and any other failure to its own `onError`.
61
- */
62
- export declare function refreshUninstallUrl(collector: Collector, pageUrl: string, { onError }?: {
63
- onError?: (error: Error) => void;
64
- }): Promise<void>;
54
+ }): ContentScriptCollector;
package/dist/extension.js CHANGED
@@ -1,12 +1,14 @@
1
- import { detectBrowser } from './browser.js';
2
- import { systemClock } from './clock.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
- const FORWARD_TYPE = 'artel.track';
1
+ import { detectBrowser } from "./browser.js";
2
+ import { systemClock } from "./clock.js";
3
+ import { newCollectorNotingDays, sendDelayMsOf } from "./collector.js";
4
+ import { AnalyticsState, Mode, } from "./collectorTypes.js";
5
+ import { Platform, SYSTEM_EVENTS } from "./envelope.js";
6
+ import { checkEvent } from "./eventCheck.js";
7
+ import { reportTo } from "./hostInput.js";
8
+ import { parseQueue, QUEUE_KEY } from "./queue.js";
9
+ import { newThrottle, throttleOf } from "./throttle.js";
10
+ import { newWebLock } from "./web.js";
11
+ const FORWARD_TYPE = "artel.track";
10
12
  /**
11
13
  * The event names the worker refuses from a content script: every system event, which the intake counts from any page
12
14
  * without the product's allowlist.
@@ -20,7 +22,8 @@ const REFUSED_NAMES = new Set(SYSTEM_EVENTS);
20
22
  const FORWARDS_PER_MINUTE = 60;
21
23
  const MINUTE_MS = 60_000;
22
24
  export function newExtensionCollector(options) {
23
- const closed = isServiceWorker() ? closeToContentScripts(options.onError) : Promise.resolve();
25
+ const isWorker = isServiceWorker();
26
+ const closed = isWorker ? closeToContentScripts(options.onError) : Promise.resolve();
24
27
  const defaults = {
25
28
  platform: Platform.Extension,
26
29
  // The function reads each default only when the caller leaves the option out, so outside an extension it needs only
@@ -30,14 +33,112 @@ export function newExtensionCollector(options) {
30
33
  lock: options.lock ?? newWebLock(),
31
34
  browserLanguage: options.browserLanguage ?? navigator.language,
32
35
  };
33
- return options.mode === Mode.Identified
34
- ? newCollector({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) })
35
- : newCollector({ ...options, ...defaults });
36
+ // `onNewDay` refreshes the uninstall page, since a day's first event changes its `active_days`. The collector queues
37
+ // no event before `refreshUninstallPage` is set below.
38
+ let refreshUninstallPage;
39
+ const onNewDay = () => void refreshUninstallPage?.();
40
+ const built = options.mode === Mode.Anonymous
41
+ ? newCollectorNotingDays({ ...options, ...defaults }, onNewDay)
42
+ : newCollectorNotingDays({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) }, onNewDay);
43
+ const { collector, refresh } = withUninstallPage(built, options.uninstallPage, options.onError);
44
+ refreshUninstallPage = refresh;
45
+ if (isWorker) {
46
+ listenAsWorker(collector, {
47
+ queueKey: `artel.${options.key}.${QUEUE_KEY}`,
48
+ sendDelayMs: sendDelayMsOf(options),
49
+ clock: options.clock ?? systemClock,
50
+ onError: options.onError,
51
+ });
52
+ }
53
+ return collector;
54
+ }
55
+ /**
56
+ * Registers the worker's listeners: `installed` and `updated` at `onInstalled`, the events content scripts forward, the
57
+ * events pages queue, and an empty `onStartup` listener. Chrome starts a worker with an `onStartup` listener when the
58
+ * browser starts, so the access level is set again before any page or content script runs.
59
+ */
60
+ function listenAsWorker(collector, { queueKey, sendDelayMs, clock, onError, }) {
61
+ const { runtime, storage } = chromeApi();
62
+ // A page's own send cannot finish once the page closes, as when a popup closes right after an event. The worker
63
+ // sends what pages queue within the send delay. Its own sends add no event to the queue, so they schedule nothing.
64
+ let isSendScheduled = false;
65
+ storage.onChanged.addListener((changes, area) => {
66
+ const change = changes[queueKey];
67
+ if (area !== "local" || change === undefined || isSendScheduled || !addsEvents(change)) {
68
+ return;
69
+ }
70
+ isSendScheduled = true;
71
+ clock.setTimeout(() => {
72
+ isSendScheduled = false;
73
+ void collector.flush();
74
+ }, sendDelayMs);
75
+ });
76
+ runtime.onInstalled.addListener(({ reason }) => {
77
+ if (reason === "install") {
78
+ void collector.installed();
79
+ }
80
+ else if (reason === "update") {
81
+ void collector.updated();
82
+ }
83
+ });
84
+ runtime.onStartup.addListener(() => undefined);
85
+ acceptForwarded(collector, clock, onError);
86
+ }
87
+ /**
88
+ * Returns the collector, which sets the uninstall page now and after each `setState` when `pageUrl` is given, and
89
+ * `refresh`, which sets it again. Chrome keeps the address as it was set, so the query must follow the user's state
90
+ * and the active days.
91
+ */
92
+ function withUninstallPage(collector, pageUrl, onError) {
93
+ if (pageUrl === undefined) {
94
+ return { collector, refresh: async () => undefined };
95
+ }
96
+ // Every write of this context goes in turn on one chain. A write that started before the latest `setState` is
97
+ // dropped, so a slow refresh never puts back the fields of a state the user has left.
98
+ let writes = Promise.resolve();
99
+ let changes = 0;
100
+ const write = (params) => {
101
+ const startedAt = changes;
102
+ const earlier = writes;
103
+ writes = (async () => {
104
+ // A failed write must not stop the next one, nor the `setState` that waits for it.
105
+ await earlier.catch(() => undefined);
106
+ const fields = await params();
107
+ if (startedAt === changes) {
108
+ await setUninstallUrl(pageUrl, fields, onError);
109
+ }
110
+ })();
111
+ return writes.catch((error) => reportTo(onError, error));
112
+ };
113
+ const refresh = () => write(() => collector.uninstallParams());
114
+ void refresh();
115
+ return {
116
+ collector: {
117
+ ...collector,
118
+ setState: async (state) => {
119
+ changes++;
120
+ if (state === AnalyticsState.OptedOut || state === AnalyticsState.Anonymous) {
121
+ // A change of state can take 30 seconds or more, as for the opted_out or forget request it sends, and the
122
+ // page must not carry the earlier state's fields meanwhile. The page alone carries fewer than any state's.
123
+ await write(async () => undefined);
124
+ }
125
+ await collector.setState(state);
126
+ await refresh();
127
+ },
128
+ },
129
+ refresh,
130
+ };
131
+ }
132
+ /** Tells whether a change of the stored queue adds an event to it, as a new envelope or one more event of an envelope. */
133
+ function addsEvents({ oldValue, newValue }) {
134
+ const queueOf = (value) => parseQueue(typeof value === "string" ? value : undefined) ?? [];
135
+ const before = new Map(queueOf(oldValue).map(({ qid, envelope }) => [qid, envelope.events.length]));
136
+ return queueOf(newValue).some(({ qid, envelope }) => envelope.events.length > (before.get(qid) ?? 0));
36
137
  }
37
138
  /** Tells whether the caller runs in the extension's service worker, the one context that may set the access level. */
38
139
  function isServiceWorker() {
39
- const scope = Reflect.get(globalThis, 'ServiceWorkerGlobalScope');
40
- return typeof scope === 'function' && globalThis instanceof scope;
140
+ const scope = Reflect.get(globalThis, "ServiceWorkerGlobalScope");
141
+ return typeof scope === "function" && globalThis instanceof scope;
41
142
  }
42
143
  /**
43
144
  * Lets only the extension's own pages and worker read and write `chrome.storage.local`, and resolves once Chrome has
@@ -46,10 +147,10 @@ function isServiceWorker() {
46
147
  async function closeToContentScripts(onError) {
47
148
  try {
48
149
  const local = chromeApi().storage.local;
49
- if (typeof local.setAccessLevel !== 'function') {
50
- throw new TypeError('artel: chrome.storage.local.setAccessLevel is missing, so content scripts can write it');
150
+ if (typeof local.setAccessLevel !== "function") {
151
+ throw new TypeError("artel: chrome.storage.local.setAccessLevel is missing, so content scripts can write it");
51
152
  }
52
- await local.setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' });
153
+ await local.setAccessLevel({ accessLevel: "TRUSTED_CONTEXTS" });
53
154
  }
54
155
  catch (error) {
55
156
  reportTo(onError, error);
@@ -76,7 +177,7 @@ export function newChromeStorageAdapter() {
76
177
  return {
77
178
  get: async (key) => {
78
179
  const value = (await chromeApi().storage.local.get(key))[key];
79
- return typeof value === 'string' ? value : undefined;
180
+ return typeof value === "string" ? value : undefined;
80
181
  },
81
182
  set: async (key, value) => {
82
183
  await chromeApi().storage.local.set({ [key]: value });
@@ -89,27 +190,51 @@ export function newChromeStorageAdapter() {
89
190
  */
90
191
  export async function forwardTrack(name, params) {
91
192
  try {
92
- await chromeApi().runtime.sendMessage({ type: FORWARD_TYPE, name, ...(params !== undefined && { params }) });
193
+ await chromeApi().runtime.sendMessage({
194
+ type: FORWARD_TYPE,
195
+ name,
196
+ ...(params !== undefined && { params }),
197
+ });
93
198
  }
94
199
  catch {
95
200
  // The send fails while the service worker updates or is gone. The content script drops the event and does not fail.
96
201
  }
97
202
  }
98
203
  /**
99
- * Returns the collector of a content script. Its `track` hands each event to the service worker with `forwardTrack`,
100
- * and the worker's collector checks, queues and sends it under the user's choice, so `flush` does nothing here. The
101
- * user's choice lives in the worker and the extension pages, so a content script can neither read nor change it. It
102
- * reads no storage, needs no key, version or endpoint, and never throws.
204
+ * Returns the collector of a content script. Its `track` applies a call's `throttleMs` in the script's memory, by
205
+ * `clock`, then hands the event to the worker with `forwardTrack`. The worker checks, queues and sends it under the
206
+ * user's analytics state, which a content script can neither read nor change. It reads no storage, needs no key,
207
+ * version or endpoint, never throws, and drops a call with a bad `throttleMs` without a report, having no `onError`.
103
208
  */
104
- export function newContentScriptCollector() {
105
- return { track: forwardTrack, flush: async () => undefined };
209
+ export function newContentScriptCollector({ clock = systemClock, } = {}) {
210
+ const throttle = newThrottle();
211
+ return {
212
+ track: async (name, params, options) => {
213
+ const now = clock.now();
214
+ const asked = throttleOf(options);
215
+ if (asked === undefined) {
216
+ return;
217
+ }
218
+ const call = { name, throttleMs: asked.throttleMs, now };
219
+ if (throttle.isDropped(call)) {
220
+ return;
221
+ }
222
+ // The window opens for an event that passes the worker's check. Only the worker knows the user's state, so an
223
+ // event the worker drops in the opted_out state opens a window too.
224
+ if (isForwardable(name, params)) {
225
+ throttle.went(call);
226
+ }
227
+ await forwardTrack(name, params);
228
+ },
229
+ };
106
230
  }
107
231
  /**
108
232
  * Tracks the events content scripts forward with `forwardTrack`, at most 60 a minute. It takes them only from this
109
233
  * extension, and only the product's own events: never a system event of the intake, such as `installed` or
110
- * `uninstalled`, which a content script has no reason to send. Returns the function that stops it.
234
+ * `uninstalled`, which a content script has no reason to send. The limit guards the queue against a flood, and the
235
+ * first event it drops in a minute goes to `onError`, so the drop is not silent.
111
236
  */
112
- export function acceptForwarded(collector, { clock = systemClock } = {}) {
237
+ function acceptForwarded(collector, clock, onError) {
113
238
  let minuteStart = Number.NEGATIVE_INFINITY;
114
239
  let tracked = 0;
115
240
  const onMessage = (message, sender) => {
@@ -123,55 +248,79 @@ export function acceptForwarded(collector, { clock = systemClock } = {}) {
123
248
  tracked = 0;
124
249
  }
125
250
  if (tracked < FORWARDS_PER_MINUTE) {
126
- tracked++;
127
251
  void collector.track(message.name, message.params);
128
252
  }
253
+ else if (tracked === FORWARDS_PER_MINUTE) {
254
+ reportTo(onError, new Error(`artel: the worker tracks at most ${FORWARDS_PER_MINUTE} forwarded events a minute, so it dropped the rest`));
255
+ }
256
+ tracked++;
129
257
  return undefined;
130
258
  };
131
259
  chromeApi().runtime.onMessage.addListener(onMessage);
132
- return () => chromeApi().runtime.onMessage.removeListener(onMessage);
133
260
  }
134
261
  /**
135
- * Sets the uninstall page to `pageUrl` with the fields of `uninstallParams()` added to its query, or to `pageUrl` alone
136
- * when `uninstallParams()` resolves to undefined. Chrome keeps the address as it was set, so the service worker calls
137
- * this on each start and after each change of state. It resolves and never rejects. A failure of `uninstallParams()`
138
- * goes to the collector's `onError`, and any other failure to its own `onError`.
262
+ * Sets the uninstall page to `pageUrl` with `params` added to its query, or to `pageUrl` alone without them. It
263
+ * resolves and never rejects: a failure, such as a `pageUrl` that is not a URL, goes to `onError`.
139
264
  */
140
- export async function refreshUninstallUrl(collector, pageUrl, { onError } = {}) {
265
+ async function setUninstallUrl(pageUrl, params, onError) {
141
266
  try {
142
- const url = new URL(pageUrl);
143
- const params = await collector.uninstallParams();
144
- for (const [name, value] of Object.entries(params ?? {})) {
145
- url.searchParams.set(name, String(value));
146
- }
147
- await chromeApi().runtime.setUninstallURL(url.toString());
267
+ // oxlint-disable-next-line no-new -- The constructor throws for a page that is not a URL. The page goes as written.
268
+ new URL(pageUrl);
269
+ await chromeApi().runtime.setUninstallURL(withQueryAdded(pageUrl, params));
148
270
  }
149
271
  catch (error) {
150
272
  reportTo(onError, error);
151
273
  }
152
274
  }
275
+ /**
276
+ * Returns `pageUrl` with `params` added at the end of its query, before any fragment. The page's own query stays as
277
+ * written, since a page may read it in a form that `URLSearchParams` would write another way.
278
+ */
279
+ function withQueryAdded(pageUrl, params) {
280
+ const query = new URLSearchParams(Object.entries(params ?? {}).map(([name, value]) => [name, String(value)])).toString();
281
+ if (query === "") {
282
+ return pageUrl;
283
+ }
284
+ const hashAt = pageUrl.indexOf("#");
285
+ const beforeFragment = hashAt === -1 ? pageUrl : pageUrl.slice(0, hashAt);
286
+ const fragment = hashAt === -1 ? "" : pageUrl.slice(hashAt);
287
+ return `${beforeFragment}${joinerAfter(beforeFragment)}${query}${fragment}`;
288
+ }
289
+ /** Returns what goes between `address` and an added query: `?`, `&`, or nothing after a `?` or `&` it ends in. */
290
+ function joinerAfter(address) {
291
+ if (!address.includes("?")) {
292
+ return "?";
293
+ }
294
+ return address.endsWith("?") || address.endsWith("&") ? "" : "&";
295
+ }
153
296
  /** Returns the global `chrome` API, or throws outside an extension context. */
154
297
  function chromeApi() {
155
- const chrome = Reflect.get(globalThis, 'chrome');
298
+ const chrome = Reflect.get(globalThis, "chrome");
156
299
  if (!isChromeApi(chrome)) {
157
- throw new Error('artel: the chrome extension API is not available here');
300
+ throw new Error("artel: the chrome extension API is not available here");
158
301
  }
159
302
  return chrome;
160
303
  }
161
304
  /** Checks only that the extension runtime is there. A missing `storage` permission surfaces when storage is used. */
162
305
  function isChromeApi(value) {
163
- return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'runtime') === 'object';
306
+ return (typeof value === "object" && value !== null && typeof Reflect.get(value, "runtime") === "object");
164
307
  }
165
308
  /**
166
- * Checks a forwarded message against what the intake takes, as `track` does, and refuses the names in
167
- * `REFUSED_NAMES`. Content scripts run among the page's scripts, so the worker cannot trust what they send.
309
+ * Checks a forwarded message against what the worker takes, as `isForwardable` does. Content scripts run among the
310
+ * page's scripts, so the worker cannot trust what they send.
168
311
  */
169
312
  function isForwarded(message) {
170
- if (typeof message !== 'object' || message === null || Reflect.get(message, 'type') !== FORWARD_TYPE) {
313
+ if (typeof message !== "object" ||
314
+ message === null ||
315
+ Reflect.get(message, "type") !== FORWARD_TYPE) {
171
316
  return false;
172
317
  }
173
- const name = Reflect.get(message, 'name');
174
- return (typeof name === 'string' &&
175
- !REFUSED_NAMES.has(name) &&
176
- eventProblem(name, Reflect.get(message, 'params')) === undefined);
318
+ return isForwardable(Reflect.get(message, "name"), Reflect.get(message, "params"));
319
+ }
320
+ /**
321
+ * Tells whether the worker takes a forwarded event: one `track` takes, with a name outside `REFUSED_NAMES`, the
322
+ * intake's system events.
323
+ */
324
+ function isForwardable(name, params) {
325
+ return (typeof name === "string" && !REFUSED_NAMES.has(name) && checkEvent(name, params) === undefined);
177
326
  }
package/dist/fields.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { ActiveDaysBucket, type PageFields } from './collectorTypes.js';
2
- import type { EventParams, UsageEvent } from './envelope.js';
3
- import type { EventStamp } from './installState.js';
1
+ import { ActiveDaysBucket, type PageFields } from "./collectorTypes.js";
2
+ import type { EventParams, UsageEvent } from "./envelope.js";
3
+ import type { EventStamp } from "./installState.js";
4
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
5
  export declare function isVersion(value: unknown): value is string;
6
6
  /** Checks a language tag, such as `en`, `pt-BR` or `zh-Hant-TW`, against the format and length the intake takes. */
package/dist/fields.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Period, daysBetween, formatDay, monthsBetween } from './calendar.js';
2
- import { ActiveDaysBucket } from './collectorTypes.js';
1
+ import { Period, daysBetween, formatDay, monthsBetween } from "./calendar.js";
2
+ import { ActiveDaysBucket } from "./collectorTypes.js";
3
3
  // The intake takes `version` and the language fields only in these formats. The intake refuses an envelope with a field
4
4
  // that breaks them, and all its events are lost. So the collector drops a bad language, and its constructor throws for
5
5
  // a bad version.
@@ -9,18 +9,18 @@ const LANGUAGE_FORMAT = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$/;
9
9
  const MAX_LANGUAGE_LENGTH = 16;
10
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
11
  export function isVersion(value) {
12
- return typeof value === 'string' && value.length <= MAX_VERSION_LENGTH && VERSION_FORMAT.test(value);
12
+ return (typeof value === "string" && value.length <= MAX_VERSION_LENGTH && VERSION_FORMAT.test(value));
13
13
  }
14
14
  /** Checks a language tag, such as `en`, `pt-BR` or `zh-Hant-TW`, against the format and length the intake takes. */
15
15
  export function isLanguage(value) {
16
- return typeof value === 'string' && value.length <= MAX_LANGUAGE_LENGTH && LANGUAGE_FORMAT.test(value);
16
+ return (typeof value === "string" && value.length <= MAX_LANGUAGE_LENGTH && LANGUAGE_FORMAT.test(value));
17
17
  }
18
18
  /** Returns the tag with `-` for each `_`, as `en_US` becomes `en-US`. The intake reads the tag this way too. */
19
19
  export function languageTag(value) {
20
- return typeof value === 'string' ? value.replaceAll('_', '-') : value;
20
+ return typeof value === "string" ? value.replaceAll("_", "-") : value;
21
21
  }
22
22
  export function primaryLanguage(tag) {
23
- return tag.split('-')[0] ?? tag;
23
+ return tag.split("-")[0] ?? tag;
24
24
  }
25
25
  /** The highest exact age in days. The intake reads 31 as 31 days or more. */
26
26
  const MAX_AGE_DAYS = 31;
@@ -45,7 +45,7 @@ export function ageInDays(days, { isExact }) {
45
45
  */
46
46
  export function uninstalledParams(params, { isExact }) {
47
47
  const age = params?.age_days;
48
- return typeof age === 'number' ? { ...params, age_days: ageInDays(age, { isExact }) } : params;
48
+ return typeof age === "number" ? { ...params, age_days: ageInDays(age, { isExact }) } : params;
49
49
  }
50
50
  /** Returns the age capped at 25 months when `isExact`, and its bucket otherwise. */
51
51
  function ageInMonths(months, { isExact }) {
@@ -1,7 +1,7 @@
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';
1
+ import { type Browser } from "./browser.js";
2
+ import type { CollectorOptions, Delivery, GetId } from "./collectorTypes.js";
3
+ import type { Build } from "./stateFields.js";
4
+ import type { StorageAdapter } from "./storage.js";
5
5
  type ReportError = (error: unknown) => void;
6
6
  /**
7
7
  * Returns `value` as JSON, cut to its first 64 characters with `…` after a cut, or its type where JSON cannot write it,
@@ -20,12 +20,21 @@ export declare function accepted(name: string, value: string | undefined, check:
20
20
  * platform that names none. A mistake in the build then fails its first run and its tests.
21
21
  */
22
22
  export declare function checkedBuild(options: CollectorOptions): Build;
23
+ /**
24
+ * Throws the `TypeError` a constructor throws for a key, a version, a platform, an endpoint or a transport the intake
25
+ * would refuse every envelope of, and returns otherwise. It reads no host API, so a product's build or test can call it.
26
+ */
27
+ export declare function checkOptions(options: Pick<CollectorOptions, "key" | "version" | "platform"> & Delivery): void;
28
+ /** Tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`. */
29
+ export declare function isTestKey(key: string): boolean;
23
30
  /**
24
31
  * Returns a function that gives the host's browser as the intake keeps it, or undefined when there is none. A function
25
32
  * the host passes runs only at the first call, which the collector makes only for an event with an id. Reports and
26
33
  * leaves out a value that is not a browser, which only a host outside TypeScript passes.
27
34
  */
28
35
  export declare function newBrowserReader(browser: Browser | (() => Browser | undefined) | undefined, reportError: ReportError): () => Browser | undefined;
36
+ /** Tells whether `id` is an id the intake takes: a string of 1 to 64 characters. */
37
+ export declare function isUsableId(id: unknown): id is string;
29
38
  /**
30
39
  * Returns a `getId` that gives a non-empty string of at most 64 characters, or undefined. A host outside TypeScript may
31
40
  * return null or an empty string, which then reads as an id the product does not know yet.