@kk-forge/artel-collector 0.2.0 → 0.4.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/collector.js CHANGED
@@ -1,29 +1,29 @@
1
1
  import { daysBetween, formatDay, localDateAt } from './calendar.js';
2
2
  import { LifecycleEvent, UNINSTALLED } from './envelope.js';
3
3
  import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams } from './fields.js';
4
- import { accepted, checkedBuild, newBrowserReader, newStringStorage, quoted, reportTo, usableId } from './hostInput.js';
4
+ import { accepted, checkedBuild, isUsableId, newBrowserReader, newStringStorage, quoted, reportTo, usableId, } from './hostInput.js';
5
5
  import { systemClock } from './clock.js';
6
6
  import { newChannelStorage } from './storage.js';
7
7
  import { AnalyticsState, Mode } from './collectorTypes.js';
8
- import { copyOfParams, eventProblem } from './eventCheck.js';
8
+ import { acceptedEvent } from './eventCheck.js';
9
9
  import { newInstallState } from './installState.js';
10
10
  import { exclusive } from './lock.js';
11
11
  import { newOutbox } from './outbox.js';
12
12
  import { newPageReader } from './page.js';
13
- import { carriesPage, channelTakes, fieldsForState } from './stateFields.js';
13
+ import { carriesPage, channelTakes, fieldsForState, isAnalyticsState } from './stateFields.js';
14
14
  import { newHttpTransport } from './transport.js';
15
15
  const SESSION_IDLE_MINUTES = 10;
16
16
  const SEND_DELAY_SECONDS = 5;
