@joryio/web-sdk 1.4.0-beta.2 → 1.4.0-beta.5

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 (71) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +1 -1
  3. package/dist/cards-ui/card-feed-view.d.ts +4 -0
  4. package/dist/cards-ui/card-feed-view.d.ts.map +1 -0
  5. package/dist/cards-ui/index.d.ts +4 -0
  6. package/dist/cards-ui/index.d.ts.map +1 -0
  7. package/dist/core/cards-ui-contract.d.ts +30 -0
  8. package/dist/core/cards-ui-contract.d.ts.map +1 -0
  9. package/dist/core/cards.d.ts +131 -0
  10. package/dist/core/cards.d.ts.map +1 -0
  11. package/dist/core/config.d.ts +21 -1
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/editor-gate.d.ts +47 -0
  14. package/dist/core/editor-gate.d.ts.map +1 -0
  15. package/dist/core/flags.d.ts +74 -0
  16. package/dist/core/flags.d.ts.map +1 -0
  17. package/dist/core/inapp.d.ts +13 -1
  18. package/dist/core/inapp.d.ts.map +1 -1
  19. package/dist/core/links.d.ts +27 -0
  20. package/dist/core/links.d.ts.map +1 -0
  21. package/dist/core/network.d.ts.map +1 -1
  22. package/dist/core/page-context.d.ts +101 -0
  23. package/dist/core/page-context.d.ts.map +1 -0
  24. package/dist/core/page-edits.d.ts +129 -0
  25. package/dist/core/page-edits.d.ts.map +1 -0
  26. package/dist/core/placements.d.ts +219 -0
  27. package/dist/core/placements.d.ts.map +1 -0
  28. package/dist/core/sdk-host-files.d.ts +5 -0
  29. package/dist/core/sdk-host-files.d.ts.map +1 -0
  30. package/dist/core/sdk.d.ts +37 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/core/subscription.d.ts +6 -0
  33. package/dist/core/subscription.d.ts.map +1 -0
  34. package/dist/editor/index.d.ts +4 -0
  35. package/dist/editor/index.d.ts.map +1 -0
  36. package/dist/editor/visual-editor.d.ts +39 -0
  37. package/dist/editor/visual-editor.d.ts.map +1 -0
  38. package/dist/index.d.mts +206 -3
  39. package/dist/index.d.ts +9 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/joryio-cards-ui.min.js +7 -0
  42. package/dist/joryio-cards-ui.min.js.map +1 -0
  43. package/dist/joryio-editor.min.js +7 -0
  44. package/dist/joryio-editor.min.js.map +1 -0
  45. package/dist/joryio-sw.js +1 -1
  46. package/dist/joryio.cjs.js +7215 -3508
  47. package/dist/joryio.min.js +2 -2
  48. package/dist/joryio.min.js.map +1 -1
  49. package/dist/joryio.mjs +7207 -3509
  50. package/dist/joryio.umd.js +7214 -3507
  51. package/package.json +4 -1
  52. package/src/cards-ui/card-feed-view.ts +249 -0
  53. package/src/cards-ui/index.ts +26 -0
  54. package/src/core/cards-ui-contract.ts +58 -0
  55. package/src/core/cards.ts +846 -0
  56. package/src/core/config.ts +86 -2
  57. package/src/core/editor-gate.ts +158 -0
  58. package/src/core/flags.ts +378 -0
  59. package/src/core/inapp.ts +283 -152
  60. package/src/core/links.ts +104 -0
  61. package/src/core/network.ts +3 -0
  62. package/src/core/page-context.ts +460 -0
  63. package/src/core/page-edits.ts +1036 -0
  64. package/src/core/placements.ts +1434 -0
  65. package/src/core/sdk-host-files.ts +93 -0
  66. package/src/core/sdk.ts +383 -1
  67. package/src/core/subscription.ts +27 -0
  68. package/src/editor/index.ts +27 -0
  69. package/src/editor/visual-editor.ts +301 -0
  70. package/src/index.ts +35 -0
  71. package/src/snippet/loader.js +25 -1
