@soulcraft/sdk 2.0.0 → 2.0.2

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 (93) hide show
  1. package/dist/client/index.d.ts +5 -38
  2. package/dist/client/index.d.ts.map +1 -1
  3. package/dist/client/index.js +5 -47
  4. package/dist/client/index.js.map +1 -1
  5. package/dist/client/namespace-proxy.d.ts +3 -4
  6. package/dist/client/namespace-proxy.d.ts.map +1 -1
  7. package/dist/client/namespace-proxy.js +3 -4
  8. package/dist/client/namespace-proxy.js.map +1 -1
  9. package/dist/index.d.ts +6 -6
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +4 -4
  12. package/dist/index.js.map +1 -1
  13. package/dist/modules/hall/browser.d.ts +83 -27
  14. package/dist/modules/hall/browser.d.ts.map +1 -1
  15. package/dist/modules/hall/browser.js +238 -49
  16. package/dist/modules/hall/browser.js.map +1 -1
  17. package/dist/modules/hall/media.d.ts +164 -0
  18. package/dist/modules/hall/media.d.ts.map +1 -0
  19. package/dist/modules/hall/media.js +182 -0
  20. package/dist/modules/hall/media.js.map +1 -0
  21. package/dist/modules/hall/server.d.ts +83 -6
  22. package/dist/modules/hall/server.d.ts.map +1 -1
  23. package/dist/modules/hall/server.js +206 -9
  24. package/dist/modules/hall/server.js.map +1 -1
  25. package/dist/modules/hall/types.d.ts +548 -25
  26. package/dist/modules/hall/types.d.ts.map +1 -1
  27. package/dist/modules/hall/types.js +12 -7
  28. package/dist/modules/hall/types.js.map +1 -1
  29. package/dist/server/hall-handlers.d.ts +40 -12
  30. package/dist/server/hall-handlers.d.ts.map +1 -1
  31. package/dist/server/hall-handlers.js +40 -12
  32. package/dist/server/hall-handlers.js.map +1 -1
  33. package/dist/server/handlers/chat/engine.d.ts.map +1 -1
  34. package/dist/server/handlers/chat/engine.js +5 -1
  35. package/dist/server/handlers/chat/engine.js.map +1 -1
  36. package/dist/server/handlers/chat/types.d.ts +17 -2
  37. package/dist/server/handlers/chat/types.d.ts.map +1 -1
  38. package/dist/server/hono-router.d.ts +2 -9
  39. package/dist/server/hono-router.d.ts.map +1 -1
  40. package/dist/server/hono-router.js +2 -46
  41. package/dist/server/hono-router.js.map +1 -1
  42. package/dist/server/index.d.ts +4 -19
  43. package/dist/server/index.d.ts.map +1 -1
  44. package/dist/server/index.js +10 -29
  45. package/dist/server/index.js.map +1 -1
  46. package/dist/types.d.ts +2 -41
  47. package/dist/types.d.ts.map +1 -1
  48. package/docs/ADR-005-hall-integration.md +449 -0
  49. package/package.json +1 -1
  50. package/dist/client/create-client-sdk.d.ts +0 -113
  51. package/dist/client/create-client-sdk.d.ts.map +0 -1
  52. package/dist/client/create-client-sdk.js +0 -169
  53. package/dist/client/create-client-sdk.js.map +0 -1
  54. package/dist/modules/app-context/index.d.ts +0 -214
  55. package/dist/modules/app-context/index.d.ts.map +0 -1
  56. package/dist/modules/app-context/index.js +0 -569
  57. package/dist/modules/app-context/index.js.map +0 -1
  58. package/dist/modules/billing/firestore-provider.d.ts +0 -60
  59. package/dist/modules/billing/firestore-provider.d.ts.map +0 -1
  60. package/dist/modules/billing/firestore-provider.js +0 -315
  61. package/dist/modules/billing/firestore-provider.js.map +0 -1
  62. package/dist/modules/brainy/proxy.d.ts +0 -48
  63. package/dist/modules/brainy/proxy.d.ts.map +0 -1
  64. package/dist/modules/brainy/proxy.js +0 -95
  65. package/dist/modules/brainy/proxy.js.map +0 -1
  66. package/dist/server/create-sdk.d.ts +0 -74
  67. package/dist/server/create-sdk.d.ts.map +0 -1
  68. package/dist/server/create-sdk.js +0 -104
  69. package/dist/server/create-sdk.js.map +0 -1
  70. package/dist/server/from-license.d.ts +0 -252
  71. package/dist/server/from-license.d.ts.map +0 -1
  72. package/dist/server/from-license.js +0 -349
  73. package/dist/server/from-license.js.map +0 -1
  74. package/dist/server/handlers.d.ts +0 -312
  75. package/dist/server/handlers.d.ts.map +0 -1
  76. package/dist/server/handlers.js +0 -376
  77. package/dist/server/handlers.js.map +0 -1
  78. package/dist/server/postmessage-handler.d.ts +0 -152
  79. package/dist/server/postmessage-handler.d.ts.map +0 -1
  80. package/dist/server/postmessage-handler.js +0 -138
  81. package/dist/server/postmessage-handler.js.map +0 -1
  82. package/dist/transports/http.d.ts +0 -86
  83. package/dist/transports/http.d.ts.map +0 -1
  84. package/dist/transports/http.js +0 -137
  85. package/dist/transports/http.js.map +0 -1
  86. package/dist/transports/postmessage.d.ts +0 -159
  87. package/dist/transports/postmessage.d.ts.map +0 -1
  88. package/dist/transports/postmessage.js +0 -207
  89. package/dist/transports/postmessage.js.map +0 -1
  90. package/dist/transports/workshop.d.ts +0 -173
  91. package/dist/transports/workshop.d.ts.map +0 -1
  92. package/dist/transports/workshop.js +0 -307
  93. package/dist/transports/workshop.js.map +0 -1
