@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,112 @@
1
+ import { HistoireSdkError, validateEmbedOrigin, validateHistoireAck, writeEmbedPadding, writeEmbedPresentation } from '@histoire/protocol';
2
+ import { HISTOIRE_CONTROL_TIMEOUT } from './validation.js';
3
+ let nextNonce = 0;
4
+ /** Create one frame and transferred port, with exact-origin port-only acknowledgment. */
5
+ export function createBridgeFrame(options) {
6
+ const document = options.container.ownerDocument;
7
+ const parentWindow = document.defaultView;
8
+ if (!parentWindow) {
9
+ throw new HistoireSdkError('BROWSER_REQUIRED', 'Attachment requires browser document');
10
+ }
11
+ const parentOrigin = validateEmbedOrigin(parentWindow.location.origin);
12
+ const base = new URL(options.url);
13
+ const url = new URL('__embed.html', base);
14
+ if (options.presentation)
15
+ writeEmbedPresentation(url.searchParams, options.presentation);
16
+ if (options.padding !== undefined)
17
+ writeEmbedPadding(url.searchParams, options.padding);
18
+ const hello = { kind: 'histoire:hello', protocolRange: { min: 1, max: 1 }, nonce: `${Date.now()}:${++nextNonce}:${Math.random()}`, sessionId: options.sessionId, mountId: options.mountId, parentOrigin, role: options.role };
19
+ for (const [key, value] of Object.entries({ view: options.surface ? 'surface' : 'bridge', ...(options.surface ? { surface: options.surface } : {}), parentOrigin, sessionId: options.sessionId, mountId: options.mountId })) {
20
+ url.searchParams.set(key, value);
21
+ }
22
+ const iframe = document.createElement('iframe');
23
+ iframe.title = options.presentation ? 'Histoire embed' : options.surface === 'preview' ? 'Histoire canvas' : options.surface ? `Histoire ${options.surface}` : 'Histoire source bridge';
24
+ iframe.style.cssText = options.surface ? 'border:0;width:100%;height:100%;display:block' : 'position:absolute;width:1px;height:1px;border:0;opacity:0;pointer-events:none';
25
+ const channel = new MessageChannel();
26
+ let active = true;
27
+ let loaded = false;
28
+ let acknowledged = false;
29
+ let rejectHandshake = () => {
30
+ };
31
+ let timer;
32
+ const ready = new Promise((resolve, reject) => {
33
+ rejectHandshake = reject;
34
+ timer = setTimeout(() => reject(new HistoireSdkError('TIMEOUT', 'Source handshake timed out')), HISTOIRE_CONTROL_TIMEOUT);
35
+ const receive = (event) => {
36
+ if (!active || acknowledged) {
37
+ return;
38
+ }
39
+ try {
40
+ const ack = validateHistoireAck(event.data, hello);
41
+ if (!ack.ok) {
42
+ throw new HistoireSdkError(ack.error.code, ack.error.message, ack.error.details);
43
+ }
44
+ acknowledged = true;
45
+ clearTimeout(timer);
46
+ channel.port1.removeEventListener('message', receive);
47
+ resolve({ port: channel.port1, ack });
48
+ }
49
+ catch (error) {
50
+ reject(error);
51
+ }
52
+ };
53
+ channel.port1.addEventListener('message', receive);
54
+ channel.port1.start();
55
+ });
56
+ void ready.catch(() => close());
57
+ /** Mark attachment inactive before removing listeners, port or DOM. */
58
+ function close() {
59
+ if (!active) {
60
+ return;
61
+ }
62
+ active = false;
63
+ clearTimeout(timer);
64
+ options.signal.removeEventListener('abort', abort);
65
+ iframe.removeEventListener('load', load);
66
+ iframe.removeEventListener('error', failed);
67
+ channel.port1.close();
68
+ channel.port2.close();
69
+ iframe.remove();
70
+ rejectHandshake(new HistoireSdkError('NOT_CONNECTED', 'Frame closed before handshake'));
71
+ }
72
+ /** Same WindowProxy navigation still retires old document and pending work. */
73
+ function load() {
74
+ if (!active) {
75
+ return;
76
+ }
77
+ if (loaded) {
78
+ options.disconnected?.();
79
+ close();
80
+ return;
81
+ }
82
+ loaded = true;
83
+ iframe.contentWindow?.postMessage(hello, base.origin, [channel.port2]);
84
+ }
85
+ /** Network/navigation failure cannot masquerade as view readiness. */
86
+ function failed() {
87
+ rejectHandshake(new HistoireSdkError('BOOK_UNAVAILABLE', 'Source document failed to load'));
88
+ close();
89
+ }
90
+ /** Controller cancellation settles handshake before releasing frame. */
91
+ function abort() {
92
+ rejectHandshake(options.signal.reason ?? new HistoireSdkError('CANCELLED', 'Connection cancelled'));
93
+ close();
94
+ }
95
+ iframe.addEventListener('load', load);
96
+ iframe.addEventListener('error', failed);
97
+ options.signal.addEventListener('abort', abort, { once: true });
98
+ if (options.signal.aborted) {
99
+ abort();
100
+ }
101
+ else {
102
+ try {
103
+ iframe.src = url.href;
104
+ options.container.append(iframe);
105
+ }
106
+ catch (error) {
107
+ close();
108
+ throw error;
109
+ }
110
+ }
111
+ return { iframe, ready, close };
112
+ }
@@ -0,0 +1,15 @@
1
+ import type { HistoireBridgeIdentity, HistoireBridgeRequest } from '@histoire/protocol';
2
+ /** Inbound test execution owns one abort controller per exact transferred-port request. */
3
+ export declare function createInboundBridgeDispatch(dispatch: ((request: HistoireBridgeRequest, signal: AbortSignal) => unknown | Promise<unknown>) | undefined): {
4
+ /** Source execution outlives runtime; validate its cancellation against captured owner. */
5
+ sourceCancellationOwner(input: {
6
+ kind?: unknown;
7
+ command?: unknown;
8
+ payload?: unknown;
9
+ }): HistoireBridgeIdentity | undefined;
10
+ /** Ack retires publication; dispatch stays observed until actual cleanup. */
11
+ run(request: HistoireBridgeRequest): Promise<unknown>;
12
+ /** Frame teardown cancels only this port's work; cleanup remains observed. */
13
+ close(): void;
14
+ };
15
+ //# sourceMappingURL=inbound.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../src/transport/inbound.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAGvF,2FAA2F;AAC3F,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,CAAC,CAAC,OAAO,EAAE,qBAAqB,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS;IASnJ,2FAA2F;IAC3F,uBAAuB,QAAQ;QAAE,IAAI,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,sBAAsB,GAAG,SAAS;IAM5H,6EAA6E;IACvE,GAAG,UAAU,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC;IAqB3D,8EAA8E;IAC9E,KAAK;EAER"}
@@ -0,0 +1,51 @@
1
+ import { HistoireSdkError } from '@histoire/protocol';
2
+ /** Inbound test execution owns one abort controller per exact transferred-port request. */
3
+ export function createInboundBridgeDispatch(dispatch) {
4
+ const active = new Map();
5
+ const lifetime = new AbortController();
6
+ /** Captured metadata equality prevents cancelling another document or target on this port. */
7
+ function sameOwner(left, right) {
8
+ return ['protocolVersion', 'sessionId', 'connectionId', 'mountId', 'sourceId', 'epoch', 'revision', 'runtimeId', 'selectionVersion'].every(key => left[key] === right[key])
9
+ && left.target?.storyId === right.target?.storyId && left.target?.variantId === right.target?.variantId;
10
+ }
11
+ return {
12
+ /** Source execution outlives runtime; validate its cancellation against captured owner. */
13
+ sourceCancellationOwner(input) {
14
+ if (input.kind !== 'request' || !['tests.cancel', 'inspection.cancel'].includes(input.command) || !input.payload || typeof input.payload !== 'object')
15
+ return;
16
+ const requestId = input.payload.requestId;
17
+ const entry = typeof requestId === 'string' ? active.get(requestId) : undefined;
18
+ if (entry && ((entry.request.command === 'tests.run' && entry.request.payload.mode === 'server') || entry.request.command.startsWith('inspection.')))
19
+ return entry.request;
20
+ },
21
+ /** Ack retires publication; dispatch stays observed until actual cleanup. */
22
+ async run(request) {
23
+ if (request.command === 'tests.cancel' || request.command === 'inspection.cancel') {
24
+ const requestId = request.payload.requestId;
25
+ const entry = active.get(requestId);
26
+ const matchesCommand = request.command === 'tests.cancel' ? ['tests.run', 'tests.collect'].includes(entry?.request.command ?? '') : Boolean(entry?.request.command.startsWith('inspection.') && entry.request.command !== 'inspection.cancel');
27
+ if (!entry || !matchesCommand || !sameOwner(entry.request, request))
28
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'No matching request on this port');
29
+ entry.abort.abort(new HistoireSdkError('CANCELLED', 'Request cancelled'));
30
+ return { requestId, cancelled: true };
31
+ }
32
+ if (!['tests.run', 'tests.collect'].includes(request.command) && !request.command.startsWith('inspection.'))
33
+ return dispatch?.(request, lifetime.signal);
34
+ if (active.has(request.requestId))
35
+ throw new HistoireSdkError('INVALID_ARGUMENT', 'Duplicate test request identity');
36
+ const abort = new AbortController();
37
+ active.set(request.requestId, { request, abort });
38
+ const signal = AbortSignal.any([abort.signal, lifetime.signal]);
39
+ try {
40
+ const result = await dispatch?.(request, signal);
41
+ signal.throwIfAborted();
42
+ return result;
43
+ }
44
+ finally {
45
+ active.delete(request.requestId);
46
+ }
47
+ },
48
+ /** Frame teardown cancels only this port's work; cleanup remains observed. */
49
+ close() { lifetime.abort(new HistoireSdkError('NOT_CONNECTED', 'Port closed')); },
50
+ };
51
+ }
@@ -0,0 +1,51 @@
1
+ import type { HistoireBridgeCommand, HistoireBridgeIdentity, HistoireBridgePublication, HistoireBridgeRequest, HistoirePortRole, HistoireSourceDescriptor, HistoireTarget } from '@histoire/protocol';
2
+ import type { HistoireRequestCapture, HistoireSessionNotification } from '../adapters/types.js';
3
+ /** Dedicated port options captured once during handshake. */
4
+ export interface BridgePortOptions {
5
+ /** Transferred channel endpoint; never shared among mounts. */
6
+ port: MessagePort;
7
+ /** Negotiated exact source/session/mount identity. */
8
+ owner: HistoireBridgeIdentity;
9
+ /** Authority established by document bootstrap. */
10
+ role: HistoirePortRole;
11
+ /** Child endpoint reverses request/publication direction. */
12
+ child?: boolean;
13
+ /** Source budgets for execution requests. */
14
+ descriptor?: HistoireSourceDescriptor;
15
+ /** Finite inbound method dispatch; replies retain captured request owner. */
16
+ dispatch?: (request: HistoireBridgeRequest, signal: AbortSignal) => Promise<unknown> | unknown;
17
+ /** First-party validated publication hook. */
18
+ publication?: (event: HistoireBridgePublication) => void;
19
+ }
20
+ /** One inbound trust gate owns correlation, sequence, sizing, rate and lifecycle. */
21
+ export declare function createBridgePort(options: BridgePortOptions): {
22
+ id: string;
23
+ /** Bound identity for first-party frame synchronization; returned copy has no authority. */
24
+ getOwner: () => {
25
+ protocolVersion: number;
26
+ sessionId: string;
27
+ connectionId: string;
28
+ mountId: string;
29
+ sourceId: string;
30
+ epoch: string;
31
+ revision: string;
32
+ runtimeId?: string;
33
+ target?: HistoireTarget;
34
+ selectionVersion?: number;
35
+ };
36
+ /** Local host owns both endpoints; canonical revision/selection advance before direct runtime observers. */
37
+ synchronizeSelection(target: HistoireTarget | null, localOwner: HistoireBridgeIdentity, cause?: string): string | undefined;
38
+ /** Send once with exact captured runtime/source ownership. */
39
+ request<T = unknown>(command: HistoireBridgeCommand, payload: unknown, capture: HistoireRequestCapture): Promise<T>;
40
+ /** Publish one validated, monotonically sequenced future event. */
41
+ post(event: HistoireBridgePublication['event'], payload: unknown, runtime?: Partial<HistoireBridgeIdentity>): void;
42
+ /** Observe future SDK notifications; no implicit callback. */
43
+ subscribe(listener: (notification: HistoireSessionNotification) => void): () => void;
44
+ /** Local frame navigation marks controller stale before endpoint closes. */
45
+ disconnect: () => void;
46
+ /** Retire pending operations when frame load or source generation changes. */
47
+ close: () => void;
48
+ };
49
+ /** First-party endpoint shape reused by view and source documents. */
50
+ export type HistoireBridgePort = ReturnType<typeof createBridgePort>;
51
+ //# sourceMappingURL=port.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"port.d.ts","sourceRoot":"","sources":["../../src/transport/port.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACrM,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAA;AAQ/F,6DAA6D;AAC7D,MAAM,WAAW,iBAAiB;IAChC,+DAA+D;IAC/D,IAAI,EAAE,WAAW,CAAA;IACjB,sDAAsD;IACtD,KAAK,EAAE,sBAAsB,CAAA;IAC7B,mDAAmD;IACnD,IAAI,EAAE,gBAAgB,CAAA;IACtB,6DAA6D;IAC7D,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,6CAA6C;IAC7C,UAAU,CAAC,EAAE,wBAAwB,CAAA;IACrC,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,qBAAqB,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;IAC9F,8CAA8C;IAC9C,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,yBAAyB,KAAK,IAAI,CAAA;CACzD;AACD,qFAAqF;AACrF,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB;;IA4LvD,4FAA4F;;;;;;;;;;;;;IAE5F,4GAA4G;iCAC/E,cAAc,GAAG,IAAI,cAAc,sBAAsB,UAAU,MAAM,GAAG,MAAM,GAAG,SAAS;IAS3H,8DAA8D;YACtD,CAAC,qBAAqB,qBAAqB,WAAW,OAAO,WAAW,sBAAsB,GAAG,OAAO,CAAC,CAAC,CAAC;IAwCnH,mEAAmE;gBACvD,yBAAyB,CAAC,OAAO,CAAC,WAAW,OAAO,YAAW,OAAO,CAAC,sBAAsB,CAAC;IAiB1G,8DAA8D;wBAC1C,CAAC,YAAY,EAAE,2BAA2B,KAAK,IAAI;IAMvE,4EAA4E;sBAzFvD,IAAI;IA2FzB,8EAA8E;iBAxG1D,IAAI;EA2G3B;AACD,sEAAsE;AACtE,MAAM,MAAM,kBAAkB,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAA"}
@@ -0,0 +1,288 @@
1
+ import { HistoireSdkError, validateBridgeEnvelope, validateBridgeEnvelopeBody, wireRecord } from '@histoire/protocol';
2
+ import { acceptBridgeViewSelection, advanceBridgeSelection, advanceBridgeSourceRevision, createBridgeRuntimeAuthority, createBridgeSelectionEcho, getBridgeIncomingOwner, isBridgeSourcePublication, isBridgeSourceRequest, synchronizeBridgeSelection, validateLocalBridgeSelection } from './authority.js';
3
+ import { createInboundBridgeDispatch } from './inbound.js';
4
+ import { createBridgeReplies } from './reply.js';
5
+ import { createBridgeRequests } from './requests.js';
6
+ import { markValidatedNotification } from './validated.js';
7
+ import { getBridgeRequestTimeout } from './validation.js';
8
+ /** One inbound trust gate owns correlation, sequence, sizing, rate and lifecycle. */
9
+ export function createBridgePort(options) {
10
+ let owner = { ...options.owner, selectionVersion: options.owner.selectionVersion ?? 0 };
11
+ /** Direct local snapshot authority supersedes queued source publications. */
12
+ let localRevision;
13
+ let active = true;
14
+ let sequence = -1;
15
+ let outboundSequence = 0;
16
+ let rateStart = Date.now();
17
+ let rateCount = 0;
18
+ const runtimes = createBridgeRuntimeAuthority();
19
+ const listeners = new Set();
20
+ const requests = createBridgeRequests();
21
+ const selectionEcho = createBridgeSelectionEcho();
22
+ const inbound = createInboundBridgeDispatch(options.dispatch ? (request, signal) => selectionEcho.dispatch(request, Boolean(options.child), () => options.dispatch(request, signal)) : undefined);
23
+ const lifetime = new AbortController();
24
+ const direction = options.child ? 'parent-to-child' : 'child-to-parent';
25
+ const outward = options.child ? 'child-to-parent' : 'parent-to-child';
26
+ /** Emitted notifications derive from fully validated envelopes or local state. */
27
+ const emit = (value) => {
28
+ if (active) {
29
+ markValidatedNotification(value);
30
+ for (const listener of [...listeners]) {
31
+ try {
32
+ listener(value);
33
+ }
34
+ catch {
35
+ }
36
+ }
37
+ }
38
+ };
39
+ const notificationOwner = () => ({ connectionId: owner.connectionId, sourceId: owner.sourceId, epoch: owner.epoch, revision: owner.revision, mountId: owner.mountId, ...(owner.runtimeId ? { runtimeId: owner.runtimeId } : {}) });
40
+ const dropped = (stale = false) => {
41
+ emit({ type: 'dropped', ...notificationOwner(), count: 1, stale });
42
+ if (stale) {
43
+ requests.reject(new HistoireSdkError('STALE_REVISION', 'Required publication dropped'));
44
+ }
45
+ };
46
+ /** Publish only validated portable notifications; runtime transitions may allocate new document IDs. */
47
+ function publish(event) {
48
+ const payload = event.payload;
49
+ if (event.event === 'catalog.changed') {
50
+ if (localRevision !== undefined && event.revision !== localRevision)
51
+ return;
52
+ owner = advanceBridgeSourceRevision(owner, event.revision, requests);
53
+ emit({ type: 'catalog', ...notificationOwner(), descriptor: payload.descriptor });
54
+ }
55
+ else if (event.event === 'source.disconnected') {
56
+ requests.reject(new HistoireSdkError('NOT_CONNECTED', 'Source disconnected'));
57
+ disconnect();
58
+ }
59
+ else if (event.event === 'readiness.changed') {
60
+ const runtime = payload.runtime;
61
+ if (!runtimes.accepts(event, owner)) {
62
+ return;
63
+ }
64
+ if (runtimes.retire(event, owner)) {
65
+ requests.reject(new HistoireSdkError('RUNTIME_CHANGED', 'Runtime document changed'), item => Boolean(item.owner.runtimeId) && !item.source && !['selection.select', 'view.sync'].includes(item.command));
66
+ }
67
+ owner = { ...owner, runtimeId: runtime.runtimeId ?? undefined, target: event.target ?? owner.target };
68
+ emit({ type: 'runtime', ...notificationOwner(), runtime });
69
+ }
70
+ else if (event.event === 'state.changed') {
71
+ emit({ type: 'state', ...notificationOwner(), state: payload });
72
+ }
73
+ else if (event.event === 'layout.changed') {
74
+ emit({ type: 'layout', ...notificationOwner(), viewports: payload.viewports });
75
+ }
76
+ else if (event.event === 'events.appended') {
77
+ for (const event of payload.items) {
78
+ emit({ type: 'event', ...notificationOwner(), event });
79
+ }
80
+ if (payload.droppedCount) {
81
+ emit({ type: 'dropped', ...notificationOwner(), count: payload.droppedCount });
82
+ }
83
+ }
84
+ else if (event.event === 'channel.message' || event.event === 'plugin.message') {
85
+ emit({ ...(event.event === 'channel.message' ? { type: 'channel' } : { type: 'plugin' }), ...notificationOwner(), message: payload });
86
+ }
87
+ options.publication?.(event);
88
+ }
89
+ const dispatch = createBridgeReplies(options, inbound, () => active, () => ++outboundSequence);
90
+ /** Validate owner before expensive payload traversal or correctly correlated oversize settlement. */
91
+ function receive(message) {
92
+ if (!active) {
93
+ return;
94
+ }
95
+ let raw;
96
+ try {
97
+ raw = wireRecord(message.data);
98
+ }
99
+ catch {
100
+ return;
101
+ }
102
+ const pending = raw.kind === 'response' && typeof raw.requestId === 'string' ? requests.get(raw.requestId) : undefined;
103
+ if (raw.kind === 'response' && !pending) {
104
+ return;
105
+ }
106
+ const replacement = options.child && raw.kind === 'request' && ['selection.select', 'view.sync'].includes(raw.command);
107
+ const sourceCancellation = inbound.sourceCancellationOwner(raw);
108
+ // Parent replacement and captured replies may retain predecessor attribution.
109
+ // New work/publications from that predecessor never regain authority.
110
+ if (!pending && !replacement && !sourceCancellation && runtimes.isRetired(raw.runtimeId) && !(raw.kind === 'event' && isBridgeSourcePublication(raw.event)) && !(raw.kind === 'request' && isBridgeSourceRequest(raw.command, raw.payload)))
111
+ return;
112
+ const expected = getBridgeIncomingOwner(owner, raw, Boolean(options.child), pending, sourceCancellation);
113
+ // Metadata validated once before rate gating; body and failure paths reuse the result.
114
+ let identified = false;
115
+ try {
116
+ validateBridgeEnvelope(raw, expected, options.role, pending?.command, direction, true);
117
+ identified = true;
118
+ if (raw.kind === 'event') {
119
+ if (Date.now() - rateStart >= 1000) {
120
+ rateStart = Date.now();
121
+ rateCount = 0;
122
+ }
123
+ if (++rateCount > 200) {
124
+ dropped(['catalog.changed', 'state.changed', 'layout.changed', 'readiness.changed'].includes(raw.event));
125
+ return;
126
+ }
127
+ }
128
+ const envelope = validateBridgeEnvelopeBody(raw, options.role, pending?.command, direction);
129
+ if (envelope.kind === 'response') {
130
+ requests.receive(envelope);
131
+ }
132
+ else if (envelope.kind === 'request') {
133
+ if (!options.dispatch) {
134
+ return;
135
+ }
136
+ if (replacement) {
137
+ // Preserve only the exact accepted intent's echo; independent host
138
+ // navigation settles old intent even when its requested target matches.
139
+ owner = envelope.command === 'view.sync' ? acceptBridgeViewSelection(owner, envelope, requests) : advanceBridgeSelection(owner, envelope.target, requests);
140
+ }
141
+ void dispatch(envelope).catch(() => {
142
+ });
143
+ }
144
+ else {
145
+ if (envelope.sequence <= sequence) {
146
+ return;
147
+ }
148
+ sequence = envelope.sequence;
149
+ publish(envelope);
150
+ }
151
+ }
152
+ catch (error) {
153
+ if (pending) {
154
+ try {
155
+ // Replace body only for identity validation. Wrong-owner messages cannot
156
+ // reject someone else's operation, including oversized forged replies.
157
+ validateBridgeEnvelope({ protocolVersion: raw.protocolVersion, sessionId: raw.sessionId, connectionId: raw.connectionId, mountId: raw.mountId, sourceId: raw.sourceId, epoch: raw.epoch, revision: raw.revision, ...(raw.runtimeId === undefined ? {} : { runtimeId: raw.runtimeId }), ...(raw.target === undefined ? {} : { target: raw.target }), ...(raw.selectionVersion === undefined ? {} : { selectionVersion: raw.selectionVersion }), kind: 'response', requestId: raw.requestId, ok: false, error: { code: 'INVALID_ARGUMENT', message: 'Invalid result' } }, expected, options.role, pending.command, direction);
158
+ pending.settle({ error });
159
+ }
160
+ catch {
161
+ }
162
+ }
163
+ else if (raw.kind === 'event' && identified) {
164
+ try {
165
+ dropped(['catalog.changed', 'state.changed', 'layout.changed', 'readiness.changed'].includes(raw.event));
166
+ }
167
+ catch {
168
+ }
169
+ }
170
+ }
171
+ }
172
+ options.port.addEventListener('message', receive);
173
+ options.port.start();
174
+ /** Retire synchronously before closing resources or rejecting pending work. */
175
+ function closePort() {
176
+ if (!active) {
177
+ return;
178
+ }
179
+ active = false;
180
+ lifetime.abort();
181
+ inbound.close();
182
+ requests.reject(new HistoireSdkError('NOT_CONNECTED', 'Port closed'));
183
+ options.port.removeEventListener('message', receive);
184
+ options.port.close();
185
+ listeners.clear();
186
+ }
187
+ /** Data disconnect retires source; surface disconnect retires only its runtime. */
188
+ function disconnect() {
189
+ if (options.role === 'data') {
190
+ emit({ type: 'disconnect', ...notificationOwner() });
191
+ }
192
+ else {
193
+ emit({ type: 'runtime', ...notificationOwner(), runtime: { status: 'stale', mountId: owner.mountId, runtimeId: owner.runtimeId ?? null, viewports: [], viewport: null } });
194
+ }
195
+ closePort();
196
+ }
197
+ return {
198
+ id: owner.connectionId,
199
+ /** Bound identity for first-party frame synchronization; returned copy has no authority. */
200
+ getOwner: () => ({ ...owner }),
201
+ /** Local host owns both endpoints; canonical revision/selection advance before direct runtime observers. */
202
+ synchronizeSelection(target, localOwner, cause) {
203
+ if (!active)
204
+ throw new HistoireSdkError('NOT_CONNECTED', 'Port is closed');
205
+ validateLocalBridgeSelection(owner, localOwner, target);
206
+ localRevision = localOwner.revision;
207
+ owner = advanceBridgeSourceRevision(owner, localOwner.revision, requests);
208
+ const selectionRequestId = selectionEcho.requestId ?? cause;
209
+ owner = advanceBridgeSelection(owner, target ?? undefined, requests, selectionRequestId);
210
+ return selectionRequestId;
211
+ },
212
+ /** Send once with exact captured runtime/source ownership. */
213
+ request(command, payload, capture) {
214
+ if (!active) {
215
+ return Promise.reject(new HistoireSdkError('NOT_CONNECTED', 'Port is closed'));
216
+ }
217
+ const identity = { ...owner, ...capture, mountId: capture.mountId ?? owner.mountId };
218
+ delete identity.signal;
219
+ // Selection owns mount/target, not document it replaces. A view sync may
220
+ // already have rotated runtime before explicit selection dispatch arrives.
221
+ const selecting = !options.child && command === 'selection.select';
222
+ if (runtimes.isRetired(identity.runtimeId) && !isBridgeSourceRequest(command, payload) && !(!options.child && ['selection.select', 'view.sync'].includes(command)))
223
+ throw new HistoireSdkError('RUNTIME_CHANGED', 'Runtime document retired');
224
+ if (selecting) {
225
+ delete identity.runtimeId;
226
+ }
227
+ const request = { ...identity, kind: 'request', command, requestId: 'validation', payload, ...(!options.child && command === 'view.sync' && selectionEcho.requestId ? { selectionRequestId: selectionEcho.requestId } : {}) };
228
+ validateBridgeEnvelope(request, selecting ? { ...owner, runtimeId: undefined, target: undefined } : owner, options.role, undefined, outward);
229
+ let posted = false;
230
+ const cancellationCommand = ['tests.run', 'tests.collect'].includes(command) ? 'tests.cancel' : command.startsWith('inspection.') && command !== 'inspection.cancel' ? 'inspection.cancel' : undefined;
231
+ const pending = requests.add(command, identity, capture.signal, getBridgeRequestTimeout(command, payload, options.descriptor), cancellationCommand
232
+ ? (requestId) => {
233
+ if (!active || !posted)
234
+ return;
235
+ const cancellation = requests.add(cancellationCommand, identity, lifetime.signal, getBridgeRequestTimeout(cancellationCommand, {}, options.descriptor));
236
+ options.port.postMessage({ ...identity, kind: 'request', command: cancellationCommand, requestId: cancellation.id, payload: { requestId } });
237
+ }
238
+ : undefined, isBridgeSourceRequest(command, payload));
239
+ if (!capture.signal.aborted) {
240
+ try {
241
+ options.port.postMessage({ ...request, requestId: pending.id });
242
+ posted = true;
243
+ // Accept host intent before queued child traffic can dispatch. Reply
244
+ // correlation keeps its captured predecessor owner independently.
245
+ if (!options.child && (selecting || command === 'view.sync')) {
246
+ owner = synchronizeBridgeSelection(owner, selecting ? identity.target : payload.selection ?? undefined);
247
+ }
248
+ }
249
+ catch (error) {
250
+ requests.get(pending.id)?.settle({ error });
251
+ }
252
+ }
253
+ return pending.promise;
254
+ },
255
+ /** Publish one validated, monotonically sequenced future event. */
256
+ post(event, payload, runtime = {}) {
257
+ if (!active) {
258
+ return;
259
+ }
260
+ const envelope = { ...owner, ...runtime, kind: 'event', event, sequence: ++outboundSequence, payload };
261
+ if (event === 'catalog.changed' && localRevision !== undefined && envelope.revision !== localRevision)
262
+ return;
263
+ if (runtimes.isRetired(envelope.runtimeId) && !isBridgeSourcePublication(event))
264
+ return;
265
+ validateBridgeEnvelope(envelope, { ...owner, ...runtime }, options.role, undefined, outward);
266
+ options.port.postMessage(envelope);
267
+ if (event === 'catalog.changed') {
268
+ owner = advanceBridgeSourceRevision(owner, envelope.revision, requests);
269
+ }
270
+ if (event === 'readiness.changed') {
271
+ if (runtimes.retire(envelope, owner))
272
+ requests.reject(new HistoireSdkError('RUNTIME_CHANGED', 'Runtime document changed'), item => Boolean(item.owner.runtimeId) && !item.source && !['selection.select', 'view.sync'].includes(item.command));
273
+ owner = { ...owner, runtimeId: envelope.runtimeId, target: envelope.target ?? owner.target };
274
+ }
275
+ },
276
+ /** Observe future SDK notifications; no implicit callback. */
277
+ subscribe(listener) {
278
+ listeners.add(listener);
279
+ return () => {
280
+ listeners.delete(listener);
281
+ };
282
+ },
283
+ /** Local frame navigation marks controller stale before endpoint closes. */
284
+ disconnect,
285
+ /** Retire pending operations when frame load or source generation changes. */
286
+ close: closePort,
287
+ };
288
+ }
@@ -0,0 +1,6 @@
1
+ import type { HistoireBridgeRequest } from '@histoire/protocol';
2
+ import type { createInboundBridgeDispatch } from './inbound.js';
3
+ import type { BridgePortOptions } from './port.js';
4
+ /** Replies and progress retain exact initiating owner even after frame navigation. */
5
+ export declare function createBridgeReplies(options: BridgePortOptions, inbound: ReturnType<typeof createInboundBridgeDispatch>, active: () => boolean, sequence: () => number): (request: HistoireBridgeRequest) => Promise<void>;
6
+ //# sourceMappingURL=reply.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reply.d.ts","sourceRoot":"","sources":["../../src/transport/reply.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAC/D,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAA;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAGlD,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,UAAU,CAAC,OAAO,2BAA2B,CAAC,EAAE,MAAM,EAAE,MAAM,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,aAE7I,qBAAqB,KAAG,OAAO,CAAC,IAAI,CAAC,CAqC7D"}
@@ -0,0 +1,44 @@
1
+ import { HistoireSdkError, validateBridgeEnvelope } from '@histoire/protocol';
2
+ /** Replies and progress retain exact initiating owner even after frame navigation. */
3
+ export function createBridgeReplies(options, inbound, active, sequence) {
4
+ const outward = options.child ? 'child-to-parent' : 'parent-to-child';
5
+ return async (request) => {
6
+ const { command: _command, payload: _payload, selectionRequestId: _selectionRequestId, ...captured } = request;
7
+ const tests = request.command === 'tests.run' || request.command === 'tests.collect';
8
+ const engine = tests && options.child && ['data', 'primary'].includes(options.role);
9
+ /** Bounded progress uses same source/document/target and unique request as result. */
10
+ function progress(status, extra = {}) {
11
+ if (!engine || !active())
12
+ return;
13
+ const { requestId, ...owner } = captured;
14
+ const event = { ...owner, kind: 'event', event: 'tests.progress', sequence: sequence(), payload: { runId: requestId, status, ...extra } };
15
+ validateBridgeEnvelope(event, request, options.role, undefined, outward);
16
+ options.port.postMessage(event);
17
+ }
18
+ let response;
19
+ try {
20
+ progress(request.command === 'tests.collect' ? 'collecting' : 'running');
21
+ let result = await inbound.run(request);
22
+ // Only engine ports add attribution; view proxies preserve inner engine's
23
+ // initiating request identity rather than inventing another run.
24
+ if (engine) {
25
+ const mode = request.command === 'tests.collect' ? 'preview' : request.payload.mode;
26
+ result = { ...result, execution: { runId: request.requestId, mode, sourceId: request.sourceId, epoch: request.epoch, revision: request.revision, target: request.target, ...(mode === 'preview' ? { runtimeId: request.runtimeId } : {}) } };
27
+ }
28
+ response = { ...captured, kind: 'response', ok: true, result: result ?? null };
29
+ validateBridgeEnvelope(response, request, options.role, request.command, outward);
30
+ // Progress has a smaller wire cap than result. Send bounded counts, never
31
+ // duplicate potentially large assertion diagnostics into an event.
32
+ const total = request.command === 'tests.run' ? result.total : undefined;
33
+ progress('completed', total === undefined ? {} : { completed: total, total });
34
+ }
35
+ catch (error) {
36
+ const failure = { code: error instanceof HistoireSdkError ? error.code : 'INTERNAL_ERROR', message: error instanceof HistoireSdkError ? error.message.slice(0, 2048) : 'Bridge operation failed' };
37
+ response = { ...captured, kind: 'response', ok: false, error: failure };
38
+ validateBridgeEnvelope(response, request, options.role, request.command, outward);
39
+ progress(failure.code === 'CANCELLED' ? 'cancelled' : 'failed', { error: failure });
40
+ }
41
+ if (active())
42
+ options.port.postMessage(response);
43
+ };
44
+ }
@@ -0,0 +1,33 @@
1
+ import type { HistoireBridgeCommand, HistoireBridgeIdentity, HistoireBridgeResponse } from '@histoire/protocol';
2
+ /** One pending operation, bound to exact captured owner and command. */
3
+ export interface BridgePending {
4
+ /** Exact allocated intent, distinct from its desired target and predecessor owner. */
5
+ requestId: string;
6
+ /** Captured command supplies successful-result validator. */
7
+ command: HistoireBridgeCommand;
8
+ /** Captured source/document/target identity. */
9
+ owner: HistoireBridgeIdentity;
10
+ /** Finite metadata/presentation work survives document teardown within same source. */
11
+ source: boolean;
12
+ /** Complete settlement and cancellation cleanup. */
13
+ settle: (value: {
14
+ result: unknown;
15
+ } | {
16
+ error: unknown;
17
+ }) => void;
18
+ }
19
+ /** Correlation registry never retries or reuses request identities. */
20
+ export declare function createBridgeRequests(): {
21
+ /** Lookup happens before untrusted successful-result validation. */
22
+ get: (id: string) => BridgePending | undefined;
23
+ /** Allocate and observe one pending request before posting. */
24
+ add(command: HistoireBridgeCommand, owner: HistoireBridgeIdentity, signal: AbortSignal, timeout: number, cancel?: (id: string) => void, source?: boolean): {
25
+ id: string;
26
+ promise: Promise<unknown>;
27
+ };
28
+ /** Settle exactly once after complete response validation. */
29
+ receive(response: HistoireBridgeResponse): void;
30
+ /** Reject affected work before closing/replacing any resource. */
31
+ reject(error: unknown, predicate?: (item: BridgePending) => boolean): void;
32
+ };
33
+ //# sourceMappingURL=requests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requests.d.ts","sourceRoot":"","sources":["../../src/transport/requests.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AAE/G,wEAAwE;AACxE,MAAM,WAAW,aAAa;IAC5B,sFAAsF;IACtF,SAAS,EAAE,MAAM,CAAA;IACjB,6DAA6D;IAC7D,OAAO,EAAE,qBAAqB,CAAA;IAC9B,gDAAgD;IAChD,KAAK,EAAE,sBAAsB,CAAA;IAC7B,uFAAuF;IACvF,MAAM,EAAE,OAAO,CAAA;IACf,oDAAoD;IACpD,MAAM,EAAE,CAAC,KAAK,EAAE;QACd,MAAM,EAAE,OAAO,CAAA;KAChB,GAAG;QACF,KAAK,EAAE,OAAO,CAAA;KACf,KAAK,IAAI,CAAA;CACX;AACD,uEAAuE;AACvE,wBAAgB,oBAAoB;IAIhC,oEAAoE;cAC1D,MAAM;IAChB,+DAA+D;iBAClD,qBAAqB,SAAS,sBAAsB,UAAU,WAAW,WAAW,MAAM,WAAW,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI;;;;IAuCtI,8DAA8D;sBAC5C,sBAAsB;IAGxC,kEAAkE;kBACpD,OAAO,cAAa,CAAC,IAAI,EAAE,aAAa,KAAK,OAAO;EAQrE"}