@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.
package/dist/browser.js CHANGED
@@ -1,24 +1,24 @@
1
1
  /** The browsers the intake tells apart. Any other browser is `other`. */
2
2
  export const BrowserName = {
3
- Chrome: 'chrome',
4
- Edge: 'edge',
5
- Opera: 'opera',
6
- Yandex: 'yandex',
7
- Brave: 'brave',
8
- Firefox: 'firefox',
9
- Safari: 'safari',
10
- Other: 'other',
3
+ Chrome: "chrome",
4
+ Edge: "edge",
5
+ Opera: "opera",
6
+ Yandex: "yandex",
7
+ Brave: "brave",
8
+ Firefox: "firefox",
9
+ Safari: "safari",
10
+ Other: "other",
11
11
  };
12
12
  /**
13
13
  * The brands of a Chromium browser, each browser's own ahead of Google Chrome. A browser that lists both goes by its
14
14
  * own.
15
15
  */
16
16
  const BRANDS = [
17
- ['Microsoft Edge', BrowserName.Edge],
18
- ['Opera', BrowserName.Opera],
19
- ['YaBrowser', BrowserName.Yandex],
20
- ['Brave', BrowserName.Brave],
21
- ['Google Chrome', BrowserName.Chrome],
17
+ ["Microsoft Edge", BrowserName.Edge],
18
+ ["Opera", BrowserName.Opera],
19
+ ["YaBrowser", BrowserName.Yandex],
20
+ ["Brave", BrowserName.Brave],
21
+ ["Google Chrome", BrowserName.Chrome],
22
22
  ];
23
23
  /**
24
24
  * User-Agent tokens of the browsers that name themselves there. Chrome goes by its brands: every Chromium browser's
@@ -43,11 +43,11 @@ export function detectBrowser(nav) {
43
43
  }
44
44
  // This check names a Chromium browser with no brand of its own `other`, and skips its User-Agent string. Such a
45
45
  // browser copies Chrome's User-Agent string, so that string names no browser.
46
- const chromiumBrands = new Set(['Chromium', ...BRANDS.map(([brand]) => brand)]);
46
+ const chromiumBrands = new Set(["Chromium", ...BRANDS.map(([brand]) => brand)]);
47
47
  if (nav.userAgentData?.brands?.some((entry) => chromiumBrands.has(entry.brand)) === true) {
48
48
  return { name: BrowserName.Other };
49
49
  }
50
- if (nav.userAgent === undefined || nav.userAgent === '') {
50
+ if (nav.userAgent === undefined || nav.userAgent === "") {
51
51
  return undefined;
52
52
  }
53
53
  return fromUserAgent(nav.userAgent);
@@ -62,7 +62,9 @@ function fromUserAgent(userAgent) {
62
62
  // The check names Safari only without a Chrome or Chromium token. A Chromium browser's User-Agent string carries
63
63
  // Safari's tokens too. One regular expression per token keeps a long User-Agent string free of backtracking.
64
64
  const version = /\bVersion\/(\d+)/.exec(userAgent)?.[1];
65
- if (version !== undefined && /\bSafari\//.test(userAgent) && !/\b(?:Chrome|Chromium)\//.test(userAgent)) {
65
+ if (version !== undefined &&
66
+ /\bSafari\//.test(userAgent) &&
67
+ !/\b(?:Chrome|Chromium)\//.test(userAgent)) {
66
68
  return withMajor(BrowserName.Safari, version);
67
69
  }
68
70
  return { name: BrowserName.Other };
@@ -72,11 +74,11 @@ function fromUserAgent(userAgent) {
72
74
  * 1 to 999 left out. Returns undefined for a value that is not an object, which only a host outside TypeScript passes.
73
75
  */
