@notionhq/custom-blocks 0.2.20 → 0.2.22

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 (66) hide show
  1. package/README.md +2 -0
  2. package/dist/bridge/SandboxBridge.d.ts +14 -18
  3. package/dist/bridge/SandboxBridge.d.ts.map +1 -1
  4. package/dist/bridge/SandboxBridge.js +59 -201
  5. package/dist/bridge/SandboxInitialization.d.ts +52 -0
  6. package/dist/bridge/SandboxInitialization.d.ts.map +1 -0
  7. package/dist/bridge/SandboxInitialization.js +217 -0
  8. package/dist/bridge/dataSources/query.d.ts.map +1 -1
  9. package/dist/bridge/dataSources/query.js +30 -23
  10. package/dist/bridge/messageInterceptor.d.ts +4 -0
  11. package/dist/bridge/messageInterceptor.d.ts.map +1 -0
  12. package/dist/bridge/messageInterceptor.js +1 -0
  13. package/dist/bridge/sandboxClient.d.ts +3 -2
  14. package/dist/bridge/sandboxClient.d.ts.map +1 -1
  15. package/dist/bridge/sandboxClient.js +3 -5
  16. package/dist/bridge.d.ts +11 -0
  17. package/dist/bridge.d.ts.map +1 -0
  18. package/dist/bridge.js +11 -0
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/init.d.ts +4 -38
  22. package/dist/init.d.ts.map +1 -1
  23. package/dist/init.js +4 -91
  24. package/dist/initTypes.d.ts +31 -0
  25. package/dist/initTypes.d.ts.map +1 -0
  26. package/dist/initTypes.js +18 -0
  27. package/dist/protocol/dataSources/propertySchema.d.ts +1 -1
  28. package/dist/protocol/dataSources/propertySchema.js +2 -0
  29. package/dist/protocol/dataSources/sortDirection.d.ts +3 -0
  30. package/dist/protocol/dataSources/sortDirection.js +2 -0
  31. package/dist/protocol/index.d.ts +1 -0
  32. package/dist/protocol/index.js +1 -0
  33. package/dist/protocol/messages/hostToSandbox.d.ts +0 -3
  34. package/dist/protocol/messages/init.d.ts +1 -1
  35. package/dist/protocol/messages/queryDataSource.d.ts +259 -47
  36. package/dist/protocol/messages/queryDataSource.js +94 -8
  37. package/dist/protocol/messages/sandboxToHost.d.ts +80 -16
  38. package/dist/styles/nds.css +1 -1
  39. package/dist/types.d.ts +5 -3
  40. package/dist/types.d.ts.map +1 -1
  41. package/dist/version.js +1 -1
  42. package/docs/bridge-interceptors.md +27 -0
  43. package/docs/data-sources.md +80 -13
  44. package/docs/errors.md +2 -0
  45. package/docs/pages.md +22 -10
  46. package/package.json +4 -4
  47. package/src/bridge/SandboxBridge.ts +74 -239
  48. package/src/bridge/SandboxInitialization.ts +295 -0
  49. package/src/bridge/dataSources/query.ts +38 -25
  50. package/src/bridge/messageInterceptor.ts +6 -0
  51. package/src/bridge/sandboxClient.ts +6 -5
  52. package/src/bridge.ts +17 -0
  53. package/src/index.ts +1 -0
  54. package/src/init.ts +8 -119
  55. package/src/initTypes.ts +43 -0
  56. package/src/styles/nds.css +1 -1
  57. package/src/styles/nds.css.metadata.json +3 -3
  58. package/src/types.ts +6 -2
  59. package/dist/bridge/primedResponses.d.ts +0 -8
  60. package/dist/bridge/primedResponses.d.ts.map +0 -1
  61. package/dist/bridge/primedResponses.js +0 -5
  62. package/dist/testing.d.ts +0 -12
  63. package/dist/testing.d.ts.map +0 -1
  64. package/dist/testing.js +0 -9
  65. package/src/bridge/primedResponses.ts +0 -11
  66. package/src/testing.ts +0 -19
