@askdialog/tracker 0.0.0-beta-20261202105047 → 0.0.0-stage

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.
Files changed (39) hide show
  1. package/README.md +2 -13
  2. package/package.json +3 -59
  3. package/dist/browser/documentCookieJar.d.ts +0 -5
  4. package/dist/browser/documentCookieJar.d.ts.map +0 -1
  5. package/dist/browser/documentCookieJar.js +0 -9
  6. package/dist/cjs/browser/documentCookieJar.js +0 -12
  7. package/dist/cjs/core/cookie.js +0 -37
  8. package/dist/cjs/core/dialogVisitor.js +0 -24
  9. package/dist/cjs/core/envelope.js +0 -35
  10. package/dist/cjs/core/index.js +0 -29
  11. package/dist/cjs/core/sender.js +0 -116
  12. package/dist/cjs/core/sessionCookie.js +0 -51
  13. package/dist/cjs/core/visitorCookie.js +0 -30
  14. package/dist/cjs/index.js +0 -20
  15. package/dist/cjs/package.json +0 -1
  16. package/dist/core/cookie.d.ts +0 -12
  17. package/dist/core/cookie.d.ts.map +0 -1
  18. package/dist/core/cookie.js +0 -31
  19. package/dist/core/dialogVisitor.d.ts +0 -8
  20. package/dist/core/dialogVisitor.d.ts.map +0 -1
  21. package/dist/core/dialogVisitor.js +0 -19
  22. package/dist/core/envelope.d.ts +0 -54
  23. package/dist/core/envelope.d.ts.map +0 -1
  24. package/dist/core/envelope.js +0 -29
  25. package/dist/core/index.d.ts +0 -7
  26. package/dist/core/index.d.ts.map +0 -1
  27. package/dist/core/index.js +0 -5
  28. package/dist/core/sender.d.ts +0 -3
  29. package/dist/core/sender.d.ts.map +0 -1
  30. package/dist/core/sender.js +0 -112
  31. package/dist/core/sessionCookie.d.ts +0 -4
  32. package/dist/core/sessionCookie.d.ts.map +0 -1
  33. package/dist/core/sessionCookie.js +0 -47
  34. package/dist/core/visitorCookie.d.ts +0 -4
  35. package/dist/core/visitorCookie.d.ts.map +0 -1
  36. package/dist/core/visitorCookie.js +0 -26
  37. package/dist/index.d.ts +0 -3
  38. package/dist/index.d.ts.map +0 -1
  39. package/dist/index.js +0 -2
package/README.md CHANGED
@@ -1,14 +1,3 @@
1
- # @askdialog/tracker
1
+ # Temporary Holding Version
2
2
 
3
- Dialog's storefront tracker. It depends on nothing from Dialog: its only runtime dependency is `uuidv7`.
4
-
5
- ## Entries
6
-
7
- - `@askdialog/tracker/core` runs where `window` and `document` do not exist, such as the Shopify web pixel's sandbox. It builds storefront events, sends them to the collector and keeps the visitor and session cookies through a `CookieJar` it is given.
8
- - `@askdialog/tracker` is the browser entry: the core, and `documentCookieJar`, the `CookieJar` of `document.cookie`.
9
-
10
- ## Core
11
-
12
- - `createStorefrontEvent` and `attributeStorefrontEvent` build the event's CloudEvents envelope, typed `com.dialog.storefront.<name>` with a uuidv7 `id`.
13
- - `sendStorefrontEvent(url, event)` sends in batches of up to 20 events, or after 1 s without a new one, each body under 60 kB, with `keepalive` when the page hides, and retries 3 times on no answer, 429 or 5xx. It never rejects. Without a page, it sends at once.
14
- - `getOrCreateDialogVisitor(jar, location)` reads or creates `_dialog_visitor_id` (13 months, on the widest domain the browser accepts; undefined when the browser refuses it) and `_dialog_session_id` (30 min idle, 24 h at most). `deleteDialogVisitor(jar, location)` deletes both.
3
+ This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/package.json CHANGED
@@ -1,62 +1,6 @@
1
1
  {
2
2
  "name": "@askdialog/tracker",
3
- "version": "0.0.0-beta-20261202105047",
4
- "private": false,
5
- "description": "Dialog storefront tracker",
6
- "type": "module",
7
- "sideEffects": false,
8
- "main": "dist/cjs/index.js",
9
- "module": "dist/index.js",
10
- "types": "dist/index.d.ts",
11
- "exports": {
12
- ".": {
13
- "types": "./dist/index.d.ts",
14
- "import": "./dist/index.js",
15
- "require": "./dist/cjs/index.js"
16
- },
17
- "./core": {
18
- "types": "./dist/core/index.d.ts",
19
- "import": "./dist/core/index.js",
20
- "require": "./dist/cjs/core/index.js"
21
- }
22
- },
23
- "typesVersions": {
24
- "*": {
25
- "core": [
26
- "dist/core/index.d.ts"
27
- ]
28
- }
29
- },
30
- "files": [
31
- "dist"
32
- ],
33
- "keywords": [
34
- "dialog",
35
- "analytics",
36
- "ecommerce",
37
- "tracker"
38
- ],
39
- "author": "Dialog",
40
- "license": "MIT",
41
- "dependencies": {
42
- "uuidv7": "^1.0.2"
43
- },
44
- "devDependencies": {
45
- "eslint-import-resolver-typescript": "^4.4.4",
46
- "eslint-plugin-import": "^2.32.0",
47
- "jsdom": "^26.1.0",
48
- "vitest": "^3.0.0"
49
- },
50
- "publishConfig": {
51
- "access": "public"
52
- },
53
- "scripts": {
54
- "clean": "rm -rf dist",
55
- "build": "pnpm run clean && tsc -p tsconfig.build.json && pnpm run build:cjs",
56
- "build:cjs": "node scripts/build-cjs.mjs",
57
- "lint": "eslint .",
58
- "lint:fix": "eslint . --fix",
59
- "test": "vitest run",
60
- "test-type": "tsc --noEmit"
61
- }
3
+ "version": "0.0.0-stage",
4
+ "stub": true,
5
+ "description": "Temporary package placeholder for staged publishing"
62
6
  }
