@notionhq/custom-blocks 0.3.2 → 0.3.4

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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -19
  3. package/dist/bridge/SandboxBridge.d.ts +0 -2
  4. package/dist/bridge/SandboxBridge.d.ts.map +1 -1
  5. package/dist/bridge/SandboxBridge.js +16 -39
  6. package/dist/bridge/SandboxInitialization.d.ts +1 -3
  7. package/dist/bridge/SandboxInitialization.d.ts.map +1 -1
  8. package/dist/bridge/SandboxInitialization.js +13 -15
  9. package/dist/bridge/appearance.d.ts +2 -10
  10. package/dist/bridge/appearance.d.ts.map +1 -1
  11. package/dist/bridge/appearance.js +2 -10
  12. package/dist/bridge/dataSources/query.d.ts +1 -2
  13. package/dist/bridge/dataSources/query.d.ts.map +1 -1
  14. package/dist/bridge/dataSources/query.js +15 -398
  15. package/dist/bridge/dataSources/queryFilter.d.ts +10 -0
  16. package/dist/bridge/dataSources/queryFilter.d.ts.map +1 -0
  17. package/dist/bridge/dataSources/queryFilter.js +123 -0
  18. package/dist/bridge/dataSources/resolveProperty.d.ts +1 -20
  19. package/dist/bridge/dataSources/resolveProperty.d.ts.map +1 -1
  20. package/dist/bridge/dataSources/resolveProperty.js +37 -32
  21. package/dist/bridge/dataSources/resolvePropertyAddress.d.ts +10 -0
  22. package/dist/bridge/dataSources/resolvePropertyAddress.d.ts.map +1 -0
  23. package/dist/bridge/dataSources/resolvePropertyAddress.js +55 -0
  24. package/dist/bridge/dataSources/resolveSorts.d.ts +10 -0
  25. package/dist/bridge/dataSources/resolveSorts.d.ts.map +1 -0
  26. package/dist/bridge/dataSources/resolveSorts.js +80 -0
  27. package/dist/bridge/hostState.d.ts +3 -7
  28. package/dist/bridge/hostState.d.ts.map +1 -1
  29. package/dist/bridge/hostState.js +0 -24
  30. package/dist/bridge/page.d.ts +9 -3
  31. package/dist/bridge/page.d.ts.map +1 -1
  32. package/dist/bridge/page.js +19 -2
  33. package/dist/bridge/readLocalManifest.d.ts +23 -0
  34. package/dist/bridge/readLocalManifest.d.ts.map +1 -0
  35. package/dist/bridge/readLocalManifest.js +46 -0
  36. package/dist/bridge/sandboxClient.d.ts +0 -2
  37. package/dist/bridge/sandboxClient.d.ts.map +1 -1
  38. package/dist/bridge/sandboxClient.js +50 -24
  39. package/dist/protocol/dataSources/dataSourcePage.d.ts +3 -4
  40. package/dist/protocol/dataSources/dataSourcePage.js +2 -3
  41. package/dist/protocol/index.d.ts +1 -0
  42. package/dist/protocol/index.js +1 -0
  43. package/dist/protocol/isLocalBlockServerUrl.d.ts +2 -0
  44. package/dist/protocol/isLocalBlockServerUrl.js +9 -0
  45. package/dist/protocol/messages/connect.d.ts +2 -2
  46. package/dist/protocol/messages/connect.js +2 -2
  47. package/dist/protocol/messages/createPage.d.ts +1 -1
  48. package/dist/protocol/messages/createPage.js +1 -1
  49. package/dist/protocol/messages/createPageResult.d.ts +3 -3
  50. package/dist/protocol/messages/createPageResult.js +4 -4
  51. package/dist/protocol/messages/getPage.d.ts +2 -2
  52. package/dist/protocol/messages/getPage.js +4 -4
  53. package/dist/protocol/messages/hostToSandbox.d.ts +3 -3
  54. package/dist/protocol/messages/hostToSandbox.js +10 -10
  55. package/dist/protocol/messages/init.d.ts +1 -1
  56. package/dist/protocol/messages/queryDataSource.d.ts +24 -0
  57. package/dist/protocol/messages/queryDataSource.js +2 -0
  58. package/dist/protocol/messages/queryDataSourceResult.d.ts +3 -3
  59. package/dist/protocol/messages/queryDataSourceResult.js +5 -5
  60. package/dist/protocol/messages/sandboxToHost.d.ts +8 -0
  61. package/dist/protocol/messages/updatePageResult.d.ts +3 -3
  62. package/dist/protocol/messages/updatePageResult.js +4 -4
  63. package/dist/protocol/pages/page.d.ts +4 -4
  64. package/dist/protocol/pages/page.js +2 -2
  65. package/dist/protocol/parent.d.ts +1 -1
  66. package/dist/protocol/protocolVersion.d.ts +3 -2
  67. package/dist/protocol/protocolVersion.js +4 -2
  68. package/dist/react/useDataSource.d.ts +2 -2
  69. package/dist/react/useDataSource.js +2 -2
  70. package/dist/types.d.ts +5 -5
  71. package/dist/types.d.ts.map +1 -1
  72. package/dist/version.js +1 -1
  73. package/docs/block-location.md +6 -4
  74. package/docs/bridge-interceptors.md +4 -0
  75. package/docs/build-tools.md +58 -0
  76. package/docs/data-sources.md +24 -18
  77. package/docs/deployment.md +23 -36
  78. package/docs/errors.md +75 -52
  79. package/docs/lifecycle.md +10 -3
  80. package/docs/pages.md +84 -76
  81. package/docs/users.md +4 -4
  82. package/package.json +4 -19
  83. package/src/bridge/SandboxBridge.ts +18 -48
  84. package/src/bridge/SandboxInitialization.ts +14 -20
  85. package/src/bridge/appearance.ts +2 -10
  86. package/src/bridge/dataSources/query.ts +17 -530
  87. package/src/bridge/dataSources/queryFilter.ts +181 -0
  88. package/src/bridge/dataSources/resolveProperty.ts +48 -39
  89. package/src/bridge/dataSources/resolvePropertyAddress.ts +62 -0
  90. package/src/bridge/dataSources/resolveSorts.ts +107 -0
  91. package/src/bridge/hostState.ts +3 -43
  92. package/src/bridge/page.ts +28 -4
  93. package/src/bridge/readLocalManifest.ts +60 -0
  94. package/src/bridge/sandboxClient.ts +63 -38
  95. package/src/react/useDataSource.ts +2 -2
  96. package/src/types.ts +5 -5
  97. package/dist/bridge/loadManifest.d.ts +0 -21
  98. package/dist/bridge/loadManifest.d.ts.map +0 -1
  99. package/dist/bridge/loadManifest.js +0 -85
  100. package/src/bridge/loadManifest.ts +0 -114
