@joryio/web-sdk 1.4.0-beta.2 → 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.
Files changed (68) hide show
  1. package/CHANGELOG.md +44 -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 +130 -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 +73 -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 +218 -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 +36 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/editor/index.d.ts +4 -0
  33. package/dist/editor/index.d.ts.map +1 -0
  34. package/dist/editor/visual-editor.d.ts +39 -0
  35. package/dist/editor/visual-editor.d.ts.map +1 -0
  36. package/dist/index.d.mts +201 -3
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/joryio-cards-ui.min.js +7 -0
  40. package/dist/joryio-cards-ui.min.js.map +1 -0
  41. package/dist/joryio-editor.min.js +7 -0
  42. package/dist/joryio-editor.min.js.map +1 -0
  43. package/dist/joryio-sw.js +1 -1
  44. package/dist/joryio.cjs.js +7200 -3513
  45. package/dist/joryio.min.js +2 -2
  46. package/dist/joryio.min.js.map +1 -1
  47. package/dist/joryio.mjs +7192 -3514
  48. package/dist/joryio.umd.js +7200 -3513
  49. package/package.json +4 -1
  50. package/src/cards-ui/card-feed-view.ts +249 -0
  51. package/src/cards-ui/index.ts +26 -0
  52. package/src/core/cards-ui-contract.ts +58 -0
  53. package/src/core/cards.ts +843 -0
  54. package/src/core/config.ts +86 -2
  55. package/src/core/editor-gate.ts +158 -0
  56. package/src/core/flags.ts +372 -0
  57. package/src/core/inapp.ts +283 -152
  58. package/src/core/links.ts +104 -0
  59. package/src/core/network.ts +3 -0
  60. package/src/core/page-context.ts +460 -0
  61. package/src/core/page-edits.ts +1036 -0
  62. package/src/core/placements.ts +1431 -0
  63. package/src/core/sdk-host-files.ts +93 -0
  64. package/src/core/sdk.ts +378 -1
  65. package/src/editor/index.ts +27 -0
  66. package/src/editor/visual-editor.ts +301 -0
  67. package/src/index.ts +33 -0
  68. package/src/snippet/loader.js +25 -1
