@joryio/web-sdk 1.4.0-beta.1 → 1.4.0-beta.4
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/CHANGELOG.md +45 -1
- package/README.md +1 -1
- package/dist/cards-ui/card-feed-view.d.ts +4 -0
- package/dist/cards-ui/card-feed-view.d.ts.map +1 -0
- package/dist/cards-ui/index.d.ts +4 -0
- package/dist/cards-ui/index.d.ts.map +1 -0
- package/dist/core/cards-ui-contract.d.ts +30 -0
- package/dist/core/cards-ui-contract.d.ts.map +1 -0
- package/dist/core/cards.d.ts +130 -0
- package/dist/core/cards.d.ts.map +1 -0
- package/dist/core/config.d.ts +21 -1
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/editor-gate.d.ts +47 -0
- package/dist/core/editor-gate.d.ts.map +1 -0
- package/dist/core/flags.d.ts +73 -0
- package/dist/core/flags.d.ts.map +1 -0
- package/dist/core/inapp.d.ts +13 -1
- package/dist/core/inapp.d.ts.map +1 -1
- package/dist/core/links.d.ts +27 -0
- package/dist/core/links.d.ts.map +1 -0
- package/dist/core/network.d.ts.map +1 -1
- package/dist/core/page-context.d.ts +101 -0
- package/dist/core/page-context.d.ts.map +1 -0
- package/dist/core/page-edits.d.ts +129 -0
- package/dist/core/page-edits.d.ts.map +1 -0
- package/dist/core/placements.d.ts +218 -0
- package/dist/core/placements.d.ts.map +1 -0
- package/dist/core/sdk-host-files.d.ts +5 -0
- package/dist/core/sdk-host-files.d.ts.map +1 -0
- package/dist/core/sdk.d.ts +36 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/editor/index.d.ts +4 -0
- package/dist/editor/index.d.ts.map +1 -0
- package/dist/editor/visual-editor.d.ts +39 -0
- package/dist/editor/visual-editor.d.ts.map +1 -0
- package/dist/index.d.mts +201 -3
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/joryio-cards-ui.min.js +7 -0
- package/dist/joryio-cards-ui.min.js.map +1 -0
- package/dist/joryio-editor.min.js +7 -0
- package/dist/joryio-editor.min.js.map +1 -0
- package/dist/joryio-sw.js +1 -1
- package/dist/joryio.cjs.js +7200 -3513
- package/dist/joryio.min.js +2 -2
- package/dist/joryio.min.js.map +1 -1
- package/dist/joryio.mjs +7192 -3514
- package/dist/joryio.umd.js +7200 -3513
- package/package.json +4 -1
- package/src/cards-ui/card-feed-view.ts +249 -0
- package/src/cards-ui/index.ts +26 -0
- package/src/core/cards-ui-contract.ts +58 -0
- package/src/core/cards.ts +843 -0
- package/src/core/config.ts +86 -2
- package/src/core/editor-gate.ts +158 -0
- package/src/core/flags.ts +372 -0
- package/src/core/inapp.ts +283 -152
- package/src/core/links.ts +104 -0
- package/src/core/network.ts +5 -2
- package/src/core/page-context.ts +460 -0
- package/src/core/page-edits.ts +1036 -0
- package/src/core/placements.ts +1431 -0
- package/src/core/sdk-host-files.ts +93 -0
- package/src/core/sdk.ts +378 -1
- package/src/editor/index.ts +27 -0
- package/src/editor/visual-editor.ts +301 -0
- package/src/index.ts +33 -0
- package/src/snippet/loader.js +25 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isAppDeepLink, safeHttpUrl } from './placements';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where a link the SDK is about to open came from. The same wire values on
|
|
5
|
+
* every Joryio SDK, pinned by the backend spec sdk-link-handler-parity.spec.ts.
|
|
6
|
+
* `push` is not emitted on web: a web push click is handled by the service
|
|
7
|
+
* worker, outside any page, where no page handler can run.
|
|
8
|
+
*/
|
|
9
|
+
export type JoryioLinkSource = 'in_app' | 'placement' | 'card' | 'push';
|
|
10
|
+
|
|
11
|
+
/** A link the SDK is about to open, handed to the site's link handler first (`setLinkHandler`). */
|
|
12
|
+
export interface JoryioLink {
|
|
13
|
+
/** An http(s) link (a root-relative in-app link resolved against the page) or an app deep link (`myapp://cart`). */
|
|
14
|
+
url: string;
|
|
15
|
+
source: JoryioLinkSource;
|
|
16
|
+
/** The in-app message's or card's campaign, when known. */
|
|
17
|
+
campaignId?: string;
|
|
18
|
+
/** The placement the link was clicked in (source `placement`). */
|
|
19
|
+
placementKey?: string;
|
|
20
|
+
/** The placement item (source `placement`). */
|
|
21
|
+
itemId?: string;
|
|
22
|
+
/** The card (source `card`). */
|
|
23
|
+
cardId?: string;
|
|
24
|
+
/** True for an app-scheme link, false for http(s). */
|
|
25
|
+
isAppDeepLink: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Do what the SDK does without a handler: http(s) opens (a new tab, or the
|
|
28
|
+
* page itself for an in-app link that targets it), an app deep link goes to
|
|
29
|
+
* the mount's `onDeepLink`. Runs at most once. Called later than the click,
|
|
30
|
+
* the browser may block a new tab: decide inside the handler where you can.
|
|
31
|
+
*/
|
|
32
|
+
openDefault: () => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Return true to take the link over (route it in your app), false to let the SDK open it. */
|
|
36
|
+
export type JoryioLinkHandler = (link: JoryioLink) => boolean;
|
|
37
|
+
|
|
38
|
+
export interface LinkContext {
|
|
39
|
+
campaignId?: string;
|
|
40
|
+
placementKey?: string;
|
|
41
|
+
itemId?: string;
|
|
42
|
+
cardId?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The one way the in-app renderer, placements and the card feed open a link:
|
|
47
|
+
* refused schemes stop here, the site's handler goes first, then the
|
|
48
|
+
* surface's own fallback.
|
|
49
|
+
*/
|
|
50
|
+
export class LinkRouter {
|
|
51
|
+
private handler: JoryioLinkHandler | null = null;
|
|
52
|
+
|
|
53
|
+
constructor(private onHandlerError: (error: unknown) => void = () => undefined) {}
|
|
54
|
+
|
|
55
|
+
setHandler(handler: JoryioLinkHandler | null): void {
|
|
56
|
+
this.handler = typeof handler === 'function' ? handler : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
get hasHandler(): boolean {
|
|
60
|
+
return this.handler !== null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Route `url`: the handler first, then `fallback`. Only http(s) and app deep
|
|
65
|
+
* links are routed; anything else (javascript:, data:, intent:, ...) is
|
|
66
|
+
* dropped and false returned. Synchronous, so the click's user activation
|
|
67
|
+
* still holds when the fallback opens a tab.
|
|
68
|
+
*/
|
|
69
|
+
route(url: unknown, source: JoryioLinkSource, context: LinkContext, fallback: () => void): boolean {
|
|
70
|
+
if (typeof url !== 'string') return false;
|
|
71
|
+
const trimmed = url.trim();
|
|
72
|
+
const appLink = isAppDeepLink(trimmed);
|
|
73
|
+
if (!safeHttpUrl(trimmed) && !appLink) return false;
|
|
74
|
+
let done = false;
|
|
75
|
+
const openDefault = () => {
|
|
76
|
+
if (done) return;
|
|
77
|
+
done = true;
|
|
78
|
+
fallback();
|
|
79
|
+
};
|
|
80
|
+
const link: JoryioLink = { url: trimmed, source, ...definedOnly(context), isAppDeepLink: appLink, openDefault };
|
|
81
|
+
const handler = this.handler;
|
|
82
|
+
if (handler) {
|
|
83
|
+
let taken = false;
|
|
84
|
+
try {
|
|
85
|
+
taken = handler(link) === true;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
// A throwing handler declines: the link still opens.
|
|
88
|
+
this.onHandlerError(error);
|
|
89
|
+
}
|
|
90
|
+
if (taken) return true;
|
|
91
|
+
}
|
|
92
|
+
openDefault();
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function definedOnly(context: LinkContext): LinkContext {
|
|
98
|
+
const out: LinkContext = {};
|
|
99
|
+
for (const key of ['campaignId', 'placementKey', 'itemId', 'cardId'] as const) {
|
|
100
|
+
const value = context[key];
|
|
101
|
+
if (typeof value === 'string' && value) out[key] = value;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
package/src/core/network.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import type { SubscriptionChannel } from './user';
|
|
6
6
|
import { Logger } from '../utils/logger';
|
|
7
|
+
import { sdkIdentityHeaders } from './config';
|
|
7
8
|
|
|
8
9
|
export interface NetworkRequest {
|
|
9
10
|
url: string;
|
|
@@ -1096,6 +1097,7 @@ export class NetworkClient {
|
|
|
1096
1097
|
'Content-Type': 'application/json',
|
|
1097
1098
|
'X-SDK-Key': this.sdkKey,
|
|
1098
1099
|
...callerHeaders,
|
|
1100
|
+
...sdkIdentityHeaders(),
|
|
1099
1101
|
};
|
|
1100
1102
|
// Attach the SDK-auth JWT last so the managed token is authoritative.
|
|
1101
1103
|
// An anonymous request may carry the storefront identity token instead (D383).
|
|
@@ -1258,6 +1260,7 @@ export class NetworkClient {
|
|
|
1258
1260
|
const headers: Record<string, string> = {
|
|
1259
1261
|
'Content-Type': 'application/json',
|
|
1260
1262
|
'X-SDK-Key': this.sdkKey,
|
|
1263
|
+
...sdkIdentityHeaders(),
|
|
1261
1264
|
};
|
|
1262
1265
|
const subject = identifiedUserOf(body);
|
|
1263
1266
|
const authToken = this.sdkAuthTokenFor(subject) ?? this.storefrontTokenFor(subject, anonymousIdOfBody(body));
|
|
@@ -1320,8 +1323,8 @@ export class NetworkClient {
|
|
|
1320
1323
|
|
|
1321
1324
|
/**
|
|
1322
1325
|
* Click-link identity (D407): hand a tracked link's `jr_t` to the server,
|
|
1323
|
-
* which
|
|
1324
|
-
* the token verifies. Anonymous by construction (no subject user); the
|
|
1326
|
+
* which attributes this anonymous visitor's events to the message's
|
|
1327
|
+
* recipient when the token verifies (attribution only - never a merge). Anonymous by construction (no subject user); the
|
|
1325
1328
|
* answer is only `{ success, status: 'ok' | 'ignored' }`.
|
|
1326
1329
|
*/
|
|
1327
1330
|
async sendIdentifyLink(apiEndpoint: string, payload: { token: string; anonymousId: string }): Promise<NetworkResponse> {
|
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page context - where the visitor is (BACKLOG D444 Phase 4,
|
|
3
|
+
* docs/PLACEMENTS_WEBSITE_LAYER.md 1).
|
|
4
|
+
*
|
|
5
|
+
* Reports the page to targeting - the URL (origin + path, NEVER the query
|
|
6
|
+
* string or the fragment), the page variables the site set, and the dataLayer
|
|
7
|
+
* keys the site listed (an allow-list: nothing is scraped) - notices
|
|
8
|
+
* single-page-app route changes, and measures the page triggers: exit intent,
|
|
9
|
+
* scroll depth, time on page.
|
|
10
|
+
*
|
|
11
|
+
* The matcher below is the backend's `common/web-experience/page-context.ts`,
|
|
12
|
+
* line for line: the server decides for the requests that name a page, this
|
|
13
|
+
* SDK decides for the overlays /sync hands over. sdk-page-context-parity.spec.ts
|
|
14
|
+
* (backend) pins both to the same wire values.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const PAGE_URL_OPERATORS = ['equals', 'contains', 'matches'] as const;
|
|
18
|
+
export const PAGE_VARIABLE_SOURCES = ['page', 'data_layer', 'utm_session', 'utm_first_touch'] as const;
|
|
19
|
+
/** The UTM fields a `utm_*` rule names; reported as `context.utm.session` / `.firstTouch` (never the query string). */
|
|
20
|
+
export const PAGE_UTM_KEYS = ['source', 'medium', 'campaign', 'term', 'content'] as const;
|
|
21
|
+
export const PAGE_VARIABLE_OPERATORS = ['equals', 'not_equals', 'contains', 'exists', 'not_exists', 'gt', 'lt'] as const;
|
|
22
|
+
export const PAGE_TRIGGER_TYPES = ['page_view', 'exit_intent', 'scroll_depth', 'time_on_page'] as const;
|
|
23
|
+
export const PAGE_CONTEXT_CAPABILITY = 'page_context';
|
|
24
|
+
|
|
25
|
+
/** Variables per source this SDK reports; the server reads the same number. */
|
|
26
|
+
export const PAGE_CONTEXT_MAX_VARIABLES = 20;
|
|
27
|
+
const MAX_VALUE_LENGTH = 200;
|
|
28
|
+
const VARIABLE_KEY_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$.-]{0,63}$/;
|
|
29
|
+
|
|
30
|
+
export type PageVariableValue = string | number | boolean;
|
|
31
|
+
export type PageTriggerType = (typeof PAGE_TRIGGER_TYPES)[number];
|
|
32
|
+
|
|
33
|
+
export interface PageUrlRule {
|
|
34
|
+
op: string;
|
|
35
|
+
value: string;
|
|
36
|
+
}
|
|
37
|
+
export interface PageVariableRule {
|
|
38
|
+
source: string;
|
|
39
|
+
key: string;
|
|
40
|
+
op: string;
|
|
41
|
+
value?: PageVariableValue;
|
|
42
|
+
}
|
|
43
|
+
export interface PageTargeting {
|
|
44
|
+
urls?: { include?: PageUrlRule[]; exclude?: PageUrlRule[] };
|
|
45
|
+
variables?: PageVariableRule[];
|
|
46
|
+
}
|
|
47
|
+
export interface PageUtm {
|
|
48
|
+
session?: Record<string, string>;
|
|
49
|
+
firstTouch?: Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
export interface PageContext {
|
|
52
|
+
url: string | null;
|
|
53
|
+
pageVariables: Record<string, PageVariableValue>;
|
|
54
|
+
dataLayer: Record<string, PageVariableValue>;
|
|
55
|
+
/** The UTM the SDK recorded (absent when none, or UTM capture is off). */
|
|
56
|
+
utm?: PageUtm;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ── The matcher (same as the backend) ─────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
function normalizePath(path: string): string {
|
|
62
|
+
const p = (path || '/').toLowerCase();
|
|
63
|
+
return p.length > 1 && p.endsWith('/') ? p.slice(0, -1) : p;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `*` = within one segment, `**` = across segments. A glob walk, no RegExp built from the rule. */
|
|
67
|
+
export function pathPatternMatches(pattern: string, path: string): boolean {
|
|
68
|
+
const pat = normalizePath(pattern);
|
|
69
|
+
const str = normalizePath(path);
|
|
70
|
+
const tokens: string[] = [];
|
|
71
|
+
for (let i = 0; i < pat.length; i++) {
|
|
72
|
+
if (pat[i] === '*') {
|
|
73
|
+
if (pat[i + 1] === '*') {
|
|
74
|
+
tokens.push('**');
|
|
75
|
+
while (pat[i + 1] === '*') i++;
|
|
76
|
+
} else tokens.push('*');
|
|
77
|
+
} else tokens.push(pat[i]);
|
|
78
|
+
}
|
|
79
|
+
let reach: boolean[] = new Array(str.length + 1).fill(false);
|
|
80
|
+
reach[0] = true;
|
|
81
|
+
for (const t of tokens) {
|
|
82
|
+
const next: boolean[] = new Array(str.length + 1).fill(false);
|
|
83
|
+
if (t === '*' || t === '**') {
|
|
84
|
+
for (let j = 0; j <= str.length; j++) {
|
|
85
|
+
if (reach[j]) next[j] = true;
|
|
86
|
+
else if (j > 0 && next[j - 1] && (t === '**' || str[j - 1] !== '/')) next[j] = true;
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
for (let j = 1; j <= str.length; j++) next[j] = reach[j - 1] && str[j - 1] === t;
|
|
90
|
+
}
|
|
91
|
+
reach = next;
|
|
92
|
+
}
|
|
93
|
+
return reach[str.length];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function pageUrlRuleMatches(rule: PageUrlRule, url: string): boolean {
|
|
97
|
+
const m = /^(https?:\/\/[^/]+)(.*)$/i.exec(url);
|
|
98
|
+
if (!m) return false;
|
|
99
|
+
const origin = m[1].toLowerCase();
|
|
100
|
+
const path = m[2] || '/';
|
|
101
|
+
let value = String(rule.value ?? '').trim();
|
|
102
|
+
const target = rule.op === 'contains' ? origin + path : path;
|
|
103
|
+
const full = rule.op === 'contains' ? null : /^(https?:\/\/[^/?#]+)([^?#]*)/i.exec(value);
|
|
104
|
+
if (full) {
|
|
105
|
+
if (full[1].toLowerCase() !== origin) return false;
|
|
106
|
+
value = full[2] || '/';
|
|
107
|
+
}
|
|
108
|
+
switch (rule.op) {
|
|
109
|
+
case 'equals':
|
|
110
|
+
return normalizePath(value) === normalizePath(target);
|
|
111
|
+
case 'contains':
|
|
112
|
+
return !!value && target.toLowerCase().includes(value.toLowerCase());
|
|
113
|
+
case 'matches':
|
|
114
|
+
return pathPatternMatches(value, target);
|
|
115
|
+
default:
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function variableRuleMatches(rule: PageVariableRule, ctx: PageContext): boolean {
|
|
121
|
+
const bag: Record<string, PageVariableValue> | undefined =
|
|
122
|
+
rule.source === 'data_layer'
|
|
123
|
+
? ctx.dataLayer
|
|
124
|
+
: rule.source === 'page'
|
|
125
|
+
? ctx.pageVariables
|
|
126
|
+
: rule.source === 'utm_session'
|
|
127
|
+
? ctx.utm?.session ?? {}
|
|
128
|
+
: rule.source === 'utm_first_touch'
|
|
129
|
+
? ctx.utm?.firstTouch ?? {}
|
|
130
|
+
: undefined;
|
|
131
|
+
if (!bag) return false; // an unknown source never matches (fail closed)
|
|
132
|
+
const has = Object.prototype.hasOwnProperty.call(bag, rule.key);
|
|
133
|
+
const actual = has ? bag[rule.key] : undefined;
|
|
134
|
+
switch (rule.op) {
|
|
135
|
+
case 'exists':
|
|
136
|
+
return has;
|
|
137
|
+
case 'not_exists':
|
|
138
|
+
return !has;
|
|
139
|
+
case 'equals':
|
|
140
|
+
return has && String(actual).toLowerCase() === String(rule.value ?? '').toLowerCase();
|
|
141
|
+
case 'not_equals':
|
|
142
|
+
return !has || String(actual).toLowerCase() !== String(rule.value ?? '').toLowerCase();
|
|
143
|
+
case 'contains':
|
|
144
|
+
return has && String(actual).toLowerCase().includes(String(rule.value ?? '').toLowerCase());
|
|
145
|
+
case 'gt':
|
|
146
|
+
case 'lt': {
|
|
147
|
+
const a = Number(actual);
|
|
148
|
+
const b = Number(rule.value);
|
|
149
|
+
if (!has || !Number.isFinite(a) || !Number.isFinite(b)) return false;
|
|
150
|
+
return rule.op === 'gt' ? a > b : a < b;
|
|
151
|
+
}
|
|
152
|
+
default:
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function hasPageTargeting(pt: PageTargeting | null | undefined): boolean {
|
|
158
|
+
return !!pt && (!!pt.urls?.include?.length || !!pt.urls?.exclude?.length || !!pt.variables?.length);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** No rules = every page. Rules and no page = no (fail closed). */
|
|
162
|
+
export function pageTargetingMatches(pt: PageTargeting | null | undefined, ctx: PageContext): boolean {
|
|
163
|
+
if (!hasPageTargeting(pt)) return true;
|
|
164
|
+
const include = pt!.urls?.include ?? [];
|
|
165
|
+
const exclude = pt!.urls?.exclude ?? [];
|
|
166
|
+
if (include.length || exclude.length) {
|
|
167
|
+
if (!ctx.url) return false;
|
|
168
|
+
if (include.length && !include.some((r) => pageUrlRuleMatches(r, ctx.url!))) return false;
|
|
169
|
+
if (exclude.some((r) => pageUrlRuleMatches(r, ctx.url!))) return false;
|
|
170
|
+
}
|
|
171
|
+
return (pt!.variables ?? []).every((r) => variableRuleMatches(r, ctx));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export const isPageTrigger = (t: { type?: string } | null | undefined): boolean =>
|
|
175
|
+
!!t && (PAGE_TRIGGER_TYPES as readonly string[]).includes(String(t.type));
|
|
176
|
+
|
|
177
|
+
// ── Reading the page ──────────────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/** origin + path of the current page, never the query string or the fragment. */
|
|
180
|
+
export function currentPageUrl(): string | null {
|
|
181
|
+
try {
|
|
182
|
+
const loc = typeof window !== 'undefined' ? window.location : undefined;
|
|
183
|
+
return loc && loc.origin && loc.origin !== 'null' ? `${loc.origin}${loc.pathname}` : null;
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function primitive(v: unknown): PageVariableValue | undefined {
|
|
190
|
+
if (typeof v === 'string') return v.slice(0, MAX_VALUE_LENGTH);
|
|
191
|
+
if (typeof v === 'number' && Number.isFinite(v)) return v;
|
|
192
|
+
if (typeof v === 'boolean') return v;
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** `a.b.c` inside an object, own properties only. */
|
|
197
|
+
function readPath(root: unknown, path: string): unknown {
|
|
198
|
+
let cur: any = root;
|
|
199
|
+
for (const part of path.split('.')) {
|
|
200
|
+
if (cur === null || typeof cur !== 'object' || !Object.prototype.hasOwnProperty.call(cur, part)) return undefined;
|
|
201
|
+
cur = cur[part];
|
|
202
|
+
}
|
|
203
|
+
return cur;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface PageContextOptions {
|
|
207
|
+
/** Global variables to report, by name (`pageType`, `shop.page.type`). Nothing else is read. */
|
|
208
|
+
pageVariables?: string[];
|
|
209
|
+
/** dataLayer keys to report (`pageType`, `ecommerce.value`): the latest value pushed for each. Nothing else is read. */
|
|
210
|
+
dataLayerVariables?: string[];
|
|
211
|
+
/** The dataLayer array's global name. Default `dataLayer`. */
|
|
212
|
+
dataLayerName?: string;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export type PageSignal = { type: 'page_change'; url: string | null } | { type: 'exit_intent' } | { type: 'scroll_depth'; percent: number } | { type: 'time_on_page'; seconds: number };
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The page as targeting sees it, and the moments the page triggers wait for.
|
|
219
|
+
* One instance per SDK; `start()` installs the listeners, `destroy()` removes
|
|
220
|
+
* them (and restores history.pushState / replaceState if this instance
|
|
221
|
+
* patched them).
|
|
222
|
+
*/
|
|
223
|
+
export class PageContextTracker {
|
|
224
|
+
private explicit: Record<string, PageVariableValue> = {};
|
|
225
|
+
private listeners = new Set<(s: PageSignal) => void>();
|
|
226
|
+
private url: string | null = currentPageUrl();
|
|
227
|
+
private maxScrollPercent = 0;
|
|
228
|
+
private visibleMs = 0;
|
|
229
|
+
private visibleSince: number | null = null;
|
|
230
|
+
private exitFired = false;
|
|
231
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
232
|
+
private undo: Array<() => void> = [];
|
|
233
|
+
private started = false;
|
|
234
|
+
|
|
235
|
+
private utmSource: (() => { current?: object | null; firstTouch?: object | null } | null) | null = null;
|
|
236
|
+
|
|
237
|
+
constructor(private options: PageContextOptions = {}) {}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Where the UTM comes from: the SDK's UTMManager (`getUTMData()`), set by
|
|
241
|
+
* the SDK when UTM capture is on. Only the five standard fields cross, as
|
|
242
|
+
* `context.utm.session` (this session's) and `.firstTouch` (this browser's
|
|
243
|
+
* first) - never the query string itself.
|
|
244
|
+
*/
|
|
245
|
+
setUtmSource(source: typeof this.utmSource): void {
|
|
246
|
+
this.utmSource = source;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private utm(): PageUtm | undefined {
|
|
250
|
+
let data: ReturnType<NonNullable<typeof this.utmSource>> = null;
|
|
251
|
+
try {
|
|
252
|
+
data = this.utmSource ? this.utmSource() : null;
|
|
253
|
+
} catch {
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
if (!data) return undefined;
|
|
257
|
+
const pick = (o: object | null | undefined): Record<string, string> | undefined => {
|
|
258
|
+
if (!o || typeof o !== 'object') return undefined;
|
|
259
|
+
const raw = o as Record<string, unknown>;
|
|
260
|
+
const out: Record<string, string> = {};
|
|
261
|
+
for (const k of PAGE_UTM_KEYS) {
|
|
262
|
+
const v = raw[`utm_${k}`];
|
|
263
|
+
if (typeof v === 'string' && v.trim()) out[k] = v.trim().slice(0, MAX_VALUE_LENGTH);
|
|
264
|
+
}
|
|
265
|
+
return Object.keys(out).length ? out : undefined;
|
|
266
|
+
};
|
|
267
|
+
const session = pick(data.current);
|
|
268
|
+
const firstTouch = pick(data.firstTouch);
|
|
269
|
+
return session || firstTouch ? { ...(session ? { session } : {}), ...(firstTouch ? { firstTouch } : {}) } : undefined;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Replaces the page variables the site set (`null` clears them). Primitives only, 20 at most. */
|
|
273
|
+
setPageVariables(vars: Record<string, unknown> | null): void {
|
|
274
|
+
const out: Record<string, PageVariableValue> = {};
|
|
275
|
+
let n = 0;
|
|
276
|
+
for (const [k, v] of Object.entries(vars || {})) {
|
|
277
|
+
if (n >= PAGE_CONTEXT_MAX_VARIABLES || !VARIABLE_KEY_PATTERN.test(k)) continue;
|
|
278
|
+
const p = primitive(v);
|
|
279
|
+
if (p === undefined) continue;
|
|
280
|
+
out[k] = p;
|
|
281
|
+
n++;
|
|
282
|
+
}
|
|
283
|
+
this.explicit = out;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
current(): PageContext {
|
|
287
|
+
const pageVariables: Record<string, PageVariableValue> = { ...this.explicit };
|
|
288
|
+
const w: any = typeof window !== 'undefined' ? window : {};
|
|
289
|
+
for (const name of (this.options.pageVariables || []).slice(0, PAGE_CONTEXT_MAX_VARIABLES)) {
|
|
290
|
+
if (Object.keys(pageVariables).length >= PAGE_CONTEXT_MAX_VARIABLES) break;
|
|
291
|
+
if (!VARIABLE_KEY_PATTERN.test(name) || name in pageVariables) continue;
|
|
292
|
+
try {
|
|
293
|
+
const p = primitive(readPath(w, name));
|
|
294
|
+
if (p !== undefined) pageVariables[name] = p;
|
|
295
|
+
} catch {
|
|
296
|
+
/* a getter that throws is not our page's problem */
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const dataLayer: Record<string, PageVariableValue> = {};
|
|
300
|
+
const keys = (this.options.dataLayerVariables || []).filter((k) => VARIABLE_KEY_PATTERN.test(k)).slice(0, PAGE_CONTEXT_MAX_VARIABLES);
|
|
301
|
+
if (keys.length) {
|
|
302
|
+
try {
|
|
303
|
+
const dl = w[this.options.dataLayerName || 'dataLayer'];
|
|
304
|
+
if (Array.isArray(dl)) {
|
|
305
|
+
// The latest push that carries a key wins - what the tag manager itself does.
|
|
306
|
+
for (let i = dl.length - 1; i >= 0 && Object.keys(dataLayer).length < keys.length; i--) {
|
|
307
|
+
const entry = dl[i];
|
|
308
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
|
|
309
|
+
for (const k of keys) {
|
|
310
|
+
if (k in dataLayer) continue;
|
|
311
|
+
const p = primitive(readPath(entry, k));
|
|
312
|
+
if (p !== undefined) dataLayer[k] = p;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
} catch {
|
|
317
|
+
/* ignore */
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const utm = this.utm();
|
|
321
|
+
return { url: this.url, pageVariables, dataLayer, ...(utm ? { utm } : {}) };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Scroll depth (max percent reached) and visible seconds on this page so far. */
|
|
325
|
+
progress(): { scrollPercent: number; seconds: number; exitIntent: boolean } {
|
|
326
|
+
const running = this.visibleSince !== null ? Date.now() - this.visibleSince : 0;
|
|
327
|
+
return { scrollPercent: this.maxScrollPercent, seconds: Math.floor((this.visibleMs + running) / 1000), exitIntent: this.exitFired };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
onSignal(cb: (s: PageSignal) => void): () => void {
|
|
331
|
+
this.listeners.add(cb);
|
|
332
|
+
return () => this.listeners.delete(cb);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
start(): void {
|
|
336
|
+
if (this.started || typeof window === 'undefined' || typeof document === 'undefined') return;
|
|
337
|
+
this.started = true;
|
|
338
|
+
this.patchHistory();
|
|
339
|
+
const on = (target: any, ev: string, fn: any, opts?: any) => {
|
|
340
|
+
target.addEventListener(ev, fn, opts);
|
|
341
|
+
this.undo.push(() => target.removeEventListener(ev, fn, opts));
|
|
342
|
+
};
|
|
343
|
+
on(window, 'popstate', () => this.checkRoute());
|
|
344
|
+
on(window, 'scroll', () => this.measureScroll(), { passive: true });
|
|
345
|
+
on(document, 'mouseout', (e: MouseEvent) => {
|
|
346
|
+
// Leaving through the top of the window, toward the tabs and the address bar.
|
|
347
|
+
if (this.exitFired || e.relatedTarget || (e as any).toElement) return;
|
|
348
|
+
if (typeof e.clientY === 'number' && e.clientY <= 0) {
|
|
349
|
+
this.exitFired = true;
|
|
350
|
+
this.emit({ type: 'exit_intent' });
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
on(document, 'visibilitychange', () => this.visibilityChanged());
|
|
354
|
+
if (document.visibilityState !== 'hidden') this.visibleSince = Date.now();
|
|
355
|
+
this.timer = setInterval(() => {
|
|
356
|
+
const { seconds } = this.progress();
|
|
357
|
+
if (this.visibleSince !== null) this.emit({ type: 'time_on_page', seconds });
|
|
358
|
+
this.checkRoute(); // a router that changes the path without history events
|
|
359
|
+
}, 1000);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
destroy(): void {
|
|
363
|
+
if (this.timer) clearInterval(this.timer);
|
|
364
|
+
this.timer = null;
|
|
365
|
+
for (const u of this.undo.splice(0).reverse()) {
|
|
366
|
+
try {
|
|
367
|
+
u();
|
|
368
|
+
} catch {
|
|
369
|
+
/* ignore */
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
this.listeners.clear();
|
|
373
|
+
this.started = false;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** A route change: the page triggers start over. */
|
|
377
|
+
private checkRoute(): void {
|
|
378
|
+
const url = currentPageUrl();
|
|
379
|
+
if (url === this.url) return;
|
|
380
|
+
this.url = url;
|
|
381
|
+
this.maxScrollPercent = 0;
|
|
382
|
+
this.visibleMs = 0;
|
|
383
|
+
this.visibleSince = typeof document !== 'undefined' && document.visibilityState === 'hidden' ? null : Date.now();
|
|
384
|
+
this.exitFired = false;
|
|
385
|
+
this.emit({ type: 'page_change', url });
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
private patchHistory(): void {
|
|
389
|
+
const h: any = typeof history !== 'undefined' ? history : null;
|
|
390
|
+
if (!h) return;
|
|
391
|
+
for (const name of ['pushState', 'replaceState'] as const) {
|
|
392
|
+
const original = h[name];
|
|
393
|
+
if (typeof original !== 'function') continue;
|
|
394
|
+
const self = this;
|
|
395
|
+
const patched = function (this: unknown, ...args: unknown[]) {
|
|
396
|
+
const r = original.apply(this, args);
|
|
397
|
+
try {
|
|
398
|
+
self.checkRoute();
|
|
399
|
+
} catch {
|
|
400
|
+
/* never break the site's router */
|
|
401
|
+
}
|
|
402
|
+
return r;
|
|
403
|
+
};
|
|
404
|
+
h[name] = patched;
|
|
405
|
+
this.undo.push(() => {
|
|
406
|
+
if (h[name] === patched) h[name] = original;
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private measureScroll(): void {
|
|
412
|
+
try {
|
|
413
|
+
const el = document.documentElement;
|
|
414
|
+
const scrollable = Math.max(el.scrollHeight, document.body?.scrollHeight || 0) - window.innerHeight;
|
|
415
|
+
const percent = scrollable <= 0 ? 100 : Math.min(100, Math.round(((window.scrollY || el.scrollTop) / scrollable) * 100));
|
|
416
|
+
if (percent > this.maxScrollPercent) {
|
|
417
|
+
this.maxScrollPercent = percent;
|
|
418
|
+
this.emit({ type: 'scroll_depth', percent });
|
|
419
|
+
}
|
|
420
|
+
} catch {
|
|
421
|
+
/* ignore */
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private visibilityChanged(): void {
|
|
426
|
+
if (document.visibilityState === 'hidden') {
|
|
427
|
+
if (this.visibleSince !== null) this.visibleMs += Date.now() - this.visibleSince;
|
|
428
|
+
this.visibleSince = null;
|
|
429
|
+
} else if (this.visibleSince === null) {
|
|
430
|
+
this.visibleSince = Date.now();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private emit(s: PageSignal): void {
|
|
435
|
+
for (const cb of Array.from(this.listeners)) {
|
|
436
|
+
try {
|
|
437
|
+
cb(s);
|
|
438
|
+
} catch {
|
|
439
|
+
/* a listener never breaks the others */
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Does this page trigger fire now? `fired` = types already fired for this campaign on this page. */
|
|
446
|
+
export function pageTriggerMet(trigger: { type?: string; value?: unknown }, signal: PageSignal, progress: { scrollPercent: number; seconds: number }): boolean {
|
|
447
|
+
const n = Number(trigger.value);
|
|
448
|
+
switch (trigger.type) {
|
|
449
|
+
case 'page_view':
|
|
450
|
+
return signal.type === 'page_change';
|
|
451
|
+
case 'exit_intent':
|
|
452
|
+
return signal.type === 'exit_intent';
|
|
453
|
+
case 'scroll_depth':
|
|
454
|
+
return (signal.type === 'scroll_depth' || signal.type === 'page_change') && Number.isFinite(n) && n > 0 && progress.scrollPercent >= n;
|
|
455
|
+
case 'time_on_page':
|
|
456
|
+
return signal.type === 'time_on_page' && Number.isFinite(n) && n > 0 && progress.seconds >= n;
|
|
457
|
+
default:
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|