@@ -1,5 +0,0 @@
1
- export declare const documentCookieJar: {
2
- get: (name: string) => string | undefined;
3
- set: (cookie: string) => void;
4
- };
5
- //# sourceMappingURL=documentCookieJar.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentCookieJar.d.ts","sourceRoot":"","sources":["../../src/browser/documentCookieJar.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,iBAAiB;gBAChB,MAAM,KAAG,MAAM,GAAG,SAAS;kBAKzB,MAAM,KAAG,IAAI;CAGR,CAAC"}
@@ -1,9 +0,0 @@
1
- export const documentCookieJar = {
2
- get: (name) => document.cookie
3
- .split("; ")
4
- .find((cookie) => cookie.startsWith(`${name}=`))
5
- ?.slice(name.length + 1),
6
- set: (cookie) => {
7
- document.cookie = cookie;
8
- },
9
- };
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.documentCookieJar = void 0;
4
- exports.documentCookieJar = {
5
- get: (name) => document.cookie
6
- .split("; ")
7
- .find((cookie) => cookie.startsWith(`${name}=`))
8
- ?.slice(name.length + 1),
9
- set: (cookie) => {
10
- document.cookie = cookie;
11
- },
12
- };
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteCookie = exports.buildCookie = exports.cookieDomains = void 0;
4
- const HTTPS_PROTOCOL = "https:";
5
- const LOCALHOST = "localhost";
6
- // Widest first: the browser refuses public suffixes (`.com`, `.myshopify.com`). Last, the host alone.
7
- const cookieDomains = (hostname) => {
8
- if (hostname === LOCALHOST || /^[0-9.]+$/.test(hostname)) {
9
- return [undefined];
10
- }
11
- const labels = hostname.split(".");
12
- return [
13
- ...labels
14
- .slice(0, -1)
15
- .map((_, index) => `.${labels.slice(index).join(".")}`)
16
- .reverse(),
17
- undefined,
18
- ];
19
- };
20
- exports.cookieDomains = cookieDomains;
21
- const buildCookie = (nameAndValue, maxAgeSeconds, domain, location) => {
22
- const domainAttribute = domain === undefined ? "" : `; domain=${domain}`;
23
- const secure = location.protocol === HTTPS_PROTOCOL ? "; Secure" : "";
24
- return `${nameAndValue}; path=/; max-age=${maxAgeSeconds}; SameSite=Lax${domainAttribute}${secure}`;
25
- };
26
- exports.buildCookie = buildCookie;
27
- // Expires the cookie on every domain it may have been written to.
28
- // Only when present, so a visitor who never had one never sees Dialog write a cookie.
29
- const deleteCookie = async (jar, name, location) => {
30
- if ((await jar.get(name)) === undefined) {
31
- return;
32
- }
33
- for (const domain of (0, exports.cookieDomains)(location.hostname)) {
34
- await jar.set((0, exports.buildCookie)(`${name}=`, 0, domain, location));
35
- }
36
- };
37
- exports.deleteCookie = deleteCookie;
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteDialogVisitor = exports.getOrCreateDialogVisitor = void 0;
4
- const cookie_js_1 = require("./cookie.js");
5
- const sessionCookie_js_1 = require("./sessionCookie.js");
6
- const visitorCookie_js_1 = require("./visitorCookie.js");
7
- // Called on every event, after consent. Undefined without a stored visitor cookie;
8
- // a session that cannot be stored only leaves the event without one.
9
- const getOrCreateDialogVisitor = async (jar, location) => {
10
- const visitorId = await (0, visitorCookie_js_1.getOrCreateDialogVisitorId)(jar, location);
11
- if (visitorId === undefined) {
12
- return undefined;
13
- }
14
- return {
15
- dialog_visitor_id: visitorId,
16
- dialog_session_id: await (0, sessionCookie_js_1.getOrCreateDialogSessionId)(jar, location).catch(() => undefined),
17
- };
18
- };
19
- exports.getOrCreateDialogVisitor = getOrCreateDialogVisitor;
20
- const deleteDialogVisitor = async (jar, location) => {
21
- await (0, cookie_js_1.deleteCookie)(jar, visitorCookie_js_1.DIALOG_VISITOR_ID_COOKIE, location);
22
- await (0, cookie_js_1.deleteCookie)(jar, sessionCookie_js_1.DIALOG_SESSION_ID_COOKIE, location);
23
- };
24
- exports.deleteDialogVisitor = deleteDialogVisitor;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.attributeStorefrontEvent = exports.createStorefrontEvent = exports.storefrontEventType = exports.STOREFRONT_EVENT_TYPE_PREFIX = void 0;
4
- const uuidv7_1 = require("uuidv7");
5
- exports.STOREFRONT_EVENT_TYPE_PREFIX = "com.dialog.storefront.";
6
- const storefrontEventType = (name) => `${exports.STOREFRONT_EVENT_TYPE_PREFIX}${name}`;
7
- exports.storefrontEventType = storefrontEventType;
8
- // GA4 passes the page fields among the properties: there they override the page's own and move to data.context.
9
- const createStorefrontEvent = ({ name, properties, page, context, id, time, }) => {
10
- const { page_location, page_title, page_referrer, viewport_width, viewport_height, ...ownProperties } = { ...page, ...properties };
11
- return {
12
- specversion: "1.0",
13
- id: id ?? (0, uuidv7_1.uuidv7)(),
14
- type: (0, exports.storefrontEventType)(name),
15
- time: time ?? new Date().toISOString(),
16
- data: {
17
- context: {
18
- ...context,
19
- page_location,
20
- page_title,
21
- page_referrer,
22
- viewport_width,
23
- viewport_height,
24
- },
25
- properties: ownProperties,
26
- },
27
- };
28
- };
29
- exports.createStorefrontEvent = createStorefrontEvent;
30
- const attributeStorefrontEvent = (event, source, attribution) => ({
31
- ...event,
32
- source,
33
- data: { ...event.data, context: { ...event.data.context, ...attribution } },
34
- });
35
- exports.attributeStorefrontEvent = attributeStorefrontEvent;
@@ -1,29 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getOrCreateDialogVisitorId = exports.DIALOG_VISITOR_ID_COOKIE = exports.getOrCreateDialogSessionId = exports.DIALOG_SESSION_ID_COOKIE = exports.sendStorefrontEvent = exports.getOrCreateDialogVisitor = exports.deleteDialogVisitor = void 0;
18
- var dialogVisitor_js_1 = require("./dialogVisitor.js");
19
- Object.defineProperty(exports, "deleteDialogVisitor", { enumerable: true, get: function () { return dialogVisitor_js_1.deleteDialogVisitor; } });
20
- Object.defineProperty(exports, "getOrCreateDialogVisitor", { enumerable: true, get: function () { return dialogVisitor_js_1.getOrCreateDialogVisitor; } });
21
- __exportStar(require("./envelope.js"), exports);
22
- var sender_js_1 = require("./sender.js");
23
- Object.defineProperty(exports, "sendStorefrontEvent", { enumerable: true, get: function () { return sender_js_1.sendStorefrontEvent; } });
24
- var sessionCookie_js_1 = require("./sessionCookie.js");
25
- Object.defineProperty(exports, "DIALOG_SESSION_ID_COOKIE", { enumerable: true, get: function () { return sessionCookie_js_1.DIALOG_SESSION_ID_COOKIE; } });
26
- Object.defineProperty(exports, "getOrCreateDialogSessionId", { enumerable: true, get: function () { return sessionCookie_js_1.getOrCreateDialogSessionId; } });
27
- var visitorCookie_js_1 = require("./visitorCookie.js");
28
- Object.defineProperty(exports, "DIALOG_VISITOR_ID_COOKIE", { enumerable: true, get: function () { return visitorCookie_js_1.DIALOG_VISITOR_ID_COOKIE; } });
29
- Object.defineProperty(exports, "getOrCreateDialogVisitorId", { enumerable: true, get: function () { return visitorCookie_js_1.getOrCreateDialogVisitorId; } });
@@ -1,116 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sendStorefrontEvent = void 0;
4
- const IDLE_FLUSH_MS = 1000;
5
- const MAX_BATCH_EVENTS = 20;
6
- // Browsers share 64 KiB between a page's pending keepalive requests: each body, and all of them, stay under it.
7
- const MAX_KEEPALIVE_BYTES = 60_000;
8
- const MAX_RETRIES = 3;
9
- const RETRY_DELAY_MS = 1000;
10
- const RETRY_JITTER_MS = 1000;
11
- const queue = [];
12
- const retries = new Map();
13
- let pendingKeepaliveBytes = 0;
14
- let idleTimer;
15
- let queuedEvents = 0;
16
- // Page hidden: keepalive whatever the budget, since the page may not live to send it otherwise.
17
- // A batch over the limit (one event larger than it) never: the browser would refuse it outright.
18
- const keepaliveBytes = (batch, pageHidden) => {
19
- const withinBudget = pageHidden || pendingKeepaliveBytes + batch.bytes <= MAX_KEEPALIVE_BYTES;
20
- return withinBudget && batch.bytes <= MAX_KEEPALIVE_BYTES ? batch.bytes : 0;
21
- };
22
- const post = async (batch, pageHidden) => {
23
- const reserved = keepaliveBytes(batch, pageHidden);
24
- pendingKeepaliveBytes += reserved;
25
- const body = `[${batch.events.join(",")}]`;
26
- const headers = { "Content-Type": "application/json" };
27
- return fetch(batch.url, {
28
- method: "POST",
29
- headers,
30
- body,
31
- keepalive: reserved > 0,
32
- })
33
- .then((response) => response.status)
34
- .catch(() => 0)
35
- .finally(() => {
36
- pendingKeepaliveBytes -= reserved;
37
- });
38
- };
39
- // Status 0 is no answer.
40
- const deliver = async (batch, pageHidden) => {
41
- const status = await post(batch, pageHidden);
42
- const retryable = status === 0 || status === 429 || status >= 500;
43
- if (retryable && batch.retries < MAX_RETRIES) {
44
- const delay = RETRY_DELAY_MS * 2 ** batch.retries++ + Math.random() * RETRY_JITTER_MS;
45
- retries.set(batch, setTimeout(() => retry(batch, false), delay));
46
- return;
47
- }
48
- batch.settles.forEach((settle) => settle());
49
- };
50
- const retry = (batch, pageHidden) => {
51
- clearTimeout(retries.get(batch));
52
- retries.delete(batch);
53
- void deliver(batch, pageHidden);
54
- };
55
- const flush = (pageHidden = false) => {
56
- clearTimeout(idleTimer);
57
- queuedEvents = 0;
58
- queue.splice(0).forEach((batch) => void deliver(batch, pageHidden));
59
- };
60
- const leave = () => {
61
- flush(true);
62
- [...retries.keys()].forEach((batch) => retry(batch, true));
63
- };
64
- // The Shopify pixel's worker has no page: its events go at once.
65
- const hasPage = () => typeof document !== "undefined";
66
- let watchingPage = false;
67
- const watchPage = () => {
68
- watchingPage = true;
69
- addEventListener("pagehide", leave);
70
- document.addEventListener("visibilitychange", () => {
71
- if (document.visibilityState === "hidden") {
72
- leave();
73
- }
74
- });
75
- };
76
- // Resolves once the event's batch is delivered or given up. Best effort: never rejects, even on
77
- // an event JSON cannot serialise (a cycle, a BigInt).
78
- const sendStorefrontEvent = async (url, event) => {
79
- let serialised;
80
- try {
81
- serialised = JSON.stringify(event);
82
- }
83
- catch {
84
- return;
85
- }
86
- if (hasPage() && !watchingPage) {
87
- watchPage();
88
- }
89
- const bytes = new TextEncoder().encode(serialised).length + 1;
90
- await new Promise((settle) => {
91
- const last = queue.at(-1);
92
- if (last?.url === url && last.bytes + bytes < MAX_KEEPALIVE_BYTES) {
93
- last.events.push(serialised);
94
- last.bytes += bytes;
95
- last.settles.push(settle);
96
- }
97
- else {
98
- queue.push({
99
- url,
100
- events: [serialised],
101
- bytes: bytes + 1,
102
- retries: 0,
103
- settles: [settle],
104
- });
105
- }
106
- queuedEvents += 1;
107
- clearTimeout(idleTimer);
108
- if (!hasPage() || queuedEvents >= MAX_BATCH_EVENTS) {
109
- flush();
110
- }
111
- else {
112
- idleTimer = setTimeout(flush, IDLE_FLUSH_MS);
113
- }
114
- });
115
- };
116
- exports.sendStorefrontEvent = sendStorefrontEvent;
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getOrCreateDialogSessionId = exports.DIALOG_SESSION_ID_COOKIE = void 0;
4
- const uuidv7_1 = require("uuidv7");
5
- const cookie_js_1 = require("./cookie.js");
6
- exports.DIALOG_SESSION_ID_COOKIE = "_dialog_session_id";
7
- const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
8
- const MAX_SESSION_MS = 24 * 60 * 60 * 1000;
9
- const ONE_DAY_IN_SECONDS = 24 * 60 * 60;
10
- const parseSession = (value) => {
11
- try {
12
- const parsed = JSON.parse(decodeURIComponent(value ?? ""));
13
- const fields = Array.isArray(parsed) ? parsed : [];
14
- const [lastActivity, id, start] = fields;
15
- return typeof lastActivity === "number" &&
16
- typeof id === "string" &&
17
- typeof start === "number"
18
- ? [lastActivity, id, start]
19
- : undefined;
20
- }
21
- catch {
22
- return undefined;
23
- }
24
- };
25
- const readLiveSession = async (jar, now) => {
26
- const session = parseSession(await jar.get(exports.DIALOG_SESSION_ID_COOKIE));
27
- if (session === undefined) {
28
- return undefined;
29
- }
30
- const [lastActivity, , start] = session;
31
- return now - lastActivity <= IDLE_TIMEOUT_MS && now - start <= MAX_SESSION_MS
32
- ? session
33
- : undefined;
34
- };
35
- // Called on every event: it starts a session, or records the event as the session's last activity.
36
- // Undefined when the browser refuses the cookie.
37
- const getOrCreateDialogSessionId = async (jar, location) => {
38
- const now = Date.now();
39
- for (const domain of (0, cookie_js_1.cookieDomains)(location.hostname)) {
40
- // Read before every write: a session another tab kept alive or rotated is adopted, not replaced,
41
- // and our own write ends the loop once a domain took it.
42
- const [lastActivity, id = (0, uuidv7_1.uuidv7)(), start = now] = (await readLiveSession(jar, now)) ?? [];
43
- if (lastActivity !== undefined && lastActivity >= now) {
44
- return id;
45
- }
46
- const session = encodeURIComponent(JSON.stringify([now, id, start]));
47
- await jar.set((0, cookie_js_1.buildCookie)(`${exports.DIALOG_SESSION_ID_COOKIE}=${session}`, ONE_DAY_IN_SECONDS, domain, location));
48
- }
49
- return (await readLiveSession(jar, now))?.[1];
50
- };
51
- exports.getOrCreateDialogSessionId = getOrCreateDialogSessionId;
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getOrCreateDialogVisitorId = exports.DIALOG_VISITOR_ID_COOKIE = void 0;
4
- const uuidv7_1 = require("uuidv7");
5
- const cookie_js_1 = require("./cookie.js");
6
- exports.DIALOG_VISITOR_ID_COOKIE = "_dialog_visitor_id";
7
- const THIRTEEN_MONTHS_IN_SECONDS = 395 * 24 * 60 * 60;
8
- const readVisitorId = async (jar) => {
9
- const id = await jar.get(exports.DIALOG_VISITOR_ID_COOKIE);
10
- return id === "" ? undefined : id;
11
- };
12
- // Undefined when the browser refuses the cookie: an id that is not stored is no visitor.
13
- const getOrCreateDialogVisitorId = async (jar, location) => {
14
- const existingId = await readVisitorId(jar);
15
- if (existingId !== undefined) {
16
- return existingId;
17
- }
18
- // Generated only when a write is needed: the pixel calls this on every event.
19
- const visitorId = (0, uuidv7_1.uuidv7)();
20
- for (const domain of (0, cookie_js_1.cookieDomains)(location.hostname)) {
21
- // Read before every write: it finds our previous write, or another Dialog script's, which wins.
22
- const storedId = await readVisitorId(jar);
23
- if (storedId !== undefined) {
24
- return storedId;
25
- }
26
- await jar.set((0, cookie_js_1.buildCookie)(`${exports.DIALOG_VISITOR_ID_COOKIE}=${visitorId}`, THIRTEEN_MONTHS_IN_SECONDS, domain, location));
27
- }
28
- return readVisitorId(jar);
29
- };
30
- exports.getOrCreateDialogVisitorId = getOrCreateDialogVisitorId;
package/dist/cjs/index.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.documentCookieJar = void 0;
18
- var documentCookieJar_js_1 = require("./browser/documentCookieJar.js");
19
- Object.defineProperty(exports, "documentCookieJar", { enumerable: true, get: function () { return documentCookieJar_js_1.documentCookieJar; } });
20
- __exportStar(require("./core/index.js"), exports);
@@ -1 +0,0 @@
1
- {"type":"commonjs"}
@@ -1,12 +0,0 @@
1
- export interface CookieJar {
2
- get: (name: string) => string | undefined | Promise<string | undefined>;
3
- set: (cookie: string) => unknown;
4
- }
5
- export interface PageLocation {
6
- hostname: string;
7
- protocol: string;
8
- }
9
- export declare const cookieDomains: (hostname: string) => (string | undefined)[];
10
- export declare const buildCookie: (nameAndValue: string, maxAgeSeconds: number, domain: string | undefined, location: PageLocation) => string;
11
- export declare const deleteCookie: (jar: CookieJar, name: string, location: PageLocation) => Promise<void>;
12
- //# sourceMappingURL=cookie.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cookie.d.ts","sourceRoot":"","sources":["../../src/core/cookie.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,SAAS;IACxB,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACxE,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;CAClC;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAGD,eAAO,MAAM,aAAa,GAAI,UAAU,MAAM,KAAG,CAAC,MAAM,GAAG,SAAS,CAAC,EAcpE,CAAC;AAEF,eAAO,MAAM,WAAW,GACtB,cAAc,MAAM,EACpB,eAAe,MAAM,EACrB,QAAQ,MAAM,GAAG,SAAS,EAC1B,UAAU,YAAY,KACrB,MAKF,CAAC;AAIF,eAAO,MAAM,YAAY,GACvB,KAAK,SAAS,EACd,MAAM,MAAM,EACZ,UAAU,YAAY,KACrB,OAAO,CAAC,IAAI,CAOd,CAAC"}
@@ -1,31 +0,0 @@
1
- const HTTPS_PROTOCOL = "https:";
2
- const LOCALHOST = "localhost";
3
- // Widest first: the browser refuses public suffixes (`.com`, `.myshopify.com`). Last, the host alone.
4
- export const cookieDomains = (hostname) => {
5
- if (hostname === LOCALHOST || /^[0-9.]+$/.test(hostname)) {
6
- return [undefined];
7
- }
8
- const labels = hostname.split(".");
9
- return [
10
- ...labels
11
- .slice(0, -1)
12
- .map((_, index) => `.${labels.slice(index).join(".")}`)
13
- .reverse(),
14
- undefined,
15
- ];
16
- };
17
- export const buildCookie = (nameAndValue, maxAgeSeconds, domain, location) => {
18
- const domainAttribute = domain === undefined ? "" : `; domain=${domain}`;
19
- const secure = location.protocol === HTTPS_PROTOCOL ? "; Secure" : "";
20
- return `${nameAndValue}; path=/; max-age=${maxAgeSeconds}; SameSite=Lax${domainAttribute}${secure}`;
21
- };
22
- // Expires the cookie on every domain it may have been written to.
23
- // Only when present, so a visitor who never had one never sees Dialog write a cookie.
24
- export const deleteCookie = async (jar, name, location) => {
25
- if ((await jar.get(name)) === undefined) {
26
- return;
27
- }
28
- for (const domain of cookieDomains(location.hostname)) {
29
- await jar.set(buildCookie(`${name}=`, 0, domain, location));
30
- }
31
- };
@@ -1,8 +0,0 @@
1
- import { type CookieJar, type PageLocation } from "./cookie.js";
2
- export interface DialogVisitor {
3
- dialog_visitor_id: string;
4
- dialog_session_id?: string;
5
- }
6
- export declare const getOrCreateDialogVisitor: (jar: CookieJar, location: PageLocation) => Promise<DialogVisitor | undefined>;
7
- export declare const deleteDialogVisitor: (jar: CookieJar, location: PageLocation) => Promise<void>;
8
- //# sourceMappingURL=dialogVisitor.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"dialogVisitor.d.ts","sourceRoot":"","sources":["../../src/core/dialogVisitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAgB,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAW9E,MAAM,WAAW,aAAa;IAC5B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAID,eAAO,MAAM,wBAAwB,GACnC,KAAK,SAAS,EACd,UAAU,YAAY,KACrB,OAAO,CAAC,aAAa,GAAG,SAAS,CAYnC,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAC9B,KAAK,SAAS,EACd,UAAU,YAAY,KACrB,OAAO,CAAC,IAAI,CAGd,CAAC"}
@@ -1,19 +0,0 @@
1
- import { deleteCookie } from "./cookie.js";
2
- import { DIALOG_SESSION_ID_COOKIE, getOrCreateDialogSessionId, } from "./sessionCookie.js";
3
- import { DIALOG_VISITOR_ID_COOKIE, getOrCreateDialogVisitorId, } from "./visitorCookie.js";
4
- // Called on every event, after consent. Undefined without a stored visitor cookie;
5
- // a session that cannot be stored only leaves the event without one.
6
- export const getOrCreateDialogVisitor = async (jar, location) => {
7
- const visitorId = await getOrCreateDialogVisitorId(jar, location);
8
- if (visitorId === undefined) {
9
- return undefined;
10
- }
11
- return {
12
- dialog_visitor_id: visitorId,
13
- dialog_session_id: await getOrCreateDialogSessionId(jar, location).catch(() => undefined),
14
- };
15
- };
16
- export const deleteDialogVisitor = async (jar, location) => {
17
- await deleteCookie(jar, DIALOG_VISITOR_ID_COOKIE, location);
18
- await deleteCookie(jar, DIALOG_SESSION_ID_COOKIE, location);
19
- };
@@ -1,54 +0,0 @@
1
- export declare const STOREFRONT_EVENT_TYPE_PREFIX = "com.dialog.storefront.";
2
- export type StorefrontEventName = "page_view" | "view_item_list" | "view_item" | "add_to_cart" | "remove_from_cart" | "view_cart" | "begin_checkout" | "add_shipping_info" | "add_payment_info" | "purchase" | `dialog_${string}`;
3
- export interface StorefrontPage {
4
- page_location: string;
5
- page_title?: string;
6
- page_referrer?: string;
7
- viewport_width?: number;
8
- viewport_height?: number;
9
- }
10
- export type StorefrontEventContext = StorefrontPage & {
11
- shop_domain: string;
12
- dialog_visitor_id?: string;
13
- dialog_session_id?: string;
14
- organization_slug?: string;
15
- page_view_id?: string;
16
- window_id?: string;
17
- browser_language?: string;
18
- timezone?: string;
19
- screen_width?: number;
20
- screen_height?: number;
21
- source_version?: string;
22
- };
23
- export interface StorefrontEvent {
24
- specversion: "1.0";
25
- id: string;
26
- source: string;
27
- type: `${typeof STOREFRONT_EVENT_TYPE_PREFIX}${string}`;
28
- time: string;
29
- data: {
30
- context: StorefrontEventContext;
31
- properties: Record<string, unknown>;
32
- };
33
- }
34
- export type UnattributedStorefrontEvent = Omit<StorefrontEvent, "source">;
35
- export interface StorefrontVisitor {
36
- dialog_visitor_id: string;
37
- dialog_session_id?: string;
38
- window_id?: string;
39
- }
40
- export type StorefrontAttribution = StorefrontVisitor & {
41
- organization_slug?: string;
42
- };
43
- export interface StorefrontEventInput {
44
- name: StorefrontEventName;
45
- properties: Record<string, unknown>;
46
- page: StorefrontPage;
47
- context: Omit<StorefrontEventContext, keyof StorefrontPage>;
48
- id?: string;
49
- time?: string;
50
- }
51
- export declare const storefrontEventType: <Name extends StorefrontEventName>(name: Name) => `${typeof STOREFRONT_EVENT_TYPE_PREFIX}${Name}`;
52
- export declare const createStorefrontEvent: ({ name, properties, page, context, id, time, }: StorefrontEventInput) => UnattributedStorefrontEvent;
53
- export declare const attributeStorefrontEvent: (event: UnattributedStorefrontEvent, source: string, attribution: StorefrontAttribution) => StorefrontEvent;
54
- //# sourceMappingURL=envelope.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../src/core/envelope.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,4BAA4B,2BAA2B,CAAC;AAGrE,MAAM,MAAM,mBAAmB,GAC3B,WAAW,GACX,gBAAgB,GAChB,WAAW,GACX,aAAa,GACb,kBAAkB,GAClB,WAAW,GACX,gBAAgB,GAChB,mBAAmB,GACnB,kBAAkB,GAClB,UAAU,GACV,UAAU,MAAM,EAAE,CAAC;AAEvB,MAAM,WAAW,cAAc;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAGD,MAAM,MAAM,sBAAsB,GAAG,cAAc,GAAG;IACpD,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAGF,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,KAAK,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;IAEX,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,GAAG,OAAO,4BAA4B,GAAG,MAAM,EAAE,CAAC;IAExD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE;QACJ,OAAO,EAAE,sBAAsB,CAAC;QAChC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACrC,CAAC;CACH;AAGD,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;AAE1E,MAAM,WAAW,iBAAiB;IAChC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAGD,MAAM,MAAM,qBAAqB,GAAG,iBAAiB,GAAG;IACtD,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,mBAAmB,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,IAAI,CAAC,sBAAsB,EAAE,MAAM,cAAc,CAAC,CAAC;IAE5D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,eAAO,MAAM,mBAAmB,GAAI,IAAI,SAAS,mBAAmB,EAClE,MAAM,IAAI,KACT,GAAG,OAAO,4BAA4B,GAAG,IAAI,EACN,CAAC;AAG3C,eAAO,MAAM,qBAAqB,GAAI,gDAOnC,oBAAoB,KAAG,2BA2BzB,CAAC;AAEF,eAAO,MAAM,wBAAwB,GACnC,OAAO,2BAA2B,EAClC,QAAQ,MAAM,EACd,aAAa,qBAAqB,KACjC,eAID,CAAC"}
@@ -1,29 +0,0 @@
1
- import { uuidv7 } from "uuidv7";
2
- export const STOREFRONT_EVENT_TYPE_PREFIX = "com.dialog.storefront.";
3
- export const storefrontEventType = (name) => `${STOREFRONT_EVENT_TYPE_PREFIX}${name}`;
4
- // GA4 passes the page fields among the properties: there they override the page's own and move to data.context.
5
- export const createStorefrontEvent = ({ name, properties, page, context, id, time, }) => {
6
- const { page_location, page_title, page_referrer, viewport_width, viewport_height, ...ownProperties } = { ...page, ...properties };
7
- return {
8
- specversion: "1.0",
9
- id: id ?? uuidv7(),
10
- type: storefrontEventType(name),
11
- time: time ?? new Date().toISOString(),
12
- data: {
13
- context: {
14
- ...context,
15
- page_location,
16
- page_title,
17
- page_referrer,
18
- viewport_width,
19
- viewport_height,
20
- },
21
- properties: ownProperties,
22
- },
23
- };
24
- };
25
- export const attributeStorefrontEvent = (event, source, attribution) => ({
26
- ...event,
27
- source,
28
- data: { ...event.data, context: { ...event.data.context, ...attribution } },
29
- });
@@ -1,7 +0,0 @@
1
- export type { CookieJar, PageLocation } from "./cookie.js";
2
- export { deleteDialogVisitor, type DialogVisitor, getOrCreateDialogVisitor, } from "./dialogVisitor.js";
3
- export * from "./envelope.js";
4
- export { sendStorefrontEvent } from "./sender.js";
5
- export { DIALOG_SESSION_ID_COOKIE, getOrCreateDialogSessionId, } from "./sessionCookie.js";
6
- export { DIALOG_VISITOR_ID_COOKIE, getOrCreateDialogVisitorId, } from "./visitorCookie.js";
7
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAEA,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EACL,mBAAmB,EACnB,KAAK,aAAa,EAClB,wBAAwB,GACzB,MAAM,oBAAoB,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,0BAA0B,GAC3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,wBAAwB,EACxB,0BAA0B,GAC3B,MAAM,oBAAoB,CAAC"}
@@ -1,5 +0,0 @@
1
- export { deleteDialogVisitor, getOrCreateDialogVisitor, } from "./dialogVisitor.js";
2
- export * from "./envelope.js";
3
- export { sendStorefrontEvent } from "./sender.js";
4
- export { DIALOG_SESSION_ID_COOKIE, getOrCreateDialogSessionId, } from "./sessionCookie.js";
5
- export { DIALOG_VISITOR_ID_COOKIE, getOrCreateDialogVisitorId, } from "./visitorCookie.js";
@@ -1,3 +0,0 @@
1
- import type { StorefrontEvent } from "./envelope.js";
2
- export declare const sendStorefrontEvent: (url: string, event: StorefrontEvent) => Promise<void>;
3
- //# sourceMappingURL=sender.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sender.d.ts","sourceRoot":"","sources":["../../src/core/sender.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAsGrD,eAAO,MAAM,mBAAmB,GAC9B,KAAK,MAAM,EACX,OAAO,eAAe,KACrB,OAAO,CAAC,IAAI,CAkCd,CAAC"}
@@ -1,112 +0,0 @@
1
- const IDLE_FLUSH_MS = 1000;
2
- const MAX_BATCH_EVENTS = 20;
3
- // Browsers share 64 KiB between a page's pending keepalive requests: each body, and all of them, stay under it.
4
- const MAX_KEEPALIVE_BYTES = 60_000;
5
- const MAX_RETRIES = 3;
6
- const RETRY_DELAY_MS = 1000;
7
- const RETRY_JITTER_MS = 1000;
8
- const queue = [];
9
- const retries = new Map();
10
- let pendingKeepaliveBytes = 0;
11
- let idleTimer;
12
- let queuedEvents = 0;
13
- // Page hidden: keepalive whatever the budget, since the page may not live to send it otherwise.
14
- // A batch over the limit (one event larger than it) never: the browser would refuse it outright.
15
- const keepaliveBytes = (batch, pageHidden) => {
16
- const withinBudget = pageHidden || pendingKeepaliveBytes + batch.bytes <= MAX_KEEPALIVE_BYTES;
17
- return withinBudget && batch.bytes <= MAX_KEEPALIVE_BYTES ? batch.bytes : 0;
18
- };
19
- const post = async (batch, pageHidden) => {
20
- const reserved = keepaliveBytes(batch, pageHidden);
21
- pendingKeepaliveBytes += reserved;
22
- const body = `[${batch.events.join(",")}]`;
23
- const headers = { "Content-Type": "application/json" };
24
- return fetch(batch.url, {
25
- method: "POST",
26
- headers,
27
- body,
28
- keepalive: reserved > 0,
29
- })
30
- .then((response) => response.status)
31
- .catch(() => 0)
32
- .finally(() => {
33
- pendingKeepaliveBytes -= reserved;
34
- });
35
- };
36
- // Status 0 is no answer.
37
- const deliver = async (batch, pageHidden) => {
38
- const status = await post(batch, pageHidden);
39
- const retryable = status === 0 || status === 429 || status >= 500;
40
- if (retryable && batch.retries < MAX_RETRIES) {
41
- const delay = RETRY_DELAY_MS * 2 ** batch.retries++ + Math.random() * RETRY_JITTER_MS;
42
- retries.set(batch, setTimeout(() => retry(batch, false), delay));
43
- return;
44
- }
45
- batch.settles.forEach((settle) => settle());
46
- };
47
- const retry = (batch, pageHidden) => {
48
- clearTimeout(retries.get(batch));
49
- retries.delete(batch);
50
- void deliver(batch, pageHidden);
51
- };
52
- const flush = (pageHidden = false) => {
53
- clearTimeout(idleTimer);
54
- queuedEvents = 0;
55
- queue.splice(0).forEach((batch) => void deliver(batch, pageHidden));
56
- };
57
- const leave = () => {
58
- flush(true);
59
- [...retries.keys()].forEach((batch) => retry(batch, true));
60
- };
61
- // The Shopify pixel's worker has no page: its events go at once.
62
- const hasPage = () => typeof document !== "undefined";
63
- let watchingPage = false;
64
- const watchPage = () => {
65
- watchingPage = true;
66
- addEventListener("pagehide", leave);
67
- document.addEventListener("visibilitychange", () => {
68
- if (document.visibilityState === "hidden") {
69
- leave();
70
- }
71
- });
72
- };
73
- // Resolves once the event's batch is delivered or given up. Best effort: never rejects, even on
74
- // an event JSON cannot serialise (a cycle, a BigInt).
75
- export const sendStorefrontEvent = async (url, event) => {
76
- let serialised;
77
- try {
78
- serialised = JSON.stringify(event);
79
- }
80
- catch {
81
- return;
82
- }
83
- if (hasPage() && !watchingPage) {
84
- watchPage();
85
- }
86
- const bytes = new TextEncoder().encode(serialised).length + 1;
87
- await new Promise((settle) => {
88
- const last = queue.at(-1);
89
- if (last?.url === url && last.bytes + bytes < MAX_KEEPALIVE_BYTES) {
90
- last.events.push(serialised);
91
- last.bytes += bytes;
92
- last.settles.push(settle);
93
- }
94
- else {
95
- queue.push({
96
- url,
97
- events: [serialised],
98
- bytes: bytes + 1,
99
- retries: 0,
100
- settles: [settle],
101
- });
102
- }
103
- queuedEvents += 1;
104
- clearTimeout(idleTimer);
105
- if (!hasPage() || queuedEvents >= MAX_BATCH_EVENTS) {
106
- flush();
107
- }
108
- else {
109
- idleTimer = setTimeout(flush, IDLE_FLUSH_MS);
110
- }
111
- });
112
- };
@@ -1,4 +0,0 @@
1
- import { type CookieJar, type PageLocation } from "./cookie.js";
2
- export declare const DIALOG_SESSION_ID_COOKIE = "_dialog_session_id";
3
- export declare const getOrCreateDialogSessionId: (jar: CookieJar, location: PageLocation) => Promise<string | undefined>;
4
- //# sourceMappingURL=sessionCookie.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sessionCookie.d.ts","sourceRoot":"","sources":["../../src/core/sessionCookie.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,aAAa,CAAC;AAErB,eAAO,MAAM,wBAAwB,uBAAuB,CAAC;AA0C7D,eAAO,MAAM,0BAA0B,GACrC,KAAK,SAAS,EACd,UAAU,YAAY,KACrB,OAAO,CAAC,MAAM,GAAG,SAAS,CAsB5B,CAAC"}
@@ -1,47 +0,0 @@
1
- import { uuidv7 } from "uuidv7";
2
- import { buildCookie, cookieDomains, } from "./cookie.js";
3
- export const DIALOG_SESSION_ID_COOKIE = "_dialog_session_id";
4
- const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
5
- const MAX_SESSION_MS = 24 * 60 * 60 * 1000;
6
- const ONE_DAY_IN_SECONDS = 24 * 60 * 60;
7
- const parseSession = (value) => {
8
- try {
9
- const parsed = JSON.parse(decodeURIComponent(value ?? ""));
10
- const fields = Array.isArray(parsed) ? parsed : [];
11
- const [lastActivity, id, start] = fields;
12
- return typeof lastActivity === "number" &&
13
- typeof id === "string" &&
14
- typeof start === "number"
15
- ? [lastActivity, id, start]
16
- : undefined;
17
- }
18
- catch {
19
- return undefined;
20
- }
21
- };
22
- const readLiveSession = async (jar, now) => {
23
- const session = parseSession(await jar.get(DIALOG_SESSION_ID_COOKIE));
24
- if (session === undefined) {
25
- return undefined;
26
- }
27
- const [lastActivity, , start] = session;
28
- return now - lastActivity <= IDLE_TIMEOUT_MS && now - start <= MAX_SESSION_MS
29
- ? session
30
- : undefined;
31
- };
32
- // Called on every event: it starts a session, or records the event as the session's last activity.
33
- // Undefined when the browser refuses the cookie.
34
- export const getOrCreateDialogSessionId = async (jar, location) => {
35
- const now = Date.now();
36
- for (const domain of cookieDomains(location.hostname)) {
37
- // Read before every write: a session another tab kept alive or rotated is adopted, not replaced,
38
- // and our own write ends the loop once a domain took it.
39
- const [lastActivity, id = uuidv7(), start = now] = (await readLiveSession(jar, now)) ?? [];
40
- if (lastActivity !== undefined && lastActivity >= now) {
41
- return id;
42
- }
43
- const session = encodeURIComponent(JSON.stringify([now, id, start]));
44
- await jar.set(buildCookie(`${DIALOG_SESSION_ID_COOKIE}=${session}`, ONE_DAY_IN_SECONDS, domain, location));
45
- }
46
- return (await readLiveSession(jar, now))?.[1];
47
- };
@@ -1,4 +0,0 @@
1
- import { type CookieJar, type PageLocation } from "./cookie.js";
2
- export declare const DIALOG_VISITOR_ID_COOKIE = "_dialog_visitor_id";
3
- export declare const getOrCreateDialogVisitorId: (jar: CookieJar, location: PageLocation) => Promise<string | undefined>;
4
- //# sourceMappingURL=visitorCookie.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"visitorCookie.d.ts","sourceRoot":"","sources":["../../src/core/visitorCookie.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,aAAa,CAAC;AAErB,eAAO,MAAM,wBAAwB,uBAAuB,CAAC;AAW7D,eAAO,MAAM,0BAA0B,GACrC,KAAK,SAAS,EACd,UAAU,YAAY,KACrB,OAAO,CAAC,MAAM,GAAG,SAAS,CAwB5B,CAAC"}
@@ -1,26 +0,0 @@
1
- import { uuidv7 } from "uuidv7";
2
- import { buildCookie, cookieDomains, } from "./cookie.js";
3
- export const DIALOG_VISITOR_ID_COOKIE = "_dialog_visitor_id";
4
- const THIRTEEN_MONTHS_IN_SECONDS = 395 * 24 * 60 * 60;
5
- const readVisitorId = async (jar) => {
6
- const id = await jar.get(DIALOG_VISITOR_ID_COOKIE);
7
- return id === "" ? undefined : id;
8
- };
9
- // Undefined when the browser refuses the cookie: an id that is not stored is no visitor.
10
- export const getOrCreateDialogVisitorId = async (jar, location) => {
11
- const existingId = await readVisitorId(jar);
12
- if (existingId !== undefined) {
13
- return existingId;
14
- }
15
- // Generated only when a write is needed: the pixel calls this on every event.
16
- const visitorId = uuidv7();
17
- for (const domain of cookieDomains(location.hostname)) {
18
- // Read before every write: it finds our previous write, or another Dialog script's, which wins.
19
- const storedId = await readVisitorId(jar);
20
- if (storedId !== undefined) {
21
- return storedId;
22
- }
23
- await jar.set(buildCookie(`${DIALOG_VISITOR_ID_COOKIE}=${visitorId}`, THIRTEEN_MONTHS_IN_SECONDS, domain, location));
24
- }
25
- return readVisitorId(jar);
26
- };
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export { documentCookieJar } from "./browser/documentCookieJar.js";
2
- export * from "./core/index.js";
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,cAAc,iBAAiB,CAAC"}
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- export { documentCookieJar } from "./browser/documentCookieJar.js";
2
- export * from "./core/index.js";