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/README.md +35 -15
- package/dist/index.cjs +62 -62
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +62 -62
- package/dist/server/index.cjs +187 -173
- package/dist/server/index.d.cts +17 -5
- package/dist/server/index.d.ts +17 -5
- package/dist/server/index.js +187 -173
- package/dist/server/node.cjs +18 -18
- package/dist/server/node.js +18 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,21 +18,24 @@ One package for the browser and the server. `zeno.id/server` holds your API key,
|
|
|
18
18
|
ZENO_API_KEY=sk_...
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
2. Make the proxy route
|
|
21
|
+
2. Make the proxy route once, with the key, and mount it on your site at a path of your choice (`/zeno` here).
|
|
22
22
|
3. In the browser, on a page with an action you want to identify (a login, signup or checkout), `start()` the browser SDK (`zeno.id`) with the same path when the page loads (it gathers signals; nothing is sent or billed), call `identify()` when the user takes the action, the identity check, and send its `requestId` to your server with the action's request.
|
|
23
|
-
4. On your server, `verify` the request ID and allow, challenge or block.
|
|
23
|
+
4. On your server, make an API client with the same key, `verify` the request ID and allow, challenge or block.
|
|
24
24
|
|
|
25
25
|
```ts
|
|
26
26
|
// zeno.ts
|
|
27
|
-
import {
|
|
27
|
+
import { createProxy } from 'zeno.id/server'
|
|
28
28
|
|
|
29
29
|
// Your proxy route: the browser SDK talks to Zeno through it
|
|
30
30
|
export const zeno = createProxy(process.env.ZENO_API_KEY)
|
|
31
|
-
// For verify() in your server's handlers
|
|
32
|
-
export const client = createClient(process.env.ZENO_API_KEY)
|
|
33
31
|
```
|
|
34
32
|
|
|
35
33
|
```ts
|
|
34
|
+
import { createClient } from 'zeno.id/server'
|
|
35
|
+
|
|
36
|
+
// Your API client, made once with the project's API key
|
|
37
|
+
const client = createClient(process.env.ZENO_API_KEY)
|
|
38
|
+
|
|
36
39
|
// After the password matched:
|
|
37
40
|
const {
|
|
38
41
|
action, // 'allow', 'challenge' or 'block'
|
|
@@ -47,7 +50,7 @@ if (action === 'block') {
|
|
|
47
50
|
}
|
|
48
51
|
```
|
|
49
52
|
|
|
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
|
|
53
|
+
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
54
|
|
|
52
55
|
## In the browser
|
|
53
56
|
|
|
@@ -56,10 +59,12 @@ Call `start()` on a page with an action you want to identify (a login, signup or
|
|
|
56
59
|
```ts
|
|
57
60
|
import { start } from 'zeno.id'
|
|
58
61
|
|
|
59
|
-
//
|
|
60
|
-
|
|
62
|
+
// Start as early as you can: it loads Zeno and starts reading the browser,
|
|
63
|
+
// so identify() is quick later (your proxy route's path)
|
|
64
|
+
const zeno = start('/zeno')
|
|
61
65
|
|
|
62
|
-
//
|
|
66
|
+
// Recognise the browser the moment the user logs in
|
|
67
|
+
// (never throws: requestId is undefined when nothing was identified)
|
|
63
68
|
const { requestId } = await zeno.identify({ action: 'login' })
|
|
64
69
|
|
|
65
70
|
const response = await fetch('/api/login', {
|
|
@@ -114,6 +119,8 @@ The script keeps no visitor id itself. The route keeps it in the `zeno_id` cooki
|
|
|
114
119
|
`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
120
|
|
|
116
121
|
```ts
|
|
122
|
+
import { forget, start, type Zeno } from 'zeno.id'
|
|
123
|
+
|
|
117
124
|
let zeno: Zeno | undefined
|
|
118
125
|
|
|
119
126
|
consentTool.onChange(async ({ fraudPrevention }) => {
|
|
@@ -242,8 +249,8 @@ Bun.serve({
|
|
|
242
249
|
```
|
|
243
250
|
|
|
244
251
|
```ts
|
|
245
|
-
import { env } from 'cloudflare:workers'
|
|
246
252
|
// A Cloudflare Worker
|
|
253
|
+
import { env } from 'cloudflare:workers'
|
|
247
254
|
import { createProxy } from 'zeno.id/server'
|
|
248
255
|
|
|
249
256
|
// Your proxy route: the browser SDK talks to Zeno through it
|
|
@@ -262,7 +269,6 @@ The docs' quickstart has SvelteKit, Nuxt, React Router, SolidStart, Astro and Ho
|
|
|
262
269
|
| Option | |
|
|
263
270
|
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
264
271
|
| `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
272
|
|
|
267
273
|
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
274
|
|
|
@@ -274,7 +280,7 @@ The route checks a `POST` before it calls Zeno: a JSON body of at most 128 KB wi
|
|
|
274
280
|
|
|
275
281
|
## Verify
|
|
276
282
|
|
|
277
|
-
`client.verify(requestId, { ip?, externalId?, maxAge? }?)` sends the request ID to `POST /verify`, which checks it and answers `{ action, reasons, event? }`. Each request ID verifies once. The event comes with its `velocity`, as `getEvent` has it, from before verify attached your `externalId`: `event.velocity['24h'].distinctExternalId` counts the users seen on this browser today, and `sameAction` its events with this event's action, for a site without external IDs. Identical devices can look like one browser, so treat a busy one as a lead to review.
|
|
283
|
+
`client.verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` sends the request ID to `POST /verify`, which checks it and answers `{ action, reasons, event? }`. Each request ID verifies once. The event comes with its `velocity`, as `getEvent` has it, from before verify attached your `externalId`: `event.velocity['24h'].distinctExternalId` counts the users seen on this browser today, and `sameAction` its events with this event's action, for a site without external IDs. Identical devices can look like one browser, so treat a busy one as a lead to review.
|
|
278
284
|
|
|
279
285
|
| Answer | When |
|
|
280
286
|
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -299,10 +305,24 @@ const { action } = await client.verify(requestId, {
|
|
|
299
305
|
|
|
300
306
|
`ip` is optional: pass the same client IP your proxy route got, not your load balancer's, and a request ID sent from another ip blocks with `ip-mismatch`; leave it out (or pass `null` or `undefined`) and there's no ip check, as there's none between an IPv4 and an IPv6 address. `no-request-id` is a `challenge` so you decide: ask for a second factor, or let it through and flag the account; never treat it as verified. API errors throw a `ZenoError`.
|
|
301
307
|
|
|
308
|
+
A lost answer is safe to retry. Each call sends an `idempotencyKey`, and after a network error or a `5xx` the SDK sends it again, twice at most, with the same key; a repeat with the same key within 5 minutes answers what the first call did instead of `already-used`. If your own code may send the same verify again (a retried job, a second try of your handler), pass your own `idempotencyKey`, 8 to 128 characters, like your request's ID.
|
|
309
|
+
|
|
310
|
+
### Test keys
|
|
311
|
+
|
|
312
|
+
For automated tests and staging, use a test key in place of your API key, in `createProxy` and `createClient`. Each answers `verify` the same every time, with a sample event; nothing is stored or billed, a test request ID can be verified again and again, and other calls refuse a test key. Without a request ID each answers `challenge` with `no-request-id`, like a real key.
|
|
313
|
+
|
|
314
|
+
| Test key | `verify` answers |
|
|
315
|
+
| ------------------- | ----------------------- |
|
|
316
|
+
| `sk_test_allow` | `allow` |
|
|
317
|
+
| `sk_test_challenge` | `challenge`, with `vpn` |
|
|
318
|
+
| `sk_test_block` | `block`, with `bad-bot` |
|
|
319
|
+
|
|
302
320
|
## Server API
|
|
303
321
|
|
|
304
322
|
```ts
|
|
305
|
-
import {
|
|
323
|
+
import { createClient } from 'zeno.id/server'
|
|
324
|
+
|
|
325
|
+
const client = createClient(process.env.ZENO_API_KEY)
|
|
306
326
|
|
|
307
327
|
const event = await client.getEvent(requestId)
|
|
308
328
|
const { items, cursor } = await client.searchEvents({
|
|
@@ -341,7 +361,7 @@ const { url } = await client.createEmbed({
|
|
|
341
361
|
|
|
342
362
|
| Method | Call |
|
|
343
363
|
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
|
|
344
|
-
| `verify(requestId, { ip?, externalId?, maxAge? }?)`
|
|
364
|
+
| `verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
|
|
345
365
|
| `getEvent(requestId)` | `GET /events/{requestId}` |
|
|
346
366
|
| `searchEvents(filters)` | `GET /events?...` |
|
|
347
367
|
| `getVisitor(visitorId)` | `GET /visitors/{visitorId}` |
|
|
@@ -359,7 +379,7 @@ A list filter (`apiKeyId`, `country`, `origin`, `asn`, `browser`, `os`, `action`
|
|
|
359
379
|
|
|
360
380
|
A failed call throws a `ZenoError` with the `status` and the API's error `code` (`ZenoErrorCode`), like `not_found`. A call answered `429 rate_limited` or `503 search_unavailable` is sent again after the API's `Retry-After`, twice, a little later each time at random so calls limited together don't all come back at once; the error of one that stays limited has `retryAfter` in seconds. Neither was carried out, so retrying a write or a delete is safe.
|
|
361
381
|
|
|
362
|
-
The SDK's own codes: `network_error` (status `0`) when the API can't be reached or doesn't answer within 10 seconds,
|
|
382
|
+
The SDK's own codes: `network_error` (status `0`) when the API can't be reached or doesn't answer within 10 seconds, retried only for `verify` (above); `invalid_request` with status `0` for an empty id (`getEvent('')`), refused before anything is sent; `request_failed` for an error answer without a code, or a success answer that isn't what the call returns (each answer is checked before it's handed back, so something between your server and Zeno that answers otherwise fails here rather than later in your code).
|
|
363
383
|
|
|
364
384
|
`addRelation` is the one billed call: each is billed like an identification and counts toward the free monthly identifications and the spend limits (reads, `createEmbed` and what events relate by themselves are free). Once a spend limit you set for the project, its organization or the key is reached it throws a `402` `spend_limit_reached` and adds nothing. Every call answers `402` `account_closed` while Zeno has closed the organization's account (for unpaid invoices); contact support to reopen it.
|
|
365
385
|
|
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
|
|
32
|
-
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code,
|
|
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
|
|
37
|
+
let isBlocked = false;
|
|
38
38
|
const listener = (event) => {
|
|
39
|
-
if (event.blockedURI.startsWith(origin))
|
|
39
|
+
if (event.blockedURI.startsWith(origin)) isBlocked = true;
|
|
40
40
|
};
|
|
41
41
|
globalThis.document?.addEventListener("securitypolicyviolation", listener);
|
|
42
42
|
return {
|
|
43
|
-
|
|
43
|
+
errorFor: async (fallback, blockedMessage) => {
|
|
44
44
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
45
|
-
return
|
|
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
|
|
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
|
|
64
|
-
const url = new URL(value,
|
|
65
|
-
return url.origin ===
|
|
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
|
|
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
|
|
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
|
|
80
|
-
if (externalId === "." || externalId === "..") throw
|
|
81
|
-
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw
|
|
82
|
-
if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw
|
|
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
|
|
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
|
|
97
|
-
*
|
|
98
|
-
*
|
|
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
|
|
105
|
+
const cspWatcher = watchCsp(new URL(endpoint).origin);
|
|
106
106
|
let response;
|
|
107
107
|
try {
|
|
108
|
-
response = await
|
|
108
|
+
response = await clearVisitorCookie(endpoint);
|
|
109
109
|
} catch {
|
|
110
|
-
throw await
|
|
110
|
+
throw await cspWatcher.errorFor(new ZenoError("network_connection"));
|
|
111
111
|
} finally {
|
|
112
|
-
|
|
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,
|
|
118
|
+
const withTimeout = (promise, ms, makeError) => {
|
|
119
119
|
let timer;
|
|
120
120
|
return Promise.race([promise, new Promise((_, reject) => {
|
|
121
|
-
timer = setTimeout(() => reject(
|
|
121
|
+
timer = setTimeout(() => reject(makeError()), ms);
|
|
122
122
|
})]).finally(() => clearTimeout(timer));
|
|
123
123
|
};
|
|
124
|
-
const
|
|
124
|
+
const toFailedIdentification = (error) => ({
|
|
125
125
|
requestId: void 0,
|
|
126
126
|
error: toZenoError(error)
|
|
127
127
|
});
|
|
128
|
-
const
|
|
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
|
|
135
|
-
identify: () => Promise.resolve(
|
|
134
|
+
const makeServerStub = () => ({
|
|
135
|
+
identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
|
|
136
136
|
stop() {}
|
|
137
137
|
});
|
|
138
|
-
const
|
|
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
|
|
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,
|
|
164
|
-
const
|
|
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
|
|
170
|
-
throw
|
|
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
|
-
|
|
172
|
+
cspWatcher.stop();
|
|
173
173
|
}
|
|
174
|
-
if (
|
|
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:
|
|
179
|
+
refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
|
|
180
180
|
});
|
|
181
|
-
|
|
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
|
|
194
|
+
if (typeof document === "undefined") return makeServerStub();
|
|
195
195
|
const endpoint = checkProxyEndpoint(path);
|
|
196
|
-
let
|
|
197
|
-
let
|
|
198
|
-
let
|
|
199
|
-
const
|
|
200
|
-
|
|
196
|
+
let isStopped = false;
|
|
197
|
+
let runningAgent;
|
|
198
|
+
let rejectOnStop = () => {};
|
|
199
|
+
const stopSignal = new Promise((_, reject) => {
|
|
200
|
+
rejectOnStop = reject;
|
|
201
201
|
});
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
202
|
+
stopSignal.catch(() => {});
|
|
203
|
+
const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
|
|
204
|
+
agentLoading.catch(() => {});
|
|
205
205
|
const identify = async (identifyOptions) => {
|
|
206
|
-
if (
|
|
206
|
+
if (isStopped) throw new ZenoError("stopped");
|
|
207
207
|
checkIdentifyOptions(identifyOptions);
|
|
208
208
|
const timeout = IDENTIFY_TIMEOUT;
|
|
209
|
-
const
|
|
210
|
-
const agent = await withTimeout(Promise.race([
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
213
|
-
return
|
|
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:
|
|
215
|
+
timeout: timeLeft
|
|
216
216
|
}));
|
|
217
217
|
};
|
|
218
218
|
return {
|
|
219
|
-
identify: (identifyOptions = {}) => identify(identifyOptions).catch(
|
|
219
|
+
identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
|
|
220
220
|
stop() {
|
|
221
|
-
if (!
|
|
222
|
-
|
|
223
|
-
|
|
221
|
+
if (!isStopped) {
|
|
222
|
+
isStopped = true;
|
|
223
|
+
rejectOnStop(new ZenoError("stopped"));
|
|
224
224
|
}
|
|
225
|
-
if (
|
|
226
|
-
else
|
|
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
|
|
71
|
-
*
|
|
72
|
-
*
|
|
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
|
|
71
|
-
*
|
|
72
|
-
*
|
|
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
|
*/
|