@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
@@ -0,0 +1,181 @@
1
+ import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
+ import {
3
+ customBlockRelativeDateValueSchema,
4
+ type ResolvedCustomBlockDataSourceFilter,
5
+ type ResolvedCustomBlockDataSourcePropertyFilter,
6
+ resolvedCustomBlockDataSourcePropertyFilterSchema,
7
+ } from "@notionhq/custom-blocks-protocol/messages/queryDataSource.js"
8
+ import * as v from "valibot"
9
+ import { resolvePropertyAddress } from "./resolvePropertyAddress.js"
10
+
11
+ const MAX_DATA_SOURCE_QUERY_FILTER_CHILDREN = 25
12
+
13
+ type ResolvePropertyFilterResult =
14
+ | { status: "ok"; filter: ResolvedCustomBlockDataSourcePropertyFilter }
15
+ | { status: "error"; error: string }
16
+
17
+ export function resolveFilter(
18
+ filter: unknown,
19
+ dataSource: NotionDataSource,
20
+ ):
21
+ | { status: "ok"; filter?: ResolvedCustomBlockDataSourceFilter }
22
+ | { status: "error"; error: string } {
23
+ if (filter === undefined) {
24
+ return { status: "ok" }
25
+ }
26
+ if (typeof filter !== "object" || filter === null || Array.isArray(filter)) {
27
+ return {
28
+ status: "error",
29
+ error: "Data source query filter must be an object.",
30
+ }
31
+ }
32
+ const filterObject = filter as Record<string, unknown>
33
+ if (Object.hasOwn(filterObject, "and")) {
34
+ if (
35
+ Object.keys(filterObject).length !== 1 ||
36
+ !Array.isArray(filterObject.and)
37
+ ) {
38
+ return {
39
+ status: "error",
40
+ error: 'Data source query filter "and" must be an array.',
41
+ }
42
+ }
43
+ if (filterObject.and.length > MAX_DATA_SOURCE_QUERY_FILTER_CHILDREN) {
44
+ return {
45
+ status: "error",
46
+ error: `Data source query filter "and" may contain at most ${MAX_DATA_SOURCE_QUERY_FILTER_CHILDREN} children.`,
47
+ }
48
+ }
49
+ const and: ResolvedCustomBlockDataSourcePropertyFilter[] = []
50
+ for (const child of filterObject.and) {
51
+ const resolved = resolvePropertyFilter(child, dataSource)
52
+ if (resolved.status === "error") {
53
+ return resolved
54
+ }
55
+ and.push(resolved.filter)
56
+ }
57
+ return { status: "ok", filter: { and } }
58
+ }
59
+ return resolvePropertyFilter(filterObject, dataSource)
60
+ }
61
+
62
+ function resolvePropertyFilter(
63
+ filter: unknown,
64
+ dataSource: NotionDataSource,
65
+ ): ResolvePropertyFilterResult {
66
+ if (typeof filter !== "object" || filter === null || Array.isArray(filter)) {
67
+ return {
68
+ status: "error",
69
+ error: "Data source query property filter must be an object.",
70
+ }
71
+ }
72
+ const filterObject = filter as Record<string, unknown>
73
+ const property = resolvePropertyAddress(filterObject, dataSource)
74
+ if (property.status === "error") {
75
+ return property
76
+ }
77
+ const branchKeys = Object.keys(filterObject).filter(
78
+ key => key !== "key" && key !== "propertyId",
79
+ )
80
+ if (branchKeys.length !== 1) {
81
+ return {
82
+ status: "error",
83
+ error:
84
+ "Data source query property filter must contain exactly one property branch.",
85
+ }
86
+ }
87
+ const branch = branchKeys[0]
88
+ const value = filterObject[branch]
89
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
90
+ return invalidOperator(branch)
91
+ }
92
+ const operatorKeys = Object.keys(value).filter(
93
+ key => branch !== "date" || key !== "target",
94
+ )
95
+ if (operatorKeys.length !== 1) {
96
+ return invalidOperator(branch)
97
+ }
98
+ if (property.propertyType !== branch) {
99
+ return {
100
+ status: "error",
101
+ error: `Data source query filter branch "${branch}" does not match property type "${property.propertyType}".`,
102
+ }
103
+ }
104
+
105
+ return parsePropertyFilter({
106
+ propertyId: property.propertyId,
107
+ branch,
108
+ value,
109
+ })
110
+ }
111
+
112
+ function parsePropertyFilter(args: {
113
+ propertyId: string
114
+ branch: string
115
+ value: unknown
116
+ }): ResolvePropertyFilterResult {
117
+ const { propertyId, branch, value } = args
118
+ const parsed = v.safeParse(
119
+ resolvedCustomBlockDataSourcePropertyFilterSchema,
120
+ { propertyId, [branch]: value },
121
+ )
122
+ if (!parsed.success) {
123
+ if (
124
+ resolvedCustomBlockDataSourcePropertyFilterSchema.options.every(
125
+ schema => !Object.hasOwn(schema.entries, branch),
126
+ )
127
+ ) {
128
+ return {
129
+ status: "error",
130
+ error: `Data source query filter branch "${branch}" is not supported.`,
131
+ }
132
+ }
133
+ return invalidOperator(branch)
134
+ }
135
+ const filter = parsed.output
136
+ if (
137
+ "number" in filter &&
138
+ !Object.values(filter.number).every(
139
+ entry => typeof entry !== "number" || Number.isFinite(entry),
140
+ )
141
+ ) {
142
+ return invalidOperator("number")
143
+ }
144
+ if (
145
+ "date" in filter &&
146
+ !Object.entries(filter.date).every(
147
+ ([key, entry]) =>
148
+ key === "target" ||
149
+ entry === true ||
150
+ typeof entry === "object" ||
151
+ v.is(customBlockRelativeDateValueSchema, entry) ||
152
+ isValidIsoDate(entry),
153
+ )
154
+ ) {
155
+ return invalidOperator("date")
156
+ }
157
+ return { status: "ok", filter }
158
+ }
159
+
160
+ function invalidOperator(branch: string): { status: "error"; error: string } {
161
+ return {
162
+ status: "error",
163
+ error: `Data source query filter branch "${branch}" has an invalid operator or value.`,
164
+ }
165
+ }
166
+
167
+ function isValidIsoDate(value: string): boolean {
168
+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
169
+ if (dateOnly !== null) {
170
+ const [, year, month, day] = dateOnly
171
+ const date = new Date(
172
+ Date.UTC(Number(year), Number(month) - 1, Number(day)),
173
+ )
174
+ return date.toISOString().slice(0, 10) === value
175
+ }
176
+ return (
177
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test(
178
+ value,
179
+ ) && Number.isFinite(Date.parse(value))
180
+ )
181
+ }
@@ -21,35 +21,46 @@ function makePropertyError(
21
21
 
22
22
  /**
23
23
  * Resolves a public SDK property write map into the ID-keyed bridge shape.
24
- *
25
- * Identifiers in `properties` may be raw property IDs or data source property keys; the latter
26
- * are looked up in the `dataSource`'s `propertyIdsByKey`. Each value is re-parsed through
27
- * the page property value schema with its `id` rewritten to the resolved property ID.
24
+ * A data source makes every identifier a property key; without one, identifiers are raw IDs.
28
25
  */
29
26
  export function resolvePropertyWriteMapForDataSource(args: {
30
27
  dataSource: NotionDataSource | undefined
31
28
  properties: NotionPagePropertyInputMap
32
- operationName: string
33
29
  }): PropertyWriteMapResolutionResult {
34
- const { dataSource, properties, operationName } = args
30
+ const { dataSource, properties } = args
31
+ const parsedMap = v.safeParse(v.record(v.string(), v.unknown()), properties)
32
+ if (Array.isArray(properties) || !parsedMap.success) {
33
+ return {
34
+ status: "error",
35
+ error: makePropertyError(
36
+ "invalid_property_value",
37
+ "Property maps must be objects.",
38
+ ),
39
+ }
40
+ }
35
41
 
36
- const resolvedProperties: CreatePageMessage["properties"] = {}
37
- for (const [identifier, value] of Object.entries(properties)) {
38
- const propertyIdResult = resolvePropertyIdentifierForDataSource({
42
+ const resolvedProperties: CreatePageMessage["properties"] =
43
+ Object.create(null)
44
+ for (const [identifier, value] of Object.entries(parsedMap.output)) {
45
+ const propertyIdResult = resolveWriteIdentifier({
39
46
  dataSource,
40
47
  identifier,
41
- operationName,
42
48
  })
43
49
  if (propertyIdResult.status === "error") {
44
50
  return propertyIdResult
45
51
  }
46
52
 
47
53
  const propertyId = propertyIdResult.propertyId
48
- if (
49
- value.id !== undefined &&
50
- value.id !== identifier &&
51
- value.id !== propertyId
52
- ) {
54
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
55
+ return {
56
+ status: "error",
57
+ error: makePropertyError(
58
+ "invalid_property_value",
59
+ `Invalid value for property ${identifier}.`,
60
+ ),
61
+ }
62
+ }
63
+ if ("id" in value && value.id !== undefined && value.id !== propertyId) {
53
64
  return {
54
65
  status: "error",
55
66
  error: makePropertyError(
@@ -58,7 +69,7 @@ export function resolvePropertyWriteMapForDataSource(args: {
58
69
  ),
59
70
  }
60
71
  }
61
- if (resolvedProperties[propertyId] !== undefined) {
72
+ if (Object.hasOwn(resolvedProperties, propertyId)) {
62
73
  return {
63
74
  status: "error",
64
75
  error: makePropertyError(
@@ -89,35 +100,33 @@ export function resolvePropertyWriteMapForDataSource(args: {
89
100
  }
90
101
 
91
102
  /**
92
- * Treats bound data source keys as aliases for property IDs. An unbound key may still be used as
93
- * a raw ID when it exactly matches a property in the data source schema.
103
+ * Resolves property keys when a data source is present and raw property IDs otherwise.
104
+ * Property keys require a bound, loaded property so an unresolved key cannot become a raw ID.
94
105
  */
95
- export function resolvePropertyIdentifierForDataSource(args: {
106
+ function resolveWriteIdentifier(args: {
96
107
  dataSource: NotionDataSource | undefined
97
108
  identifier: string
98
- operationName: string
99
109
  }):
100
110
  | { status: "success"; propertyId: string }
101
111
  | { status: "error"; error: CustomBlockPropertyErrorInfo } {
102
- const { dataSource, identifier, operationName } = args
103
- if (dataSource !== undefined && identifier in dataSource.propertyIdsByKey) {
104
- const propertyId = dataSource.propertyIdsByKey[identifier]
105
- if (propertyId === undefined) {
106
- // If the property is not bound to a key, check if it is a valid property ID. If so, we
107
- // can use it directly.
108
- if (identifier in dataSource.propertySchemasById) {
109
- return { status: "success", propertyId: identifier }
110
- }
111
- return {
112
- status: "error",
113
- error: makePropertyError(
114
- "unmapped_property",
115
- `${operationName} cannot resolve property key "${identifier}" because it is not bound to a Notion property.`,
116
- ),
117
- }
112
+ const { dataSource, identifier } = args
113
+ if (dataSource === undefined) {
114
+ return { status: "success", propertyId: identifier }
115
+ }
116
+ const propertyId = Object.hasOwn(dataSource.propertyIdsByKey, identifier)
117
+ ? dataSource.propertyIdsByKey[identifier]
118
+ : undefined
119
+ if (
120
+ propertyId === undefined ||
121
+ !dataSource.collectionSchema?.propertiesById[propertyId]
122
+ ) {
123
+ return {
124
+ status: "error",
125
+ error: makePropertyError(
126
+ "unmapped_property",
127
+ `Cannot resolve property key "${identifier}" on this page.`,
128
+ ),
118
129
  }
119
- return { status: "success", propertyId }
120
130
  }
121
-
122
- return { status: "success", propertyId: identifier }
131
+ return { status: "success", propertyId }
123
132
  }
@@ -0,0 +1,62 @@
1
+ import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
+
3
+ export function resolvePropertyAddress(
4
+ value: Record<string, unknown>,
5
+ dataSource: NotionDataSource,
6
+ ):
7
+ | { status: "ok"; propertyId: string; propertyType: string }
8
+ | { status: "error"; error: string } {
9
+ const hasKey = Object.hasOwn(value, "key")
10
+ const hasPropertyId = Object.hasOwn(value, "propertyId")
11
+ if (hasKey === hasPropertyId) {
12
+ return {
13
+ status: "error",
14
+ error:
15
+ "Data source query filters and sorts must use exactly one of key or propertyId.",
16
+ }
17
+ }
18
+ let propertyId: string
19
+ if (hasKey) {
20
+ if (typeof value.key !== "string") {
21
+ return {
22
+ status: "error",
23
+ error: "Data source query property key must be a string.",
24
+ }
25
+ }
26
+ if (!Object.hasOwn(dataSource.propertyIdsByKey, value.key)) {
27
+ return {
28
+ status: "error",
29
+ error: `Unknown property key "${value.key}" for data source "${dataSource.key}".`,
30
+ }
31
+ }
32
+ const resolvedPropertyId = dataSource.propertyIdsByKey[value.key]
33
+ if (resolvedPropertyId === undefined) {
34
+ return {
35
+ status: "error",
36
+ error: `Property key "${value.key}" for data source "${dataSource.key}" is not bound.`,
37
+ }
38
+ }
39
+ propertyId = resolvedPropertyId
40
+ } else {
41
+ if (typeof value.propertyId !== "string") {
42
+ return {
43
+ status: "error",
44
+ error: "Data source query propertyId must be a string.",
45
+ }
46
+ }
47
+ propertyId = value.propertyId
48
+ }
49
+ const properties = dataSource.collectionSchema?.propertiesById ?? {}
50
+ if (!Object.hasOwn(properties, propertyId)) {
51
+ return {
52
+ status: "error",
53
+ error: `Unknown property ID "${propertyId}" for data source "${dataSource.key}".`,
54
+ }
55
+ }
56
+ const propertySchema = properties[propertyId]
57
+ return {
58
+ status: "ok",
59
+ propertyId,
60
+ propertyType: propertySchema.type,
61
+ }
62
+ }
@@ -0,0 +1,107 @@
1
+ import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
+ import { CUSTOM_BLOCK_DATA_SOURCE_SORTABLE_PROPERTY_TYPES } from "@notionhq/custom-blocks-protocol/dataSources/propertySchema.js"
3
+ import { notionSortDirectionSchema } from "@notionhq/custom-blocks-protocol/dataSources/sortDirection.js"
4
+ import {
5
+ CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS,
6
+ type ResolvedCustomBlockDataSourceSort,
7
+ } from "@notionhq/custom-blocks-protocol/messages/queryDataSource.js"
8
+ import * as v from "valibot"
9
+ import { resolvePropertyAddress } from "./resolvePropertyAddress.js"
10
+
11
+ const supportedDataSourceSortPropertyTypes = new Set<string>(
12
+ CUSTOM_BLOCK_DATA_SOURCE_SORTABLE_PROPERTY_TYPES,
13
+ )
14
+
15
+ export function resolveSorts(
16
+ sorts: unknown,
17
+ dataSource: NotionDataSource,
18
+ ):
19
+ | { status: "ok"; sorts?: ResolvedCustomBlockDataSourceSort[] }
20
+ | { status: "error"; error: string } {
21
+ if (sorts === undefined) {
22
+ return { status: "ok" }
23
+ }
24
+ if (!Array.isArray(sorts)) {
25
+ return {
26
+ status: "error",
27
+ error: "Data source query sorts must be an array.",
28
+ }
29
+ }
30
+ if (sorts.length === 0) {
31
+ return { status: "ok" }
32
+ }
33
+ if (sorts.length > CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS) {
34
+ return {
35
+ status: "error",
36
+ error: `Data source query sorts may contain at most ${CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS} entries.`,
37
+ }
38
+ }
39
+
40
+ const resolvedSorts: ResolvedCustomBlockDataSourceSort[] = []
41
+ const seenPropertyIds = new Set<string>()
42
+ for (const sort of sorts) {
43
+ const resolved = resolveSort(sort, dataSource)
44
+ if (resolved.status === "error") {
45
+ return resolved
46
+ }
47
+ if (seenPropertyIds.has(resolved.sort.propertyId)) {
48
+ return {
49
+ status: "error",
50
+ error: `Data source query sorts cannot contain duplicate property ID "${resolved.sort.propertyId}".`,
51
+ }
52
+ }
53
+ seenPropertyIds.add(resolved.sort.propertyId)
54
+ resolvedSorts.push(resolved.sort)
55
+ }
56
+ return { status: "ok", sorts: resolvedSorts }
57
+ }
58
+
59
+ function resolveSort(
60
+ sort: unknown,
61
+ dataSource: NotionDataSource,
62
+ ):
63
+ | { status: "ok"; sort: ResolvedCustomBlockDataSourceSort }
64
+ | { status: "error"; error: string } {
65
+ if (typeof sort !== "object" || sort === null || Array.isArray(sort)) {
66
+ return {
67
+ status: "error",
68
+ error: "Data source query sort must be an object.",
69
+ }
70
+ }
71
+ const sortObject = sort as Record<string, unknown>
72
+ if (
73
+ Object.keys(sortObject).some(
74
+ key => !["key", "propertyId", "direction"].includes(key),
75
+ )
76
+ ) {
77
+ return {
78
+ status: "error",
79
+ error: "Data source query sort contains unsupported fields.",
80
+ }
81
+ }
82
+ const property = resolvePropertyAddress(sortObject, dataSource)
83
+ if (property.status === "error") {
84
+ return property
85
+ }
86
+ if (!supportedDataSourceSortPropertyTypes.has(property.propertyType)) {
87
+ return {
88
+ status: "error",
89
+ error: `Data source query sorts do not yet support property type "${property.propertyType}".`,
90
+ }
91
+ }
92
+ const direction = sortObject.direction
93
+ if (
94
+ !Object.hasOwn(sortObject, "direction") ||
95
+ !v.is(notionSortDirectionSchema, direction)
96
+ ) {
97
+ return {
98
+ status: "error",
99
+ error:
100
+ 'Data source query sort direction must be "ascending" or "descending".',
101
+ }
102
+ }
103
+ return {
104
+ status: "ok",
105
+ sort: { propertyId: property.propertyId, direction },
106
+ }
107
+ }
@@ -4,14 +4,14 @@ import type { NotionBlockId } from "@notionhq/custom-blocks-protocol/ids.js"
4
4
  import type { CustomBlockManifest } from "@notionhq/custom-blocks-protocol/manifest.js"
5
5
  import type { CustomBlockQueryDataSourceErrorInfo } from "@notionhq/custom-blocks-protocol/messages/queryDataSourceResult.js"
6
6
  import type {
7
+ bridgePageSchema,
7
8
  CustomBlockPage,
8
- notionPageDataSchema,
9
9
  } from "@notionhq/custom-blocks-protocol/pages/page.js"
10
10
  import type { NotionParent } from "@notionhq/custom-blocks-protocol/parent.js"
11
11
  import type { NotionTheme } from "@notionhq/custom-blocks-protocol/theme.js"
12
12
  import type { NotionUser } from "@notionhq/custom-blocks-protocol/users/user.js"
13
13
  import type { InferOutput } from "valibot"
14
- import type { DataSourceSnapshot, NotionPage } from "../types.js"
14
+ import type { DataSourceSnapshot } from "../types.js"
15
15
 
16
16
  export type CustomBlockHostState = UninitializedHostState | InitializedHostState
17
17
 
@@ -37,7 +37,7 @@ export type InitializedHostState = {
37
37
  export type DataSourceQueryState = {
38
38
  dataSourceKey: string
39
39
  /** Latest pages from the host as parsed from the bridge. */
40
- items: InferOutput<typeof notionPageDataSchema>[]
40
+ items: InferOutput<typeof bridgePageSchema>[]
41
41
  isLoading: boolean
42
42
  hasMore: boolean
43
43
  error?: CustomBlockQueryDataSourceErrorInfo
@@ -57,43 +57,3 @@ export function createEmptyDataSourceQueryState(
57
57
  }
58
58
 
59
59
  export type DataSourceQueryView = DataSourceSnapshot
60
-
61
- const EMPTY_QUERY_VIEW: DataSourceQueryView = {
62
- items: [],
63
- propertyIdsByKey: {},
64
- isLoading: false,
65
- hasMore: false,
66
- }
67
-
68
- export function getDataSourceQueryView(
69
- hostState: CustomBlockHostState,
70
- key: string,
71
- subscriptionId: string,
72
- createNotionPage: (args: {
73
- page: InferOutput<typeof notionPageDataSchema>
74
- dataSource: NotionDataSource | undefined
75
- }) => NotionPage,
76
- ): DataSourceQueryView {
77
- if (hostState.status !== "initialized") {
78
- return EMPTY_QUERY_VIEW
79
- }
80
-
81
- const dataSource = hostState.dataSources.find(entry => entry.key === key)
82
- const subscriptionState = hostState.dataSourceState[subscriptionId]
83
- const queryState =
84
- subscriptionState?.dataSourceKey === key
85
- ? subscriptionState
86
- : createEmptyDataSourceQueryState(key)
87
-
88
- return {
89
- items:
90
- dataSource === undefined
91
- ? []
92
- : queryState.items.map(entry =>
93
- createNotionPage({ page: entry, dataSource }),
94
- ),
95
- propertyIdsByKey: dataSource?.propertyIdsByKey ?? {},
96
- isLoading: queryState.isLoading,
97
- hasMore: queryState.hasMore,
98
- }
99
- }
@@ -1,9 +1,10 @@
1
- import type { notionPageDataSchema } from "@notionhq/custom-blocks-protocol/pages/page.js"
1
+ import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
+ import type { bridgePageSchema } from "@notionhq/custom-blocks-protocol/pages/page.js"
2
3
  import type { InferOutput } from "valibot"
3
4
  import type { NotionPage } from "../types.js"
4
5
 
5
- export function toNotionPageFromNotionPageData(args: {
6
- page: InferOutput<typeof notionPageDataSchema>
6
+ export function toNotionPageFromBridgePage(args: {
7
+ bridgePage: InferOutput<typeof bridgePageSchema>
7
8
  dataSourceKey: string | undefined
8
9
  getPropertyById: NotionPage["getPropertyById"]
9
10
  getPropertyByKey: NotionPage["getPropertyByKey"]
@@ -11,7 +12,7 @@ export function toNotionPageFromNotionPageData(args: {
11
12
  updateByKey: NotionPage["updateByKey"]
12
13
  }): NotionPage {
13
14
  return {
14
- ...args.page,
15
+ ...args.bridgePage,
15
16
  dataSourceKey: args.dataSourceKey ?? null,
16
17
  getPropertyById: args.getPropertyById,
17
18
  getPropertyByKey: args.getPropertyByKey,
@@ -21,3 +22,26 @@ export function toNotionPageFromNotionPageData(args: {
21
22
  unarchive: () => args.updateById({ is_archived: false }),
22
23
  }
23
24
  }
25
+
26
+ /** Prevents key-based property updates from falling back to raw IDs without data source context. */
27
+ export function makeUpdatePageByKey(args: {
28
+ dataSource: NotionDataSource | undefined
29
+ update: NotionPage["updateByKey"]
30
+ }): NotionPage["updateByKey"] {
31
+ return async payload => {
32
+ if (
33
+ args.dataSource === undefined &&
34
+ Object.keys(payload.properties ?? {}).length > 0
35
+ ) {
36
+ return {
37
+ status: "error",
38
+ error: {
39
+ code: "unmapped_property",
40
+ message: "Key-based property updates require data source context.",
41
+ isRetryable: false,
42
+ },
43
+ }
44
+ }
45
+ return args.update(payload)
46
+ }
47
+ }
@@ -0,0 +1,60 @@
1
+ import type { CustomBlockErrorInfo } from "@notionhq/custom-blocks-protocol/errors.js"
2
+ import { isLocalBlockServerUrl } from "@notionhq/custom-blocks-protocol/isLocalBlockServerUrl.js"
3
+ import {
4
+ type CustomBlockManifest,
5
+ manifestSchema,
6
+ } from "@notionhq/custom-blocks-protocol/manifest.js"
7
+ import * as v from "valibot"
8
+
9
+ export type LocalManifestReadResult =
10
+ | { status: "success"; manifest: CustomBlockManifest | undefined }
11
+ | { status: "error"; error: CustomBlockErrorInfo<"manifest_invalid"> }
12
+
13
+ /**
14
+ * Reads and validates JSON from the script with ID `notion-custom-block-manifest`
15
+ * and type `application/json`, injected into the block HTML by dev tooling.
16
+ * The SDK sends this declaration in `connect` so the host can prepare bindings.
17
+ *
18
+ * The URL check limits this development metadata to supported local block servers.
19
+ * Deployed blocks receive their manifest from the host in `init`. Reading this
20
+ * metadata uses the current document and makes no network request.
21
+ */
22
+ export function readLocalManifest(args: {
23
+ document: Document
24
+ url: URL
25
+ }): LocalManifestReadResult {
26
+ if (!isLocalBlockServerUrl(args.url)) {
27
+ return { status: "success", manifest: undefined }
28
+ }
29
+ const metadata = args.document.getElementById("notion-custom-block-manifest")
30
+ if (metadata === null) {
31
+ return { status: "success", manifest: undefined }
32
+ }
33
+ if (
34
+ metadata.tagName !== "SCRIPT" ||
35
+ metadata.getAttribute("type") !== "application/json"
36
+ ) {
37
+ return invalidManifest()
38
+ }
39
+ let input: unknown
40
+ try {
41
+ input = JSON.parse(metadata.textContent ?? "")
42
+ } catch {
43
+ return invalidManifest()
44
+ }
45
+ const parsed = v.safeParse(manifestSchema, input)
46
+ return parsed.success
47
+ ? { status: "success", manifest: parsed.output }
48
+ : invalidManifest()
49
+ }
50
+
51
+ function invalidManifest(): LocalManifestReadResult {
52
+ return {
53
+ status: "error",
54
+ error: {
55
+ code: "manifest_invalid",
56
+ message: "The local custom block metadata is not a valid manifest.",
57
+ isRetryable: false,
58
+ },
59
+ }
60
+ }