@@ -0,0 +1,843 @@
1
+ /**
2
+ * Content cards (docs/PLACEMENTS_PLAN.md section 11, BACKLOG D444 Phase 3): a
3
+ * persistent feed per person - a message center inside the site. Cards come
4
+ * from card campaigns and the journey step "Add card".
5
+ *
6
+ * Draw the feed with `mountCardFeed(element)`, or read it with `getCards()`
7
+ * and draw it yourself, reporting with `markCardViewed` / `markCardRead` /
8
+ * `markCardClicked` / `dismissCard`. The default feed's drawing code is a
9
+ * separate file, `joryio-cards-ui.min.js`, loaded the first time a page mounts
10
+ * a feed (src/core/cards-ui-contract.ts); everything else here is in the core.
11
+ *
12
+ * The rules, the same on every Joryio SDK (names and values pinned by the
13
+ * backend's SDK parity specs):
14
+ *
15
+ * - `POST /v1/in-app/cards` with the visitor's ids, `limit`, `cursor`, `etag`
16
+ * (first page only), `trackingConsent` and the `cards` capability.
17
+ * - The last feed is served from the cache (memory + sessionStorage, scoped
18
+ * to the visitor) for its `ttlSeconds` (CARD_FEED_TTL_SECONDS); at most one
19
+ * network refresh per CARD_MIN_REFRESH_SECONDS - a forced refresh inside
20
+ * that window is deferred to its end and coalesced.
21
+ * - `notModified: true`, `success: false`, HTTP 429 or no answer keep the cache.
22
+ * - An identity or consent change bumps a generation: an answer to a request
23
+ * made before it is discarded.
24
+ * - A report (`POST /v1/in-app/track` `{ deliveryToken, action, sessionId }`)
25
+ * is applied to the cache at once and listeners are told; each action at
26
+ * most once per card; read / clicked / dismissed first count the card as
27
+ * viewed; clicked implies read.
28
+ * - `stateScope: "device"` (an anonymous visitor): read / dismissed card ids
29
+ * are kept in localStorage, tied to the anonymous id, and applied to every
30
+ * feed; cleared on identify / reset / wipeData.
31
+ * - Without tracking consent nothing is requested and nothing reported (an
32
+ * inbox is personal: the server answers an unconsented visitor an empty feed).
33
+ * - Web has no silent push: the feed refreshes on the TTL, `refreshCards()`,
34
+ * identity and consent changes.
35
+ */
36
+
37
+ import { Logger } from '../utils/logger';
38
+ import { bucketHash } from '../utils/bucket-hash';
39
+ import { sdkIdentityHeaders } from './config';
40
+ import { IdentityManager } from './identity';
41
+ import { SessionManager } from './session';
42
+ import { InAppAuthProvider } from './inapp';
43
+ import type { LinkRouter } from './links';
44
+ import { PlacementConsent, trackViewable } from './placements';
45
+ import { CARDS_UI_API_VERSION, CARDS_UI_BUNDLE_FILE, CARDS_UI_GLOBAL, CardFeedHost, CardFeedView, CardsUiBundleApi } from './cards-ui-contract';
46
+ import { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';
47
+
48
+ /** The feed goes to the network at most once per this many seconds; extra calls coalesce. Same name and value on every Joryio SDK. */
49
+ export const CARD_MIN_REFRESH_SECONDS = 30;
50
+ /** How long the feed is served from the cache before it is asked for again (the answer's `ttlSeconds` wins). Same on every Joryio SDK. */
51
+ export const CARD_FEED_TTL_SECONDS = 300;
52
+ /** The capability a card-aware SDK declares. */
53
+ export const CARD_SDK_CAPABILITY = 'cards';
54
+ /** What the SDK reports about a card: the `action` of `POST /v1/in-app/track`. Wire values. */
55
+ export const CARD_ACTIONS = {
56
+ VIEWED: 'viewed',
57
+ READ: 'read',
58
+ CLICKED: 'clicked',
59
+ DISMISSED: 'dismissed',
60
+ } as const;
61
+ export type CardAction = (typeof CARD_ACTIONS)[keyof typeof CARD_ACTIONS];
62
+
63
+ /** `server`: read / dismissed are kept per person on the server. `device`: an anonymous visitor - this browser keeps them. */
64
+ export type CardStateScope = 'server' | 'device';
65
+
66
+ /** Cards per request (the server's default page). */
67
+ const PAGE_SIZE = 20;
68
+ /** Read / dismissed ids an anonymous browser keeps (oldest dropped first). */
69
+ const DEVICE_STATE_MAX = 500;
70
+ /** The pre-scoping, origin-wide names - never read, removed on start. */
71
+ const LEGACY_FEED_STORAGE_NAME = 'joryio_cards_v1';
72
+ const LEGACY_DEVICE_STORAGE_NAME = 'joryio_cards_device_v1';
73
+ /**
74
+ * Per workspace, like the flags and placements caches (flagsStorageKey,
75
+ * placementsStorageKey): two workspaces on one site that know a visitor by the
76
+ * same ids must never read each other's feed or read/dismissed state. Carries a
77
+ * hash of the SDK key, never the key itself.
78
+ */
79
+ export const cardsFeedStorageKey = (sdkKey: string): string => `joryio_cards_v1_${bucketHash(sdkKey).toString(36)}`;
80
+ export const cardsDeviceStorageKey = (sdkKey: string): string => `joryio_cards_device_v1_${bucketHash(sdkKey).toString(36)}`;
81
+
82
+ /** One card of the person's feed. */
83
+ export interface Card {
84
+ /** Stable id of this card for this person. */
85
+ id: string;
86
+ /** Campaign id, or `journey:<canvasId>:<nodeId>` for a journey card. */
87
+ campaignId: string;
88
+ variantId: string | null;
89
+ title: string | null;
90
+ body: string | null;
91
+ imageUrl: string | null;
92
+ /** Button label; null = no button (the whole card opens `url` when set). */
93
+ buttonText: string | null;
94
+ /** An http(s) URL or the site's own deep link; null = nothing to open. */
95
+ url: string | null;
96
+ pinned: boolean;
97
+ /** ISO 8601. */
98
+ createdAt: string;
99
+ /** ISO 8601, or null. */
100
+ expiresAt: string | null;
101
+ read: boolean;
102
+ clicked: boolean;
103
+ }
104
+
105
+ /** The person's feed (or one page of it). */
106
+ export interface CardFeed {
107
+ /** Pinned first, then newest first. */
108
+ cards: Card[];
109
+ /** Unread cards across the whole feed, not this page: the badge. */
110
+ unreadCount: number;
111
+ /** Pass to `getCards({ cursor })` for the next page; null on the last one. */
112
+ nextCursor: string | null;
113
+ stateScope: CardStateScope;
114
+ }
115
+
116
+ export interface GetCardsOptions {
117
+ /** The `nextCursor` of the feed: load the page after it (added to the cached feed). */
118
+ cursor?: string | null;
119
+ }
120
+
121
+ export type CardsUpdatedCallback = (feed: CardFeed) => void;
122
+
123
+ export interface MountCardFeedOptions {
124
+ /** Shown when the feed is empty. Default "No messages yet". */
125
+ emptyText?: string;
126
+ /** The marker on a pinned card. Default "Pinned". */
127
+ pinnedLabel?: string;
128
+ /** The accessible label of the dismiss control. Default "Dismiss". */
129
+ dismissLabel?: string;
130
+ /** The accessible label of the unread dot. Default "Unread". */
131
+ unreadLabel?: string;
132
+ /**
133
+ * A card's url is an app deep link (`myapp://...`): route it in your app
134
+ * (the click is already reported). Without this only an http(s) link is
135
+ * opened; the SDK never navigates to any other scheme. A handler set with
136
+ * `setLinkHandler` sees every link first; this one is called when it
137
+ * returns false.
138
+ */
139
+ onDeepLink?: (url: string, card: Card) => void;
140
+ /** Called after each draw with the feed drawn. */
141
+ onRender?: (feed: CardFeed, element: HTMLElement) => void;
142
+ }
143
+
144
+ export interface CardFeedHandle {
145
+ element: HTMLElement;
146
+ /** Stop filling the element and remove what the SDK drew. */
147
+ remove(): void;
148
+ }
149
+
150
+ /** What the card manager needs from the SDK. */
151
+ export interface CardRuntime {
152
+ /** The consent now, or null when nothing may be sent at all. Only `granted` requests and reports anything. */
153
+ consent: () => PlacementConsent | null;
154
+ requestTimeoutMs?: number;
155
+ noteStatus?: (status: number, data: any) => void;
156
+ /** Where `joryio-cards-ui.min.js` comes from (init `cardsUiScriptUrl`); default the SDK host. */
157
+ cardsUiScriptUrl?: string;
158
+ /** Tests: how a script is loaded. Default a script tag. */
159
+ loadScript?: (src: string) => Promise<void>;
160
+ }
161
+
162
+ /** A card as the server sent it (with its delivery token - never handed out). */
163
+ interface WireCard extends Card {
164
+ deliveryToken: string;
165
+ }
166
+
167
+ interface FeedMount {
168
+ element: HTMLElement;
169
+ options: MountCardFeedOptions;
170
+ /** The renderer's view; null until joryio-cards-ui.min.js has loaded (or for good when it could not). */
171
+ view: CardFeedView | null;
172
+ }
173
+
174
+ /** The renderer on the page, if it is one the core accepts (the contract version it was built for). */
175
+ function pageCardsUi(): CardsUiBundleApi | null {
176
+ const api = typeof window !== 'undefined' ? (window as any)[CARDS_UI_GLOBAL] : null;
177
+ return api && api.version === CARDS_UI_API_VERSION && typeof api.mount === 'function' ? api : null;
178
+ }
179
+
180
+ const nowMs = () => Date.now();
181
+
182
+ const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);
183
+
184
+ function parseCard(o: any): WireCard | null {
185
+ if (!o || typeof o !== 'object') return null;
186
+ const id = str(o.id);
187
+ const token = str(o.deliveryToken);
188
+ if (!id || !token) return null;
189
+ return {
190
+ id,
191
+ campaignId: str(o.campaignId) || '',
192
+ variantId: str(o.variantId),
193
+ title: str(o.title),
194
+ body: str(o.body),
195
+ imageUrl: str(o.imageUrl),
196
+ buttonText: str(o.buttonText),
197
+ url: str(o.url),
198
+ pinned: o.pinned === true,
199
+ createdAt: str(o.createdAt) || '',
200
+ expiresAt: str(o.expiresAt),
201
+ read: o.read === true,
202
+ clicked: o.clicked === true,
203
+ deliveryToken: token,
204
+ };
205
+ }
206
+
207
+ function parseCards(list: unknown): WireCard[] {
208
+ return Array.isArray(list) ? (list.map(parseCard).filter(Boolean) as WireCard[]) : [];
209
+ }
210
+
211
+ function publicCard(c: WireCard, read: boolean, clicked: boolean): Card {
212
+ return {
213
+ id: c.id,
214
+ campaignId: c.campaignId,
215
+ variantId: c.variantId,
216
+ title: c.title,
217
+ body: c.body,
218
+ imageUrl: c.imageUrl,
219
+ buttonText: c.buttonText,
220
+ url: c.url,
221
+ pinned: c.pinned,
222
+ createdAt: c.createdAt,
223
+ expiresAt: c.expiresAt,
224
+ read,
225
+ clicked,
226
+ };
227
+ }
228
+
229
+ export class CardManager {
230
+ /** The SDK's link router (`setLinkHandler`); set by the SDK after construction. */
231
+ links: LinkRouter | null = null;
232
+ // The feed as the server sent it (first page plus any pages loaded after it).
233
+ private wireCards: WireCard[] = [];
234
+ private serverUnread = 0;
235
+ private nextCursor: string | null = null;
236
+ private stateScope: CardStateScope = 'server';
237
+ private etag: string | null = null;
238
+ private ttlSeconds = CARD_FEED_TTL_SECONDS;
239
+ private fetchedAt: number | null = null;
240
+ private lastNetworkAt: number | null = null;
241
+ private inflight: Promise<void> | null = null;
242
+ private deferredTimer: ReturnType<typeof setTimeout> | null = null;
243
+ private listeners = new Set<CardsUpdatedCallback>();
244
+ private mounts = new Set<FeedMount>();
245
+ /** `action:cardId` already reported (each action at most once per card). */
246
+ private reported = new Set<string>();
247
+ /** What this browser did since the last identity change, keyed by card id + createdAt (a replaced card is a new one). */
248
+ private overlayRead = new Set<string>();
249
+ private overlayClicked = new Set<string>();
250
+ private overlayDismissed = new Set<string>();
251
+ /** An anonymous visitor's state, by card id, in localStorage. Cleared on identify / reset. */
252
+ private deviceRead = new Set<string>();
253
+ private deviceDismissed = new Set<string>();
254
+ /** Bumped when WHO the feed is for changes; older answers are discarded. */
255
+ private generation = 0;
256
+ private destroyed = false;
257
+ /** The card feed renderer once loaded (kept: a later change to the global is not read again). */
258
+ private cardsUi: CardsUiBundleApi | null = null;
259
+ private cardsUiLoading: Promise<CardsUiBundleApi | null> | null = null;
260
+
261
+ constructor(
262
+ private apiEndpoint: string,
263
+ private sdkKey: string,
264
+ private identity: IdentityManager,
265
+ private session: SessionManager,
266
+ private logger: Logger,
267
+ private runtime: CardRuntime,
268
+ private auth?: InAppAuthProvider,
269
+ ) {
270
+ this.removeLegacyStorage();
271
+ this.loadFeedCache();
272
+ this.loadDeviceState();
273
+ }
274
+
275
+ // ── public API ──────────────────────────────────────────────────────────
276
+
277
+ /** The feed (from the cache while fresh), or with `cursor` the page after it, added to the feed. */
278
+ async getCards(options: GetCardsOptions = {}): Promise<CardFeed> {
279
+ const cursor = options && typeof options.cursor === 'string' && options.cursor ? options.cursor : null;
280
+ if (cursor) return this.loadPage(cursor);
281
+ if (!this.fresh()) await this.fetch(false);
282
+ return this.view();
283
+ }
284
+
285
+ /** The unread count of the cached feed. Never goes to the network. */
286
+ getUnreadCardCount(): number {
287
+ return this.view().unreadCount;
288
+ }
289
+
290
+ /** Ask the server again (at most once per CARD_MIN_REFRESH_SECONDS; inside it, deferred to its end). */
291
+ async refreshCards(): Promise<void> {
292
+ await this.fetch(true);
293
+ }
294
+
295
+ /** Called with the whole feed whenever it changes. Returns an unsubscribe. */
296
+ onCardsUpdated(callback: CardsUpdatedCallback): () => void {
297
+ if (typeof callback !== 'function') return () => undefined;
298
+ this.listeners.add(callback);
299
+ return () => {
300
+ this.listeners.delete(callback);
301
+ };
302
+ }
303
+
304
+ markCardViewed(card: Card | string): void {
305
+ this.report(card, CARD_ACTIONS.VIEWED);
306
+ }
307
+
308
+ markCardRead(card: Card | string): void {
309
+ this.report(card, CARD_ACTIONS.READ);
310
+ }
311
+
312
+ markCardClicked(card: Card | string): void {
313
+ this.report(card, CARD_ACTIONS.CLICKED);
314
+ }
315
+
316
+ dismissCard(card: Card | string): void {
317
+ this.report(card, CARD_ACTIONS.DISMISSED);
318
+ }
319
+
320
+ /**
321
+ * Draw the feed into `element` and keep it up to date. Returns a handle at
322
+ * once; the feed is drawn as soon as the renderer file is there (at once
323
+ * when it already is). If it cannot be loaded (a Content-Security-Policy
324
+ * without the SDK host, a network failure) a warning is logged, the element
325
+ * gets `data-joryio-card-feed-state="unavailable"` and stays as the site
326
+ * left it - nothing throws, and the data API keeps working.
327
+ */
328
+ mountCardFeed(element: HTMLElement, options: MountCardFeedOptions = {}): CardFeedHandle | null {
329
+ if (!element || typeof (element as any).appendChild !== 'function') {
330
+ this.logger.warn('mountCardFeed: an element is required');
331
+ return null;
332
+ }
333
+ if (typeof document === 'undefined') return null;
334
+ for (const existing of this.mounts) if (existing.element === element) this.unmount(existing);
335
+ const mount: FeedMount = { element, options: options || {}, view: null };
336
+ this.mounts.add(mount);
337
+ if (!this.fresh()) this.fetch(false).catch(() => undefined);
338
+ // Already on the page (loaded for an earlier feed, or imported by a bundler): draw now.
339
+ this.cardsUi = this.cardsUi || pageCardsUi();
340
+ if (this.cardsUi) this.attach(mount, this.cardsUi);
341
+ else
342
+ void this.loadCardsUi().then((api) => {
343
+ if (!this.mounts.has(mount)) return; // removed (or destroyed) before the file came
344
+ if (api) this.attach(mount, api);
345
+ else element.setAttribute('data-joryio-card-feed-state', 'unavailable');
346
+ });
347
+ return { element, remove: () => this.unmount(mount) };
348
+ }
349
+
350
+ /**
351
+ * The person or the consent changed: forget the feed (and, for a new
352
+ * person, the anonymous visitor's device state), tell the listeners, and
353
+ * ask again when the site shows or listens to the feed.
354
+ */
355
+ invalidate(clearDeviceState: boolean): void {
356
+ this.generation++;
357
+ this.wireCards = [];
358
+ this.serverUnread = 0;
359
+ this.nextCursor = null;
360
+ this.stateScope = 'server';
361
+ this.etag = null;
362
+ this.ttlSeconds = CARD_FEED_TTL_SECONDS;
363
+ this.fetchedAt = null;
364
+ this.lastNetworkAt = null;
365
+ this.inflight = null;
366
+ if (this.deferredTimer) clearTimeout(this.deferredTimer);
367
+ this.deferredTimer = null;
368
+ this.reported.clear();
369
+ this.overlayRead.clear();
370
+ this.overlayClicked.clear();
371
+ this.overlayDismissed.clear();
372
+ if (clearDeviceState) {
373
+ this.deviceRead.clear();
374
+ this.deviceDismissed.clear();
375
+ try {
376
+ if (typeof localStorage !== 'undefined') localStorage.removeItem(cardsDeviceStorageKey(this.sdkKey));
377
+ } catch {
378
+ /* storage blocked */
379
+ }
380
+ }
381
+ try {
382
+ if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem(cardsFeedStorageKey(this.sdkKey));
383
+ } catch {
384
+ /* storage blocked */
385
+ }
386
+ const watched = this.listeners.size > 0 || this.mounts.size > 0;
387
+ // The previous person's cards go NOW: they must not stay in front of the next person.
388
+ this.notify();
389
+ if (watched && !this.destroyed) this.fetch(true).catch(() => undefined);
390
+ }
391
+
392
+ destroy(): void {
393
+ this.destroyed = true;
394
+ for (const mount of Array.from(this.mounts)) this.unmount(mount);
395
+ if (this.deferredTimer) clearTimeout(this.deferredTimer);
396
+ this.deferredTimer = null;
397
+ this.listeners.clear();
398
+ }
399
+
400
+ // ── fetching ────────────────────────────────────────────────────────────
401
+
402
+ private fresh(): boolean {
403
+ return this.fetchedAt !== null && nowMs() - this.fetchedAt < this.ttlSeconds * 1000;
404
+ }
405
+
406
+ /**
407
+ * Ask for the first page. A request already running is joined; inside
408
+ * CARD_MIN_REFRESH_SECONDS of the last one nothing goes out - a forced
409
+ * refresh is deferred to the end of that window, anything else gets the cache.
410
+ */
411
+ private fetch(force: boolean): Promise<void> {
412
+ if (this.destroyed) return Promise.resolve();
413
+ if (this.inflight) {
414
+ if (force) this.defer();
415
+ return this.inflight;
416
+ }
417
+ if (this.lastNetworkAt !== null && nowMs() - this.lastNetworkAt < CARD_MIN_REFRESH_SECONDS * 1000) {
418
+ if (force) this.defer();
419
+ return Promise.resolve();
420
+ }
421
+ const run = this.requestFirstPage().finally(() => {
422
+ if (this.inflight === run) this.inflight = null;
423
+ });
424
+ this.inflight = run;
425
+ return run;
426
+ }
427
+
428
+ private defer(): void {
429
+ if (this.deferredTimer) return;
430
+ const wait = Math.max(0, (this.lastNetworkAt ?? 0) + CARD_MIN_REFRESH_SECONDS * 1000 - nowMs());
431
+ this.deferredTimer = setTimeout(() => {
432
+ this.deferredTimer = null;
433
+ if (!this.destroyed) this.fetch(false).catch(() => undefined);
434
+ }, wait + 10);
435
+ }
436
+
437
+ /** One POST; null when there is nothing to use (no consent, failure, 429, success false, a stale answer). */
438
+ private async post(cursor: string | null): Promise<{ data: any; generation: number } | null> {
439
+ const consent = this.runtime.consent();
440
+ // An inbox is personal: without consent the server would answer an empty
441
+ // feed, so nothing is asked (and nobody named).
442
+ if (consent !== 'granted' || this.destroyed) return null;
443
+ const generation = this.generation;
444
+ if (!cursor) this.lastNetworkAt = nowMs();
445
+ const userId = this.identity.getUserId();
446
+ const anonymousId = this.identity.getAnonymousId();
447
+ const body: Record<string, any> = {
448
+ ...(userId ? { userId } : {}),
449
+ anonymousId,
450
+ sessionId: this.session.getSessionId(),
451
+ deviceType: 'web',
452
+ locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
453
+ capabilities: [CARD_SDK_CAPABILITY, 'content.native'],
454
+ trackingConsent: consent,
455
+ limit: PAGE_SIZE,
456
+ ...(cursor ? { cursor } : {}),
457
+ ...(!cursor && this.etag ? { etag: this.etag } : {}),
458
+ };
459
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
460
+ const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
461
+ try {
462
+ const response = await fetch(`${this.apiEndpoint}/v1/in-app/cards`, {
463
+ method: 'POST',
464
+ headers: {
465
+ 'Content-Type': 'application/json',
466
+ 'X-SDK-Key': this.sdkKey,
467
+ ...sdkIdentityHeaders(),
468
+ ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {}),
469
+ },
470
+ body: JSON.stringify(body),
471
+ ...(controller ? { signal: controller.signal } : {}),
472
+ });
473
+ if (!response.ok) {
474
+ // 429 (the per-device limit) and every other failure: keep the cache.
475
+ this.runtime.noteStatus?.(response.status, null);
476
+ this.logger.debug(`Card feed request answered ${response.status}; keeping the cached feed`);
477
+ return null;
478
+ }
479
+ const data = await response.json();
480
+ if (generation !== this.generation) {
481
+ this.logger.debug('Discarding a card feed answer that predates an identity or consent change');
482
+ return null;
483
+ }
484
+ if (!data || typeof data !== 'object' || data.success === false) {
485
+ this.logger.debug('Card feed answered success: false; keeping the cached feed');
486
+ return null;
487
+ }
488
+ return { data, generation };
489
+ } catch (error) {
490
+ const timedOut = (error as any)?.name === 'AbortError';
491
+ this.logger.debug(timedOut ? 'Card feed request timed out' : 'Card feed request failed', error);
492
+ return null;
493
+ } finally {
494
+ clearTimeout(timeout);
495
+ }
496
+ }
497
+
498
+ private async requestFirstPage(): Promise<void> {
499
+ const answer = await this.post(null);
500
+ if (!answer || answer.generation !== this.generation) return;
501
+ const { data } = answer;
502
+ const t = nowMs();
503
+ this.ttlSeconds = typeof data.ttlSeconds === 'number' && data.ttlSeconds > 0 ? data.ttlSeconds : CARD_FEED_TTL_SECONDS;
504
+ let changed = false;
505
+ if (data.notModified === true && this.fetchedAt !== null) {
506
+ // The feed we hold is still the feed: keep the cards.
507
+ this.fetchedAt = t;
508
+ } else if (data.notModified === true) {
509
+ // notModified for an etag we no longer hold the cards of: ask again without it.
510
+ this.etag = null;
511
+ this.lastNetworkAt = null;
512
+ return this.requestFirstPage();
513
+ } else {
514
+ const before = JSON.stringify(this.view());
515
+ this.wireCards = parseCards(data.cards);
516
+ this.serverUnread = typeof data.unreadCount === 'number' ? Math.max(0, data.unreadCount) : 0;
517
+ this.nextCursor = str(data.nextCursor);
518
+ this.stateScope = data.stateScope === 'device' ? 'device' : 'server';
519
+ this.etag = str(data.etag);
520
+ this.fetchedAt = t;
521
+ changed = before !== JSON.stringify(this.view());
522
+ }
523
+ this.persistFeed();
524
+ if (changed) this.notify();
525
+ }
526
+
527
+ /** The page after `cursor`: added to the cached feed; returns that page (with this browser's state applied). */
528
+ private async loadPage(cursor: string): Promise<CardFeed> {
529
+ const answer = await this.post(cursor);
530
+ if (!answer || answer.generation !== this.generation) return { ...this.view(), cards: [] };
531
+ const { data } = answer;
532
+ const cards = parseCards(data.cards);
533
+ const known = new Set(this.wireCards.map((c) => c.id));
534
+ this.wireCards = this.wireCards.concat(cards.filter((c) => !known.has(c.id)));
535
+ this.nextCursor = str(data.nextCursor);
536
+ if (typeof data.unreadCount === 'number') this.serverUnread = Math.max(0, data.unreadCount);
537
+ this.persistFeed();
538
+ const full = this.view();
539
+ const ids = new Set(cards.map((c) => c.id));
540
+ this.notify();
541
+ return { ...full, cards: full.cards.filter((c) => ids.has(c.id)) };
542
+ }
543
+
544
+ private notify(): void {
545
+ for (const mount of this.mounts) this.render(mount);
546
+ if (!this.listeners.size) return;
547
+ const feed = this.view();
548
+ for (const listener of Array.from(this.listeners)) {
549
+ try {
550
+ listener(feed);
551
+ } catch (error) {
552
+ this.logger.error('The onCardsUpdated callback threw; ignored:', error);
553
+ }
554
+ }
555
+ }
556
+
557
+ // ── the feed with this browser's state ──────────────────────────────────
558
+
559
+ private key(c: WireCard): string {
560
+ return `${c.id}\u0000${c.createdAt}`;
561
+ }
562
+
563
+ /**
564
+ * The cached feed with what this browser did applied: dismissed and
565
+ * expired cards removed, read / clicked set, and the unread count lowered
566
+ * by each card the server counted as unread that is no longer.
567
+ */
568
+ private view(): CardFeed {
569
+ const t = nowMs();
570
+ let unread = this.serverUnread;
571
+ const out: Card[] = [];
572
+ for (const c of this.wireCards) {
573
+ const key = this.key(c);
574
+ const dismissed = this.overlayDismissed.has(key) || this.deviceDismissed.has(c.id);
575
+ const expiresAt = c.expiresAt ? Date.parse(c.expiresAt) : NaN;
576
+ const expired = Number.isFinite(expiresAt) && expiresAt <= t;
577
+ const clicked = c.clicked || this.overlayClicked.has(key);
578
+ const read = c.read || clicked || this.overlayRead.has(key) || this.deviceRead.has(c.id);
579
+ if (!c.read && (read || dismissed || expired)) unread--;
580
+ if (dismissed || expired) continue;
581
+ out.push(publicCard(c, read, clicked));
582
+ }
583
+ return { cards: out, unreadCount: Math.max(0, unread), nextCursor: this.nextCursor, stateScope: this.stateScope };
584
+ }
585
+
586
+ // ── reporting ───────────────────────────────────────────────────────────
587
+
588
+ /**
589
+ * A report: applied to the cache at once (listeners told), sent to
590
+ * /v1/in-app/track only with consent. Each action at most once per card;
591
+ * read / clicked / dismissed first count the card as viewed; `read` on a
592
+ * card already read sends nothing.
593
+ */
594
+ private report(cardOrId: Card | string, action: CardAction): void {
595
+ const id = typeof cardOrId === 'string' ? cardOrId : cardOrId?.id;
596
+ const createdAt = typeof cardOrId === 'string' ? null : cardOrId?.createdAt;
597
+ // A card of someone who is no longer here (identify / reset since), a
598
+ // replaced card, or an unknown id: nothing.
599
+ const card = this.wireCards.find((c) => c.id === id && (createdAt == null || c.createdAt === createdAt));
600
+ if (!card) {
601
+ this.logger.debug(`Card report ignored: ${String(id)} is not in the current feed`);
602
+ return;
603
+ }
604
+ const key = this.key(card);
605
+ const alreadyRead =
606
+ card.read || card.clicked || this.overlayRead.has(key) || this.overlayClicked.has(key) || this.deviceRead.has(card.id);
607
+ if (action === CARD_ACTIONS.READ && alreadyRead) {
608
+ this.reported.add(`${CARD_ACTIONS.READ}:${card.id}`);
609
+ return;
610
+ }
611
+ const once = `${action}:${card.id}`;
612
+ if (this.reported.has(once)) return;
613
+ this.reported.add(once);
614
+ const toSend: CardAction[] = [];
615
+ if (action !== CARD_ACTIONS.VIEWED && !this.reported.has(`${CARD_ACTIONS.VIEWED}:${card.id}`)) {
616
+ this.reported.add(`${CARD_ACTIONS.VIEWED}:${card.id}`);
617
+ toSend.push(CARD_ACTIONS.VIEWED);
618
+ }
619
+ toSend.push(action);
620
+ const device = this.stateScope === 'device';
621
+ if (action === CARD_ACTIONS.READ || action === CARD_ACTIONS.CLICKED) {
622
+ this.overlayRead.add(key);
623
+ if (device) this.deviceRead.add(card.id);
624
+ }
625
+ if (action === CARD_ACTIONS.CLICKED) {
626
+ this.overlayClicked.add(key);
627
+ this.reported.add(`${CARD_ACTIONS.READ}:${card.id}`);
628
+ }
629
+ if (action === CARD_ACTIONS.DISMISSED) {
630
+ this.overlayDismissed.add(key);
631
+ if (device) this.deviceDismissed.add(card.id);
632
+ }
633
+ if (device && action !== CARD_ACTIONS.VIEWED) this.persistDeviceState();
634
+ if (action !== CARD_ACTIONS.VIEWED) this.notify();
635
+ if (this.runtime.consent() !== 'granted') return;
636
+ const sessionId = this.session.getSessionId();
637
+ for (const a of toSend) this.send({ deliveryToken: card.deliveryToken, action: a, sessionId });
638
+ }
639
+
640
+ private send(body: { deliveryToken: string; action: CardAction; sessionId: string }): void {
641
+ const userId = this.identity.getUserId();
642
+ fetch(`${this.apiEndpoint}/v1/in-app/track`, {
643
+ method: 'POST',
644
+ headers: {
645
+ 'Content-Type': 'application/json',
646
+ 'X-SDK-Key': this.sdkKey,
647
+ ...sdkIdentityHeaders(),
648
+ ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : this.identity.getAnonymousId()) || {}),
649
+ },
650
+ body: JSON.stringify(body),
651
+ keepalive: true,
652
+ })
653
+ .then((response) => {
654
+ if (!response.ok) this.runtime.noteStatus?.(response.status, null);
655
+ })
656
+ .catch((error) => this.logger.debug('Card report failed', error));
657
+ }
658
+
659
+ // ── drawing ─────────────────────────────────────────────────────────────
660
+
661
+ /**
662
+ * The renderer file, once per page: the global when it is already there
663
+ * (loaded before, or imported by a bundler), else a script tag from the SDK
664
+ * host (exact version, then the major channel) or `cardsUiScriptUrl`. A
665
+ * failure is warned once per attempt and not cached, so a later mount tries again.
666
+ */
667
+ private loadCardsUi(): Promise<CardsUiBundleApi | null> {
668
+ if (this.cardsUiLoading) return this.cardsUiLoading;
669
+ const run = (async () => {
670
+ let api = pageCardsUi();
671
+ const load = this.runtime.loadScript ?? ((src: string) => loadSdkScript(src, 'data-joryio-cards-ui'));
672
+ for (const src of api ? [] : sdkHostFileUrls(CARDS_UI_BUNDLE_FILE, this.runtime.cardsUiScriptUrl)) {
673
+ try {
674
+ await load(src);
675
+ api = pageCardsUi();
676
+ if (api) break;
677
+ } catch (error) {
678
+ this.logger.debug('Joryio card feed file failed to load', error);
679
+ }
680
+ }
681
+ if (!api) {
682
+ // Short on purpose: every byte of the core is downloaded by every visitor.
683
+ this.logger.warn(`mountCardFeed: ${CARDS_UI_BUNDLE_FILE} could not be loaded (Content-Security-Policy script-src?)`);
684
+ }
685
+ this.cardsUi = api;
686
+ return api;
687
+ })().catch(() => null);
688
+ this.cardsUiLoading = run;
689
+ void run.then((api) => {
690
+ if (!api) this.cardsUiLoading = null;
691
+ });
692
+ return run;
693
+ }
694
+
695
+ private attach(mount: FeedMount, api: CardsUiBundleApi): void {
696
+ try {
697
+ mount.view = api.mount(mount.element, mount.options, this.feedHost(mount));
698
+ mount.view.render();
699
+ } catch (error) {
700
+ this.logger.error('The card feed could not be drawn:', error);
701
+ }
702
+ }
703
+
704
+ private feedHost(mount: FeedMount): CardFeedHost {
705
+ return {
706
+ view: () => this.view(),
707
+ generation: () => this.generation,
708
+ markCardViewed: (card) => this.markCardViewed(card),
709
+ markCardRead: (card) => this.markCardRead(card),
710
+ markCardClicked: (card) => this.markCardClicked(card),
711
+ dismissCard: (card) => this.dismissCard(card),
712
+ routeLink: (url, context, fallback) => {
713
+ if (!this.mounts.has(mount)) return;
714
+ if (this.links) this.links.route(url, 'card', context, fallback);
715
+ else fallback();
716
+ },
717
+ loadMore: async () => {
718
+ const cursor = this.nextCursor;
719
+ if (!cursor || !this.mounts.has(mount) || !this.wireCards.length) return;
720
+ await this.loadPage(cursor);
721
+ },
722
+ trackViewable,
723
+ logger: this.logger,
724
+ };
725
+ }
726
+
727
+ private unmount(mount: FeedMount): void {
728
+ this.mounts.delete(mount);
729
+ const view = mount.view;
730
+ mount.view = null;
731
+ try {
732
+ view?.remove();
733
+ } catch (error) {
734
+ this.logger.debug('Card feed remove failed', error);
735
+ }
736
+ }
737
+
738
+ private render(mount: FeedMount): void {
739
+ try {
740
+ mount.view?.render();
741
+ } catch (error) {
742
+ this.logger.error('The card feed could not be drawn:', error);
743
+ }
744
+ }
745
+
746
+ // ── storage ─────────────────────────────────────────────────────────────
747
+
748
+ private subjectKey(): string {
749
+ return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
750
+ }
751
+
752
+ /** The unscoped names any workspace on this origin could read: never read, removed on start. */
753
+ private removeLegacyStorage(): void {
754
+ try {
755
+ if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem?.(LEGACY_FEED_STORAGE_NAME);
756
+ } catch {
757
+ /* storage blocked */
758
+ }
759
+ try {
760
+ if (typeof localStorage !== 'undefined') localStorage.removeItem?.(LEGACY_DEVICE_STORAGE_NAME);
761
+ } catch {
762
+ /* storage blocked */
763
+ }
764
+ }
765
+
766
+ private persistFeed(): void {
767
+ try {
768
+ if (typeof sessionStorage === 'undefined') return;
769
+ sessionStorage.setItem(
770
+ cardsFeedStorageKey(this.sdkKey),
771
+ JSON.stringify({
772
+ subject: this.subjectKey(),
773
+ fetchedAt: this.fetchedAt,
774
+ etag: this.etag,
775
+ ttlSeconds: this.ttlSeconds,
776
+ unreadCount: this.serverUnread,
777
+ nextCursor: this.nextCursor,
778
+ stateScope: this.stateScope,
779
+ cards: this.wireCards,
780
+ }),
781
+ );
782
+ } catch {
783
+ /* storage blocked or full: memory only */
784
+ }
785
+ }
786
+
787
+ private loadFeedCache(): void {
788
+ try {
789
+ if (typeof sessionStorage === 'undefined') return;
790
+ const raw = sessionStorage.getItem(cardsFeedStorageKey(this.sdkKey));
791
+ if (!raw) return;
792
+ const stored = JSON.parse(raw);
793
+ // Another visitor's feed (a reset or a login since) is not this one's.
794
+ if (!stored || stored.subject !== this.subjectKey()) return;
795
+ this.wireCards = parseCards(stored.cards);
796
+ this.serverUnread = typeof stored.unreadCount === 'number' ? Math.max(0, stored.unreadCount) : 0;
797
+ this.nextCursor = str(stored.nextCursor);
798
+ this.stateScope = stored.stateScope === 'device' ? 'device' : 'server';
799
+ this.etag = str(stored.etag);
800
+ this.ttlSeconds = typeof stored.ttlSeconds === 'number' && stored.ttlSeconds > 0 ? stored.ttlSeconds : CARD_FEED_TTL_SECONDS;
801
+ this.fetchedAt = typeof stored.fetchedAt === 'number' ? stored.fetchedAt : null;
802
+ } catch {
803
+ this.wireCards = [];
804
+ }
805
+ }
806
+
807
+ private persistDeviceState(): void {
808
+ const trim = (set: Set<string>) => {
809
+ while (set.size > DEVICE_STATE_MAX) set.delete(set.values().next().value as string);
810
+ };
811
+ trim(this.deviceRead);
812
+ trim(this.deviceDismissed);
813
+ try {
814
+ if (typeof localStorage === 'undefined') return;
815
+ localStorage.setItem(
816
+ cardsDeviceStorageKey(this.sdkKey),
817
+ JSON.stringify({
818
+ anonymousId: this.identity.getAnonymousId(),
819
+ read: Array.from(this.deviceRead),
820
+ dismissed: Array.from(this.deviceDismissed),
821
+ }),
822
+ );
823
+ } catch {
824
+ /* storage blocked or full: memory only */
825
+ }
826
+ }
827
+
828
+ private loadDeviceState(): void {
829
+ try {
830
+ if (typeof localStorage === 'undefined') return;
831
+ const raw = localStorage.getItem(cardsDeviceStorageKey(this.sdkKey));
832
+ if (!raw) return;
833
+ const stored = JSON.parse(raw);
834
+ // Kept for one anonymous visitor; a new one starts clean.
835
+ if (!stored || stored.anonymousId !== this.identity.getAnonymousId()) return;
836
+ for (const id of Array.isArray(stored.read) ? stored.read : []) if (typeof id === 'string') this.deviceRead.add(id);
837
+ for (const id of Array.isArray(stored.dismissed) ? stored.dismissed : []) if (typeof id === 'string') this.deviceDismissed.add(id);
838
+ } catch {
839
+ this.deviceRead.clear();
840
+ this.deviceDismissed.clear();
841
+ }
842
+ }
843
+ }