17
17
  export function newCollector(options) {
18
18
  const product = checkedBuild(options);
19
19
  const { mode } = options;
20
- const transport = options.transport ?? newHttpTransport(options.endpoint);
20
+ const transports = transportsOf(options);
21
21
  const storage = newChannelStorage(newStringStorage(options.storage), options.key);
22
22
  const clock = options.clock ?? systemClock;
23
23
  const reportError = (error) => reportTo(options.onError, error);
24
24
  const lock = exclusive(options.lock);
25
25
  const getId = options.mode === Mode.Identified ? usableId(options.getId, reportError) : undefined;
26
- const readBrowser = options.mode === Mode.Identified ? newBrowserReader(options.browser, reportError) : undefined;
26
+ const readBrowser = options.mode === Mode.Anonymous ? undefined : newBrowserReader(options.browser, reportError);
27
27
  const browserLanguage = accepted('browserLanguage', languageTag(options.browserLanguage), isLanguage, reportError);
28
28
  const uiLanguage = accepted('uiLanguage', languageTag(options.uiLanguage), isLanguage, reportError);
29
29
  const install = newInstallState({
@@ -31,25 +31,15 @@ export function newCollector(options) {
31
31
  sessionIdleMs: durationOr(options.sessionIdleMinutes, SESSION_IDLE_MINUTES) * 60_000,
32
32
  });
33
33
  const outbox = newOutbox({
34
+ key: options.key,
34
35
  storage,
35
36
  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
- }),
37
+ ...transports,
38
+ // The current state decides the id, so an envelope names no user once the state has left the one it was recorded
39
+ // in. The state can change in this or another context after the lease.
40
+ identify: () => lock(async () => identityIn(await currentFields())),
51
41
  giveBack: (items) => giveBack(items),
52
- sendDelayMs: durationOr(options.sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000,
42
+ sendDelayMs: sendDelayMsOf(options),
53
43
  clock,
54
44
  reportError,
55
45
  });
@@ -65,11 +55,7 @@ export function newCollector(options) {
65
55
  const withInstallDay = async () => {
66
56
  if (!isInstallDayKnown) {
67
57
  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
- }
58
+ await settleStoredState();
73
59
  isInstallDayKnown = true;
74
60
  // The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and
75
61
  // its events go with the first send after the lease runs out.
@@ -89,9 +75,9 @@ export function newCollector(options) {
89
75
  await install.giveBack(items.map((item) => item.envelope));
90
76
  }
91
77
  /**
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.
78
+ * Stores the id an envelope names the user by. An id other than the last one means another user: the events of the
79
+ * last one, and those that waited for an id after it, are dropped, so none goes under another user's id. The session
80
+ * ends, so no session holds the events of two users.
95
81
  */
96
82
  async function noteId(id) {
97
83
  const last = await install.lastId();
@@ -104,32 +90,80 @@ export function newCollector(options) {
104
90
  }
105
91
  await install.setLastId(id);
106
92
  }
107
- /** Drops the queued events that name the user or wait for an id, and the last id with them. */
93
+ /**
94
+ * Resolves to the id the state of `fields` names the user by, with its kind and the browser, or to undefined while
95
+ * there is none. The pseudonymous state's id is the install id, which the collector makes once. A new id counts as
96
+ * another user, as `noteId` describes.
97
+ */
98
+ async function identityIn({ idKind }) {
99
+ if (idKind === undefined) {
100
+ return undefined;
101
+ }
102
+ const id = idKind === AnalyticsState.Pseudonymous ? await install.installId() : await getId?.();
103
+ if (id === undefined) {
104
+ return undefined;
105
+ }
106
+ await noteId(id);
107
+ const browser = readBrowser?.();
108
+ return { id, id_kind: idKind, ...(browser !== undefined && { browser }) };
109
+ }
110
+ /**
111
+ * Forgets the last id, as `forget` does, and drops the queued events that name the user or wait for an id. Deletes
112
+ * the install id, so a later pseudonymous state takes a new one.
113
+ */
108
114
  async function leaveIdentity() {
115
+ const last = await install.lastId();
116
+ if (isUsableId(last)) {
117
+ await giveBack(await outbox.forget(last));
118
+ }
109
119
  await giveBack(await outbox.discardIdentified());
120
+ // The install id goes before the last id. A run that stops between them then keeps the last id, and the next run
121
+ // leaves it again.
122
+ await install.dropInstallId();
110
123
  await install.setLastId('');
111
124
  }
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('');
125
+ /**
126
+ * Stores `next` and leaves the id of `previous`, and resolves to whether `previous` had one. A change between the two
127
+ * states with an id leaves first. A run that stops in between keeps the old state with its id forgotten, so no event
128
+ * goes under the other state's id. Any other change stores first, so an opt-out stays, and the next run leaves the id
129
+ * the stored state no longer has.
130
+ */
131
+ async function storeState(previous, next) {
132
+ const hadId = fieldsIn(previous).idKind !== undefined;
133
+ const isSwitch = hadId && fieldsIn(next).idKind !== undefined;
134
+ if (isSwitch) {
135
+ await leaveIdentity();
136
+ }
137
+ await install.setState(next);
138
+ if (hadId && !isSwitch) {
139
+ await leaveIdentity();
140
+ }
141
+ return hadId;
116
142
  }
117
143
  /**
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.
144
+ * Finishes a change of state that a stopped run or a change of the channel's mode left. Stores a state this channel
145
+ * no longer takes as anonymous. Leaves the last id in a state without one, and drops the queue in the opted_out
146
+ * state.
120
147
  */
121
- async function dropStateTheChannelNoLongerTakes() {
148
+ async function settleStoredState() {
122
149
  const stored = await install.state();
123
- if (stored === AnalyticsState.Identified && !takes(stored)) {
124
- await leaveIdentity();
150
+ const isUntaken = isAnalyticsState(stored) && !takes(stored);
151
+ if (isUntaken) {
125
152
  await install.setState(AnalyticsState.Anonymous);
126
153
  await install.endSession();
127
154
  }
155
+ const state = await currentState();
156
+ if (isUntaken || (fieldsIn(state).idKind === undefined && isUsableId(await install.lastId()))) {
157
+ await leaveIdentity();
158
+ }
159
+ if (state === AnalyticsState.OptedOut) {
160
+ await giveBack(await outbox.discard());
161
+ }
128
162
  }
129
163
  async function currentState() {
130
164
  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.
165
+ // The function reads a state this channel does not take as anonymous. Such a state stays after the product changes
166
+ // its mode.
133
167
  return takes(stored) ? stored : AnalyticsState.Anonymous;
134
168
  }
135
169
  function takes(state) {
@@ -156,12 +190,9 @@ export function newCollector(options) {
156
190
  if (view?.isRepeatedView === true) {
157
191
  return false;
158
192
  }
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
- }
193
+ // 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
194
+ // dropped events, the install and version marks included, before this event takes its own.
195
+ const identity = await identityIn(fields);
165
196
  const productVersion = fields.product.version;
166
197
  // A `takeMark` that fails took no mark, so nothing goes back.
167
198
  if (takeMark !== undefined && !(await takeMark(productVersion))) {
@@ -180,14 +211,14 @@ export function newCollector(options) {
180
211
  page: fields.mayCarryPage ? view?.fields : undefined,
181
212
  isAgeExact: fields.isAgeExact,
182
213
  });
183
- const browser = id === undefined ? undefined : readBrowser?.();
214
+ const { browser, ...id } = identity ?? {};
184
215
  dropped = await outbox.add({
185
216
  key: options.key,
186
217
  ...fields.product,
187
218
  ...(browser !== undefined && { browser }),
188
219
  session: stamp.session,
189
- ...(id !== undefined && { id }),
190
- }, event, { awaitsId: fields.mayName && id === undefined });
220
+ ...id,
221
+ }, event, { awaitsId: fields.idKind !== undefined && identity === undefined });
191
222
  }
192
223
  catch (error) {
193
224
  // A failure before the queue holds the event loses it. Its marks go back, so the next event takes them and the
@@ -220,21 +251,12 @@ export function newCollector(options) {
220
251
  }
221
252
  const collector = {
222
253
  track: async (name, given) => {
223
- let params;
224
- try {
225
- params = copyOfParams(given);
226
- }
227
- catch (error) {
228
- reportError(error);
229
- return;
230
- }
231
- const problem = eventProblem(name, params);
232
- if (problem !== undefined) {
233
- reportError(new Error(`artel: event ${quoted(name)} ${problem}, so it was not tracked`));
254
+ const event = acceptedEvent(name, given, reportError);
255
+ if (event === undefined) {
234
256
  return;
235
257
  }
236
258
  const page = pageOf(name);
237
- await serialize(async () => record({ name, params, page }), false);
259
+ await serialize(async () => record({ name, params: event.params, page }), false);
238
260
  },
239
261
  // The opted_out state takes no install mark. A user who turns analytics back on still sends `installed`.
240
262
  installed: async () => {
@@ -248,7 +270,7 @@ export function newCollector(options) {
248
270
  await serialize(async () => record({ name: LifecycleEvent.Updated, page, takeMark }), false);
249
271
  },
250
272
  setState: async (next) => {
251
- const isOptedOut = await serialize(async () => {
273
+ const hasRequest = await serialize(async () => {
252
274
  if (!takes(next)) {
253
275
  reportError(new TypeError(`artel: a channel of mode ${quoted(mode)} takes no state ${quoted(next)}`));
254
276
  return false;
@@ -257,34 +279,31 @@ export function newCollector(options) {
257
279
  if (previous === next) {
258
280
  return false;
259
281
  }
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);
282
+ const hadId = await storeState(previous, next);
262
283
  if (next === AnalyticsState.OptedOut) {
263
284
  // Events from before the opt-out that have not gone yet never go.
264
- await discardForOptOut();
285
+ await giveBack(await outbox.discard());
265
286
  await recordOptOut();
266
287
  }
267
- else if (previous === AnalyticsState.Identified) {
268
- await leaveIdentity();
269
- }
270
288
  // A new session keeps the intake from tying together events from before and after the change.
271
289
  await install.endSession();
272
- return next === AnalyticsState.OptedOut;
290
+ return hadId || next === AnalyticsState.OptedOut;
273
291
  }, false);
274
- if (isOptedOut) {
292
+ // The forget request and the opted_out go at once.
293
+ if (hasRequest) {
275
294
  await flush();
276
295
  }
277
296
  },
278
297
  getState: () => serialize(currentState, AnalyticsState.Anonymous),
279
298
  flush,
280
299
  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'));
300
+ // The intake refuses a forget of any other value, which no envelope carries as its id.
301
+ if (!isUsableId(id)) {
302
+ reportError(new TypeError('artel: forget takes an id of 1 to 64 characters'));
284
303
  return;
285
304
  }
286
305
  await serialize(async () => {
287
- // The intake deletes the user's events, so each envelope of the id gives back its marks, sent or not.
306
+ // The intake deletes the id's events, so each envelope of the id gives back its marks, sent or not.
288
307
  await giveBack(await outbox.forget(id));
289
308
  // 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
309
  // as another user, so the events that wait after the forget never go under it.
@@ -293,9 +312,7 @@ export function newCollector(options) {
293
312
  await install.forgetLastId();
294
313
  }
295
314
  }, 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();
315
+ await outbox.send();
299
316
  },
300
317
  uninstallParams: () => serialize(async () => {
301
318
  const fields = await currentFields();
@@ -313,6 +330,23 @@ export function newCollector(options) {
313
330
  };
314
331
  return collector;
315
332
  }
333
+ /**
334
+ * Returns the transport of the envelopes and that of the forget requests. The intake's forget address replaces the last
335
+ * segment of the relay path, `/v1/public/relay`. A product's own transport takes both kinds of request.
336
+ */
337
+ function transportsOf(options) {
338
+ if (options.transport !== undefined) {
339
+ return { transport: options.transport, forgetTransport: options.transport };
340
+ }
341
+ return {
342
+ transport: newHttpTransport(options.endpoint),
343
+ forgetTransport: newHttpTransport(new URL('forget', options.endpoint).href),
344
+ };
345
+ }
346
+ /** Returns the longest an event waits in the queue before a send starts, as the options set it. */
347
+ export function sendDelayMsOf({ sendDelaySeconds }) {
348
+ return durationOr(sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000;
349
+ }
316
350
  /** Returns `value`, or `fallback` for a duration that is no finite number from 0. */
317
351
  function durationOr(value, fallback) {
318
352
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
@@ -6,26 +6,36 @@ import type { ProductFields } from './stateFields.js';
6
6
  import type { StorageAdapter } from './storage.js';
7
7
  import type { Transport } from './transport.js';
8
8
  /**
9
- * What a channel may collect at most, as set in the intake's admin. The collector's mode matches its channel's. An
10
- * identified channel lets a user who agrees be identified. An anonymous one never does.
9
+ * What a channel may collect at most, as set in the intake's admin. The collector's mode matches its channel's. Each
10
+ * mode takes the states up to its own: a pseudonymous channel adds the install id, and an identified one the account
11
+ * id.
11
12
  */
12
13
  export declare const Mode: {
13
14
  readonly Anonymous: 'anonymous';
15
+ readonly Pseudonymous: 'pseudonymous';
14
16
  readonly Identified: 'identified';
15
17
  };
16
18
  export type Mode = (typeof Mode)[keyof typeof Mode];
17
- /** What the collector sends for this user, a choice the collector stores. Every user starts anonymous. */
19
+ /** The user's analytics state, which the collector stores and which decides what it sends. Users start anonymous. */
18
20
  export declare const AnalyticsState: {
19
21
  /** Sends nothing. Switching to it sends one `opted_out`, with no id or browser, and drops what was not sent. */
20
22
  readonly OptedOut: 'opted_out';
21
23
  /** Sends events with no id or browser, the primary languages only and coarse ages. Needs no consent. */
22
24
  readonly Anonymous: 'anonymous';
23
- /** Sends the id from `getId`, the browser, the full languages and exact ages. Only an identified channel takes it. */
25
+ /**
26
+ * Sends a random install id the collector makes and stores, the browser, the full languages and exact ages. Needs
27
+ * consent. A pseudonymous or identified channel takes it.
28
+ */
29
+ readonly Pseudonymous: 'pseudonymous';
30
+ /**
31
+ * Sends what the pseudonymous state sends, with the id from `getId` in place of the install id. Needs consent. Only
32
+ * an identified channel takes it.
33
+ */
24
34
  readonly Identified: 'identified';
25
35
  };
26
36
  export type AnalyticsState = (typeof AnalyticsState)[keyof typeof AnalyticsState];
27
- /** The states a collector of channel mode `M` takes: an anonymous channel never identifies a user. */
28
- export type StateOf<M extends Mode> = M extends typeof Mode.Identified ? AnalyticsState : Exclude<AnalyticsState, typeof AnalyticsState.Identified>;
37
+ /** The states a collector of channel mode `M` takes: those up to its mode. */
38
+ export type StateOf<M extends Mode> = M extends typeof Mode.Identified ? AnalyticsState : M extends typeof Mode.Pseudonymous ? Exclude<AnalyticsState, typeof AnalyticsState.Identified> : Exclude<AnalyticsState, typeof AnalyticsState.Pseudonymous | typeof AnalyticsState.Identified>;
29
39
  /**
30
40
  * Returns the user's id, or undefined while the product does not know it yet. The collector never makes one up. The
31
41
  * collector calls it while it holds its lock, so it must not await a method of the same collector, which would wait on
@@ -46,7 +56,7 @@ export interface CommonOptions {
46
56
  version: string;
47
57
  /** The user's language, such as `pt-BR`: what the browser asks sites for. */
48
58
  browserLanguage?: string | undefined;
49
- /** The language the product shows its interface in: the outcome of its own localization. */
59
+ /** The language the user picked in the product, when the product offers that choice. Left out otherwise. */
50
60
  uiLanguage?: string | undefined;
51
61
  storage: StorageAdapter;
52
62
  /** Minutes without events that end a session, 10 by default. */
@@ -76,20 +86,25 @@ export type Delivery = {
76
86
  transport: Transport;
77
87
  endpoint?: never;
78
88
  };
79
- /** The channel mode, with what an identified channel takes besides. */
89
+ /**
90
+ * The browser the product runs in, or a function that returns it, such as `() => detectBrowser(navigator)`. The
91
+ * collector calls the function once, for the first event with an id, the only kind of envelope that carries it.
92
+ */
93
+ type BrowserOption = Browser | (() => Browser | undefined) | undefined;
94
+ /** The channel mode, with what a channel with an id takes besides. */
80
95
  export type ModeOptions = {
81
96
  mode: typeof Mode.Anonymous;
82
97
  getId?: never;
83
98
  browser?: never;
99
+ } | {
100
+ mode: typeof Mode.Pseudonymous;
101
+ getId?: never;
102
+ browser?: BrowserOption;
84
103
  } | {
85
104
  mode: typeof Mode.Identified;
86
105
  /** Gives the id in the identified state. The collector calls it in no other state. */
87
106
  getId: GetId;
88
- /**
89
- * The browser the product runs in, or a function that returns it, such as `() => detectBrowser(navigator)`. The
90
- * collector calls the function once, for the first event with an id, the only kind of envelope that carries it.
91
- */
92
- browser?: Browser | (() => Browser | undefined) | undefined;
107
+ browser?: BrowserOption;
93
108
  };
94
109
  /** The options only a site's collector takes, since only platform web sends pages. */
95
110
  export interface PageOptions {
@@ -139,7 +154,7 @@ export declare const ActiveDaysBucket: {
139
154
  export type ActiveDaysBucket = (typeof ActiveDaysBucket)[keyof typeof ActiveDaysBucket];
140
155
  /** What an uninstall page gets in its query string, shaped by the state as an envelope is. */
141
156
  export interface UninstallParams extends ProductFields {
142
- /** Days since install: exact up to 31 in the identified state, a bucket otherwise. */
157
+ /** Days since install: exact up to 31 in a state with an id, a bucket otherwise. */
143
158
  age_days: number;
144
159
  /** The bucket of the number of local days with an event. */
145
160
  active_days: ActiveDaysBucket;
@@ -161,10 +176,11 @@ export interface Collector<M extends Mode = Mode> {
161
176
  */
162
177
  updated(): Promise<void>;
163
178
  /**
164
- * Stores the user's choice and starts a new session. Switching to `opted_out` drops what was not sent, except an
165
- * earlier `opted_out`, and sends one `opted_out`, at once or at the end of a retry wait that is running. Switching
166
- * from `identified` drops the queued events that name the user. A dropped event that no request carried gives back
167
- * its marks. The same state again does nothing.
179
+ * Stores the user's analytics state and starts a new session. Switching to `opted_out` drops what was not sent,
180
+ * except an earlier `opted_out`, and sends one `opted_out`, at once or at the end of a retry wait that is running.
181
+ * Switching from `pseudonymous` or `identified` forgets the last id, as `forget` does, and drops the queued events
182
+ * that wait for an id. Switching from `pseudonymous` also deletes the install id. A dropped event that no request
183
+ * carried gives back its marks. The same state again does nothing.
168
184
  */
169
185
  setState(state: StateOf<M>): Promise<void>;
170
186
  /**
@@ -173,15 +189,15 @@ export interface Collector<M extends Mode = Mode> {
173
189
  */
174
190
  getState(): Promise<AnalyticsState>;
175
191
  /**
176
- * Sends what is queued now, or once the retry wait is over. A page calls it when it is hidden, since the user may not
177
- * come back.
192
+ * Sends what is queued now, or once the retry wait is over. The collector sends within the send delay without it, so a
193
+ * product calls it only to send sooner.
178
194
  */
179
195
  flush(): Promise<void>;
180
196
  /**
181
- * Drops this id's queued events and resolves once this collector's request in progress ends. For the last id, it also
182
- * drops the events that wait for an id, and the next id counts as another user. The host calls it once the user left
183
- * the identified state or `getId` stopped giving the id, then asks the intake to forget the user. The intake also
184
- * deletes the user's events that arrive within a minute after the forget, such as a request from another context.
197
+ * Drops this id's queued events and asks the intake to delete the id's events, after this collector's request in
198
+ * progress. For the last id, it also drops the events that wait for an id, and the next id counts as another user.
199
+ * The collector stores the request until the intake answers it. The intake also deletes the user's events that arrive
200
+ * within a minute after the forget, such as a request from another context.
185
201
  */
186
202
  forget(id: string): Promise<void>;
187
203
  /**
@@ -1,18 +1,28 @@
1
1
  /**
2
- * What a channel may collect at most, as set in the intake's admin. The collector's mode matches its channel's. An
3
- * identified channel lets a user who agrees be identified. An anonymous one never does.
2
+ * What a channel may collect at most, as set in the intake's admin. The collector's mode matches its channel's. Each
3
+ * mode takes the states up to its own: a pseudonymous channel adds the install id, and an identified one the account
4
+ * id.
4
5
  */
5
6
  export const Mode = {
6
7
  Anonymous: 'anonymous',
8
+ Pseudonymous: 'pseudonymous',
7
9
  Identified: 'identified',
8
10
  };
9
- /** What the collector sends for this user, a choice the collector stores. Every user starts anonymous. */
11
+ /** The user's analytics state, which the collector stores and which decides what it sends. Users start anonymous. */
10
12
  export const AnalyticsState = {
11
13
  /** Sends nothing. Switching to it sends one `opted_out`, with no id or browser, and drops what was not sent. */
12
14
  OptedOut: 'opted_out',
13
15
  /** Sends events with no id or browser, the primary languages only and coarse ages. Needs no consent. */
14
16
  Anonymous: 'anonymous',
15
- /** Sends the id from `getId`, the browser, the full languages and exact ages. Only an identified channel takes it. */
17
+ /**
18
+ * Sends a random install id the collector makes and stores, the browser, the full languages and exact ages. Needs
19
+ * consent. A pseudonymous or identified channel takes it.
20
+ */
21
+ Pseudonymous: 'pseudonymous',
22
+ /**
23
+ * Sends what the pseudonymous state sends, with the id from `getId` in place of the install id. Needs consent. Only
24
+ * an identified channel takes it.
25
+ */
16
26
  Identified: 'identified',
17
27
  };
18
28
  /** Bucket for the number of days with at least one event. */
@@ -0,0 +1,26 @@
1
+ import type { Collector, CommonOptions, Delivery, Mode, ModeOptions } from './collectorTypes.js';
2
+ import type { Platform } from './envelope.js';
3
+ import type { StorageAdapter } from './storage.js';
4
+ /**
5
+ * The options of `newDesktopCollector`: those of `newCollector` with `storage` optional and a desktop `platform`. An
6
+ * option left out or `undefined` takes its default.
7
+ */
8
+ export type DesktopCollectorOptions = Omit<CommonOptions, 'storage'> & {
9
+ /** The operating system the app runs on, as the intake names it. */
10
+ platform: typeof Platform.MacOs | typeof Platform.Windows | typeof Platform.Linux;
11
+ /** The storage, the webview's `localStorage` by default. */
12
+ storage?: StorageAdapter | undefined;
13
+ /** A desktop product names no browser. */
14
+ browser?: never;
15
+ /** A desktop product sends no page. */
16
+ getPage?: never;
17
+ } & Delivery & ModeOptions;
18
+ /**
19
+ * Returns a collector for a window of a desktop app, such as a Tauri webview. Its windows share the webview's
20
+ * `localStorage` and Web Locks, so they keep one queue and one state. It sends the user's language from
21
+ * `navigator.language`. The app passes its own `uiLanguage`. It sends `installed` and `updated` itself when they are
22
+ * due.
23
+ */
24
+ export declare function newDesktopCollector<M extends Mode>(options: DesktopCollectorOptions & {
25
+ mode: M;
26
+ }): Collector<M>;
@@ -0,0 +1,15 @@
1
+ import { newCollector } from './collector.js';
2
+ import { newLocalStorageAdapter, newWebLock } from './web.js';
3
+ export function newDesktopCollector(options) {
4
+ const collector = newCollector({
5
+ ...options,
6
+ storage: options.storage ?? newLocalStorageAdapter(),
7
+ lock: options.lock ?? newWebLock(),
8
+ browserLanguage: options.browserLanguage ?? navigator.language,
9
+ });
10
+ // A desktop app has no install event, so each start marks the install and the version. Both send once under the
11
+ // lock, so every window may build a collector. The collector runs its calls in this order.
12
+ void collector.installed();
13
+ void collector.updated();
14
+ return collector;
15
+ }
@@ -47,6 +47,8 @@ export interface UsageEvent {
47
47
  page?: string;
48
48
  referrer?: string;
49
49
  }
50
+ /** Where an envelope's `id` comes from: the install id the collector makes, or the account id from `getId`. */
51
+ export type IdKind = 'pseudonymous' | 'identified';
50
52
  /** What one request to the intake carries. */
51
53
  export interface Envelope {
52
54
  key: string;
@@ -63,6 +65,8 @@ export interface Envelope {
63
65
  browser?: Browser;
64
66
  session: string;
65
67
  id?: string;
68
+ /** Present exactly when `id` is. The intake keeps the id only when its kind is within the channel's mode. */
69
+ id_kind?: IdKind;
66
70
  /** Stays the same on each retry of this envelope. The intake keeps it once. */
67
71
  batch?: string;
68
72
  events: UsageEvent[];
@@ -3,10 +3,11 @@ import { type EventParams } from './envelope.js';
3
3
  * Tells why the intake would drop the event, or returns undefined when its form passes. The check refuses `installed`,
4
4
  * `updated` and `opted_out`, because only the collector's own methods send them.
5
5
  */
6
- export declare function eventProblem(name: unknown, params: unknown): string | undefined;
6
+ export declare function checkEvent(name: unknown, params: unknown): string | undefined;
7
7
  /**
8
- * Returns a shallow copy of the own enumerable entries of object params, and other params as they are. The collector
9
- * checks and queues the copy, so a later change the host makes to its object reaches neither. Throws what a getter or a
10
- * proxy of the params throws.
8
+ * Returns a copy of the params of an event `track` takes, or reports why it refuses the event and returns undefined.
9
+ * The copy is taken once, so a later change the host makes to its object reaches neither the check nor the event.
11
10
  */
12
- export declare function copyOfParams(params: EventParams | undefined): EventParams | undefined;
11
+ export declare function acceptedEvent(name: string, given: EventParams | undefined, reportError: (error: unknown) => void): {
12
+ params: EventParams | undefined;
13
+ } | undefined;
@@ -29,7 +29,7 @@ const SYSTEM_EVENT_PARAMS = new Map([
29
29
  * Tells why the intake would drop the event, or returns undefined when its form passes. The check refuses `installed`,
30
30
  * `updated` and `opted_out`, because only the collector's own methods send them.
31
31
  */
32
- export function eventProblem(name, params) {
32
+ export function checkEvent(name, params) {
33
33
  if (typeof name !== 'string' || !NAME_FORMAT.test(name)) {
34
34
  return 'has a name the intake does not take';
35
35
  }
@@ -38,12 +38,32 @@ export function eventProblem(name, params) {
38
38
  }
39
39
  return paramsProblem(name, params);
40
40
  }
41
+ /**
42
+ * Returns a copy of the params of an event `track` takes, or reports why it refuses the event and returns undefined.
43
+ * The copy is taken once, so a later change the host makes to its object reaches neither the check nor the event.
44
+ */
45
+ export function acceptedEvent(name, given, reportError) {
46
+ let params;
47
+ try {
48
+ params = copyOfParams(given);
49
+ }
50
+ catch (error) {
51
+ reportError(error);
52
+ return undefined;
53
+ }
54
+ const problem = checkEvent(name, params);
55
+ if (problem !== undefined) {
56
+ reportError(new Error(`artel: event ${quoted(name)} ${problem}, so it was not tracked`));
57
+ return undefined;
58
+ }
59
+ return { params };
60
+ }
41
61
  /**
42
62
  * Returns a shallow copy of the own enumerable entries of object params, and other params as they are. The collector
43
63
  * checks and queues the copy, so a later change the host makes to its object reaches neither. Throws what a getter or a
44
64
  * proxy of the params throws.
45
65
  */
46
- export function copyOfParams(params) {
66
+ function copyOfParams(params) {
47
67
  // An untyped host can pass null or a list. The function returns such params as they are, so the check refuses them.
48
68
  const value = params;
49
69
  return typeof value === 'object' && value !== null && !Array.isArray(value)
package/dist/exports.d.ts CHANGED
@@ -2,6 +2,8 @@ export { detectBrowser, BrowserName, type Browser, type NavigatorFields } from '
2
2
  export { newCollector } from './collector.js';
3
3
  export { ActiveDaysBucket, AnalyticsState, Mode, type Collector, type CollectorOptions, type CommonOptions, type Delivery, type GetId, type ModeOptions, type PageFields, type PageOptions, type StateOf, type UninstallParams, } from './collectorTypes.js';
4
4
  export { Platform, type EventParams } from './envelope.js';
5
+ export { checkEvent } from './eventCheck.js';
6
+ export { checkOptions, isTestKey } from './hostInput.js';
5
7
  export { newMemoryStorage, type StorageAdapter } from './storage.js';
6
8
  export { newHttpTransport, type Transport, type TransportResult } from './transport.js';
7
9
  export type { Lock } from './lock.js';
package/dist/exports.js CHANGED
@@ -2,6 +2,8 @@ export { detectBrowser, BrowserName } from './browser.js';
2
2
  export { newCollector } from './collector.js';
3
3
  export { ActiveDaysBucket, AnalyticsState, Mode, } from './collectorTypes.js';
4
4
  export { Platform } from './envelope.js';
5
+ export { checkEvent } from './eventCheck.js';
6
+ export { checkOptions, isTestKey } from './hostInput.js';
5
7
  export { newMemoryStorage } from './storage.js';
6
8
  export { newHttpTransport } from './transport.js';
7
9
  export { systemClock } from './clock.js';