@notionhq/custom-blocks-dev-shell 0.4.1 → 0.4.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.
@@ -1,200 +0,0 @@
1
- # @notionhq/custom-blocks-host
2
-
3
- The host manages the bridge between your application and a custom block iframe. Your application
4
- owns the iframe, permissions, data access, persistence, analytics, and UI. Block authors use
5
- `@notionhq/custom-blocks`.
6
-
7
- Create the host before navigating the iframe. Pass the full block URL as `sandboxUrl`, and call
8
- `stop()` when removing the iframe. The host calls `getViewer()` synchronously once to capture a user
9
- or anonymous identity. Create a fresh host and iframe when that identity changes. The
10
- `handlers.getUser` handler loads profiles separately. See
11
- [Current viewer](docs/host-contract.md#current-viewer) for identity validation and profile-read
12
- errors.
13
-
14
- For configuration and lifecycle details, see [Initialization and lifecycle](docs/lifecycle.md).
15
-
16
- For data handlers, query subscriptions, and partial integrations, see the
17
- [Host contract](docs/host-contract.md). The host accepts `CustomBlockHostOptions`.
18
-
19
- Use `BridgeParent` from `@notionhq/custom-blocks-host/protocol` to construct parent references with
20
- plain string IDs. The host validates the parent before sending it to the block.
21
-
22
- Implement `CustomBlockHostHandlers` to connect the host to your application. Handlers that return
23
- results use promises. `CustomBlockHostHandler<Args, Payload>` supplies the shared signature and
24
- request context. Handlers return shared bridge data using `CustomBlockHostHandlerResult`. Use
25
- `makeBridgePage` to construct a complete `BridgePage` from your records. See
26
- [Return bridge data](docs/handlers.md#return-bridge-data).
27
-
28
- ## Create a host
29
-
30
- Install `@notionhq/custom-blocks-host` in your embedding application. Run this TypeScript through
31
- your browser bundler after the document body exists.
32
-
33
- This example embeds a block with no data sources and supplies fixed demo context. Replace
34
- `https://blocks.example.com/hello` with your block's URL. Serve the block from a different origin
35
- than the embedding application.
36
-
37
- ```ts
38
- import { createCustomBlockHost, hostHandlerNotImplemented } from "@notionhq/custom-blocks-host"
39
-
40
- function mountCustomBlock(container: HTMLElement, blockUrl: URL): () => void {
41
- if (
42
- !["http:", "https:"].includes(blockUrl.protocol) ||
43
- blockUrl.origin === window.location.origin
44
- ) {
45
- throw new Error("The block needs an HTTP or HTTPS URL on a separate origin")
46
- }
47
-
48
- const wrapper = document.createElement("section")
49
- const status = document.createElement("p")
50
- status.setAttribute("role", "status")
51
- status.textContent = "Loading block…"
52
- const iframe = document.createElement("iframe")
53
- iframe.title = "Hello custom block"
54
- iframe.setAttribute("sandbox", "allow-scripts allow-same-origin")
55
- iframe.allow = "clipboard-write"
56
- iframe.style.width = "100%"
57
- iframe.style.height = "300px"
58
- iframe.style.visibility = "hidden"
59
- wrapper.append(status, iframe)
60
- container.append(wrapper)
61
-
62
- function setHeight(height: number) {
63
- iframe.style.height = `${Math.min(1200, Math.max(120, height))}px`
64
- }
65
-
66
- const host = createCustomBlockHost({
67
- iframe,
68
- instance: { type: "block", blockId: "11111111-1111-4111-8111-111111111111" },
69
- getViewer: () => ({ type: "user", userId: "33333333-3333-4333-8333-333333333333" }),
70
- theme: "light",
71
- contrastMode: "standard",
72
- containingPage: {
73
- type: "page",
74
- id: "22222222-2222-4222-8222-222222222222",
75
- parent: { type: "workspace", workspace: true },
76
- },
77
- parent: {
78
- type: "page_id",
79
- page_id: "22222222-2222-4222-8222-222222222222",
80
- },
81
- sandboxUrl: blockUrl.href,
82
- manifestSource: "host",
83
- getPersistedManifest: async () => ({
84
- status: "success",
85
- manifest: { version: 1, dataSources: {} },
86
- }),
87
- bindings: { pages: {}, dataSources: {} },
88
- handlers: {
89
- getDataSource: async () => ({ status: "success", state: { status: "unavailable" } }),
90
- subscribeToQuery: ({ onError }) => onError(hostHandlerNotImplemented("subscribeToQuery")),
91
- getPage: async () => ({ status: "error", error: hostHandlerNotImplemented("getPage") }),
92
- createPage: async () => ({ status: "error", error: hostHandlerNotImplemented("createPage") }),
93
- updatePage: async () => ({ status: "error", error: hostHandlerNotImplemented("updatePage") }),
94
- getUser: async () => ({ status: "error", error: hostHandlerNotImplemented("getUser") }),
95
- listUsers: async () => ({ status: "error", error: hostHandlerNotImplemented("listUsers") }),
96
- openPage: async () => ({ status: "error", error: hostHandlerNotImplemented("openPage") }),
97
- openExternalUrl: async () => ({
98
- status: "error",
99
- error: hostHandlerNotImplemented("openExternalUrl"),
100
- }),
101
- resize: message => setHeight(message.height),
102
- },
103
- onStatusChange: state => {
104
- if (state.status === "ready") {
105
- setHeight(state.initialHeight ?? 300)
106
- status.hidden = true
107
- iframe.style.visibility = "visible"
108
- } else if (state.status === "failed") {
109
- iframe.style.visibility = "hidden"
110
- status.hidden = false
111
- status.textContent = `Block failed: ${state.error.code}`
112
- }
113
- },
114
- })
115
-
116
- // The host must listen before the block starts its handshake.
117
- iframe.src = blockUrl.href
118
-
119
- return () => {
120
- host.stop()
121
- wrapper.remove()
122
- }
123
- }
124
-
125
- const dispose = mountCustomBlock(document.body, new URL("https://blocks.example.com/hello"))
126
- window.addEventListener("pagehide", dispose, { once: true })
127
- ```
128
-
129
- The example displays “Loading block…” until the host reports `ready`, then reveals the iframe. A
130
- connection failure displays its error code. The example limits the iframe height to 120–1,200 CSS
131
- pixels.
132
-
133
- Call `dispose()` when your application removes the embed. To retry a failed connection or change the
134
- block URL, dispose of the current embed and call `mountCustomBlock()` again.
135
-
136
- Initial `theme`, `contrastMode`, `containingPage`, and `parent` may be `null` while loading. Call
137
- the corresponding setters as values resolve. Setup waits for the manifest, theme, and contrast mode.
138
- Parent and containing page values can arrive later. See
139
- [manifest and initial state](docs/lifecycle.md#manifest-and-initial-state) for the loading contract.
140
-
141
- For a production integration, replace the demo context and manifest with your application's values.
142
- Supply data source bindings and handlers for the APIs your block uses. Your application must enforce
143
- permissions and record access.
144
-
145
- To connect workspace data, see [Connect a data source](docs/handlers.md#connect-a-data-source).
146
-
147
- Data source reads resolve configured property IDs against the loaded schema. Exact matches win.
148
- Otherwise, the host decodes a URL-encoded ID once and uses it only when it matches a schema
149
- property. The host validates these mappings before returning them; saved bindings stay unchanged.
150
-
151
- `CustomBlockHostInstance` accepts plain string IDs. `instance` identifies the configured block,
152
- page, or view independently of the page currently being displayed. `CustomBlockInstance` uses
153
- `{ type: "block" | "page", blockId }` or `{ type: "view", viewId }`. The identity stays fixed for
154
- the host connection and is included in `init`. A layout module backed by a custom block uses that
155
- block's identity.
156
-
157
- ## Guides and reference
158
-
159
- - [Initialization and lifecycle](docs/lifecycle.md): manifests, initial values, timeouts, live
160
- updates, and cleanup.
161
- - [Handlers and data](docs/handlers.md): application handlers, data source integration, queries, and
162
- navigation.
163
- - [Connection compatibility](docs/compatibility.md): protocol negotiation and version requirements.
164
-
165
- The runtime handles the wire handshake and message validation. The shared protocol references define
166
- message payloads and versioning:
167
-
168
- - [Wire protocol](../bridge/protocol.md)
169
- - [Protocol versioning](../bridge/versioning.md)
170
-
171
- ## Protocol schemas and types
172
-
173
- The `/protocol` entrypoint exposes message schemas and types, data shapes, IDs, and error
174
- definitions. Import these definitions through the host package:
175
-
176
- ```ts
177
- import {
178
- sandboxToHostMessageSchema,
179
- type SandboxToHostMessage,
180
- } from "@notionhq/custom-blocks-host/protocol"
181
- ```
182
-
183
- Host APIs, configuration, handler results, and domain argument types are available from
184
- `@notionhq/custom-blocks-host`.
185
-
186
- These schemas validate wire payloads. Your application still enforces permissions.
187
-
188
- ## Standalone browser module
189
-
190
- `dist/browser.js` is one ES module with all dependencies. Use it when the browser must not fetch
191
- additional modules, such as under an exact-URL Content Security Policy.
192
-
193
- ### Native page icons
194
-
195
- `CustomBlockHostPageIcon` accepts canonical native icon names from hosts. Hosts validate names and
196
- colors before writing. The runtime validates response payloads.
197
-
198
- Hosts must check URL-backed icon and cover writes against the block's network permissions before
199
- mutating records. Notion permits the submitted HTTPS destination only when its origin is
200
- allowlisted. That origin is trusted to redirect.
@@ -1,126 +0,0 @@
1
- # Connection compatibility
2
-
3
- The SDK and host release independently. Their package versions do not determine whether they can
4
- communicate. The connection uses a protocol version that both implement.
5
-
6
- ## Supported versions
7
-
8
- The current SDK connection contract is protocol 12. The SDK sends `connect` with a
9
- `supportedProtocolVersions` array of distinct positive integers. The host selects a version from
10
- that offer and returns it in `connectResult.protocolVersion`. This host selects protocol 12 when the
11
- offer includes it and the configured minimum permits it. Otherwise, it returns
12
- `unsupported_protocol_version`.
13
-
14
- The selected version applies to the connection. `init` does not repeat it. `sdkVersion` identifies
15
- the SDK package for diagnostics. It does not select the protocol.
16
-
17
- `LATEST_BRIDGE_PROTOCOL_VERSION` identifies the latest contract defined by the protocol package.
18
- `MIN_HOST_SUPPORTED_BRIDGE_PROTOCOL_VERSION` defines the host runtime's minimum. The
19
- `minBridgeProtocolVersion` option defaults to that minimum and can restrict which SDKs an embedding
20
- application accepts. Changing this option cannot add support for a contract the host does not
21
- implement.
22
-
23
- The host also accepts the protocol 3–11 handshake, where `connect` declares a single
24
- `bridgeProtocolVersion`. Those connections retain eager initialization and their response formats.
25
- The current SDK requires protocol 12 and cannot connect to a host that supports only protocols 3–11.
26
-
27
- ## Connection requirements
28
-
29
- Create the host before navigating the iframe so it can receive `connect`. Each host and iframe
30
- handle one connection. Create a fresh pair to retry, change the block URL, or change viewers.
31
-
32
- A successful `connectResult` confirms the selected protocol. Setup completes when the sandbox
33
- accepts `init` and sends a successful `initResult`. The host then permits data operations while it
34
- waits for `ready`. The embedding application reveals the iframe when the host reports `ready`. See
35
- [Initialization and lifecycle](lifecycle.md) for payload delivery, callbacks, and timeouts.
36
-
37
- An SDK must implement every protocol version it advertises. If the SDK requires a contract the host
38
- does not implement, update the embedding application's host before adopting that SDK. Publishing a
39
- host package does not update applications that use it.
40
-
41
- The [protocol versioning reference](../../bridge/versioning.md) defines the rules for wire
42
- contract changes.
43
-
44
- ## Host normalization
45
-
46
- The host validates sandbox requests before dispatching them to handlers. Handlers use current data
47
- shapes, and the host converts responses to the sandbox's declared protocol. Setters, query
48
- refreshes, and handler responses use the same conversion. Messages that need no conversion pass
49
- through unchanged.
50
-
51
- ## Current compatibility behavior
52
-
53
- | Target | Query results | Page operation results | Binding schemas | Native icons |
54
- | ------ | --------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
55
- | 3–4 | Flat ID-keyed values, including synthetic metadata entries | ID-keyed properties with unsupported property objects omitted | Synthetic metadata read schemas restored in outgoing copies | External SVG URLs in page operations. Icons omitted from flat query results |
56
- | 5 | Same query values as protocols 3–4 | Same page format as protocols 3–4 | Actual database schemas. The SDK supplies synthetic read schemas locally | Same as protocols 3–4 |
57
- | 6 | Unified name-keyed properties. Text fallback property objects become `null` | Same unified page format | Actual database schemas | External SVG URLs |
58
- | 7–8 | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | External SVG URLs |
59
- | 9–12 | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | Native icon objects |
60
-
61
- The synthetic metadata IDs are `created_time`, `last_edited_time`, `created_by`, and
62
- `last_edited_by`. They retain metadata meaning if an actual property uses the same raw ID. This
63
- matches the protocol 3–4 binding schema precedence. Host validation always uses the unmodified
64
- actual database schema.
65
-
66
- Release-specific compatibility limits are documented in the changelog entries for
67
- [protocol 5 page context](../../bridge/changelog.md#protocol-5-unavailable-containing-page-context)
68
- and
69
- [protocol 6 text fallback properties](../../bridge/changelog.md#protocol-6-richer-fallback-properties).
70
-
71
- ### Native page icons
72
-
73
- Protocol 9 and later receive native icon objects. Protocols 3–8 receive external SVG URLs in page
74
- operation results, and protocols 6–8 also receive them in query results. Protocols 3–5 use flat
75
- query results without page appearance fields. Omitted native colors default to gray when producing
76
- SVG URLs.
77
-
78
- ### Unavailable containing-page context
79
-
80
- Protocols 3–4 receive `context_unavailable` during initialization or stop when containing-page
81
- context becomes unavailable. This concerns `init.page` and `pageChanged.page`, not a page
82
- operation's `page_unavailable` error.
83
-
84
- ### Protocol 3–5 metadata query semantics
85
-
86
- Page creation and edit metadata is readable without corresponding database columns. Current page
87
- objects carry these fields at the top level. Protocol 3–5 query adapters copy them into
88
- `propertiesById` for older SDKs.
89
-
90
- Filters and sorts require actual database properties in the bound schema. The host does not support
91
- queries against synthetic metadata IDs without corresponding database properties.
92
-
93
- ## Data source binding names
94
-
95
- Protocols 11–12 use `dataSourceSchema` and `dataSourcePointer`. Host adapters supply only these
96
- current names. The outgoing boundary restores `collectionSchema` and `collectionPointer` for
97
- protocols 3–10.
98
-
99
- Protocols 3–11 receive bindings in eager initialization and replacement bindings in
100
- `dataSourcesChanged`. Protocol 12 reads bindings through `getDataSource`. After a configuration
101
- change, `dataSourcesInvalidated` tells the SDK to reload metadata when an operation needs it.
102
-
103
- ## Initialization and location values
104
-
105
- | Contract | Protocols 3–11 | Protocol 12 |
106
- | ---------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
107
- | Initialization | Eager values include the current user, parent, containing page, and data source bindings | Setup contains `instance`, `manifest`, and `preferences`. Data access does not block setup |
108
- | Reveal | Successful `initResult` supplies the initial height and permits reveal | Successful `initResult` permits data operations. `ready` supplies the initial height and permits reveal |
109
- | Containing-page display mode | Omitted from eager init and `pageChanged` | Required on accessible containing-page descriptors. Defaults to `full_page` |
110
- | Location failures | Known initial failures fail eager initialization. `parentError` and `pageError` are not sent | `parentError` and `pageError` report known failures independently. Later value notifications clear the corresponding error |
111
- | Missing user names | Compatibility encoding omits missing names and preserves empty strings | Full user profiles contain `name: string \| null` |
112
-
113
- For protocols 3–11, a malformed `initResult` with the active `initializationId` fails setup with
114
- `invalid_init_result_payload`. See [host lifecycle](lifecycle.md#callbacks) for setup diagnostics.
115
-
116
- For protocols 3–11, the host converts `does_not_exist`, `permission_denied`, and `load_failed`
117
- handler errors to the operation's existing error codes. User lookup and listing use
118
- `get_user_failed` and `list_users_failed`. Page reads, creation, and updates use `get_page_failed`,
119
- `create_page_failed`, or `update_page_failed` for load failures, and `page_unavailable` for missing
120
- or inaccessible pages. Page opening uses `page_unavailable`. Protocol 12 preserves the shared
121
- resource error codes.
122
-
123
- Protocols 3–11 require a user viewer and a successful `handlers.getUser` result for eager
124
- initialization. On these protocols, anonymous setup fails with `current_user_unavailable` before
125
- profile loading. Protocol 12 anonymous setup succeeds. The `getViewer` request and `getViewerResult`
126
- response require a host with viewer-read support.
@@ -1,119 +0,0 @@
1
- # Host handlers and data
2
-
3
- Handlers connect block requests to your application's data access, persistence, and navigation. The
4
- runtime validates bridge messages and manages subscriptions. Your application enforces viewer
5
- permissions and implements the requested operations.
6
-
7
- The [dev shell](https://www.npmjs.com/package/@notionhq/custom-blocks-dev-shell) is a working host
8
- implementation with local sample data. Use it as a reference for a larger integration. Production
9
- hosts must provide their own permissions, data access, and persistence.
10
-
11
- ## Handler contracts
12
-
13
- Every `CustomBlockHostHandlers` method is required. Use `hostHandlerNotImplemented()` in explicit
14
- wrappers for the
15
- [operations that can report unsupported](host-contract.md#options-and-partial-implementations).
16
- Handlers that return results use promises. Errors carry `{ code, message, isRetryable }`, with open
17
- string codes.
18
-
19
- ### Return bridge data
20
-
21
- Handlers return data in the bridge's shared types. Use bridge builders to construct complete objects
22
- from application records.
23
-
24
- The host validates result shapes and matches responses to requests. Your application checks that
25
- records exist and that the viewer may perform the requested operation.
26
-
27
- The runtime validates query filters and sorts against the bound data source schema before
28
- `subscribeToQuery` runs. See the [wire reference](../../bridge/protocol.md#data-sources) for
29
- query semantics.
30
-
31
- For one-shot requests, a handler that throws, rejects, or returns a malformed result produces
32
- `unknown_error`. Exception details go to `onLog`. The sandbox receives a generic error. Specific
33
- errors returned by handlers pass through unchanged.
34
-
35
- Shared resource errors are `load_failed`, `permission_denied`, and `does_not_exist`. Return
36
- `does_not_exist` only when the underlying operation establishes absence and permits disclosing it.
37
- Missing local records do not establish absence. Preserve an unavailable result when the underlying
38
- operation does not distinguish missing resources from denied access. The embedding application makes
39
- that decision. The shared host forwards its result.
40
-
41
- ## Connect a data source
42
-
43
- To extend the [embed example](../README.md#create-a-host) with a data source, add its manifest
44
- declaration, bindings, metadata handler, and query handler. The block uses the same declaration and
45
- queries the source through the SDK's public APIs.
46
-
47
- Declare `tasks` and its property keys in the manifest. Supply their IDs in `bindings.dataSources`,
48
- and return the schema from `getDataSource({ dataSourceId, signal })`. Missing resources and denied
49
- access both return `{ status: "success", state: { status: "unavailable" } }`. Binding failures
50
- return an error. See [metadata and configuration](host-contract.md#metadata-and-configuration).
51
-
52
- `subscribeToQuery` receives the source ID, query options, limit, signal, and callbacks described in
53
- [queries and cancellation](host-contract.md#queries-and-cancellation). Enforce record access, apply
54
- the requested filters, sorts, and archive selection, and honor the limit before calling
55
- `onSnapshot({ items, hasMore })`. If you reduce the requested limit, include
56
- `limitClamp: { requested, applied }` in the snapshot. See
57
- [query limits](../../bridge/protocol.md#host-applied-query-limits) for the result contract.
58
- Result properties use display names as keys and include raw property IDs. The runtime validates
59
- results before sending them to the SDK.
60
-
61
- ## Refresh active queries
62
-
63
- The platform observer calls `onSnapshot` again when rows change. Release the observer and cancel
64
- pending setup when the subscription signal aborts. The shared host handles subscription IDs,
65
- replacement, unsubscribe, and shutdown. Do not return a second cleanup callback.
66
-
67
- Use `host.refreshDataSource({ dataSourceId })` when source metadata or access changes. The refresh
68
- invalidates metadata and cancels queries for every source, not just `dataSourceId`. It does not
69
- fetch replacement metadata. See [Updates](host-contract.md#updates) for the contract. Ordinary row
70
- changes flow through the active observer and need no metadata refresh.
71
-
72
- ## Page and user operations
73
-
74
- `createPage`, `getPage`, and `updatePage` connect page requests to your application's data access
75
- and persistence. `getUser` and `listUsers` supply user data. Each handler returns a success payload
76
- or an error. The runtime adds the request's correlation ID and sends the response. The application
77
- enforces record access before reading or writing data.
78
-
79
- For `createPage` and `updatePage`, return success after your application confirms the save. A local
80
- cache update or queued transaction does not establish that a remote save succeeded. Capture the
81
- requested mutation's response state before waiting, so later edits do not enter its result.
82
-
83
- If a save fails or confirmation exceeds your application's deadline, return `create_page_failed` or
84
- `update_page_failed`. A timeout does not cancel the queued write. Set `isRetryable: false` when
85
- repeating the operation could duplicate a create or race a write that is still pending. Keep any
86
- private server rejection details in internal application logs; return a safe message to the block.
87
-
88
- `openPage` handles navigation to a Notion page. `resize` receives the block's requested height in
89
- CSS pixels. The application owns navigation and iframe sizing.
90
-
91
- ## External navigation
92
-
93
- `openExternalUrl` receives an `AbortSignal` and an absolute HTTP or HTTPS URL without credentials.
94
- The URL is limited to 2,048 JavaScript code units before and after normalization. The host
95
- implementation displays the exact URL, obtains approval, and navigates only after approval. It may
96
- apply further restrictions. Dismiss pending confirmation UI when the signal aborts.
97
-
98
- Each iframe permits one pending navigation. A different request receives `pending_navigation`. A
99
- duplicate of the active request is ignored. Completed requests are forgotten, so later requests
100
- require fresh approval. The runtime redacts the URL from `onLog` payloads and suppresses results
101
- after stop.
102
-
103
- ## Property binding
104
-
105
- `getAutoBoundPropertyIdsByKey({ manifestProperties, propertySchemasById })` requires matching
106
- property types and either an exact raw ID match or a display-name match after trimming and
107
- lowercasing. IDs are not trimmed or case-folded. Exactly one candidate creates a binding. Zero or
108
- multiple candidates leave the property unmapped. The result maps manifest property keys to database
109
- property IDs. An ID match has no priority over a name match: if they identify different compatible
110
- properties, the manifest property stays unmapped.
111
-
112
- ## Date conversion and types
113
-
114
- `toNotionDateValue()` converts `NotionDateInput` into the four `CustomBlockDateValue` variants,
115
- including reminders. Invalid input throws `InvalidNotionDateError`.
116
-
117
- The root exports host configuration, handlers, results, and domain argument types. Wire schemas,
118
- message and page types, and shared constants use the
119
- [protocol subpath](../README.md#protocol-schemas-and-types).
@@ -1,203 +0,0 @@
1
- # Host contract
2
-
3
- `createCustomBlockHost(options: CustomBlockHostOptions)` returns a running `CustomBlockHost`.
4
- `CustomBlockHostHandlers` connects that instance to application data and actions. See
5
- [Connection compatibility](compatibility.md) for protocol negotiation and version requirements.
6
-
7
- Your application supplies authorized data and actions. The shared host owns initialization, message
8
- validation, protocol compatibility, subscriptions, cancellation, and shutdown. Each host instance
9
- belongs to one viewer. Stop the host and create a fresh host and iframe to change viewers.
10
-
11
- ## Options and partial implementations
12
-
13
- Required options are `instance`, `getViewer`, `theme`, `contrastMode`, `containingPage`, `parent`,
14
- `iframe`, `sandboxUrl`, `manifestSource`, `getPersistedManifest`, `onStatusChange`, `bindings`, and
15
- `handlers`. `instance` and viewer identity stay fixed for the connection. Optional settings for this
16
- contract are `onLog`, `minBridgeProtocolVersion`, `noConnectTimeoutMs`, `initialStateTimeoutMs`,
17
- `noInitResultTimeoutMs`, and `noReadyTimeoutMs`.
18
-
19
- `theme`, `contrastMode`, `containingPage`, and `parent` accept `null` while unresolved. Supply
20
- resolved values through `setTheme()`, `setContrastMode()`, `setContainingPage()`, and `setParent()`.
21
- The host retains the latest values. Setup waits for theme and contrast mode, but not parent or
22
- containing page values. Your application observes changes and calls the setters. Creating the host
23
- does not subscribe to application state. See
24
- [Manifest and initial state](lifecycle.md#manifest-and-initial-state) for loading and delivery.
25
-
26
- For an accessible containing page, supply `displayMode`: `"full_page"`, `"side_peek"`, or
27
- `"center_peek"`. Call `setContainingPage()` when the mode changes, even if the page ID is unchanged.
28
- Use `full_page` outside peek presentation. It is also the default when the field is omitted.
29
- Unavailable pages carry no display metadata.
30
-
31
- Supply known initial failures through `parentError` and `containingPageError`, or report later
32
- failures with `setParentError(error)` and `setContainingPageError(error)`. Errors carry `code`,
33
- `message`, and `isRetryable`. Setup still succeeds. A later value setter clears the error. Use
34
- unavailable values for resources the host cannot expose. Use errors when loading failed.
35
-
36
- Every handler is required. `hostHandlerNotImplemented` accepts `getPage`, `createPage`,
37
- `updatePage`, `getUser`, `listUsers`, `openPage`, `openExternalUrl`, and `subscribeToQuery`.
38
- Failures from these operations leave initialization and unrelated operations available. The SDK
39
- requests the current user profile and source metadata independently after setup acknowledgment.
40
-
41
- A partial integration supplies an explicit wrapper using `hostHandlerNotImplemented`, which creates
42
- a non-retryable `host_handler_not_implemented` error:
43
-
44
- ```ts
45
- import {
46
- createCustomBlockHost,
47
- hostHandlerNotImplemented,
48
- type CustomBlockHostOptions,
49
- } from "@notionhq/custom-blocks-host"
50
-
51
- declare const options: CustomBlockHostOptions
52
-
53
- options.handlers.getPage = async () => ({
54
- status: "error",
55
- error: hostHandlerNotImplemented("getPage"),
56
- })
57
-
58
- options.handlers.subscribeToQuery = ({ onError }) => {
59
- onError(hostHandlerNotImplemented("subscribeToQuery"))
60
- }
61
-
62
- const host = createCustomBlockHost(options)
63
- host.stop()
64
- ```
65
-
66
- `resize` returns no result and sends no result message. Its handler can do nothing if the embed has
67
- a fixed size. The application enforces authorization and obtains any required approval. Neither
68
- manifest declarations nor bindings establish access.
69
-
70
- Full user profiles require `name: string | null` and `avatar_url: string | null`. Use `null` when a
71
- name is unavailable. Empty strings remain empty strings. The `makeBridgeUser` builder accepts an
72
- omitted name and supplies `null` before validating the full profile. ID-only user references do not
73
- promise profile fields.
74
-
75
- ## Handler inputs and results
76
-
77
- `CustomBlockHostHandlerResult<Payload>` combines `{ status: "success" }` with named payload fields,
78
- or returns `{ status: "error", error: { code, message, isRetryable } }`. For example, `getUser`
79
- returns `{ status: "success", user }` and `listUsers` returns `{ status: "success", list }`.
80
- `getPersistedManifest` returns `{ status: "success", manifest }`. Actions without payloads return
81
- `{ status: "success" }`. The shared host validates results and logs unexpected exceptions before
82
- returning a generic error to the sandbox.
83
-
84
- Asynchronous providers receive `CustomBlockHostRequestContext` with an `AbortSignal`. Inputs omit
85
- sandbox message types and correlation IDs. Named domain arguments such as
86
- `CustomBlockHostCreatePageArgs`, `CustomBlockHostUpdatePageArgs`, and `CustomBlockHostOpenPageArgs`
87
- contain only operation data. Handlers receive those arguments combined with
88
- `CustomBlockHostRequestContext`, which supplies `signal`. Page operations include insertion rules,
89
- properties, and appearance. Source and page operations use raw IDs. The SDK resolves data source
90
- keys before sending requests.
91
-
92
- | Handler | Additional input | Success payload |
93
- | ----------------- | ---------------------------------- | --------------------------------------- |
94
- | `getDataSource` | `dataSourceId` | `state: CustomBlockHostDataSourceState` |
95
- | `getPage` | `pageId`, optional `dataSourceId` | `page: BridgePage` |
96
- | `createPage` | Existing creation payload | `page: BridgePage` |
97
- | `updatePage` | Existing update payload | `page: BridgePage` |
98
- | `getUser` | `userId` | `user: BridgeUser` |
99
- | `listUsers` | Optional `pageSize`, `startCursor` | `list: BridgeUserList` |
100
- | `openPage` | `pageId`, `mode` | None |
101
- | `openExternalUrl` | `url` | None |
102
-
103
- `openPage` completes the requested action without echoing its input. The shared host includes the
104
- requested page ID in the wire response.
105
-
106
- Handlers that return results use promises. `CustomBlockHostHandler<Args, Payload>` combines domain
107
- arguments with `CustomBlockHostRequestContext` and the shared result type. `subscribeToQuery` and
108
- `resize` remain synchronous.
109
-
110
- ## Current viewer
111
-
112
- `getViewer()` runs synchronously once during host creation and returns `CustomBlockHostViewer`:
113
-
114
- ```ts
115
- type CustomBlockHostViewer = { type: "user"; userId: string } | { type: "anonymous" }
116
- ```
117
-
118
- The callback returns a known identity. The host validates and retains it. Login, logout, and account
119
- switching require a new host and iframe. The `getViewer` bridge request returns the captured
120
- identity without loading a profile. Anonymous setup succeeds. The embedding application authorizes
121
- rendering and each data operation.
122
-
123
- `handlers.getUser({ userId, signal })` supplies profiles for user reads and eager initialization.
124
- Current-user reads use the captured viewer ID and verify that the returned profile matches it.
125
- Anonymous current-user reads return non-retryable `current_user_unavailable` without calling the
126
- handler. Handler errors are forwarded. A rejected promise, mismatched ID, or malformed profile
127
- produces `unknown_error`, with details in the host log. The host does not cache profiles.
128
-
129
- ## Metadata and configuration
130
-
131
- `customBlockHostBindingsSchema` and `customBlockHostDataSourceStateSchema` are host-only Valibot
132
- schemas exported with their types. They describe application configuration and source metadata
133
- separately from wire payloads.
134
-
135
- ```ts
136
- type CustomBlockHostBindings = {
137
- pages: Record<string, { pageId: string }>
138
- dataSources: Record<
139
- string,
140
- {
141
- dataSourceId: string
142
- propertyIdsByKey: Record<string, string | undefined>
143
- }
144
- >
145
- }
146
- ```
147
-
148
- The host validates configuration shape. `pages` maps page keys to IDs, but the runtime does not use
149
- those mappings to resolve page requests or include them in `init`. A `getDataSource` request reads
150
- metadata for one source key declared in the manifest and configured in `dataSources`. The host
151
- validates its property mappings before returning the binding. Metadata reads do not query rows.
152
-
153
- `CustomBlockHostDataSourceState` is `{ status: "unavailable" }` or
154
- `{ status: "available", dataSource: { dataSourceSchema, capabilities } }`. Capabilities contain
155
- `read`, `create`, `update`, and `archive`. The runtime does not send these flags to the sandbox. An
156
- available source's metadata remains available even when `capabilities.read` is false. The
157
- application handler remains responsible for enforcing viewer permissions on every operation.
158
-
159
- Missing sources and denied access both use `{ status: "unavailable" }`. A `getDataSource` request
160
- for an unavailable source returns `data_source_inaccessible` without source metadata. Invalid
161
- property mappings return a binding error.
162
-
163
- ## Queries and cancellation
164
-
165
- `subscribeToQuery(args: CustomBlockHostSubscribeToQueryArgs): void` receives `dataSourceId`,
166
- optional `filter`, `sorts`, and `archive_status`, plus `limit`, `signal`, `onSnapshot`, and
167
- `onError`. `archive_status` accepts `"active"`, `"archived"`, or `"all"`. See the
168
- [query semantics](../../bridge/protocol.md#data-sources) for archive selection defaults. A
169
- `CustomBlockHostQuerySnapshot` contains `items: BridgePage[]`, `hasMore`, and optional `limitClamp`.
170
- The application validates the limit and enforces its cap. The shared host validates filters and
171
- sorts against the bound schema before starting the observer. See
172
- [query limits](../../bridge/protocol.md#host-applied-query-limits) for the metadata contract.
173
-
174
- The signal controls the subscription lifetime, including asynchronous setup. The application checks
175
- for an already-aborted signal and cancels pending setup and observers on abort. Replacement,
176
- unsubscribe, invalidation, non-retryable errors, and shutdown abort the signal. Retryable errors can
177
- leave the observer active. Callbacks may run synchronously. The host ignores late callbacks after
178
- cancellation. There is no returned cleanup function or top-level query-unsubscribed callback. The
179
- SDK returns its own unsubscribe function, which sends the cancellation request to the host.
180
-
181
- `resize({ height })` requests an iframe height in CSS pixels. The application applies the height.
182
- The [lifecycle reference](lifecycle.md#callbacks) describes when to size and reveal the iframe.
183
-
184
- ## Updates
185
-
186
- `stop()`, `setTheme()`, `setContrastMode()`, `setParent()`, and `setContainingPage()` return `void`.
187
- `setBindings()` and `refreshDataSource()` return promises of `CustomBlockHostHandlerResult`.
188
-
189
- `setBindings(nextBindings)` validates and stores the configuration without reading metadata.
190
- `refreshDataSource({ dataSourceId })` requests a metadata refresh. Once the manifest is available,
191
- both methods clear all cached source metadata, abort pending operations and queries, and notify the
192
- sandbox with `dataSourcesInvalidated`. Neither method fetches replacement metadata. The next source
193
- read validates its property mappings.
194
-
195
- Invalidation affects every source, including unchanged bindings and sources other than the supplied
196
- `dataSourceId`. Before the manifest is available, both methods return success without invalidation.
197
- Malformed `setBindings()` input rejects with a schema validation error.
198
-
199
- A successful configuration change cancels outstanding one-shot host operations, including unrelated
200
- reads. A late completion returns non-retryable `host_state_changed`. A dispatched write may already
201
- have committed. Cancellation does not roll back a write. Stopping or failing the host aborts
202
- initialization, pending operations, metadata refreshes, and subscriptions before reporting its final
203
- status.