package/docs/pages.md CHANGED
@@ -1,8 +1,12 @@
1
- # Pages and unified page objects
1
+ # Pages
2
2
 
3
- `pages.get` and `pages.create` return `{ status: "success", page: NotionPage }` on success. Failures
4
- return `{ status: "error", error }`. Data source methods use the same status envelopes and page
5
- type.
3
+ The `pages` API reads, creates, updates, and opens Notion pages from a custom block. This guide
4
+ covers page results, property access, mutations, and navigation. Data source operations return the
5
+ same page objects, so these property methods also apply to query rows.
6
+
7
+ `pages.get` and `pages.create` return `{ status: "success", page }` or `{ status: "error", error }`.
8
+ Both the Pages and Data sources namespaces return the same `NotionPage` type, with methods to read
9
+ and update properties.
6
10
 
7
11
  ```ts
8
12
  import { pages, dataSources } from "@notionhq/custom-blocks"
@@ -14,23 +18,22 @@ if (result.status === "success") {
14
18
  }
15
19
  ```
16
20
 
17
- `NotionPageData` contains serializable page fields. The SDK constructs `NotionPage` by adding
18
- property getters and mutation methods. These methods send bridge messages and are never serialized.
19
- Both namespaces use this same page type.
21
+ `BridgePage` contains the serializable page fields. `NotionPage` adds methods, which are not
22
+ serialized. Reads use loaded values. Writes send bridge messages to Notion.
20
23
 
21
24
  ## Page fields
22
25
 
23
- `properties` maps property display names to typed values or `null`. Each typed value retains its raw
24
- property ID. `getPropertyById` scans loaded values and returns the matching value or `null`. Neither
25
- getter fetches data.
26
+ `properties` maps property display names to typed values or `null`. Each typed value includes its
27
+ raw property ID. `getPropertyById` returns the loaded value with that ID, or `null`. Neither
28
+ property getter fetches data.
26
29
 
27
- All pages contain `created_time`, `last_edited_time`, `created_by`, `last_edited_by`, and
28
- `last_visited_time`. Unavailable metadata uses `null`. These fields are separate from schema
30
+ Every page has `created_time`, `last_edited_time`, `created_by`, `last_edited_by`, and
31
+ `last_visited_time` fields. Unavailable values are `null`. These fields are separate from database
29
32
  properties.
