@notionhq/custom-blocks 0.3.1 → 0.3.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.
Files changed (46) hide show
  1. package/README.md +2 -8
  2. package/dist/bridge/SandboxBridge.d.ts +469 -15
  3. package/dist/bridge/SandboxBridge.d.ts.map +1 -1
  4. package/dist/bridge/SandboxBridge.js +119 -88
  5. package/dist/bridge/dataSources/resolveProperty.d.ts +1 -20
  6. package/dist/bridge/dataSources/resolveProperty.d.ts.map +1 -1
  7. package/dist/bridge/dataSources/resolveProperty.js +37 -32
  8. package/dist/bridge/page.d.ts +11 -7
  9. package/dist/bridge/page.d.ts.map +1 -1
  10. package/dist/bridge/page.js +20 -50
  11. package/dist/bridge/sandboxClient.d.ts.map +1 -1
  12. package/dist/bridge/sandboxClient.js +32 -6
  13. package/dist/dataSources.d.ts.map +1 -1
  14. package/dist/dataSources.js +4 -3
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/protocol/dataSources/dateValue.d.ts +2 -2
  18. package/dist/protocol/dataSources/dateValue.js +9 -7
  19. package/dist/protocol/messages/createPage.d.ts +64 -2
  20. package/dist/protocol/messages/createPageResult.d.ts +192 -6
  21. package/dist/protocol/messages/getPage.d.ts +192 -6
  22. package/dist/protocol/messages/hostToSandbox.d.ts +704 -22
  23. package/dist/protocol/messages/queryDataSourceResult.d.ts +128 -4
  24. package/dist/protocol/messages/sandboxToHost.d.ts +128 -4
  25. package/dist/protocol/messages/updatePage.d.ts +64 -2
  26. package/dist/protocol/messages/updatePageResult.d.ts +192 -6
  27. package/dist/protocol/pages/page.d.ts +360 -12
  28. package/dist/protocol/pages/page.js +48 -2
  29. package/dist/protocol/protocolVersion.d.ts +2 -1
  30. package/dist/protocol/protocolVersion.js +3 -1
  31. package/dist/types.d.ts +1 -1
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/version.js +1 -1
  34. package/docs/build-tools.md +55 -0
  35. package/docs/data-sources.md +12 -9
  36. package/docs/deployment.md +16 -34
  37. package/docs/errors.md +65 -52
  38. package/docs/pages.md +85 -78
  39. package/package.json +2 -18
  40. package/src/bridge/SandboxBridge.ts +168 -129
  41. package/src/bridge/dataSources/resolveProperty.ts +48 -39
  42. package/src/bridge/page.ts +32 -75
  43. package/src/bridge/sandboxClient.ts +40 -7
  44. package/src/dataSources.ts +7 -9
  45. package/src/index.ts +6 -0
  46. package/src/types.ts +6 -0
@@ -4,10 +4,7 @@ import type {
4
4
  NotionDataSource,
5
5
  NotionDataSourceBindings,
6
6
  } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
7
- import type {
8
- NotionDataSourceId,
9
- NotionPageId,
10
- } from "@notionhq/custom-blocks-protocol/ids.js"
7
+ import type { NotionPageId } from "@notionhq/custom-blocks-protocol/ids.js"
11
8
  import type { CustomBlockManifest } from "@notionhq/custom-blocks-protocol/manifest.js"
