@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,93 @@
1
+ /**
2
+ * The files the core loads on demand from the SDK host, next to
3
+ * `joryio.min.js`: the point-and-click editor (`joryio-editor.min.js`,
4
+ * src/core/editor-gate.ts) and the default card feed (`joryio-cards-ui.min.js`,
5
+ * src/core/cards.ts). Kept out of the core so that a visitor who never needs
6
+ * them never downloads them (BACKLOG D444).
7
+ */
8
+ import { SDK_VERSION } from './config';
9
+
10
+ export const SDK_HOST = 'https://sdk.joryio.com';
11
+
12
+ /** A core bundle's own file name: what a script tag loads (sdk.joryio.com, the npm package's dist/). */
13
+ const CORE_FILE = /\/joryio(?:\.umd)?(?:\.min)?\.js$/;
14
+
15
+ /**
16
+ * The folder the running core was loaded from (with a trailing slash), when
17
+ * it was loaded by a script tag as `joryio.min.js` over https - for example
18
+ * `https://sdk.joryio.com/web/1.4.0-beta.4/`. Null when bundled into the
19
+ * site's own code (the script is then the site's file), or not over https.
20
+ */
21
+ export function coreFolderOf(src: string | null | undefined): string | null {
22
+ if (!src || typeof src !== 'string') return null;
23
+ let u: URL;
24
+ try {
25
+ u = new URL(src);
26
+ } catch {
27
+ return null;
28
+ }
29
+ if (u.protocol !== 'https:' || !CORE_FILE.test(u.pathname)) return null;
30
+ return `${u.origin}${u.pathname.replace(/[^/]*$/, '')}`;
31
+ }
32
+
33
+ /**
34
+ * Read while this module is evaluated, i.e. while the core's script runs:
35
+ * `document.currentScript` is null afterwards (and for a module script),
36
+ * then the last `<script src=".../joryio.min.js">` on the page is used.
37
+ */
38
+ function readOwnFolder(): string | null {
39
+ if (typeof document === 'undefined') return null;
40
+ try {
41
+ const current = document.currentScript as HTMLScriptElement | null;
42
+ const fromCurrent = coreFolderOf(current && current.src);
43
+ if (fromCurrent || (current && current.src)) return fromCurrent;
44
+ const tags = document.querySelectorAll('script[src]');
45
+ for (let i = tags.length - 1; i >= 0; i--) {
46
+ const folder = coreFolderOf((tags[i] as HTMLScriptElement).src);
47
+ if (folder) return folder;
48
+ }
49
+ } catch {
50
+ /* no DOM access */
51
+ }
52
+ return null;
53
+ }
54
+ const OWN_FOLDER = readOwnFolder();
55
+
56
+ /**
57
+ * Where a lazily loaded file comes from, in order:
58
+ * 1. the folder the core itself was loaded from (`coreFolderOf`), so a core
59
+ * from `sdk.joryio.com/web/1.4.0-beta.4/` (a beta, whose SDK_VERSION
60
+ * still says 1.4.0) or from the npm package's `dist/` on a CDN loads the
61
+ * side files of the same build - unless that folder is the major channel
62
+ * `sdk.joryio.com/web/<major>/`, which moves: then 2 goes first;
63
+ * 2. the exact SDK version's folder on the SDK host (immutable, the same
64
+ * build as this core);
65
+ * 3. the major channel, as a fallback (a version not on the CDN, such as a
66
+ * local build).
67
+ * An init option (`editorScriptUrl`, `cardsUiScriptUrl`) replaces all of
68
+ * them, for a self-hosted SDK.
69
+ */
70
+ export function sdkHostFileUrls(file: string, override?: string, ownFolder: string | null = OWN_FOLDER): string[] {
71
+ if (override) return [override];
72
+ const major = SDK_VERSION.split('.')[0];
73
+ const exact = `${SDK_HOST}/web/${SDK_VERSION}/${file}`;
74
+ const channel = `${SDK_HOST}/web/${major}/${file}`;
75
+ const urls = ownFolder && ownFolder !== `${SDK_HOST}/web/${major}/` ? [`${ownFolder}${file}`, exact, channel] : [exact, channel];
76
+ return urls.filter((u, i) => urls.indexOf(u) === i);
77
+ }
78
+
79
+ /** Inject one script tag; resolves when it ran (onload), rejects on an error (a 404, a blocking CSP). */
80
+ export function loadSdkScript(src: string, marker: string): Promise<void> {
81
+ return new Promise((resolve, reject) => {
82
+ const s = document.createElement('script');
83
+ s.src = src;
84
+ s.async = true;
85
+ s.setAttribute(marker, 'bundle');
86
+ s.onload = () => resolve();
87
+ s.onerror = () => {
88
+ s.remove();
89
+ reject(new Error(`could not load ${src}`));
90
+ };
91
+ (document.head || document.documentElement).appendChild(s);
92
+ });
93
+ }
package/src/core/sdk.ts CHANGED
@@ -3,6 +3,9 @@
3
3
  * Main SDK class