30
33
 
31
- Parent, icon, cover, URLs, timestamps, and archive states remain page metadata. Absent icons,
32
- covers, URLs, and timestamps use explicit `null` values. `is_archived` and `in_trash` include
33
- inherited state. The SDK does not support trash mutations.
34
+ Parent, icon, cover, URLs, timestamps, and archive state are page metadata. Missing icons, covers,
35
+ URLs, and timestamps are `null`. `is_archived` and `in_trash` include inherited state. The SDK
36
+ cannot move pages to or from the trash.
34
37
 
35
38
  ## Data source context
36
39
 
@@ -43,21 +46,29 @@ if (result.status === "success") {
43
46
  }
44
47
  ```
45
48
 
46
- `dataSourceKey` identifies the retained manifest data source context. It is `null` for pages
47
- returned by the Pages namespace. `getPropertyByKey` returns `null` without context or for invalid,
48
- unbound, or missing properties. The shared `propertyIdsByKey` map converts manifest keys to raw
49
- property IDs. Unbound keys map to `undefined`. Pages contain no binding maps.
49
+ Pages returned by Data sources methods retain their manifest key in `dataSourceKey`. Pages returned
50
+ by the Pages namespace have `dataSourceKey: null`.
51
+
52
+ `getPropertyByKey` uses the retained data source binding to resolve a manifest property key. It
53
+ returns `null` if the page has no context, the key is invalid or unbound, or the property is
54
+ missing. The result's `propertyIdsByKey` map exposes these bindings, with `undefined` for unbound
55
+ keys. The page itself has no binding map.
50
56
 
51
57
  ## Create pages
52
58
 
53
- `pages.create` retains `CreatePageArgs` and all `CreatePageParent` variants:
59
+ `pages.create` accepts `CreatePageArgs` with one of three `CreatePageParent` variants:
54
60
 
55
61
  - `{ type: "page_id", page_id }` creates a child page.
56
62
  - `{ type: "data_source_id", data_source_id }` creates a data source row.
57
63
  - `{ type: "data_source_key", key }` creates a row using a manifest binding.
58
64
 
59
- Only page parents accept `NotionCreatePagePosition`. Its variants are `start`, `end`, `before`, and
60
- `after`. Before and after positions require a `blockId`.
65
+ Only a `page_id` parent accepts `NotionCreatePagePosition`: `start`, `end`, `before`, or `after`.
66
+ The `before` and `after` positions require a `blockId`.
67
+
68
+ A `page_id` or `data_source_id` parent uses raw property IDs. A `data_source_key` parent uses
69
+ manifest property keys bound to properties in the loaded database schema.
70
+
71
+ In this example, `tasks` has a `title` manifest key bound to the database's title property:
61
72
 
62
73
  ```ts
