@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,242 @@
1
+ import { createDebugBuffer, HISTOIRE_ERROR_CODES, HistoireSdkError, sameInspectionOwner } from '@histoire/protocol';
2
+ /** Avoid retaining a retired session through V8's lazy asynchronous error stack. */
3
+ function diagnosticClosureError(code, message) {
4
+ const error = new HistoireSdkError(code, message);
5
+ error.stack = undefined;
6
+ return error;
7
+ }
8
+ /** Keep public failure identity without retaining runtime frames through a lazy stack. */
9
+ function detachReadyError(value) {
10
+ const code = value instanceof Error ? Object.getOwnPropertyDescriptor(value, 'code')?.value : undefined;
11
+ const error = value instanceof Error && typeof code === 'string' && HISTOIRE_ERROR_CODES.includes(code)
12
+ ? new HistoireSdkError(code, value.message, value instanceof HistoireSdkError ? value.details : undefined)
13
+ : value instanceof Error ? Object.assign(new Error(value.message), { name: value.name }) : new Error('Diagnostic observation failed.');
14
+ error.stack = undefined;
15
+ return error;
16
+ }
17
+ /** Detach release closure after use so retained handles cannot retain the session. */
18
+ function diagnosticHandle(ready, closed, initialRelease) {
19
+ let release = initialRelease;
20
+ let closing;
21
+ return {
22
+ handle: {
23
+ ready,
24
+ closed,
25
+ unsubscribe() {
26
+ if (closing)
27
+ return closing;
28
+ const run = release;
29
+ release = undefined;
30
+ closing = run();
31
+ return closing;
32
+ },
33
+ },
34
+ /** Automatic retirement also releases the handle's session reference. */
35
+ detach(completion) {
36
+ release = undefined;
37
+ closing ??= completion;
38
+ },
39
+ };
40
+ }
41
+ /** Share one remote observation and its cursor among listeners of the same SDK session. */
42
+ export function createSessionDebug(context, acquire) {
43
+ const buffer = createDebugBuffer();
44
+ let nextId = 0;
45
+ let stream;
46
+ let retained;
47
+ /** Retained evidence is readable only while its captured authority remains current. */
48
+ function pruneRetention() {
49
+ if (retained && !retained.current()) {
50
+ buffer.clear();
51
+ retained = undefined;
52
+ context.listeners.delete(pruneRetention);
53
+ }
54
+ }
55
+ /** Discard local evidence without recycling its sequence identities. */
56
+ function clearRetention() {
57
+ buffer.clear();
58
+ retained = undefined;
59
+ context.listeners.delete(pruneRetention);
60
+ }
61
+ /** Stop polling immediately and reserve one cleanup promise before awaiting registration. */
62
+ function close(current, error) {
63
+ if (current.closing)
64
+ return current.closing;
65
+ const completion = Promise.withResolvers();
66
+ current.closing = completion.promise;
67
+ void current.closing.catch(() => { });
68
+ current.active = false;
69
+ if (stream === current)
70
+ stream = undefined;
71
+ context.listeners.delete(current.changed);
72
+ for (const listener of current.listeners) {
73
+ listener.active = false;
74
+ listener.callback = undefined;
75
+ listener.detach(current.closing);
76
+ if (error)
77
+ listener.closed.reject(error);
78
+ else
79
+ listener.closed.resolve();
80
+ }
81
+ current.listeners.clear();
82
+ clearTimeout(current.timer);
83
+ current.abort.abort();
84
+ if (!current.attempted) {
85
+ completion.resolve();
86
+ return current.closing;
87
+ }
88
+ // Stop immediately, then join registration: if the first stop raced ahead of
89
+ // registration, retry after settlement using the same captured owner and ID.
90
+ const early = Promise.resolve().then(() => current.lease.invoke('stop', current.id)).then(() => true, () => false);
91
+ const cleanup = (async () => {
92
+ const [stopped] = await Promise.all([early, current.ready.catch(() => { })]);
93
+ if (!stopped) {
94
+ try {
95
+ await current.lease.invoke('stop', current.id);
96
+ }
97
+ catch {
98
+ throw diagnosticClosureError('SOURCE_UNAVAILABLE', 'Diagnostic cleanup could not be confirmed.');
99
+ }
100
+ }
101
+ })();
102
+ let timer;
103
+ const timeout = new Promise((_resolve, reject) => {
104
+ timer = setTimeout(() => reject(diagnosticClosureError('TIMEOUT', 'Diagnostic cleanup could not be confirmed.')), 5000);
105
+ });
106
+ void Promise.race([cleanup, timeout]).then(completion.resolve, completion.reject).finally(() => clearTimeout(timer));
107
+ return current.closing;
108
+ }
109
+ /** Publish only after rechecking the captured owner and subscriber lifetime. */
110
+ function accept(current, page) {
111
+ if (!current.active || !current.lease.current()) {
112
+ pruneRetention();
113
+ void close(current, diagnosticClosureError('RUNTIME_CHANGED', 'Diagnostic owner changed.'));
114
+ return;
115
+ }
116
+ pruneRetention();
117
+ let previous = current.cursor;
118
+ for (const entry of page.items) {
119
+ if (!entry.owner || !sameInspectionOwner(entry.owner, current.lease.owner) || entry.sequence <= previous || entry.sequence > page.nextSequence)
120
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Invalid diagnostic owner or sequence.');
121
+ previous = entry.sequence;
122
+ }
123
+ if (page.nextSequence < previous)
124
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Invalid diagnostic cursor.');
125
+ // Remote cumulative eviction includes rows already delivered. Only cursor gaps
126
+ // represent evidence this SDK missed; count them once in local chronology.
127
+ let cursor = current.cursor;
128
+ for (const { sequence, ...entry } of page.items) {
129
+ if (sequence <= cursor)
130
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Invalid diagnostic sequence.');
131
+ buffer.drop(sequence - cursor - 1);
132
+ buffer.add(entry);
133
+ cursor = sequence;
134
+ }
135
+ if (page.nextSequence < cursor)
136
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Invalid diagnostic cursor.');
137
+ buffer.drop(page.nextSequence - cursor);
138
+ current.cursor = page.nextSequence;
139
+ if (page.items.length) {
140
+ retained = current.lease;
141
+ context.listeners.add(pruneRetention);
142
+ }
143
+ const snapshot = context.copy(buffer.read());
144
+ for (const listener of current.listeners) {
145
+ if (!current.active || !current.lease.current()) {
146
+ void close(current, diagnosticClosureError('RUNTIME_CHANGED', 'Diagnostic owner changed.'));
147
+ break;
148
+ }
149
+ if (listener.active) {
150
+ try {
151
+ listener.callback?.(snapshot);
152
+ }
153
+ catch { }
154
+ }
155
+ }
156
+ }
157
+ /** Poll the same captured runtime; failed or retired work cannot schedule another poll. */
158
+ async function poll(current) {
159
+ try {
160
+ const page = await current.lease.invoke('read', current.id, current.cursor, current.abort.signal);
161
+ accept(current, page);
162
+ if (current.active && current.lease.current())
163
+ current.timer = setTimeout(() => void poll(current), 250);
164
+ }
165
+ catch {
166
+ if (current.active) {
167
+ clearRetention();
168
+ void close(current, diagnosticClosureError('SOURCE_UNAVAILABLE', 'Diagnostic observation lost.'));
169
+ }
170
+ }
171
+ }
172
+ return {
173
+ /** A local read does not start instrumentation. */
174
+ getSnapshot: (options) => {
175
+ pruneRetention();
176
+ return context.copy(buffer.read(options));
177
+ },
178
+ /** Clear local evidence without reusing sequence identities. */
179
+ clear: () => clearRetention(),
180
+ /** One listener handle owns one reference to the current observation. */
181
+ subscribe(callback) {
182
+ if (typeof callback !== 'function')
183
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Diagnostic listener must be a function.');
184
+ context.assertConnected();
185
+ pruneRetention();
186
+ if (stream && !stream.lease.current())
187
+ void close(stream, diagnosticClosureError('RUNTIME_CHANGED', 'Diagnostic owner changed.'));
188
+ if (!stream) {
189
+ const lease = acquire();
190
+ const current = {
191
+ lease,
192
+ id: `${context.sessionId}:debug:${++nextId}`,
193
+ listeners: new Set(),
194
+ abort: new AbortController(),
195
+ cursor: 0,
196
+ attempted: false,
197
+ active: true,
198
+ ready: Promise.resolve(),
199
+ changed: () => { },
200
+ };
201
+ stream = current;
202
+ current.changed = () => {
203
+ if (!current.lease.current())
204
+ void close(current, diagnosticClosureError('RUNTIME_CHANGED', 'Diagnostic owner changed.'));
205
+ };
206
+ context.listeners.add(current.changed);
207
+ // Defer start so immediate unsubscribe can cancel before any runtime work.
208
+ current.ready = Promise.resolve().then(async () => {
209
+ if (!current.active || !current.lease.current())
210
+ throw new HistoireSdkError('CANCELLED', 'Diagnostic observation cancelled.');
211
+ current.attempted = true;
212
+ const page = await lease.invoke('start', current.id, undefined, current.abort.signal);
213
+ if (!current.active || !lease.current())
214
+ throw new HistoireSdkError('CANCELLED', 'Diagnostic observation cancelled.');
215
+ accept(current, page);
216
+ if (current.active)
217
+ current.timer = setTimeout(() => void poll(current), 250);
218
+ }).catch((error) => { throw detachReadyError(error); });
219
+ void current.ready.catch(() => {
220
+ if (current.active) {
221
+ clearRetention();
222
+ void close(current, diagnosticClosureError('SOURCE_UNAVAILABLE', 'Diagnostic observation lost.'));
223
+ }
224
+ });
225
+ }
226
+ const current = stream;
227
+ const closed = Promise.withResolvers();
228
+ void closed.promise.catch(() => { });
229
+ const listener = { callback, active: true, closed, detach: () => { } };
230
+ current.listeners.add(listener);
231
+ const handle = diagnosticHandle(current.ready, closed.promise, () => {
232
+ listener.active = false;
233
+ listener.callback = undefined;
234
+ listener.closed.resolve();
235
+ current.listeners.delete(listener);
236
+ return current.listeners.size ? Promise.resolve() : close(current);
237
+ });
238
+ listener.detach = handle.detach;
239
+ return handle.handle;
240
+ },
241
+ };
242
+ }
@@ -0,0 +1,7 @@
1
+ import type { HistoireEvent } from '@histoire/protocol';
2
+ import type { SessionContext } from './context.js';
3
+ /** Store attributable current-runtime events with bounded per-session history. */
4
+ export declare function appendEvent(context: SessionContext, event: HistoireEvent): void;
5
+ /** Clear retained history without reusing sequence or request identity. */
6
+ export declare function clearEvents(context: SessionContext): void;
7
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/session/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAElD,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,aAAa,GAAG,IAAI,CAc/E;AAED,2EAA2E;AAC3E,wBAAgB,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI,CAGzD"}
@@ -0,0 +1,23 @@
1
+ /** Store attributable current-runtime events with bounded per-session history. */
2
+ export function appendEvent(context, event) {
3
+ if (!Number.isFinite(event.timestamp) || !event.target || event.runtimeId !== context.snapshot.runtime.runtimeId || event.target.storyId !== context.snapshot.selection?.storyId)
4
+ return;
5
+ const story = context.snapshot.catalog.stories.find(story => story.id === event.target.storyId);
6
+ if (story?.variants.filter(variant => variant.id === event.target.variantId).length !== 1)
7
+ return;
8
+ const cleaned = context.copy({ ...event, sequence: ++context.eventCounter });
9
+ const items = [...context.snapshot.events.items, cleaned];
10
+ const dropped = Math.max(0, items.length - 1000);
11
+ context.publish({ events: { items: items.slice(dropped), droppedCount: context.snapshot.events.droppedCount + dropped } });
12
+ for (const listener of context.eventListeners) {
13
+ try {
14
+ listener(cleaned);
15
+ }
16
+ catch { /* An event consumer cannot block other subscribers or cleanup. */ }
17
+ }
18
+ }
19
+ /** Clear retained history without reusing sequence or request identity. */
20
+ export function clearEvents(context) {
21
+ context.assertActive();
22
+ context.publish({ events: { items: [], droppedCount: 0 } });
23
+ }
@@ -0,0 +1,5 @@
1
+ import type { HistoireInspection } from '@histoire/protocol';
2
+ import type { SessionContext } from './context.js';
3
+ /** Finite reads capture authority before scheduling transport work. */
4
+ export declare function createSessionInspection(context: SessionContext): HistoireInspection;
5
+ //# sourceMappingURL=inspection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspection.d.ts","sourceRoot":"","sources":["../../src/session/inspection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAsD,MAAM,oBAAoB,CAAA;AAChH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAOlD,uEAAuE;AACvE,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,cAAc,GAAG,kBAAkB,CAmEnF"}
@@ -0,0 +1,88 @@
1
+ import { HISTOIRE_INSPECTION_OPERATION_CAPABILITIES, HistoireSdkError, sameInspectionOwner, validateInspectionInput, validateInspectionResult, validateInspectionTarget, wireRecord } from '@histoire/protocol';
2
+ import { observeOperation } from './ownership.js';
3
+ import { request } from './request.js';
4
+ import { primaryRuntime } from './state.js';
5
+ import { assertVariant } from './variant.js';
6
+ /** Finite reads capture authority before scheduling transport work. */
7
+ export function createSessionInspection(context) {
8
+ let pending = 0;
9
+ let pendingCleanup = 0;
10
+ async function read(kind, options = {}) {
11
+ if (!options || typeof options !== 'object' || Array.isArray(options))
12
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Inspection options must be an object.');
13
+ let descriptors;
14
+ try {
15
+ wireRecord(options);
16
+ descriptors = Object.getOwnPropertyDescriptors(options);
17
+ if (Object.values(descriptors).some(descriptor => !('value' in descriptor)))
18
+ throw new Error('Accessor');
19
+ }
20
+ catch {
21
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Inspection options must be a plain object without accessors.');
22
+ }
23
+ const signal = descriptors.signal?.value;
24
+ const input = Object.fromEntries(Object.entries(descriptors).filter(([key, descriptor]) => key !== 'signal' && descriptor.enumerable).map(([key, descriptor]) => [key, descriptor.value]));
25
+ if (signal !== undefined && !(signal instanceof AbortSignal))
26
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Invalid cancellation signal.');
27
+ validateInspectionInput(kind, input);
28
+ const target = input.target ?? context.selected();
29
+ validateInspectionTarget(target);
30
+ const capturedTarget = context.copy(target);
31
+ assertVariant(context.story(capturedTarget.storyId), capturedTarget.variantId);
32
+ const primary = primaryRuntime(context);
33
+ const source = context.snapshot.source;
34
+ const owner = { sourceId: source.sourceId, epoch: source.epoch, revision: source.revision, runtimeId: context.snapshot.runtime.runtimeId, target: capturedTarget };
35
+ const payload = context.copy({ ...input, target: capturedTarget });
36
+ if (input.expectedOwner && !sameInspectionOwner(input.expectedOwner, owner))
37
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Inspection owner changed.');
38
+ const assertCapability = () => {
39
+ const capability = HISTOIRE_INSPECTION_OPERATION_CAPABILITIES[kind];
40
+ if (!context.descriptor?.inspection?.[capability]?.available || !context.snapshot.inspection?.[capability]?.available || ((kind === 'highlight' || kind === 'highlightLease') && input.componentId !== undefined && (!context.descriptor?.inspection?.highlight?.available || !context.snapshot.inspection?.highlight?.available || !context.descriptor?.inspection?.componentHighlight?.available || !context.snapshot.inspection?.componentHighlight?.available)))
41
+ throw new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Inspection is unavailable.');
42
+ };
43
+ assertCapability();
44
+ const cleanup = kind === 'highlightClear';
45
+ if ((cleanup ? pendingCleanup : pending) >= 16)
46
+ throw new HistoireSdkError('RATE_LIMITED', 'Too many inspection requests.');
47
+ if (cleanup)
48
+ pendingCleanup++;
49
+ else
50
+ pending++;
51
+ try {
52
+ let result;
53
+ try {
54
+ result = await request(context, primary.transport, `inspection.${kind}`, payload, { kind: input.target ? 'inspection' : 'runtime', mountId: primary.handle.id }, signal, capturedTarget);
55
+ }
56
+ catch (error) {
57
+ if (error instanceof HistoireSdkError && ['RUNTIME_CHANGED', 'STALE_REVISION', 'DISPOSED', 'NOT_CONNECTED', 'CANCELLED'].includes(error.code))
58
+ throw error;
59
+ assertCapability();
60
+ throw error;
61
+ }
62
+ assertCapability();
63
+ const action = ['highlight', 'highlightLease', 'highlightClear', 'pick'].includes(kind);
64
+ const validated = action ? result : validateInspectionResult(result);
65
+ if (!sameInspectionOwner(validated.owner, owner) || (!action && (validated.mode !== 'live' || validated.inspection !== kind)))
66
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Inspection response owner changed.');
67
+ return context.copy(validated);
68
+ }
69
+ finally {
70
+ if (cleanup)
71
+ pendingCleanup--;
72
+ else
73
+ pending--;
74
+ }
75
+ }
76
+ return {
77
+ variant: options => observeOperation(read('variant', options)),
78
+ dom: options => observeOperation(read('dom', options)),
79
+ components: options => observeOperation(read('components', options)),
80
+ component: options => observeOperation(read('component', options)),
81
+ componentForElement: options => observeOperation(read('componentForElement', options)),
82
+ accessibility: options => observeOperation(read('accessibility', options)),
83
+ highlight: options => observeOperation(read('highlight', options)),
84
+ highlightLease: options => observeOperation(read('highlightLease', options)),
85
+ clearHighlight: options => observeOperation(read('highlightClear', options)),
86
+ pick: options => observeOperation(read('pick', options)),
87
+ };
88
+ }
@@ -0,0 +1,87 @@
1
+ import type { HistoirePresetAction, HistoirePresetList, HistoireSelectionInput, HistoireSessionStatus, HistoireSourceDescriptor, HistoireStoryFileOrigin, HistoireTarget } from '@histoire/protocol';
2
+ import type { HistoireMount, HistoireSession } from '../types.js';
3
+ import type { SessionContext } from './context.js';
4
+ /** Finite docs-link intent; only standalone supplies routing, while native hosts keep URLs local. */
5
+ export interface HistoireStoryLink {
6
+ /** Exact collected target, retaining explicit null versus omitted variant choice. */
7
+ readonly selection: HistoireSelectionInput;
8
+ /** Requested panel from source link, interpreted only by standalone routing. */
9
+ readonly panel?: string;
10
+ /** Source documentation anchor, scoped to native panel or standalone route. */
11
+ readonly anchor?: string;
12
+ }
13
+ /** One first-party registry for source metadata and finite runtime/UI actions. */
14
+ interface SessionInternals {
15
+ descriptor: () => HistoireSourceDescriptor;
16
+ /** Exact immutable descriptor accepted by the owning controller. */
17
+ acceptedDescriptor?: () => HistoireSourceDescriptor;
18
+ presets: (input: HistoirePresetAction) => Promise<HistoirePresetList>;
19
+ openInEditor?: (target: HistoireTarget) => Promise<null>;
20
+ docsPolicy?: 'trusted-local';
21
+ selectionSettled?: () => Promise<void>;
22
+ /** Exact active primary handle; a retained closing mountId proves no ownership. */
23
+ primaryMountActive?: (mount: HistoireMount) => boolean;
24
+ /** Owned standalone adapter preserves link presentation alongside canonical selection. */
25
+ storyLink?: (link: HistoireStoryLink) => Promise<void>;
26
+ }
27
+ /** Read-only snapshot fields required to decide editor-action visibility. */
28
+ interface EditorActionSnapshot {
29
+ /** Current connection state. */
30
+ readonly status: HistoireSessionStatus;
31
+ /** Whether current catalog no longer matches source revision. */
32
+ readonly stale: boolean;
33
+ /** Connected source mode, when available. */
34
+ readonly source: {
35
+ readonly mode: 'dev' | 'static';
36
+ } | null;
37
+ /** Current editor capability state. */
38
+ readonly capabilities: {
39
+ readonly openInEditor: {
40
+ readonly available: boolean;
41
+ };
42
+ };
43
+ /** Current catalog stories needed for provenance lookup. */
44
+ readonly catalog: {
45
+ readonly stories: readonly {
46
+ readonly id: string;
47
+ readonly fileOrigin?: HistoireStoryFileOrigin;
48
+ }[];
49
+ };
50
+ /** Current story target, when selected. */
51
+ readonly selection: Readonly<HistoireTarget> | null;
52
+ }
53
+ /** Source-document proxy registers only finite delegates, never another controller. */
54
+ export declare function registerHistoireSessionInternals(session: HistoireSession, delegates: SessionInternals): void;
55
+ /** Fully validate, detach, and freeze one source descriptor before branding it accepted. */
56
+ export declare function acceptHistoireSourceDescriptor(value: unknown): HistoireSourceDescriptor;
57
+ /** Checks identity against SDK-minted immutable projections; shape alone never grants trust. */
58
+ export declare function isAcceptedHistoireSourceDescriptor(value: unknown): value is HistoireSourceDescriptor;
59
+ /** Select one known docs link through explicit standalone adapter or router-free native controller. */
60
+ export declare function selectHistoireStoryLink(session: HistoireSession, link: HistoireStoryLink): Promise<void>;
61
+ /**
62
+ * Routes docs story links of `session` through `owner`, keeping its other delegates.
63
+ * Passive replica sessions own isolated selection; their documentation links must
64
+ * still navigate the workbench that owns the canonical selection and URL.
65
+ */
66
+ export declare function delegateHistoireStoryLinks(session: HistoireSession, owner: HistoireSession): void;
67
+ /** Trust is granted by first-party local adapter, never URL/origin/source descriptor. */
68
+ export declare function getHistoireDocsPolicy(session: HistoireSession): 'trusted-local' | 'remote';
69
+ /** Compatibility type entry; protocol owns finite preset wire definitions. */
70
+ export type { HistoirePresetAction, HistoirePresetList } from '@histoire/protocol';
71
+ /** Bind private context without exposing adapters/controller through internal getters. */
72
+ export declare function bindHistoireSessionInternals(session: HistoireSession, context: SessionContext, selectionSettled: () => Promise<void>): void;
73
+ /** First-party layout transitions await current selection ACK without replay or public state fields. */
74
+ export declare function waitForHistoireSelection(session: HistoireSession): Promise<void>;
75
+ /** First-party primary wrappers cannot admit a closing handle from snapshot identity alone. */
76
+ export declare function isHistoirePrimaryMountActive(session: HistoireSession, mount: HistoireMount): boolean;
77
+ /** Detached current source descriptor; no mutable source config or adapter access. */
78
+ export declare function getHistoireSessionDescriptor(session: HistoireSession): HistoireSourceDescriptor;
79
+ /** Returns branded metadata when module copies agree, else uses the detached legacy delegate. */
80
+ export declare function getAcceptedHistoireSessionDescriptor(session: HistoireSession): HistoireSourceDescriptor;
81
+ /** Current target can expose an editor action only for a ready project-owned dev story. */
82
+ export declare function canOpenHistoireTargetInEditor(snapshot: EditorActionSnapshot, target?: Readonly<HistoireTarget> | null): boolean;
83
+ /** Capture current primary through existing operation guards; no implicit runtime creation. */
84
+ export declare function requestHistoireStatePreset(session: HistoireSession, input: HistoirePresetAction): Promise<HistoirePresetList>;
85
+ /** First-party target-only editor action; arbitrary caller paths never enter transport. */
86
+ export declare function requestHistoireOpenInEditor(session: HistoireSession, target: HistoireTarget): Promise<null>;
87
+ //# sourceMappingURL=internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../../src/session/internal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACpM,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAQlD,qGAAqG;AACrG,MAAM,WAAW,iBAAiB;IAChC,qFAAqF;IACrF,QAAQ,CAAC,SAAS,EAAE,sBAAsB,CAAA;IAC1C,gFAAgF;IAChF,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,kFAAkF;AAClF,UAAU,gBAAgB;IACxB,UAAU,EAAE,MAAM,wBAAwB,CAAA;IAC1C,oEAAoE;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6BAA6B,CAAC,QAAQ,EAAE,oBAAoB,EAAE,MAAM,GAAE,QAAQ,CAAC,cAAc,CAAC,GAAG,IAAyB,GAAG,OAAO,CAInJ;AAED,+FAA+F;AAC/F,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAS7H;AAED,2FAA2F;AAC3F,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3G"}
@@ -0,0 +1,144 @@
1
+ import { HistoireSdkError, isHistoireProjectFileOrigin, validateBridgePayload, validateHistoireSourceDescriptor } from '@histoire/protocol';
2
+ import { observeOperation } from './ownership.js';
3
+ import { request } from './request.js';
4
+ import { copyProjection, freezeProjection } from './snapshot.js';
5
+ import { primaryRuntime } from './state.js';
6
+ import { assertVariant } from './variant.js';
7
+ const sessions = new WeakMap();
8
+ const internalsKey = Symbol.for('@histoire/sdk/session-internals/protocol-1');
9
+ const acceptedDescriptors = new WeakSet();
10
+ /** Separate SDK/native bundles resolve delegates on same owned controller, never global active state. */
11
+ function internals(session) {
12
+ return sessions.get(session) ?? session[internalsKey];
13
+ }
14
+ /** Source-document proxy registers only finite delegates, never another controller. */
15
+ export function registerHistoireSessionInternals(session, delegates) {
16
+ sessions.set(session, delegates);
17
+ if (!Object.hasOwn(session, internalsKey))
18
+ Object.defineProperty(session, internalsKey, { get: () => sessions.get(session), enumerable: false });
19
+ }
20
+ /** Fully validate, detach, and freeze one source descriptor before branding it accepted. */
21
+ export function acceptHistoireSourceDescriptor(value) {
22
+ const descriptor = copyProjection(validateHistoireSourceDescriptor(value));
23
+ freezeProjection(descriptor);
24
+ acceptedDescriptors.add(descriptor);
25
+ return descriptor;
26
+ }
27
+ /** Checks identity against SDK-minted immutable projections; shape alone never grants trust. */
28
+ export function isAcceptedHistoireSourceDescriptor(value) {
29
+ return typeof value === 'object' && value !== null && acceptedDescriptors.has(value);
30
+ }
31
+ /** Select one known docs link through explicit standalone adapter or router-free native controller. */
32
+ export function selectHistoireStoryLink(session, link) {
33
+ try {
34
+ return observeOperation(internals(session)?.storyLink?.(link) ?? session.selection.select(link.selection));
35
+ }
36
+ catch (error) {
37
+ return observeOperation(Promise.reject(error));
38
+ }
39
+ }
40
+ /**
41
+ * Routes docs story links of `session` through `owner`, keeping its other delegates.
42
+ * Passive replica sessions own isolated selection; their documentation links must
43
+ * still navigate the workbench that owns the canonical selection and URL.
44
+ */
45
+ export function delegateHistoireStoryLinks(session, owner) {
46
+ const current = internals(session);
47
+ if (!current)
48
+ throw new TypeError('Session internals unavailable');
49
+ sessions.set(session, { ...current, storyLink: link => selectHistoireStoryLink(owner, link) });
50
+ }
51
+ /** Trust is granted by first-party local adapter, never URL/origin/source descriptor. */
52
+ export function getHistoireDocsPolicy(session) {
53
+ return internals(session)?.docsPolicy ?? 'remote';
54
+ }
55
+ /** Bind private context without exposing adapters/controller through internal getters. */
56
+ export function bindHistoireSessionInternals(session, context, selectionSettled) {
57
+ registerHistoireSessionInternals(session, {
58
+ selectionSettled,
59
+ primaryMountActive(mount) {
60
+ const owned = context.mounts.get(mount.id);
61
+ return context.primaryId === mount.id && owned?.handle === mount && owned.active;
62
+ },
63
+ descriptor() {
64
+ context.assertConnected();
65
+ return structuredClone(context.descriptor);
66
+ },
67
+ acceptedDescriptor() {
68
+ context.assertConnected();
69
+ return context.descriptor;
70
+ },
71
+ async openInEditor(target) {
72
+ validateBridgePayload('openInEditor', target);
73
+ context.assertCapability('openInEditor');
74
+ const story = context.story(target.storyId);
75
+ if (!isHistoireProjectFileOrigin(story.fileOrigin))
76
+ throw new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Editor is unavailable for non-project stories');
77
+ if (target.variantId != null)
78
+ assertVariant(story, target.variantId);
79
+ return request(context, context.assertConnected(), 'openInEditor', target);
80
+ },
81
+ async presets(input) {
82
+ validateBridgePayload('controls.preset', input);
83
+ const primary = primaryRuntime(context);
84
+ const result = await request(context, primary.transport, 'controls.preset', input, { kind: 'runtime', mountId: primary.handle.id });
85
+ if (input.action === 'apply' || input.action === 'delete')
86
+ await session.state.get();
87
+ return result;
88
+ },
89
+ });
90
+ }
91
+ /** First-party layout transitions await current selection ACK without replay or public state fields. */
92
+ export function waitForHistoireSelection(session) {
93
+ return internals(session)?.selectionSettled?.() ?? Promise.resolve();
94
+ }
95
+ /** First-party primary wrappers cannot admit a closing handle from snapshot identity alone. */
96
+ export function isHistoirePrimaryMountActive(session, mount) {
97
+ return internals(session)?.primaryMountActive?.(mount) ?? false;
98
+ }
99
+ /** Detached current source descriptor; no mutable source config or adapter access. */
100
+ export function getHistoireSessionDescriptor(session) {
101
+ const entry = internals(session);
102
+ if (!entry)
103
+ throw new HistoireSdkError('NOT_CONNECTED', 'First-party session metadata unavailable');
104
+ return entry.descriptor();
105
+ }
106
+ /** Returns branded metadata when module copies agree, else uses the detached legacy delegate. */
107
+ export function getAcceptedHistoireSessionDescriptor(session) {
108
+ const entry = internals(session);
109
+ if (!entry)
110
+ throw new HistoireSdkError('NOT_CONNECTED', 'Accepted first-party session metadata unavailable');
111
+ const descriptor = entry.acceptedDescriptor?.();
112
+ return isAcceptedHistoireSourceDescriptor(descriptor) ? descriptor : entry.descriptor();
113
+ }
114
+ /** Current target can expose an editor action only for a ready project-owned dev story. */
115
+ export function canOpenHistoireTargetInEditor(snapshot, target = snapshot.selection) {
116
+ if (!target || snapshot.status !== 'ready' || snapshot.stale || snapshot.source?.mode !== 'dev' || !snapshot.capabilities.openInEditor.available)
117
+ return false;
118
+ const story = snapshot.catalog.stories.find(story => story.id === target.storyId);
119
+ return !!story && isHistoireProjectFileOrigin(story.fileOrigin);
120
+ }
121
+ /** Capture current primary through existing operation guards; no implicit runtime creation. */
122
+ export function requestHistoireStatePreset(session, input) {
123
+ const entry = internals(session);
124
+ if (!entry)
125
+ return observeOperation(Promise.reject(new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Runtime preset adapter unavailable')));
126
+ try {
127
+ return observeOperation(entry.presets(input));
128
+ }
129
+ catch (error) {
130
+ return observeOperation(Promise.reject(error));
131
+ }
132
+ }
133
+ /** First-party target-only editor action; arbitrary caller paths never enter transport. */
134
+ export function requestHistoireOpenInEditor(session, target) {
135
+ const entry = internals(session);
136
+ if (!entry?.openInEditor)
137
+ return observeOperation(Promise.reject(new HistoireSdkError('CAPABILITY_UNAVAILABLE', 'Editor adapter unavailable')));
138
+ try {
139
+ return observeOperation(entry.openInEditor(target));
140
+ }
141
+ catch (error) {
142
+ return observeOperation(Promise.reject(error));
143
+ }
144
+ }
@@ -0,0 +1,6 @@
1
+ import type { HistoireEmbedPresentation, HistoireSurface } from '@histoire/protocol';
2
+ import type { HistoireMount } from '../types.js';
3
+ import type { SessionContext } from './context.js';
4
+ /** Reserve primary synchronously before invoking any browser/source adapter. */
5
+ export declare function mountSurface(context: SessionContext, container: HTMLElement | undefined, surface: HistoireSurface, hidden?: boolean, input?: HistoireEmbedPresentation, paddingInput?: number): HistoireMount;
6
+ //# sourceMappingURL=mounts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mounts.d.ts","sourceRoot":"","sources":["../../src/session/mounts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,cAAc,CAAA;AAuD9D,gFAAgF;AAChF,wBAAgB,YAAY,CAAC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,WAAW,GAAG,SAAS,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,UAAQ,EAAE,KAAK,CAAC,EAAE,yBAAyB,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,aAAa,CA8E3M"}