@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,136 @@
1
+ import { HistoireSdkError } from '@histoire/protocol';
2
+ import { createSettingsPersistence } from '../persistence/storage.js';
3
+ import { OperationOwner } from './ownership.js';
4
+ import { copyProjection, effectiveCapabilities, freezeProjection, initialSnapshot } from './snapshot.js';
5
+ /** Framework-neutral private state shared by controller service modules. */
6
+ export class SessionContext {
7
+ /** Stable session identity, independent of target IDs. */
8
+ sessionId = `histoire-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
9
+ /** Normalized source book base. */
10
+ url;
11
+ /** First-party adapters; no construction side effects. */
12
+ adapters;
13
+ /** Local parent API for first-party surface proxies; never serialized. */
14
+ session = null;
15
+ /** Stable immutable projection. */
16
+ snapshot = initialSnapshot();
17
+ /** Negotiated engine support before runtime readiness filtering. */
18
+ engine = null;
19
+ /** Current SDK-accepted immutable descriptor, detached from adapter-owned input. */
20
+ descriptor = null;
21
+ /** Active data bridge, absent until explicit connect. */
22
+ connection = null;
23
+ /** Exact source listener cleanup. */
24
+ unsubscribeSource = null;
25
+ /** Session snapshot observers. */
26
+ listeners = new Set();
27
+ /** Event observers. */
28
+ eventListeners = new Set();
29
+ /** Application relay owned by this session, not any framework/global store. */
30
+ deliverChannel;
31
+ /** Frame plugin relay owned by this session. */
32
+ deliverPlugin;
33
+ /** Owned pending work. */
34
+ operations = new OperationOwner();
35
+ /** Per-story remembered explicit/default variant. */
36
+ remembered = new Map();
37
+ /** Owned surface registry. */
38
+ mounts = new Map();
39
+ /** Synchronously reserved primary attachment. */
40
+ primaryId = null;
41
+ /** Selection lifetime; same target can acquire a new document. */
42
+ selectionVersion = 0;
43
+ /** Actual runtime document lifetime. */
44
+ runtimeVersion = 0;
45
+ /** Mount allocation counter. */
46
+ mountCounter = 0;
47
+ /** Monotonic attributable event counter. */
48
+ eventCounter = 0;
49
+ /** Explicit host edits win over later source defaults and persisted preferences. */
50
+ explicitSettings = {};
51
+ /** One preference application per document/value; concurrent readiness coalesces. */
52
+ settingsSync = null;
53
+ /** Opt-in lazy preference persistence. */
54
+ persistence;
55
+ /** Validate URL without window/document/storage access. */
56
+ constructor(options, adapters) {
57
+ let url;
58
+ try {
59
+ url = new URL(options.url);
60
+ }
61
+ catch {
62
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Source URL must be absolute HTTP(S).');
63
+ }
64
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
65
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Source URL must be an HTTP(S) book base without credentials, query or fragment.');
66
+ }
67
+ if (options.persistenceKey !== undefined && typeof options.persistenceKey !== 'string')
68
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Persistence key must be a string.');
69
+ if (!url.pathname.endsWith('/'))
70
+ url.pathname += '/';
71
+ this.url = url.href;
72
+ this.adapters = adapters;
73
+ this.persistence = createSettingsPersistence(this.url, options.persistenceKey, adapters.storage);
74
+ }
75
+ /** Publish one coherent immutable replacement; isolate subscriber exceptions. */
76
+ publish(patch) {
77
+ const next = { ...this.snapshot, ...patch };
78
+ next.capabilities = effectiveCapabilities(next, this.engine);
79
+ // Source grants are upper bounds; only the current ready actor can grant execution.
80
+ if (this.descriptor?.inspection) {
81
+ next.inspection = Object.fromEntries(Object.entries(this.descriptor.inspection).map(([name, capability]) => [name, capability?.available && next.status === 'ready' && next.runtime.status === 'ready' && next.runtime.inspection?.[name]?.available
82
+ ? { available: true }
83
+ : { available: false, reason: 'CAPABILITY_UNAVAILABLE' }]));
84
+ }
85
+ else {
86
+ delete next.inspection;
87
+ }
88
+ this.snapshot = freezeProjection(next);
89
+ for (const listener of this.listeners) {
90
+ try {
91
+ listener(this.snapshot);
92
+ }
93
+ catch { /* Consumer callbacks cannot interrupt transport ownership. */ }
94
+ }
95
+ }
96
+ /** Reject terminal access before any operation/resource creation. */
97
+ assertActive() {
98
+ if (this.snapshot.status === 'disposed')
99
+ throw new HistoireSdkError('DISPOSED', 'Session disposed.');
100
+ }
101
+ /** Require explicit successful source connection. */
102
+ assertConnected() {
103
+ this.assertActive();
104
+ if (!this.connection || this.snapshot.status !== 'ready')
105
+ throw new HistoireSdkError('NOT_CONNECTED', 'Session is not connected.');
106
+ return this.connection;
107
+ }
108
+ /** Check source support separately from runtime requirement. */
109
+ assertCapability(name) {
110
+ this.assertConnected();
111
+ const capability = this.engine?.[name];
112
+ if (!capability?.available)
113
+ throw new HistoireSdkError('CAPABILITY_UNAVAILABLE', `Source does not support ${name}.`, { capability: name, ...(capability?.reason ? { reason: capability.reason } : {}) });
114
+ }
115
+ /** Require exact selected variant without fabricating a target. */
116
+ selected() {
117
+ this.assertConnected();
118
+ if (this.snapshot.selection?.variantId == null)
119
+ throw new HistoireSdkError('SELECTION_REQUIRED', 'Select a story variant first.');
120
+ return this.snapshot.selection;
121
+ }
122
+ /** Resolve exact lookup and reject duplicate IDs before mutation. */
123
+ story(storyId) {
124
+ this.assertConnected();
125
+ if (typeof storyId !== 'string')
126
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Story ID must be a string.');
127
+ const matches = this.snapshot.catalog.stories.filter(story => story.id === storyId);
128
+ if (!matches.length)
129
+ throw new HistoireSdkError('STORY_NOT_FOUND', 'Story ID not found.', { storyId });
130
+ if (matches.length !== 1)
131
+ throw new HistoireSdkError('STORY_AMBIGUOUS', 'Story ID is ambiguous.', { storyId });
132
+ return matches[0];
133
+ }
134
+ /** Copy validated incoming projection without freezing source adapters. */
135
+ copy(value) { return freezeProjection(copyProjection(value)); }
136
+ }
@@ -0,0 +1,5 @@
1
+ import type { HistoireSessionAdapters } from '../adapters/types.js';
2
+ import type { HistoireSession, HistoireSessionOptions } from '../types.js';
3
+ /** Create isolated controller over first-party adapters; no DOM on construction. */
4
+ export declare function createHistoireSessionWithAdapters(options: HistoireSessionOptions, adapters: HistoireSessionAdapters): HistoireSession;
5
+ //# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../src/session/controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAA4B,MAAM,sBAAsB,CAAA;AAC7F,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAmC1E,oFAAoF;AACpF,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,sBAAsB,EAAE,QAAQ,EAAE,uBAAuB,GAAG,eAAe,CA+LrI"}
@@ -0,0 +1,217 @@
1
+ import { HistoireSdkError, validateSettingsPatch } from '@histoire/protocol';
2
+ import { createSessionChannels } from './channels.js';
3
+ import { SessionContext } from './context.js';
4
+ import { acquireDiagnosticLease } from './debug-lease.js';
5
+ import { createSessionDebug } from './debug.js';
6
+ import { clearEvents } from './events.js';
7
+ import { createSessionInspection } from './inspection.js';
8
+ import { acceptHistoireSourceDescriptor, bindHistoireSessionInternals, isAcceptedHistoireSourceDescriptor } from './internal.js';
9
+ import { mountSurface } from './mounts.js';
10
+ import { receiveNotification } from './notifications.js';
11
+ import { observeOperation } from './ownership.js';
12
+ import { createSessionPlugins } from './plugins.js';
13
+ import { request } from './request.js';
14
+ import { reconcileSelection, resolveSelection, select } from './selection.js';
15
+ import { collectTests, getDocs, getSource, runTests } from './services.js';
16
+ import { updateSettings } from './settings.js';
17
+ import { getState, patchState, resetState } from './state.js';
18
+ /** Create isolated controller over first-party adapters; no DOM on construction. */
19
+ export function createHistoireSessionWithAdapters(options, adapters) {
20
+ const context = new SessionContext(options, adapters);
21
+ let connecting = null;
22
+ let disposing = null;
23
+ let selected = Promise.resolve();
24
+ let pendingSelection = null;
25
+ const closed = new WeakSet();
26
+ /** Close each acquired source exactly once, including late acquisition. */
27
+ const closeSource = async (connection) => {
28
+ if (closed.has(connection))
29
+ return;
30
+ closed.add(connection);
31
+ await connection.close();
32
+ };
33
+ /** Explicit connection shares in-flight work and never executes stories. */
34
+ const connect = () => {
35
+ try {
36
+ context.assertActive();
37
+ }
38
+ catch (error) {
39
+ return observeOperation(Promise.reject(error));
40
+ }
41
+ if (connecting)
42
+ return connecting;
43
+ if (context.snapshot.status === 'ready')
44
+ return Promise.resolve();
45
+ const previous = context.connection;
46
+ connecting = context.operations.run({ kind: 'connect' }, async (signal) => {
47
+ // Keep predecessor attached until owned task starts. Reentrant disposal
48
+ // during connecting publication must still be able to close that source.
49
+ context.unsubscribeSource?.();
50
+ context.unsubscribeSource = null;
51
+ context.connection = null;
52
+ signal.throwIfAborted();
53
+ await Promise.all([...context.mounts.values()].map(mount => mount.handle.unmount()));
54
+ if (previous)
55
+ await closeSource(previous);
56
+ if (signal.aborted)
57
+ throw signal.reason;
58
+ const connection = await context.adapters.connect({ url: context.url, sessionId: context.sessionId, signal });
59
+ if (signal.aborted || context.snapshot.status === 'disposed') {
60
+ await closeSource(connection);
61
+ throw signal.reason ?? new HistoireSdkError('DISPOSED', 'Session disposed during connection.');
62
+ }
63
+ try {
64
+ if (connection.descriptor.protocolVersion !== 1 || connection.descriptor.descriptorVersion !== 1)
65
+ throw new HistoireSdkError('PROTOCOL_MISMATCH', 'Unsupported source descriptor version.');
66
+ const descriptor = isAcceptedHistoireSourceDescriptor(connection.descriptor)
67
+ ? connection.descriptor
68
+ : acceptHistoireSourceDescriptor(connection.descriptor);
69
+ context.connection = connection;
70
+ context.descriptor = descriptor;
71
+ context.engine = context.copy(descriptor.capabilities);
72
+ const catalog = context.copy(descriptor.catalog);
73
+ const saved = context.persistence.read();
74
+ const settings = context.copy({ ...context.snapshot.settings, ...validateSettingsPatch(connection.initialSettings ?? {}), ...saved, ...context.explicitSettings });
75
+ const selected = reconcileSelection(context, catalog);
76
+ context.unsubscribeSource = connection.subscribe(notification => receiveNotification(context, notification));
77
+ context.publish({
78
+ status: 'ready',
79
+ stale: false,
80
+ source: context.copy({ sourceId: descriptor.sourceId, url: context.url, mode: descriptor.mode, epoch: descriptor.epoch, revision: descriptor.revision }),
81
+ catalog,
82
+ inspection: context.copy(descriptor.inspection),
83
+ diagnostics: catalog.diagnostics,
84
+ selection: context.copy(selected),
85
+ settings,
86
+ state: null,
87
+ });
88
+ }
89
+ catch (error) {
90
+ context.connection = null;
91
+ await closeSource(connection);
92
+ throw error;
93
+ }
94
+ }, () => context.assertActive());
95
+ const current = connecting;
96
+ void current.then(() => { if (connecting === current)
97
+ connecting = null; }, () => {
98
+ if (connecting === current)
99
+ connecting = null;
100
+ if (context.snapshot.status !== 'disposed')
101
+ context.publish({ status: 'failed', stale: context.snapshot.source !== null });
102
+ });
103
+ // Reserve shared operation before observers can synchronously call connect.
104
+ context.publish({ status: 'connecting' });
105
+ return current;
106
+ };
107
+ /** Terminal invalidation happens synchronously before owned-resource awaits. */
108
+ const dispose = () => {
109
+ if (disposing)
110
+ return disposing;
111
+ context.selectionVersion++;
112
+ context.runtimeVersion++;
113
+ context.publish({ status: 'disposed', stale: context.snapshot.source !== null });
114
+ context.operations.reject('DISPOSED', 'Session disposed.');
115
+ context.unsubscribeSource?.();
116
+ context.unsubscribeSource = null;
117
+ context.listeners.clear();
118
+ context.eventListeners.clear();
119
+ const connection = context.connection;
120
+ context.connection = null;
121
+ disposing = Promise.allSettled([...context.mounts.values()].map(mount => mount.handle.unmount()).concat(connection ? [closeSource(connection)] : [])).then((results) => {
122
+ const failure = results.find(result => result.status === 'rejected');
123
+ if (failure?.status === 'rejected')
124
+ throw failure.reason;
125
+ });
126
+ void disposing.catch(() => { });
127
+ return disposing;
128
+ };
129
+ const session = {
130
+ connect,
131
+ dispose,
132
+ getSnapshot: () => context.snapshot,
133
+ subscribe: (listener) => {
134
+ context.assertActive();
135
+ context.listeners.add(listener);
136
+ return () => context.listeners.delete(listener);
137
+ },
138
+ catalog: {
139
+ list: () => observeOperation((async () => {
140
+ context.assertCapability('catalog');
141
+ return context.snapshot.catalog.stories;
142
+ })()),
143
+ getStory: storyId => observeOperation((async () => {
144
+ context.assertCapability('catalog');
145
+ return context.story(storyId);
146
+ })()),
147
+ search: query => observeOperation((async () => {
148
+ context.assertCapability('search');
149
+ if (typeof query !== 'string')
150
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Search query must be a string.');
151
+ return context.copy(await request(context, context.assertConnected(), 'catalog.search', { query }));
152
+ })()),
153
+ },
154
+ selection: { select: (input) => {
155
+ let target;
156
+ try {
157
+ target = resolveSelection(context, input);
158
+ }
159
+ catch (error) {
160
+ return observeOperation(Promise.reject(error));
161
+ }
162
+ const source = context.snapshot.source;
163
+ const pending = pendingSelection;
164
+ if (pending && pending.version === context.selectionVersion && pending.connection === context.connection
165
+ && pending.source.epoch === source.epoch && pending.source.revision === source.revision
166
+ && pending.mountId === context.primaryId && (!pending.mountId || context.mounts.get(pending.mountId)?.active)
167
+ && pending.target.storyId === target.storyId && pending.target.variantId === target.variantId) {
168
+ return pending.promise;
169
+ }
170
+ let resolve;
171
+ let reject;
172
+ const promise = observeOperation(new Promise((complete, fail) => {
173
+ resolve = complete;
174
+ reject = fail;
175
+ }));
176
+ const previous = context.snapshot.selection;
177
+ const changed = previous?.storyId !== target.storyId || previous.variantId !== target.variantId;
178
+ const intent = { target, version: context.selectionVersion + Number(changed), source, connection: context.connection, mountId: context.primaryId, promise };
179
+ // Reserve ACK and composition barrier before publication. Reentrant or
180
+ // later matching intent cannot replace this barrier with an early no-op.
181
+ pendingSelection = intent;
182
+ selected = promise.then(() => { }, () => { });
183
+ void select(context, target).then(() => {
184
+ if (pendingSelection === intent)
185
+ pendingSelection = null;
186
+ resolve();
187
+ }, (error) => {
188
+ if (pendingSelection === intent)
189
+ pendingSelection = null;
190
+ reject(error);
191
+ });
192
+ return promise;
193
+ } },
194
+ state: { get: () => observeOperation(getState(context)), patch: patch => observeOperation(patchState(context, patch)), reset: () => observeOperation(resetState(context)) },
195
+ settings: { update: patch => observeOperation(updateSettings(context, patch)) },
196
+ events: {
197
+ subscribe: (listener) => {
198
+ context.assertActive();
199
+ context.eventListeners.add(listener);
200
+ return () => context.eventListeners.delete(listener);
201
+ },
202
+ clear: () => clearEvents(context),
203
+ },
204
+ channels: createSessionChannels(context),
205
+ inspect: createSessionInspection(context),
206
+ debug: createSessionDebug(context, () => acquireDiagnosticLease(context)),
207
+ plugins: createSessionPlugins(context),
208
+ docs: { get: storyId => observeOperation(getDocs(context, storyId)) },
209
+ source: { get: input => observeOperation(getSource(context, input)) },
210
+ tests: { collect: () => observeOperation(collectTests(context)), run: options => observeOperation(runTests(context, options)) },
211
+ mount: (container, options) => mountSurface(context, container, options.surface, false, options.presentation, options.padding),
212
+ createHiddenPreview: () => mountSurface(context, undefined, 'preview', true),
213
+ };
214
+ context.session = session;
215
+ bindHistoireSessionInternals(session, context, () => selected);
216
+ return session;
217
+ }
@@ -0,0 +1,5 @@
1
+ import type { SessionContext } from './context.js';
2
+ import type { DiagnosticLease } from './debug.js';
3
+ /** Capture an already mounted runtime and transport; no cleanup rebinds to a successor. */
4
+ export declare function acquireDiagnosticLease(context: SessionContext): DiagnosticLease;
5
+ //# sourceMappingURL=debug-lease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-lease.d.ts","sourceRoot":"","sources":["../../src/session/debug-lease.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAKjD,2FAA2F;AAC3F,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,cAAc,GAAG,eAAe,CAsD/E"}
@@ -0,0 +1,64 @@
1
+ import { HistoireSdkError, sameInspectionOwner, validateInspectionResult } from '@histoire/protocol';
2
+ import { request } from './request.js';
3
+ import { primaryRuntime } from './state.js';
4
+ /** Capture an already mounted runtime and transport; no cleanup rebinds to a successor. */
5
+ export function acquireDiagnosticLease(context) {
6
+ context.assertConnected();
7
+ if (!context.descriptor?.inspection?.diagnostics?.available || !context.snapshot.inspection?.diagnostics?.available)
8
+ throw new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Diagnostics unavailable.');
9
+ const primary = primaryRuntime(context);
10
+ const source = context.snapshot.source;
11
+ const connection = context.connection;
12
+ const selected = context.selected();
13
+ const target = { storyId: selected.storyId, variantId: selected.variantId };
14
+ const owner = context.copy({ sourceId: source.sourceId, epoch: source.epoch, revision: source.revision, runtimeId: context.snapshot.runtime.runtimeId, target });
15
+ const selectionVersion = context.selectionVersion;
16
+ const runtimeVersion = context.runtimeVersion;
17
+ /** Check current authority after every async delivery. */
18
+ function current() {
19
+ const snapshot = context.snapshot;
20
+ return snapshot.status === 'ready' && context.connection === connection && context.descriptor?.inspection?.diagnostics?.available === true && snapshot.inspection?.diagnostics?.available === true
21
+ && snapshot.source?.sourceId === owner.sourceId && snapshot.source.epoch === owner.epoch && snapshot.source.revision === owner.revision
22
+ && snapshot.runtime.runtimeId === owner.runtimeId && snapshot.runtime.status === 'ready'
23
+ && snapshot.selection?.storyId === owner.target.storyId && snapshot.selection?.variantId === owner.target.variantId
24
+ && context.primaryId === primary.handle.id && context.mounts.get(primary.handle.id) === primary && primary.active
25
+ && context.selectionVersion === selectionVersion && context.runtimeVersion === runtimeVersion;
26
+ }
27
+ return {
28
+ owner,
29
+ current,
30
+ /** Stop may use captured transport after withdrawal, but cannot retarget a new document. */
31
+ async invoke(action, observationId, afterSequence, signal) {
32
+ const payload = { action, observationId, target: owner.target, expectedOwner: owner, ...(afterSequence === undefined ? {} : { afterSequence }) };
33
+ let result;
34
+ if (action === 'stop') {
35
+ result = await primary.transport.request('inspection.debug', payload, {
36
+ sessionId: context.sessionId,
37
+ connectionId: primary.transport.id,
38
+ mountId: primary.handle.id,
39
+ sourceId: owner.sourceId,
40
+ epoch: owner.epoch,
41
+ revision: owner.revision,
42
+ runtimeId: owner.runtimeId,
43
+ target: owner.target,
44
+ signal: AbortSignal.timeout(5000),
45
+ });
46
+ }
47
+ else {
48
+ if (!current())
49
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Diagnostic owner changed.');
50
+ result = await request(context, primary.transport, 'inspection.debug', payload, { kind: 'runtime', mountId: primary.handle.id }, signal, owner.target);
51
+ if (!current())
52
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Diagnostic owner changed.');
53
+ }
54
+ const parsed = validateInspectionResult(result);
55
+ if (parsed.mode !== 'live' || parsed.inspection !== 'debug' || !sameInspectionOwner(parsed.owner, owner))
56
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Diagnostic response owner changed.');
57
+ for (const row of parsed.items) {
58
+ if (!row.owner || !sameInspectionOwner(row.owner, owner))
59
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Diagnostic entry owner changed.');
60
+ }
61
+ return context.copy(parsed);
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,14 @@
1
+ import type { HistoireDebug, HistoireDebugPage, HistoireInspectionOwner } from '@histoire/protocol';
2
+ import type { SessionContext } from './context.js';
3
+ /** Captured transport and authority; stop must never acquire a replacement runtime. */
4
+ export interface DiagnosticLease {
5
+ /** Captured public owner, also checked against each result. */
6
+ owner: HistoireInspectionOwner;
7
+ /** Whether this exact source, attachment, document and permission remain active. */
8
+ current: () => boolean;
9
+ /** Execute against the captured transport, including cleanup after withdrawal. */
10
+ invoke: (action: 'start' | 'read' | 'stop', observationId: string, afterSequence?: number, signal?: AbortSignal) => Promise<HistoireDebugPage>;
11
+ }
12
+ /** Share one remote observation and its cursor among listeners of the same SDK session. */
13
+ export declare function createSessionDebug(context: SessionContext, acquire: () => DiagnosticLease): HistoireDebug;
14
+ //# sourceMappingURL=debug.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug.d.ts","sourceRoot":"","sources":["../../src/session/debug.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAA;AACnG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAGlD,uFAAuF;AACvF,MAAM,WAAW,eAAe;IAC9B,+DAA+D;IAC/D,KAAK,EAAE,uBAAuB,CAAA;IAC9B,oFAAoF;IACpF,OAAO,EAAE,MAAM,OAAO,CAAA;IACtB,kFAAkF;IAClF,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAA;CAC/I;AA2CD,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,eAAe,GAAG,aAAa,CAqMzG"}