package/README.md CHANGED
@@ -127,6 +127,8 @@ Import React hooks and components from `@notionhq/custom-blocks/react`.
127
127
  - [`docs/users.md`](./docs/users.md) — `users.list / get`, the `NotionUser` shape, paging.
128
128
  - [`docs/errors.md`](./docs/errors.md) — request results, error format, error codes, retries, and
129
129
  initialization failures.
130
+ - [`docs/bridge-interceptors.md`](./docs/bridge-interceptors.md) — `registerMessageInterceptor` and
131
+ `MessageInterceptor` for controlled bridge responses.
130
132
  - [`docs/deployment.md`](./docs/deployment.md) — worker-backed deploys, localhost self-hosted
131
133
  fallback, where the manifest comes from.
132
134
 
@@ -4,6 +4,7 @@ import { type InitMessage } from "../protocol/messages/init.js";
4
4
  import type { CreatePageArgs, CreatePageResult, DataSourceQueryOptions, GetPageResult, GetUserResult, ListUsersArgs, ListUsersResult, NotionDataSourcePageUpdateArgs, NotionUserId, OpenPageOptions, OpenPageResult, UpdatePageArgs, UpdatePageResult } from "../types.js";
5
5
  import { type CustomBlockHostState } from "./hostState.js";
6
6
  import type { ManifestLoadResult } from "./loadManifest.js";
7
+ import type { MessageInterceptor } from "./messageInterceptor.js";
7
8
  /**
8
9
  * A single entry in the bridge message log. Kept intentionally plain so the log is copy-pasteable
9
10
  * to a local coding agent without needing extra context.
@@ -23,37 +24,38 @@ export type QueryDataSourceArgs = {
23
24
  export declare class SandboxBridge {
24
25
  private hostState;
25
26
  private listeners;
27
+ private messageInterceptors;
26
28
  private messageLog;
27
29
  private messageLogListeners;
28
- private nextRequestId;
29
30
  private readonly pendingCreatePage;
30
31
  private readonly pendingGetPage;
31
32
  private readonly pendingGetUser;
32
33
  private readonly pendingListUsers;
33
34
  private readonly pendingOpenPage;
34
35
  private readonly pendingUpdatePage;
35
- private hasSentConnect;
36
- private hasReceivedInit;
37
- private initializationId;
38
- private hasSentInitResult;
39
- private pendingOutboundMessages;
40
36
  private latestDataSourceBindings;
41
37
  private isMockState;
42
38
  private isListening;
43
- private resolveInit;
44
- private rejectInit;
45
- private readonly initMessage;
39
+ private isDisposed;
40
+ private readonly initialization;
41
+ initialize(): Promise<import("../initTypes.js").CustomBlockInitPayload>;
42
+ /**
43
+ * Stops this bridge permanently. Rejects pending initialization, cancels
44
+ * acknowledgment callbacks, removes the message listener, and discards queued
45
+ * outbound messages. Further host messages are ignored.
46
+ *
47
+ * Pending page and user requests are not settled by disposal.
48
+ */
49
+ dispose(): void;
46
50
  startListening(): void;
47
51
  private static MAX_LOG_ENTRIES;
48
52
  private logMessage;
49
53
  getMessageLog(): readonly MessageLogEntry[];
50
54
  subscribeToMessageLog(listener: () => void): () => boolean;
51
- awaitInit(): Promise<void>;
55
+ registerMessageInterceptor(interceptor: MessageInterceptor): () => void;
52
56
  sendConnect(manifestResult: ManifestLoadResult): void;
53
57
  private postToHost;
54
58
  private sendToHost;
55
- private flushPendingOutboundMessages;
56
- private getMessageType;
57
59
  private notify;
58
60
  private handleMessage;