@@ -1,138 +0,0 @@
1
- /**
2
- * @module server/postmessage-handler
3
- * @description Parent-frame PostMessage handler for Workshop WebContainer kit iframes.
4
- *
5
- * Workshop kit apps run as WebContainer iframes inside the Workshop editor. They use
6
- * {@link PostMessageTransport} from `@soulcraft/sdk/client` to post Brainy RPC calls to the
7
- * parent Workshop frame. This module provides the parent-side handler that receives those
8
- * calls, dispatches them to the live Brainy instance, and posts the response back.
9
- *
10
- * ## Wire protocol
11
- *
12
- * **Inbound** (from kit iframe):
13
- * ```json
14
- * { "type": "brainy:request", "id": "<uuid>", "method": "find", "args": [{...}] }
15
- * ```
16
- *
17
- * **Outbound** (to kit iframe):
18
- * ```json
19
- * { "type": "brainy:response", "id": "<uuid>", "result": [...] }
20
- * { "type": "brainy:response", "id": "<uuid>", "error": { "code": "...", "message": "..." } }
21
- * ```
22
- *
23
- * ## Usage (Workshop parent frame)
24
- *
25
- * ```typescript
26
- * import { createBrainyPostMessageHandler } from '@soulcraft/sdk/server'
27
- * import { createSDK, BrainyInstancePool } from '@soulcraft/sdk/server'
28
- *
29
- * const pool = new BrainyInstancePool({ ... })
30
- *
31
- * // Mount once per kit iframe window:
32
- * const handler = createBrainyPostMessageHandler({
33
- * resolveBrain: async (method) => {
34
- * const brain = await pool.forUser(currentUser.emailHash, currentWorkspaceId)
35
- * return brain
36
- * },
37
- * allowedOrigin: 'null', // WebContainer iframes have origin 'null'
38
- * targetWindow: kitIframeRef.contentWindow!,
39
- * })
40
- *
41
- * // When the kit iframe is torn down:
42
- * handler.dispose()
43
- * ```
44
- *
45
- * ## Security
46
- *
47
- * The handler validates the `event.origin` against `allowedOrigin` before dispatching.
48
- * WebContainer iframes have `origin: 'null'` — pass `'null'` (string) for those.
49
- * For externally hosted kit apps, pass the expected origin string.
50
- *
51
- * Optionally, set `allowedSource` to the `contentWindow` of the specific iframe to
52
- * reject messages from other frames on the same origin.
53
- */
54
- import { LocalTransport } from '../transports/local.js';
55
- // ─────────────────────────────────────────────────────────────────────────────
56
- // Factory
57
- // ─────────────────────────────────────────────────────────────────────────────
58
- /**
59
- * Mount a PostMessage handler in the parent Workshop frame.
60
- *
61
- * Listens for `brainy:request` messages from kit iframes, dispatches each call to
62
- * the resolved Brainy instance via a {@link LocalTransport}, and posts the result
63
- * back as a `brainy:response` message.
64
- *
65
- * @param config - Handler configuration including brain resolver and allowed origin.
66
- * @returns A {@link BrainyPostMessageHandler} with a `dispose()` method.
67
- *
68
- * @example
69
- * ```typescript
70
- * const handler = createBrainyPostMessageHandler({
71
- * resolveBrain: () => pool.forUser(user.emailHash, workspaceId),
72
- * allowedOrigin: 'null', // WebContainer iframes report origin 'null'
73
- * targetWindow: iframe.contentWindow!,
74
- * })
75
- *
76
- * // On iframe unmount:
77
- * handler.dispose()
78
- * ```
79
- */
80
- export function createBrainyPostMessageHandler(config) {
81
- const listenerWin = config.listenerWindow ?? window;
82
- async function _handleMessage(event) {
83
- // Validate origin.
84
- if (config.allowedOrigin !== '*' && event.origin !== config.allowedOrigin)
85
- return;
86
- const data = event.data;
87
- if (!data || data.type !== 'brainy:request' || !data.id)
88
- return;
89
- const { id, method, args } = data;
90
- // Determine the window to reply to.
91
- const replyTo = config.targetWindow ?? event.source;
92
- if (!replyTo)
93
- return;
94
- let response;
95
- try {
96
- const brain = await config.resolveBrain(method);
97
- const transport = new LocalTransport(brain);
98
- const result = await transport.call(method, args);
99
- response = { type: 'brainy:response', id, result };
100
- }
101
- catch (err) {
102
- const message = err instanceof Error ? err.message : String(err);
103
- // Map known error names to codes the client can deserialize.
104
- let code = 'RPC_ERROR';
105
- if (err instanceof Error) {
106
- if (err.name === 'SDKAuthError' || message.includes('Unauthorized'))
107
- code = 'AUTH_ERROR';
108
- else if (err.name === 'SDKForbiddenError' || message.includes('Forbidden'))
109
- code = 'FORBIDDEN';
110
- else if (err.name === 'BrainyMethodNotFoundError')
111
- code = 'METHOD_NOT_FOUND';
112
- }
113
- response = { type: 'brainy:response', id, error: { code, message } };
114
- }
115
- replyTo.postMessage(response, '*');
116
- }
117
- const listener = (event) => { void _handleMessage(event); };
118
- listenerWin.addEventListener('message', listener);
119
- // Wire Brainy change event forwarding to the kit iframe.
120
- let _unsubscribeEvents;
121
- if (config.subscribeToEvents) {
122
- _unsubscribeEvents = config.subscribeToEvents((changeEvent) => {
123
- // Resolve the reply target — prefer config.targetWindow, fall back to null (no-op).
124
- const replyTo = config.targetWindow;
125
- if (!replyTo)
126
- return;
127
- const msg = { type: 'brainy:event', event: changeEvent };
128
- replyTo.postMessage(msg, '*');
129
- });
130
- }
131
- return {
132
- dispose() {
133
- listenerWin.removeEventListener('message', listener);
134
- _unsubscribeEvents?.();
135
- },
136
- };
137
- }
138
- //# sourceMappingURL=postmessage-handler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postmessage-handler.js","sourceRoot":"","sources":["../../src/server/postmessage-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAA;AAuFvD,gFAAgF;AAChF,UAAU;AACV,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;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ACpD,kBAAkB,EAAE,EAAE,CAAA;QACxB,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -1,86 +0,0 @@
1
- /**
2
- * @module transports/http
3
- * @description HTTP transport — sends Brainy RPC calls as JSON POST requests.
4
- *
5
- * Posts to `{baseUrl}/api/brainy/rpc` with body `{ method, args }` and expects
6
- * `{ result }` or `{ error: { code, message } }` in the response.
7
- *
8
- * Works isomorphically in both the browser and server-side Bun/Node environments.
9
- * Uses `AbortController` for the configurable timeout (default 30 seconds).
10
- *
11
- * Change events are not supported by the HTTP transport — use the WebSocket
12
- * transport (`'ws'`) if real-time push events are required.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { createSDK } from '@soulcraft/sdk/client'
17
- *
18
- * const sdk = createSDK({
19
- * mode: 'client',
20
- * product: 'workshop',
21
- * transport: 'http',
22
- * baseUrl: 'https://workshop.soulcraft.com',
23
- * auth: 'cookie', // send session cookies
24
- * })
25
- *
26
- * const results = await sdk.brainy.find({ query: 'candle kits', limit: 10 })
27
- * ```
28
- */
29
- import type { SDKTransport } from './transport.js';
30
- import type { BrainyChangeEvent } from '../modules/brainy/events.js';
31
- /**
32
- * Transport that sends Brainy RPC calls over HTTP POST.
33
- *
34
- * Each `call()` invocation is an independent HTTP request.
35
- * The transport is always considered "alive" — connectivity errors surface
36
- * as rejected promises from individual calls rather than a persistent state.
37
- */
38
- export declare class HttpTransport implements SDKTransport {
39
- private readonly rpcUrl;
40
- private readonly authToken;
41
- private readonly credentials;
42
- private readonly timeoutMs;
43
- /**
44
- * @param baseUrl - Base URL of the Brainy server, e.g. `'https://workshop.soulcraft.com'`.
45
- * @param authToken - Optional capability token sent as `Authorization: Bearer <token>`.
46
- * @param credentials - If `true`, include cookies with each request (same-origin browser use).
47
- * @param timeoutMs - Request timeout in milliseconds. Default: 30 000.
48
- */
49
- constructor(baseUrl: string, authToken?: string, credentials?: boolean, timeoutMs?: number);
50
- /**
51
- * Sends the RPC call as a JSON POST and returns the result.
52
- *
53
- * @param method - Dot-separated Brainy method name (e.g. `'find'`, `'vfs.readdir'`).
54
- * @param args - Positional arguments forwarded to the server.
55
- * @returns The deserialized return value from Brainy.
56
- * @throws {@link SDKTimeoutError} if the request exceeds `timeoutMs`.
57
- * @throws {@link SDKAuthError} on HTTP 401.
58
- * @throws {@link SDKForbiddenError} on HTTP 403.
59
- * @throws {@link SDKRpcError} on any other non-ok HTTP response (5xx, 502, 503, etc.) or Brainy-level error.
60
- * @throws {@link SDKDisconnectedError} on network failure.
61
- */
62
- call(method: string, args: unknown[]): Promise<unknown>;
63
- /**
64
- * No-op — HTTP transport does not support push change events.
65
- *
66
- * Use the WebSocket transport for real-time subscriptions.
67
- *
68
- * @param _handler - Unused.
69
- */
70
- onEvent(_handler: (event: BrainyChangeEvent) => void): void;
71
- /**
72
- * No-op — no listeners to remove.
73
- *
74
- * @param _handler - Unused.
75
- */
76
- offEvent(_handler: (event: BrainyChangeEvent) => void): void;
77
- /**
78
- * Always returns `true` — HTTP transport is stateless; errors surface per-call.
79
- */
80
- isAlive(): boolean;
81
- /**
82
- * No-op — HTTP transport has no persistent connection to close.
83
- */
84
- close(): Promise<void>;
85
- }
86
- //# sourceMappingURL=http.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/transports/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AA8BpE;;;;;;GAMG;AACH,qBAAa,aAAc,YAAW,YAAY;IAChD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAoB;IAC9C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAQ;IAElC;;;;;OAKG;gBAED,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,MAAM,EAClB,WAAW,UAAQ,EACnB,SAAS,SAAS;IAQpB;;;;;;;;;;;OAWG;IACG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IA+C7D;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,GAAG,IAAI;IAI3D;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,GAAG,IAAI;IAI5D;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B"}
@@ -1,137 +0,0 @@
1
- /**
2
- * @module transports/http
3
- * @description HTTP transport — sends Brainy RPC calls as JSON POST requests.
4
- *
5
- * Posts to `{baseUrl}/api/brainy/rpc` with body `{ method, args }` and expects
6
- * `{ result }` or `{ error: { code, message } }` in the response.
7
- *
8
- * Works isomorphically in both the browser and server-side Bun/Node environments.
9
- * Uses `AbortController` for the configurable timeout (default 30 seconds).
10
- *
11
- * Change events are not supported by the HTTP transport — use the WebSocket
12
- * transport (`'ws'`) if real-time push events are required.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { createSDK } from '@soulcraft/sdk/client'
17
- *
18
- * const sdk = createSDK({
19
- * mode: 'client',
20
- * product: 'workshop',
21
- * transport: 'http',
22
- * baseUrl: 'https://workshop.soulcraft.com',
23
- * auth: 'cookie', // send session cookies
24
- * })
25
- *
26
- * const results = await sdk.brainy.find({ query: 'candle kits', limit: 10 })
27
- * ```
28
- */
29
- import { SDKDisconnectedError, SDKTimeoutError, SDKAuthError, SDKForbiddenError, SDKRpcError, } from '../modules/brainy/errors.js';
30
- /**
31
- * Transport that sends Brainy RPC calls over HTTP POST.
32
- *
33
- * Each `call()` invocation is an independent HTTP request.
34
- * The transport is always considered "alive" — connectivity errors surface
35
- * as rejected promises from individual calls rather than a persistent state.
36
- */
37
- export class HttpTransport {
38
- rpcUrl;
39
- authToken;
40
- credentials;
41
- timeoutMs;
42
- /**
43
- * @param baseUrl - Base URL of the Brainy server, e.g. `'https://workshop.soulcraft.com'`.
44
- * @param authToken - Optional capability token sent as `Authorization: Bearer <token>`.
45
- * @param credentials - If `true`, include cookies with each request (same-origin browser use).
46
- * @param timeoutMs - Request timeout in milliseconds. Default: 30 000.
47
- */
48
- constructor(baseUrl, authToken, credentials = false, timeoutMs = 30_000) {
49
- this.rpcUrl = `${baseUrl.replace(/\/$/, '')}/api/brainy/rpc`;
50
- this.authToken = authToken;
51
- this.credentials = credentials;
52
- this.timeoutMs = timeoutMs;
53
- }
54
- /**
55
- * Sends the RPC call as a JSON POST and returns the result.
56
- *
57
- * @param method - Dot-separated Brainy method name (e.g. `'find'`, `'vfs.readdir'`).
58
- * @param args - Positional arguments forwarded to the server.
59
- * @returns The deserialized return value from Brainy.
60
- * @throws {@link SDKTimeoutError} if the request exceeds `timeoutMs`.
61
- * @throws {@link SDKAuthError} on HTTP 401.
62
- * @throws {@link SDKForbiddenError} on HTTP 403.
63
- * @throws {@link SDKRpcError} on any other non-ok HTTP response (5xx, 502, 503, etc.) or Brainy-level error.
64
- * @throws {@link SDKDisconnectedError} on network failure.
65
- */
66
- async call(method, args) {
67
- const abort = new AbortController();
68
- const timer = setTimeout(() => abort.abort(), this.timeoutMs);
69
- const headers = { 'Content-Type': 'application/json' };
70
- if (this.authToken)
71
- headers['Authorization'] = `Bearer ${this.authToken}`;
72
- const body = { method, args };
73
- let response;
74
- try {
75
- response = await fetch(this.rpcUrl, {
76
- method: 'POST',
77
- headers,
78
- body: JSON.stringify(body),
79
- credentials: this.credentials ? 'include' : 'omit',
80
- signal: abort.signal,
81
- });
82
- }
83
- catch (err) {
84
- clearTimeout(timer);
85
- if (err instanceof DOMException && err.name === 'AbortError') {
86
- throw new SDKTimeoutError(method);
87
- }
88
- throw new SDKDisconnectedError(err);
89
- }
90
- finally {
91
- clearTimeout(timer);
92
- }
93
- if (response.status === 401)
94
- throw new SDKAuthError();
95
- if (response.status === 403)
96
- throw new SDKForbiddenError();
97
- if (!response.ok) {
98
- throw new SDKRpcError(`HTTP_${response.status}`, `SDK: server returned HTTP ${response.status} — the service may be temporarily unavailable`);
99
- }
100
- const json = (await response.json());
101
- if ('error' in json && json.error) {
102
- throw new SDKRpcError(json.error.code, json.error.message);
103
- }
104
- return json.result;
105
- }
106
- /**
107
- * No-op — HTTP transport does not support push change events.
108
- *
109
- * Use the WebSocket transport for real-time subscriptions.
110
- *
111
- * @param _handler - Unused.
112
- */
113
- onEvent(_handler) {
114
- // HTTP is stateless — no server push; use WsTransport for change events.
115
- }
116
- /**
117
- * No-op — no listeners to remove.
118
- *
119
- * @param _handler - Unused.
120
- */
121
- offEvent(_handler) {
122
- // Nothing to remove for HTTP transport.
123
- }
124
- /**
125
- * Always returns `true` — HTTP transport is stateless; errors surface per-call.
126
- */
127
- isAlive() {
128
- return true;
129
- }
130
- /**
131
- * No-op — HTTP transport has no persistent connection to close.
132
- */
133
- async close() {
134
- // Stateless — no connection to close.
135
- }
136
- }
137
- //# sourceMappingURL=http.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/transports/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAIH,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,YAAY,EACZ,iBAAiB,EACjB,WAAW,GACZ,MAAM,6BAA6B,CAAA;AAuBpC;;;;;;GAMG;AACH,MAAM,OAAO,aAAa;IACP,MAAM,CAAQ;IACd,SAAS,CAAoB;IAC7B,WAAW,CAAS;IACpB,SAAS,CAAQ;IAElC;;;;;OAKG;IACH,YACE,OAAe,EACf,SAAkB,EAClB,WAAW,GAAG,KAAK,EACnB,SAAS,GAAG,MAAM;QA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M,CAAC,CAAA;YACnC,CAAC;YACD,MAAM,IAAI,oBAAoB,CAAC,GAAG,CAAC,CAAA;QACrC,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAA;QACrB,CAAC;QAED,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;YAAE,MAAM,IAAI,YAAY,EAAE,CAAA;QACrD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;YAAE,MAAM,IAAI,iBAAiB,EAAE,CAAA;QAE1D,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,WAAW,CACnB,QAAQ,QAAQ,CAAC,MAAM,EAAE,EACzB,6BAA6B,QAAQ,CAAC,MAAM,+CAA+C,CAC5F,CAAA;QACH,CAAC;QAED,MAAM,IAAI,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAgB,CAAA;QAEnD,IAAI,OAAO,IAAI,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAClC,MAAM,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;QAC5D,CAAC;QAED,OAAQ,IAA2B,CAAC,MAAM,CAAA;IAC5C,CAAC;IAED;;;;;;OAMG;IACH,OAAO,CAAC,QAA4C;QAClD,yEAAyE;IAC3E,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,QAA4C;QACnD,wCAAwC;IAC1C,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACT,sCAAsC;IACxC,CAAC;CACF"}
@@ -1,159 +0,0 @@
1
- /**
2
- * @module transports/postmessage
3
- * @description PostMessage transport — sends Brainy RPC calls from a child iframe to its
4
- * parent frame via `window.postMessage`.
5
- *
6
- * Designed for Workshop kit apps running inside WebContainer iframes. The kit app calls
7
- * Brainy methods as normal via `createBrainyProxy(transport)`, and each call is forwarded
8
- * to the parent Workshop frame which owns the actual Brainy instance.
9
- *
10
- * ## Wire protocol
11
- *
12
- * **Request** (kit iframe → parent):
13
- * ```json
14
- * { "type": "brainy:request", "id": "<uuid>", "method": "find", "args": [{ "query": "..." }] }
15
- * ```
16
- *
17
- * **Response** (parent → kit iframe):
18
- * ```json
19
- * { "type": "brainy:response", "id": "<uuid>", "result": [...] }
20
- * { "type": "brainy:response", "id": "<uuid>", "error": { "code": "RPC_ERROR", "message": "..." } }
21
- * ```
22
- *
23
- * The `id` field correlates each response to its originating request. Pending calls are
24
- * resolved or rejected when the matching response arrives.
25
- *
26
- * ## Usage
27
- *
28
- * ```typescript
29
- * // Kit app (iframe):
30
- * import { PostMessageTransport, createBrainyProxy } from '@soulcraft/sdk/client'
31
- *
32
- * const transport = new PostMessageTransport()
33
- * const brainy = createBrainyProxy(transport)
34
- *
35
- * const results = await brainy.find({ query: 'candle inventory', limit: 10 })
36
- * ```
37
- *
38
- * The parent frame must mount a `createBrainyPostMessageHandler` from `@soulcraft/sdk/server`
39
- * to receive and respond to these messages.
40
- *
41
- * ## Security
42
- *
43
- * Messages are sent to `targetOrigin`. Always pass the explicit Workshop origin
44
- * (e.g. `'https://workshop.soulcraft.com'`). Using `'*'` broadcasts to any origin
45
- * and must never be used in production — it leaks Brainy RPC responses to third-party
46
- * frames. The parent handler validates `event.source` and `event.origin` before dispatching.
47
- */
48
- import type { SDKTransport } from './transport.js';
49
- import type { BrainyChangeEvent } from '../modules/brainy/events.js';
50
- /** A Brainy RPC request posted from the kit iframe to the parent. */
51
- export interface PostMessageRequest {
52
- type: 'brainy:request';
53
- id: string;
54
- method: string;
55
- args: unknown[];
56
- }
57
- /** A successful Brainy RPC response posted from the parent to the kit iframe. */
58
- export interface PostMessageSuccessResponse {
59
- type: 'brainy:response';
60
- id: string;
61
- result: unknown;
62
- }
63
- /** An error Brainy RPC response posted from the parent to the kit iframe. */
64
- export interface PostMessageErrorResponse {
65
- type: 'brainy:response';
66
- id: string;
67
- error: {
68
- code: string;
69
- message: string;
70
- };
71
- }
72
- /** Union of all response shapes. */
73
- export type PostMessageResponse = PostMessageSuccessResponse | PostMessageErrorResponse;
74
- /** A real-time change event forwarded from the parent frame to the kit iframe. */
75
- export interface PostMessageEventMessage {
76
- type: 'brainy:event';
77
- event: BrainyChangeEvent;
78
- }
79
- /** Minimal window-like interface required by the transport. */
80
- export interface PostMessageWindow {
81
- addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
82
- removeEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
83
- postMessage(message: unknown, targetOrigin: string): void;
84
- readonly parent: PostMessageWindow;
85
- }
86
- /**
87
- * PostMessage transport for kit apps running inside Workshop WebContainer iframes.
88
- *
89
- * Each `call()` posts a `brainy:request` message to `window.parent` and waits for
90
- * a matching `brainy:response` message. Responses are correlated by a UUID `id` field
91
- * generated per request.
92
- *
93
- * The transport installs a single `message` listener on `window` at construction time
94
- * and removes it when `close()` is called.
95
- */
96
- export declare class PostMessageTransport implements SDKTransport {
97
- private readonly _targetOrigin;
98
- private readonly _timeoutMs;
99
- private readonly _pending;
100
- private readonly _eventHandlers;
101
- private _closed;
102
- private readonly _messageListener;
103
- private readonly _listenerWindow;
104
- private readonly _parentWindow;
105
- /**
106
- * @param targetOrigin - The origin to which requests are sent.
107
- * Must be an explicit origin (e.g. `'https://workshop.soulcraft.com'`).
108
- * Never use `'*'` in production — it broadcasts RPC responses to any origin.
109
- * @param timeoutMs - Per-call timeout in milliseconds. Default: 30 000.
110
- * @param listenerWindow - Window on which to listen for responses. Defaults to `window`.
111
- * Pass a custom object in tests or non-browser environments.
112
- * @param parentWindow - Window to which requests are posted. Defaults to `window.parent`.
113
- * Pass a custom object in tests or non-browser environments.
114
- */
115
- constructor(targetOrigin: string, timeoutMs?: number, listenerWindow?: PostMessageWindow, parentWindow?: PostMessageWindow);
116
- private _handleMessage;
117
- private _generateId;
118
- /**
119
- * Dispatch a Brainy RPC call via `window.parent.postMessage`.
120
- *
121
- * @param method - Dot-separated Brainy method name (e.g. `'find'`, `'vfs.readFile'`).
122
- * @param args - Positional arguments forwarded to Brainy on the parent frame.
123
- * @returns A Promise that resolves with the Brainy method's return value.
124
- * @throws {@link SDKDisconnectedError} if the transport has been closed.
125
- * @throws {@link SDKTimeoutError} if no response arrives within `timeoutMs`.
126
- * @throws {@link SDKAuthError} if the parent responds with an auth error.
127
- * @throws {@link SDKRpcError} if the parent responds with a Brainy-level error.
128
- */
129
- call(method: string, args: unknown[]): Promise<unknown>;
130
- /**
131
- * Register a handler for real-time Brainy change events.
132
- *
133
- * Change events are forwarded from the parent frame via `brainy:event` messages.
134
- * The parent handler posts these when Brainy fires a data change.
135
- *
136
- * @param handler - Called with each {@link BrainyChangeEvent}.
137
- */
138
- onEvent(handler: (event: BrainyChangeEvent) => void): void;
139
- /**
140
- * Remove a previously registered change event handler.
141
- *
142
- * @param handler - The same function reference passed to {@link onEvent}.
143
- */
144
- offEvent(handler: (event: BrainyChangeEvent) => void): void;
145
- /**
146
- * Returns `true` when the transport is open.
147
- *
148
- * PostMessage is always available as long as the transport has not been closed —
149
- * it relies on `window.parent` which is always present inside an iframe.
150
- */
151
- isAlive(): boolean;
152
- /**
153
- * Close the transport, removing the message listener and rejecting all pending calls.
154
- *
155
- * After calling `close()`, any further `call()` invocations throw `SDKDisconnectedError`.
156
- */
157
- close(): Promise<void>;
158
- }
159
- //# sourceMappingURL=postmessage.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postmessage.d.ts","sourceRoot":"","sources":["../../src/transports/postmessage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAapE,qEAAqE;AACrE,MAAM,WAAW,kBAAkB;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