@histoire/sdk 0.0.0-stage → 1.0.0-beta.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.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/types.d.ts +152 -0
  3. package/dist/adapters/types.d.ts.map +1 -0
  4. package/dist/adapters/types.js +1 -0
  5. package/dist/index.d.ts +6 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +19 -0
  8. package/dist/internal.d.ts +16 -0
  9. package/dist/internal.d.ts.map +1 -0
  10. package/dist/internal.js +8 -0
  11. package/dist/mounts/channel.d.ts +20 -0
  12. package/dist/mounts/channel.d.ts.map +1 -0
  13. package/dist/mounts/channel.js +76 -0
  14. package/dist/mounts/events.d.ts +9 -0
  15. package/dist/mounts/events.d.ts.map +1 -0
  16. package/dist/mounts/events.js +45 -0
  17. package/dist/mounts/geometry.d.ts +9 -0
  18. package/dist/mounts/geometry.d.ts.map +1 -0
  19. package/dist/mounts/geometry.js +69 -0
  20. package/dist/mounts/handle.d.ts +5 -0
  21. package/dist/mounts/handle.d.ts.map +1 -0
  22. package/dist/mounts/handle.js +44 -0
  23. package/dist/mounts/iframe.d.ts +4 -0
  24. package/dist/mounts/iframe.d.ts.map +1 -0
  25. package/dist/mounts/iframe.js +143 -0
  26. package/dist/mounts/overlay.d.ts +11 -0
  27. package/dist/mounts/overlay.d.ts.map +1 -0
  28. package/dist/mounts/overlay.js +53 -0
  29. package/dist/mounts/view-snapshot.d.ts +4 -0
  30. package/dist/mounts/view-snapshot.d.ts.map +1 -0
  31. package/dist/mounts/view-snapshot.js +24 -0
  32. package/dist/persistence/key.d.ts +3 -0
  33. package/dist/persistence/key.d.ts.map +1 -0
  34. package/dist/persistence/key.js +4 -0
  35. package/dist/persistence/storage.d.ts +13 -0
  36. package/dist/persistence/storage.d.ts.map +1 -0
  37. package/dist/persistence/storage.js +37 -0
  38. package/dist/session/channels.d.ts +8 -0
  39. package/dist/session/channels.d.ts.map +1 -0
  40. package/dist/session/channels.js +117 -0
  41. package/dist/session/context.d.ts +97 -0
  42. package/dist/session/context.d.ts.map +1 -0
  43. package/dist/session/context.js +136 -0
  44. package/dist/session/controller.d.ts +5 -0
  45. package/dist/session/controller.d.ts.map +1 -0
  46. package/dist/session/controller.js +217 -0
  47. package/dist/session/debug-lease.d.ts +5 -0
  48. package/dist/session/debug-lease.d.ts.map +1 -0
  49. package/dist/session/debug-lease.js +64 -0
  50. package/dist/session/debug.d.ts +14 -0
  51. package/dist/session/debug.d.ts.map +1 -0
  52. package/dist/session/debug.js +242 -0
  53. package/dist/session/events.d.ts +7 -0
  54. package/dist/session/events.d.ts.map +1 -0
  55. package/dist/session/events.js +23 -0
  56. package/dist/session/inspection.d.ts +5 -0
  57. package/dist/session/inspection.d.ts.map +1 -0
  58. package/dist/session/inspection.js +88 -0
  59. package/dist/session/internal.d.ts +87 -0
  60. package/dist/session/internal.d.ts.map +1 -0
  61. package/dist/session/internal.js +144 -0
  62. package/dist/session/mounts.d.ts +6 -0
  63. package/dist/session/mounts.d.ts.map +1 -0
  64. package/dist/session/mounts.js +153 -0
  65. package/dist/session/notifications.d.ts +5 -0
  66. package/dist/session/notifications.d.ts.map +1 -0
  67. package/dist/session/notifications.js +143 -0
  68. package/dist/session/ownership.d.ts +20 -0
  69. package/dist/session/ownership.d.ts.map +1 -0
  70. package/dist/session/ownership.js +69 -0
  71. package/dist/session/plugin-hub.d.ts +59 -0
  72. package/dist/session/plugin-hub.d.ts.map +1 -0
  73. package/dist/session/plugin-hub.js +215 -0
  74. package/dist/session/plugins.d.ts +8 -0
  75. package/dist/session/plugins.d.ts.map +1 -0
  76. package/dist/session/plugins.js +78 -0
  77. package/dist/session/request.d.ts +8 -0
  78. package/dist/session/request.d.ts.map +1 -0
  79. package/dist/session/request.js +99 -0
  80. package/dist/session/runtime.d.ts +5 -0
  81. package/dist/session/runtime.d.ts.map +1 -0
  82. package/dist/session/runtime.js +25 -0
  83. package/dist/session/selection.d.ts +9 -0
  84. package/dist/session/selection.d.ts.map +1 -0
  85. package/dist/session/selection.js +111 -0
  86. package/dist/session/services.d.ts +18 -0
  87. package/dist/session/services.d.ts.map +1 -0
  88. package/dist/session/services.js +51 -0
  89. package/dist/session/settings.d.ts +7 -0
  90. package/dist/session/settings.d.ts.map +1 -0
  91. package/dist/session/settings.js +31 -0
  92. package/dist/session/snapshot.d.ts +12 -0
  93. package/dist/session/snapshot.d.ts.map +1 -0
  94. package/dist/session/snapshot.js +72 -0
  95. package/dist/session/state.d.ts +11 -0
  96. package/dist/session/state.d.ts.map +1 -0
  97. package/dist/session/state.js +73 -0
  98. package/dist/session/variant.d.ts +4 -0
  99. package/dist/session/variant.d.ts.map +1 -0
  100. package/dist/session/variant.js +11 -0
  101. package/dist/transport/authority.d.ts +35 -0
  102. package/dist/transport/authority.d.ts.map +1 -0
  103. package/dist/transport/authority.js +110 -0
  104. package/dist/transport/connection.d.ts +4 -0
  105. package/dist/transport/connection.d.ts.map +1 -0
  106. package/dist/transport/connection.js +37 -0
  107. package/dist/transport/handshake.d.ts +36 -0
  108. package/dist/transport/handshake.d.ts.map +1 -0
  109. package/dist/transport/handshake.js +112 -0
  110. package/dist/transport/inbound.d.ts +15 -0
  111. package/dist/transport/inbound.d.ts.map +1 -0
  112. package/dist/transport/inbound.js +51 -0
  113. package/dist/transport/port.d.ts +51 -0
  114. package/dist/transport/port.d.ts.map +1 -0
  115. package/dist/transport/port.js +288 -0
  116. package/dist/transport/reply.d.ts +6 -0
  117. package/dist/transport/reply.d.ts.map +1 -0
  118. package/dist/transport/reply.js +44 -0
  119. package/dist/transport/requests.d.ts +33 -0
  120. package/dist/transport/requests.d.ts.map +1 -0
  121. package/dist/transport/requests.js +62 -0
  122. package/dist/transport/session-commands.d.ts +5 -0
  123. package/dist/transport/session-commands.d.ts.map +1 -0
  124. package/dist/transport/session-commands.js +70 -0
  125. package/dist/transport/validated.d.ts +13 -0
  126. package/dist/transport/validated.d.ts.map +1 -0
  127. package/dist/transport/validated.js +22 -0
  128. package/dist/transport/validation.d.ts +8 -0
  129. package/dist/transport/validation.d.ts.map +1 -0
  130. package/dist/transport/validation.js +20 -0
  131. package/dist/types.d.ts +143 -0
  132. package/dist/types.d.ts.map +1 -0
  133. package/dist/types.js +1 -0
  134. package/package.json +38 -3
  135. package/README.md +0 -3
