@selfhelp/shared 1.15.1 → 1.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,51 @@ All notable changes to `@selfhelp/shared` will be documented in this file.
9
9
 
10
10
  This project follows semantic versioning.
11
11
 
12
+ ## v1.15.3
13
+
14
+ **Live Preview shared theme + language sync** — extends the bridge contract so a
15
+ colour-scheme / language change in either preview pane (the inline web pane or
16
+ the embedded mobile frame) is mirrored in the other. Additive only — two new
17
+ message types + payload — so `^1.15.x` consumers are unaffected; the frontend
18
+ (`>=0.1.39`) and mobile (`>=0.1.17`) Live Preview adopt it.
19
+
20
+ ### Added (additive, non-breaking)
21
+
22
+ - **`types/preview-bridge.ts`** new exports:
23
+ - message types `PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES` (shell → frame) and
24
+ `PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED` (frame → shell);
25
+ - the shared payload `IPreviewPreferences` (`colorScheme` +
26
+ cross-platform `locale`) and `TPreviewColorScheme` (`light` / `dark` /
27
+ `auto`, 1:1 with Mantine + the mobile theme store);
28
+ - the message shapes `IPreviewSetPreferencesCommand` /
29
+ `IPreviewPreferencesChangedMessage`, both added to the `TPreviewBridgeMessage`
30
+ union and validated by `isPreviewBridgeMessage`. Covered by the bridge tests.
31
+
32
+ ## v1.15.2
33
+
34
+ **Live Preview bridge contract** — the `postMessage` protocol that keeps the CMS
35
+ **Live Preview** shell and its two embedded frames (web frontend +
36
+ `selfhelp-mobile-preview`) on the same page. Clicking a link in one frame reports
37
+ the navigation up to the shell, which drives the other frame to the same CMS
38
+ keyword (with a per-frame loop guard). Additive only — new module + exports — so
39
+ `^1.15.x` consumers are unaffected; the frontend (`>=0.1.35`) and mobile
40
+ (`>=0.1.14`) Live Preview adopt it.
41
+
42
+ ### Added (additive, non-breaking)
43
+
44
+ - **`types/preview-bridge.ts`** (re-exported from the root): the single source of
45
+ truth for the bridge protocol —
46
+ - message-type constants `PREVIEW_BRIDGE_MESSAGE` (`READY` / `NAVIGATED` /
47
+ `NAVIGATE`) + `TPreviewBridgeMessageType`;
48
+ - activation/origin query-param names `PREVIEW_SHELL_PARAM` (`previewShell`) and
49
+ `PREVIEW_PARENT_ORIGIN_PARAM` (`parentOrigin`);
50
+ - payload shapes `IPreviewReadyMessage`, `IPreviewNavigatedMessage`,
51
+ `IPreviewNavigateCommand`, the `TPreviewBridgeMessage` union, and
52
+ `TPreviewFrameSource`;
53
+ - runtime helpers `isPreviewBridgeMessage(value)` (defensive guard for
54
+ `event.data`) and `previewKeywordFromPath(path)` (web/mobile paths → the same
55
+ keyword sync unit). Covered by `types/__tests__/preview-bridge.test.ts`.
56
+
12
57
  ## v1.15.1
13
58
 
14
59
  Mobile preview RN/Expo provenance parity **plus the CMS-driven mobile-preview
package/dist/index.d.mts CHANGED
@@ -846,6 +846,152 @@ interface IMobilePreviewExchangeData {
846
846
  }
847
847
  type IMobilePreviewExchangeResponse = IBaseApiResponse<IMobilePreviewExchangeData>;
848
848
 
