zeno.id 0.2.0 → 0.3.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/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
  };