zeno.id 0.2.0 → 0.3.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/README.md CHANGED
@@ -47,7 +47,7 @@ if (action === 'block') {
47
47
  }
48
48
  ```
49
49
 
50
- The package reads no option or secret from the environment: `createProxy(apiKey, options?)` and `createClient(apiKey, options?)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the route or client is made: neither fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is; `apiUrl` in their options is only for another Zeno API than the live one.
50
+ The package reads no option or secret from the environment: `createProxy(apiKey, options?)` and `createClient(apiKey, options?)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the route or client is made: neither fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is, so there's no address to set.
51
51
 
52
52
  ## In the browser
53
53
 
@@ -56,10 +56,12 @@ Call `start()` on a page with an action you want to identify (a login, signup or
56
56
  ```ts
57
57
  import { start } from 'zeno.id'
58
58
 
59
- // When the login page loads:
60
- const zeno = start('/zeno') // the same path as your route
59
+ // Start as early as you can: it loads Zeno and starts reading the browser,
60
+ // so identify() is quick later (your proxy route's path)
61
+ const zeno = start('/zeno')
61
62
 
62
- // When the user logs in (never throws; requestId is undefined when it failed):
63
+ // Recognise the browser the moment the user logs in
64
+ // (never throws: requestId is undefined when nothing was identified)
63
65
  const { requestId } = await zeno.identify({ action: 'login' })
64
66
 
