@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
package/src/core/config.ts
CHANGED
|
@@ -2,7 +2,23 @@
|
|
|
2
2
|
* SDK Configuration Types and Defaults
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
export const SDK_VERSION = '1.4.0'; // keep in sync with package.json
|
|
5
|
+
export const SDK_VERSION = '1.4.0'; // keep in sync with package.json (sdk-version-parity.spec.ts pins it)
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Sent on EVERY request to the API, so the dashboard can show which SDK
|
|
9
|
+
* version each app runs and when a newer one is out (D427). Same wire names
|
|
10
|
+
* on all five SDKs: `X-Joryio-SDK` is the platform (the header the backend's
|
|
11
|
+
* SDK-key guard and bot detection already read), `X-Joryio-SDK-Version` this
|
|
12
|
+
* build's version. The web SDK has no bridge, so it never sends
|
|
13
|
+
* `X-Joryio-SDK-Wrapper`. The public SDK routes allow these in CORS.
|
|
14
|
+
*/
|
|
15
|
+
export const SDK_PLATFORM_HEADER = 'X-Joryio-SDK';
|
|
16
|
+
export const SDK_VERSION_HEADER = 'X-Joryio-SDK-Version';
|
|
17
|
+
export const SDK_PLATFORM = 'web';
|
|
18
|
+
|
|
19
|
+
export function sdkIdentityHeaders(): Record<string, string> {
|
|
20
|
+
return { [SDK_PLATFORM_HEADER]: SDK_PLATFORM, [SDK_VERSION_HEADER]: SDK_VERSION };
|
|
21
|
+
}
|
|
6
22
|
export const DEFAULT_API_ENDPOINT = 'https://api-eu1.joryio.com/api';
|
|
7
23
|
|
|
8
24
|
/**
|
|
@@ -110,6 +126,13 @@ export interface InAppOptions {
|
|
|
110
126
|
*/
|
|
111
127
|
allowHtmlJsInAppMessages?: boolean;
|
|
112
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Fill every `<div data-joryio-placement="key">` on the page (and those added
|
|
131
|
+
* later) with its placement. On by default; off = only insertPlacement()
|
|
132
|
+
* draws. Placements work whether or not overlays (`enabled`) are on.
|
|
133
|
+
*/
|
|
134
|
+
autoMountPlacements?: boolean;
|
|
135
|
+
|
|
113
136
|
// Callback hooks
|
|
114
137
|
onMessageDisplay?: (message: any) => void;
|
|
115
138
|
onMessageClick?: (message: any, action: string) => void;
|
|
@@ -121,6 +144,48 @@ export interface InitConfig {
|
|
|
121
144
|
// Required
|
|
122
145
|
sdkKey: string;
|
|
123
146
|
|
|
147
|
+
/**
|
|
148
|
+
* Page context for targeting (D444 Phase 4): what the SDK may report about
|
|
149
|
+
* the page besides its URL (origin + path, never the query string). Nothing
|
|
150
|
+
* is read that is not listed here. Set the page's own variables with
|
|
151
|
+
* `setPageVariables()`.
|
|
152
|
+
*/
|
|
153
|
+
pageContext?: {
|
|
154
|
+
/** Global variables to report, by name (`pageType`, `shop.page.type`). */
|
|
155
|
+
pageVariables?: string[];
|
|
156
|
+
/** dataLayer keys to report (`pageType`, `ecommerce.value`): the latest pushed value of each. */
|
|
157
|
+
dataLayerVariables?: string[];
|
|
158
|
+
/** The dataLayer array's global name. Default `dataLayer`. */
|
|
159
|
+
dataLayerName?: string;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Page edits on this site (D444 Phase 4). Default on: the SDK applies the
|
|
164
|
+
* page edits Joryio sends and opens the point-and-click editor when the
|
|
165
|
+
* dashboard asks. `false`: it never applies a page edit, never holds an
|
|
166
|
+
* element back and never loads the editor - whatever the server says.
|
|
167
|
+
* (Workspace-wide: Settings -> Placements -> Allow page edits on this website.)
|
|
168
|
+
*/
|
|
169
|
+
pageEdits?: boolean;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Where the point-and-click editor's file is loaded from. Default: the
|
|
173
|
+
* folder `joryio.min.js` itself was loaded from (a beta at
|
|
174
|
+
* `sdk.joryio.com/web/1.4.0-beta.4/`, the npm package's `dist/` on a CDN),
|
|
175
|
+
* then the SDK host (`https://sdk.joryio.com/web/<version>/joryio-editor.min.js`,
|
|
176
|
+
* then `/web/<major>/`). Set it only when you host the SDK files yourself.
|
|
177
|
+
*/
|
|
178
|
+
editorScriptUrl?: string;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Where the default card feed's file (`mountCardFeed`) is loaded from.
|
|
182
|
+
* Default: the folder `joryio.min.js` itself was loaded from, then the SDK
|
|
183
|
+
* host (`https://sdk.joryio.com/web/<version>/joryio-cards-ui.min.js`, then
|
|
184
|
+
* `/web/<major>/`), the first time the page mounts a feed. Set it only when
|
|
185
|
+
* you host the SDK files yourself.
|
|
186
|
+
*/
|
|
187
|
+
cardsUiScriptUrl?: string;
|
|
188
|
+
|
|
124
189
|
// API Configuration
|
|
125
190
|
apiEndpoint?: string;
|
|
126
191
|
|
|
@@ -230,14 +295,19 @@ export interface InitConfig {
|
|
|
230
295
|
plugins?: Array<Plugin>;
|
|
231
296
|
}
|
|
232
297
|
|
|
233
|
-
export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'sdkAuthenticationToken' | 'trackingConsent' | 'webPush' | 'storefrontIdentityToken' | 'storefrontIdentityTokenProvider'>> {
|
|
298
|
+
export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'pageContext' | 'sdkAuthenticationToken' | 'trackingConsent' | 'webPush' | 'storefrontIdentityToken' | 'storefrontIdentityTokenProvider' | 'editorScriptUrl' | 'cardsUiScriptUrl'>> {
|
|
234
299
|
userId?: string;
|
|
300
|
+
/** Undefined = the SDK host (see InitConfig.editorScriptUrl). */
|
|
301
|
+
editorScriptUrl?: string;
|
|
302
|
+
/** Undefined = the SDK host (see InitConfig.cardsUiScriptUrl). */
|
|
303
|
+
cardsUiScriptUrl?: string;
|
|
235
304
|
/** Undefined = not set by the app (see InitConfig.webPush). */
|
|
236
305
|
webPush?: boolean;
|
|
237
306
|
/** Undefined = not set by the app (see InitConfig.trackingConsent). */
|
|
238
307
|
trackingConsent?: 'granted' | 'denied' | 'pending';
|
|
239
308
|
plugins: Array<Plugin>;
|
|
240
309
|
inApp: Required<InAppOptions>;
|
|
310
|
+
pageContext: { pageVariables: string[]; dataLayerVariables: string[]; dataLayerName: string };
|
|
241
311
|
// Optional — absent until the host app supplies a token.
|
|
242
312
|
sdkAuthenticationToken?: string;
|
|
243
313
|
storefrontIdentityToken?: string;
|
|
@@ -354,6 +424,7 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
|
|
|
354
424
|
zIndex: config.inApp?.displayOptions?.zIndex || 999999,
|
|
355
425
|
},
|
|
356
426
|
allowHtmlJsInAppMessages: config.inApp?.allowHtmlJsInAppMessages === true,
|
|
427
|
+
autoMountPlacements: config.inApp?.autoMountPlacements !== false,
|
|
357
428
|
onMessageDisplay: config.inApp?.onMessageDisplay || (() => {}),
|
|
358
429
|
onMessageClick: config.inApp?.onMessageClick || (() => {}),
|
|
359
430
|
onMessageDismiss: config.inApp?.onMessageDismiss || (() => {}),
|
|
@@ -379,6 +450,19 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
|
|
|
379
450
|
trackPageProperties: config.trackPageProperties !== false,
|
|
380
451
|
trackDeviceProperties: config.trackDeviceProperties !== false,
|
|
381
452
|
inApp: inAppOptions,
|
|
453
|
+
pageContext: {
|
|
454
|
+
pageVariables: Array.isArray(config.pageContext?.pageVariables) ? config.pageContext!.pageVariables.filter((v) => typeof v === 'string') : [],
|
|
455
|
+
dataLayerVariables: Array.isArray(config.pageContext?.dataLayerVariables)
|
|
456
|
+
? config.pageContext!.dataLayerVariables.filter((v) => typeof v === 'string')
|
|
457
|
+
: [],
|
|
458
|
+
dataLayerName:
|
|
459
|
+
typeof config.pageContext?.dataLayerName === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(config.pageContext.dataLayerName)
|
|
460
|
+
? config.pageContext.dataLayerName
|
|
461
|
+
: 'dataLayer',
|
|
462
|
+
},
|
|
463
|
+
pageEdits: config.pageEdits !== false,
|
|
464
|
+
editorScriptUrl: typeof config.editorScriptUrl === 'string' && /^https:\/\//i.test(config.editorScriptUrl) ? config.editorScriptUrl : undefined,
|
|
465
|
+
cardsUiScriptUrl: typeof config.cardsUiScriptUrl === 'string' && /^https:\/\//i.test(config.cardsUiScriptUrl) ? config.cardsUiScriptUrl : undefined,
|
|
382
466
|
// Tri-state on purpose: unset ("decide from this browser") is not `false`.
|
|
383
467
|
webPush: config.webPush === true ? true : config.webPush === false ? false : undefined,
|
|
384
468
|
persistQueue: config.persistQueue !== false,
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The point-and-click editor's door in the core bundle (BACKLOG D444 Phase 4,
|
|
3
|
+
* docs/PLACEMENTS_WEBSITE_LAYER.md 3).
|
|
4
|
+
*
|
|
5
|
+
* The visual editor itself (highlight, panel, selector computation) is a
|
|
6
|
+
* separate file, `joryio-editor.min.js`, served from the same SDK host next to
|
|
7
|
+
* `joryio.min.js`, so the ~every-visitor bundle carries only this handshake:
|
|
8
|
+
*
|
|
9
|
+
* 1. only when the tab was opened with `?joryio_editor=1` AND by another
|
|
10
|
+
* window (`window.opener`) AND page edits are not switched off in the
|
|
11
|
+
* site's code (`pageEdits: false`), post `joryio:editor-ready` to the
|
|
12
|
+
* opener (no secret in it);
|
|
13
|
+
* 2. accept `joryio:editor-token` only from that opener window, and check
|
|
14
|
+
* the token with `POST /v1/in-app/editor/verify`, which answers the
|
|
15
|
+
* dashboard origin it was minted for (bound to this site's origin and
|
|
16
|
+
* this SDK key's workspace; refused when page edits are off);
|
|
17
|
+
* 3. only then load the editor bundle and hand it the verified dashboard
|
|
18
|
+
* origin and the opener. Nothing is loaded for any other visitor.
|
|
19
|
+
*/
|
|
20
|
+
import type { Logger } from '../utils/logger';
|
|
21
|
+
import { sdkIdentityHeaders } from './config';
|
|
22
|
+
import { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';
|
|
23
|
+
|
|
24
|
+
export const EDITOR_QUERY_FLAG = 'joryio_editor';
|
|
25
|
+
export const EDITOR_MESSAGES = {
|
|
26
|
+
READY: 'joryio:editor-ready',
|
|
27
|
+
TOKEN: 'joryio:editor-token',
|
|
28
|
+
ACTIVE: 'joryio:editor-active',
|
|
29
|
+
PICK: 'joryio:editor-pick',
|
|
30
|
+
CLOSE: 'joryio:editor-close',
|
|
31
|
+
CLOSED: 'joryio:editor-closed',
|
|
32
|
+
} as const;
|
|
33
|
+
|
|
34
|
+
/** The global the editor bundle registers itself under, and the contract version between the two files. */
|
|
35
|
+
export const EDITOR_GLOBAL = '__joryioEditor';
|
|
36
|
+
export const EDITOR_API_VERSION = 1;
|
|
37
|
+
/** The file next to joryio.min.js on the SDK host. */
|
|
38
|
+
export const EDITOR_BUNDLE_FILE = 'joryio-editor.min.js';
|
|
39
|
+
|
|
40
|
+
export interface EditorBundleApi {
|
|
41
|
+
version: number;
|
|
42
|
+
start(ctx: { dashboardOrigin: string; opener: Window; logger: Logger; onStop: () => void }): { stop(): void };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Where the editor bundle is loaded from: the exact SDK version's folder on
|
|
47
|
+
* the SDK host, then the major channel (see sdkHostFileUrls).
|
|
48
|
+
* `editorScriptUrl` (init) replaces both, for a self-hosted SDK.
|
|
49
|
+
*/
|
|
50
|
+
export function editorBundleUrls(override?: string): string[] {
|
|
51
|
+
return sdkHostFileUrls(EDITOR_BUNDLE_FILE, override);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** True when this tab was opened by the dashboard's editor (the flag and an opener). */
|
|
55
|
+
export function editorRequested(): boolean {
|
|
56
|
+
try {
|
|
57
|
+
return typeof window !== 'undefined' && !!window.opener && new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) === '1';
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function loadScript(src: string): Promise<void> {
|
|
64
|
+
return loadSdkScript(src, 'data-joryio-editor');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class EditorGate {
|
|
68
|
+
private opener: Window | null = null;
|
|
69
|
+
private dashboardOrigin: string | null = null;
|
|
70
|
+
private verifying = false;
|
|
71
|
+
private session: { stop(): void } | null = null;
|
|
72
|
+
private off: (() => void) | null = null;
|
|
73
|
+
|
|
74
|
+
constructor(
|
|
75
|
+
private apiEndpoint: string,
|
|
76
|
+
private sdkKey: string,
|
|
77
|
+
private logger: Logger,
|
|
78
|
+
private options: { scriptUrl?: string; load?: (src: string) => Promise<void> } = {},
|
|
79
|
+
) {}
|
|
80
|
+
|
|
81
|
+
/** Step 1. Does nothing unless the dashboard's editor opened this tab. */
|
|
82
|
+
start(): void {
|
|
83
|
+
if (!editorRequested() || this.opener) return;
|
|
84
|
+
this.opener = window.opener as Window;
|
|
85
|
+
const onMessage = (e: MessageEvent) => void this.onMessage(e);
|
|
86
|
+
window.addEventListener('message', onMessage);
|
|
87
|
+
this.off = () => window.removeEventListener('message', onMessage);
|
|
88
|
+
try {
|
|
89
|
+
// No secret in it, so any target origin: the dashboard checks it came from the tab it opened.
|
|
90
|
+
this.opener.postMessage({ type: EDITOR_MESSAGES.READY }, '*');
|
|
91
|
+
} catch {
|
|
92
|
+
/* the opener went away */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
isActive(): boolean {
|
|
97
|
+
return !!this.session;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
stop(): void {
|
|
101
|
+
const session = this.session;
|
|
102
|
+
this.session = null;
|
|
103
|
+
session?.stop();
|
|
104
|
+
this.off?.();
|
|
105
|
+
this.off = null;
|
|
106
|
+
this.dashboardOrigin = null;
|
|
107
|
+
this.opener = null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private async onMessage(e: MessageEvent): Promise<void> {
|
|
111
|
+
const data = e.data as { type?: string; token?: string } | null;
|
|
112
|
+
if (!data || typeof data.type !== 'string' || this.dashboardOrigin) return;
|
|
113
|
+
if (data.type !== EDITOR_MESSAGES.TOKEN || e.source !== this.opener || typeof data.token !== 'string' || this.verifying) return;
|
|
114
|
+
this.verifying = true;
|
|
115
|
+
try {
|
|
116
|
+
const res = await fetch(`${this.apiEndpoint}/v1/in-app/editor/verify`, {
|
|
117
|
+
method: 'POST',
|
|
118
|
+
headers: { 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey, ...sdkIdentityHeaders() },
|
|
119
|
+
body: JSON.stringify({ token: data.token }),
|
|
120
|
+
});
|
|
121
|
+
const answer = res.ok ? await res.json() : null;
|
|
122
|
+
// The token says which dashboard may talk to this tab; the message must have come from it.
|
|
123
|
+
if (!answer?.valid || typeof answer.dashboardOrigin !== 'string' || answer.dashboardOrigin !== e.origin) {
|
|
124
|
+
this.logger.warn('Joryio editor: the editor token was not accepted for this site');
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
this.dashboardOrigin = answer.dashboardOrigin;
|
|
128
|
+
// The message listener of the handshake is done; the editor installs its own.
|
|
129
|
+
this.off?.();
|
|
130
|
+
this.off = null;
|
|
131
|
+
await this.loadAndStart(answer.dashboardOrigin);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
this.logger.debug('Joryio editor verification failed', error);
|
|
134
|
+
} finally {
|
|
135
|
+
this.verifying = false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Step 3: the bundle, only now. */
|
|
140
|
+
private async loadAndStart(dashboardOrigin: string): Promise<void> {
|
|
141
|
+
const load = this.options.load ?? loadScript;
|
|
142
|
+
let api: EditorBundleApi | undefined = (window as any)[EDITOR_GLOBAL];
|
|
143
|
+
for (const src of api ? [] : editorBundleUrls(this.options.scriptUrl)) {
|
|
144
|
+
try {
|
|
145
|
+
await load(src);
|
|
146
|
+
api = (window as any)[EDITOR_GLOBAL];
|
|
147
|
+
if (api) break;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
this.logger.debug('Joryio editor bundle failed to load', error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (!api || api.version !== EDITOR_API_VERSION || typeof api.start !== 'function' || !this.opener) {
|
|
153
|
+
this.logger.warn('Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.session = api.start({ dashboardOrigin, opener: this.opener, logger: this.logger, onStop: () => this.stop() });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature flags + remote config (Joryio BACKLOG D446).
|
|
3
|
+
*
|
|
4
|
+
* - `getFlag(key, default)` and the typed getters read the answer held on the
|
|
5
|
+
* device; they never wait for the network. Before the first answer, for a
|
|
6
|
+
* flag the server did not send, or for a value of the wrong type, they return
|
|
7
|
+
* the in-code default.
|
|
8
|
+
* - Nothing is fetched until the app uses flags (the first getter, getAllFlags,
|
|
9
|
+
* refreshFlags or onFlagsUpdated on this device), so a site that never reads
|
|
10
|
+
* a flag costs no request. From then on the answer (`POST /v1/flags/evaluate`,
|
|
11
|
+
* every active flag in one call) is
|
|
12
|
+
* kept in localStorage for the same visitor, and refreshed on start, when the
|
|
13
|
+
* page becomes visible again (at most once per FLAGS_MIN_REFRESH_SECONDS), on
|
|
14
|
+
* identify / reset, and on `refreshFlags()`. Browsers have no silent push
|
|
15
|
+
* (every web push must show a notification), so `jry_sync: "flags"` does not
|
|
16
|
+
* apply on the web.
|
|
17
|
+
* - An exposure (`flag.exposure`) is logged the first time a value is read in
|
|
18
|
+
* a session: once per flag and variant per session, unless the answer said
|
|
19
|
+
* `logExposure: false` (server-side sampling). The server re-evaluates every
|
|
20
|
+
* exposure, so only real assignments count.
|
|
21
|
+
* - Without tracking consent nothing is sent: no request names the visitor,
|
|
22
|
+
* no exposure is logged, and the getters return the in-code default.
|
|
23
|
+
*
|
|
24
|
+
* The same names and wire values on all five SDKs.
|
|
25
|
+
*/
|
|
26
|
+
import { Logger } from '../utils/logger';
|
|
27
|
+
import { bucketHash } from '../utils/bucket-hash';
|
|
28
|
+
import { sdkIdentityHeaders } from './config';
|
|
29
|
+
import { IdentityManager } from './identity';
|
|
30
|
+
import { SessionManager } from './session';
|
|
31
|
+
|
|
32
|
+
/** A refresh asked for within this many seconds of the last one is skipped (start, identify and refreshFlags() always go). */
|
|
33
|
+
export const FLAGS_MIN_REFRESH_SECONDS = 60;
|
|
34
|
+
/** Exposures are sent in one request this long after the first read. */
|
|
35
|
+
export const FLAG_EXPOSURE_FLUSH_MS = 1000;
|
|
36
|
+
/** The silent-push value that refreshes flags on the native SDKs (not applicable on the web). */
|
|
37
|
+
export const FLAG_SYNC_PUSH_VALUE = 'flags';
|
|
38
|
+
|
|
39
|
+
export type FlagValueType = 'boolean' | 'string' | 'number' | 'json';
|
|
40
|
+
/**
|
|
41
|
+
* Why the person got this value - the server's wire value, passed to the app
|
|
42
|
+
* unchanged. `override`: a journey's Feature flag step set it for them.
|
|
43
|
+
* `experiment`: an arm of a running feature flag experiment campaign (its
|
|
44
|
+
* holdout is `holdout`). Same list as the backend FLAG_REASONS.
|
|
45
|
+
*/
|
|
46
|
+
export type FlagReason = 'off' | 'rule' | 'default' | 'holdout' | 'archived' | 'override' | 'experiment';
|
|
47
|
+
|
|
48
|
+
/** One flag as the server sent it. */
|
|
49
|
+
export interface FlagResult {
|
|
50
|
+
value: unknown;
|
|
51
|
+
variant: string;
|
|
52
|
+
valueType: FlagValueType;
|
|
53
|
+
reason: FlagReason;
|
|
54
|
+
version: number;
|
|
55
|
+
logExposure: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type FlagsUpdatedCallback = (changedKeys: string[]) => void;
|
|
59
|
+
|
|
60
|
+
interface FlagsAuth {
|
|
61
|
+
getSdkAuthHeaders(subjectUserId?: string | null, anonymousId?: string | null): Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface FlagsRuntime {
|
|
65
|
+
/** true when the SDK may send (initialized, consent granted, not suspended). */
|
|
66
|
+
canSend: () => boolean;
|
|
67
|
+
requestTimeoutMs?: number;
|
|
68
|
+
noteStatus?: (status: number, data: unknown) => void;
|
|
69
|
+
/** Attributes the app set on this device, matched by attribute rules. */
|
|
70
|
+
attributes?: () => Record<string, unknown>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface Stored {
|
|
74
|
+
subject: string;
|
|
75
|
+
etag: string;
|
|
76
|
+
fetchedAt: number;
|
|
77
|
+
flags: Record<string, FlagResult>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The cached answer is per workspace: the key carries a hash of the SDK key
|
|
82
|
+
* (the same hash the StorageManager prefixes every other key with), so two
|
|
83
|
+
* workspaces on one origin - which may know the same person by the same
|
|
84
|
+
* external id - never read each other's flags. The unscoped key of builds
|
|
85
|
+
* before 2026-11-21 is never read; it is removed on the first load.
|
|
86
|
+
*/
|
|
87
|
+
const LEGACY_STORAGE_KEY = 'jry_flags';
|
|
88
|
+
export const flagsStorageKey = (sdkKey: string): string => `jry_flags_${bucketHash(sdkKey).toString(36)}`;
|
|
89
|
+
const nowMs = () => Date.now();
|
|
90
|
+
|
|
91
|
+
export class FlagsManager {
|
|
92
|
+
private flags: Record<string, FlagResult> = {};
|
|
93
|
+
private etag = '';
|
|
94
|
+
private fetchedAt = 0;
|
|
95
|
+
private generation = 0;
|
|
96
|
+
private inflight: Promise<void> | null = null;
|
|
97
|
+
private inflightGeneration = 0;
|
|
98
|
+
private listeners = new Set<FlagsUpdatedCallback>();
|
|
99
|
+
/** `<sessionId>|<person>|<flag>|<variant>` already reported this session. */
|
|
100
|
+
private exposed = new Set<string>();
|
|
101
|
+
/**
|
|
102
|
+
* Exposures waiting to be sent, each batch with the identity it was read
|
|
103
|
+
* under (who, session, attributes, generation) - captured when the first
|
|
104
|
+
* exposure of the batch was queued. A batch is always sent as the person who
|
|
105
|
+
* read the values, never as whoever is identified when the timer fires.
|
|
106
|
+
*/
|
|
107
|
+
private pending: { body: Record<string, unknown>; generation: number; exposures: Array<{ key: string; variant: string }> } | null = null;
|
|
108
|
+
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
109
|
+
/** The app reads flags on this device (a stored answer, or a call this page). */
|
|
110
|
+
private used = false;
|
|
111
|
+
private onVisible = () => {
|
|
112
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'visible') void this.refresh(false);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
constructor(
|
|
116
|
+
private readonly apiEndpoint: string,
|
|
117
|
+
private readonly sdkKey: string,
|
|
118
|
+
private readonly identity: IdentityManager,
|
|
119
|
+
private readonly session: SessionManager,
|
|
120
|
+
private readonly logger: Logger,
|
|
121
|
+
private readonly runtime: FlagsRuntime,
|
|
122
|
+
private readonly auth?: FlagsAuth | null,
|
|
123
|
+
) {
|
|
124
|
+
this.load();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Start: read the stored answer, refresh it, and refresh again when the page is shown. */
|
|
128
|
+
start(): void {
|
|
129
|
+
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', this.onVisible);
|
|
130
|
+
if (this.used) void this.refresh(true);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The first use on a page that had no stored answer fetches one (the getter itself returns at once). */
|
|
134
|
+
private use(): void {
|
|
135
|
+
if (this.used) return;
|
|
136
|
+
this.used = true;
|
|
137
|
+
void this.refresh(true);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
destroy(): void {
|
|
141
|
+
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', this.onVisible);
|
|
142
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
143
|
+
this.flushTimer = null;
|
|
144
|
+
this.listeners.clear();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The visitor or consent changed: the held answer belongs to someone else. */
|
|
148
|
+
onIdentityChanged(): void {
|
|
149
|
+
this.generation++;
|
|
150
|
+
// The batch carries its own snapshot, so it still goes as the previous person.
|
|
151
|
+
this.flush();
|
|
152
|
+
const before = Object.keys(this.flags);
|
|
153
|
+
this.flags = {};
|
|
154
|
+
this.etag = '';
|
|
155
|
+
this.fetchedAt = 0;
|
|
156
|
+
this.save();
|
|
157
|
+
if (before.length) this.emit(before);
|
|
158
|
+
if (this.used) void this.refresh(true);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
getFlag<T = unknown>(key: string, defaultValue: T): T {
|
|
162
|
+
const f = this.read(key);
|
|
163
|
+
return f ? (f.value as T) : defaultValue;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
getBoolFlag(key: string, defaultValue: boolean): boolean {
|
|
167
|
+
const f = this.read(key, 'boolean');
|
|
168
|
+
return f && typeof f.value === 'boolean' ? f.value : defaultValue;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
getStringFlag(key: string, defaultValue: string): string {
|
|
172
|
+
const f = this.read(key, 'string');
|
|
173
|
+
return f && typeof f.value === 'string' ? f.value : defaultValue;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
getNumberFlag(key: string, defaultValue: number): number {
|
|
177
|
+
const f = this.read(key, 'number');
|
|
178
|
+
return f && typeof f.value === 'number' ? f.value : defaultValue;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
getJsonFlag<T = unknown>(key: string, defaultValue: T): T {
|
|
182
|
+
const f = this.read(key, 'json');
|
|
183
|
+
return f ? (f.value as T) : defaultValue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Every flag the device holds, as key -> value. Reading them all logs no exposure. */
|
|
187
|
+
getAllFlags(): Record<string, unknown> {
|
|
188
|
+
if (!this.runtime.canSend()) return {};
|
|
189
|
+
this.use();
|
|
190
|
+
const out: Record<string, unknown> = {};
|
|
191
|
+
for (const [k, f] of Object.entries(this.flags)) out[k] = f.value;
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Ask the server now (always goes, unlike the automatic refreshes). */
|
|
196
|
+
async refreshFlags(): Promise<void> {
|
|
197
|
+
this.used = true;
|
|
198
|
+
await this.refresh(true);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Called with the keys whose value changed. Returns an unsubscribe function. */
|
|
202
|
+
onFlagsUpdated(callback: FlagsUpdatedCallback): () => void {
|
|
203
|
+
this.listeners.add(callback);
|
|
204
|
+
this.use();
|
|
205
|
+
return () => this.listeners.delete(callback);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ── internals ────────────────────────────────────────────────────────────
|
|
209
|
+
|
|
210
|
+
private read(key: string, type?: FlagValueType): FlagResult | null {
|
|
211
|
+
if (!this.runtime.canSend()) return null;
|
|
212
|
+
this.use();
|
|
213
|
+
const f = this.flags[key];
|
|
214
|
+
if (!f || (type && f.valueType !== type)) return null;
|
|
215
|
+
this.noteExposure(key, f);
|
|
216
|
+
return f;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private noteExposure(key: string, f: FlagResult): void {
|
|
220
|
+
if (!f.logExposure) return;
|
|
221
|
+
// The person is part of the mark: after an account switch in the same
|
|
222
|
+
// session the next person's first read is their own exposure.
|
|
223
|
+
const mark = `${this.session.getSessionId()}|${this.subjectKey()}|${key}|${f.variant}`;
|
|
224
|
+
if (this.exposed.has(mark)) return;
|
|
225
|
+
this.exposed.add(mark);
|
|
226
|
+
if (!this.pending || this.pending.generation !== this.generation) {
|
|
227
|
+
// A batch from before an identity change is sent first, as its own person.
|
|
228
|
+
if (this.pending) this.flush();
|
|
229
|
+
this.pending = { body: this.requestBody(), generation: this.generation, exposures: [] };
|
|
230
|
+
}
|
|
231
|
+
this.pending.exposures.push({ key, variant: f.variant });
|
|
232
|
+
if (!this.flushTimer) this.flushTimer = setTimeout(() => this.flush(), FLAG_EXPOSURE_FLUSH_MS);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Send the queued exposures (one request, the same identity as the evaluation). */
|
|
236
|
+
flush(): void {
|
|
237
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
238
|
+
this.flushTimer = null;
|
|
239
|
+
const batch = this.pending;
|
|
240
|
+
this.pending = null;
|
|
241
|
+
// Consent withdrawn since the reads: nothing is sent.
|
|
242
|
+
if (!batch || !batch.exposures.length || !this.runtime.canSend()) return;
|
|
243
|
+
const body = { ...batch.body, exposures: batch.exposures.slice(0, 100) };
|
|
244
|
+
this.post('/v1/flags/exposures', body, true).catch((error) => this.logger.debug('Flag exposures failed', error));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private subjectKey(): string {
|
|
248
|
+
return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private requestBody(): Record<string, unknown> {
|
|
252
|
+
const userId = this.identity.getUserId();
|
|
253
|
+
return {
|
|
254
|
+
...(userId ? { userId } : {}),
|
|
255
|
+
anonymousId: this.identity.getAnonymousId(),
|
|
256
|
+
sessionId: this.session.getSessionId(),
|
|
257
|
+
attributes: this.runtime.attributes?.() ?? {},
|
|
258
|
+
context: {
|
|
259
|
+
platform: 'web',
|
|
260
|
+
locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
|
|
261
|
+
url: typeof location !== 'undefined' ? location.href.split('?')[0] : undefined,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private async refresh(force: boolean): Promise<void> {
|
|
267
|
+
if (!this.runtime.canSend() || !this.used) return;
|
|
268
|
+
if (this.inflight) {
|
|
269
|
+
// A request in flight for a previous visitor: wait for it, then ask for this one.
|
|
270
|
+
const stale = this.inflightGeneration !== this.generation;
|
|
271
|
+
await this.inflight;
|
|
272
|
+
if (stale) await this.refresh(true);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (!force && nowMs() - this.fetchedAt < FLAGS_MIN_REFRESH_SECONDS * 1000) return;
|
|
276
|
+
const generation = this.generation;
|
|
277
|
+
this.inflightGeneration = generation;
|
|
278
|
+
this.inflight = (async () => {
|
|
279
|
+
try {
|
|
280
|
+
const res = await this.post('/v1/flags/evaluate', { ...this.requestBody(), ...(this.etag ? { etag: this.etag } : {}) }, false);
|
|
281
|
+
if (!res) return;
|
|
282
|
+
if (generation !== this.generation) return; // answer for a previous visitor
|
|
283
|
+
this.fetchedAt = nowMs();
|
|
284
|
+
if (res.notModified) {
|
|
285
|
+
this.save();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (!res.flags || typeof res.flags !== 'object') return;
|
|
289
|
+
const next = res.flags as Record<string, FlagResult>;
|
|
290
|
+
const changed = Object.keys({ ...this.flags, ...next }).filter(
|
|
291
|
+
(k) => JSON.stringify(this.flags[k]?.value) !== JSON.stringify(next[k]?.value) || this.flags[k]?.variant !== next[k]?.variant,
|
|
292
|
+
);
|
|
293
|
+
this.flags = next;
|
|
294
|
+
this.etag = typeof res.etag === 'string' ? res.etag : '';
|
|
295
|
+
this.save();
|
|
296
|
+
if (changed.length) this.emit(changed);
|
|
297
|
+
} catch (error) {
|
|
298
|
+
this.logger.debug('Flags refresh failed; keeping the held flags', error);
|
|
299
|
+
} finally {
|
|
300
|
+
this.inflight = null;
|
|
301
|
+
}
|
|
302
|
+
})();
|
|
303
|
+
return this.inflight;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private async post(path: string, body: Record<string, unknown>, keepalive: boolean): Promise<any> {
|
|
307
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
|
308
|
+
const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
|
|
309
|
+
const userId = typeof body.userId === 'string' ? body.userId : null;
|
|
310
|
+
try {
|
|
311
|
+
const response = await fetch(`${this.apiEndpoint}${path}`, {
|
|
312
|
+
method: 'POST',
|
|
313
|
+
headers: {
|
|
314
|
+
'Content-Type': 'application/json',
|
|
315
|
+
'X-SDK-Key': this.sdkKey,
|
|
316
|
+
...sdkIdentityHeaders(),
|
|
317
|
+
...(this.auth?.getSdkAuthHeaders(userId, userId ? null : (body.anonymousId as string) ?? null) || {}),
|
|
318
|
+
},
|
|
319
|
+
body: JSON.stringify(body),
|
|
320
|
+
...(keepalive ? { keepalive: true } : {}),
|
|
321
|
+
...(controller ? { signal: controller.signal } : {}),
|
|
322
|
+
});
|
|
323
|
+
if (!response.ok) {
|
|
324
|
+
this.runtime.noteStatus?.(response.status, null);
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
return await response.json();
|
|
328
|
+
} finally {
|
|
329
|
+
clearTimeout(timeout);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private emit(keys: string[]): void {
|
|
334
|
+
for (const cb of Array.from(this.listeners)) {
|
|
335
|
+
try {
|
|
336
|
+
cb(keys);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
this.logger.error('onFlagsUpdated callback failed', error);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private load(): void {
|
|
344
|
+
try {
|
|
345
|
+
if (typeof localStorage === 'undefined') return;
|
|
346
|
+
// Not workspace-scoped: another workspace on this origin may have written it.
|
|
347
|
+
localStorage.removeItem(LEGACY_STORAGE_KEY);
|
|
348
|
+
const raw = localStorage.getItem(flagsStorageKey(this.sdkKey));
|
|
349
|
+
if (!raw) return;
|
|
350
|
+
const s: Stored = JSON.parse(raw);
|
|
351
|
+
// Another visitor's answer is never used.
|
|
352
|
+
if (!s || s.subject !== this.subjectKey() || typeof s.flags !== 'object') return;
|
|
353
|
+
this.flags = s.flags;
|
|
354
|
+
this.etag = s.etag || '';
|
|
355
|
+
this.used = true;
|
|
356
|
+
// The stored answer is used at once, but a start refresh always goes.
|
|
357
|
+
this.fetchedAt = 0;
|
|
358
|
+
} catch {
|
|
359
|
+
/* unreadable storage: start empty */
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private save(): void {
|
|
364
|
+
try {
|
|
365
|
+
if (typeof localStorage === 'undefined') return;
|
|
366
|
+
const s: Stored = { subject: this.subjectKey(), etag: this.etag, fetchedAt: this.fetchedAt, flags: this.flags };
|
|
367
|
+
localStorage.setItem(flagsStorageKey(this.sdkKey), JSON.stringify(s));
|
|
368
|
+
} catch {
|
|
369
|
+
/* storage full or blocked: memory only */
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|