74
76
  export function copyBrowser(value) {
75
- if (typeof value !== 'object' || value === null) {
77
+ if (typeof value !== "object" || value === null) {
76
78
  return undefined;
77
79
  }
78
- const name = Reflect.get(value, 'name');
79
- const major = Reflect.get(value, 'major');
80
+ const name = Reflect.get(value, "name");
81
+ const major = Reflect.get(value, "major");
80
82
  const known = Object.values(BrowserName).find((candidate) => candidate === name && candidate !== BrowserName.Other);
81
83
  if (known === undefined) {
82
84
  return { name: BrowserName.Other };
@@ -90,10 +92,10 @@ function withMajor(name, version) {
90
92
  }
91
93
  /** Returns the major version, or undefined when the string has none from 1 to 999, the range the intake takes. */
92
94
  function majorOf(version) {
93
- const major = Number.parseInt(version ?? '', 10);
95
+ const major = Number.parseInt(version ?? "", 10);
94
96
  return isMajor(major) ? major : undefined;
95
97
  }
96
98
  /** Checks for a whole number from 1 to 999, the range the intake takes. */
97
99
  function isMajor(value) {
98
- return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 999;
100
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 999;
99
101
  }
@@ -6,11 +6,11 @@ export interface CalendarDate {
6
6
  }
7
7
  /** The periods an event can be the first of, in the order the intake lists them. */
8
8
  export declare const Period: {
9
- readonly Day: 'day';
10
- readonly Week: 'week';
11
- readonly Month: 'month';
12
- readonly Quarter: 'quarter';
13
- readonly Year: 'year';
9
+ readonly Day: "day";
10
+ readonly Week: "week";
11
+ readonly Month: "month";
12
+ readonly Quarter: "quarter";
13
+ readonly Year: "year";
14
14
  };
15
15
  export type Period = (typeof Period)[keyof typeof Period];
16
16
  /**
package/dist/calendar.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /** The periods an event can be the first of, in the order the intake lists them. */
2
2
  export const Period = {
3
- Day: 'day',
4
- Week: 'week',
5
- Month: 'month',
6
- Quarter: 'quarter',
7
- Year: 'year',
3
+ Day: "day",
4
+ Week: "week",
5
+ Month: "month",
6
+ Quarter: "quarter",
7
+ Year: "year",
8
8
  };
9
9
  const DAY_MS = 86_400_000;
10
10
  /**
@@ -26,7 +26,7 @@ export function formatDay(date) {
26
26
  }
27
27
  /** Parses a `YYYY-MM-DD` day, or returns undefined when the text is missing or has another form. */
28
28
  export function parseDay(text) {
29
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text ?? '');
29
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text ?? "");
30
30
  if (!match) {
31
31
  return undefined;
32
32
  }
@@ -71,5 +71,5 @@ function utcMidnight(date) {
71
71
  return Date.UTC(date.year, date.month - 1, date.day);
72
72
  }
73
73
  function pad(value) {
74
- return String(value).padStart(2, '0');
74
+ return String(value).padStart(2, "0");
75
75
  }
@@ -1,13 +1,16 @@
1
- import { Mode, type Collector, type CollectorOptions } from './collectorTypes.js';
1
+ import { Mode, type Collector, type CollectorOptions } from "./collectorTypes.js";
2
2
  /**
3
3
  * Returns a collector. Throws a `TypeError` that names the option for options that would make the intake refuse every
4
4
  * envelope, such as a bad key, version or endpoint, and for options only a host outside TypeScript passes. A language
5
5
  * that breaks the intake's format is left out and goes to `onError`, since it often comes from the browser.
6
6
  */
7
- export declare function newCollector(options: CollectorOptions & {
8
- mode: typeof Mode.Identified;
9
- }): Collector<'identified'>;
10
- export declare function newCollector(options: CollectorOptions & {
11
- mode: typeof Mode.Anonymous;
12
- }): Collector<'anonymous'>;
13
- export declare function newCollector(options: CollectorOptions): Collector;
7
+ export declare function newCollector<M extends Mode>(options: CollectorOptions & {
8
+ mode: M;
9
+ }): Collector<M>;
10
+ /**
11
+ * Returns a collector, as `newCollector` does, that calls `onNewDay` inside its lock each time it queues the first
12
+ * event of a local day. That event adds the day to the active days.
13
+ */
14
+ export declare function newCollectorNotingDays(options: CollectorOptions, onNewDay: () => void): Collector;
15
+ /** Returns the longest an event waits in the queue before a send starts, as the options set it. */
16
+ export declare function sendDelayMsOf({ sendDelaySeconds, }: Pick<CollectorOptions, "sendDelaySeconds">): number;
package/dist/collector.js CHANGED
@@ -1,55 +1,53 @@
1
- import { daysBetween, formatDay, localDateAt } from './calendar.js';
2
- import { LifecycleEvent, UNINSTALLED } from './envelope.js';
3
- import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams } from './fields.js';
4
- import { accepted, checkedBuild, newBrowserReader, newStringStorage, quoted, reportTo, usableId } from './hostInput.js';
5
- import { systemClock } from './clock.js';
6
- import { newChannelStorage } from './storage.js';
7
- import { AnalyticsState, Mode } from './collectorTypes.js';
8
- import { copyOfParams, eventProblem } from './eventCheck.js';
9
- import { newInstallState } from './installState.js';
10
- import { exclusive } from './lock.js';
11
- import { newOutbox } from './outbox.js';
12
- import { newPageReader } from './page.js';
13
- import { carriesPage, channelTakes, fieldsForState } from './stateFields.js';
14
- import { newHttpTransport } from './transport.js';
1
+ import { daysBetween, formatDay, localDateAt, Period } from "./calendar.js";
2
+ import { LifecycleEvent, UNINSTALLED } from "./envelope.js";
3
+ import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams, } from "./fields.js";
4
+ import { accepted, checkedBuild, isUsableId, newBrowserReader, newStringStorage, quoted, reportTo, usableId, } from "./hostInput.js";
5
+ import { systemClock } from "./clock.js";
6
+ import { newChannelStorage } from "./storage.js";
7
+ import { AnalyticsState, Mode } from "./collectorTypes.js";
8
+ import { acceptedEvent } from "./eventCheck.js";
9
+ import { newInstallState } from "./installState.js";
10
+ import { exclusive } from "./lock.js";
11
+ import { newOutbox } from "./outbox.js";
12
+ import { newPageReader } from "./page.js";
13
+ import { carriesPage, channelTakes, fieldsForState, isAnalyticsState, } from "./stateFields.js";
14
+ import { newThrottle } from "./throttle.js";
15
+ import { transportsOf } from "./transport.js";
15
16
  const SESSION_IDLE_MINUTES = 10;