@@ -0,0 +1,143 @@
1
+ import { HistoireSdkError } from '@histoire/protocol';
2
+ import { createBridgeFrame } from '../transport/handshake.js';
3
+ import { createBridgePort } from '../transport/port.js';
4
+ import { dispatchHistoireSessionCommand } from '../transport/session-commands.js';
5
+ import { getBridgeSurfaceRole } from '../transport/validation.js';
6
+ import { createMountEventStream } from './events.js';
7
+ import { createMountGeometry } from './geometry.js';
8
+ import { waitBridgeRuntime } from './handle.js';
9
+ import { createMountOverlay } from './overlay.js';
10
+ import { createMountViewSnapshot } from './view-snapshot.js';
11
+ /** Own iframe and optional hidden container; caller session always stays local. */
12
+ export function mountRemoteSurface(context) {
13
+ if (context.container && (!context.container.ownerDocument || context.container.nodeType !== 1 || typeof context.container.append !== 'function')) {
14
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Surface container must be browser element');
15
+ }
16
+ const document = context.container?.ownerDocument ?? globalThis.document;
17
+ if (!document?.body) {
18
+ throw new HistoireSdkError('BROWSER_REQUIRED', 'Surface requires browser document');
19
+ }
20
+ const hidden = context.hidden ? document.createElement('div') : undefined;
21
+ if (hidden) {
22
+ // Browsers throttle requestAnimationFrame in far-offscreen child frames,
23
+ // preventing framework readiness. A transparent, non-interactive viewport
24
+ // keeps real layout and frame scheduling while contributing no visible UI.
25
+ hidden.style.cssText = `position:fixed;left:0;top:0;opacity:0;z-index:-2147483647;width:${context.settings.responsiveWidth}px;height:${context.settings.responsiveHeight ?? 560}px;overflow:hidden;pointer-events:none`;
26
+ hidden.setAttribute('aria-hidden', 'true');
27
+ document.body.append(hidden);
28
+ }
29
+ const container = context.container ?? hidden;
30
+ if (!container) {
31
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Surface container required');
32
+ }
33
+ const abort = new AbortController();
34
+ const role = getBridgeSurfaceRole(context.surface);
35
+ let bridge;
36
+ let off = () => {
37
+ };
38
+ let stopEvents = () => { };
39
+ let active = true;
40
+ let customOnly = false;
41
+ const projectSnapshot = createMountViewSnapshot(context.surface);
42
+ const listeners = new Set();
43
+ const publications = new Set();
44
+ let synchronize = () => { };
45
+ const source = context.session.getSnapshot().source;
46
+ const id = `${context.mountId}:connection`;
47
+ const frame = createBridgeFrame({ url: source.url, sessionId: context.sessionId, mountId: context.mountId, surface: context.surface, presentation: context.presentation, padding: context.padding, role, container, signal: abort.signal, disconnected: () => {
48
+ bridge?.disconnect();
49
+ close();
50
+ } });
51
+ if (hidden)
52
+ frame.iframe.tabIndex = -1;
53
+ const geometry = createMountGeometry(frame.iframe, container, (value) => {
54
+ for (const listener of listeners)
55
+ listener(value);
56
+ });
57
+ const overlay = createMountOverlay(frame.iframe, (event) => {
58
+ for (const listener of publications)
59
+ listener(event);
60
+ });
61
+ const connected = frame.ready.then(({ port, ack }) => {
62
+ if (!active) {
63
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Surface detached');
64
+ }
65
+ if (ack.owner.connectionId !== id) {
66
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Mismatched surface port identity');
67
+ }
68
+ bridge = createBridgePort({ port, owner: ack.owner, role, descriptor: ack.descriptor, dispatch: (request, signal) => dispatchHistoireSessionCommand(context.session, request.command, request.payload, request, signal), publication: event => overlay.receive(event) });
69
+ bridge.subscribe((value) => {
70
+ const projected = geometry.receive(value);
71
+ for (const listener of listeners) {
72
+ listener(projected);
73
+ }
74
+ // Data and mount ports receive publication independently. Resynchronize
75
+ // once this port owns the new revision, after an earlier intent was stale.
76
+ if (value.type === 'catalog')
77
+ synchronize();
78
+ });
79
+ return bridge;
80
+ });
81
+ const ready = connected.then(async (endpoint) => {
82
+ // Empty/docs-only selection has view readiness but owns no story document.
83
+ const runtimeReady = role === 'primary' && context.target?.variantId != null ? waitBridgeRuntime(endpoint, abort.signal, context.source.descriptor.config?.storyCollectTimeout ?? 30_000) : undefined;
84
+ /** Parent snapshot is sole selection/settings controller; event history streams separately. */
85
+ synchronize = () => {
86
+ const snapshot = context.session.getSnapshot();
87
+ if (snapshot.status !== 'ready' || !active) {
88
+ return;
89
+ }
90
+ const owner = endpoint.getOwner();
91
+ void endpoint.request('view.sync', projectSnapshot(snapshot), { ...owner, signal: abort.signal }).catch(() => {
92
+ });
93
+ };
94
+ off = context.session.subscribe(synchronize);
95
+ const snapshot = context.session.getSnapshot();
96
+ if (role === 'controls')
97
+ await endpoint.request('controls.configure', { customOnly }, { ...endpoint.getOwner(), signal: abort.signal });
98
+ await endpoint.request('view.sync', projectSnapshot(snapshot), { ...endpoint.getOwner(), signal: abort.signal });
99
+ stopEvents = createMountEventStream(context.session, (payload, owner) => endpoint.post('events.appended', payload, owner));
100
+ return runtimeReady ? await runtimeReady : undefined;
101
+ });
102
+ void ready.catch(() => {
103
+ });
104
+ /** Mark inactive and abort all readiness/requests before releasing owned elements. */
105
+ function close() {
106
+ if (!active) {
107
+ return;
108
+ }
109
+ active = false;
110
+ abort.abort();
111
+ off();
112
+ stopEvents();
113
+ bridge?.close();
114
+ geometry.close();
115
+ overlay.close();
116
+ frame.close();
117
+ hidden?.remove();
118
+ listeners.clear();
119
+ publications.clear();
120
+ }
121
+ return { id, ready, ...(['controls', 'primary'].includes(role)
122
+ ? { channel: {
123
+ configure(value) { customOnly = value; },
124
+ subscribe(listener) {
125
+ publications.add(listener);
126
+ return () => {
127
+ publications.delete(listener);
128
+ };
129
+ },
130
+ post(event, payload) {
131
+ overlay.clear();
132
+ const snapshot = context.session.getSnapshot();
133
+ if (active && snapshot.runtime.runtimeId && snapshot.selection)
134
+ bridge?.post(event, payload, { runtimeId: snapshot.runtime.runtimeId, target: snapshot.selection });
135
+ },
136
+ } }
137
+ : {}), request: async (command, payload, capture) => (await connected).request(command, payload, capture), subscribe(listener) {
138
+ listeners.add(listener);
139
+ return () => {
140
+ listeners.delete(listener);
141
+ };
142
+ }, close };
143
+ }
@@ -0,0 +1,11 @@
1
+ import type { HistoireBridgePublication } from '@histoire/protocol';
2
+ /** Project source-local opaque anchors through outer frame without child DOM access. */
3
+ export declare function createMountOverlay(iframe: HTMLIFrameElement, publish: (event: HistoireBridgePublication) => void): {
4
+ /** Replacing/closing overlays retires retained geometry before notification. */
5
+ receive(event: HistoireBridgePublication): void;
6
+ /** Parent result closes geometry immediately; stale refresh cannot reopen listbox. */
7
+ clear(): void;
8
+ /** Stop every host geometry callback before attachment disappears. */
9
+ close(): void;
10
+ };
11
+ //# sourceMappingURL=overlay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../src/mounts/overlay.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAA;AAGnE,wFAAwF;AACxF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,yBAAyB,KAAK,IAAI;IA0B7G,gFAAgF;IAChF,OAAO,QAAQ,yBAAyB,GAAG,IAAI;IAK/C,sFAAsF;IACtF,KAAK,IAAI,IAAI;IACb,sEAAsE;IACtE,KAAK,IAAI,IAAI;EAShB"}
@@ -0,0 +1,53 @@
1
+ import { mapRuntimeViewport } from '@histoire/protocol';
2
+ /** Project source-local opaque anchors through outer frame without child DOM access. */
3
+ export function createMountOverlay(iframe, publish) {
4
+ const window = iframe.ownerDocument.defaultView;
5
+ let active = true;
6
+ let last;
7
+ let scheduled = 0;
8
+ /** Only anchor rectangle is mapped; callback/value payload never crosses this boundary. */
9
+ function project(event) {
10
+ const payload = event.payload;
11
+ if (!payload.anchor || !event.target)
12
+ return event;
13
+ const rect = iframe.getBoundingClientRect();
14
+ const mapped = mapRuntimeViewport({ ...payload.anchor, target: event.target, visibleRect: payload.anchor, scale: 1 }, rect, { width: iframe.clientWidth || 1, height: iframe.clientHeight || 1 }, { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight });
15
+ return mapped ? { ...event, payload: { ...payload, anchor: mapped.visibleRect } } : { ...event, event: 'overlay.close', payload: { id: payload.id } };
16
+ }
17
+ /** Host scrolling/resizing recomputes same captured document's retained anchor. */
18
+ function refresh() {
19
+ if (!active || !last || scheduled)
20
+ return;
21
+ scheduled = window.requestAnimationFrame(() => {
22
+ scheduled = 0;
23
+ if (active && last)
24
+ publish(project({ ...last, event: 'overlay.update' }));
25
+ });
26
+ }
27
+ const resize = new ResizeObserver(refresh);
28
+ resize.observe(iframe);
29
+ window.addEventListener('resize', refresh);
30
+ iframe.ownerDocument.addEventListener('scroll', refresh, true);
31
+ return {
32
+ /** Replacing/closing overlays retires retained geometry before notification. */
33
+ receive(event) {
34
+ if (event.event === 'overlay.open' || event.event === 'overlay.update')
35
+ last = event;
36
+ else if (event.event === 'overlay.close' || event.event === 'readiness.changed')
37
+ last = undefined;
38
+ if (active)
39
+ publish(project(event));
40
+ },
41
+ /** Parent result closes geometry immediately; stale refresh cannot reopen listbox. */
42
+ clear() { last = undefined; },
43
+ /** Stop every host geometry callback before attachment disappears. */
44
+ close() {
45
+ active = false;
46
+ last = undefined;
47
+ window.cancelAnimationFrame(scheduled);
48
+ resize.disconnect();
49
+ window.removeEventListener('resize', refresh);
50
+ iframe.ownerDocument.removeEventListener('scroll', refresh, true);
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,4 @@
1
+ import type { HistoireReadonly, HistoireSnapshot, HistoireSurface } from '@histoire/protocol';
2
+ /** Own latest view metadata projection for one mount; host catalog remains complete. */
3
+ export declare function createMountViewSnapshot(surface: HistoireSurface): (snapshot: HistoireReadonly<HistoireSnapshot>) => HistoireReadonly<HistoireSnapshot>;
4
+ //# sourceMappingURL=view-snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-snapshot.d.ts","sourceRoot":"","sources":["../../src/mounts/view-snapshot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAE9G,wFAAwF;AACxF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,eAAe,cAO5C,gBAAgB,CAAC,gBAAgB,CAAC,KAAG,gBAAgB,CAAC,gBAAgB,CAAC,CAgB1F"}
@@ -0,0 +1,24 @@
1
+ /** Own latest view metadata projection for one mount; host catalog remains complete. */
2
+ export function createMountViewSnapshot(surface) {
3
+ const runtimeOnly = surface === 'preview';
4
+ let previousCatalog;
5
+ let previousStoryId;
6
+ let projectedCatalog;
7
+ /** Runtime frames need selected story's complete variant registry, never unrelated navigation. */
8
+ return (snapshot) => {
9
+ const storyId = snapshot.selection?.storyId ?? null;
10
+ let catalog = snapshot.catalog;
11
+ if (runtimeOnly) {
12
+ // Immutable catalog publication replaces its reference. State/layout ACKs
13
+ // and same-story selections reuse this mount's metadata in O(1).
14
+ if (previousCatalog !== catalog || previousStoryId !== storyId) {
15
+ previousCatalog = catalog;
16
+ previousStoryId = storyId;
17
+ projectedCatalog = { ...catalog, stories: catalog.stories.filter(story => story.id === storyId), tree: [] };
18
+ }
19
+ // Keep all matches so malformed duplicate IDs cannot become valid actors.
20
+ catalog = projectedCatalog;
21
+ }
22
+ return { ...snapshot, catalog, events: { items: [], droppedCount: snapshot.events.droppedCount } };
23
+ };
24
+ }
@@ -0,0 +1,3 @@
1
+ /** Preference namespace contains full normalized source and explicit caller key. */
2
+ export declare function getHistoirePersistenceKey(url: string, key: string): string;
3
+ //# sourceMappingURL=key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key.d.ts","sourceRoot":"","sources":["../../src/persistence/key.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAE1E"}
@@ -0,0 +1,4 @@
1
+ /** Preference namespace contains full normalized source and explicit caller key. */
2
+ export function getHistoirePersistenceKey(url, key) {
3
+ return `histoire:sdk:v1:${encodeURIComponent(url)}:${encodeURIComponent(key)}`;
4
+ }
@@ -0,0 +1,13 @@
1
+ import type { HistoireSettings } from '@histoire/protocol';
2
+ import type { HistoirePreferenceStorage } from '../adapters/types.js';
3
+ /** Lazy browser access occurs only after explicit persistence opt-in. */
4
+ declare function browserStorage(): HistoirePreferenceStorage | undefined;
5
+ /** Source-scoped settings persistence; failures retain in-memory preferences. */
6
+ export declare function createSettingsPersistence(url: string, key?: string, storage?: typeof browserStorage): {
7
+ /** Read once during explicit connect; denied/malformed data never blocks it. */
8
+ read(): Partial<HistoireSettings>;
9
+ /** Write only validated host-owned settings; no state or events persisted. */
10
+ write(settings: HistoireSettings): void;
11
+ };
12
+ export {};
13
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../../src/persistence/storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AAIrE,yEAAyE;AACzE,iBAAS,cAAc,IAAI,yBAAyB,GAAG,SAAS,CAE/D;AAED,iFAAiF;AACjF,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,OAAO,wBAAiB;IAIzF,gFAAgF;IAChF,IAAI,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAWjC,8EAA8E;IAC9E,KAAK,WAAW,gBAAgB,GAAG,IAAI;EAQ1C"}
@@ -0,0 +1,37 @@
1
+ import { validateSettingsPatch } from '@histoire/protocol';
2
+ import { getHistoirePersistenceKey } from './key.js';
3
+ /** Lazy browser access occurs only after explicit persistence opt-in. */
4
+ function browserStorage() {
5
+ return typeof window === 'undefined' ? undefined : window.localStorage;
6
+ }
7
+ /** Source-scoped settings persistence; failures retain in-memory preferences. */
8
+ export function createSettingsPersistence(url, key, storage = browserStorage) {
9
+ let disabled = key === undefined;
10
+ const namespace = key === undefined ? '' : getHistoirePersistenceKey(url, key);
11
+ return {
12
+ /** Read once during explicit connect; denied/malformed data never blocks it. */
13
+ read() {
14
+ if (disabled)
15
+ return {};
16
+ try {
17
+ const saved = storage()?.getItem(namespace);
18
+ return saved ? validateSettingsPatch(JSON.parse(saved)) : {};
19
+ }
20
+ catch {
21
+ disabled = true;
22
+ return {};
23
+ }
24
+ },
25
+ /** Write only validated host-owned settings; no state or events persisted. */
26
+ write(settings) {
27
+ if (disabled)
28
+ return;
29
+ try {
30
+ storage()?.setItem(namespace, JSON.stringify(settings));
31
+ }
32
+ catch {
33
+ disabled = true;
34
+ }
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,8 @@
1
+ import type { HistoireHostChannel } from '../types.js';
2
+ import type { SessionContext } from './context.js';
3
+ /** Session-local application namespaces, sharing one rate window per direction/document. */
4
+ export declare function createSessionChannels(context: SessionContext): {
5
+ /** Open configured namespace without automatically starting a story. */
6
+ open(name: string): HistoireHostChannel;
7
+ };
8
+ //# sourceMappingURL=channels.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channels.d.ts","sourceRoot":"","sources":["../../src/session/channels.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAMlD,4FAA4F;AAC5F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,cAAc;IAkEzD,wEAAwE;IACxE,IAAI,OAAO,MAAM,GAAG,mBAAmB;EAiC1C"}
@@ -0,0 +1,117 @@
1
+ import { createHostChannelRateLimiter, HistoireSdkError, validateHostChannelNames, validateHostChannelPayload } from '@histoire/protocol';
2
+ import { observeOperation } from './ownership.js';
3
+ import { request } from './request.js';
4
+ import { primaryRuntime } from './state.js';
5
+ /** Session-local application namespaces, sharing one rate window per direction/document. */
6
+ export function createSessionChannels(context) {
7
+ const listeners = new Map();
8
+ const incoming = createHostChannelRateLimiter();
9
+ const outgoing = createHostChannelRateLimiter();
10
+ let runtimeId = null;
11
+ let generation = 0;
12
+ let status = context.snapshot.status;
13
+ let sourceIdentity;
14
+ /** Public readiness can be transiently empty while same document stays owned. */
15
+ function currentDocument() {
16
+ const primary = context.primaryId ? context.mounts.get(context.primaryId) : undefined;
17
+ return primary?.active ? primary.runtimeId : null;
18
+ }
19
+ /** Source policy is checked independently of current preview readiness. */
20
+ function allowed(name) {
21
+ validateHostChannelNames([name]);
22
+ context.assertCapability('hostChannels');
23
+ if (!context.engine?.hostChannels.channels?.includes(name))
24
+ throw new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Host channel is not enabled.', { name });
25
+ }
26
+ context.listeners.add((snapshot) => {
27
+ // Selection briefly clears public runtimeId even when actual document stays.
28
+ // Only physical owned-document retirement releases subscribers.
29
+ const ownedDocument = currentDocument();
30
+ const nextSource = snapshot.source ? JSON.stringify([snapshot.source.sourceId, snapshot.source.epoch]) : undefined;
31
+ const retiredSource = (status === 'ready' && snapshot.status !== 'ready') || (sourceIdentity !== undefined && nextSource !== sourceIdentity);
32
+ if (retiredSource || (runtimeId && ownedDocument !== runtimeId)) {
33
+ generation++;
34
+ // Callers may retain unsubscribe closures referencing these sets.
35
+ // Retirement releases callbacks independently of later unsubscribe calls.
36
+ for (const subscriptions of listeners.values())
37
+ subscriptions.clear();
38
+ listeners.clear();
39
+ incoming.reset();
40
+ outgoing.reset();
41
+ }
42
+ runtimeId = ownedDocument;
43
+ status = snapshot.status;
44
+ sourceIdentity = nextSource;
45
+ });
46
+ context.deliverChannel = (message) => {
47
+ try {
48
+ allowed(message.name);
49
+ validateHostChannelPayload(message, true);
50
+ if (message.runtimeId !== context.snapshot.runtime.runtimeId || message.target.storyId !== context.snapshot.selection?.storyId
51
+ || context.story(message.target.storyId).variants.filter(variant => variant.id === message.target.variantId).length !== 1) {
52
+ return;
53
+ }
54
+ }
55
+ catch {
56
+ incoming.drop();
57
+ return;
58
+ }
59
+ if (!incoming.accept())
60
+ return;
61
+ const copy = context.copy(message);
62
+ const deliveryGeneration = generation;
63
+ /** Async consumer failures remain observed, but never charge a replacement document. */
64
+ function failed() {
65
+ if (deliveryGeneration === generation && message.runtimeId === currentDocument())
66
+ incoming.drop();
67
+ }
68
+ for (const listener of listeners.get(message.name) ?? []) {
69
+ try {
70
+ void Promise.resolve(listener(copy)).catch(failed);
71
+ }
72
+ catch {
73
+ failed();
74
+ }
75
+ }
76
+ };
77
+ return {
78
+ /** Open configured namespace without automatically starting a story. */
79
+ open(name) {
80
+ allowed(name);
81
+ let capturedRuntime = currentDocument();
82
+ const capturedGeneration = generation;
83
+ /** Handle may open before explicit mount; first use binds it to actual document. */
84
+ function captureOwner() {
85
+ const current = currentDocument();
86
+ if (capturedGeneration !== generation || (capturedRuntime && current !== capturedRuntime))
87
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Host channel handle belongs to retired runtime.');
88
+ if (current)
89
+ capturedRuntime = current;
90
+ }
91
+ return {
92
+ post: (type, data) => observeOperation((async () => {
93
+ allowed(name);
94
+ if (!context.snapshot.selection?.variantId)
95
+ throw new HistoireSdkError('PREVIEW_NOT_READY', 'Host channel requires a selected variant.');
96
+ const primary = primaryRuntime(context);
97
+ captureOwner();
98
+ const payload = validateHostChannelPayload({ name, type, data });
99
+ if (!outgoing.accept())
100
+ throw new HistoireSdkError('RATE_LIMITED', 'Host channel rate limit exceeded.');
101
+ await request(context, primary.transport, 'channel.post', context.copy(payload), { kind: 'runtime', mountId: primary.handle.id });
102
+ })()),
103
+ subscribe(listener) {
104
+ allowed(name);
105
+ captureOwner();
106
+ if (typeof listener !== 'function')
107
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Expected host channel listener.');
108
+ const subscriptions = listeners.get(name) ?? new Set();
109
+ listeners.set(name, subscriptions);
110
+ subscriptions.add(listener);
111
+ return () => subscriptions.delete(listener);
112
+ },
113
+ getDroppedCount: () => Math.min(Number.MAX_SAFE_INTEGER, incoming.droppedCount + outgoing.droppedCount),
114
+ };
115
+ },
116
+ };
117
+ }
@@ -0,0 +1,97 @@
1
+ import type { HistoireCapabilities, HistoireCapabilityName, HistoireHostChannelMessage, HistoirePluginChannelEvent, HistoireSettings, HistoireSettingsPatch, HistoireSnapshot, HistoireSourceDescriptor, HistoireTarget } from '@histoire/protocol';
2
+ import type { HistoireSessionAdapters, HistoireSourceConnection, HistoireSurfaceConnection } from '../adapters/types.js';
3
+ import type { HistoireMount, HistoireSession, HistoireSessionOptions } from '../types.js';
4
+ import { createSettingsPersistence } from '../persistence/storage.js';
5
+ import { OperationOwner } from './ownership.js';
6
+ /** One attachment; primary ownership survives until complete async cleanup. */
7
+ export interface OwnedMount {
8
+ /** Public caller handle. */
9
+ handle: HistoireMount;
10
+ /** First-party transport and element owner. */
11
+ transport: HistoireSurfaceConnection;
12
+ /** Listener cleanup. */
13
+ unsubscribe: () => void;
14
+ /** Whether notifications still belong to active attachment. */
15
+ active: boolean;
16
+ /** Hidden primaries never expose visible variant geometry. */
17
+ hidden: boolean;
18
+ /** Current document independent of selection's temporary mounting projection. */
19
+ runtimeId: string | null;
20
+ /** Retired documents can never reclaim attachment, even with delayed mounting. */
21
+ retiredRuntimeIds: Set<string>;
22
+ /** Idempotent cleanup promise. */
23
+ closing?: Promise<void>;
24
+ }
25
+ /** Framework-neutral private state shared by controller service modules. */
26
+ export declare class SessionContext {
27
+ /** Stable session identity, independent of target IDs. */
28
+ readonly sessionId: string;
29
+ /** Normalized source book base. */
30
+ readonly url: string;
31
+ /** First-party adapters; no construction side effects. */
32
+ readonly adapters: HistoireSessionAdapters;
33
+ /** Local parent API for first-party surface proxies; never serialized. */
34
+ session: HistoireSession | null;
35
+ /** Stable immutable projection. */
36
+ snapshot: HistoireSnapshot;
37
+ /** Negotiated engine support before runtime readiness filtering. */
38
+ engine: HistoireCapabilities | null;
39
+ /** Current SDK-accepted immutable descriptor, detached from adapter-owned input. */
40
+ descriptor: HistoireSourceDescriptor | null;
41
+ /** Active data bridge, absent until explicit connect. */
42
+ connection: HistoireSourceConnection | null;
43
+ /** Exact source listener cleanup. */
44
+ unsubscribeSource: (() => void) | null;
45
+ /** Session snapshot observers. */
46
+ readonly listeners: Set<(snapshot: Readonly<HistoireSnapshot>) => void>;
47
+ /** Event observers. */
48
+ readonly eventListeners: Set<(event: HistoireSnapshot['events']['items'][number]) => void>;
49
+ /** Application relay owned by this session, not any framework/global store. */
50
+ deliverChannel?: (message: HistoireHostChannelMessage) => void;
51
+ /** Frame plugin relay owned by this session. */
52
+ deliverPlugin?: (message: HistoirePluginChannelEvent) => void;
53
+ /** Owned pending work. */
54
+ readonly operations: OperationOwner;
55
+ /** Per-story remembered explicit/default variant. */
56
+ readonly remembered: Map<string, string>;
57
+ /** Owned surface registry. */
58
+ readonly mounts: Map<string, OwnedMount>;
59
+ /** Synchronously reserved primary attachment. */
60
+ primaryId: string | null;
61
+ /** Selection lifetime; same target can acquire a new document. */
62
+ selectionVersion: number;
63
+ /** Actual runtime document lifetime. */
64
+ runtimeVersion: number;
65
+ /** Mount allocation counter. */
66
+ mountCounter: number;
67
+ /** Monotonic attributable event counter. */
68
+ eventCounter: number;
69
+ /** Explicit host edits win over later source defaults and persisted preferences. */
70
+ explicitSettings: HistoireSettingsPatch;
71
+ /** One preference application per document/value; concurrent readiness coalesces. */
72
+ settingsSync: {
73
+ mountId: string;
74
+ runtimeId: string;
75
+ settings: HistoireSettings;
76
+ promise: Promise<void>;
77
+ } | null;
78
+ /** Opt-in lazy preference persistence. */
79
+ readonly persistence: ReturnType<typeof createSettingsPersistence>;
80
+ /** Validate URL without window/document/storage access. */
81
+ constructor(options: HistoireSessionOptions, adapters: HistoireSessionAdapters);
82
+ /** Publish one coherent immutable replacement; isolate subscriber exceptions. */
83
+ publish(patch: Partial<HistoireSnapshot>): void;
84
+ /** Reject terminal access before any operation/resource creation. */
85
+ assertActive(): void;
86
+ /** Require explicit successful source connection. */
87
+ assertConnected(): HistoireSourceConnection;
88
+ /** Check source support separately from runtime requirement. */
89
+ assertCapability(name: HistoireCapabilityName): void;
90
+ /** Require exact selected variant without fabricating a target. */
91
+ selected(): HistoireTarget;
92
+ /** Resolve exact lookup and reject duplicate IDs before mutation. */
93
+ story(storyId: string): import("@histoire/protocol").HistoireCatalogStory;
94
+ /** Copy validated incoming projection without freezing source adapters. */
95
+ copy<T>(value: T): T;
96
+ }
97
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/session/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACnP,OAAO,KAAK,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AACxH,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAEzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAA;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAG/C,+EAA+E;AAC/E,MAAM,WAAW,UAAU;IACzB,4BAA4B;IAC5B,MAAM,EAAE,aAAa,CAAA;IACrB,+CAA+C;IAC/C,SAAS,EAAE,yBAAyB,CAAA;IACpC,wBAAwB;IACxB,WAAW,EAAE,MAAM,IAAI,CAAA;IACvB,+DAA+D;IAC/D,MAAM,EAAE,OAAO,CAAA;IACf,8DAA8D;IAC9D,MAAM,EAAE,OAAO,CAAA;IACf,iFAAiF;IACjF,SAAS,EAAE,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