12
9
  import type {
13
10
  CreatePageMessage,
@@ -41,9 +38,7 @@ import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/mess
41
38
  import type { UnsubscribeDataSourceQueryMessage } from "@notionhq/custom-blocks-protocol/messages/unsubscribeDataSourceQuery.js"
42
39
  import type { UpdatePageMessage } from "@notionhq/custom-blocks-protocol/messages/updatePage.js"
43
40
  import type { UpdatePageResultMessage } from "@notionhq/custom-blocks-protocol/messages/updatePageResult.js"
44
- import type { notionPageDataSchema } from "@notionhq/custom-blocks-protocol/pages/page.js"
45
41
  import type { NotionTheme } from "@notionhq/custom-blocks-protocol/theme.js"
46
- import type { InferOutput } from "valibot"
47
42
  import * as v from "valibot"
48
43
  import type {
49
44
  CreatePageArgs,
@@ -59,6 +54,7 @@ import type {
59
54
  OpenPageOptions,
60
55
  OpenPageResult,
61
56
  PageUpdatePayload,
57
+ UpdatePageResult,
62
58
  } from "../types.js"
63
59
  import { unreachable } from "../utils.js"
64
60
  import {
@@ -76,7 +72,7 @@ import {
76
72
  import type { ManifestLoadResult } from "./loadManifest.js"
77
73
  import type { MessageInterceptor } from "./messageInterceptor.js"
78
74
  import { notifyListener } from "./notifyListener.js"
79
- import { toNotionPageFromNotionPageData } from "./page.js"
75
+ import { makeUpdatePageByKey, toNotionPageFromNotionPageData } from "./page.js"
80
76
  import { PendingRequests } from "./pendingRequests.js"
81
77
  import { SandboxInitialization } from "./SandboxInitialization.js"
82
78
 
@@ -103,6 +99,7 @@ export class SandboxBridge {
103
99
  theme: "light",
104
100
  contrastMode: DEFAULT_CONTRAST_MODE,
105
101
  }
102
+ private pendingPageUpdates = new Map<NotionPageId, Promise<void>>()
106
103
  private listeners = new Set<() => void>()
107
104
  private messageInterceptors = new Set<MessageInterceptor>()
108
105
  private messageLog: MessageLogEntry[] = []
@@ -758,20 +755,34 @@ export class SandboxBridge {
758
755
  this.postToHost(outbound)
759
756
  }
760
757
 
761
- createPage(
762
- createPageArgs: CreatePageArgs,
763
- dataSourceId: NotionDataSourceId | undefined,
764
- ): Promise<CreatePageResult> {
758
+ createPage(args: {
759
+ parent: CreatePageArgs["parent"]
760
+ properties: CreatePageArgs["properties"]
761
+ position?: CreatePageArgs["position"]
762
+ dataSource: NotionDataSource | undefined
763
+ }): Promise<CreatePageResult> {
764
+ const { dataSource } = args
765
+ const dataSourceKey = dataSource?.key
765
766
  return new Promise(resolve => {
766
- const resolvedParent = this.resolveCreatePageParent(createPageArgs.parent)
767
- if (resolvedParent.status === "error") {
768
- resolve(resolvedParent)
769
- return
767
+ let parent: CreatePageMessageParent
768
+ let propertyDataSource = dataSource
769
+ if (dataSource?.collectionPointer) {
770
+ parent = {
771
+ type: "data_source_id",
772
+ data_source_id: dataSource.collectionPointer.id,
773
+ }
774
+ } else {
775
+ const resolvedParent = this.resolveCreatePageParent(args.parent)
776
+ if (resolvedParent.status === "error") {
777
+ resolve(resolvedParent)
778
+ return
779
+ }
780
+ parent = resolvedParent.parent
781
+ propertyDataSource = resolvedParent.dataSource
770
782
  }
771
783
  const resolvedProperties = resolvePropertyWriteMapForDataSource({
772
- dataSource: resolvedParent.dataSource,
773
- properties: createPageArgs.properties,
774
- operationName: "createPage",
784
+ dataSource: propertyDataSource,
785
+ properties: args.properties,
775
786
  })
776
787
  if (resolvedProperties.status === "error") {
777
788
  resolve(resolvedProperties)
@@ -782,38 +793,85 @@ export class SandboxBridge {
782
793
  resolve(result)
783
794
  return
784
795
  }
785
- resolve({
786
- status: "success",
787
- page: this.buildNotionPage({ page: result.page, dataSourceId }),
796
+ const update = async (
797
+ args: Parameters<SandboxBridge["updatePage"]>[0],
798
+ ): Promise<UpdatePageResult> => {
799
+ const result = await this.updatePage(args)
800
+ if (result.status === "error") {
801
+ return result
802
+ }
803
+ Object.assign(page, result.page)
804
+ return { status: "success", page }
805
+ }
806
+ const page: NotionPage = toNotionPageFromNotionPageData({
807
+ page: result.page,
808
+ dataSourceKey,
809
+ getPropertyById: propertyId =>
810
+ this.getPropertyById({ page, propertyId }),
811
+ getPropertyByKey: propertyKey =>
812
+ this.getPropertyByKey({ page, dataSource, propertyKey }),
813
+ updateById: payload =>
814
+ update({ ...payload, pageId: page.id, dataSource: undefined }),
815
+ updateByKey: makeUpdatePageByKey({
816
+ dataSource,
817
+ update: payload =>
818
+ update({ ...payload, pageId: page.id, dataSource }),
819
+ }),
788
820
  })
821
+ resolve({ status: "success", page })
789
822
  })
790
823
  const outbound: CreatePageMessage = {
791
824
  type: "createPage",
792
825
  requestId,
793
- parent: resolvedParent.parent,
826
+ parent,
794
827
  properties: resolvedProperties.properties,
795
828
  }
796
- if (createPageArgs.position !== undefined) {
797
- outbound.position = createPageArgs.position
829
+ if (args.position !== undefined) {
830
+ outbound.position = args.position
798
831
  }
799
832
  this.postToHost(outbound)
800
833
  })
801
834
  }
802
835
 
803
- getPage(
804
- pageId: NotionPageId,
805
- dataSourceId: NotionDataSourceId | undefined,
806
- ): Promise<GetPageResult> {
836
+ getPage(args: {
837
+ pageId: NotionPageId
838
+ dataSource: NotionDataSource | undefined
839
+ }): Promise<GetPageResult> {
840
+ const { pageId, dataSource } = args
841
+ const dataSourceId = dataSource?.collectionPointer?.id
842
+ const dataSourceKey = dataSource?.key
807
843
  return new Promise(resolve => {
808
844
  const requestId = this.pendingGetPage.allocate(result => {
809
845
  if (result.status === "error") {
810
846
  resolve(result)
811
847
  return
812
848
  }
813
- resolve({
814
- status: "success",
815
- page: this.buildNotionPage({ page: result.page, dataSourceId }),
849
+ const update = async (
850
+ args: Parameters<SandboxBridge["updatePage"]>[0],
851
+ ): Promise<UpdatePageResult> => {
852
+ const result = await this.updatePage(args)
853
+ if (result.status === "error") {
854
+ return result
855
+ }
856
+ Object.assign(page, result.page)
857
+ return { status: "success", page }
858
+ }
859
+ const page: NotionPage = toNotionPageFromNotionPageData({
860
+ page: result.page,
861
+ dataSourceKey,
862
+ getPropertyById: propertyId =>
863
+ this.getPropertyById({ page, propertyId }),
864
+ getPropertyByKey: propertyKey =>
865
+ this.getPropertyByKey({ page, dataSource, propertyKey }),
866
+ updateById: payload =>
867
+ update({ ...payload, pageId: page.id, dataSource: undefined }),
868
+ updateByKey: makeUpdatePageByKey({
869
+ dataSource,
870
+ update: payload =>
871
+ update({ ...payload, pageId: page.id, dataSource }),
872
+ }),
816
873
  })
874
+ resolve({ status: "success", page })
817
875
  })
818
876
  const outbound: GetPageMessage = {
819
877
  type: "getPage",
@@ -878,67 +936,79 @@ export class SandboxBridge {
878
936
  })
879
937
  }
880
938
 
881
- private updatePage(
882
- args: UpdatePageArgs,
883
- dataSourceId: NotionDataSourceId | undefined,
884
- ): Promise<BridgeMessagePayload<UpdatePageResultMessage>> {
885
- const dataSource =
886
- this.hostState.status === "initialized" && dataSourceId !== undefined
939
+ getPropertyById(args: { page: NotionPage; propertyId: string }) {
940
+ return (
941
+ Object.values(args.page.properties).find(
942
+ value => value?.id === args.propertyId,
943
+ ) ?? null
944
+ )
945
+ }
946
+
947
+ getPropertyByKey(args: {
948
+ page: NotionPage
949
+ dataSource: NotionDataSource | undefined
950
+ propertyKey: string
951
+ }) {
952
+ const { page, dataSource, propertyKey } = args
953
+ const currentDataSource =
954
+ this.hostState.status === "initialized"
887
955
  ? this.hostState.dataSources.find(
888
- source => source.collectionPointer?.id === dataSourceId,
956
+ source => source.key === dataSource?.key,
889
957
  )
890
958
  : undefined
891
- if (dataSourceId !== undefined) {
892
- const unmappedKey = Object.keys(args.properties ?? {}).find(key => {
893
- const id =
894
- dataSource && Object.hasOwn(dataSource.propertyIdsByKey, key)
895
- ? dataSource.propertyIdsByKey[key]
896
- : undefined
897
- return !id || !dataSource?.collectionSchema?.propertiesById[id]
959
+ // Keep the captured mapping valid only while its key remains bound to the original database.
960
+ if (
961
+ !dataSource?.collectionPointer ||
962
+ currentDataSource?.collectionPointer?.id !==
963
+ dataSource.collectionPointer.id
964
+ ) {
965
+ return null
966
+ }
967
+ const propertyId = Object.hasOwn(dataSource.propertyIdsByKey, propertyKey)
968
+ ? dataSource.propertyIdsByKey[propertyKey]
969
+ : undefined
970
+ return propertyId === undefined
971
+ ? null
972
+ : this.getPropertyById({ page, propertyId })
973
+ }
974
+
975
+ updatePage(args: {
976
+ pageId: NotionPageId
977
+ properties?: PageUpdatePayload["properties"]
978
+ icon?: PageUpdatePayload["icon"]
979
+ cover?: PageUpdatePayload["cover"]
980
+ is_archived?: PageUpdatePayload["is_archived"]
981
+ dataSource: NotionDataSource | undefined
982
+ }): Promise<BridgeMessagePayload<UpdatePageResultMessage>> {
983
+ const operation = async (): Promise<
984
+ BridgeMessagePayload<UpdatePageResultMessage>
985
+ > => {
986
+ const { dataSource } = args
987
+ const dataSourceId = dataSource?.collectionPointer?.id
988
+ const resolved = resolvePropertyWriteMapForDataSource({
989
+ dataSource,
990
+ properties: args.properties === undefined ? {} : args.properties,
898
991
  })
899
- if (unmappedKey !== undefined) {
900
- return Promise.resolve({
901
- status: "error",
902
- error: {
903
- code: "unmapped_property",
904
- message: `Cannot resolve property key "${unmappedKey}" on this page.`,
905
- isRetryable: false,
906
- },
907
- })
992
+ if (resolved.status === "error") {
993
+ return resolved
908
994
  }
909
- }
910
- const resolved = resolvePropertyWriteMapForDataSource({
911
- dataSource,
912
- properties: args.properties ?? {},
913
- operationName: "page.update",
914
- })
915
- if (resolved.status === "error") {
916
- return Promise.resolve(resolved)
917
- }
918
- const isArchived = args.is_archived
919
- return new Promise(resolve => {
920
995
  if (
921
- (args.properties === undefined ||
922
- Object.keys(args.properties).length === 0) &&
996
+ Object.keys(args.properties ?? {}).length === 0 &&
923
997
  args.icon === undefined &&
924
998
  args.cover === undefined &&
925
- isArchived === undefined
999
+ args.is_archived === undefined
926
1000
  ) {
927
- resolve({
1001
+ return {
928
1002
  status: "error",
929
1003
  error: {
930
1004
  code: "invalid_page_update",
931
1005
  message: "updatePage requires at least one property.",
932
1006
  isRetryable: false,
933
1007
  },
934
- })
935
- return
1008
+ }
936
1009
  }
937
-
938
- const requestId = this.pendingUpdatePage.allocate(resolve)
939
- const outbound: UpdatePageMessage = {
1010
+ const outbound: Omit<UpdatePageMessage, "requestId"> = {
940
1011
  type: "updatePage",
941
- requestId,
942
1012
  dataSourceId,
943
1013
  pageId: args.pageId,
944
1014
  }
@@ -951,47 +1021,29 @@ export class SandboxBridge {
951
1021
  if (args.cover !== undefined) {
952
1022
  outbound.cover = args.cover
953
1023
  }
954
- if (isArchived !== undefined) {
955
- outbound.archived = isArchived
1024
+ if (args.is_archived !== undefined) {
1025
+ outbound.archived = args.is_archived
1026
+ }
1027
+ return new Promise<BridgeMessagePayload<UpdatePageResultMessage>>(
1028
+ resolve => {
1029
+ const requestId = this.pendingUpdatePage.allocate(resolve)
1030
+ this.postToHost({ ...outbound, requestId })
1031
+ },
1032
+ )
1033
+ }
1034
+ const pending = this.pendingPageUpdates.get(args.pageId)
1035
+ const result = pending ? pending.then(operation) : operation()
1036
+ const finished = result.then(
1037
+ () => undefined,
1038
+ () => undefined,
1039
+ )
1040
+ this.pendingPageUpdates.set(args.pageId, finished)
1041
+ void finished.then(() => {
1042
+ if (this.pendingPageUpdates.get(args.pageId) === finished) {
1043
+ this.pendingPageUpdates.delete(args.pageId)
956
1044
  }
957
- this.postToHost(outbound)
958
- })
959
- }
960
-
961
- /**
962
- * Builds an SDK page object from loaded page data and wires its methods to the bridge.
963
- * Unlike `pages.create`, this does not send a create request or create a page in Notion.
964
- */
965
- buildNotionPage(args: {
966
- page: InferOutput<typeof notionPageDataSchema>
967
- dataSourceId: NotionDataSourceId | undefined
968
- }): NotionPage {
969
- const { page, dataSourceId } = args
970
- const dataSource =
971
- this.hostState.status === "initialized" && dataSourceId !== undefined
972
- ? this.hostState.dataSources.find(
973
- source => source.collectionPointer?.id === dataSourceId,
974
- )
975
- : undefined
976
- return toNotionPageFromNotionPageData({
977
- page,
978
- dataSource,
979
- getDataSource: () => {
980
- if (
981
- this.hostState.status !== "initialized" ||
982
- dataSourceId === undefined
983
- ) {
984
- return undefined
985
- }
986
- return this.hostState.dataSources.find(
987
- source =>
988
- source.key === dataSource?.key &&
989
- source.collectionPointer?.id === dataSourceId,
990
- )
991
- },
992
- update: (payload, updateDataSourceId) =>
993
- this.updatePage({ ...payload, pageId: page.id }, updateDataSourceId),
994
1045
  })
1046
+ return result
995
1047
  }
996
1048
 
997
1049
  /**
@@ -1009,15 +1061,8 @@ export class SandboxBridge {
1009
1061
  switch (parent.type) {
1010
1062
  case "page_id":
1011
1063
  return { status: "ok", parent, dataSource: undefined }
1012
- case "data_source_id": {
1013
- const dataSource =
1014
- this.hostState.status === "initialized"
1015
- ? this.hostState.dataSources.find(
1016
- entry => entry.collectionPointer?.id === parent.data_source_id,
1017
- )
1018
- : undefined
1019
- return { status: "ok", parent, dataSource }
1020
- }
1064
+ case "data_source_id":
1065
+ return { status: "ok", parent, dataSource: undefined }
1021
1066
  case "data_source_key": {
1022
1067
  if (this.hostState.status !== "initialized") {
1023
1068
  return {
@@ -1235,9 +1280,3 @@ function formatInvalidHostReason(
1235
1280
  const extra = issues.length > 1 ? ` (+${issues.length - 1} more)` : ""
1236
1281
  return `Could not parse ${labelled}: ${detail}${extra}`
1237
1282
  }
1238
-
1239
- type UpdatePageArgs = Omit<
1240
- UpdatePageMessage,
1241
- "type" | "requestId" | "archived" | "properties" | "dataSourceId"
1242
- > &
1243
- PageUpdatePayload
@@ -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
  }
@@ -1,90 +1,47 @@
1
1
  import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
- import type { NotionDataSourceId } from "@notionhq/custom-blocks-protocol/ids.js"
3
- import type { BridgeMessagePayload } from "@notionhq/custom-blocks-protocol/messages/messagePayload.js"
4
- import type { UpdatePageResultMessage } from "@notionhq/custom-blocks-protocol/messages/updatePageResult.js"
5
2
  import type { notionPageDataSchema } from "@notionhq/custom-blocks-protocol/pages/page.js"
6
3
  import type { InferOutput } from "valibot"
7
- import type {
8
- NotionPage,
9
- PageUpdatePayload,
10
- UpdatePageResult,
11
- } from "../types.js"
4
+ import type { NotionPage } from "../types.js"
12
5
 
13
6
  export function toNotionPageFromNotionPageData(args: {
14
7
  page: InferOutput<typeof notionPageDataSchema>
15
- dataSource: NotionDataSource | undefined
16
- getDataSource: () => NotionDataSource | undefined
17
- update: (
18
- payload: PageUpdatePayload,
19
- dataSourceId: NotionDataSourceId | undefined,
20
- ) => Promise<BridgeMessagePayload<UpdatePageResultMessage>>
8
+ dataSourceKey: string | undefined
9
+ getPropertyById: NotionPage["getPropertyById"]
10
+ getPropertyByKey: NotionPage["getPropertyByKey"]
11
+ updateById: NotionPage["updateById"]
12
+ updateByKey: NotionPage["updateByKey"]
21
13
  }): NotionPage {
22
- const { page: bridgePage, dataSource } = args
23
- const getPropertyById = (id: string) =>
24
- Object.values(sdkPage.properties).find(value => value?.id === id) ?? null
25
- let pending: Promise<void> | undefined
26
- const updatePage = (
27
- payload: PageUpdatePayload,
28
- dataSourceId: NotionDataSourceId | undefined,
29
- ): Promise<UpdatePageResult> => {
30
- const operation = async (): Promise<UpdatePageResult> => {
31
- const result = await args.update(payload, dataSourceId)
32
- if (result.status === "error") {
33
- return result
34
- }
35
- Object.assign(sdkPage, result.page)
36
- return { status: "success", page: sdkPage }
37
- }
38
- const result = pending ? pending.then(operation) : operation()
39
- const finished = result.then(
40
- () => undefined,
41
- () => undefined,
42
- )
43
- pending = finished
44
- void finished.then(() => {
45
- if (pending === finished) {
46
- pending = undefined
47
- }
48
- })
49
- return result
14
+ return {
15
+ ...args.page,
16
+ dataSourceKey: args.dataSourceKey ?? null,
17
+ getPropertyById: args.getPropertyById,
18
+ getPropertyByKey: args.getPropertyByKey,
19
+ updateById: args.updateById,
20
+ updateByKey: args.updateByKey,
21
+ archive: () => args.updateById({ is_archived: true }),
22
+ unarchive: () => args.updateById({ is_archived: false }),
50
23
  }
51
- const updateById = (payload: PageUpdatePayload) =>
52
- updatePage(payload, undefined)
53
- const updateByKey = (
54
- payload: PageUpdatePayload,
55
- ): Promise<UpdatePageResult> => {
56
- const dataSourceId = dataSource?.collectionPointer?.id
57
- if (dataSourceId === undefined) {
58
- return Promise.resolve({
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 {
59
37
  status: "error",
60
38
  error: {
61
- code: "unmapped_data_source",
62
- message: "This page has no bound data source context.",
39
+ code: "unmapped_property",
40
+ message: "Key-based property updates require data source context.",
63
41
  isRetryable: false,
64
42
  },
65
- })
43
+ }
66
44
  }
67
- return updatePage(payload, dataSourceId)
68
- }
69
- const methods = {
70
- getPropertyById,
71
- getPropertyByKey: (key: string) => {
72
- const source = args.getDataSource()
73
- const id =
74
- source && Object.hasOwn(source.propertyIdsByKey, key)
75
- ? source.propertyIdsByKey[key]
76
- : undefined
77
- return id === undefined ? null : getPropertyById(id)
78
- },
79
- updateById,
80
- updateByKey,
81
- archive: () => updateById({ is_archived: true }),
82
- unarchive: () => updateById({ is_archived: false }),
83
- }
84
- const sdkPage: NotionPage = {
85
- ...bridgePage,
86
- dataSourceKey: dataSource?.key ?? null,
87
- ...methods,
45
+ return args.update(payload)
88
46
  }
89
- return sdkPage
90
47
  }