16
17
  const SEND_DELAY_SECONDS = 5;
17
18
  export function newCollector(options) {
19
+ return newCollectorNotingDays(options, () => undefined);
20
+ }
21
+ /**
22
+ * Returns a collector, as `newCollector` does, that calls `onNewDay` inside its lock each time it queues the first
23
+ * event of a local day. That event adds the day to the active days.
24
+ */
25
+ export function newCollectorNotingDays(options, onNewDay) {
18
26
  const product = checkedBuild(options);
19
27
  const { mode } = options;
20
- const transport = options.transport ?? newHttpTransport(options.endpoint);
28
+ const transports = transportsOf(options);
21
29
  const storage = newChannelStorage(newStringStorage(options.storage), options.key);
22
30
  const clock = options.clock ?? systemClock;
23
31
  const reportError = (error) => reportTo(options.onError, error);
24
32
  const lock = exclusive(options.lock);
25
33
  const getId = options.mode === Mode.Identified ? usableId(options.getId, reportError) : undefined;
26
- const readBrowser = options.mode === Mode.Identified ? newBrowserReader(options.browser, reportError) : undefined;
27
- const browserLanguage = accepted('browserLanguage', languageTag(options.browserLanguage), isLanguage, reportError);
28
- const uiLanguage = accepted('uiLanguage', languageTag(options.uiLanguage), isLanguage, reportError);
34
+ const readBrowser = options.mode === Mode.Anonymous ? undefined : newBrowserReader(options.browser, reportError);
35
+ const browserLanguage = accepted("browserLanguage", languageTag(options.browserLanguage), isLanguage, reportError);
36
+ const uiLanguage = accepted("uiLanguage", languageTag(options.uiLanguage), isLanguage, reportError);
29
37
  const install = newInstallState({
30
38
  storage,
31
39
  sessionIdleMs: durationOr(options.sessionIdleMinutes, SESSION_IDLE_MINUTES) * 60_000,
32
40
  });
33
41
  const outbox = newOutbox({
42
+ key: options.key,
34
43
  storage,
35
44
  lock,
36
- transport,
37
- identify: () => lock(async () => {
38
- // The check names no user once the state has left identified. The state can change in this or another context
39
- // after the lease.
40
- if (!(await currentFields()).mayName) {
41
- return undefined;
42
- }
43
- const id = await getId?.();
44
- if (id === undefined) {
45
- return undefined;
46
- }
47
- await noteId(id);
48
- const browser = readBrowser?.();
49
- return { id, ...(browser !== undefined && { browser }) };
50
- }),
45
+ ...transports,
46
+ // The current state decides the id, so an envelope names no user once the state has left the one it was recorded
47
+ // in. The state can change in this or another context after the lease.
48
+ identify: () => lock(async () => identityIn(await currentFields())),
51
49
  giveBack: (items) => giveBack(items),
52
- sendDelayMs: durationOr(options.sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000,
50
+ sendDelayMs: sendDelayMsOf(options),
53
51
  clock,
54
52
  reportError,
55
53
  });
@@ -59,27 +57,31 @@ export function newCollector(options) {
59
57
  ? newPageReader({ getPage: options.getPage, reportError })
60
58
  : undefined;
61
59
  const pageOf = (name) => pages?.read(name);
60
+ const throttle = newThrottle();
62
61
  // The install day is the local date of the first call of any method, so it waits on no particular event.
63
62
  let isInstallDayKnown = false;
63
+ /**
64
+ * Stores the install day, settles the stored state and schedules the first send, once per collector. The caller
65
+ * holds the lock.
66
+ */
67
+ async function startOnce() {
68
+ if (isInstallDayKnown) {
69
+ return;
70
+ }
71
+ await install.installDayOr(localDateAt(clock.now()));
72
+ await settleStoredState();
73
+ isInstallDayKnown = true;
74
+ // The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and its
75
+ // events go with the first send after the lease runs out.
76
+ outbox.sendSoon();
77
+ }
64
78
  function serialize(operation, fallback) {
65
- const withInstallDay = async () => {
66
- if (!isInstallDayKnown) {
67
- await install.installDayOr(localDateAt(clock.now()));
68
- await dropStateTheChannelNoLongerTakes();
69
- if ((await currentState()) === AnalyticsState.OptedOut) {
70
- // A run stopped between storing the opted_out state and dropping the queue left events that must not go.
71
- await discardForOptOut();
72
- }
73
- isInstallDayKnown = true;
74
- // The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and
75
- // its events go with the first send after the lease runs out.
76
- outbox.sendSoon();
77
- }
78
- return operation();
79
- };
80
79
  // Each operation reads and writes several storage keys. The lock keeps two events from both taking the same
81
80
  // first-of-day mark.
82
- return lock(withInstallDay).catch((error) => {
81
+ return lock(async () => {
82
+ await startOnce();
83
+ return operation();
84
+ }).catch((error) => {
83
85
  reportError(error);
84
86
  return fallback;
85
87
  });
@@ -89,9 +91,9 @@ export function newCollector(options) {
89
91
  await install.giveBack(items.map((item) => item.envelope));
90
92
  }
91
93
  /**
92
- * Stores the id `getId` gave. An id other than the last one means another user: the events of the last one, and
93
- * those that waited for an id after it, are dropped, so none goes under another user's id. The session ends, so no
94
- * session holds the events of two users.
94
+ * Stores the id an envelope names the user by. An id other than the last one means another user: the events of the
95
+ * last one, and those that waited for an id after it, are dropped, so none goes under another user's id. The session
96
+ * ends, so no session holds the events of two users.
95
97
  */
96
98
  async function noteId(id) {
97
99
  const last = await install.lastId();
@@ -104,32 +106,80 @@ export function newCollector(options) {
104
106
  }
105
107
  await install.setLastId(id);
106
108
  }
107
- /** Drops the queued events that name the user or wait for an id, and the last id with them. */
109
+ /**
110
+ * Resolves to the id the state of `fields` names the user by, with its kind and the browser, or to undefined while
111
+ * there is none. The pseudonymous state's id is the install id, which the collector makes once. A new id counts as
112
+ * another user, as `noteId` describes.
113
+ */
114
+ async function identityIn({ idKind }) {
115
+ if (idKind === undefined) {
116
+ return undefined;
117
+ }
118
+ const id = idKind === AnalyticsState.Pseudonymous ? await install.installId() : await getId?.();
119
+ if (id === undefined) {
120
+ return undefined;
121
+ }
122
+ await noteId(id);
123
+ const browser = readBrowser?.();
124
+ return { id, id_kind: idKind, ...(browser !== undefined && { browser }) };
125
+ }
126
+ /**
127
+ * Forgets the last id, as `forget` does, and drops the queued events that name the user or wait for an id. Deletes
128
+ * the install id, so a later pseudonymous state takes a new one.
129
+ */
108
130
  async function leaveIdentity() {
131
+ const last = await install.lastId();
132
+ if (isUsableId(last)) {
133
+ await giveBack(await outbox.forget(last));
134
+ }
109
135
  await giveBack(await outbox.discardIdentified());
110
- await install.setLastId('');
136
+ // The install id goes before the last id. A run that stops between them then keeps the last id, and the next run
137
+ // leaves it again.
138
+ await install.dropInstallId();
139
+ await install.setLastId("");
111
140
  }
112
- /** Drops what was not sent, except an `opted_out`, and the last id with it. */
113
- async function discardForOptOut() {
114
- await giveBack(await outbox.discard());
115
- await install.setLastId('');
141
+ /**
142
+ * Stores `next` and leaves the id of `previous`, and resolves to whether `previous` had one. A change between the two
143
+ * states with an id leaves first. A run that stops in between keeps the old state with its id forgotten, so no event
144
+ * goes under the other state's id. Any other change stores first, so an opt-out stays, and the next run leaves the id
145
+ * the stored state no longer has.
146
+ */
147
+ async function storeState(previous, next) {
148
+ const hadId = fieldsIn(previous).idKind !== undefined;
149
+ const isSwitch = hadId && fieldsIn(next).idKind !== undefined;
150
+ if (isSwitch) {
151
+ await leaveIdentity();
152
+ }
153
+ await install.setState(next);
154
+ if (hadId && !isSwitch) {
155
+ await leaveIdentity();
156
+ }
157
+ return hadId;
116
158
  }
117
159
  /**
118
- * Stores an identified state as anonymous when this channel is anonymous, as after the product changed its mode.
119
- * Drops the queued events that name the user or wait for an id, which this channel can never send.
160
+ * Finishes a change of state that a stopped run or a change of the channel's mode left. Stores a state this channel
161
+ * no longer takes as anonymous. Leaves the last id in a state without one, and drops the queue in the opted_out
162
+ * state.
120
163
  */
121
- async function dropStateTheChannelNoLongerTakes() {
164
+ async function settleStoredState() {
122
165
  const stored = await install.state();
123
- if (stored === AnalyticsState.Identified && !takes(stored)) {
124
- await leaveIdentity();
166
+ const isUntaken = isAnalyticsState(stored) && !takes(stored);
167
+ if (isUntaken) {
125
168
  await install.setState(AnalyticsState.Anonymous);
126
169
  await install.endSession();
127
170
  }
171
+ const state = await currentState();
172
+ if (isUntaken || (fieldsIn(state).idKind === undefined && isUsableId(await install.lastId()))) {
173
+ await leaveIdentity();
174
+ }
175
+ if (state === AnalyticsState.OptedOut) {
176
+ await giveBack(await outbox.discard());
177
+ }
128
178
  }
129
179
  async function currentState() {
130
180
  const stored = await install.state();
131
- // The function reads an identified state this channel does not take as anonymous. Such a state stays after the
132
- // product changes its mode.
181
+ // The function reads a state this channel does not take as anonymous. Such a state stays after the product changes
182
+ // its mode.
133
183
  return takes(stored) ? stored : AnalyticsState.Anonymous;
134
184
  }
135
185
  function takes(state) {
@@ -156,12 +206,9 @@ export function newCollector(options) {
156
206
  if (view?.isRepeatedView === true) {
157
207
  return false;
158
208
  }
159
- // The identified state names the user once the product knows the id. Another user's id gives back the marks of the
160
- // last user's dropped events, the install and version marks included, before this event takes its own.
161
- const id = fields.mayName ? await getId?.() : undefined;
162
- if (id !== undefined) {
163
- await noteId(id);
164
- }
209
+ // A state with an id names the user once the id is known. Another user's id gives back the marks of the last user's
210
+ // dropped events, the install and version marks included, before this event takes its own.
211
+ const identity = await identityIn(fields);
165
212
  const productVersion = fields.product.version;
166
213
  // A `takeMark` that fails took no mark, so nothing goes back.
167
214
  if (takeMark !== undefined && !(await takeMark(productVersion))) {
@@ -169,8 +216,10 @@ export function newCollector(options) {
169
216
  }
170
217
  let event;
171
218
  let dropped;
219
+ let isNewDay = false;
172
220
  try {
173
221
  const stamp = await install.stamp(clock.now());
222
+ isNewDay = stamp.first.includes(Period.Day);
174
223
  event = newEvent({
175
224
  name,
176
225
  // The `uninstalled` age gets the precision of the envelope's ages, so a state that sends no exact age does not
@@ -180,24 +229,30 @@ export function newCollector(options) {
180
229
  page: fields.mayCarryPage ? view?.fields : undefined,
181
230
  isAgeExact: fields.isAgeExact,
182
231
  });
183
- const browser = id === undefined ? undefined : readBrowser?.();
232
+ const { browser, ...id } = identity ?? {};
184
233
  dropped = await outbox.add({
185
234
  key: options.key,
186
235
  ...fields.product,
187
236
  ...(browser !== undefined && { browser }),
188
237
  session: stamp.session,
189
- ...(id !== undefined && { id }),
190
- }, event, { awaitsId: fields.mayName && id === undefined });
238
+ ...id,
239
+ }, event, { awaitsId: fields.idKind !== undefined && identity === undefined });
191
240
  }
192
241
  catch (error) {
193
242
  // A failure before the queue holds the event loses it. Its marks go back, so the next event takes them and the
194
243
  // day still counts. A failed stamp gave back its own first-of-period marks.
195
244
  await install.giveBack([
196
- { version: productVersion, events: [event ?? { name, day: formatDay(localDateAt(clock.now())) }] },
245
+ {
246
+ version: productVersion,
247
+ events: [event ?? { name, day: formatDay(localDateAt(clock.now())) }],
248
+ },
197
249
  ]);
198
250
  throw error;
199
251
  }
200
252
  view?.recorded();
253
+ if (isNewDay) {
254
+ onNewDay();
255
+ }
201
256
  // The queue holds the event by now, so a failure here keeps its marks.
202
257
  await giveBack(dropped);
203
258
  return true;
@@ -218,23 +273,38 @@ export function newCollector(options) {
218
273
  await serialize(async () => undefined, undefined);
219
274
  await outbox.send();
220
275
  }
221
- const collector = {
222
- track: async (name, given) => {
223
- let params;
224
- try {
225
- params = copyOfParams(given);
226
- }
227
- catch (error) {
228
- reportError(error);
229
- return;
276
+ /**
277
+ * Schedules a send at construction when the storage holds requests, such as the events of a page or a window that
278
+ * closed before its send. It runs `startOnce`, which settles the stored state before it schedules the send.
279
+ */
280
+ async function sendWhatIsLeft() {
281
+ await lock(async () => {
282
+ // A storage that fails here fails the next call too, and that call reports it once.
283
+ if (await outbox.holdsRequests().catch(() => false)) {
284
+ await startOnce();
230
285
  }
231
- const problem = eventProblem(name, params);
232
- if (problem !== undefined) {
233
- reportError(new Error(`artel: event ${quoted(name)} ${problem}, so it was not tracked`));
286
+ }).catch(reportError);
287
+ }
288
+ const collector = {
289
+ track: async (name, given, trackOptions) => {
290
+ const calledAt = clock.now();
291
+ const event = acceptedEvent({ name, given, options: trackOptions, reportError });
292
+ if (event === undefined) {
234
293
  return;
235
294
  }
236
295
  const page = pageOf(name);
237
- await serialize(async () => record({ name, params, page }), false);
296
+ await serialize(async () => {
297
+ // The check and the mark run in the lock, so of two calls in quick turn only the first goes.
298
+ const call = { name, throttleMs: event.throttleMs, now: calledAt };
299
+ if (throttle.isDropped(call)) {
300
+ return false;
301
+ }
302
+ const isRecorded = await record({ name, params: event.params, page });
303
+ if (isRecorded) {
304
+ throttle.went(call);
305
+ }
306
+ return isRecorded;
307
+ }, false);
238
308
  },
239
309
  // The opted_out state takes no install mark. A user who turns analytics back on still sends `installed`.
240
310
  installed: async () => {
@@ -248,7 +318,7 @@ export function newCollector(options) {
248
318
  await serialize(async () => record({ name: LifecycleEvent.Updated, page, takeMark }), false);
249
319
  },
250
320
  setState: async (next) => {
251
- const isOptedOut = await serialize(async () => {
321
+ const hasRequest = await serialize(async () => {
252
322
  if (!takes(next)) {
253
323
  reportError(new TypeError(`artel: a channel of mode ${quoted(mode)} takes no state ${quoted(next)}`));
254
324
  return false;
@@ -257,34 +327,31 @@ export function newCollector(options) {
257
327
  if (previous === next) {
258
328
  return false;
259
329
  }
260
- // The state goes first. A failure after it leaves the user opted out, and the next run drops what is queued.
261
- await install.setState(next);
330
+ const hadId = await storeState(previous, next);
262
331
  if (next === AnalyticsState.OptedOut) {
263
332
  // Events from before the opt-out that have not gone yet never go.
264
- await discardForOptOut();
333
+ await giveBack(await outbox.discard());
265
334
  await recordOptOut();
266
335
  }
267
- else if (previous === AnalyticsState.Identified) {
268
- await leaveIdentity();
269
- }
270
336
  // A new session keeps the intake from tying together events from before and after the change.
271
337
  await install.endSession();
272
- return next === AnalyticsState.OptedOut;
338
+ return hadId || next === AnalyticsState.OptedOut;
273
339
  }, false);
274
- if (isOptedOut) {
340
+ // The forget request and the opted_out go at once.
341
+ if (hasRequest) {
275
342
  await flush();
276
343
  }
277
344
  },
278
345
  getState: () => serialize(currentState, AnalyticsState.Anonymous),
279
346
  flush,
280
347
  forget: async (id) => {
281
- // A host outside TypeScript can pass any value, which no envelope carries as its id.
282
- if (typeof id !== 'string') {
283
- reportError(new TypeError('artel: forget takes the id getId gave, a string'));
348
+ // The intake refuses a forget of any other value, which no envelope carries as its id.
349
+ if (!isUsableId(id)) {
350
+ reportError(new TypeError("artel: forget takes an id of 1 to 64 characters"));
284
351
  return;
285
352
  }
286
353
  await serialize(async () => {
287
- // The intake deletes the user's events, so each envelope of the id gives back its marks, sent or not.
354
+ // The intake deletes the id's events, so each envelope of the id gives back its marks, sent or not.
288
355
  await giveBack(await outbox.forget(id));
289
356
  // The events that wait for an id after the last user are that user's, so they go with it. The next id counts
290
357
  // as another user, so the events that wait after the forget never go under it.
@@ -293,9 +360,7 @@ export function newCollector(options) {
293
360
  await install.forgetLastId();
294
361
  }
295
362
  }, undefined);
296
- // A request already on its way may carry the id. It must reach the intake before the host asks the intake to
297
- // forget the user.
298
- await outbox.settled();
363
+ await outbox.send();
299
364
  },
300
365
  uninstallParams: () => serialize(async () => {
301
366
  const fields = await currentFields();
@@ -311,9 +376,14 @@ export function newCollector(options) {
311
376
  };
312
377
  }, undefined),
313
378
  };
379
+ void sendWhatIsLeft();
314
380
  return collector;
315
381
  }
382
+ /** Returns the longest an event waits in the queue before a send starts, as the options set it. */
383
+ export function sendDelayMsOf({ sendDelaySeconds, }) {
384
+ return durationOr(sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000;
385
+ }
316
386
  /** Returns `value`, or `fallback` for a duration that is no finite number from 0. */
317
387
  function durationOr(value, fallback) {
318
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
388
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
319
389
  }