849
+ /**
850
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
851
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
852
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
853
+ * web image).
854
+ *
855
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
856
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
857
+ * "navigate to keyword" command down from the shell, so clicking a link in one
858
+ * frame keeps the other frame on the same page. The same channel also carries
859
+ * the shared colour-scheme + language preferences both ways (SET_PREFERENCES
860
+ * down, PREFERENCES_CHANGED up) so the two panes stay in the same theme/locale.
861
+ * The shell prevents sync loops with a per-frame "expected value" guard (it
862
+ * ignores the echo of a command it just sent). See the frontend `LivePreview`
863
+ * shell + `PreviewShellBridge` and the mobile `PreviewSyncBridge`.
864
+ *
865
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
866
+ * activation/origin query-param names, the payload shapes, and the runtime type
867
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
868
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
869
+ *
870
+ * Security: messages are validated by `event.origin` on both ends (the shell
871
+ * allow-lists its own origin for the web frame and the mobile origin for the
872
+ * mobile frame; each frame trusts only the shell origin it was handed via
873
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
874
+ */
875
+ /** Which embedded preview frame a bridge message refers to. */
876
+ type TPreviewFrameSource = 'web' | 'mobile';
877
+ /**
878
+ * Three-way colour-scheme choice, shared VERBATIM across both panes — it maps
879
+ * 1:1 onto the web's Mantine `useMantineColorScheme` and the mobile theme store
880
+ * (`'auto'` = follow the OS on both).
881
+ */
882
+ type TPreviewColorScheme = 'light' | 'dark' | 'auto';
883
+ /**
884
+ * The shared, cross-pane preview preferences. `locale` (e.g. `de-CH`) is the
885
+ * cross-platform language key — each pane maps it to its own language id from
886
+ * its languages list; `null` means "unknown / leave as-is". Carried by both the
887
+ * shell→frame {@link IPreviewSetPreferencesCommand} and the frame→shell
888
+ * {@link IPreviewPreferencesChangedMessage} so theme + language stay in sync.
889
+ */
890
+ interface IPreviewPreferences {
891
+ colorScheme: TPreviewColorScheme;
892
+ locale: string | null;
893
+ }
894
+ /**
895
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
896
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
897
+ * so a real visitor never posts navigation messages.
898
+ */
899
+ declare const PREVIEW_SHELL_PARAM = "previewShell";
900
+ /**
901
+ * Query param carrying the shell's `window.location.origin` so a (possibly
902
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
903
+ */
904
+ declare const PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
905
+ /**
906
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
907
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
908
+ */
909
+ declare const PREVIEW_BRIDGE_MESSAGE: {
910
+ /** frame → shell: the bridge mounted and is ready to sync. */
911
+ readonly READY: "selfhelp-preview:ready";
912
+ /** frame → shell: the frame navigated to a new in-app location. */
913
+ readonly NAVIGATED: "selfhelp-preview:navigated";
914
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
915
+ readonly NAVIGATE: "selfhelp-preview:navigate";
916
+ /**
917
+ * shell → frame: apply the shared colour-scheme + language preferences (no
918
+ * reload), so the web pane and the mobile frame stay in the same theme/locale.
919
+ */
920
+ readonly SET_PREFERENCES: "selfhelp-preview:set-preferences";
921
+ /** frame → shell: the user changed the colour scheme / language in the frame. */
922
+ readonly PREFERENCES_CHANGED: "selfhelp-preview:preferences-changed";
923
+ };
924
+ type TPreviewBridgeMessageType = (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
925
+ /** frame → shell: emitted once when the bridge mounts. */
926
+ interface IPreviewReadyMessage {
927
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
928
+ source: TPreviewFrameSource;
929
+ }
930
+ /**
931
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
932
+ * the current page (the cross-platform sync unit), or `null` for home / a
933
+ * non-CMS location. `locale` is the frame's active locale when known (a toolbar
934
+ * indicator); active cross-pane language sync rides {@link PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED}.
935
+ */
936
+ interface IPreviewNavigatedMessage {
937
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
938
+ source: TPreviewFrameSource;
939
+ keyword: string | null;
940
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
941
+ href: string;
942
+ locale?: string | null;
943
+ }
944
+ /**
945
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
946
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
947
+ * state and the embedded dev client are preserved.
948
+ */
949
+ interface IPreviewNavigateCommand {
950
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
951
+ keyword: string | null;
952
+ }
953
+ /**
954
+ * shell → frame: apply the shared colour-scheme + language {@link IPreviewPreferences}
955
+ * with NO reload, so a theme/language change in one pane (or the toolbar) is
956
+ * mirrored in the other. Idempotent — re-applying the current values is a no-op.
957
+ */
958
+ interface IPreviewSetPreferencesCommand {
959
+ type: typeof PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES;
960
+ preferences: IPreviewPreferences;
961
+ }
962
+ /**
963
+ * frame → shell: the user changed the colour scheme and/or language inside the
964
+ * frame; the shell applies it to the other pane. The shell guards against the
965
+ * echo of a value it just pushed so the two panes never ping-pong.
966
+ */
967
+ interface IPreviewPreferencesChangedMessage {
968
+ type: typeof PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED;
969
+ source: TPreviewFrameSource;
970
+ preferences: IPreviewPreferences;
971
+ }
972
+ /** Every message that can cross the preview bridge, in either direction. */
973
+ type TPreviewBridgeMessage = IPreviewReadyMessage | IPreviewNavigatedMessage | IPreviewNavigateCommand | IPreviewSetPreferencesCommand | IPreviewPreferencesChangedMessage;
974
+ /**
975
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
976
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
977
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
978
+ */
979
+ declare function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage;
980
+ /**
981
+ * Loop-guard equality for the shared preferences. Both bridges keep the last
982
+ * value they pushed to / received from the other pane and skip re-emitting (or
983
+ * re-applying) an equal one, so a theme/language change never ping-pongs. Shared
984
+ * so the two panes compare preferences identically.
985
+ */
986
+ declare function arePreviewPreferencesEqual(a: IPreviewPreferences | null | undefined, b: IPreviewPreferences | null | undefined): boolean;
987
+ /**
988
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
989
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
990
+ * Shared so the web and mobile bridges derive identical keywords from their
991
+ * respective routers.
992
+ */
993
+ declare function previewKeywordFromPath(path: string | null | undefined): string | null;
994
+
849
995
  /**
850
996
  * Cross-repo SelfHelp distribution contracts: registry index + release metadata
851
997
  * (core / frontend / scheduler / worker / plugin), security advisories,
@@ -1894,4 +2040,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1894
2040
  */
1895
2041
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1896
2042
 
1897
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
2043
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IPreviewNavigateCommand, type IPreviewNavigatedMessage, type IPreviewPreferences, type IPreviewPreferencesChangedMessage, type IPreviewReadyMessage, type IPreviewSetPreferencesCommand, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, PREVIEW_BRIDGE_MESSAGE, PREVIEW_PARENT_ORIGIN_PARAM, PREVIEW_SHELL_PARAM, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, type TPreviewBridgeMessage, type TPreviewBridgeMessageType, type TPreviewColorScheme, type TPreviewFrameSource, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, arePreviewPreferencesEqual, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, isPreviewBridgeMessage, parseInlineRich, parseSpacing, previewKeywordFromPath, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.d.ts CHANGED
@@ -846,6 +846,152 @@ interface IMobilePreviewExchangeData {
846
846
  }
847
847
  type IMobilePreviewExchangeResponse = IBaseApiResponse<IMobilePreviewExchangeData>;
848
848
 
849
+ /**
850
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
851
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
852
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
853
+ * web image).
854
+ *
855
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
856
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
857
+ * "navigate to keyword" command down from the shell, so clicking a link in one
858
+ * frame keeps the other frame on the same page. The same channel also carries
859
+ * the shared colour-scheme + language preferences both ways (SET_PREFERENCES
860
+ * down, PREFERENCES_CHANGED up) so the two panes stay in the same theme/locale.
861
+ * The shell prevents sync loops with a per-frame "expected value" guard (it
862
+ * ignores the echo of a command it just sent). See the frontend `LivePreview`
863
+ * shell + `PreviewShellBridge` and the mobile `PreviewSyncBridge`.
864
+ *
865
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
866
+ * activation/origin query-param names, the payload shapes, and the runtime type
867
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
868
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
869
+ *
870
+ * Security: messages are validated by `event.origin` on both ends (the shell
871
+ * allow-lists its own origin for the web frame and the mobile origin for the
872
+ * mobile frame; each frame trusts only the shell origin it was handed via
873
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
874
+ */
875
+ /** Which embedded preview frame a bridge message refers to. */
876
+ type TPreviewFrameSource = 'web' | 'mobile';
877
+ /**
878
+ * Three-way colour-scheme choice, shared VERBATIM across both panes — it maps
879
+ * 1:1 onto the web's Mantine `useMantineColorScheme` and the mobile theme store
880
+ * (`'auto'` = follow the OS on both).
881
+ */
882
+ type TPreviewColorScheme = 'light' | 'dark' | 'auto';
883
+ /**
884
+ * The shared, cross-pane preview preferences. `locale` (e.g. `de-CH`) is the
885
+ * cross-platform language key — each pane maps it to its own language id from
886
+ * its languages list; `null` means "unknown / leave as-is". Carried by both the
887
+ * shell→frame {@link IPreviewSetPreferencesCommand} and the frame→shell
888
+ * {@link IPreviewPreferencesChangedMessage} so theme + language stay in sync.
889
+ */
890
+ interface IPreviewPreferences {
891
+ colorScheme: TPreviewColorScheme;
892
+ locale: string | null;
893
+ }
894
+ /**
895
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
896
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
897
+ * so a real visitor never posts navigation messages.
898
+ */
899
+ declare const PREVIEW_SHELL_PARAM = "previewShell";
900
+ /**
901
+ * Query param carrying the shell's `window.location.origin` so a (possibly
902
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
903
+ */
904
+ declare const PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
905
+ /**
906
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
907
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
908
+ */
909
+ declare const PREVIEW_BRIDGE_MESSAGE: {
910
+ /** frame → shell: the bridge mounted and is ready to sync. */
911
+ readonly READY: "selfhelp-preview:ready";
912
+ /** frame → shell: the frame navigated to a new in-app location. */
913
+ readonly NAVIGATED: "selfhelp-preview:navigated";
914
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
915
+ readonly NAVIGATE: "selfhelp-preview:navigate";
916
+ /**
917
+ * shell → frame: apply the shared colour-scheme + language preferences (no
918
+ * reload), so the web pane and the mobile frame stay in the same theme/locale.
919
+ */
920
+ readonly SET_PREFERENCES: "selfhelp-preview:set-preferences";
921
+ /** frame → shell: the user changed the colour scheme / language in the frame. */
922
+ readonly PREFERENCES_CHANGED: "selfhelp-preview:preferences-changed";
923
+ };
924
+ type TPreviewBridgeMessageType = (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
925
+ /** frame → shell: emitted once when the bridge mounts. */
926
+ interface IPreviewReadyMessage {
927
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
928
+ source: TPreviewFrameSource;
929
+ }
930
+ /**
931
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
932
+ * the current page (the cross-platform sync unit), or `null` for home / a
933
+ * non-CMS location. `locale` is the frame's active locale when known (a toolbar
934
+ * indicator); active cross-pane language sync rides {@link PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED}.
935
+ */
936
+ interface IPreviewNavigatedMessage {
937
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
938
+ source: TPreviewFrameSource;
939
+ keyword: string | null;
940
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
941
+ href: string;
942
+ locale?: string | null;
943
+ }
944
+ /**
945
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
946
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
947
+ * state and the embedded dev client are preserved.
948
+ */
949
+ interface IPreviewNavigateCommand {
950
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
951
+ keyword: string | null;
952
+ }
953
+ /**
954
+ * shell → frame: apply the shared colour-scheme + language {@link IPreviewPreferences}
955
+ * with NO reload, so a theme/language change in one pane (or the toolbar) is
956
+ * mirrored in the other. Idempotent — re-applying the current values is a no-op.
957
+ */
958
+ interface IPreviewSetPreferencesCommand {
959
+ type: typeof PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES;
960
+ preferences: IPreviewPreferences;
961
+ }
962
+ /**
963
+ * frame → shell: the user changed the colour scheme and/or language inside the
964
+ * frame; the shell applies it to the other pane. The shell guards against the
965
+ * echo of a value it just pushed so the two panes never ping-pong.
966
+ */
967
+ interface IPreviewPreferencesChangedMessage {
968
+ type: typeof PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED;
969
+ source: TPreviewFrameSource;
970
+ preferences: IPreviewPreferences;
971
+ }
972
+ /** Every message that can cross the preview bridge, in either direction. */
973
+ type TPreviewBridgeMessage = IPreviewReadyMessage | IPreviewNavigatedMessage | IPreviewNavigateCommand | IPreviewSetPreferencesCommand | IPreviewPreferencesChangedMessage;
974
+ /**
975
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
976
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
977
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
978
+ */
979
+ declare function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage;
980
+ /**
981
+ * Loop-guard equality for the shared preferences. Both bridges keep the last
982
+ * value they pushed to / received from the other pane and skip re-emitting (or
983
+ * re-applying) an equal one, so a theme/language change never ping-pongs. Shared
984
+ * so the two panes compare preferences identically.
985
+ */
986
+ declare function arePreviewPreferencesEqual(a: IPreviewPreferences | null | undefined, b: IPreviewPreferences | null | undefined): boolean;
987
+ /**
988
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
989
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
990
+ * Shared so the web and mobile bridges derive identical keywords from their
991
+ * respective routers.
992
+ */
993
+ declare function previewKeywordFromPath(path: string | null | undefined): string | null;
994
+
849
995
  /**
850
996
  * Cross-repo SelfHelp distribution contracts: registry index + release metadata
851
997
  * (core / frontend / scheduler / worker / plugin), security advisories,
@@ -1894,4 +2040,4 @@ declare function transformPageData(apiPage: IRawPage): IPageItem;
1894
2040
  */
1895
2041
  declare function transformPagesData(pages: IRawPage[] | null | undefined): IPageItem[];
1896
2042
 
1897
- export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, parseInlineRich, parseSpacing, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
2043
+ export { API_VERSION_PREFIX, type AdvisoryAffected, type AdvisoryFeed, type AdvisorySeverity, type BackupManifest, type BackupRetentionPolicy, type BackupSchedulePolicy, type BundledPluginRef, CLASS_PATTERNS, CLASS_REMAP, CLIENT_TYPE_MOBILE, CLIENT_TYPE_MOBILE_AND_WEB, CLIENT_TYPE_WEB, COLOR_NAMES, type CheckSeverity, type CompatibilityRules, type CoreRelease, type DatabaseMigrationMetadata, ENDPOINTS, type FrontendRelease, HEADER_CLIENT_TYPE, type IApiError, type IApiMeta, type IAssetSource, type IBaseApiResponse, type IBasePageInfo, type IBasePageSection, type IClassPattern, type IClassRemap, type ICompatibilityError, type IConditionContext, IContentField, type IEvaluatedCondition, type IForgotPasswordRequest, type IForgotPasswordResponse, type IFormDeleteRequest, type IFormDeleteResponse, type IFormResultLegacyFields, type IFormSubmitData, type IFormSubmitRequest, type IFormSubmitResponse, type IFormUpdateData, type IFormUpdateRequest, type IFormUpdateResponse, type IFrontendUpdatePreflight, type IFrontendUpdatePreflightResponse, type IFrontendUpdateReleases, type IFrontendUpdateReleasesResponse, type IFrontendUpdateRequest, type IFrontendUpdateRequestResponse, type IGetPageResponse, type IGetPagesResponse, type IInlineNode, type IJwtPayload, type ILanguage, type ILanguageItem, type ILanguagePreference, type ILanguagePreferenceUpdateResponse, type ILanguagesResponse, type ILoginRequest, type ILoginSuccessData, type ILoginSuccessResponse, type ILogoutSuccessResponse, type IMaintenanceSetRequest, type IMeta, type IMobileAdapterBaseProps, type IMobileButtonProps, type IMobileCardProps, type IMobileCheckboxProps, type IMobileContainerProps, type IMobileInputProps, type IMobileModalProps, type IMobilePreviewExchangeData, type IMobilePreviewExchangeRequest, type IMobilePreviewExchangeResponse, type IMobilePreviewSessionData, type IMobilePreviewSessionRequest, type IMobilePreviewSessionResponse, type IMobilePreviewUpdatePreflight, type IMobilePreviewUpdatePreflightResponse, type IMobilePreviewUpdateReleases, type IMobilePreviewUpdateReleasesResponse, type IMobilePreviewUpdateRequest, type IMobilePreviewUpdateRequestResponse, type IMobileSelectOption, type IMobileSelectProps, type IMobileSwitchProps, type IMobileTextProps, type IMobileTextareaProps, type IMobileUiAdapters, type IPageAccessTypeInfo, type IPageContent, type IPageField, type IPageFieldTranslation, type IPageFieldsData, type IPageItem, type IPageSectionWithFields, type IPageSectionsData, type IPreviewNavigateCommand, type IPreviewNavigatedMessage, type IPreviewPreferences, type IPreviewPreferencesChangedMessage, type IPreviewReadyMessage, type IPreviewSetPreferencesCommand, type IRefreshRequest, type IRefreshSuccessResponse, type IResetPasswordRequest, type IResetPasswordResponse, type ISpacingValue, type ISystemAdvisories, type ISystemAdvisoriesResponse, type ISystemAdvisory, type ISystemAdvisoryAffected, type ISystemHealth, type ISystemHealthComponent, type ISystemHealthResponse, type ISystemInstalledPlugin, type ISystemMaintenance, type ISystemMaintenanceResponse, type ISystemVersion, type ISystemVersionResponse, type ITwoFactorRequiredData, type ITwoFactorRequiredResponse, type ITwoFactorVerifyRequest, type ITwoFactorVerifySuccessResponse, type IUpdatePreflight, type IUpdatePreflightCheck, type IUpdatePreflightOption, type IUpdatePreflightResponse, type IUpdateRelease, type IUpdateReleases, type IUpdateReleasesResponse, type IUpdateRequest, type IUpdateRequestResponse, type IUpdateStatus, type IUpdateStatusManager, type IUpdateStatusResponse, type IUpdateStep, type IUserData, type IUserDataResponse, type ImageRef, type InstalledPlugin, type InstanceImages, type InstanceLock, type InstanceManifest, type InstanceMode, type InstanceResourceConfig, type InstanceRouting, type InstanceStatus, type InstanceVersions, type InventoryInstanceEntry, LITERAL_CLASSES, type LockPluginEntry, type LockServiceEntry, MOBILE_PREVIEW_ENDPOINTS, type MobilePreviewRelease, PERMISSIONS, PREVIEW_BRIDGE_MESSAGE, PREVIEW_PARENT_ORIGIN_PARAM, PREVIEW_SHELL_PARAM, type PluginRelease, type PreflightCheck, type PreflightOption, type PreflightStatus, RELEASE_CHANNELS, type RegistryIndex, type RegistryReleaseRef, type ReleaseChannel, type RuntimeServicePolicy, type RuntimeServiceRange, SIZE_VALUES, SPACING_VALUES, SYSTEM_ENDPOINTS, type SchedulerRelease, type SecurityAdvisory, type ServerInventory, type ServiceBackendCompatibility, type SignatureBlock, type SupportBundleMeta, type TCalcedValues, type TClassDecision, type TClientType, THeroUiButtonVariant, THeroUiSize, TMobileButtonFeedback, TMobileFieldVariant, TMobileSelectPresentation, type TPermission, type TPlatform, type TPreviewBridgeMessage, type TPreviewBridgeMessageType, type TPreviewColorScheme, type TPreviewFrameSource, TStyleName, type TSystemAdvisorySeverity, type TSystemComponentStatus, type TSystemDeployment, type TSystemHealthOverall, type TUpdateCheckSeverity, type TUpdateKind, type TUpdateOperationStatus, type TUpdatePreflightStatus, type TrustLevel, type TrustedKey, type TrustedKeysFile, type UpdatePreflightResult, type WorkerRelease, arePreviewPreferencesEqual, buildConditionContext, classifyClass, classifyClassString, evaluateCondition, findRemap, hasInlineFormatting, isPreviewBridgeMessage, parseInlineRich, parseSpacing, previewKeywordFromPath, replaceCalcedValues, resolveAssetSources, resolveAssetUrl, spacingToClasses, stripHtmlToText, transformPageData, transformPagesData };
package/dist/index.js CHANGED
@@ -49,6 +49,9 @@ __export(index_exports, {
49
49
  LITERAL_CLASSES: () => LITERAL_CLASSES,
50
50
  MOBILE_PREVIEW_ENDPOINTS: () => MOBILE_PREVIEW_ENDPOINTS,
51
51
  PERMISSIONS: () => PERMISSIONS,
52
+ PREVIEW_BRIDGE_MESSAGE: () => PREVIEW_BRIDGE_MESSAGE,
53
+ PREVIEW_PARENT_ORIGIN_PARAM: () => PREVIEW_PARENT_ORIGIN_PARAM,
54
+ PREVIEW_SHELL_PARAM: () => PREVIEW_SHELL_PARAM,
52
55
  RADIUS_PX: () => RADIUS_PX,
53
56
  RELEASE_CHANNELS: () => RELEASE_CHANNELS,
54
57
  SIZE_VALUES: () => SIZE_VALUES,
@@ -58,6 +61,7 @@ __export(index_exports, {
58
61
  STYLE_REGISTRY: () => STYLE_REGISTRY,
59
62
  SYSTEM_ENDPOINTS: () => SYSTEM_ENDPOINTS,
60
63
  _resetPluginStyleRegistry: () => _resetPluginStyleRegistry,
64
+ arePreviewPreferencesEqual: () => arePreviewPreferencesEqual,
61
65
  buildConditionContext: () => buildConditionContext,
62
66
  classifyClass: () => classifyClass,
63
67
  classifyClassString: () => classifyClassString,
@@ -75,6 +79,7 @@ __export(index_exports, {
75
79
  gridSpanToReactNativeColumn: () => gridSpanToReactNativeColumn,
76
80
  hasInlineFormatting: () => hasInlineFormatting,
77
81
  isKnownStyleName: () => isKnownStyleName,
82
+ isPreviewBridgeMessage: () => isPreviewBridgeMessage,
78
83
  isRegisteredStyleName: () => isRegisteredStyleName,
79
84
  isStyleAllowedOnPage: () => isStyleAllowedOnPage,
80
85
  isStylePlacementAllowed: () => isStylePlacementAllowed,
@@ -94,6 +99,7 @@ __export(index_exports, {
94
99
  parseDimensionToWeb: () => parseDimensionToWeb,
95
100
  parseInlineRich: () => parseInlineRich,
96
101
  parseSpacing: () => parseSpacing,
102
+ previewKeywordFromPath: () => previewKeywordFromPath,
97
103
  radiusToPx: () => radiusToPx,
98
104
  replaceCalcedValues: () => replaceCalcedValues,
99
105
  resolveAssetSources: () => resolveAssetSources,
@@ -211,6 +217,63 @@ var MOBILE_PREVIEW_ENDPOINTS = {
211
217
  EXCHANGE: `${MOBILE_PREVIEW_PREFIX}/mobile-preview/session/exchange`
212
218
  };
213
219
 
220
+ // src/types/preview-bridge.ts
221
+ var PREVIEW_SHELL_PARAM = "previewShell";
222
+ var PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
223
+ var PREVIEW_BRIDGE_MESSAGE = {
224
+ /** frame → shell: the bridge mounted and is ready to sync. */
225
+ READY: "selfhelp-preview:ready",
226
+ /** frame → shell: the frame navigated to a new in-app location. */
227
+ NAVIGATED: "selfhelp-preview:navigated",
228
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
229
+ NAVIGATE: "selfhelp-preview:navigate",
230
+ /**
231
+ * shell → frame: apply the shared colour-scheme + language preferences (no
232
+ * reload), so the web pane and the mobile frame stay in the same theme/locale.
233
+ */
234
+ SET_PREFERENCES: "selfhelp-preview:set-preferences",
235
+ /** frame → shell: the user changed the colour scheme / language in the frame. */
236
+ PREFERENCES_CHANGED: "selfhelp-preview:preferences-changed"
237
+ };
238
+ function isPreviewPreferences(value) {
239
+ if (typeof value !== "object" || value === null) return false;
240
+ const record = value;
241
+ return (record.colorScheme === "light" || record.colorScheme === "dark" || record.colorScheme === "auto") && (typeof record.locale === "string" || record.locale === null);
242
+ }
243
+ function isPreviewBridgeMessage(value) {
244
+ if (typeof value !== "object" || value === null) return false;
245
+ const record = value;
246
+ switch (record.type) {
247
+ case PREVIEW_BRIDGE_MESSAGE.READY:
248
+ return record.source === "web" || record.source === "mobile";
249
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
250
+ return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string";
251
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
252
+ return typeof record.keyword === "string" || record.keyword === null;
253
+ case PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES:
254
+ return isPreviewPreferences(record.preferences);
255
+ case PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED:
256
+ return (record.source === "web" || record.source === "mobile") && isPreviewPreferences(record.preferences);
257
+ default:
258
+ return false;
259
+ }
260
+ }
261
+ function arePreviewPreferencesEqual(a, b) {
262
+ if (!a || !b) return false;
263
+ return a.colorScheme === b.colorScheme && a.locale === b.locale;
264
+ }
265
+ function previewKeywordFromPath(path) {
266
+ if (!path) return null;
267
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? "";
268
+ const trimmed = withoutQuery.replace(/^\/+/, "").replace(/\/+$/, "");
269
+ if (trimmed === "") return null;
270
+ try {
271
+ return decodeURIComponent(trimmed);
272
+ } catch {
273
+ return trimmed;
274
+ }
275
+ }
276
+
214
277
  // src/types/distribution.ts
215
278
  var RELEASE_CHANNELS = ["stable", "beta", "nightly", "test"];
216
279
 
@@ -1543,6 +1606,9 @@ function transformPagesData(pages) {
1543
1606
  LITERAL_CLASSES,
1544
1607
  MOBILE_PREVIEW_ENDPOINTS,
1545
1608
  PERMISSIONS,
1609
+ PREVIEW_BRIDGE_MESSAGE,
1610
+ PREVIEW_PARENT_ORIGIN_PARAM,
1611
+ PREVIEW_SHELL_PARAM,
1546
1612
  RADIUS_PX,
1547
1613
  RELEASE_CHANNELS,
1548
1614
  SIZE_VALUES,
@@ -1552,6 +1618,7 @@ function transformPagesData(pages) {
1552
1618
  STYLE_REGISTRY,
1553
1619
  SYSTEM_ENDPOINTS,
1554
1620
  _resetPluginStyleRegistry,
1621
+ arePreviewPreferencesEqual,
1555
1622
  buildConditionContext,
1556
1623
  classifyClass,
1557
1624
  classifyClassString,
@@ -1569,6 +1636,7 @@ function transformPagesData(pages) {
1569
1636
  gridSpanToReactNativeColumn,
1570
1637
  hasInlineFormatting,
1571
1638
  isKnownStyleName,
1639
+ isPreviewBridgeMessage,
1572
1640
  isRegisteredStyleName,
1573
1641
  isStyleAllowedOnPage,
1574
1642
  isStylePlacementAllowed,
@@ -1588,6 +1656,7 @@ function transformPagesData(pages) {
1588
1656
  parseDimensionToWeb,
1589
1657
  parseInlineRich,
1590
1658
  parseSpacing,
1659
+ previewKeywordFromPath,
1591
1660
  radiusToPx,
1592
1661
  replaceCalcedValues,
1593
1662
  resolveAssetSources,
package/dist/index.mjs CHANGED
@@ -90,6 +90,63 @@ var MOBILE_PREVIEW_ENDPOINTS = {
90
90
  EXCHANGE: `${MOBILE_PREVIEW_PREFIX}/mobile-preview/session/exchange`
91
91
  };
92
92
 
93
+ // src/types/preview-bridge.ts
94
+ var PREVIEW_SHELL_PARAM = "previewShell";
95
+ var PREVIEW_PARENT_ORIGIN_PARAM = "parentOrigin";
96
+ var PREVIEW_BRIDGE_MESSAGE = {
97
+ /** frame → shell: the bridge mounted and is ready to sync. */
98
+ READY: "selfhelp-preview:ready",
99
+ /** frame → shell: the frame navigated to a new in-app location. */
100
+ NAVIGATED: "selfhelp-preview:navigated",
101
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
102
+ NAVIGATE: "selfhelp-preview:navigate",
103
+ /**
104
+ * shell → frame: apply the shared colour-scheme + language preferences (no
105
+ * reload), so the web pane and the mobile frame stay in the same theme/locale.
106
+ */
107
+ SET_PREFERENCES: "selfhelp-preview:set-preferences",
108
+ /** frame → shell: the user changed the colour scheme / language in the frame. */
109
+ PREFERENCES_CHANGED: "selfhelp-preview:preferences-changed"
110
+ };
111
+ function isPreviewPreferences(value) {
112
+ if (typeof value !== "object" || value === null) return false;
113
+ const record = value;
114
+ return (record.colorScheme === "light" || record.colorScheme === "dark" || record.colorScheme === "auto") && (typeof record.locale === "string" || record.locale === null);
115
+ }
116
+ function isPreviewBridgeMessage(value) {
117
+ if (typeof value !== "object" || value === null) return false;
118
+ const record = value;
119
+ switch (record.type) {
120
+ case PREVIEW_BRIDGE_MESSAGE.READY:
121
+ return record.source === "web" || record.source === "mobile";
122
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
123
+ return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string";
124
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
125
+ return typeof record.keyword === "string" || record.keyword === null;
126
+ case PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES:
127
+ return isPreviewPreferences(record.preferences);
128
+ case PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED:
129
+ return (record.source === "web" || record.source === "mobile") && isPreviewPreferences(record.preferences);
130
+ default:
131
+ return false;
132
+ }
133
+ }
134
+ function arePreviewPreferencesEqual(a, b) {
135
+ if (!a || !b) return false;
136
+ return a.colorScheme === b.colorScheme && a.locale === b.locale;
137
+ }
138
+ function previewKeywordFromPath(path) {
139
+ if (!path) return null;
140
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? "";
141
+ const trimmed = withoutQuery.replace(/^\/+/, "").replace(/\/+$/, "");
142
+ if (trimmed === "") return null;
143
+ try {
144
+ return decodeURIComponent(trimmed);
145
+ } catch {
146
+ return trimmed;
147
+ }
148
+ }
149
+
93
150
  // src/types/distribution.ts
94
151
  var RELEASE_CHANNELS = ["stable", "beta", "nightly", "test"];
95
152
 
@@ -1421,6 +1478,9 @@ export {
1421
1478
  LITERAL_CLASSES,
1422
1479
  MOBILE_PREVIEW_ENDPOINTS,
1423
1480
  PERMISSIONS,
1481
+ PREVIEW_BRIDGE_MESSAGE,
1482
+ PREVIEW_PARENT_ORIGIN_PARAM,
1483
+ PREVIEW_SHELL_PARAM,
1424
1484
  RADIUS_PX,
1425
1485
  RELEASE_CHANNELS,
1426
1486
  SIZE_VALUES,
@@ -1430,6 +1490,7 @@ export {
1430
1490
  STYLE_REGISTRY,
1431
1491
  SYSTEM_ENDPOINTS,
1432
1492
  _resetPluginStyleRegistry,
1493
+ arePreviewPreferencesEqual,
1433
1494
  buildConditionContext,
1434
1495
  classifyClass,
1435
1496
  classifyClassString,
@@ -1447,6 +1508,7 @@ export {
1447
1508
  gridSpanToReactNativeColumn,
1448
1509
  hasInlineFormatting,
1449
1510
  isKnownStyleName,
1511
+ isPreviewBridgeMessage,
1450
1512
  isRegisteredStyleName,
1451
1513
  isStyleAllowedOnPage,
1452
1514
  isStylePlacementAllowed,
@@ -1466,6 +1528,7 @@ export {
1466
1528
  parseDimensionToWeb,
1467
1529
  parseInlineRich,
1468
1530
  parseSpacing,
1531
+ previewKeywordFromPath,
1469
1532
  radiusToPx,
1470
1533
  replaceCalcedValues,
1471
1534
  resolveAssetSources,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.15.1",
3
+ "version": "1.15.3",
4
4
  "description": "Shared TypeScript package for SelfHelp web frontend and mobile app: style registry, types, API contracts, Mantine theme tokens, condition + interpolation engines, CMS class allow-list.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,185 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Live Preview bridge contract tests.
7
+ *
8
+ * The shell and both frame bridges trust `isPreviewBridgeMessage` to narrow
9
+ * arbitrary cross-frame `postMessage` data, and derive the cross-platform sync
10
+ * unit with `previewKeywordFromPath`. These lock both: a malformed/foreign
11
+ * message must be rejected, a well-formed one in either direction accepted, and
12
+ * web/mobile paths must reduce to the same keyword (so sync can't drift).
13
+ */
14
+ import { describe, expect, it } from 'vitest';
15
+ import {
16
+ PREVIEW_BRIDGE_MESSAGE,
17
+ arePreviewPreferencesEqual,
18
+ isPreviewBridgeMessage,
19
+ previewKeywordFromPath,
20
+ type TPreviewBridgeMessage,
21
+ } from '../preview-bridge';
22
+
23
+ describe('isPreviewBridgeMessage', () => {
24
+ it('accepts a frame->shell navigated message (the user clicked a link)', () => {
25
+ const msg: TPreviewBridgeMessage = {
26
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
27
+ source: 'web',
28
+ keyword: 'impressum',
29
+ href: '/impressum?previewShell=1',
30
+ locale: 'de-CH',
31
+ };
32
+ expect(isPreviewBridgeMessage(msg)).toBe(true);
33
+ });
34
+
35
+ it('accepts a navigated message for home (keyword null) and a ready message', () => {
36
+ expect(
37
+ isPreviewBridgeMessage({
38
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
39
+ source: 'mobile',
40
+ keyword: null,
41
+ href: '/',
42
+ }),
43
+ ).toBe(true);
44
+ expect(
45
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.READY, source: 'mobile' }),
46
+ ).toBe(true);
47
+ });
48
+
49
+ it('accepts a shell->frame navigate command (keyword or null)', () => {
50
+ expect(
51
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: 'team' }),
52
+ ).toBe(true);
53
+ expect(
54
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: null }),
55
+ ).toBe(true);
56
+ });
57
+
58
+ it('accepts a shell->frame set-preferences command (theme + locale)', () => {
59
+ const msg: TPreviewBridgeMessage = {
60
+ type: PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES,
61
+ preferences: { colorScheme: 'dark', locale: 'de-CH' },
62
+ };
63
+ expect(isPreviewBridgeMessage(msg)).toBe(true);
64
+ // `auto` scheme + unknown locale (null) is valid too.
65
+ expect(
66
+ isPreviewBridgeMessage({
67
+ type: PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES,
68
+ preferences: { colorScheme: 'auto', locale: null },
69
+ }),
70
+ ).toBe(true);
71
+ });
72
+
73
+ it('accepts a frame->shell preferences-changed message', () => {
74
+ const msg: TPreviewBridgeMessage = {
75
+ type: PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED,
76
+ source: 'mobile',
77
+ preferences: { colorScheme: 'light', locale: 'en-GB' },
78
+ };
79
+ expect(isPreviewBridgeMessage(msg)).toBe(true);
80
+ });
81
+
82
+ it('rejects preference messages with an invalid scheme or missing payload', () => {
83
+ // unknown colour scheme
84
+ expect(
85
+ isPreviewBridgeMessage({
86
+ type: PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES,
87
+ preferences: { colorScheme: 'sepia', locale: 'de-CH' },
88
+ }),
89
+ ).toBe(false);
90
+ // preferences-changed without a source
91
+ expect(
92
+ isPreviewBridgeMessage({
93
+ type: PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED,
94
+ preferences: { colorScheme: 'dark', locale: null },
95
+ }),
96
+ ).toBe(false);
97
+ // missing payload entirely
98
+ expect(
99
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES }),
100
+ ).toBe(false);
101
+ });
102
+
103
+ it('rejects foreign / malformed messages so cross-frame noise is ignored', () => {
104
+ expect(isPreviewBridgeMessage(null)).toBe(false);
105
+ expect(isPreviewBridgeMessage('selfhelp-preview:navigate')).toBe(false);
106
+ expect(isPreviewBridgeMessage({ type: 'webpack:hot-update' })).toBe(false);
107
+ // wrong source
108
+ expect(
109
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.READY, source: 'desktop' }),
110
+ ).toBe(false);
111
+ // navigated without href
112
+ expect(
113
+ isPreviewBridgeMessage({
114
+ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATED,
115
+ source: 'web',
116
+ keyword: 'x',
117
+ }),
118
+ ).toBe(false);
119
+ // navigate with a non-string keyword
120
+ expect(
121
+ isPreviewBridgeMessage({ type: PREVIEW_BRIDGE_MESSAGE.NAVIGATE, keyword: 5 }),
122
+ ).toBe(false);
123
+ });
124
+ });
125
+
126
+ describe('arePreviewPreferencesEqual (loop guard)', () => {
127
+ it('treats same scheme + locale as equal so an echo is skipped', () => {
128
+ expect(
129
+ arePreviewPreferencesEqual(
130
+ { colorScheme: 'dark', locale: 'de-CH' },
131
+ { colorScheme: 'dark', locale: 'de-CH' },
132
+ ),
133
+ ).toBe(true);
134
+ expect(
135
+ arePreviewPreferencesEqual(
136
+ { colorScheme: 'auto', locale: null },
137
+ { colorScheme: 'auto', locale: null },
138
+ ),
139
+ ).toBe(true);
140
+ });
141
+
142
+ it('treats a differing scheme or locale as not equal so the change propagates', () => {
143
+ expect(
144
+ arePreviewPreferencesEqual(
145
+ { colorScheme: 'dark', locale: 'de-CH' },
146
+ { colorScheme: 'light', locale: 'de-CH' },
147
+ ),
148
+ ).toBe(false);
149
+ expect(
150
+ arePreviewPreferencesEqual(
151
+ { colorScheme: 'dark', locale: 'de-CH' },
152
+ { colorScheme: 'dark', locale: 'en-GB' },
153
+ ),
154
+ ).toBe(false);
155
+ });
156
+
157
+ it('treats a null/undefined side as not equal (no last value yet → always emit)', () => {
158
+ const prefs = { colorScheme: 'light', locale: 'en-GB' } as const;
159
+ expect(arePreviewPreferencesEqual(null, prefs)).toBe(false);
160
+ expect(arePreviewPreferencesEqual(prefs, undefined)).toBe(false);
161
+ expect(arePreviewPreferencesEqual(null, null)).toBe(false);
162
+ });
163
+ });
164
+
165
+ describe('previewKeywordFromPath', () => {
166
+ it('reduces web and mobile paths to the same keyword (no drift)', () => {
167
+ expect(previewKeywordFromPath('/impressum')).toBe('impressum');
168
+ expect(previewKeywordFromPath('impressum')).toBe('impressum');
169
+ expect(previewKeywordFromPath('/impressum/')).toBe('impressum');
170
+ expect(previewKeywordFromPath('/impressum?previewShell=1')).toBe('impressum');
171
+ expect(previewKeywordFromPath('/impressum#section')).toBe('impressum');
172
+ });
173
+
174
+ it('treats home / empty as null (the shared "home" sentinel)', () => {
175
+ expect(previewKeywordFromPath('/')).toBeNull();
176
+ expect(previewKeywordFromPath('')).toBeNull();
177
+ expect(previewKeywordFromPath(null)).toBeNull();
178
+ expect(previewKeywordFromPath(undefined)).toBeNull();
179
+ });
180
+
181
+ it('keeps multi-segment keywords and decodes percent-encoding', () => {
182
+ expect(previewKeywordFromPath('/projects/alpha')).toBe('projects/alpha');
183
+ expect(previewKeywordFromPath('/caf%C3%A9')).toBe('café');
184
+ });
185
+ });
@@ -15,6 +15,7 @@ export * from './styles/unknown';
15
15
  export * from './pages';
16
16
  export * from './auth';
17
17
  export * from './api';
18
+ export * from './preview-bridge';
18
19
  export * from './distribution';
19
20
  export * from './mantine/common';
20
21
  export * from './mobile-adapters';
@@ -0,0 +1,223 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Live Preview bridge contract — the `postMessage` protocol between the CMS
7
+ * **Live Preview** shell (the admin page that embeds the previews) and the two
8
+ * embedded preview frames (the web frontend and the `selfhelp-mobile-preview`
9
+ * web image).
10
+ *
11
+ * The shell owns the canonical preview page. Each frame runs a small bridge that
12
+ * (a) reports its in-app navigations up to the shell and (b) accepts a
13
+ * "navigate to keyword" command down from the shell, so clicking a link in one
14
+ * frame keeps the other frame on the same page. The same channel also carries
15
+ * the shared colour-scheme + language preferences both ways (SET_PREFERENCES
16
+ * down, PREFERENCES_CHANGED up) so the two panes stay in the same theme/locale.
17
+ * The shell prevents sync loops with a per-frame "expected value" guard (it
18
+ * ignores the echo of a command it just sent). See the frontend `LivePreview`
19
+ * shell + `PreviewShellBridge` and the mobile `PreviewSyncBridge`.
20
+ *
21
+ * This module is the SINGLE SOURCE OF TRUTH for the message `type` strings, the
22
+ * activation/origin query-param names, the payload shapes, and the runtime type
23
+ * guard, so the shell and both bridges cannot drift. It is a pure contract: no
24
+ * DOM / window access lives here (each app reads `window`/`postMessage` itself).
25
+ *
26
+ * Security: messages are validated by `event.origin` on both ends (the shell
27
+ * allow-lists its own origin for the web frame and the mobile origin for the
28
+ * mobile frame; each frame trusts only the shell origin it was handed via
29
+ * {@link PREVIEW_PARENT_ORIGIN_PARAM}). Never post these with `'*'`.
30
+ */
31
+
32
+ /** Which embedded preview frame a bridge message refers to. */
33
+ export type TPreviewFrameSource = 'web' | 'mobile';
34
+
35
+ /**
36
+ * Three-way colour-scheme choice, shared VERBATIM across both panes — it maps
37
+ * 1:1 onto the web's Mantine `useMantineColorScheme` and the mobile theme store
38
+ * (`'auto'` = follow the OS on both).
39
+ */
40
+ export type TPreviewColorScheme = 'light' | 'dark' | 'auto';
41
+
42
+ /**
43
+ * The shared, cross-pane preview preferences. `locale` (e.g. `de-CH`) is the
44
+ * cross-platform language key — each pane maps it to its own language id from
45
+ * its languages list; `null` means "unknown / leave as-is". Carried by both the
46
+ * shell→frame {@link IPreviewSetPreferencesCommand} and the frame→shell
47
+ * {@link IPreviewPreferencesChangedMessage} so theme + language stay in sync.
48
+ */
49
+ export interface IPreviewPreferences {
50
+ colorScheme: TPreviewColorScheme;
51
+ locale: string | null;
52
+ }
53
+
54
+ /**
55
+ * Query param the shell appends to a frame URL to ACTIVATE its bridge
56
+ * (`previewShell=1`). Absent (normal public browsing) → the bridge stays dormant
57
+ * so a real visitor never posts navigation messages.
58
+ */
59
+ export const PREVIEW_SHELL_PARAM = 'previewShell';
60
+
61
+ /**
62
+ * Query param carrying the shell's `window.location.origin` so a (possibly
63
+ * cross-origin) frame can target its `postMessage` precisely instead of `'*'`.
64
+ */
65
+ export const PREVIEW_PARENT_ORIGIN_PARAM = 'parentOrigin';
66
+
67
+ /**
68
+ * Message `type` discriminators. Namespaced (`selfhelp-preview:`) so they never
69
+ * collide with other `postMessage` traffic (HMR, analytics, embeds).
70
+ */
71
+ export const PREVIEW_BRIDGE_MESSAGE = {
72
+ /** frame → shell: the bridge mounted and is ready to sync. */
73
+ READY: 'selfhelp-preview:ready',
74
+ /** frame → shell: the frame navigated to a new in-app location. */
75
+ NAVIGATED: 'selfhelp-preview:navigated',
76
+ /** shell → frame: navigate the frame to a CMS keyword (soft, no reload). */
77
+ NAVIGATE: 'selfhelp-preview:navigate',
78
+ /**
79
+ * shell → frame: apply the shared colour-scheme + language preferences (no
80
+ * reload), so the web pane and the mobile frame stay in the same theme/locale.
81
+ */
82
+ SET_PREFERENCES: 'selfhelp-preview:set-preferences',
83
+ /** frame → shell: the user changed the colour scheme / language in the frame. */
84
+ PREFERENCES_CHANGED: 'selfhelp-preview:preferences-changed',
85
+ } as const;
86
+
87
+ export type TPreviewBridgeMessageType =
88
+ (typeof PREVIEW_BRIDGE_MESSAGE)[keyof typeof PREVIEW_BRIDGE_MESSAGE];
89
+
90
+ /** frame → shell: emitted once when the bridge mounts. */
91
+ export interface IPreviewReadyMessage {
92
+ type: typeof PREVIEW_BRIDGE_MESSAGE.READY;
93
+ source: TPreviewFrameSource;
94
+ }
95
+
96
+ /**
97
+ * frame → shell: the frame moved to a new page. `keyword` is the CMS keyword of
98
+ * the current page (the cross-platform sync unit), or `null` for home / a
99
+ * non-CMS location. `locale` is the frame's active locale when known (a toolbar
100
+ * indicator); active cross-pane language sync rides {@link PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED}.
101
+ */
102
+ export interface IPreviewNavigatedMessage {
103
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATED;
104
+ source: TPreviewFrameSource;
105
+ keyword: string | null;
106
+ /** Full in-frame href, for diagnostics / the toolbar URL display. */
107
+ href: string;
108
+ locale?: string | null;
109
+ }
110
+
111
+ /**
112
+ * shell → frame: navigate to `keyword` (the canonical page). `null`/empty =
113
+ * home. The frame performs a SOFT client-side navigation (no reload), so app
114
+ * state and the embedded dev client are preserved.
115
+ */
116
+ export interface IPreviewNavigateCommand {
117
+ type: typeof PREVIEW_BRIDGE_MESSAGE.NAVIGATE;
118
+ keyword: string | null;
119
+ }
120
+
121
+ /**
122
+ * shell → frame: apply the shared colour-scheme + language {@link IPreviewPreferences}
123
+ * with NO reload, so a theme/language change in one pane (or the toolbar) is
124
+ * mirrored in the other. Idempotent — re-applying the current values is a no-op.
125
+ */
126
+ export interface IPreviewSetPreferencesCommand {
127
+ type: typeof PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES;
128
+ preferences: IPreviewPreferences;
129
+ }
130
+
131
+ /**
132
+ * frame → shell: the user changed the colour scheme and/or language inside the
133
+ * frame; the shell applies it to the other pane. The shell guards against the
134
+ * echo of a value it just pushed so the two panes never ping-pong.
135
+ */
136
+ export interface IPreviewPreferencesChangedMessage {
137
+ type: typeof PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED;
138
+ source: TPreviewFrameSource;
139
+ preferences: IPreviewPreferences;
140
+ }
141
+
142
+ /** Every message that can cross the preview bridge, in either direction. */
143
+ export type TPreviewBridgeMessage =
144
+ | IPreviewReadyMessage
145
+ | IPreviewNavigatedMessage
146
+ | IPreviewNavigateCommand
147
+ | IPreviewSetPreferencesCommand
148
+ | IPreviewPreferencesChangedMessage;
149
+
150
+ /** Runtime guard for the shared preferences payload. */
151
+ function isPreviewPreferences(value: unknown): value is IPreviewPreferences {
152
+ if (typeof value !== 'object' || value === null) return false;
153
+ const record = value as Record<string, unknown>;
154
+ return (
155
+ (record.colorScheme === 'light' ||
156
+ record.colorScheme === 'dark' ||
157
+ record.colorScheme === 'auto') &&
158
+ (typeof record.locale === 'string' || record.locale === null)
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Runtime guard: is `value` a well-formed preview-bridge message? Use it on the
164
+ * receiving end of a `message` event (AFTER the `event.origin` allow-list check)
165
+ * to safely narrow `event.data`. Defensive against arbitrary cross-frame noise.
166
+ */
167
+ export function isPreviewBridgeMessage(value: unknown): value is TPreviewBridgeMessage {
168
+ if (typeof value !== 'object' || value === null) return false;
169
+ const record = value as Record<string, unknown>;
170
+ switch (record.type) {
171
+ case PREVIEW_BRIDGE_MESSAGE.READY:
172
+ return record.source === 'web' || record.source === 'mobile';
173
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
174
+ return (
175
+ (record.source === 'web' || record.source === 'mobile') &&
176
+ (typeof record.keyword === 'string' || record.keyword === null) &&
177
+ typeof record.href === 'string'
178
+ );
179
+ case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
180
+ return typeof record.keyword === 'string' || record.keyword === null;
181
+ case PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES:
182
+ return isPreviewPreferences(record.preferences);
183
+ case PREVIEW_BRIDGE_MESSAGE.PREFERENCES_CHANGED:
184
+ return (
185
+ (record.source === 'web' || record.source === 'mobile') &&
186
+ isPreviewPreferences(record.preferences)
187
+ );
188
+ default:
189
+ return false;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Loop-guard equality for the shared preferences. Both bridges keep the last
195
+ * value they pushed to / received from the other pane and skip re-emitting (or
196
+ * re-applying) an equal one, so a theme/language change never ping-pongs. Shared
197
+ * so the two panes compare preferences identically.
198
+ */
199
+ export function arePreviewPreferencesEqual(
200
+ a: IPreviewPreferences | null | undefined,
201
+ b: IPreviewPreferences | null | undefined,
202
+ ): boolean {
203
+ if (!a || !b) return false;
204
+ return a.colorScheme === b.colorScheme && a.locale === b.locale;
205
+ }
206
+
207
+ /**
208
+ * Normalize an in-app path to its CMS keyword (the sync unit): strip the leading
209
+ * slash and any query/hash, decode segments; an empty path (home) → `null`.
210
+ * Shared so the web and mobile bridges derive identical keywords from their
211
+ * respective routers.
212
+ */
213
+ export function previewKeywordFromPath(path: string | null | undefined): string | null {
214
+ if (!path) return null;
215
+ const withoutQuery = path.split(/[?#]/, 1)[0] ?? '';
216
+ const trimmed = withoutQuery.replace(/^\/+/, '').replace(/\/+$/, '');
217
+ if (trimmed === '') return null;
218
+ try {
219
+ return decodeURIComponent(trimmed);
220
+ } catch {
221
+ return trimmed;
222
+ }
223
+ }