4
4
  */
5
5
 
6
+ import { PageEditManager } from './page-edits';
7
+ import { EditorGate, editorRequested } from './editor-gate';
8
+ import { PageContextTracker } from './page-context';
6
9
  import { InitConfig, ResolvedConfig, resolveConfig, SDK_VERSION } from './config';
7
10
  import { StorageManager } from './storage';
8
11
  import { SessionManager, SESSION_ID_KEY } from './session';
@@ -18,6 +21,11 @@ import {
18
21
  } from './network';
19
22
  import { UTMManager } from './utm';
20
23
  import { InAppMessagingManager, InAppCampaign } from './inapp';
24
+ import { PlacementManager, Placement, PlacementHandle, InsertPlacementOptions, PlacementsUpdatedCallback, PlacementConsent } from './placements';
25
+ import { CardManager, Card, CardFeed, CardFeedHandle, CardsUpdatedCallback, GetCardsOptions, MountCardFeedOptions } from './cards';
26
+ import { JoryioSubscription, joryioSubscription } from './subscription';
27
+ import { LinkRouter, JoryioLinkHandler } from './links';
28
+ import { FlagsManager, FlagsUpdatedCallback } from './flags';
21
29
  import { User } from './user';
22
30
  import { Logger } from '../utils/logger';
23
31
  import { getDeviceProperties } from './device';
