@notionhq/custom-blocks 0.2.21 → 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
@@ -0,0 +1,217 @@
1
+ import { CustomBlockInitializationError, } from "../protocol/messages/init.js";
2
+ import { LATEST_BRIDGE_PROTOCOL_VERSION } from "../protocol/protocolVersion.js";
3
+ import { NotInIframeError } from "../initTypes.js";
4
+ import { CUSTOM_BLOCKS_SDK_VERSION } from "../version.js";
5
+ import { attemptToLoadSelfHostedManifest, } from "./loadManifest.js";
6
+ const INITIALIZATION_ID = "custom-block-initialization-1";
7
+ /** Owns one document's startup, acknowledgement, and messages queued during rendering. */
8
+ export class SandboxInitialization {
9
+ options;
10
+ phase = "idle";
11
+ pendingMessages = [];
12
+ initPromise;
13
+ frameId;
14
+ fallbackId;
15
+ resolveInit;
16
+ rejectInit;
17
+ initialized = new Promise((resolve, reject) => {
18
+ this.resolveInit = resolve;
19
+ this.rejectInit = reject;
20
+ });
21
+ constructor(options) {
22
+ this.options = options;
23
+ // A host can report an error before a caller starts awaiting initialization.
24
+ void this.initialized.catch(() => { });
25
+ }
26
+ initialize() {
27
+ if (this.initPromise === undefined) {
28
+ this.options.start();
29
+ this.initPromise = this.run();
30
+ }
31
+ return this.initPromise;
32
+ }
33
+ async run() {
34
+ try {
35
+ if (typeof window !== "undefined" && window.parent === window) {
36
+ throw new NotInIframeError();
37
+ }
38
+ await Promise.all([this.loadManifestAndConnect(), this.initialized]);
39
+ const state = this.options.getState();
40
+ if (state.status !== "initialized") {
41
+ throw new CustomBlockInitializationError({
42
+ code: "context_unavailable",
43
+ message: "Host block payload is unavailable.",
44
+ isRetryable: true,
45
+ });
46
+ }
47
+ return {
48
+ theme: state.theme,
49
+ contrastMode: state.contrastMode,
50
+ blockId: state.blockId,
51
+ parent: state.parent,
52
+ page: state.page,
53
+ currentUser: state.currentUser,
54
+ dataSources: state.dataSources,
55
+ };
56
+ }
57
+ catch (error) {
58
+ if (error instanceof CustomBlockInitializationError) {
59
+ throw error;
60
+ }
61
+ throw new CustomBlockInitializationError({
62
+ code: "unknown_error",
63
+ message: error instanceof Error ? error.message : String(error),
64
+ isRetryable: false,
65
+ });
66
+ }
67
+ }
68
+ async loadManifestAndConnect() {
69
+ const manifest = await attemptToLoadSelfHostedManifest();
70
+ if (this.phase !== "disposed") {
71
+ this.sendConnect(manifest);
72
+ }
73
+ }
74
+ sendConnect(result) {
75
+ if (typeof window === "undefined") {
76
+ return;
77
+ }
78
+ if (this.phase !== "idle" && this.phase !== "preview") {
79
+ console.warn("[custom-blocks-sdk] ignoring duplicate connect message");
80
+ return;
81
+ }
82
+ this.phase = "waiting";
83
+ const identity = {
84
+ type: "connect",
85
+ initializationId: INITIALIZATION_ID,
86
+ bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
87
+ sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
88
+ };
89
+ const message = result.error !== undefined
90
+ ? { ...identity, status: "error", error: result.error }
91
+ : {
92
+ ...identity,
93
+ status: "success",
94
+ ...(result.manifest !== null ? { manifest: result.manifest } : {}),
95
+ };
96
+ this.options.post(message);
97
+ }
98
+ handleInit(message) {
99
+ if (this.phase === "idle" ||
100
+ this.phase === "preview" ||
101
+ this.phase === "disposed" ||
102
+ message.initializationId !== INITIALIZATION_ID) {
103
+ console.warn(`[custom-blocks-sdk] ignoring init for unknown initializationId ${message.initializationId}`);
104
+ return;
105
+ }
106
+ if (this.phase !== "waiting") {
107
+ console.warn("[custom-blocks-sdk] ignoring duplicate init message");
108
+ return;
109
+ }
110
+ this.phase = "applying";
111
+ if (message.status === "error") {
112
+ console.error(`[custom-blocks-sdk] host reported init error (${message.error.code}): ${message.error.message}`);
113
+ this.phase = "failed";
114
+ this.reject(new CustomBlockInitializationError(message.error));
115
+ return;
116
+ }
117
+ const error = this.options.apply(message);
118
+ if (error !== undefined) {
119
+ this.fail(error);
120
+ return;
121
+ }
122
+ // Subscribers can complete or dispose initialization while apply notifies them.
123
+ if (this.phase !== "applying") {
124
+ return;
125
+ }
126
+ this.phase = "rendering";
127
+ this.resolve();
128
+ this.fallbackId = setTimeout(() => this.complete(), 100);
129
+ if (typeof requestAnimationFrame === "function") {
130
+ this.frameId = requestAnimationFrame(() => this.complete());
131
+ }
132
+ }
133
+ handleInvalidInit(id, error) {
134
+ if (this.phase !== "waiting" || INITIALIZATION_ID !== id) {
135
+ return false;
136
+ }
137
+ this.fail(error);
138
+ return true;
139
+ }
140
+ post(message) {
141
+ if (this.phase === "disposed") {
142
+ return;
143
+ }
144
+ if (this.phase === "rendering" || this.phase === "applying") {
145
+ this.pendingMessages.push(message);
146
+ }
147
+ else {
148
+ this.options.post(message);
149
+ }
150
+ }
151
+ complete() {
152
+ if (this.phase !== "rendering") {
153
+ return;
154
+ }
155
+ const message = {
156
+ type: "initResult",
157
+ initializationId: INITIALIZATION_ID,
158
+ status: "success",
159
+ initialHeight: this.options.getInitialHeight(),
160
+ };
161
+ this.phase = "ready";
162
+ this.clearAcknowledgement();
163
+ this.options.post(message);
164
+ const pending = this.pendingMessages;
165
+ this.pendingMessages = [];
166
+ for (const message of pending) {
167
+ this.post(message);
168
+ }
169
+ }
170
+ setPreview() {
171
+ this.clearAcknowledgement();
172
+ this.phase = "preview";
173
+ this.resolve();
174
+ }
175
+ dispose() {
176
+ this.phase = "disposed";
177
+ this.clearAcknowledgement();
178
+ this.pendingMessages = [];
179
+ this.reject(new CustomBlockInitializationError({
180
+ code: "unknown_error",
181
+ message: "SDK runtime was disposed before initialization completed.",
182
+ isRetryable: false,
183
+ }));
184
+ }
185
+ fail(error) {
186
+ if (this.phase !== "waiting" && this.phase !== "applying") {
187
+ return;
188
+ }
189
+ this.phase = "failed";
190
+ this.options.post({
191
+ type: "initResult",
192
+ initializationId: INITIALIZATION_ID,
193
+ status: "error",
194
+ error,
195
+ });
196
+ this.reject(new CustomBlockInitializationError(error));
197
+ }
198
+ resolve() {
199
+ this.resolveInit?.();
200
+ this.resolveInit = undefined;
201
+ this.rejectInit = undefined;
202
+ }
203
+ reject(error) {
204
+ this.rejectInit?.(error);
205
+ this.resolveInit = undefined;
206
+ this.rejectInit = undefined;
207
+ }
208
+ clearAcknowledgement() {
209
+ clearTimeout(this.fallbackId);
210
+ this.fallbackId = undefined;
211
+ if (this.frameId !== undefined &&
212
+ typeof cancelAnimationFrame === "function") {
213
+ cancelAnimationFrame(this.frameId);
214
+ this.frameId = undefined;
215
+ }
216
+ }
217
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/bridge/dataSources/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4DAA4D,CAAA;AAElG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAA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AM,8DAA8D,CAAA;AACrE,OAAO,KAAK,EAAE,mCAAmC,EAAE,MAAM,oEAAoE,CAAA;AAE7H,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAU1D,MAAM,MAAM,uBAAuB,GAAG;IACrC,YAAY,EAAE,kBAAkB,CAAA;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,mCAAmC,CAAA;IAC5C,KAAK,CAAC,EAAE,iCAAiC,EAAE,CAAA;IAC3C,QAAQ,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,4BAA4B,GACrC;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,mCAAmC,CAAA;CAAE,GAC/D;IACA,MAAM,EAAE,IAAI,CAAA;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,KAAK,EAAE,uBAAuB,CAAA;CAC7B,CAAA;AAYJ,wBAAgB,sBAAsB,CAAC,IAAI,EAAE;IAC5C,WAAW,EAAE,gBAAgB,EAAE,CAAA;IAC/B,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;CAChC,GAAG,4BAA4B,CAgF/B;AAwFD,wBAAgB,iCAAiC,CAChD,OAAO,EAAE,oBAAoB,GAAG,SAAS,GACvC,MAAM,CAMR"}
@@ -1,5 +1,6 @@
1
1
  import { CUSTOM_BLOCK_DATA_SOURCE_SORTABLE_PROPERTY_TYPES } from "../../protocol/dataSources/propertySchema.js";
2
- import { CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS, customBlockCheckboxFilterOperatorSchema, customBlockContainsFilterOperatorSchema, customBlockCreatedByFilterOperatorSchema, customBlockDateFilterOperatorSchema, customBlockNumberFilterOperatorSchema, customBlockOptionFilterOperatorSchema, customBlockPeopleFilterOperatorSchema, customBlockTextFilterOperatorSchema, } from "../../protocol/messages/queryDataSource.js";
2
+ import { notionSortDirectionSchema } from "../../protocol/dataSources/sortDirection.js";
3
+ import { CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS, customBlockCheckboxFilterOperatorSchema, customBlockContainsFilterOperatorSchema, customBlockCreatedByFilterOperatorSchema, customBlockDateFilterOperatorSchema, customBlockNumberFilterOperatorSchema, customBlockOptionFilterOperatorSchema, customBlockPeopleFilterOperatorSchema, customBlockRelativeDateValueSchema, customBlockStatusFilterOperatorSchema, customBlockTextFilterOperatorSchema, } from "../../protocol/messages/queryDataSource.js";
3
4
  import * as v from "valibot";
4
5
  import { unreachable } from "../../utils.js";
5
6
  const DEFAULT_DATA_SOURCE_QUERY_LIMIT = 20;
@@ -257,7 +258,7 @@ function resolveSort(sort, dataSource) {
257
258
  }
258
259
  const direction = sortObject.direction;
259
260
  if (!Object.hasOwn(sortObject, "direction") ||
260
- (direction !== "ascending" && direction !== "descending")) {
261
+ !v.is(notionSortDirectionSchema, direction)) {
261
262
  return {
262
263
  status: "error",
263
264
  error: 'Data source query sort direction must be "ascending" or "descending".',
@@ -289,10 +290,11 @@ function resolvePropertyFilter(filter, dataSource) {
289
290
  }
290
291
  const branch = branchKeys[0];
291
292
  const value = filterObject[branch];
292
- if (typeof value !== "object" ||
293
- value === null ||
294
- Array.isArray(value) ||
295
- Object.keys(value).length !== 1) {
293
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
294
+ return invalidOperator(branch);
295
+ }
296
+ const operatorKeys = Object.keys(value).filter(key => branch !== "date" || key !== "target");
297
+ if (operatorKeys.length !== 1) {
296
298
  return invalidOperator(branch);
297
299
  }
298
300
  if (property.propertyType !== branch) {
@@ -324,12 +326,23 @@ function resolvePropertyFilterBranch(args) {
324
326
  case "checkbox":
325
327
  return resolveCheckboxPropertyFilter(args.propertyId, args.value);
326
328
  case "select":
327
- case "status":
328
329
  return resolveOptionPropertyFilter({
329
330
  propertyId: args.propertyId,
330
- branch: args.branch,
331
+ branch: "select",
331
332
  value: args.value,
332
333
  });
334
+ case "status": {
335
+ const parsed = v.safeParse(customBlockStatusFilterOperatorSchema, args.value);
336
+ return parsed.success
337
+ ? {
338
+ status: "ok",
339
+ filter: {
340
+ propertyId: args.propertyId,
341
+ status: parsed.output,
342
+ },
343
+ }
344
+ : invalidOperator("status");
345
+ }
333
346
  case "multi_select":
334
347
  return resolveMultiSelectPropertyFilter(args.propertyId, args.value);
335
348
  case "date":
@@ -402,20 +415,10 @@ function resolveOptionPropertyFilter(args) {
402
415
  if (!parsed.success) {
403
416
  return invalidOperator(args.branch);
404
417
  }
405
- switch (args.branch) {
406
- case "select":
407
- return {
408
- status: "ok",
409
- filter: { propertyId: args.propertyId, select: parsed.output },
410
- };
411
- case "status":
412
- return {
413
- status: "ok",
414
- filter: { propertyId: args.propertyId, status: parsed.output },
415
- };
416
- default:
417
- return unreachable(args.branch);
418
- }
418
+ return {
419
+ status: "ok",
420
+ filter: { propertyId: args.propertyId, select: parsed.output },
421
+ };
419
422
  }
420
423
  function resolveMultiSelectPropertyFilter(propertyId, value) {
421
424
  const parsed = v.safeParse(customBlockContainsFilterOperatorSchema, value);
@@ -426,7 +429,11 @@ function resolveMultiSelectPropertyFilter(propertyId, value) {
426
429
  function resolveDatePropertyFilter(propertyId, value) {
427
430
  const parsed = v.safeParse(customBlockDateFilterOperatorSchema, value);
428
431
  if (!parsed.success ||
429
- !Object.values(parsed.output).every(entry => entry === true || isValidIsoDate(entry))) {
432
+ !Object.entries(parsed.output).every(([key, entry]) => key === "target" ||
433
+ entry === true ||
434
+ typeof entry === "object" ||
435
+ v.safeParse(customBlockRelativeDateValueSchema, entry).success ||
436
+ isValidIsoDate(entry))) {
430
437
  return invalidOperator("date");
431
438
  }
432
439
  return {
@@ -0,0 +1,4 @@
1
+ import type { HostToSandboxMessage } from "../protocol/messages/hostToSandbox.js";
2
+ import type { SandboxToHostMessage } from "../protocol/messages/sandboxToHost.js";
3
+ export type MessageInterceptor = (message: SandboxToHostMessage) => HostToSandboxMessage | undefined;
4
+ //# sourceMappingURL=messageInterceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messageInterceptor.d.ts","sourceRoot":"","sources":["../../src/bridge/messageInterceptor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4DAA4D,CAAA;AACtG,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4DAA4D,CAAA;AAEtG,MAAM,MAAM,kBAAkB,GAAG,CAChC,OAAO,EAAE,oBAAoB,KACzB,oBAAoB,GAAG,SAAS,CAAA"}
@@ -0,0 +1 @@
1
+ export {};
@@ -3,11 +3,12 @@ import type { InitMessage } from "../protocol/messages/init.js";
3
3
  import type { CreatePageArgs, CreatePageResult, GetPageResult, GetUserResult, ListUsersArgs, ListUsersResult, NotionUserId, OpenPageOptions, OpenPageResult, UpdatePageArgs, UpdatePageResult } from "../types.js";
4
4
  import { type CustomBlockHostState, type DataSourceQueryView } from "./hostState.js";
5
5
  import type { ManifestLoadResult } from "./loadManifest.js";
6
+ import type { MessageInterceptor } from "./messageInterceptor.js";
6
7
  import { type MessageLogEntry, type QueryDataSourceArgs } from "./SandboxBridge.js";
7
8
  export declare const customBlockHost: {
8
- start: () => void;
9
+ registerMessageInterceptor: (interceptor: MessageInterceptor) => (() => void);
9
10
  sendConnect: (manifestResult: ManifestLoadResult) => void;
10
- awaitInit: () => Promise<void>;
11
+ initialize: () => Promise<import("../initTypes.js").CustomBlockInitPayload>;
11
12
  subscribe: (listener: () => void) => () => boolean;
12
13
  getState: () => CustomBlockHostState;
13
14
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"sandboxClient.d.ts","sourceRoot":"","sources":["../../src/bridge/sandboxClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yCAAyC,CAAA;AAC3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mDAAmD,CAAA;AACpF,OAAO,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AM;CAG3B,CAAA;AAED,eAAO,MAAM,sBAAsB;IAClC,oBAAoB;IAIpB,KAAK,SAAS,mBAAmB;IAIjC,OAAO,mBAAmB,MAAM;IAIhC,OAAO,cACK,oBAAoB,OAC1B,MAAM,kBACK,MAAM,KACpB,mBAAmB;CAQtB,CAAA;AAED,eAAO,MAAM,UAAU;IACtB,WAAW,QAAM,SAAS,eAAe,EAAE;IAI3C,SAAS,aAAa,MAAM,IAAI;CAGhC,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,KAAK;IACjB;;OAEG;IACH,MAAM,UAAU,cAAc,KAAG,OAAO,CAAC,gBAAgB,CAAC;IAI1D;;OAEG;IACH,GAAG,WAAW,YAAY,KAAG,OAAO,CAAC,aAAa,CAAC;IAInD;;OAEG;IACH,IAAI,WACK,YAAY,WACX,eAAe,KACtB,OAAO,CAAC,cAAc,CAAC;IAI1B;;OAEG;IACH,MAAM,UAAU,cAAc,KAAG,OAAO,CAAC,gBAAgB,CAAC;IAI1D;;OAEG;IACH,OAAO,WAAW,YAAY,KAAG,OAAO,CAAC,gBAAgB,CAAC;IAI1D;;OAEG;IACH,SAAS,WAAW,YAAY,KAAG,OAAO,CAAC,gBAAgB,CAAC;CAG5D,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,KAAK;IACjB;;OAEG;IACH,IAAI,WAAW,aAAa,KAAG,OAAO,CAAC,eAAe,CAAC;IAIvD;;OAEG;IACH,GAAG,WAAW,YAAY,KAAG,OAAO,CAAC,aAAa,CAAC;CAGnD,CAAA"}
@@ -8,15 +8,13 @@ function getBridge() {
8
8
  return bridge;
9
9
  }
10
10
  export const customBlockHost = {
11
- start: () => {
12
- getBridge().startListening();
11
+ registerMessageInterceptor: (interceptor) => {
12
+ return getBridge().registerMessageInterceptor(interceptor);
13
13
  },
14
14
  sendConnect: (manifestResult) => {
15
15
  getBridge().sendConnect(manifestResult);
16
16
  },
17
- awaitInit: () => {
18
- return getBridge().awaitInit();
19
- },
17
+ initialize: () => getBridge().initialize(),
20
18
  subscribe: (listener) => {
21
19
  return getBridge().subscribe(listener);
22
20
  },
@@ -0,0 +1,11 @@
1
+ import type { MessageInterceptor } from "./bridge/messageInterceptor.js";
2
+ export type { MessageInterceptor } from "./bridge/messageInterceptor.js";
3
+ /**
4
+ * Add a handler for SDK messages sent to the host.
5
+ * Return a host message to replace an outgoing message.
6
+ * Return undefined to let other handlers inspect the message.
7
+ * The SDK sends the message to the host if no handler returns a response.
8
+ * Call the returned function to remove the handler.
9
+ */
10
+ export declare function registerMessageInterceptor(interceptor: MessageInterceptor): () => void;
11
+ //# sourceMappingURL=bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAA;AAGxE,YAAY,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAA;AAExE;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACzC,WAAW,EAAE,kBAAkB,GAC7B,MAAM,IAAI,CAEZ"}
package/dist/bridge.js ADDED
@@ -0,0 +1,11 @@
1
+ import { customBlockHost } from "./bridge/sandboxClient.js";
2
+ /**
3
+ * Add a handler for SDK messages sent to the host.
4
+ * Return a host message to replace an outgoing message.
5
+ * Return undefined to let other handlers inspect the message.
6
+ * The SDK sends the message to the host if no handler returns a response.
7
+ * Call the returned function to remove the handler.
8
+ */
9
+ export function registerMessageInterceptor(interceptor) {
10
+ return customBlockHost.registerMessageInterceptor(interceptor);
11
+ }
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export type { CustomBlockDataSourceResolutionErrorCode, CustomBlockDataSourceRes
14
14
  export type { NotionBuiltinPropertyId, NotionDualProperty, NotionPropertyColor, NotionPropertyOption, NotionPropertySchema, NotionPropertyType, NotionStatusGroup, } from "./protocol/dataSources/propertySchema.js";
15
15
  export { NOTION_BUILTIN_PROPERTY_IDS, NOTION_PROPERTY_TYPES, } from "./protocol/dataSources/propertySchema.js";
16
16
  export type { NotionRecordPointer } from "./protocol/dataSources/recordPointer.js";
17
+ export type { NotionSortDirection } from "./protocol/dataSources/sortDirection.js";
17
18
  export type { CustomBlockErrorInfo } from "./protocol/errors.js";
18
19
  export type { NotionAgentId, NotionBlockId, NotionDataSourceId, NotionPageId, NotionSpaceId, } from "./protocol/ids.js";
19
20
  export type { CustomBlockManifest, ManifestDataSource, ManifestIcon, ManifestProperty, } from "./protocol/manifest.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAA;AACtF,YAAY,EACX,sBAAsB,EACtB,gBAAgB,GAChB,MAAM,4DAA4D,CAAA;AACnE,YAAY,EAAE,qBAAqB,EAAE,MAAM,iEAAiE,CAAA;AAC5G,YAAY,EACX,UAAU,EACV,eAAe,EACf,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,sBAAsB,EACtB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,GAClB,MAAM,2DAA2D,CAAA;AAClE,YAAY,EACX,wCAAwC,EACxC,wCAAwC,EACxC,4BAA4B,EAC5B,4BAA4B,GAC5B,MAAM,wDAAwD,CAAA;AAC/D,YAAY,EACX,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,GACjB,MAAM,gEAAgE,CAAA;AACvE,OAAO,EACN,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,gEAAgE,CAAA;AACvE,YAAY,EAAE,mBAAmB,EAAE,MAAM,+DAA+D,CAAA;AACxG,YAAY,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAA;AACtF,YAAY,EACX,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,aAAa,GACb,MAA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AA;AAC7D,YAAY,EACX,2BAA2B,EAC3B,2BAA2B,GAC3B,MAAM,sDAAsD,CAAA;AAC7D,YAAY,EACX,kCAAkC,EAClC,kCAAkC,GAClC,MAAM,mDAAmD,CAAA;AAC1D,OAAO,EAAE,8BAA8B,EAAE,MAAM,mDAAmD,CAAA;AAClG,YAAY,EACX,6BAA6B,EAC7B,6BAA6B,GAC7B,MAAM,wDAAwD,CAAA;AAC/D,YAAY,EACX,4BAA4B,EAC5B,4BAA4B,EAC5B,YAAY,GACZ,MAAM,uDAAuD,CAAA;AAC9D,YAAY,EACX,mCAAmC,EACnC,mCAAmC,GACnC,MAAM,oEAAoE,CAAA;AAC3E,YAAY,EACX,8BAA8B,EAC9B,8BAA8B,GAC9B,MAAM,+DAA+D,CAAA;AACtE,YAAY,EACX,eAAe,EACf,UAAU,EACV,eAAe,EACf,cAAc,EACd,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,gDAAgD,CAAA;AACvD,YAAY,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAA;AAC9E,YAAY,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA;AAC5E,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAA;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAC9C,OAAO,EACN,KAAK,sBAAsB,EAC3B,eAAe,EACf,gBAAgB,GAChB,MAAM,WAAW,CAAA;AAClB,cAAc,YAAY,CAAA"}
package/dist/init.d.ts CHANGED
@@ -1,42 +1,8 @@
1
- import type { NotionContrastMode } from "./protocol/contrast.js";
2
- import type { NotionDataSource } from "./protocol/dataSources/dataSource.js";
3
- import type { NotionBlockId } from "./protocol/ids.js";
4
- import { CustomBlockInitializationError } from "./protocol/messages/init.js";
5
- import type { CustomBlockPage } from "./protocol/pages/page.js";
6
- import type { NotionParent } from "./protocol/parent.js";
7
- import type { NotionTheme } from "./protocol/theme.js";
8
- import type { NotionUser } from "./protocol/users/user.js";
1
+ import type { CustomBlockInitPayload } from "./initTypes.js";
2
+ export { type CustomBlockInitPayload, NotInIframeError, } from "./initTypes.js";
9
3
  /**
10
- * The payload sent by the host in the `init` message in response to the sandbox's `connect` message.
11
- */
12
- export type CustomBlockInitPayload = {
13
- theme: NotionTheme;
14
- contrastMode: NotionContrastMode;
15
- blockId: NotionBlockId;
16
- parent: NotionParent;
17
- page: CustomBlockPage;
18
- currentUser: NotionUser;
19
- dataSources: NotionDataSource[];
20
- };
21
- /**
22
- * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
23
- * `postMessage` would just hit the same window and the handshake can never complete.
24
- * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
25
- * warning banner. Direct callers can `instanceof` it to apply their own policy.
26
- */
27
- export declare class NotInIframeError extends CustomBlockInitializationError {
28
- constructor(message?: string);
29
- code: "not_in_iframe";
30
- }
31
- /**
32
- * Initializes the custom block by running the SDK <-> host handshake.
33
- *
34
- * Resolves with the block's initial context (theme, block location, current
35
- * user, data sources) once the host has initialized the block. Rejects with a
36
- * `CustomBlockInitializationError` if initialization fails.
37
- *
38
- * Idempotent: subsequent calls return the same promise as the first.
39
- * Mount your React tree (or call any SDK hook) only after the returned promise resolves.
4
+ * Initializes the block once. Later calls reuse the first promise.
5
+ * Await this promise before reading initialized state or mounting SDK hooks.
40
6
  */
41
7
  export declare function initCustomBlock(): Promise<CustomBlockInitPayload>;
42
8
  //# sourceMappingURL=init.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAA;AACtF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4DAA4D,CAAA;AAClG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yCAAyC,CAAA;AAC5E,OAAO,EAAE,8BAA8B,EAAE,MAAM,mDAAmD,CAAA;AAClG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gDAAgD,CAAA;AACrF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAA;AAC9E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA;AAC5E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gDAAgD,CAAA;AAKhF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACpC,KAAK,EAAE,WAAW,CAAA;IAClB,YAAY,EAAE,kBAAkB,CAAA;IAChC,OAAO,EAAE,aAAa,CAAA;IACtB,MAAM,EAAE,YAAY,CAAA;IACpB,IAAI,EAAE,eAAe,CAAA;IACrB,WAAW,EAAE,UAAU,CAAA;IACvB,WAAW,EAAE,gBAAgB,EAAE,CAAA;CAC/B,CAAA;AAED;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,8BAA8B;IACnE,YAAY,OAAO,GAAE,MAA8B,EAOlD;IAEO,IAAI,EAAE,eAAe,CAAA;CAC7B;AAOD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,IAAI,OAAO,CAAC,sBAAsB,CAAC,CAMjE"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAA;AAE5D,OAAO,EACN,KAAK,sBAAsB,EAC3B,gBAAgB,GAChB,MAAM,gBAAgB,CAAA;AAEvB;;;GAGG;AACH,wBAAgB,eAAe,IAAI,OAAO,CAAC,sBAAsB,CAAC,CAEjE"}
package/dist/init.js CHANGED
@@ -1,96 +1,9 @@
1
- import { CustomBlockInitializationError } from "./protocol/messages/init.js";
2
- import { attemptToLoadSelfHostedManifest } from "./bridge/loadManifest.js";
3
1
  import { customBlockHost } from "./bridge/sandboxClient.js";
4
- import { unreachable } from "./utils.js";
2
+ export { NotInIframeError, } from "./initTypes.js";
5
3
  /**
6
- * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
7
- * `postMessage` would just hit the same window and the handshake can never complete.
8
- * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
9
- * warning banner. Direct callers can `instanceof` it to apply their own policy.
10
- */
11
- export class NotInIframeError extends CustomBlockInitializationError {
12
- constructor(message = NOT_IN_IFRAME_MESSAGE) {
13
- super({
14
- code: "not_in_iframe",
15
- message,
16
- isRetryable: false,
17
- });
18
- this.name = "NotInIframeError";
19
- }
20
- }
21
- const NOT_IN_IFRAME_MESSAGE = "<NotionCustomBlock> only works inside an iframe — use the dev shell or deploy to Notion.";
22
- let initPromise;
23
- /**
24
- * Initializes the custom block by running the SDK <-> host handshake.
25
- *
26
- * Resolves with the block's initial context (theme, block location, current
27
- * user, data sources) once the host has initialized the block. Rejects with a
28
- * `CustomBlockInitializationError` if initialization fails.
29
- *
30
- * Idempotent: subsequent calls return the same promise as the first.
31
- * Mount your React tree (or call any SDK hook) only after the returned promise resolves.
4
+ * Initializes the block once. Later calls reuse the first promise.
5
+ * Await this promise before reading initialized state or mounting SDK hooks.
32
6
  */
33
7
  export function initCustomBlock() {
34
- if (initPromise === undefined) {
35
- customBlockHost.start();
36
- initPromise = performHandshake();
37
- }
38
- return initPromise;
39
- }
40
- /**
41
- * Performs the host <-> sandbox SDK handshake:
42
- * 1. On localhost, attempts to load the worker manifest from the page-relative
43
- * `manifest` path
44
- * 2. Sends `connect` with the manifest
45
- * 3. Awaits the host's `init` message
46
- * 4. Applies the `init` payload and acknowledges with `initResult` (fire-and-forget)
47
- *
48
- * Resolves with the `init` payload after the process above. Rejects with a
49
- * `CustomBlockInitializationError` if any step fails.
50
- */
51
- async function performHandshake() {
52
- try {
53
- // Fail fast with a typed error when rendered as a standalone tab and not in a parent frame.
54
- // Otherwise, `postMessage` to `window.parent` would just hit the same window and never
55
- // arrive.
56
- if (typeof window !== "undefined" && window.parent === window) {
57
- throw new NotInIframeError();
58
- }
59
- // Load the manifest and send it to the host.
60
- const manifestResult = await attemptToLoadSelfHostedManifest();
61
- customBlockHost.sendConnect(manifestResult);
62
- await customBlockHost.awaitInit();
63
- const hostState = customBlockHost.getState();
64
- switch (hostState.status) {
65
- case "initialized":
66
- return {
67
- theme: hostState.theme,
68
- contrastMode: hostState.contrastMode,
69
- blockId: hostState.blockId,
70
- parent: hostState.parent,
71
- page: hostState.page,
72
- currentUser: hostState.currentUser,
73
- dataSources: hostState.dataSources,
74
- };
75
- case "uninitialized":
76
- throw new CustomBlockInitializationError({
77
- code: "context_unavailable",
78
- message: "Host block payload is unavailable.",
79
- isRetryable: true,
80
- });
81
- default:
82
- return unreachable(hostState);
83
- }
84
- }
85
- catch (error) {
86
- if (error instanceof CustomBlockInitializationError) {
87
- throw error;
88
- }
89
- const message = error instanceof Error ? error.message : String(error);
90
- throw new CustomBlockInitializationError({
91
- code: "unknown_error",
92
- message,
93
- isRetryable: false,
94
- });
95
- }
8
+ return customBlockHost.initialize();
96
9
  }
@@ -0,0 +1,31 @@
1
+ import type { NotionContrastMode } from "./protocol/contrast.js";
2
+ import type { NotionDataSource } from "./protocol/dataSources/dataSource.js";
3
+ import type { NotionBlockId } from "./protocol/ids.js";
4
+ import { CustomBlockInitializationError } from "./protocol/messages/init.js";
5
+ import type { CustomBlockPage } from "./protocol/pages/page.js";
6
+ import type { NotionParent } from "./protocol/parent.js";
7
+ import type { NotionTheme } from "./protocol/theme.js";
8
+ import type { NotionUser } from "./protocol/users/user.js";
9
+ /**
10
+ * Initial context returned by `initCustomBlock()`.
11
+ */
12
+ export type CustomBlockInitPayload = {
13
+ theme: NotionTheme;
14
+ contrastMode: NotionContrastMode;
15
+ blockId: NotionBlockId;
16
+ parent: NotionParent;
17
+ page: CustomBlockPage;
18
+ currentUser: NotionUser;
19
+ dataSources: NotionDataSource[];
20
+ };
21
+ /**
22
+ * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
23
+ * `postMessage` would just hit the same window and the handshake can never complete.
24
+ * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
25
+ * warning banner. Direct callers can `instanceof` it to apply their own policy.
26
+ */
27
+ export declare class NotInIframeError extends CustomBlockInitializationError {
28
+ constructor(message?: string);
29
+ code: "not_in_iframe";
30
+ }
31
+ //# sourceMappingURL=initTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initTypes.d.ts","sourceRoot":"","sources":["../src/initTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAA;AACtF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4DAA4D,CAAA;AAClG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yCAAyC,CAAA;AAC5E,OAAO,EAAE,8BAA8B,EAAE,MAAM,mDAAmD,CAAA;AAClG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gDAAgD,CAAA;AACrF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAA;AAC9E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAA;AAC5E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gDAAgD,CAAA;AAEhF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACpC,KAAK,EAAE,WAAW,CAAA;IAClB,YAAY,EAAE,kBAAkB,CAAA;IAChC,OAAO,EAAE,aAAa,CAAA;IACtB,MAAM,EAAE,YAAY,CAAA;IACpB,IAAI,EAAE,eAAe,CAAA;IACrB,WAAW,EAAE,UAAU,CAAA;IACvB,WAAW,EAAE,gBAAgB,EAAE,CAAA;CAC/B,CAAA;AAED;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,8BAA8B;IACnE,YAAY,OAAO,GAAE,MAA8B,EAOlD;IAEO,IAAI,EAAE,eAAe,CAAA;CAC7B"}
@@ -0,0 +1,18 @@
1
+ import { CustomBlockInitializationError } from "./protocol/messages/init.js";
2
+ /**
3
+ * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
4
+ * `postMessage` would just hit the same window and the handshake can never complete.
5
+ * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
6
+ * warning banner. Direct callers can `instanceof` it to apply their own policy.
7
+ */
8
+ export class NotInIframeError extends CustomBlockInitializationError {
9
+ constructor(message = NOT_IN_IFRAME_MESSAGE) {
10
+ super({
11
+ code: "not_in_iframe",
12
+ message,
13
+ isRetryable: false,
14
+ });
15
+ this.name = "NotInIframeError";
16
+ }
17
+ }
18
+ const NOT_IN_IFRAME_MESSAGE = "Custom block initialization requires a Notion host. For local development, open the block in the dev shell. Otherwise, deploy it to Notion.";