65
67
  const response = await fetch('/api/login', {
@@ -114,6 +116,8 @@ The script keeps no visitor id itself. The route keeps it in the `zeno_id` cooki
114
116
  `zeno.stop()` ends identification for good, for a visitor who withdraws consent: an `identify()` in progress and every later one answer the `stopped` error, nothing more is collected or sent, and a `POST` to the route's `?forget` clears its cookie. A script still loading never starts: its module may finish downloading, but it isn't started. `forget(path)` does the same without loading or starting anything, and resolves once the route cleared the cookie (it rejects with `network_connection` or `server_error` when it couldn't, and `not_in_browser` on the server). Call `start()` again to identify once consent is back.
115
117
 
116
118
  ```ts
119
+ import { forget, start, type Zeno } from 'zeno.id'
120
+
117
121
  let zeno: Zeno | undefined
118
122
 
119
123
  consentTool.onChange(async ({ fraudPrevention }) => {
@@ -242,8 +246,8 @@ Bun.serve({
242
246
  ```
243
247
 
244
248
  ```ts
245
- import { env } from 'cloudflare:workers'
246
249
  // A Cloudflare Worker
250
+ import { env } from 'cloudflare:workers'
247
251
  import { createProxy } from 'zeno.id/server'
248
252
 
249
253
  // Your proxy route: the browser SDK talks to Zeno through it
@@ -262,7 +266,6 @@ The docs' quickstart has SvelteKit, Nuxt, React Router, SolidStart, Astro and Ho
262
266
  | Option | |
263
267
  | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
264
268
  | `cookiePath` | The path the browser calls the route on, when something in front of the handler rewrites it (the browser calls `/zeno`, a handler at `/api/proxy` answers); by default the request's. |
265
- | `apiUrl` | Only for another Zeno API than the live one, like a staging deployment. |
266
269
 
267
270
  The route forwards your visitors' headers by name only, apart from the values Zeno reads (`User-Agent`, `Origin`, `Signature-Agent`, `Signature-Input`), so your cookies and credentials never leave your server.
268
271
 
package/dist/index.cjs CHANGED
@@ -28,21 +28,21 @@ var ZenoError = class extends Error {
28
28
  const toZenoError = (error) => {
29
29
  if (error instanceof ZenoError) return error;
30
30
  const { name, code, message } = typeof error === "object" && error !== null ? error : {};
31
- const text = typeof message === "string" ? message : void 0;
32
- return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
31
+ const messageText = typeof message === "string" ? message : void 0;
32
+ return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
33
33
  };
34
34
  //#endregion
35
35
  //#region src/browser/csp.ts
36
36
  const watchCsp = (origin) => {
37
- let blocked = false;
37
+ let isBlocked = false;
38
38
  const listener = (event) => {
39
- if (event.blockedURI.startsWith(origin)) blocked = true;
39
+ if (event.blockedURI.startsWith(origin)) isBlocked = true;
40
40
  };
41
41
  globalThis.document?.addEventListener("securitypolicyviolation", listener);
42
42
  return {
43
- failure: async (otherwise, blockedMessage) => {
43
+ errorFor: async (fallback, blockedMessage) => {
44
44
  await new Promise((resolve) => setTimeout(resolve, 0));
45
- return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
45
+ return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
46
46
  },
47
47
  stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
48
48
  };
@@ -56,13 +56,13 @@ const importModule = (url) => import(
56
56
  );
57
57
  //#endregion
58
58
  //#region src/browser/options.ts
59
- const invalid = (message) => new ZenoError("invalid_options", message);
59
+ const invalidOptions = (message) => new ZenoError("invalid_options", message);
60
60
  const resolveEndpoint = (value) => {
61
61
  if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
62
62
  try {
63
- const page = new URL(globalThis.location.href);
64
- const url = new URL(value, page);
65
- return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
63
+ const pageUrl = new URL(globalThis.location.href);
64
+ const url = new URL(value, pageUrl);
65
+ return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
66
66
  } catch {
67
67
  return;
68
68
  }
@@ -70,20 +70,20 @@ const resolveEndpoint = (value) => {
70
70
  const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
71
71
  const checkProxyEndpoint = (path, call = "start") => {
72
72
  const url = resolveEndpoint(path ?? "/zeno");
73
- if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
73
+ if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
74
74
  return url;
75
75
  };
76
76
  const checkIdentifyOptions = (options) => {
77
- if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
77
+ if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
78
78
  const { externalId, action, metadata } = options;
79
- if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
80
- if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
81
- if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("action must be a string of at most 1,024 characters");
82
- if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
79
+ if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
80
+ if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
81
+ if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
82
+ if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
83
83
  };
84
84
  //#endregion
85
85
  //#region src/browser/storage.ts
86
- const forgetStored = (endpoint) => {
86
+ const clearVisitorCookie = (endpoint) => {
87
87
  return fetch(`${endpoint}?forget`, {
88
88
  method: "POST",
89
89
  credentials: "same-origin",
@@ -93,49 +93,49 @@ const forgetStored = (endpoint) => {
93
93
  //#endregion
94
94
  //#region src/browser/forget.ts
95
95
  /**
96
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
97
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
98
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
96
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
97
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
98
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
99
99
  *
100
100
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
101
101
  */
102
102
  const forget = async (path) => {
103
103
  if (typeof document === "undefined") throw new ZenoError("not_in_browser");
104
104
  const endpoint = checkProxyEndpoint(path, "forget");
105
- const csp = watchCsp(new URL(endpoint).origin);
105
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
106
106
  let response;
107
107
  try {
108
- response = await forgetStored(endpoint);
108
+ response = await clearVisitorCookie(endpoint);
109
109
  } catch {
110
- throw await csp.failure(new ZenoError("network_connection"));
110
+ throw await cspWatcher.errorFor(new ZenoError("network_connection"));
111
111
  } finally {
112
- csp.stop();
112
+ cspWatcher.stop();
113
113
  }
114
114
  if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
115
115
  };
116
116
  //#endregion
117
117
  //#region src/browser/index.ts
118
- const withTimeout = (promise, ms, error) => {
118
+ const withTimeout = (promise, ms, makeError) => {
119
119
  let timer;
120
120
  return Promise.race([promise, new Promise((_, reject) => {
121
- timer = setTimeout(() => reject(error()), ms);
121
+ timer = setTimeout(() => reject(makeError()), ms);
122
122
  })]).finally(() => clearTimeout(timer));
123
123
  };
124
- const failed = (error) => ({
124
+ const toFailedIdentification = (error) => ({
125
125
  requestId: void 0,
126
126
  error: toZenoError(error)
127
127
  });
128
- const ownAnswer = (identification) => {
128
+ const withOwnError = (identification) => {
129
129
  return identification.error ? {
130
130
  ...identification,
131
131
  error: toZenoError(identification.error)
132
132
  } : identification;
133
133
  };
134
- const onServer = () => ({
135
- identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
134
+ const makeServerStub = () => ({
135
+ identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
136
136
  stop() {}
137
137
  });
138
- const refreshChallengeToken = (endpoint) => async () => {
138
+ const makeChallengeTokenRefresh = (endpoint) => async () => {
139
139
  try {
140
140
  const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
141
141
  return toChallengeToken(module?.challengeToken);
@@ -143,7 +143,7 @@ const refreshChallengeToken = (endpoint) => async () => {
143
143
  return;
144
144
  }
145
145
  };
146
- const loadFailure = async (endpoint) => {
146
+ const explainLoadFailure = async (endpoint) => {
147
147
  const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
148
148
  try {
149
149
  const response = await fetch(endpoint, { credentials: "same-origin" });
@@ -160,25 +160,25 @@ const loadFailure = async (endpoint) => {
160
160
  return fallback;
161
161
  }
162
162
  };
163
- const loadAgent = async (endpoint, stopped, started) => {
164
- const csp = watchCsp(new URL(endpoint).origin);
163
+ const loadAgent = async (endpoint, isStopped, onStarted) => {
164
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
165
165
  let module;
166
166
  try {
167
167
  module = await importModule(endpoint);
168
168
  } catch {
169
- const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
170
- throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
169
+ const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
170
+ throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
171
171
  } finally {
172
- csp.stop();
172
+ cspWatcher.stop();
173
173
  }
174
- if (stopped()) throw new ZenoError("stopped");
174
+ if (isStopped()) throw new ZenoError("stopped");
175
175
  if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
176
176
  try {
177
177
  const agent = module.start(new URL(endpoint).pathname, {
178
178
  challengeToken: toChallengeToken(module.challengeToken),
179
- refreshChallengeToken: refreshChallengeToken(endpoint)
179
+ refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
180
180
  });
181
- started(agent);
181
+ onStarted(agent);
182
182
  return agent;
183
183
  } catch (error) {
184
184
  throw toZenoError(error);
@@ -191,39 +191,39 @@ const loadAgent = async (endpoint, stopped, started) => {
191
191
  * fragment. The script loads from it and identifies through it.
192
192
  */
193
193
  const start = (path) => {
194
- if (typeof document === "undefined") return onServer();
194
+ if (typeof document === "undefined") return makeServerStub();
195
195
  const endpoint = checkProxyEndpoint(path);
196
- let stopped = false;
197
- let running;
198
- let rejectStopped = () => {};
199
- const stopping = new Promise((_, reject) => {
200
- rejectStopped = reject;
196
+ let isStopped = false;
197
+ let runningAgent;
198
+ let rejectOnStop = () => {};
199
+ const stopSignal = new Promise((_, reject) => {
200
+ rejectOnStop = reject;
201
201
  });
202
- stopping.catch(() => {});
203
- const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
204
- loaded.catch(() => {});
202
+ stopSignal.catch(() => {});
203
+ const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
204
+ agentLoading.catch(() => {});
205
205
  const identify = async (identifyOptions) => {
206
- if (stopped) throw new ZenoError("stopped");
206
+ if (isStopped) throw new ZenoError("stopped");
207
207
  checkIdentifyOptions(identifyOptions);
208
208
  const timeout = IDENTIFY_TIMEOUT;
209
- const started = performance.now();
210
- const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
211
- const left = Math.max(1, timeout - (performance.now() - started));
212
- if (stopped) throw new ZenoError("stopped");
213
- return ownAnswer(await agent.identify({
209
+ const startedAt = performance.now();
210
+ const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
211
+ const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
212
+ if (isStopped) throw new ZenoError("stopped");
213
+ return withOwnError(await agent.identify({
214
214
  ...identifyOptions,
215
- timeout: left
215
+ timeout: timeLeft
216
216
  }));
217
217
  };
218
218
  return {
219
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
219
+ identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
220
220
  stop() {
221
- if (!stopped) {
222
- stopped = true;
223
- rejectStopped(new ZenoError("stopped"));
221
+ if (!isStopped) {
222
+ isStopped = true;
223
+ rejectOnStop(new ZenoError("stopped"));
224
224
  }
225
- if (running) running.stop();
226
- else forgetStored(endpoint).catch(() => {});
225
+ if (runningAgent) runningAgent.stop();
226
+ else clearVisitorCookie(endpoint).catch(() => {});
227
227
  }
228
228
  };
229
229
  };
package/dist/index.d.cts CHANGED
@@ -67,9 +67,9 @@ type Zeno = {
67
67
  //#endregion
68
68
  //#region src/browser/forget.d.ts
69
69
  /**
70
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
71
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
72
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
70
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
71
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
72
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
73
73
  *
74
74
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
75
75
  */
package/dist/index.d.ts CHANGED
@@ -67,9 +67,9 @@ type Zeno = {
67
67
  //#endregion
68
68
  //#region src/browser/forget.d.ts
69
69
  /**
70
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
71
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
72
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
70
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
71
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
72
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
73
73
  *
74
74
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
75
75
  */
package/dist/index.js CHANGED
@@ -27,21 +27,21 @@ var ZenoError = class extends Error {
27
27
  const toZenoError = (error) => {
28
28
  if (error instanceof ZenoError) return error;
29
29
  const { name, code, message } = typeof error === "object" && error !== null ? error : {};
30
- const text = typeof message === "string" ? message : void 0;
31
- return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
30
+ const messageText = typeof message === "string" ? message : void 0;
31
+ return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
32
32
  };
33
33
  //#endregion
34
34
  //#region src/browser/csp.ts
35
35
  const watchCsp = (origin) => {
36
- let blocked = false;
36
+ let isBlocked = false;
37
37
  const listener = (event) => {
38
- if (event.blockedURI.startsWith(origin)) blocked = true;
38
+ if (event.blockedURI.startsWith(origin)) isBlocked = true;
39
39
  };
40
40
  globalThis.document?.addEventListener("securitypolicyviolation", listener);
41
41
  return {
42
- failure: async (otherwise, blockedMessage) => {
42
+ errorFor: async (fallback, blockedMessage) => {
43
43
  await new Promise((resolve) => setTimeout(resolve, 0));
44
- return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
44
+ return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
45
45
  },
46
46
  stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
47
47
  };
@@ -55,13 +55,13 @@ const importModule = (url) => import(
55
55
  );
56
56
  //#endregion
57
57
  //#region src/browser/options.ts
58
- const invalid = (message) => new ZenoError("invalid_options", message);
58
+ const invalidOptions = (message) => new ZenoError("invalid_options", message);
59
59
  const resolveEndpoint = (value) => {
60
60
  if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
61
61
  try {
62
- const page = new URL(globalThis.location.href);
63
- const url = new URL(value, page);
64
- return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
62
+ const pageUrl = new URL(globalThis.location.href);
63
+ const url = new URL(value, pageUrl);
64
+ return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
65
65
  } catch {
66
66
  return;
67
67
  }
@@ -69,20 +69,20 @@ const resolveEndpoint = (value) => {
69
69
  const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
70
70
  const checkProxyEndpoint = (path, call = "start") => {
71
71
  const url = resolveEndpoint(path ?? "/zeno");
72
- if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
72
+ if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
73
73
  return url;
74
74
  };
75
75
  const checkIdentifyOptions = (options) => {
76
- if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
76
+ if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
77
77
  const { externalId, action, metadata } = options;
78
- if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
79
- if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
80
- if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("action must be a string of at most 1,024 characters");
81
- if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
78
+ if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
79
+ if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
80
+ if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
81
+ if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
82
82
  };
83
83
  //#endregion
84
84
  //#region src/browser/storage.ts
85
- const forgetStored = (endpoint) => {
85
+ const clearVisitorCookie = (endpoint) => {
86
86
  return fetch(`${endpoint}?forget`, {
87
87
  method: "POST",
88
88
  credentials: "same-origin",
@@ -92,49 +92,49 @@ const forgetStored = (endpoint) => {
92
92
  //#endregion
93
93
  //#region src/browser/forget.ts
94
94
  /**
95
- * Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
96
- * withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
97
- * stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
95
+ * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
96
+ * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
97
+ * cleared the cookie; on the server it rejects with `not_in_browser`.
98
98
  *
99
99
  * @param path The same path on this site you pass to `start()`, `/zeno` by default.
100
100
  */
101
101
  const forget = async (path) => {
102
102
  if (typeof document === "undefined") throw new ZenoError("not_in_browser");
103
103
  const endpoint = checkProxyEndpoint(path, "forget");
104
- const csp = watchCsp(new URL(endpoint).origin);
104
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
105
105
  let response;
106
106
  try {
107
- response = await forgetStored(endpoint);
107
+ response = await clearVisitorCookie(endpoint);
108
108
  } catch {
109
- throw await csp.failure(new ZenoError("network_connection"));
109
+ throw await cspWatcher.errorFor(new ZenoError("network_connection"));
110
110
  } finally {
111
- csp.stop();
111
+ cspWatcher.stop();
112
112
  }
113
113
  if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
114
114
  };
115
115
  //#endregion
116
116
  //#region src/browser/index.ts
117
- const withTimeout = (promise, ms, error) => {
117
+ const withTimeout = (promise, ms, makeError) => {
118
118
  let timer;
119
119
  return Promise.race([promise, new Promise((_, reject) => {
120
- timer = setTimeout(() => reject(error()), ms);
120
+ timer = setTimeout(() => reject(makeError()), ms);
121
121
  })]).finally(() => clearTimeout(timer));
122
122
  };
123
- const failed = (error) => ({
123
+ const toFailedIdentification = (error) => ({
124
124
  requestId: void 0,
125
125
  error: toZenoError(error)
126
126
  });
127
- const ownAnswer = (identification) => {
127
+ const withOwnError = (identification) => {
128
128
  return identification.error ? {
129
129
  ...identification,
130
130
  error: toZenoError(identification.error)
131
131
  } : identification;
132
132
  };
133
- const onServer = () => ({
134
- identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
133
+ const makeServerStub = () => ({
134
+ identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
135
135
  stop() {}
136
136
  });
137
- const refreshChallengeToken = (endpoint) => async () => {
137
+ const makeChallengeTokenRefresh = (endpoint) => async () => {
138
138
  try {
139
139
  const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
140
140
  return toChallengeToken(module?.challengeToken);
@@ -142,7 +142,7 @@ const refreshChallengeToken = (endpoint) => async () => {
142
142
  return;
143
143
  }
144
144
  };
145
- const loadFailure = async (endpoint) => {
145
+ const explainLoadFailure = async (endpoint) => {
146
146
  const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
147
147
  try {
148
148
  const response = await fetch(endpoint, { credentials: "same-origin" });
@@ -159,25 +159,25 @@ const loadFailure = async (endpoint) => {
159
159
  return fallback;
160
160
  }
161
161
  };
162
- const loadAgent = async (endpoint, stopped, started) => {
163
- const csp = watchCsp(new URL(endpoint).origin);
162
+ const loadAgent = async (endpoint, isStopped, onStarted) => {
163
+ const cspWatcher = watchCsp(new URL(endpoint).origin);
164
164
  let module;
165
165
  try {
166
166
  module = await importModule(endpoint);
167
167
  } catch {
168
- const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
169
- throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
168
+ const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
169
+ throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
170
170
  } finally {
171
- csp.stop();
171
+ cspWatcher.stop();
172
172
  }
173
- if (stopped()) throw new ZenoError("stopped");
173
+ if (isStopped()) throw new ZenoError("stopped");
174
174
  if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
175
175
  try {
176
176
  const agent = module.start(new URL(endpoint).pathname, {
177
177
  challengeToken: toChallengeToken(module.challengeToken),
178
- refreshChallengeToken: refreshChallengeToken(endpoint)
178
+ refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
179
179
  });
180
- started(agent);
180
+ onStarted(agent);
181
181
  return agent;
182
182
  } catch (error) {
183
183
  throw toZenoError(error);
@@ -190,39 +190,39 @@ const loadAgent = async (endpoint, stopped, started) => {
190
190
  * fragment. The script loads from it and identifies through it.
191
191
  */
192
192
  const start = (path) => {
193
- if (typeof document === "undefined") return onServer();
193
+ if (typeof document === "undefined") return makeServerStub();
194
194
  const endpoint = checkProxyEndpoint(path);
195
- let stopped = false;
196
- let running;
197
- let rejectStopped = () => {};
198
- const stopping = new Promise((_, reject) => {
199
- rejectStopped = reject;
195
+ let isStopped = false;
196
+ let runningAgent;
197
+ let rejectOnStop = () => {};
198
+ const stopSignal = new Promise((_, reject) => {
199
+ rejectOnStop = reject;
200
200
  });
201
- stopping.catch(() => {});
202
- const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
203
- loaded.catch(() => {});
201
+ stopSignal.catch(() => {});
202
+ const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
203
+ agentLoading.catch(() => {});
204
204
  const identify = async (identifyOptions) => {
205
- if (stopped) throw new ZenoError("stopped");
205
+ if (isStopped) throw new ZenoError("stopped");
206
206
  checkIdentifyOptions(identifyOptions);
207
207
  const timeout = IDENTIFY_TIMEOUT;
208
- const started = performance.now();
209
- const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
210
- const left = Math.max(1, timeout - (performance.now() - started));
211
- if (stopped) throw new ZenoError("stopped");
212
- return ownAnswer(await agent.identify({
208
+ const startedAt = performance.now();
209
+ const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
210
+ const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
211
+ if (isStopped) throw new ZenoError("stopped");
212
+ return withOwnError(await agent.identify({
213
213
  ...identifyOptions,
214
- timeout: left
214
+ timeout: timeLeft
215
215
  }));
216
216
  };
217
217
  return {
218
- identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
218
+ identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
219
219
  stop() {
220
- if (!stopped) {
221
- stopped = true;
222
- rejectStopped(new ZenoError("stopped"));
220
+ if (!isStopped) {
221
+ isStopped = true;
222
+ rejectOnStop(new ZenoError("stopped"));
223
223
  }
224
- if (running) running.stop();
225
- else forgetStored(endpoint).catch(() => {});
224
+ if (runningAgent) runningAgent.stop();
225
+ else clearVisitorCookie(endpoint).catch(() => {});
226
226
  }
227
227
  };
228
228
  };