@@ -254,6 +262,17 @@ export class JoryioSDK {
254
262
  private network!: NetworkClient;
255
263
  private utm!: UTMManager;
256
264
  private inapp!: InAppMessagingManager;
265
+ /** Placements: spots inside the page filled per visitor (placements.ts). */
266
+ private placements!: PlacementManager;
267
+ /** Content cards: the person's feed (cards.ts). */
268
+ private cards!: CardManager;
269
+ // Created with the instance, so setLinkHandler works before init().
270
+ private links = new LinkRouter((error) => this.logger?.error('Your link handler threw; the link opens as without one:', error));
271
+ private pageContext!: PageContextTracker;
272
+ private pageEdits!: PageEditManager;
273
+ private editor: EditorGate | null = null;
274
+ /** Feature flags + remote config (flags.ts). */
275
+ private flags!: FlagsManager;
257
276
  private _user!: User;
258
277
  private _push!: PushManager;
259
278
  private _ecommerce: EcommerceTracker | null = null;
@@ -531,6 +550,86 @@ export class JoryioSDK {
531
550
  // false, so every HTML campaign is refused with no way to opt in.
532
551
  this.inapp.setAllowHtmlJsInAppMessages(this.config.inApp.allowHtmlJsInAppMessages);
533
552
 
553
+ // Page context (D444 Phase 4): one tracker for overlays, placements and page edits.
554
+ this.pageContext = new PageContextTracker(this.config.pageContext);
555
+ // UTM page rules (D444 Phase 4 follow-up): the UTM this SDK already recorded, when capture is on.
556
+ this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
557
+ this.inapp.setPageContext(this.pageContext);
558
+
559
+ this.placements = new PlacementManager(
560
+ this.config.apiEndpoint,
561
+ this.config.sdkKey,
562
+ this.identity,
563
+ this.session,
564
+ this.logger,
565
+ {
566
+ consent: () => this.placementConsent(),
567
+ allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
568
+ requestTimeoutMs: this.config.requestTimeout,
569
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
570
+ bridge: {
571
+ logCustomEvent: (name, properties) => this.track(name, properties),
572
+ setCustomUserAttribute: (key, value) => this.setAttribute(key, value),
573
+ changeUser: (userId) => this.identify(userId),
574
+ requestPushPermission: () => {
575
+ this._push.subscribe().catch((error) => this.logger.warn('Push subscribe failed:', error));
576
+ },
577
+ },
578
+ },
579
+ this.network,
580
+ );
581
+ this.placements.setPageContext(this.pageContext);
582
+
583
+ // Page edits (D444 Phase 4): selector edits from page-edit campaigns.
584
+ this.pageEdits = new PageEditManager(
585
+ this.config.apiEndpoint,
586
+ this.config.sdkKey,
587
+ this.identity,
588
+ this.session,
589
+ this.logger,
590
+ {
591
+ consent: () => this.placementConsent(),
592
+ requestTimeoutMs: this.config.requestTimeout,
593
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
594
+ },
595
+ this.network,
596
+ );
597
+ this.pageEdits.setPageContext(this.pageContext);
598
+
599
+ this.cards = new CardManager(
600
+ this.config.apiEndpoint,
601
+ this.config.sdkKey,
602
+ this.identity,
603
+ this.session,
604
+ this.logger,
605
+ {
606
+ consent: () => this.placementConsent(),
607
+ requestTimeoutMs: this.config.requestTimeout,
608
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
609
+ cardsUiScriptUrl: this.config.cardsUiScriptUrl,
610
+ },
611
+ this.network,
612
+ );
613
+
614
+ // One link router for every surface that opens a link (setLinkHandler).
615
+ this.inapp.links = this.links;
616
+ this.placements.links = this.links;
617
+ this.cards.links = this.links;
618
+
619
+ this.flags = new FlagsManager(
620
+ this.config.apiEndpoint,
621
+ this.config.sdkKey,
622
+ this.identity,
623
+ this.session,
624
+ this.logger,
625
+ {
626
+ canSend: () => this.isInitialized && !this.disabled && !this.network.isSuspended() && this.canSend(),
627
+ requestTimeoutMs: this.config.requestTimeout,
628
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
629
+ },
630
+ this.network,
631
+ );
632
+
534
633
  // Initialize user object for subscription management
535
634
  this._user = new User(
536
635
  this.logger,
@@ -645,6 +744,26 @@ export class JoryioSDK {
645
744
  if (!this.disabled) JoryioSDK.instance = this;
646
745
  this.logger.info('SDK initialized successfully');
647
746
 
747
+ // <div data-joryio-placement="key"> elements, now and as the page changes.
748
+ if (!this.disabled && this.config.inApp.autoMountPlacements) this.placements.autoMount();
749
+ // Route changes, scroll depth, time on page, exit intent (D444 Phase 4).
750
+ if (!this.disabled) this.pageContext.start();
751
+ // `pageEdits: false` (init): no page edit, no anti-flicker, no editor - whatever the server says.
752
+ if (!this.disabled && this.config.pageEdits) {
753
+ if (editorRequested()) {
754
+ // The dashboard's point-and-click editor opened this tab: the page as
755
+ // the site draws it (no page edits), and the picker once the token is
756
+ // vouched for - only then is the editor's own file loaded. Nothing
757
+ // happens for a tab that was not opened that way.
758
+ this.editor = new EditorGate(this.config.apiEndpoint, this.config.sdkKey, this.logger, { scriptUrl: this.config.editorScriptUrl });
759
+ this.editor.start();
760
+ } else {
761
+ this.pageEdits.start();
762
+ }
763
+ }
764
+ // Flags: the stored answer is readable at once; refresh it now and when the page is shown again.
765
+ if (!this.disabled) this.flags.start();
766
+
648
767
  // Report permission state now the SDK is live - only when this site uses
649
768
  // web push (see pushPermissionReported), and only on a change.
650
769
  this.reportPushPermissionIfChanged();
@@ -958,6 +1077,11 @@ export class JoryioSDK {
958
1077
  this.pinAnonymousWrites();
959
1078
  this.network.switchUser(userId);
960
1079
  this.identity.adopt(anonymousId, userId);
1080
+ this.placements.invalidate();
1081
+ // Another person: the anonymous visitor's card state goes too.
1082
+ this.cards.invalidate(true);
1083
+ this.pageEdits?.invalidate();
1084
+ this.flags.onIdentityChanged();
961
1085
  // Whoever was kept for withdrawals here belongs to the old identity.
962
1086
  this.withdrawalUserId = null;
963
1087
  if (loggedOut) {
@@ -1345,6 +1469,15 @@ export class JoryioSDK {
1345
1469
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
1346
1470
  // In-app answers requested under the previous state are stale.
1347
1471
  this.inapp.invalidate();
1472
+ // Placement answers too: a grant turns generic answers personal, a
1473
+ // refusal turns personal answers generic.
1474
+ this.placements?.invalidate();
1475
+ // The card feed is asked for only with consent: a grant fetches it, a refusal empties it.
1476
+ this.cards?.invalidate(false);
1477
+ // Consent changed: the stored site settings go too (as every per-workspace store).
1478
+ this.pageEdits?.invalidate({ siteSettings: true });
1479
+ // Flags too: without consent nothing is read or sent; a grant fetches.
1480
+ this.flags?.onIdentityChanged();
1348
1481
  }
1349
1482
 
1350
1483
  if (this.isOptedOut) {
@@ -1738,6 +1871,7 @@ export class JoryioSDK {
1738
1871
  if (this.canSend()) {
1739
1872
  try {
1740
1873
  this.inapp?.onEventTracked(eventName, eventProperties);
1874
+ this.placements?.onEventTracked(eventName, eventProperties);
1741
1875
  } catch (error) {
1742
1876
  this.logger.error('In-app trigger evaluation failed:', error);
1743
1877
  }
@@ -1814,7 +1948,13 @@ export class JoryioSDK {
1814
1948
  // set is B's own. Also keeps the user id for auth-failure reporting.
1815
1949
  this.network.switchUser(userId);
1816
1950
  // In-app answers requested for the previous identity are stale.
1817
- if (previousUserId !== userId) this.inapp.invalidate();
1951
+ if (previousUserId !== userId) {
1952
+ this.inapp.invalidate();
1953
+ this.placements.invalidate();
1954
+ this.cards.invalidate(true);
1955
+ this.pageEdits?.invalidate();
1956
+ this.flags.onIdentityChanged();
1957
+ }
1818
1958
 
1819
1959
  if (!this.canSend()) return; // consent pending: sent when granted
1820
1960
 
@@ -2375,7 +2515,12 @@ export class JoryioSDK {
2375
2515
  // New anonymous id, no user id.
2376
2516
  this.pinAnonymousWrites();
2377
2517
  this.identity.reset(anonymousId);
2518
+ this.flags.onIdentityChanged();
2378
2519
  this.network.setCurrentUserId(this.identity.getUserId());
2520
+ this.placements.invalidate();
2521
+ this.cards.invalidate(true);
2522
+ // reset / resetTo: the stored site settings go too (identify keeps them - the same for every visitor).
2523
+ this.pageEdits?.invalidate({ siteSettings: true });
2379
2524
 
2380
2525
  // UTM before the session: the new session's Session Start (tracked by the
2381
2526
  // session's onNewSession hook) must not carry the outgoing user's campaign.
@@ -2482,7 +2627,11 @@ export class JoryioSDK {
2482
2627
  this.forgetDeferredIdentify();
2483
2628
  this.pinAnonymousWrites();
2484
2629
  this.identity.reset();
2630
+ this.flags.onIdentityChanged();
2485
2631
  this.network.setCurrentUserId(null);
2632
+ this.placements.invalidate();
2633
+ this.cards?.invalidate(true);
2634
+ this.pageEdits?.invalidate({ siteSettings: true });
2486
2635
  this.utm.reset();
2487
2636
  this.session.clear();
2488
2637
  this.lastTrackedUrl = null;
@@ -3249,6 +3398,233 @@ export class JoryioSDK {
3249
3398
  }
3250
3399
  }
3251
3400
 
3401
+ /**
3402
+ * What a placement request may carry (docs/PLACEMENTS_PLAN.md 3.9): null =
3403
+ * nothing may be sent at all; `granted` = the visitor is named and their
3404
+ * interactions reported; `pending` / `denied` (opted out and Do Not Track
3405
+ * included) = an anonymous request for generic content, nothing reported.
3406
+ */
3407
+ private placementConsent(): PlacementConsent | null {
3408
+ if (!this.isInitialized || this.disabled || this.network.isSuspended()) return null;
3409
+ if (this.canSend()) return 'granted';
3410
+ return this.consentPending ? 'pending' : 'denied';
3411
+ }
3412
+
3413
+ /**
3414
+ * Receive EVERY link the SDK is about to open - an in-app message button or
3415
+ * link, a placement button, a card click - before it opens: http(s) links
3416
+ * and app deep links (`myapp://cart`) alike, with where it came from
3417
+ * (`link.source`: in_app, placement, card) and the ids that go with it.
3418
+ * Return true to take the link over - route it with your single-page app's
3419
+ * router instead of a new tab - or false to let the SDK open it as it does
3420
+ * without a handler. A refused scheme (javascript:, data:, ...) never
3421
+ * reaches it. Synchronous on purpose: the click's user activation still
3422
+ * holds when the SDK opens a tab. Works before init(). Same name on iOS,
3423
+ * Android, React Native and Unity (`SetLinkHandler`).
3424
+ */
3425
+ setLinkHandler(handler: JoryioLinkHandler): void {
3426
+ if (typeof handler !== 'function') {
3427
+ this.logger?.warn('setLinkHandler() needs a function; use clearLinkHandler() to remove one');
3428
+ return;
3429
+ }
3430
+ this.links.setHandler(handler);
3431
+ }
3432
+
3433
+ /** Remove the handler set with setLinkHandler: links open as they do without one. */
3434
+ clearLinkHandler(): void {
3435
+ this.links.setHandler(null);
3436
+ }
3437
+
3438
+ /**
3439
+ * Draw placement `placementKey` into `element` (docs: Placements). The SDK
3440
+ * fetches, caches and refreshes it, measures viewability and reports
3441
+ * impressions, clicks and dismissals. Returns a handle whose `remove()`
3442
+ * stops it; null for an invalid key or element.
3443
+ */
3444
+ /**
3445
+ * The page's own variables for page targeting (D444 Phase 4), e.g.
3446
+ * `{ pageType: 'product', category: 'shoes' }`. Replaces what was set
3447
+ * before; `null` clears it. Primitives only, at most 20. Call it on every
3448
+ * page (and after each route change in a single-page app). Safe before
3449
+ * init.
3450
+ */
3451
+ setPageVariables(variables: Record<string, string | number | boolean> | null): void {
3452
+ try {
3453
+ this.pageContext?.setPageVariables(variables);
3454
+ } catch (error) {
3455
+ this.logger.warn('setPageVariables failed:', error);
3456
+ }
3457
+ }
3458
+
3459
+ insertPlacement(placementKey: string, element: HTMLElement, options?: InsertPlacementOptions): PlacementHandle | null {
3460
+ if (!this.isInitialized) {
3461
+ this.logger.error('SDK not initialized');
3462
+ return null;
3463
+ }
3464
+ return this.placements.insertPlacement(placementKey, element, options);
3465
+ }
3466
+
3467
+ /**
3468
+ * The placements for `placementKeys`, to draw with your own UI. Report what
3469
+ * the person did with `item.markDisplayed()` (once it was viewable),
3470
+ * `item.markClicked()` and `item.markDismissed()`; for a held-out visitor
3471
+ * (`isControl`), `placement.markDisplayed()` when the empty spot was viewable.
3472
+ */
3473
+ async getPlacements(placementKeys: string[]): Promise<Record<string, Placement>> {
3474
+ if (!this.isInitialized) {
3475
+ this.logger.error('SDK not initialized');
3476
+ return {};
3477
+ }
3478
+ return this.placements.getPlacements(placementKeys);
3479
+ }
3480
+
3481
+ /** Ask the server again (default: every placement on the page). At most once per key per PLACEMENT_MIN_REFRESH_SECONDS. */
3482
+ async refreshPlacements(placementKeys?: string[]): Promise<void> {
3483
+ if (!this.isInitialized) return;
3484
+ await this.placements.refreshPlacements(placementKeys);
3485
+ }
3486
+
3487
+ /** Called with the placements whose content changed. Returns a JoryioSubscription: `cancel()` it to stop (calling it is the same). */
3488
+ onPlacementsUpdated(callback: PlacementsUpdatedCallback): JoryioSubscription {
3489
+ if (!this.isInitialized) {
3490
+ this.logger.error('SDK not initialized');
3491
+ return joryioSubscription(() => undefined);
3492
+ }
3493
+ return this.placements.onPlacementsUpdated(callback);
3494
+ }
3495
+
3496
+ /**
3497
+ * The person's content cards (docs: Content cards): from the cache while it
3498
+ * is fresh (CARD_FEED_TTL_SECONDS), from the server otherwise. With
3499
+ * `{ cursor: feed.nextCursor }`, the next page - added to the cached feed.
3500
+ * Without tracking consent the feed is empty and nothing is asked.
3501
+ */
3502
+ async getCards(options?: GetCardsOptions): Promise<CardFeed> {
3503
+ if (!this.isInitialized) {
3504
+ this.logger.error('SDK not initialized');
3505
+ return { cards: [], unreadCount: 0, nextCursor: null, stateScope: 'server' };
3506
+ }
3507
+ return this.cards.getCards(options);
3508
+ }
3509
+
3510
+ /** Unread cards in the cached feed (the badge). Never goes to the network. */
3511
+ getUnreadCardCount(): number {
3512
+ if (!this.isInitialized) return 0;
3513
+ return this.cards.getUnreadCardCount();
3514
+ }
3515
+
3516
+ /** Report that a card (or card id) was on screen - the feed drawn by mountCardFeed does this itself. */
3517
+ markCardViewed(card: Card | string): void {
3518
+ if (!this.isInitialized) return;
3519
+ this.cards.markCardViewed(card);
3520
+ }
3521
+
3522
+ /** Mark a card read: the unread count drops at once. A card already read sends nothing. */
3523
+ markCardRead(card: Card | string): void {
3524
+ if (!this.isInitialized) return;
3525
+ this.cards.markCardRead(card);
3526
+ }
3527
+
3528
+ /** Report a tap on a card (it counts as read too). Open `card.url` yourself when you draw the feed. */
3529
+ markCardClicked(card: Card | string): void {
3530
+ if (!this.isInitialized) return;
3531
+ this.cards.markCardClicked(card);
3532
+ }
3533
+
3534
+ /** Dismiss a card: it leaves the feed at once, on every device for a known person. */
3535
+ dismissCard(card: Card | string): void {
3536
+ if (!this.isInitialized) return;
3537
+ this.cards.dismissCard(card);
3538
+ }
3539
+
3540
+ /** Ask the server for the feed again. At most once per CARD_MIN_REFRESH_SECONDS; extra calls coalesce. */
3541
+ async refreshCards(): Promise<void> {
3542
+ if (!this.isInitialized) return;
3543
+ await this.cards.refreshCards();
3544
+ }
3545
+
3546
+ /**
3547
+ * Called with the whole feed whenever it changes - the way to keep a feed UI
3548
+ * of your own up to date. Returns a JoryioSubscription: `cancel()` it to stop
3549
+ * (calling it, `sub()`, is the same).
3550
+ */
3551
+ onCardsUpdated(callback: CardsUpdatedCallback): JoryioSubscription {
3552
+ if (!this.isInitialized) {
3553
+ this.logger.error('SDK not initialized');
3554
+ return joryioSubscription(() => undefined);
3555
+ }
3556
+ return this.cards.onCardsUpdated(callback);
3557
+ }
3558
+
3559
+ /**
3560
+ * Draw the person's card feed into `element` and keep it up to date. Cards
3561
+ * are reported viewed and read once half of one was on screen for a second,
3562
+ * clicked on a tap (then its http(s) link opens, or a deep link goes to
3563
+ * `onDeepLink`), dismissed on its x. Returns a handle whose `remove()` stops it.
3564
+ * The drawing code is `joryio-cards-ui.min.js`, loaded from the SDK host the
3565
+ * first time a feed is mounted (`cardsUiScriptUrl` to self-host): the handle
3566
+ * comes back at once and the feed appears when the file has loaded. If it
3567
+ * cannot load, a warning is logged and the element gets
3568
+ * `data-joryio-card-feed-state="unavailable"`; the data API keeps working.
3569
+ */
3570
+ mountCardFeed(element: HTMLElement, options?: MountCardFeedOptions): CardFeedHandle | null {
3571
+ if (!this.isInitialized) {
3572
+ this.logger.error('SDK not initialized');
3573
+ return null;
3574
+ }
3575
+ return this.cards.mountCardFeed(element, options);
3576
+ }
3577
+
3578
+ /**
3579
+ * A flag's value for this visitor, or `defaultValue` before the first answer,
3580
+ * for a flag the server did not send, or without tracking consent. Never
3581
+ * waits for the network. The first read in a session logs an exposure.
3582
+ */
3583
+ getFlag<T = unknown>(key: string, defaultValue: T): T {
3584
+ if (!this.isInitialized) return defaultValue;
3585
+ return this.flags.getFlag(key, defaultValue);
3586
+ }
3587
+
3588
+ /** A boolean flag, or `defaultValue` (also for a flag of another type). */
3589
+ getBoolFlag(key: string, defaultValue: boolean): boolean {
3590
+ return this.isInitialized ? this.flags.getBoolFlag(key, defaultValue) : defaultValue;
3591
+ }
3592
+
3593
+ /** A string flag, or `defaultValue`. */
3594
+ getStringFlag(key: string, defaultValue: string): string {
3595
+ return this.isInitialized ? this.flags.getStringFlag(key, defaultValue) : defaultValue;
3596
+ }
3597
+
3598
+ /** A number flag, or `defaultValue`. */
3599
+ getNumberFlag(key: string, defaultValue: number): number {
3600
+ return this.isInitialized ? this.flags.getNumberFlag(key, defaultValue) : defaultValue;
3601
+ }
3602
+
3603
+ /** A JSON flag (object, array or scalar), or `defaultValue`. */
3604
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): T {
3605
+ return this.isInitialized ? this.flags.getJsonFlag(key, defaultValue) : defaultValue;
3606
+ }
3607
+
3608
+ /** Every flag held for this visitor, key -> value. Logs no exposure. */
3609
+ getAllFlags(): Record<string, unknown> {
3610
+ return this.isInitialized ? this.flags.getAllFlags() : {};
3611
+ }
3612
+
3613
+ /** Fetch the flags now. */
3614
+ async refreshFlags(): Promise<void> {
3615
+ if (!this.isInitialized) return;
3616
+ await this.flags.refreshFlags();
3617
+ }
3618
+
3619
+ /** Called with the keys whose value changed. Returns a JoryioSubscription: `cancel()` it to stop (calling it is the same). */
3620
+ onFlagsUpdated(callback: FlagsUpdatedCallback): JoryioSubscription {
3621
+ if (!this.isInitialized) {
3622
+ this.logger.error('SDK not initialized');
3623
+ return joryioSubscription(() => undefined);
3624
+ }
3625
+ return this.flags.onFlagsUpdated(callback);
3626
+ }
3627
+
3252
3628
  /**
3253
3629
  * Destroy the SDK instance
3254
3630
  */
@@ -3310,6 +3686,12 @@ export class JoryioSDK {
3310
3686
  // Clear in-app messaging (every timer included)
3311
3687
  this.inapp.clearAll();
3312
3688
  this.inapp.destroy();
3689
+ this.placements.destroy();
3690
+ this.cards.destroy();
3691
+ this.pageEdits?.destroy();
3692
+ this.editor?.stop();
3693
+ this.pageContext?.destroy();
3694
+ this.flags.destroy();
3313
3695
 
3314
3696
  this.isInitialized = false;
3315
3697
  if (JoryioSDK.instance === this) JoryioSDK.instance = null;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Returned by every `on...Updated` listener - `onCardsUpdated`,
3
+ * `onPlacementsUpdated` and `onFlagsUpdated`: `cancel()` stops the updates.
4
+ * It is also callable, `sub()` being `sub.cancel()`, so code that called the
5
+ * returned function keeps working. Cancelling twice is harmless.
6
+ *
7
+ * One type with the same name and the same `cancel()` on every Joryio SDK
8
+ * (iOS, Android, React Native; Unity `JoryioSubscription.Cancel()`), pinned by
9
+ * the backend's SDK parity spec.
10
+ */
11
+ export interface JoryioSubscription {
12
+ (): void;
13
+ cancel(): void;
14
+ }
15
+
16
+ /** A JoryioSubscription that runs `stop` once. */
17
+ export function joryioSubscription(stop: () => void): JoryioSubscription {
18
+ let done = false;
19
+ const cancel = (): void => {
20
+ if (done) return;
21
+ done = true;
22
+ stop();
23
+ };
24
+ const sub = (() => cancel()) as JoryioSubscription;
25
+ sub.cancel = cancel;
26
+ return sub;
27
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The visual editor bundle - `joryio-editor.min.js` on the SDK host, next to
3
+ * `joryio.min.js` (BACKLOG D444 Phase 4 follow-up).
4
+ *
5
+ * Loaded by the core's EditorGate (src/core/editor-gate.ts) only in a tab the
6
+ * Joryio dashboard opened for the point-and-click editor, and only after the
7
+ * server vouched for the editor token. It registers one global and does
8
+ * nothing else on its own: no request, no listener, until the gate calls
9
+ * `start` with the verified dashboard origin.
10
+ */
11
+ import { VisualEditor } from './visual-editor';
12
+ import { EDITOR_API_VERSION, EDITOR_GLOBAL, type EditorBundleApi } from '../core/editor-gate';
13
+
14
+ const api: EditorBundleApi = {
15
+ version: EDITOR_API_VERSION,
16
+ start({ dashboardOrigin, opener, logger, onStop }) {
17
+ const editor = new VisualEditor(dashboardOrigin, opener, logger, onStop);
18
+ editor.start();
19
+ return { stop: () => editor.stop() };
20
+ },
21
+ };
22
+
23
+ if (typeof window !== 'undefined' && !(window as any)[EDITOR_GLOBAL]) {
24
+ (window as any)[EDITOR_GLOBAL] = api;
25
+ }
26
+
27
+ export { api as editorApi };