59
61
  private receiveMessage;
@@ -66,13 +68,7 @@ export declare class SandboxBridge {
66
68
  */
67
69
  setMockState(message: InitMessage): void;
68
70
  completeInitialization(): void;
69
- private sendInitResultError;
70
71
  private applyInit;
71
- /**
72
- * Lets the initial application render commit before we acknowledge init. The host keeps the
73
- * iframe covered throughout this frame, so it can apply the measured height before first paint.
74
- */
75
- private scheduleInitResult;
76
72
  createDataSourceSubscriptionId(): string;
77
73
  queryDataSource({ subscriptionId, key, options, forceRequery, }: QueryDataSourceArgs): void;
78
74
  private setDataSourceQueryError;
@@ -1 +1 @@
1
- {"version":3,"file":"SandboxBridge.d.ts","sourceRoot":"","sources":["../../src/bridge/SandboxBridge.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,gBAAgB,EAEhB,MAAM,4DAA4D,CAAA;AACnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yCAAyC,CAAA;AAc3E,OAAO,EAEN,KAAK,WAAW,EAEhB,MAAM,mDAAmD,CAAA;AAgB1D,OAAO,KAAK,EACX,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,aAAa,EACb,aAAa,EACb,aAAa,EACb,eAAe,EACf,8BAA8B,EAC9B,YAAY,EACZ,eAAe,EACf,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,MAAM,aAAa,CAAA;AAapB,OAAO,EACN,KAAK,oBAAoB,EAGzB,MAAM,gBAAgB,CAAA;AACvB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAK3D;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,GAAG,UAAU,CAAA;IAC9B,IAAI,EAAE,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C;IAED,sBAAsB,SAErB;IAED,OAAO,CAAC,SAAS;IAwCjB,8BAA8B,IAAI,MAAM,CAEvC;IAED,eAAe,CAAC,EACf,cAAc,EACd,GAAG,EACH,OAAY,EACZ,YAAoB,GACpB,EAAE,mBAAmB,QAqFrB;IAED,OAAO,CAAC,uBAAuB;IA4B/B,6BAA6B,CAAC,cAAc,EAAE,MAAM,QAkBnD;IAED,UAAU,CAAC,MAAM,EAAE,MAAM,QAWxB;IAED,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA4B1D;IAED,OAAO,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAUpD;IAED,QAAQ,CACP,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,cAAc,CAAC,CAWzB;IAED,OAAO,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAUpD;IAED,SAAS,CAAC,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,eAAe,CAAC,CAW5D;IAED,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAyC1D;IAED;;;;OAIG;IACH,oBAAoB,CAAC,IAAI,EAAE;QAC1B,UAAU,EAAE,gBAAgB,CAAA;QAC5B,MAAM,EAAE,YAAY,CAAA;QACpB,cAAc,EAAE,8BAA8B,CAAA;KAC9C,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAqB5B;IAED;;;;OAIG;IACH,OAAO,CAAC,uBAAuB;CAkE/B"}
@@ -1,11 +1,9 @@
1
1
  import { DEFAULT_CONTRAST_MODE } from "../protocol/contrast.js";
2
- import { hostToSandboxMessageSchema, } from "../protocol/messages/hostToSandbox.js";
2
+ import { hostToSandboxMessageSchema } from "../protocol/messages/hostToSandbox.js";
3
3
  import { readIncomingType } from "../protocol/messages/incomingType.js";
4
- import { CustomBlockInitializationError, initMessageSchema, } from "../protocol/messages/init.js";
5
- import { LATEST_BRIDGE_PROTOCOL_VERSION } from "../protocol/protocolVersion.js";
4
+ import { initMessageSchema, } from "../protocol/messages/init.js";
6
5
  import * as v from "valibot";
7
6
  import { unreachable } from "../utils.js";
8
- import { CUSTOM_BLOCKS_SDK_VERSION } from "../version.js";
9
7
  import { NOTION_DARK_BACKGROUND_BASE, NOTION_LIGHT_BACKGROUND_BASE, } from "./appearance.js";
10
8
  import { resolveDataSourceQuery } from "./dataSources/query.js";
11
9
  import { getDataSourceReadSchemas, resolveDataSources, } from "./dataSources/resolve.js";
@@ -13,17 +11,7 @@ import { resolvePropertyWriteMapForDataSource } from "./dataSources/resolvePrope
13
11
  import { createEmptyDataSourceQueryState, } from "./hostState.js";
14
12
  import { notifyListener } from "./notifyListener.js";
15
13
  import { PendingRequests } from "./pendingRequests.js";
16
- import { globalPrimedResponsesCache } from "./primedResponses.js";
17
- const RESPONSE_TYPE_BY_REQUEST = new Map([
18
- ["getPage", "getPageResult"],
19
- ["openPage", "openPageResult"],
20
- ["createPage", "createPageResult"],
21
- ["updatePage", "updatePageResult"],
22
- ["getUser", "getUserResult"],
23
- ["listUsers", "listUsersResult"],
24
- ["queryDataSource", "queryDataSourceResult"],
25
- ]);
26
- const INIT_RESULT_TIMER_FALLBACK_MS = 100;
14
+ import { SandboxInitialization } from "./SandboxInitialization.js";
27
15
  export class SandboxBridge {
28
16
  hostState = {
29
17
  status: "uninitialized",
@@ -31,31 +19,48 @@ export class SandboxBridge {
31
19
  contrastMode: DEFAULT_CONTRAST_MODE,
32
20
  };
33
21
  listeners = new Set();
22
+ messageInterceptors = new Set();
34
23
  messageLog = [];
35
24
  messageLogListeners = new Set();
36
- nextRequestId = 1;
37
25
  pendingCreatePage = new PendingRequests("custom-block-create-page");
38
26
  pendingGetPage = new PendingRequests("custom-block-get-page");
39
27
  pendingGetUser = new PendingRequests("custom-block-get-user");
40
28
  pendingListUsers = new PendingRequests("custom-block-list-users");
41
29
  pendingOpenPage = new PendingRequests("custom-block-open-page");
42
30
  pendingUpdatePage = new PendingRequests("custom-block-update-page");
43
- hasSentConnect = false;
44
- hasReceivedInit = false;
45
- initializationId;
46
- hasSentInitResult = false;
47
- pendingOutboundMessages = [];
48
31
  latestDataSourceBindings = {};
49
32
  isMockState = false;
50
33
  isListening = false;
51
- resolveInit;
52
- rejectInit;
53
- initMessage = new Promise((resolve, reject) => {
54
- this.resolveInit = resolve;
55
- this.rejectInit = reject;
34
+ isDisposed = false;
35
+ initialization = new SandboxInitialization({
36
+ start: () => this.startListening(),
37
+ post: message => this.sendToHost(message),
38
+ apply: message => this.applyInit(message, true),
39
+ getState: () => this.hostState,
40
+ getInitialHeight: getInitialContentHeight,
56
41
  });
42
+ initialize() {
43
+ return this.initialization.initialize();
44
+ }
45
+ /**
46
+ * Stops this bridge permanently. Rejects pending initialization, cancels
47
+ * acknowledgment callbacks, removes the message listener, and discards queued
48
+ * outbound messages. Further host messages are ignored.
49
+ *
50
+ * Pending page and user requests are not settled by disposal.
51
+ */
52
+ dispose() {
53
+ this.isDisposed = true;
54
+ this.initialization.dispose();
55
+ if (this.isListening) {
56
+ window.removeEventListener("message", this.handleMessage);
57
+ this.isListening = false;
58
+ }
59
+ this.listeners.clear();
60
+ this.messageLogListeners.clear();
61
+ }
57
62
  startListening() {
58
- if (this.isListening || typeof window === "undefined") {
63
+ if (this.isDisposed || this.isListening || typeof window === "undefined") {
59
64
  return;
60
65
  }
61
66
  this.isListening = true;
@@ -82,89 +87,27 @@ export class SandboxBridge {
82
87
  this.messageLogListeners.add(listener);
83
88
  return () => this.messageLogListeners.delete(listener);
84
89
  }
85
- awaitInit() {
86
- return this.initMessage;
90
+ registerMessageInterceptor(interceptor) {
91
+ this.messageInterceptors.add(interceptor);
92
+ return () => this.messageInterceptors.delete(interceptor);
87
93
  }
88
94
  sendConnect(manifestResult) {
89
- if (typeof window === "undefined") {
90
- return;
91
- }
92
- if (this.hasSentConnect) {
93
- console.warn("[custom-blocks-sdk] ignoring duplicate connect message");
94
- return;
95
- }
96
- const { manifest, error } = manifestResult;
97
- this.hasSentConnect = true;
98
- const initializationId = `custom-block-initialization-${this.nextRequestId}`;
99
- this.nextRequestId += 1;
100
- this.initializationId = initializationId;
101
- const connectMessage = error !== undefined
102
- ? {
103
- type: "connect",
104
- initializationId,
105
- status: "error",
106
- bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
107
- sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
108
- error,
109
- }
110
- : {
111
- type: "connect",
112
- initializationId,
113
- status: "success",
114
- bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
115
- sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
116
- ...(manifest !== null ? { manifest } : {}),
117
- };
118
- this.postToHost(connectMessage);
95
+ this.initialization.sendConnect(manifestResult);
119
96
  }
120
97
  postToHost(message) {
121
- if (this.hostState.status === "initialized" &&
122
- !this.hasSentInitResult &&
123
- !this.isMockState &&
124
- this.getMessageType(message) !== "initResult") {
125
- this.pendingOutboundMessages.push(message);
126
- return;
127
- }
128
- this.sendToHost(message);
98
+ this.initialization.post(message);
129
99
  }
130
100
  sendToHost(message) {
131
- // Check if the message is a primed response
132
- const messageType = readIncomingType(message);
133
- if (messageType !== undefined &&
134
- typeof message === "object" &&
135
- message !== null) {
136
- const responseType = RESPONSE_TYPE_BY_REQUEST.get(messageType);
137
- const primed = responseType && globalPrimedResponsesCache.get(responseType);
138
- if (responseType !== undefined && primed !== undefined) {
139
- globalPrimedResponsesCache.delete(responseType);
140
- const response = {
141
- ...primed,
142
- type: responseType,
143
- ...("requestId" in message ? { requestId: message.requestId } : {}),
144
- ...("subscriptionId" in message
145
- ? { subscriptionId: message.subscriptionId }
146
- : {}),
147
- };
101
+ for (const interceptor of [...this.messageInterceptors]) {
102
+ const response = interceptor(message);
103
+ if (response !== undefined) {
148
104
  queueMicrotask(() => this.receiveMessage(response));
149
105
  return;
150
106
  }
151
107
  }
152
- // If no primed response is found, proceed as normal
153
108
  this.logMessage("sent", message);
154
109
  window.parent.postMessage(message, "*");
155
110
  }
156
- flushPendingOutboundMessages() {
157
- const pendingMessages = this.pendingOutboundMessages;
158
- this.pendingOutboundMessages = [];
159
- for (const message of pendingMessages) {
160
- this.sendToHost(message);
161
- }
162
- }
163
- getMessageType(message) {
164
- return typeof message === "object" && message !== null && "type" in message
165
- ? message.type
166
- : undefined;
167
- }
168
111
  notify = () => {
169
112
  for (const listener of this.listeners) {
170
113
  notifyListener(listener);
@@ -177,22 +120,22 @@ export class SandboxBridge {
177
120
  this.receiveMessage(event.data);
178
121
  };
179
122
  receiveMessage(data) {
123
+ if (this.isDisposed) {
124
+ return;
125
+ }
180
126
  this.logMessage("received", data);
181
127
  const parsed = v.safeParse(hostToSandboxMessageSchema, data);
182
128
  if (!parsed.success) {
183
129
  console.warn("[custom-blocks-sdk] ignoring malformed host message", parsed.issues);
184
130
  const incomingType = readIncomingType(data);
185
- if (!this.hasReceivedInit &&
186
- incomingType === "init" &&
187
- this.initializationId !== undefined &&
188
- readInitializationId(data) === this.initializationId) {
189
- this.hasReceivedInit = true;
190
- this.sendInitResultError(invalidInitPayloadError(parsed.issues));
131
+ if (incomingType === "init" &&
132
+ this.initialization.handleInvalidInit(readInitializationId(data), invalidInitPayloadError(parsed.issues))) {
191
133
  return;
192
134
  }
193
- // Loop guard: never NACK a NACK. Excludes both directions — `invalidSandboxMessage` is
194
- // what the host normally sends, but a buggy host that echoes our own
195
- // `invalidHostMessage` back would otherwise spin a NACK feedback loop.
135
+ // Loop guard: never NACK a NACK. Excludes both directions —
136
+ // `invalidSandboxMessage` is what the host normally sends, but
137
+ // a buggy host that echoes our own `invalidHostMessage` back
138
+ // would otherwise spin a NACK feedback loop.
196
139
  if (incomingType !== "invalidSandboxMessage" &&
197
140
  incomingType !== "invalidHostMessage") {
198
141
  const nack = {
@@ -215,16 +158,7 @@ export class SandboxBridge {
215
158
  // `init` is the only message valid before initialization. Handle it up front so every later
216
159
  // case can assume `status === "initialized"`.
217
160
  if (message.type === "init") {
218
- if (message.initializationId !== this.initializationId) {
219
- console.warn(`[custom-blocks-sdk] ignoring init for unknown initializationId ${message.initializationId}`);
220
- return;
221
- }
222
- if (this.hasReceivedInit) {
223
- console.warn("[custom-blocks-sdk] ignoring duplicate init message");
224
- return;
225
- }
226
- this.hasReceivedInit = true;
227
- this.applyInit(message, true);
161
+ this.initialization.handleInit(message);
228
162
  return;
229
163
  }
230
164
  // Alias to keep TS's narrowed `InitializedHostState` across the switch below. Reading
@@ -428,61 +362,20 @@ export class SandboxBridge {
428
362
  */
429
363
  setMockState(message) {
430
364
  this.isMockState = true;
431
- this.applyInit(v.parse(initMessageSchema, message), false);
432
- }
433
- completeInitialization() {
434
- if (this.hasSentInitResult ||
435
- this.initializationId === undefined ||
436
- this.hostState.status !== "initialized") {
437
- return;
365
+ const parsed = v.parse(initMessageSchema, message);
366
+ if (parsed.status === "success") {
367
+ this.startListening();
368
+ this.applyInit(parsed, false);
369
+ this.initialization.setPreview();
438
370
  }
439
- const result = {
440
- type: "initResult",
441
- initializationId: this.initializationId,
442
- status: "success",
443
- initialHeight: getInitialContentHeight(),
444
- };
445
- this.hasSentInitResult = true;
446
- this.postToHost(result);
447
- this.flushPendingOutboundMessages();
448
371
  }
449
- sendInitResultError(error) {
450
- if (this.hasSentInitResult || this.initializationId === undefined) {
451
- return;
452
- }
453
- const result = {
454
- type: "initResult",
455
- initializationId: this.initializationId,
456
- status: "error",
457
- error,
458
- };
459
- this.hasSentInitResult = true;
460
- this.postToHost(result);
461
- if (this.rejectInit) {
462
- this.rejectInit(new CustomBlockInitializationError(error));
463
- this.resolveInit = undefined;
464
- this.rejectInit = undefined;
465
- }
372
+ completeInitialization() {
373
+ this.initialization.complete();
466
374
  }
467
375
  applyInit(message, postResult) {
468
376
  if (postResult) {
469
377
  this.isMockState = false;
470
378
  }
471
- if (message.status === "error") {
472
- // The host couldn't construct block location for this block (most commonly the parent
473
- // record failed to resolve). Surface the failure through the `awaitInit` promise so
474
- // callers see it through `useCustomBlockInit().error` instead of timing out. We also
475
- // log here because not every consumer renders the error UI, and we want the failure
476
- // visible in the browser console either way. We deliberately don't NACK the host or
477
- // post anything back over the bridge since the host has already given up.
478
- console.error(`[custom-blocks-sdk] host reported init error (${message.error.code}): ${message.error.message}`);
479
- if (this.rejectInit) {
480
- this.rejectInit(new CustomBlockInitializationError(message.error));
481
- this.resolveInit = undefined;
482
- this.rejectInit = undefined;
483
- }
484
- return;
485
- }
486
379
  const { blockId, parent, page } = message;
487
380
  this.latestDataSourceBindings = message.dataSources.bindings;
488
381
  const dataSources = postResult
@@ -493,8 +386,7 @@ export class SandboxBridge {
493
386
  : resolveMockDataSources(this.latestDataSourceBindings);
494
387
  const bindingError = getInitBindingError(message.manifest, dataSources);
495
388
  if (postResult && bindingError !== undefined) {
496
- this.sendInitResultError(bindingError);
497
- return;
389
+ return bindingError;
498
390
  }
499
391
  this.hostState = {
500
392
  status: "initialized",
@@ -513,41 +405,7 @@ export class SandboxBridge {
513
405
  contrastMode: message.contrastMode,
514
406
  });
515
407
  this.notify();
516
- // Resolve the awaitInit promise once. Subsequent `init` messages (the host shouldn't send
517
- // these, but be tolerant) update state but don't re-resolve.
518
- if (this.resolveInit) {
519
- this.resolveInit();
520
- this.resolveInit = undefined;
521
- this.rejectInit = undefined;
522
- }
523
- if (postResult) {
524
- this.scheduleInitResult(message.initializationId);
525
- }
526
- }
527
- /**
528
- * Lets the initial application render commit before we acknowledge init. The host keeps the
529
- * iframe covered throughout this frame, so it can apply the measured height before first paint.
530
- */
531
- scheduleInitResult(initializationId) {
532
- let didAcknowledge = false;
533
- let fallbackTimerId;
534
- const acknowledge = () => {
535
- if (didAcknowledge) {
536
- return;
537
- }
538
- didAcknowledge = true;
539
- if (fallbackTimerId !== undefined) {
540
- window.clearTimeout(fallbackTimerId);
541
- }
542
- if (this.initializationId !== initializationId) {
543
- return;
544
- }
545
- this.completeInitialization();
546
- };
547
- fallbackTimerId = window.setTimeout(acknowledge, INIT_RESULT_TIMER_FALLBACK_MS);
548
- if (typeof requestAnimationFrame === "function") {
549
- requestAnimationFrame(acknowledge);
550
- }
408
+ return undefined;
551
409
  }
552
410
  createDataSourceSubscriptionId() {
553
411
  return `data-source:${globalThis.crypto.randomUUID()}`;
@@ -0,0 +1,52 @@
1
+ import { type InitMessage } from "../protocol/messages/init.js";
2
+ import type { CustomBlockInitResultErrorInfo } from "../protocol/messages/initResult.js";
3
+ import type { SandboxToHostMessage } from "../protocol/messages/sandboxToHost.js";
4
+ import { type CustomBlockInitPayload } from "../initTypes.js";
5
+ import type { CustomBlockHostState } from "./hostState.js";
6
+ import { type ManifestLoadResult } from "./loadManifest.js";
7
+ /** Bridge callbacks used by the initialization controller. */
8
+ export type InitializationOptions = {
9
+ /** Starts listening for host messages on the first call to initialize, before connect is sent. */
10
+ start: () => void;
11
+ /** Sends a message immediately, bypassing the controller's outbound queue. */
12
+ post: (message: SandboxToHostMessage) => void;
13
+ /**
14
+ * Applies a validated, matching init response and notifies state subscribers.
15
+ * Returns an error if the host context cannot be accepted, or undefined on success.
16
+ */
17
+ apply: (message: Extract<InitMessage, {
18
+ status: "success";
19
+ }>) => CustomBlockInitResultErrorInfo | undefined;
20
+ /** Reads the current host state to build the context returned after initialization. */
21
+ getState: () => CustomBlockHostState;
22
+ /** Measures the initial content height in pixels when sending initResult.success. */
23
+ getInitialHeight: () => number;
24
+ };
25
+ /** Owns one document's startup, acknowledgement, and messages queued during rendering. */
26
+ export declare class SandboxInitialization {
27
+ private readonly options;
28
+ private phase;
29
+ private pendingMessages;
30
+ private initPromise;
31
+ private frameId;
32
+ private fallbackId;
33
+ private resolveInit;
34
+ private rejectInit;
35
+ private readonly initialized;
36
+ constructor(options: InitializationOptions);
37
+ initialize(): Promise<CustomBlockInitPayload>;
38
+ private run;
39
+ private loadManifestAndConnect;
40
+ sendConnect(result: ManifestLoadResult): void;
41
+ handleInit(message: InitMessage): void;
42
+ handleInvalidInit(id: string | undefined, error: CustomBlockInitResultErrorInfo): boolean;
43
+ post(message: SandboxToHostMessage): void;
44
+ complete(): void;
45
+ setPreview(): void;
46
+ dispose(): void;
47
+ private fail;
48
+ private resolve;
49
+ private reject;
50
+ private clearAcknowledgement;
51
+ }
52
+ //# sourceMappingURL=SandboxInitialization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SandboxInitialization.d.ts","sourceRoot":"","sources":["../../src/bridge/SandboxInitialization.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,WAAW,EAChB,MAAM,mDAAmD,CAAA;AAC1D,OAAO,KAAK,EACX,8BAA8B,EAE9B,MAAM,yDAAyD,CAAA;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4DAA4D,CAAA;AAEtG,OAAO,EAAE,KAAK,sBAAsB,EAAoB,MAAM,iBAAiB,CAAA;AAE/E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAC1D,OAAO,EAEN,KAAK,kBAAkB,EACvB,MAAM,mBAAmB,CAAA;AAuB1B,8DAA8D;AAC9D,MAAM,MAAM,qBAAqB,GAAG;IACnC,kGAAkG;IAClG,KAAK,EAAE,MAAM,IAAI,CAAA;IACjB,8EAA8E;IAC9E,IAAI,EAAE,CAAC,OAAO,EAAE,oBAAoB,KAAK,IAAI,CAAA;IAC7C;;;OAGG;IACH,KAAK,EAAE,CACN,OAAO,EAAE,OAAO,CAAC,WAAW,EAAE;QAAE,MAAM,EAAE,SAAS,CAAA;KAAE,CAAC,KAChD,8BAA8B,GAAG,SAAS,CAAA;IAC/C,uFAAuF;IACvF,QAAQ,EAAE,MAAM,oBAAoB,CAAA;IACpC,qFAAqF;IACrF,gBAAgB,EAAE,MAAM,MAAM,CAAA;CAC9B,CAAA;AAED,0FAA0F;AAC1F,qBAAa,qBAAqB;IAarB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAZpC,OAAO,CAAC,KAAK,CAAqC;IAClD,OAAO,C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