@@ -0,0 +1,1036 @@
1
+ /**
2
+ * Page edits on web (BACKLOG D444 Phase 4, docs/PLACEMENTS_WEBSITE_LAYER.md 2).
3
+ *
4
+ * A page-edit campaign changes elements of the site's own page, found by CSS
5
+ * selector: replace a text, an image, a link, hide an element, or insert a
6
+ * placement next to it. Nothing else - no HTML, no script, no free-form DOM.
7
+ *
8
+ * - Text is set with `textContent` (never parsed as HTML); image and link
9
+ * addresses must be absolute http(s); a selector that could escape the
10
+ * anti-flicker style rule is refused. The server checks the same and this
11
+ * SDK checks again: an edit it does not trust is skipped, never half-applied.
12
+ * - Site settings first (`GET /v1/in-app/site-settings?sdkKey=`, public,
13
+ * the same for every visitor; asked once per SDK session and refreshed at
14
+ * most every SITE_SETTINGS_SESSION_REFRESH_SECONDS, kept in sessionStorage
15
+ * so the session's later page loads do not wait for it): page edits off
16
+ * for this site, or no live page-edit campaign, = nothing is asked or
17
+ * applied on this page view. Otherwise the per-visitor answer.
18
+ * - Anti-flicker: only edited elements are hidden (opacity, so the layout
19
+ * does not move), for at most PAGE_EDIT_ANTI_FLICKER_MS from the start of
20
+ * the page, never the whole body: the ones edited on this page last time,
21
+ * or - on a first view, when there are none - the site's list from the site
22
+ * settings (selectors only).
23
+ * - Static edits from the last answer for this page apply at once, as each
24
+ * element appears (MutationObserver); personalized edits apply when the
25
+ * answer arrives and are never stored.
26
+ * - A route change undoes this page's edits and applies the next page's.
27
+ * - Exposure: `in_app.displayed` once an edit of the experience landed on an
28
+ * element; a control visitor reports `in_app.control_viewed` once one of
29
+ * the control's selectors is on the page.
30
+ * - Server-applied edits (D450): a store plugin may already have written the
31
+ * edits that are the same for every visitor into the page's HTML. Its
32
+ * marker - a JSON block `#joryio-server-page-edits` and
33
+ * `data-joryio-applied="<campaignId>:<editId>"` on each changed element -
34
+ * says which. The SDK never applies those again (no double insert, no
35
+ * flicker), counts them as landed for the exposure (once, with its own
36
+ * answer's token), keeps them out of the anti-flicker rule, and undoes one
37
+ * (from `data-joryio-orig` and the element's `<template data-joryio-orig>`)
38
+ * when the definitive answer for this visitor no longer carries it -
39
+ * paused, edited, the visitor suppressed or in a control, page edits
40
+ * switched off - or on a route change to another page.
41
+ */
42
+ import { bucketHash } from '../utils/bucket-hash';
43
+ import type { IdentityManager } from './identity';
44
+ import type { SessionManager } from './session';
45
+ import type { Logger } from '../utils/logger';
46
+ import type { InAppAuthProvider } from './inapp';
47
+ import type { PlacementConsent } from './placements';
48
+ import { sdkIdentityHeaders } from './config';
49
+ import { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';
50
+
51
+ export const PAGE_EDIT_OPERATIONS = ['replace_text', 'replace_image', 'replace_link', 'hide', 'insert_placement'] as const;
52
+ export const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append'] as const;
53
+ export const PAGE_EDITS_CAPABILITY = 'page_edits';
54
+ /** The longest edited elements stay hidden while the SDK waits. Never the whole body. */
55
+ export const PAGE_EDIT_ANTI_FLICKER_MS = 300;
56
+
57
+ const MAX_SELECTOR_LENGTH = 500;
58
+ const MAX_TEXT_LENGTH = 2000;
59
+ const MAX_URL_LENGTH = 2048;
60
+ const PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;
61
+ const STYLE_ID = 'joryio-page-edits-anti-flicker';
62
+ /**
63
+ * Both stores are per workspace: the names carry a hash of the SDK key (the
64
+ * flags cache's scheme), so two workspaces on one origin never share edits
65
+ * or anti-flicker selectors. The unscoped names of earlier builds are never
66
+ * read; they are removed on the first load.
67
+ */
68
+ const LEGACY_ANSWER_STORE = 'jry_page_edits';
69
+ const LEGACY_SELECTOR_STORE = 'jry_page_edit_selectors';
70
+ export const pageEditsStorageKeys = (sdkKey: string): { answers: string; selectors: string; site: string } => {
71
+ const h = bucketHash(sdkKey).toString(36);
72
+ return { answers: `jry_page_edits_${h}`, selectors: `jry_page_edit_selectors_${h}`, site: `jry_page_edit_site_${h}` };
73
+ };
74
+ const MAX_REMEMBERED_PAGES = 50;
75
+ const DEFAULT_TTL_SECONDS = 300;
76
+ /**
77
+ * The site settings are asked once per SDK session and then at most every
78
+ * this many seconds within it (sessionStorage, per workspace, tied to the
79
+ * session id: a new session asks again). The server's `ttlSeconds` (60) is
80
+ * the HTTP cache lifetime for browsers and the CDN and no longer shortens
81
+ * this: on a multi-page store every full page load used to re-ask, and the
82
+ * answer is the same for every visitor and changes only when a page-edit
83
+ * campaign is launched or page edits are switched on or off. The cost, by
84
+ * design: a newly launched page-edit campaign reaches a visitor already on
85
+ * the site within this time. Pausing is not delayed - `/page-edits` checks
86
+ * every campaign's liveness itself on every page.
87
+ */
88
+ export const SITE_SETTINGS_SESSION_REFRESH_SECONDS = 600;
89
+ /** At most this many selectors of the site list go into the style rule (the server sends at most 200). */
90
+ const MAX_SITE_SELECTORS = 200;
91
+
92
+ /**
93
+ * The marker a store plugin writes with the edits it applied in the HTML
94
+ * (backend common/web-experience/server-page-edits.ts, the plugins' shared
95
+ * core; pinned by server-page-edits-parity.spec.ts).
96
+ */
97
+ export const SERVER_PAGE_EDITS_MARKER_ID = 'joryio-server-page-edits';
98
+ export const SERVER_APPLIED_ATTR = 'data-joryio-applied';
99
+ export const SERVER_ORIG_ATTR = 'data-joryio-orig';
100
+ export const SERVER_SPOT_ATTR = 'data-joryio-server-spot';
101
+ const SERVER_MARKER_VERSION = 1;
102
+
103
+ interface ServerEdit {
104
+ experienceId: string;
105
+ variantId: string | null;
106
+ edit: PageEditWire;
107
+ }
108
+
109
+ const sameEdit = (a: PageEditWire, b: PageEditWire): boolean =>
110
+ a.id === b.id &&
111
+ a.selector === b.selector &&
112
+ a.operation === b.operation &&
113
+ (a.value ?? null) === (b.value ?? null) &&
114
+ (a.placementKey ?? null) === (b.placementKey ?? null) &&
115
+ (a.position ?? null) === (b.position ?? null) &&
116
+ !b.personalized;
117
+
118
+ function serverMarkerElement(): HTMLScriptElement | null {
119
+ const head = document.head;
120
+ if (!head) return null;
121
+ for (const c of Array.from(head.children)) {
122
+ if (c.id === SERVER_PAGE_EDITS_MARKER_ID) {
123
+ return c.tagName === 'SCRIPT' && (c.getAttribute('type') || '').trim().toLowerCase() === 'application/json' ? (c as HTMLScriptElement) : null;
124
+ }
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /** An address the undo may write back: absolute http(s) or relative (no scheme). Anything else is dropped. */
130
+ function safeRestoredUrl(v: unknown): string | null {
131
+ if (typeof v !== 'string' || v.length > MAX_URL_LENGTH) return null;
132
+ // eslint-disable-next-line no-control-regex
133
+ if (/[\u0000-\u001f\u007f]/.test(v)) return null;
134
+ const t = v.trim();
135
+ if (/^https?:\/\//i.test(t)) return v;
136
+ // A scheme is letters before a ':' that comes before any '/', '?' or '#'.
137
+ return /^[a-z][a-z0-9+.-]*:/i.test(t) ? null : v;
138
+ }
139
+
140
+ const safeRestoredSrcset = (v: unknown): string | null =>
141
+ typeof v === 'string' && v.split(',').every((c) => !c.trim() || safeRestoredUrl(c.trim().split(/\s+/)[0]) !== null) ? v : null;
142
+
143
+ const HIDE_DECLARATION = 'display:none !important';
144
+
145
+ /**
146
+ * Inline text markup a replaced element's original content may come back with.
147
+ * Everything else is unwrapped to its text (its children are kept, checked the same way):
148
+ * no script, frame, object, embed, meta, base, link, style, form, svg or math element is
149
+ * ever created, and no attribute outside RESTORE_ATTRIBUTES (no on*, style, srcdoc, data).
150
+ */
151
+ const RESTORE_ELEMENTS = new Set(['A', 'ABBR', 'B', 'BDI', 'BDO', 'BR', 'CITE', 'CODE', 'DATA', 'DEL', 'DFN', 'EM', 'I', 'IMG', 'INS', 'KBD', 'MARK', 'Q', 'S', 'SAMP', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TIME', 'U', 'VAR', 'WBR']);
152
+ const RESTORE_ATTRIBUTES = new Set(['class', 'id', 'title', 'lang', 'dir', 'alt', 'width', 'height', 'datetime', 'href', 'src', 'srcset', 'rel', 'target']);
153
+ const MAX_RESTORE_NODES = 500;
154
+
155
+ function restoreInline(from: DocumentFragment): DocumentFragment {
156
+ const out = document.createDocumentFragment();
157
+ let budget = MAX_RESTORE_NODES;
158
+ const copy = (src: Node, into: Node): void => {
159
+ for (const n of Array.from(src.childNodes)) {
160
+ if (budget-- <= 0) return;
161
+ if (n.nodeType === 3) {
162
+ into.appendChild(document.createTextNode(n.nodeValue || ''));
163
+ } else if (n.nodeType === 1) {
164
+ const e = n as Element;
165
+ if (e.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !RESTORE_ELEMENTS.has(e.tagName)) {
166
+ // Not allowed: only its text and allowed descendants, never the element.
167
+ if (!/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(e.tagName)) copy(e, into);
168
+ continue;
169
+ }
170
+ const made = document.createElement(e.tagName.toLowerCase());
171
+ for (const a of Array.from(e.attributes)) {
172
+ const name = a.name.toLowerCase();
173
+ if (!RESTORE_ATTRIBUTES.has(name)) continue;
174
+ if (name === 'href' || name === 'src') {
175
+ const v = safeRestoredUrl(a.value);
176
+ if (v !== null) made.setAttribute(name, v);
177
+ } else if (name === 'srcset') {
178
+ const v = safeRestoredSrcset(a.value);
179
+ if (v !== null) made.setAttribute(name, v);
180
+ } else {
181
+ made.setAttribute(name, a.value);
182
+ }
183
+ }
184
+ into.appendChild(made);
185
+ copy(e, made);
186
+ }
187
+ }
188
+ };
189
+ copy(from, out);
190
+ return out;
191
+ }
192
+
193
+ const tokensOf = (el: Element): string[] => (el.getAttribute(SERVER_APPLIED_ATTR) || '').split(/\s+/).filter(Boolean);
194
+
195
+ /** `GET /v1/in-app/site-settings` (backend common/web-experience/page-edit-site.ts). */
196
+ export interface SiteSettingsResponse {
197
+ success?: boolean;
198
+ ttlSeconds?: number;
199
+ pageEdits?: { enabled?: boolean; active?: boolean; antiFlickerSelectors?: string[] };
200
+ }
201
+ export interface PageEditSite {
202
+ enabled: boolean;
203
+ active: boolean;
204
+ antiFlickerSelectors: string[];
205
+ }
206
+
207
+ export type PageEditOperation = (typeof PAGE_EDIT_OPERATIONS)[number];
208
+ export type PageEditPosition = (typeof PAGE_EDIT_POSITIONS)[number];
209
+
210
+ export interface PageEditWire {
211
+ id: string;
212
+ selector: string;
213
+ operation: PageEditOperation;
214
+ value?: string;
215
+ placementKey?: string;
216
+ position?: PageEditPosition;
217
+ personalized?: true;
218
+ }
219
+
220
+ export interface PageEditExperienceWire {
221
+ id: string;
222
+ variantId: string | null;
223
+ deliveryId: string | null;
224
+ deliveryToken: string | null;
225
+ isControl: boolean;
226
+ controlToken: string | null;
227
+ selectors: string[];
228
+ edits: PageEditWire[];
229
+ }
230
+
231
+ export interface PageEditsResponse {
232
+ success?: boolean;
233
+ ttlSeconds?: number;
234
+ experiences?: PageEditExperienceWire[];
235
+ }
236
+
237
+ export interface PageEditRuntime {
238
+ /** As placements: null = send nothing; `granted` = personal serving and reporting. */
239
+ consent: () => PlacementConsent | null;
240
+ requestTimeoutMs?: number;
241
+ noteStatus?: (status: number, data: any) => void;
242
+ }
243
+
244
+ /** Same rule as the server: nothing that could close the style rule, no comment, no control character. */
245
+ export function isSafeSelector(selector: unknown): selector is string {
246
+ if (typeof selector !== 'string') return false;
247
+ const s = selector.trim();
248
+ if (!s || s.length > MAX_SELECTOR_LENGTH) return false;
249
+ if (/[{};<@]/.test(s) || s.includes('/*') || s.includes('*/')) return false;
250
+ // eslint-disable-next-line no-control-regex
251
+ if (/[\u0000-\u001f\u007f]/.test(s)) return false;
252
+ try {
253
+ if (typeof document !== 'undefined') document.createDocumentFragment().querySelector(s);
254
+ } catch {
255
+ return false; // not a selector this browser parses
256
+ }
257
+ return true;
258
+ }
259
+
260
+ export function isSafeEditUrl(url: unknown): url is string {
261
+ if (typeof url !== 'string') return false;
262
+ const u = url.trim();
263
+ if (!u || u.length > MAX_URL_LENGTH) return false;
264
+ // eslint-disable-next-line no-control-regex
265
+ if (/[\u0000-\u001f\u007f\s]/.test(u)) return false;
266
+ return /^https?:\/\/[^/?#\s]+/i.test(u);
267
+ }
268
+
269
+ /** The edit as this SDK will apply it, or null - an edit it does not trust is skipped whole. */
270
+ export function trustedEdit(e: any): PageEditWire | null {
271
+ if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector)) return null;
272
+ const base = { id: e.id, selector: e.selector.trim(), ...(e.personalized === true ? { personalized: true as const } : {}) };
273
+ switch (e.operation) {
274
+ case 'hide':
275
+ return { ...base, operation: 'hide' };
276
+ case 'replace_text':
277
+ return typeof e.value === 'string' && e.value.length <= MAX_TEXT_LENGTH ? { ...base, operation: 'replace_text', value: e.value } : null;
278
+ case 'replace_image':
279
+ case 'replace_link':
280
+ return isSafeEditUrl(e.value) ? { ...base, operation: e.operation, value: e.value.trim() } : null;
281
+ case 'insert_placement':
282
+ return typeof e.placementKey === 'string' && PLACEMENT_KEY_PATTERN.test(e.placementKey)
283
+ ? { ...base, operation: 'insert_placement', placementKey: e.placementKey, position: (PAGE_EDIT_POSITIONS as readonly string[]).includes(e.position) ? e.position : 'after' }
284
+ : null;
285
+ default:
286
+ return null;
287
+ }
288
+ }
289
+
290
+ interface Applied {
291
+ el: Element;
292
+ editId: string;
293
+ undo: () => void;
294
+ }
295
+
296
+ interface Experience {
297
+ wire: PageEditExperienceWire;
298
+ edits: PageEditWire[];
299
+ }
300
+
301
+ /** The site settings as stored for one SDK session (`sid`), answered at `at`. */
302
+ interface StoredSite {
303
+ sid: string;
304
+ at: number;
305
+ value: PageEditSite;
306
+ }
307
+
308
+ export class PageEditManager {
309
+ private page: PageContextTracker | null = null;
310
+ private pageUnsubscribe: (() => void) | null = null;
311
+ private experiences: Experience[] = [];
312
+ private applied: Applied[] = [];
313
+ private reported = new Set<string>();
314
+ private observer: MutationObserver | null = null;
315
+ private scheduled = false;
316
+ private flickerTimer: ReturnType<typeof setTimeout> | null = null;
317
+ /** When the current page started: the anti-flicker never lasts past this + PAGE_EDIT_ANTI_FLICKER_MS. */
318
+ private pageStartedAt = 0;
319
+ /** The last site settings answer, for its session id (mirrors the sessionStorage entry). */
320
+ private site: StoredSite | null = null;
321
+ private siteRequest: Promise<PageEditSite | null> | null = null;
322
+ private readonly stores: { answers: string; selectors: string; site: string };
323
+ /** Edits the page's HTML arrived with (token -> edit); null until the marker was read. */
324
+ private server: Map<string, ServerEdit> | null = null;
325
+ /** The page those were written for: a route change elsewhere undoes them. */
326
+ private serverUrl: string | null = null;
327
+ private generation = 0;
328
+ private started = false;
329
+ private destroyed = false;
330
+
331
+ constructor(
332
+ private apiEndpoint: string,
333
+ private sdkKey: string,
334
+ private identity: IdentityManager,
335
+ private session: SessionManager,
336
+ private logger: Logger,
337
+ private runtime: PageEditRuntime,
338
+ private auth?: InAppAuthProvider,
339
+ ) {
340
+ this.stores = pageEditsStorageKeys(sdkKey);
341
+ try {
342
+ // Not workspace-scoped: another workspace on this origin may have written them.
343
+ localStorage.removeItem(LEGACY_SELECTOR_STORE);
344
+ sessionStorage.removeItem(LEGACY_ANSWER_STORE);
345
+ } catch {
346
+ /* storage blocked */
347
+ }
348
+ }
349
+
350
+ setPageContext(tracker: PageContextTracker | null): void {
351
+ this.pageUnsubscribe?.();
352
+ this.pageUnsubscribe = null;
353
+ this.page = tracker;
354
+ if (tracker) {
355
+ this.pageUnsubscribe = tracker.onSignal((s) => {
356
+ if (s.type === 'page_change' && this.started) this.loadPage();
357
+ });
358
+ }
359
+ }
360
+
361
+ /** Hide what was edited here last time, apply what is known, observe the DOM, ask the server. */
362
+ start(): void {
363
+ if (this.started || this.destroyed || typeof document === 'undefined') return;
364
+ this.started = true;
365
+ if (typeof MutationObserver !== 'undefined' && document.documentElement) {
366
+ this.observer = new MutationObserver(() => this.schedule());
367
+ this.observer.observe(document.documentElement, { childList: true, subtree: true });
368
+ }
369
+ this.loadPage();
370
+ }
371
+
372
+ /**
373
+ * The audience changed (identify, reset, consent): forget this visitor's
374
+ * answers and ask again. `siteSettings: true` (reset, wipeData, a consent
375
+ * change) forgets the stored site settings too; identify keeps them - they
376
+ * are the same for every visitor of the site.
377
+ */
378
+ invalidate(opts: { siteSettings?: boolean } = {}): void {
379
+ this.generation++;
380
+ this.reported.clear();
381
+ if (opts.siteSettings) this.forgetSite();
382
+ try {
383
+ sessionStorage.removeItem(this.stores.answers);
384
+ } catch {
385
+ /* ignore */
386
+ }
387
+ if (this.started) this.loadPage();
388
+ }
389
+
390
+ destroy(): void {
391
+ this.destroyed = true;
392
+ this.pageUnsubscribe?.();
393
+ this.observer?.disconnect();
394
+ this.observer = null;
395
+ this.revertAll();
396
+ this.showAll();
397
+ }
398
+
399
+ /** Currently applied edits, for tests and debugging. */
400
+ appliedCount(): number {
401
+ return this.applied.length;
402
+ }
403
+
404
+ /** Edits the page arrived with from the server and still carries, for tests and debugging. */
405
+ serverAppliedCount(): number {
406
+ return this.serverEdits().size;
407
+ }
408
+
409
+ // ── one page ─────────────────────────────────────────────────────────────
410
+
411
+ private url(): string | null {
412
+ return this.page ? this.page.current().url : currentPageUrl();
413
+ }
414
+
415
+ private loadPage(): void {
416
+ const generation = ++this.generation;
417
+ this.revertAll();
418
+ const url = this.url();
419
+ if (!url) {
420
+ this.experiences = [];
421
+ return;
422
+ }
423
+ this.pageStartedAt = Date.now();
424
+ // The server's edits belong to the page they were written for.
425
+ const server = this.serverEdits();
426
+ if (this.serverUrl === null) this.serverUrl = url;
427
+ else if (url !== this.serverUrl && server.size) this.reconcileServer([]);
428
+ // 1. Anti-flicker: the elements edited on this page last time, at most 300 ms.
429
+ const remembered = this.rememberedSelectors(url);
430
+ this.hide(remembered);
431
+ // 2. Static edits from the last answer for this page, applied as elements appear.
432
+ this.experiences = this.cachedExperiences(url);
433
+ this.applyAll();
434
+ // 3. The site settings (cached), then the answer for this page and visitor.
435
+ void this.siteThenFetch(url, generation, remembered.length > 0);
436
+ }
437
+
438
+ private async siteThenFetch(url: string, generation: number, rememberedAny: boolean): Promise<void> {
439
+ // A stored answer for this session is used at once - no wait before the
440
+ // per-visitor request - and refreshed in the background when it is older
441
+ // than SITE_SETTINGS_SESSION_REFRESH_SECONDS. Only without one (first
442
+ // page of a session) does the page wait for the site settings.
443
+ const stored = this.storedSite();
444
+ let site: PageEditSite | null;
445
+ if (stored) {
446
+ site = stored.value;
447
+ if (Date.now() - stored.at >= SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) {
448
+ void this.requestSite().then((fresh) => {
449
+ // Was off or idle and is live now: this page asks after all.
450
+ if (fresh && fresh.enabled && fresh.active && !(site!.enabled && site!.active) && generation === this.generation && !this.destroyed) {
451
+ void this.fetch(url, generation);
452
+ }
453
+ });
454
+ }
455
+ } else {
456
+ site = await this.siteSettings();
457
+ }
458
+ if (generation !== this.generation || this.destroyed) return;
459
+ if (site && (!site.enabled || !site.active)) {
460
+ // Off for this site, or nothing live: undo what the cache (or the server) applied, ask nothing.
461
+ this.revertAll();
462
+ this.reconcileServer([]);
463
+ this.experiences = [];
464
+ this.showAll();
465
+ return;
466
+ }
467
+ // First view on this page: hold back the site's edited elements, inside the same 300 ms.
468
+ if (site && !rememberedAny && site.antiFlickerSelectors.length) this.hide(site.antiFlickerSelectors);
469
+ await this.fetch(url, generation);
470
+ }
471
+
472
+ /**
473
+ * The site settings: one GET per SDK session, then at most one per
474
+ * SITE_SETTINGS_SESSION_REFRESH_SECONDS within it, kept in sessionStorage
475
+ * per workspace across the session's page loads. A CORS-simple request (no
476
+ * custom header, the key in the query string - the server refuses a key in
477
+ * a header there, the URL being the cache key), so no preflight. Null when
478
+ * unknown (network error, an HTTP error, an answer it cannot read): then
479
+ * the SDK asks /page-edits as it always did, and nothing is stored.
480
+ */
481
+ siteSettings(): Promise<PageEditSite | null> {
482
+ const stored = this.storedSite();
483
+ if (stored && Date.now() - stored.at < SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) return Promise.resolve(stored.value);
484
+ return this.requestSite();
485
+ }
486
+
487
+ /** The stored answer for the current session id (any age), or null. */
488
+ private storedSite(): StoredSite | null {
489
+ const sid = this.session.getSessionId();
490
+ if (!sid) return null; // no session (after wipeData): nothing to tie it to
491
+ if (this.site && this.site.sid === sid) return this.site;
492
+ this.site = null;
493
+ try {
494
+ const raw = JSON.parse(sessionStorage.getItem(this.stores.site) || 'null');
495
+ const v = raw?.value;
496
+ if (raw && raw.sid === sid && typeof raw.at === 'number' && raw.at <= Date.now() && v && typeof v === 'object') {
497
+ this.site = {
498
+ sid,
499
+ at: raw.at,
500
+ value: {
501
+ enabled: v.enabled !== false,
502
+ active: v.active !== false,
503
+ antiFlickerSelectors: (Array.isArray(v.antiFlickerSelectors) ? v.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),
504
+ },
505
+ };
506
+ } else if (raw) {
507
+ sessionStorage.removeItem(this.stores.site); // another session's answer
508
+ }
509
+ } catch {
510
+ /* storage blocked or unreadable: ask */
511
+ }
512
+ return this.site;
513
+ }
514
+
515
+ private forgetSite(): void {
516
+ this.site = null;
517
+ try {
518
+ sessionStorage.removeItem(this.stores.site);
519
+ } catch {
520
+ /* ignore */
521
+ }
522
+ }
523
+
524
+ private requestSite(): Promise<PageEditSite | null> {
525
+ if (this.siteRequest) return this.siteRequest;
526
+ const request = (async (): Promise<PageEditSite | null> => {
527
+ const sid = this.session.getSessionId();
528
+ try {
529
+ const res = await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`, { method: 'GET', credentials: 'omit' });
530
+ if (!res.ok) {
531
+ this.runtime.noteStatus?.(res.status, null);
532
+ this.forgetSite();
533
+ return null;
534
+ }
535
+ const data: SiteSettingsResponse = await res.json();
536
+ const pe = data?.pageEdits;
537
+ if (!pe || typeof pe !== 'object') {
538
+ this.forgetSite();
539
+ return null;
540
+ }
541
+ const value: PageEditSite = {
542
+ enabled: pe.enabled !== false,
543
+ active: pe.active !== false,
544
+ antiFlickerSelectors: (Array.isArray(pe.antiFlickerSelectors) ? pe.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),
545
+ };
546
+ // data.ttlSeconds is the HTTP cache lifetime; the SDK keeps the
547
+ // answer for the session (SITE_SETTINGS_SESSION_REFRESH_SECONDS).
548
+ if (sid) {
549
+ this.site = { sid, at: Date.now(), value };
550
+ try {
551
+ sessionStorage.setItem(this.stores.site, JSON.stringify(this.site));
552
+ } catch {
553
+ /* storage full or blocked: kept in memory for this page */
554
+ }
555
+ }
556
+ return value;
557
+ } catch (error) {
558
+ this.logger.debug('Site settings request failed', error);
559
+ // Unknown: a stale stored answer is not trusted past its refresh time.
560
+ this.forgetSite();
561
+ return null;
562
+ } finally {
563
+ this.siteRequest = null;
564
+ }
565
+ })();
566
+ this.siteRequest = request;
567
+ return request;
568
+ }
569
+
570
+ private async fetch(url: string, generation: number): Promise<void> {
571
+ const consent = this.runtime.consent();
572
+ if (consent === null || this.destroyed) {
573
+ this.showAll();
574
+ return;
575
+ }
576
+ const personal = consent === 'granted';
577
+ const userId = personal ? this.identity.getUserId() : null;
578
+ const anonymousId = personal ? this.identity.getAnonymousId() : null;
579
+ const body = {
580
+ ...(userId ? { userId } : {}),
581
+ ...(anonymousId ? { anonymousId } : {}),
582
+ ...(personal ? { sessionId: this.session.getSessionId() } : {}),
583
+ deviceType: 'web',
584
+ locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
585
+ capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY],
586
+ trackingConsent: consent,
587
+ context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} },
588
+ };
589
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
590
+ const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
591
+ try {
592
+ const res = await fetch(`${this.apiEndpoint}/v1/in-app/page-edits`, {
593
+ method: 'POST',
594
+ headers: {
595
+ 'Content-Type': 'application/json',
596
+ 'X-SDK-Key': this.sdkKey,
597
+ ...sdkIdentityHeaders(),
598
+ ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),
599
+ },
600
+ body: JSON.stringify(body),
601
+ ...(controller ? { signal: controller.signal } : {}),
602
+ });
603
+ if (generation !== this.generation) return;
604
+ if (!res.ok) {
605
+ // 429 and every other failure: keep what is applied (the cached static edits).
606
+ this.runtime.noteStatus?.(res.status, null);
607
+ return;
608
+ }
609
+ const data: PageEditsResponse = await res.json();
610
+ if (generation !== this.generation || !data || data.success === false || !Array.isArray(data.experiences)) return;
611
+ const experiences = data.experiences
612
+ .filter((x) => x && typeof x.id === 'string')
613
+ .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e): e is PageEditWire => !!e) }));
614
+ this.revertAll();
615
+ this.experiences = experiences;
616
+ // The definitive answer: a server-applied edit it no longer carries is undone first.
617
+ this.reconcileServer(experiences);
618
+ this.remember(url, experiences, data.ttlSeconds);
619
+ this.applyAll();
620
+ } catch (error) {
621
+ this.logger.debug('Page edits request failed', error);
622
+ } finally {
623
+ clearTimeout(timeout);
624
+ if (generation === this.generation) this.showAll();
625
+ }
626
+ }
627
+
628
+ // ── applying ─────────────────────────────────────────────────────────────
629
+
630
+ private schedule(): void {
631
+ if (this.scheduled || this.destroyed) return;
632
+ this.scheduled = true;
633
+ const run = () => {
634
+ this.scheduled = false;
635
+ this.applyAll();
636
+ };
637
+ if (typeof queueMicrotask === 'function') queueMicrotask(run);
638
+ else void Promise.resolve().then(run);
639
+ }
640
+
641
+ private applyAll(): void {
642
+ if (this.destroyed || typeof document === 'undefined') return;
643
+ // Our own DOM writes would wake the observer; it is paused while we write.
644
+ this.observer?.disconnect();
645
+ try {
646
+ for (const x of this.experiences) {
647
+ if (x.wire.isControl) {
648
+ const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
649
+ if (seen) this.reportControl(x.wire);
650
+ continue;
651
+ }
652
+ let landed = false;
653
+ for (const edit of x.edits) {
654
+ const token = `${x.wire.id}:${edit.id}`;
655
+ const server = this.serverEdits().get(token);
656
+ const byServer = !!server && server.variantId === (x.wire.variantId ?? null) && sameEdit(server.edit, edit);
657
+ for (const el of this.query(edit.selector)) {
658
+ if (this.applied.some((a) => a.el === el && a.editId === edit.id)) {
659
+ landed = true;
660
+ continue;
661
+ }
662
+ // Already in the HTML the server sent: never applied a second time.
663
+ if (byServer && tokensOf(el).includes(token)) {
664
+ landed = true;
665
+ continue;
666
+ }
667
+ const undo = this.applyOne(el, edit);
668
+ if (undo) {
669
+ this.applied.push({ el, editId: edit.id, undo });
670
+ landed = true;
671
+ }
672
+ }
673
+ }
674
+ if (landed) this.reportDisplayed(x.wire);
675
+ }
676
+ } finally {
677
+ if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });
678
+ }
679
+ }
680
+
681
+ private query(selector: string): Element[] {
682
+ try {
683
+ return Array.from(document.querySelectorAll(selector)).filter((el) => !(el as HTMLElement).closest?.('[data-joryio-editor]'));
684
+ } catch {
685
+ return [];
686
+ }
687
+ }
688
+
689
+ /** One edit on one element; returns how to undo it, or null when it does not fit the element. */
690
+ private applyOne(el: Element, edit: PageEditWire): (() => void) | null {
691
+ const h = el as HTMLElement;
692
+ switch (edit.operation) {
693
+ case 'replace_text': {
694
+ const before = Array.from(el.childNodes);
695
+ el.textContent = edit.value ?? '';
696
+ return () => {
697
+ el.textContent = '';
698
+ before.forEach((n) => el.appendChild(n));
699
+ };
700
+ }
701
+ case 'replace_image': {
702
+ if (el.tagName !== 'IMG') return null;
703
+ const src = el.getAttribute('src');
704
+ const srcset = el.getAttribute('srcset');
705
+ el.setAttribute('src', edit.value!);
706
+ // A srcset would win over the new src in every browser.
707
+ el.removeAttribute('srcset');
708
+ return () => {
709
+ if (src === null) el.removeAttribute('src');
710
+ else el.setAttribute('src', src);
711
+ if (srcset !== null) el.setAttribute('srcset', srcset);
712
+ };
713
+ }
714
+ case 'replace_link': {
715
+ if (el.tagName !== 'A') return null;
716
+ const href = el.getAttribute('href');
717
+ el.setAttribute('href', edit.value!);
718
+ return () => (href === null ? el.removeAttribute('href') : el.setAttribute('href', href));
719
+ }
720
+ case 'hide': {
721
+ const display = h.style.getPropertyValue('display');
722
+ const priority = h.style.getPropertyPriority('display');
723
+ h.style.setProperty('display', 'none', 'important');
724
+ return () => (display ? h.style.setProperty('display', display, priority) : h.style.removeProperty('display'));
725
+ }
726
+ case 'insert_placement': {
727
+ const spot = document.createElement('div');
728
+ spot.setAttribute('data-joryio-placement', edit.placementKey!);
729
+ spot.setAttribute('data-joryio-edit', edit.id);
730
+ const where: InsertPosition =
731
+ edit.position === 'before' ? 'beforebegin' : edit.position === 'prepend' ? 'afterbegin' : edit.position === 'append' ? 'beforeend' : 'afterend';
732
+ el.insertAdjacentElement(where, spot);
733
+ return () => spot.remove();
734
+ }
735
+ default:
736
+ return null;
737
+ }
738
+ }
739
+
740
+ private revertAll(): void {
741
+ const applied = this.applied.splice(0).reverse();
742
+ if (!applied.length) return;
743
+ this.observer?.disconnect();
744
+ try {
745
+ for (const a of applied) {
746
+ try {
747
+ a.undo();
748
+ } catch {
749
+ /* the element may be gone */
750
+ }
751
+ }
752
+ } finally {
753
+ if (this.observer && typeof document !== 'undefined' && document.documentElement) {
754
+ this.observer.observe(document.documentElement, { childList: true, subtree: true });
755
+ }
756
+ }
757
+ }
758
+
759
+ // ── anti-flicker ─────────────────────────────────────────────────────────
760
+
761
+ private hide(selectors: string[]): void {
762
+ const safe = selectors.filter(isSafeSelector);
763
+ if (!safe.length || typeof document === 'undefined') return;
764
+ // Never past PAGE_EDIT_ANTI_FLICKER_MS from the start of this page, however late the list arrived.
765
+ const left = PAGE_EDIT_ANTI_FLICKER_MS - (Date.now() - (this.pageStartedAt || Date.now()));
766
+ if (left <= 0) return;
767
+ let style = document.getElementById(STYLE_ID) as HTMLStyleElement | null;
768
+ if (!style) {
769
+ style = document.createElement('style');
770
+ style.id = STYLE_ID;
771
+ (document.head || document.documentElement).appendChild(style);
772
+ }
773
+ // Only these elements, never the body; opacity, so the layout does not move.
774
+ // Elements the server already edited are never held back.
775
+ style.textContent = this.serverEdits().size
776
+ ? `:is(${safe.join(',')}):not([${SERVER_APPLIED_ATTR}]){opacity:0 !important}`
777
+ : `${safe.join(',')}{opacity:0 !important}`;
778
+ if (this.flickerTimer) clearTimeout(this.flickerTimer);
779
+ this.flickerTimer = setTimeout(() => this.showAll(), left);
780
+ }
781
+
782
+ private showAll(): void {
783
+ if (this.flickerTimer) clearTimeout(this.flickerTimer);
784
+ this.flickerTimer = null;
785
+ try {
786
+ document.getElementById(STYLE_ID)?.remove();
787
+ } catch {
788
+ /* ignore */
789
+ }
790
+ }
791
+
792
+ // ── what is remembered (selectors and static edits only, never a personalized value) ──
793
+
794
+ private subjectKey(): string {
795
+ return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
796
+ }
797
+
798
+ private remember(url: string, experiences: Experience[], ttlSeconds?: number): void {
799
+ const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.map((e) => e.selector))))];
800
+ try {
801
+ const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
802
+ delete all[url];
803
+ if (selectors.length) all[url] = selectors.slice(0, 50);
804
+ const keys = Object.keys(all);
805
+ for (const k of keys.slice(0, Math.max(0, keys.length - MAX_REMEMBERED_PAGES))) delete all[k];
806
+ localStorage.setItem(this.stores.selectors, JSON.stringify(all));
807
+ } catch {
808
+ /* storage blocked: no anti-flicker next time, nothing else */
809
+ }
810
+ try {
811
+ const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};
812
+ const pages = stored.subject === this.subjectKey() && stored.pages ? stored.pages : {};
813
+ pages[url] = {
814
+ at: Date.now(),
815
+ ttl: (ttlSeconds && ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS) * 1000,
816
+ experiences: experiences
817
+ .filter((x) => !x.wire.isControl)
818
+ .map((x) => ({ ...x.wire, deliveryToken: null, edits: x.edits.filter((e) => !e.personalized) }))
819
+ .filter((x) => x.edits.length),
820
+ };
821
+ sessionStorage.setItem(this.stores.answers, JSON.stringify({ subject: this.subjectKey(), pages }));
822
+ } catch {
823
+ /* ignore */
824
+ }
825
+ }
826
+
827
+ private rememberedSelectors(url: string): string[] {
828
+ try {
829
+ const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
830
+ return Array.isArray(all[url]) ? all[url].filter((s: unknown) => typeof s === 'string') : [];
831
+ } catch {
832
+ return [];
833
+ }
834
+ }
835
+
836
+ private cachedExperiences(url: string): Experience[] {
837
+ try {
838
+ const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};
839
+ if (stored.subject !== this.subjectKey()) return [];
840
+ const entry = stored.pages?.[url];
841
+ if (!entry || Date.now() - entry.at > entry.ttl) return [];
842
+ // Applied, never reported: the exposure belongs to the answer with a token.
843
+ return (entry.experiences || []).map((wire: PageEditExperienceWire) => ({
844
+ wire: { ...wire, isControl: false, deliveryToken: null },
845
+ edits: (wire.edits || []).map(trustedEdit).filter((e): e is PageEditWire => !!e && !e.personalized),
846
+ }));
847
+ } catch {
848
+ return [];
849
+ }
850
+ }
851
+
852
+ // ── edits the server applied (D450) ──────────────────────────────────────
853
+
854
+ /** The marker, read once it is in the DOM (it sits right after <head>). */
855
+ private serverEdits(): Map<string, ServerEdit> {
856
+ if (this.server) return this.server;
857
+ const found = new Map<string, ServerEdit>();
858
+ if (typeof document === 'undefined') return found;
859
+ // Trusted only where the plugin writes it: a JSON <script> directly in <head>
860
+ // (the plugin inserts it right after <head>, before any page script). An
861
+ // element with that id anywhere else - user content in the body, DOM
862
+ // clobbering - is ignored.
863
+ const el = serverMarkerElement();
864
+ if (!el) {
865
+ // Not (yet) in the DOM: asked again on the next call while the page is still loading.
866
+ if (document.readyState !== 'loading') this.server = found;
867
+ return found;
868
+ }
869
+ try {
870
+ const data = JSON.parse(el.textContent || '{}');
871
+ if (data && data.v === SERVER_MARKER_VERSION && Array.isArray(data.experiences)) {
872
+ for (const x of data.experiences) {
873
+ if (!x || typeof x.id !== 'string' || !Array.isArray(x.edits)) continue;
874
+ for (const raw of x.edits) {
875
+ const edit = trustedEdit(raw);
876
+ if (edit && !edit.personalized) found.set(`${x.id}:${edit.id}`, { experienceId: x.id, variantId: typeof x.variantId === 'string' ? x.variantId : null, edit });
877
+ }
878
+ }
879
+ }
880
+ } catch {
881
+ /* a marker this SDK cannot read: treated as none; the edits it lists stay as the page has them */
882
+ }
883
+ this.server = found;
884
+ return found;
885
+ }
886
+
887
+ /**
888
+ * Keep the server-applied edits the definitive answer still carries for this
889
+ * visitor (same campaign, variant and edit); undo every other one.
890
+ */
891
+ private reconcileServer(experiences: Experience[]): void {
892
+ const server = this.serverEdits();
893
+ if (!server.size || typeof document === 'undefined') return;
894
+ const keep = new Set<string>();
895
+ for (const x of experiences) {
896
+ if (x.wire.isControl) continue;
897
+ for (const e of x.edits) {
898
+ const token = `${x.wire.id}:${e.id}`;
899
+ const s = server.get(token);
900
+ if (s && s.variantId === (x.wire.variantId ?? null) && sameEdit(s.edit, e)) keep.add(token);
901
+ }
902
+ }
903
+ const undo = [...server.keys()].filter((t) => !keep.has(t));
904
+ if (!undo.length) return;
905
+ this.observer?.disconnect();
906
+ try {
907
+ for (const token of undo) {
908
+ this.undoServerEdit(token, server.get(token)!.edit);
909
+ server.delete(token);
910
+ }
911
+ } finally {
912
+ if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });
913
+ }
914
+ }
915
+
916
+ /** Put back what the server changed for one edit, from the undo data it left on each element. */
917
+ private undoServerEdit(token: string, edit: PageEditWire): void {
918
+ for (const el of Array.from(document.querySelectorAll(`[${SERVER_APPLIED_ATTR}]`))) {
919
+ const tokens = tokensOf(el);
920
+ if (!tokens.includes(token)) continue;
921
+ let all: Record<string, any> = {};
922
+ try {
923
+ all = JSON.parse(el.getAttribute(SERVER_ORIG_ATTR) || '{}') || {};
924
+ } catch {
925
+ all = {};
926
+ }
927
+ const orig = all[token] || {};
928
+ // Only an element that still shows exactly what the server applied is put back,
929
+ // and only with values that pass the same checks as an edit.
930
+ try {
931
+ switch (edit.operation) {
932
+ case 'replace_text': {
933
+ const tpl = Array.from(el.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute(SERVER_ORIG_ATTR) === token) as HTMLTemplateElement | undefined;
934
+ if (tpl && tpl.content && el.textContent === edit.value) {
935
+ // Rebuilt node by node through an allowlist - never the template's markup made live.
936
+ const restored = restoreInline(tpl.content);
937
+ el.textContent = '';
938
+ el.appendChild(restored);
939
+ }
940
+ break;
941
+ }
942
+ case 'replace_image':
943
+ if (el.tagName === 'IMG' && el.getAttribute('src') === edit.value) {
944
+ const src = safeRestoredUrl(orig.src);
945
+ const srcset = safeRestoredSrcset(orig.srcset);
946
+ if (src === null) el.removeAttribute('src');
947
+ else el.setAttribute('src', src);
948
+ if (srcset !== null) el.setAttribute('srcset', srcset);
949
+ }
950
+ break;
951
+ case 'replace_link':
952
+ if (el.tagName === 'A' && el.getAttribute('href') === edit.value) {
953
+ const href = safeRestoredUrl(orig.href);
954
+ if (href === null) el.removeAttribute('href');
955
+ else el.setAttribute('href', href);
956
+ }
957
+ break;
958
+ case 'hide': {
959
+ // Never a style string from the marker: the original is put back only when the
960
+ // attribute is exactly it plus the server's one declaration; otherwise that one
961
+ // declaration is removed.
962
+ const current = el.getAttribute('style') || '';
963
+ const before = typeof orig.style === 'string' ? orig.style : null;
964
+ const base = before === null ? '' : before.trim().replace(/;+$/, '');
965
+ if (current === (base ? base + ';' : '') + HIDE_DECLARATION) {
966
+ if (before === null) el.removeAttribute('style');
967
+ else el.setAttribute('style', before);
968
+ } else if ((el as HTMLElement).style?.getPropertyValue('display') === 'none') {
969
+ (el as HTMLElement).style.removeProperty('display');
970
+ }
971
+ break;
972
+ }
973
+ default:
974
+ break;
975
+ }
976
+ } catch {
977
+ /* the element changed since: leave it */
978
+ }
979
+ const left = tokens.filter((t) => t !== token);
980
+ if (left.length) el.setAttribute(SERVER_APPLIED_ATTR, left.join(' '));
981
+ else el.removeAttribute(SERVER_APPLIED_ATTR);
982
+ delete all[token];
983
+ if (Object.keys(all).length) el.setAttribute(SERVER_ORIG_ATTR, JSON.stringify(all));
984
+ else el.removeAttribute(SERVER_ORIG_ATTR);
985
+ }
986
+ if (edit.operation === 'insert_placement') {
987
+ for (const spot of Array.from(document.querySelectorAll(`div[${SERVER_SPOT_ATTR}][data-joryio-placement]`))) {
988
+ if (spot.getAttribute(SERVER_SPOT_ATTR) === token && spot.getAttribute('data-joryio-placement') === edit.placementKey) spot.remove();
989
+ }
990
+ }
991
+ }
992
+
993
+ // ── reporting ────────────────────────────────────────────────────────────
994
+
995
+ private reportDisplayed(x: PageEditExperienceWire): void {
996
+ if (!x.deliveryToken || this.runtime.consent() !== 'granted') return;
997
+ const once = `displayed:${x.deliveryId || x.deliveryToken}`;
998
+ if (this.reported.has(once)) return;
999
+ this.reported.add(once);
1000
+ this.post({
1001
+ campaignId: x.id,
1002
+ ...(x.variantId ? { variantId: x.variantId } : {}),
1003
+ deliveryToken: x.deliveryToken,
1004
+ action: 'displayed',
1005
+ displayedAt: new Date().toISOString(),
1006
+ });
1007
+ }
1008
+
1009
+ private reportControl(x: PageEditExperienceWire): void {
1010
+ if (!x.controlToken || this.runtime.consent() !== 'granted') return;
1011
+ const once = `control:${x.controlToken}`;
1012
+ if (this.reported.has(once)) return;
1013
+ this.reported.add(once);
1014
+ this.post({ action: 'control_viewed', controlToken: x.controlToken, viewedAt: new Date().toISOString() });
1015
+ }
1016
+
1017
+ private post(body: Record<string, any>): void {
1018
+ const userId = this.identity.getUserId();
1019
+ const full = { ...body, ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId(), sessionId: this.session.getSessionId(), deviceType: 'web' };
1020
+ fetch(`${this.apiEndpoint}/v1/in-app/track`, {
1021
+ method: 'POST',
1022
+ headers: {
1023
+ 'Content-Type': 'application/json',
1024
+ 'X-SDK-Key': this.sdkKey,
1025
+ ...sdkIdentityHeaders(),
1026
+ ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : this.identity.getAnonymousId()) || {}),
1027
+ },
1028
+ body: JSON.stringify(full),
1029
+ keepalive: true,
1030
+ })
1031
+ .then((r) => {
1032
+ if (!r.ok) this.runtime.noteStatus?.(r.status, null);
1033
+ })
1034
+ .catch((error) => this.logger.debug('Page edit report failed', error));
1035
+ }
1036
+ }