63
74
  const page = await pages.create({
@@ -71,28 +82,32 @@ const row = await pages.create({
71
82
  })
72
83
  ```
73
84
 
74
- Create payloads retain existing property formats and semantic key resolution. Create does not accept
75
- icons or covers.
85
+ If a property value includes `id`, it must match the target's raw property ID. Unknown or unbound
86
+ manifest keys return `unmapped_property`. Creation does not accept icons or covers.
76
87
 
77
88
  ## Mutate pages
78
89
 
79
- `PageUpdatePayload` accepts properties, icon, cover, and `is_archived`. Each method retains the page
80
- ID and data source context. Mutation methods return `UpdatePageResult` with the updated page or a
81
- structured error. Successful writes refresh the same page object.
90
+ Page methods use the page's ID and retained data source context. `PageUpdatePayload` accepts
91
+ `properties`, `icon`, `cover`, and `is_archived`.
82
92
 
83
93
  - `page.updateById` interprets property keys as raw property IDs.
84
94
  - `page.updateByKey` interprets property keys as manifest keys.
85
95
  - `page.archive()` sets `is_archived` to `true`.
86
96
  - `page.unarchive()` sets `is_archived` to `false`.
87
97
 
88
- ID writes accept `NotionPagePropertyInputMap` and fill omitted value IDs. Mismatched value IDs and
89
- duplicate properties fail before sending a request. Keyed writes require valid bindings and loaded
90
- properties. The SDK validates every key before sending any write. A missing context, invalid key,
91
- unbound key, or missing property produces a local error. An empty update also produces a local
92
- error.
98
+ Both update methods accept `NotionPagePropertyInputMap`. The SDK fills in omitted value IDs. If a
99
+ value includes `id`, it must match the target's raw property ID, even in a key-based update.
93
100
 
94
- Icons use `NotionPageIcon` and covers use `NotionPageCover`. Use emoji, external URLs, or existing
95
- hosted file URLs. File upload references remain unsupported.
101
+ Property writes through `updateByKey` require a page returned by a Data sources method and keys
102
+ bound to properties in the loaded database schema. Updates to only `icon`, `cover`, or `is_archived`
103
+ do not require data source context.
104
+
105
+ The SDK validates all properties before sending an update. Invalid values, mismatched IDs, duplicate
106
+ targets, and unresolved keys return local errors. An update must include at least one property or
107
+ metadata change. See [Local page update errors](errors.md#local-page-update-errors).
108
+
109
+ Icons use `NotionPageIcon` and covers use `NotionPageCover`. Supported values include emoji,
110
+ external URLs, and existing hosted file URLs. File upload references are unsupported.
96
111
 
97
112
  ## Types
98
113
 
@@ -108,20 +123,20 @@ hosted file URLs. File upload references remain unsupported.
108
123
 
109
124
  ## Property support
110
125
 
111
- This table shows property support for custom blocks running in Notion.
126
+ The table below shows property support in Notion:
112
127
 
113
- - **Read value** shows `page.properties` after reads, creates, and successful instance writes.
114
- Unsupported properties return `null`.
128
+ - **Read value** shows `page.properties` after a read, create, or successful update. Unsupported
129
+ properties return `null`.
115
130
  - **Create** covers property writes through `pages.create`.
116
131
  - **Update** covers property writes through `page.updateById`.
117
132
 
118
- Pages outside a data source support only `title`. Other property writes require a data source row
119
- and a property in its schema.
133
+ Pages outside a data source support only `title`. Other properties require a data source row and a
134
+ matching property in its schema.
120
135
 
121
136
  - 🟢 **Supported:** The SDK supports this operation in Notion.
122
- - 🟡 **Limited:** The SDK supports this operation with the restrictions shown in the cell.
137
+ - 🟡 **Limited:** The SDK supports this operation with the listed restrictions.
123
138
  - 🔴 **Unavailable:** The SDK does not expose this operation.
124
- - ⚫ **Not supported in Notion:** Notion itself does not support this operation in the stated case.
139
+ - ⚫ **Not supported in Notion:** Notion does not support this operation in the stated case.
125
140
 
126
141
  | Property type | Read value (`pages.get`) | Create (`pages.create`) | Update (`page.updateById`) |
127
142
  | ------------------- | ---------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |
@@ -154,30 +169,26 @@ and a property in its schema.
154
169
 
155
170
  ### Notes
156
171
 
157
- - Select, multi-select, and status reads return option names and colors when available. They also
158
- return IDs when the options match the schema. Writes accept an existing option ID or a name and
159
- set the selected value. They do not edit option definitions. If you supply both an ID and a name,
160
- the host uses the ID. The host rejects unknown IDs.
172
+ - Select, multi-select, and status reads return available option names and colors, plus IDs for
173
+ options that match the schema. Writes select options by ID or name without editing their
174
+ definitions. If you supply both, the host uses the ID. Unknown IDs fail.
161
175
  - Date-time writes preserve hours and minutes but discard seconds and milliseconds.
162
- - Title and rich text use text arrays, but reads and writes preserve only plain text. Reads and
163
- writes do not preserve formatting, links, mentions, or equations as structured rich text.
164
- - `pages.get` resolves Files links and readable file/image/pdf/audio/video references that have a
165
- source. Create/update responses include link items only. File writes accept `external` URLs and
166
- existing `file` URLs and store them as links. Upload references (`file_upload`) are unsupported.
176
+ - Title and rich text use text arrays that preserve only plain text. Formatting, links, mentions,
177
+ and equations are not preserved as structured rich text.
178
+ - `pages.get` resolves Files links and readable file, image, PDF, audio, and video references with a
179
+ source. Create and update responses include only links. File writes store `external` URLs and
180
+ existing `file` URLs as links. Upload references (`file_upload`) are unsupported.
167
181
  - Relation writes replace the value and reject `has_more: true`.
168
- - Top-level `created_time` and `last_edited_time` remain available independently of schema
169
- properties.
170
- - Formula, rollup, unique ID, button, verification, and location reads retain their type with a
171
- string value.
172
- - These strings contain stored text only. Formulas and rollups are not evaluated. Missing values
173
- return `""`.
182
+ - Top-level `created_time` and `last_edited_time` do not depend on the database schema.
183
+ - Formula, rollup, unique ID, button, verification, and location reads keep their type but return
184
+ stored text as a string. Formulas and rollups are not evaluated. Missing values return `""`.
174
185
 
175
186
  For query properties, filters, and sorts, see
176
- [Data source property support](./data-sources.md#property-support).
187
+ [Data source property support](data-sources.md#property-support).
177
188
 
178
189
  ## Opening pages
179
190
 
180
- `pages.open(pageId, { mode })` asks Notion to open a readable page using host-owned navigation:
191
+ `pages.open(pageId, { mode })` asks Notion to open a page the viewer can read:
181
192
 
182
193
  ```ts
183
194
  const result = await pages.open(pageId, { mode: "side_peek" })
@@ -187,31 +198,31 @@ if (result.status === "error") {
187
198
  }
188
199
  ```
189
200
 
190
- When the block is inside a peek, opening another page in that peek replaces it and unmounts the
191
- block, losing its local state. The request result may not be observable after the block unmounts.
201
+ If the block is inside a peek, opening another page in that peek unmounts the block and loses its
202
+ local state. The block may unmount before it receives the request result.
192
203
 
193
- Modes are `"side_peek"` and `"center_peek"`. Success means the host handed the request to Notion
194
- navigation; it does not wait for route-leave confirmation or for the page to finish loading. A
195
- surface that cannot host the requested peek may fall back to full-page navigation. The success
196
- result contains `{ pageId }` only — call `pages.get(pageId)` separately when you need readable page
204
+ Modes are `"side_peek"` and `"center_peek"`. Success means the host passed the request to Notion's
205
+ navigation system. The method does not wait for confirmation to leave the current page or for the
206
+ new page to load. If the current surface cannot show the requested peek, Notion may open a full page
207
+ instead. The success result contains only `{ pageId }`. Use `pages.get(pageId)` to read the page's
197
208
  metadata.
198
209
 
199
210
  ### Files reads
200
211
 
201
- Each Files entry is either an external link (`type: "external"`) or a Notion-hosted file
212
+ Each Files entry is either an external link (`type: "external"`) or a file hosted by Notion
202
213
  (`type: "file"`), in the order shown in Notion. A hosted file's `file.url` is a signed URL that
203
214
  expires at `file.expiry_time`. Call `pages.get` again when you need a fresh URL. `expiry_time` can
204
215
  be missing on older hosts.
205
216
 
206
- An empty Files value returns `[]`. If the host can't resolve an entry (for example, you can't read
207
- the referenced file, or it points to a folder), `pages.get` fails with an error instead of returning
208
- a partial list.
217
+ An empty Files value returns `[]`. If the host cannot resolve an entry, `pages.get` fails instead of
218
+ returning a partial list. For example, an entry may point to a folder or a file the viewer cannot
219
+ read.
209
220
 
210
221
  ## Mutation results
211
222
 
212
- Page instance methods return `UpdatePageResult`: the updated page or a structured error. Successful
213
- methods refresh the same page object before resolving. Use `updateById` for raw property IDs and
214
- `updateByKey` for manifest keys.
223
+ Update and archive methods return `UpdatePageResult`: `{ status: "success", page }` or
224
+ `{ status: "error", error }`. A successful update refreshes the same page object before the promise
225
+ resolves. Separately fetched pages remain independent objects.
215
226
 
216
227
  ## Namespace methods
217
228
 
@@ -224,8 +235,8 @@ methods refresh the same page object before resolving. Use `updateById` for raw
224
235
  | `dataSources.getPage(key, pageId)` | `{ status: "success", page, propertyIdsByKey }` |
225
236
  | `dataSources.create(key, payload)` | `{ status: "success", page, propertyIdsByKey }` |
226
237
 
227
- The Pages namespace exposes `get`, `create`, and `open`. Use page instance methods for all writes
228
- and archive changes.
238
+ The Pages namespace exposes `get`, `create`, and `open`. Use page methods to update properties or
239
+ metadata and to archive or unarchive a page:
229
240
 
230
241
  ```ts
231
242
  const fetched = await pages.get(pageId)
@@ -238,6 +249,3 @@ if (fetched.status === "success") {
238
249
  if (result.status === "success") console.log(page.properties.Score)
239
250
  }
240
251
  ```
241
-
242
- The successful write refreshes this page before the promise resolves. Separately fetched pages
243
- remain independent objects.
package/docs/users.md CHANGED
@@ -7,7 +7,7 @@ import { customBlock, initCustomBlock, users, type NotionUserId } from "@notionh
7
7
  import { useCurrentUser } from "@notionhq/custom-blocks/react"
8
8
  ```
9
9
 
10
- `users.get()` and `users.list()` follow the SDK's [error-handling contract](./errors.md). Check
10
+ `users.get()` and `users.list()` follow the SDK's [error-handling contract](errors.md). Check
11
11
  `result.status` before reading `result.user` or `result.list`.
12
12
 
13
13
  ## Reading the current user
@@ -16,7 +16,7 @@ import { useCurrentUser } from "@notionhq/custom-blocks/react"
16
16
  read the user from the block’s state without a separate request.
17
17
 
18
18
  Wait for `initCustomBlock()` to resolve before calling the getter or mounting components that use
19
- the hook. See [initialization](./lifecycle.md).
19
+ the hook. See [initialization](lifecycle.md).
20
20
 
21
21
  ### TypeScript API
22
22
 
@@ -36,7 +36,7 @@ const unsubscribe = customBlock.subscribeToCurrentUser(nextUser => {
36
36
  ```
37
37
 
38
38
  Call `unsubscribe()` when you no longer need updates. The callback receives the initial profile and
39
- later changes. See [context subscriptions](./block-location.md#reading-values-and-following-changes)
39
+ later changes. See [context subscriptions](block-location.md#reading-values-and-following-changes)
40
40
  for initialization and equality rules.
41
41
 
42
42
  ### React hook
@@ -154,7 +154,7 @@ A user returned by `users.list()` does not necessarily have access to the curren
154
154
  source. Do not use this list to check page or data source permissions.
155
155
 
156
156
  If a request returns `status: "error"`, handle the error before reading `result.user` or
157
- `result.list`. See [error handling](./errors.md).
157
+ `result.list`. See [error handling](errors.md).
158
158
 
159
159
  ## Types
160
160
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notionhq/custom-blocks",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -31,7 +31,8 @@
31
31
  "src",
32
32
  "bin",
33
33
  "docs",
34
- "dist"
34
+ "dist",
35
+ "LICENSE"
35
36
  ],
36
37
  "peerDependencies": {
37
38
  "react": "^19.2.8"
@@ -41,24 +42,8 @@
41
42
  "optional": true
42
43
  }
43
44
  },
44
- "devDependencies": {
45
- "@testing-library/react": "^16.3.3",
46
- "@types/node": "^26.5.0",
47
- "@types/react": "^19.2.18",
48
- "@types/react-dom": "^19.2.7",
49
- "@vitest/coverage-v8": "^5.0.0",
50
- "jsdom": "^30.0.1",
51
- "react": "^19.2.8",
52
- "react-dom": "^19.2.8",
53
- "vitest": "^5.0.0"
54
- },
55
45
  "dependencies": {
56
- "valibot": "^1.4.2"
57
- },
58
- "scripts": {
59
- "test": "vitest run --environment jsdom",
60
- "test:coverage": "vitest run --environment jsdom --coverage --coverage.provider=v8 --coverage.reporter=json",
61
- "typecheck": "tsc --project tsconfig.json && tsc --project cli/tsconfig.json"
46
+ "valibot": "^1.5.0"
62
47
  },
63
48
  "bin": {
64
49
  "notion-custom-blocks": "./bin/notion-custom-blocks/cli.js"
@@ -69,10 +69,9 @@ import {
69
69
  createEmptyDataSourceQueryState,
70
70
  type DataSourceQueryState,
71
71
  } from "./hostState.js"
72
- import type { ManifestLoadResult } from "./loadManifest.js"
73
72
  import type { MessageInterceptor } from "./messageInterceptor.js"
74
73
  import { notifyListener } from "./notifyListener.js"
75
- import { toNotionPageFromNotionPageData } from "./page.js"
74
+ import { makeUpdatePageByKey, toNotionPageFromBridgePage } from "./page.js"
76
75
  import { PendingRequests } from "./pendingRequests.js"
77
76
  import { SandboxInitialization } from "./SandboxInitialization.js"
78
77
 
@@ -196,10 +195,6 @@ export class SandboxBridge {
196
195
  return () => this.messageInterceptors.delete(interceptor)
197
196
  }
198
197
 
199
- sendConnect(manifestResult: ManifestLoadResult) {
200
- this.initialization.sendConnect(manifestResult)
201
- }
202
-
203
198
  private postToHost(message: SandboxToHostMessage) {
204
199
  this.initialization.post(message)
205
200
  }
@@ -783,7 +778,6 @@ export class SandboxBridge {
783
778
  const resolvedProperties = resolvePropertyWriteMapForDataSource({
784
779
  dataSource: propertyDataSource,
785
780
  properties: args.properties,
786
- operationName: "createPage",
787
781
  })
788
782
  if (resolvedProperties.status === "error") {
789
783
  resolve(resolvedProperties)
@@ -804,8 +798,8 @@ export class SandboxBridge {
804
798
  Object.assign(page, result.page)
805
799
  return { status: "success", page }
806
800
  }
807
- const page: NotionPage = toNotionPageFromNotionPageData({
808
- page: result.page,
801
+ const page: NotionPage = toNotionPageFromBridgePage({
802
+ bridgePage: result.page,
809
803
  dataSourceKey,
810
804
  getPropertyById: propertyId =>
811
805
  this.getPropertyById({ page, propertyId }),
@@ -813,8 +807,11 @@ export class SandboxBridge {
813
807
  this.getPropertyByKey({ page, dataSource, propertyKey }),
814
808
  updateById: payload =>
815
809
  update({ ...payload, pageId: page.id, dataSource: undefined }),
816
- updateByKey: payload =>
817
- update({ ...payload, pageId: page.id, dataSource }),
810
+ updateByKey: makeUpdatePageByKey({
811
+ dataSource,
812
+ update: payload =>
813
+ update({ ...payload, pageId: page.id, dataSource }),
814
+ }),
818
815
  })
819
816
  resolve({ status: "success", page })
820
817
  })
@@ -854,8 +851,8 @@ export class SandboxBridge {
854
851
  Object.assign(page, result.page)
855
852
  return { status: "success", page }
856
853
  }
857
- const page: NotionPage = toNotionPageFromNotionPageData({
858
- page: result.page,
854
+ const page: NotionPage = toNotionPageFromBridgePage({
855
+ bridgePage: result.page,
859
856
  dataSourceKey,
860
857
  getPropertyById: propertyId =>
861
858
  this.getPropertyById({ page, propertyId }),
@@ -863,8 +860,11 @@ export class SandboxBridge {
863
860
  this.getPropertyByKey({ page, dataSource, propertyKey }),
864
861
  updateById: payload =>
865
862
  update({ ...payload, pageId: page.id, dataSource: undefined }),
866
- updateByKey: payload =>
867
- update({ ...payload, pageId: page.id, dataSource }),
863
+ updateByKey: makeUpdatePageByKey({
864
+ dataSource,
865
+ update: payload =>
866
+ update({ ...payload, pageId: page.id, dataSource }),
867
+ }),
868
868
  })
869
869
  resolve({ status: "success", page })
870
870
  })
@@ -980,32 +980,9 @@ export class SandboxBridge {
980
980
  > => {
981
981
  const { dataSource } = args
982
982
  const dataSourceId = dataSource?.collectionPointer?.id
983
- const propertyIdsByKey = dataSource?.propertyIdsByKey ?? {}
984
- if (dataSource !== undefined) {
985
- for (const propertyKey of Object.keys(args.properties ?? {})) {
986
- const propertyId = Object.hasOwn(propertyIdsByKey, propertyKey)
987
- ? propertyIdsByKey[propertyKey]
988
- : undefined
989
- if (
990
- propertyId &&
991
- dataSource?.collectionSchema?.propertiesById[propertyId]
992
- ) {
993
- continue
994
- }
995
- return {
996
- status: "error",
997
- error: {
998
- code: "unmapped_property",
999
- message: `Cannot resolve property key "${propertyKey}" on this page.`,
1000
- isRetryable: false,
1001
- },
1002
- }
1003
- }
1004
- }
1005
983
  const resolved = resolvePropertyWriteMapForDataSource({
1006
984
  dataSource,
1007
- properties: args.properties ?? {},
1008
- operationName: "page.update",
985
+ properties: args.properties === undefined ? {} : args.properties,
1009
986
  })
1010
987
  if (resolved.status === "error") {
1011
988
  return resolved
@@ -1079,15 +1056,8 @@ export class SandboxBridge {
1079
1056
  switch (parent.type) {
1080
1057
  case "page_id":
1081
1058
  return { status: "ok", parent, dataSource: undefined }
1082
- case "data_source_id": {
1083
- const dataSource =
1084
- this.hostState.status === "initialized"
1085
- ? this.hostState.dataSources.find(
1086
- entry => entry.collectionPointer?.id === parent.data_source_id,
1087
- )
1088
- : undefined
1089
- return { status: "ok", parent, dataSource }
1090
- }
1059
+ case "data_source_id":
1060
+ return { status: "ok", parent, dataSource: undefined }
1091
1061
  case "data_source_key": {
1092
1062
  if (this.hostState.status !== "initialized") {
1093
1063
  return {
@@ -12,16 +12,13 @@ import { LATEST_BRIDGE_PROTOCOL_VERSION } from "@notionhq/custom-blocks-protocol
12
12
  import { type CustomBlockInitPayload, NotInIframeError } from "../initTypes.js"
13
13
  import { CUSTOM_BLOCKS_SDK_VERSION } from "../version.js"
14
14
  import type { CustomBlockHostState } from "./hostState.js"
15
- import {
16
- attemptToLoadSelfHostedManifest,
17
- type ManifestLoadResult,
18
- } from "./loadManifest.js"
15
+ import { readLocalManifest } from "./readLocalManifest.js"
19
16
 
20
17
  const INITIALIZATION_ID = "custom-block-initialization-1"
21
18
 
22
19
  /** Tracks the startup handshake and when outbound messages can be sent. */
23
20
  type SandboxInitializationPhase =
24
- /** No connect message has been sent. Manifest loading can still be in progress. */
21
+ /** No connect message has been sent. */
25
22
  | "idle"
26
23
  /** Standalone preview state is available without a host handshake. */
27
24
  | "preview"
@@ -86,10 +83,11 @@ export class SandboxInitialization {
86
83
 
87
84
  private async run(): Promise<CustomBlockInitPayload> {
88
85
  try {
89
- if (typeof window !== "undefined" && window.parent === window) {
86
+ if (typeof window === "undefined" || window.parent === window) {
90
87
  throw new NotInIframeError()
91
88
  }
92
- await Promise.all([this.loadManifestAndConnect(), this.initialized])
89
+ this.sendConnect()
90
+ await this.initialized
93
91
  const state = this.options.getState()
94
92
  if (state.status !== "initialized") {
95
93
  throw new CustomBlockInitializationError({
@@ -119,21 +117,15 @@ export class SandboxInitialization {
119
117
  }
120
118
  }
121
119
 
122
- private async loadManifestAndConnect() {
123
- const manifest = await attemptToLoadSelfHostedManifest()
124
- if (this.phase !== "disposed") {
125
- this.sendConnect(manifest)
126
- }
127
- }
128
-
129
- sendConnect(result: ManifestLoadResult) {
130
- if (typeof window === "undefined") {
131
- return
132
- }
120
+ private sendConnect() {
133
121
  if (this.phase !== "idle" && this.phase !== "preview") {
134
122
  console.warn("[custom-blocks-sdk] ignoring duplicate connect message")
135
123
  return
136
124
  }
125
+ const result = readLocalManifest({
126
+ document: window.document,
127
+ url: new URL(window.location.href),
128
+ })
137
129
  this.phase = "waiting"
138
130
  const identity = {
139
131
  type: "connect" as const,
@@ -142,12 +134,14 @@ export class SandboxInitialization {
142
134
  sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
143
135
  }
144
136
  const message: ConnectMessage =
145
- result.error !== undefined
137
+ result.status === "error"
146
138
  ? { ...identity, status: "error", error: result.error }
147
139
  : {
148
140
  ...identity,
149
141
  status: "success",
150
- ...(result.manifest !== null ? { manifest: result.manifest } : {}),
142
+ ...(result.manifest !== undefined
143
+ ? { manifest: result.manifest }
144
+ : {}),
151
145
  }
152
146
  this.options.post(message)
153
147
  }
@@ -1,14 +1,6 @@
1
1
  /**
2
- * Background color values used before the NDS token scope mounts.
3
- *
4
- * The light value matches NDS's semantic `--bg-base` token in light mode
5
- * (`--gray-0`, white). The dark value is the existing SDK fallback canvas
6
- * color; it is not an exact current generated NDS value. Current NDS maps
7
- * dark `--bg-base` to `--gray-145` (approximately `#1b1b1b`), while the
8
- * legacy notion-next gray surface is `rgba(32, 32, 32, 1)`.
9
- *
10
- * Keep the resolved values here because the document must be styled before the block's NDS
11
- * stylesheet and token scope are guaranteed to be available.
2
+ * Background colors applied before the block's NDS stylesheet and token scope
3
+ * are available, preventing an initial theme flash.
12
4
  */
13
5
  export const NOTION_DARK_BACKGROUND_BASE = "#191918"
14
6
  export const NOTION_LIGHT_BACKGROUND_BASE = "#ffffff"