@superdurable/connector-notion 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/dex-connector.json +206 -0
- package/dist/chunk-LZTWSFD4.js +390 -0
- package/dist/connection-CFdIOEsZ.d.ts +762 -0
- package/dist/index.d.ts +352 -0
- package/dist/index.js +1187 -0
- package/dist/mock.d.ts +159 -0
- package/dist/mock.js +381 -0
- package/package.json +58 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1187 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigSchema,
|
|
3
|
+
Connection,
|
|
4
|
+
ConnectorID,
|
|
5
|
+
CreatePageBranch,
|
|
6
|
+
CreatePageBranchCreated,
|
|
7
|
+
CreatePageBranchDefect,
|
|
8
|
+
CreatePageBranchInvalidResponse,
|
|
9
|
+
CreatePageBranchNotFound,
|
|
10
|
+
CreatePageBranchProviderRejected,
|
|
11
|
+
CreatePageBranchUncertain,
|
|
12
|
+
CreatePageDefinition,
|
|
13
|
+
CreatePageInputSchema,
|
|
14
|
+
CreatePageMetadata,
|
|
15
|
+
CreatePageOutputSchema,
|
|
16
|
+
DateRangeSchema,
|
|
17
|
+
GetPageBranch,
|
|
18
|
+
GetPageBranchDefect,
|
|
19
|
+
GetPageBranchFound,
|
|
20
|
+
GetPageBranchInvalidResponse,
|
|
21
|
+
GetPageBranchNotFound,
|
|
22
|
+
GetPageBranchProviderRejected,
|
|
23
|
+
GetPageDefinition,
|
|
24
|
+
GetPageInputSchema,
|
|
25
|
+
GetPageMetadata,
|
|
26
|
+
GetPageOutputSchema,
|
|
27
|
+
PageContentSchema,
|
|
28
|
+
PagePropertySchema,
|
|
29
|
+
PageSchema,
|
|
30
|
+
ParentSchema,
|
|
31
|
+
PropertyValueSchema,
|
|
32
|
+
ProviderID,
|
|
33
|
+
QueryDatabaseBranch,
|
|
34
|
+
QueryDatabaseBranchDefect,
|
|
35
|
+
QueryDatabaseBranchInvalidResponse,
|
|
36
|
+
QueryDatabaseBranchNotFound,
|
|
37
|
+
QueryDatabaseBranchProviderRejected,
|
|
38
|
+
QueryDatabaseBranchQueried,
|
|
39
|
+
QueryDatabaseDefinition,
|
|
40
|
+
QueryDatabaseInputSchema,
|
|
41
|
+
QueryDatabaseMetadata,
|
|
42
|
+
QueryDatabaseOutputSchema,
|
|
43
|
+
QueryFilterSchema,
|
|
44
|
+
QuerySortSchema,
|
|
45
|
+
SearchBranch,
|
|
46
|
+
SearchBranchDefect,
|
|
47
|
+
SearchBranchInvalidResponse,
|
|
48
|
+
SearchBranchNoMatch,
|
|
49
|
+
SearchBranchProviderRejected,
|
|
50
|
+
SearchBranchSearched,
|
|
51
|
+
SearchDefinition,
|
|
52
|
+
SearchInputSchema,
|
|
53
|
+
SearchMatchSchema,
|
|
54
|
+
SearchMetadata,
|
|
55
|
+
SearchOutputSchema,
|
|
56
|
+
UpdatePagePropertiesBranch,
|
|
57
|
+
UpdatePagePropertiesBranchDefect,
|
|
58
|
+
UpdatePagePropertiesBranchInvalidResponse,
|
|
59
|
+
UpdatePagePropertiesBranchNotFound,
|
|
60
|
+
UpdatePagePropertiesBranchProviderRejected,
|
|
61
|
+
UpdatePagePropertiesBranchUpdated,
|
|
62
|
+
UpdatePagePropertiesDefinition,
|
|
63
|
+
UpdatePagePropertiesInputSchema,
|
|
64
|
+
UpdatePagePropertiesMetadata,
|
|
65
|
+
UpdatePagePropertiesOutputSchema,
|
|
66
|
+
decodeCredentials,
|
|
67
|
+
newConnection,
|
|
68
|
+
newConnectionWithOperations,
|
|
69
|
+
newProjectConnection
|
|
70
|
+
} from "./chunk-LZTWSFD4.js";
|
|
71
|
+
|
|
72
|
+
// src/generated/steps.ts
|
|
73
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
74
|
+
function newSearchStep(configuration) {
|
|
75
|
+
const { connection, connectionName, searched, noMatch, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
76
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
77
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.search(), connection: connection.reference, branches: [
|
|
78
|
+
goToBranch("searched", searched),
|
|
79
|
+
...noMatch ? [goToBranch("noMatch", noMatch)] : [],
|
|
80
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
81
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
82
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
83
|
+
] });
|
|
84
|
+
}
|
|
85
|
+
function newQueryDatabaseStep(configuration) {
|
|
86
|
+
const { connection, connectionName, queried, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
87
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
88
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.queryDatabase(), connection: connection.reference, branches: [
|
|
89
|
+
goToBranch("queried", queried),
|
|
90
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
91
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
92
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
93
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
94
|
+
] });
|
|
95
|
+
}
|
|
96
|
+
function newGetPageStep(configuration) {
|
|
97
|
+
const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
98
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
99
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getPage(), connection: connection.reference, branches: [
|
|
100
|
+
goToBranch("found", found),
|
|
101
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
102
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
103
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
104
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
105
|
+
] });
|
|
106
|
+
}
|
|
107
|
+
function newCreatePageStep(configuration) {
|
|
108
|
+
const { connection, connectionName, created, notFound, providerRejected, uncertain, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
109
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
110
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.createPage(), connection: connection.reference, branches: [
|
|
111
|
+
goToBranch("created", created),
|
|
112
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
113
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
114
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
115
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
116
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
117
|
+
] });
|
|
118
|
+
}
|
|
119
|
+
function newUpdatePagePropertiesStep(configuration) {
|
|
120
|
+
const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
121
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
122
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.updatePageProperties(), connection: connection.reference, branches: [
|
|
123
|
+
goToBranch("updated", updated),
|
|
124
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
125
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
126
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
127
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
128
|
+
] });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/project.ts
|
|
132
|
+
import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
|
|
133
|
+
import { z } from "zod";
|
|
134
|
+
|
|
135
|
+
// src/client.ts
|
|
136
|
+
import { ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
|
|
137
|
+
import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
138
|
+
import { CredentialBrokerUnavailableError } from "@superdurable/connectors-sdk/projectconfig";
|
|
139
|
+
|
|
140
|
+
// src/operations.ts
|
|
141
|
+
import { isIP } from "net";
|
|
142
|
+
import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
|
|
143
|
+
import { newFence } from "@superdurable/connectors-sdk/singledispatch";
|
|
144
|
+
var emptyParent = { type: "" };
|
|
145
|
+
var emptyPage = { id: "", title: "", parent: emptyParent, inTrash: false, archived: false, properties: {} };
|
|
146
|
+
var emptyContent = { text: "", blockCount: 0, hasMoreBlocks: false, textTruncated: false, nestedBlockCount: 0, skippedBlockCount: 0 };
|
|
147
|
+
var emptySearch = { matches: [], hasMore: false };
|
|
148
|
+
var emptyQuery = { dataSourceId: "", pages: [], hasMore: false, resultLimitReached: false };
|
|
149
|
+
var emptyGet = { page: emptyPage, content: emptyContent };
|
|
150
|
+
var emptyUpdate = { page: emptyPage };
|
|
151
|
+
var emptyCreate = {};
|
|
152
|
+
var SearchOperation = class {
|
|
153
|
+
/** Bind one Notion client. */
|
|
154
|
+
constructor(client) {
|
|
155
|
+
this.client = client;
|
|
156
|
+
}
|
|
157
|
+
client;
|
|
158
|
+
/** Return the manifest definition. */
|
|
159
|
+
definition() {
|
|
160
|
+
return SearchDefinition;
|
|
161
|
+
}
|
|
162
|
+
/** Validate and search one bounded page. */
|
|
163
|
+
async invoke(call, input) {
|
|
164
|
+
let request;
|
|
165
|
+
try {
|
|
166
|
+
const query = (input.query ?? "").trim();
|
|
167
|
+
if ([...query].length > 1e3) throw new Error("query is too long");
|
|
168
|
+
if (input.objectType && input.objectType !== "page" && input.objectType !== "data_source") throw new Error("invalid objectType");
|
|
169
|
+
if (input.sortDirection && input.sortDirection !== "ascending" && input.sortDirection !== "descending") throw new Error("invalid sortDirection");
|
|
170
|
+
const pageSize = input.pageSize || 20;
|
|
171
|
+
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) throw new Error("invalid pageSize");
|
|
172
|
+
const cursor = validateCursor(input.startCursor ?? "");
|
|
173
|
+
request = { ...query ? { query } : {}, ...input.objectType ? { filter: { property: "object", value: input.objectType } } : {}, ...input.sortDirection ? { sort: { timestamp: "last_edited_time", direction: input.sortDirection } } : {}, ...cursor ? { start_cursor: cursor } : {}, page_size: pageSize };
|
|
174
|
+
} catch {
|
|
175
|
+
return queryBranch("search", "defect", emptySearch, failure("search", "VALIDATION", "invalid search input"));
|
|
176
|
+
}
|
|
177
|
+
const result = await this.client.exchange(call, "search", "search", "POST", "/search", request);
|
|
178
|
+
if (!("response" in result)) return readAttempt("search", result, emptySearch, "providerRejected");
|
|
179
|
+
try {
|
|
180
|
+
const body = objectJSON(result.response.body);
|
|
181
|
+
const results = arrayOrEmpty(body.results);
|
|
182
|
+
if (results.length > Number(request.page_size)) throw new Error("too many results");
|
|
183
|
+
const nextCursor = validateCursor(text(body.next_cursor));
|
|
184
|
+
const matches = [];
|
|
185
|
+
for (const value of results) {
|
|
186
|
+
const resource = object(value);
|
|
187
|
+
if (resource.object !== "page" && resource.object !== "data_source") continue;
|
|
188
|
+
const id = parseID(string(resource.id));
|
|
189
|
+
const title = resource.object === "page" ? titleOfProperties(decodeProperties(resource.properties)) : joinRichText(resource.title);
|
|
190
|
+
matches.push({
|
|
191
|
+
objectType: resource.object,
|
|
192
|
+
id,
|
|
193
|
+
title,
|
|
194
|
+
parent: decodeParent(resource.parent),
|
|
195
|
+
inTrash: resource.in_trash === true,
|
|
196
|
+
...text(resource.url) ? { url: text(resource.url) } : {},
|
|
197
|
+
...text(resource.last_edited_time) ? { lastEditedTime: text(resource.last_edited_time) } : {}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
const output = { matches, hasMore: body.has_more === true, ...body.has_more === true && nextCursor ? { nextCursor } : {} };
|
|
201
|
+
return queryBranch("search", matches.length === 0 && !request.start_cursor ? "noMatch" : "searched", output, matches.length === 0 && !request.start_cursor ? failure("search", "NOT_FOUND", "no title matched") : void 0, result.receipt);
|
|
202
|
+
} catch {
|
|
203
|
+
return queryBranch("search", "invalidResponse", emptySearch, failure("search", "PROTOCOL", "Notion returned an invalid search page"), result.receipt);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
var QueryDatabaseOperation = class {
|
|
208
|
+
/** Bind one Notion client. */
|
|
209
|
+
constructor(client) {
|
|
210
|
+
this.client = client;
|
|
211
|
+
}
|
|
212
|
+
client;
|
|
213
|
+
/** Return the manifest definition. */
|
|
214
|
+
definition() {
|
|
215
|
+
return QueryDatabaseDefinition;
|
|
216
|
+
}
|
|
217
|
+
/** Resolve the data source and query rows. */
|
|
218
|
+
async invoke(call, input) {
|
|
219
|
+
let selection;
|
|
220
|
+
let body;
|
|
221
|
+
let properties;
|
|
222
|
+
try {
|
|
223
|
+
selection = selectDataSource(input.dataSourceId, input.databaseId);
|
|
224
|
+
const pageSize = input.pageSize || 50;
|
|
225
|
+
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) throw new Error("invalid pageSize");
|
|
226
|
+
const cursor = validateCursor(input.startCursor ?? "");
|
|
227
|
+
properties = input.properties ?? [];
|
|
228
|
+
if (properties.length > 100 || properties.some((value) => !value.trim() || value.trim() !== value || [...value].length > 256)) throw new Error("invalid properties");
|
|
229
|
+
if ((input.sorts?.length ?? 0) > 10) throw new Error("too many sorts");
|
|
230
|
+
body = { ...input.filter ? { filter: encodeFilter(input.filter) } : {}, ...input.sorts?.length ? { sorts: input.sorts.map(encodeSort) } : {}, ...cursor ? { start_cursor: cursor } : {}, page_size: pageSize, result_type: "page" };
|
|
231
|
+
} catch {
|
|
232
|
+
return queryBranch("queryDatabase", "defect", emptyQuery, failure("queryDatabase", "VALIDATION", "invalid query input"));
|
|
233
|
+
}
|
|
234
|
+
const resolved = await resolveDataSource(this.client, call, "queryDatabase", selection);
|
|
235
|
+
if (typeof resolved !== "string") return readAttempt("queryDatabase", resolved, emptyQuery, "providerRejected", "notFound");
|
|
236
|
+
const output = { ...emptyQuery, dataSourceId: resolved };
|
|
237
|
+
const suffix = properties.length ? `?${properties.map((property) => `filter_properties%5B%5D=${queryEscape(property)}`).join("&")}` : "";
|
|
238
|
+
const result = await this.client.exchange(call, "queryDatabase", "database query", "POST", `/data_sources/${pathEscape(resolved)}/query${suffix}`, body, "read", void 0, void 0, resolved);
|
|
239
|
+
if (!("response" in result)) return readAttempt("queryDatabase", result, output, "providerRejected", "notFound");
|
|
240
|
+
try {
|
|
241
|
+
const page = objectJSON(result.response.body);
|
|
242
|
+
const results = arrayOrEmpty(page.results);
|
|
243
|
+
if (results.length > Number(body.page_size)) throw new Error("too many rows");
|
|
244
|
+
const nextCursor = validateCursor(text(page.next_cursor));
|
|
245
|
+
return queryBranch("queryDatabase", "queried", {
|
|
246
|
+
dataSourceId: resolved,
|
|
247
|
+
pages: results.map(decodePage),
|
|
248
|
+
hasMore: page.has_more === true,
|
|
249
|
+
resultLimitReached: objectOrEmpty(page.request_status).incomplete_reason === "query_result_limit_reached",
|
|
250
|
+
...page.has_more === true && nextCursor ? { nextCursor } : {}
|
|
251
|
+
}, void 0, result.receipt);
|
|
252
|
+
} catch {
|
|
253
|
+
return queryBranch("queryDatabase", "invalidResponse", output, failure("queryDatabase", "PROTOCOL", "Notion returned an invalid query page"), result.receipt);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
var GetPageOperation = class {
|
|
258
|
+
/** Bind one Notion client. */
|
|
259
|
+
constructor(client) {
|
|
260
|
+
this.client = client;
|
|
261
|
+
}
|
|
262
|
+
client;
|
|
263
|
+
/** Return the manifest definition. */
|
|
264
|
+
definition() {
|
|
265
|
+
return GetPageDefinition;
|
|
266
|
+
}
|
|
267
|
+
/** Read metadata and optionally render block content. */
|
|
268
|
+
async invoke(call, input) {
|
|
269
|
+
let pageId;
|
|
270
|
+
let maxBlocks;
|
|
271
|
+
let maxTextCharacters;
|
|
272
|
+
try {
|
|
273
|
+
pageId = parseID(input.pageId);
|
|
274
|
+
maxBlocks = input.maxBlocks || 100;
|
|
275
|
+
maxTextCharacters = input.maxTextCharacters || 2e4;
|
|
276
|
+
if (!Number.isInteger(maxBlocks) || maxBlocks < 1 || maxBlocks > 500 || !Number.isInteger(maxTextCharacters) || maxTextCharacters < 1 || maxTextCharacters > 1e5) throw new Error("invalid content bounds");
|
|
277
|
+
} catch {
|
|
278
|
+
return queryBranch("getPage", "defect", emptyGet, failure("getPage", "VALIDATION", "invalid page input"));
|
|
279
|
+
}
|
|
280
|
+
const result = await this.client.exchange(call, "getPage", "page read", "GET", `/pages/${pathEscape(pageId)}`, void 0, "read", void 0, void 0, pageId);
|
|
281
|
+
if (!("response" in result)) return readAttempt("getPage", result, emptyGet, "providerRejected", "notFound");
|
|
282
|
+
let page;
|
|
283
|
+
try {
|
|
284
|
+
page = decodePage(objectJSON(result.response.body));
|
|
285
|
+
} catch {
|
|
286
|
+
return queryBranch("getPage", "invalidResponse", emptyGet, failure("getPage", "PROTOCOL", "Notion returned an unusable page"), result.receipt);
|
|
287
|
+
}
|
|
288
|
+
if (input.skipContent) return queryBranch("getPage", "found", { page, content: emptyContent }, void 0, result.receipt);
|
|
289
|
+
const content = { ...emptyContent };
|
|
290
|
+
const lines = [];
|
|
291
|
+
let cursor = "";
|
|
292
|
+
let listNumber = 0;
|
|
293
|
+
for (; ; ) {
|
|
294
|
+
const query = `page_size=${Math.min(100, maxBlocks - content.blockCount)}${cursor ? `&start_cursor=${queryEscape(cursor)}` : ""}`;
|
|
295
|
+
const blocks = await this.client.exchange(call, "getPage", "page content read", "GET", `/blocks/${pathEscape(page.id)}/children?${query}`, void 0, "read", void 0, void 0, pageId);
|
|
296
|
+
if (!("response" in blocks)) return readAttempt("getPage", blocks, emptyGet, "providerRejected", "notFound", result.receipt);
|
|
297
|
+
let blockList;
|
|
298
|
+
try {
|
|
299
|
+
blockList = objectJSON(blocks.response.body);
|
|
300
|
+
if (array(blockList.results).length > Math.min(100, maxBlocks - content.blockCount)) throw new Error("too many blocks");
|
|
301
|
+
} catch {
|
|
302
|
+
return queryBranch("getPage", "invalidResponse", emptyGet, failure("getPage", "PROTOCOL", "Notion returned an invalid block list"), result.receipt);
|
|
303
|
+
}
|
|
304
|
+
for (const value of array(blockList.results)) {
|
|
305
|
+
const block = object(value);
|
|
306
|
+
content.blockCount++;
|
|
307
|
+
if (block.has_children === true) content.nestedBlockCount++;
|
|
308
|
+
if (block.type !== "numbered_list_item") listNumber = 0;
|
|
309
|
+
const rendered = renderBlock(block, listNumber);
|
|
310
|
+
if (block.type === "numbered_list_item") listNumber++;
|
|
311
|
+
if (rendered === null) {
|
|
312
|
+
content.skippedBlockCount++;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (content.textTruncated) continue;
|
|
316
|
+
const remaining = maxTextCharacters - [...lines.join("\n")].length - (lines.length ? 1 : 0);
|
|
317
|
+
if ([...rendered].length > remaining) {
|
|
318
|
+
content.textTruncated = true;
|
|
319
|
+
if (remaining > 0) lines.push([...rendered].slice(0, remaining).join(""));
|
|
320
|
+
} else lines.push(rendered);
|
|
321
|
+
}
|
|
322
|
+
const next = text(blockList.next_cursor);
|
|
323
|
+
if (blockList.has_more !== true || !next) break;
|
|
324
|
+
if (content.blockCount >= maxBlocks) {
|
|
325
|
+
content.hasMoreBlocks = true;
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
cursor = validateCursor(next);
|
|
330
|
+
} catch {
|
|
331
|
+
return queryBranch("getPage", "invalidResponse", emptyGet, failure("getPage", "PROTOCOL", "invalid block cursor"), result.receipt);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
content.text = lines.join("\n");
|
|
335
|
+
return queryBranch("getPage", "found", { page, content }, void 0, result.receipt);
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
var CreatePageOperation = class {
|
|
339
|
+
/** Bind one Notion client. */
|
|
340
|
+
constructor(client) {
|
|
341
|
+
this.client = client;
|
|
342
|
+
}
|
|
343
|
+
client;
|
|
344
|
+
/** Return the manifest definition. */
|
|
345
|
+
definition() {
|
|
346
|
+
return CreatePageDefinition;
|
|
347
|
+
}
|
|
348
|
+
/** Record the stable call identity without sending it to Notion. */
|
|
349
|
+
idempotencyKey(callId) {
|
|
350
|
+
return callId;
|
|
351
|
+
}
|
|
352
|
+
/** Never repeat a write that may have reached Notion. */
|
|
353
|
+
async invoke(call, input) {
|
|
354
|
+
let fence;
|
|
355
|
+
try {
|
|
356
|
+
fence = newFence(call, 12e4);
|
|
357
|
+
} catch {
|
|
358
|
+
return mutationBranch("createPage", "defect", emptyCreate, failure("createPage", "LOCAL_DEFECT", "page dispatch could not be initialized"));
|
|
359
|
+
}
|
|
360
|
+
const decision = fence.decide();
|
|
361
|
+
if (decision.kind === "failClosed") return newMutationUncertain(emptyCreate, failure("createPage", "PROTOCOL", "page dispatch checkpoint cannot be trusted"), {});
|
|
362
|
+
if (decision.kind === "readBackRequired") {
|
|
363
|
+
const pageId = decision.marker?.providerId;
|
|
364
|
+
if (!pageId) return newMutationUncertain(emptyCreate, failure("createPage", "PROTOCOL", "page may have been sent without a confirmable ID"), {});
|
|
365
|
+
return this.confirmPage(call, pageId, {}, false);
|
|
366
|
+
}
|
|
367
|
+
let selection;
|
|
368
|
+
let properties;
|
|
369
|
+
let children;
|
|
370
|
+
try {
|
|
371
|
+
selection = selectDataSource(input.dataSourceId, input.databaseId);
|
|
372
|
+
properties = encodeProperties(input.properties ?? {});
|
|
373
|
+
children = encodeParagraphs(input.bodyText ?? "");
|
|
374
|
+
} catch {
|
|
375
|
+
return mutationBranch("createPage", "defect", emptyCreate, failure("createPage", "VALIDATION", "invalid page input"));
|
|
376
|
+
}
|
|
377
|
+
const credentials = await this.client.resolveToken(call, "createPage");
|
|
378
|
+
if ("outcome" in credentials) {
|
|
379
|
+
try {
|
|
380
|
+
await fence.recordNotSent();
|
|
381
|
+
} catch {
|
|
382
|
+
return newMutationRetry(failure("createPage", "AVAILABILITY", "credential checkpoint unavailable"));
|
|
383
|
+
}
|
|
384
|
+
return writeFromLookup(credentials.outcome);
|
|
385
|
+
}
|
|
386
|
+
const resolved = await resolveDataSource(this.client, call, "createPage", selection, credentials.token);
|
|
387
|
+
if (typeof resolved !== "string") {
|
|
388
|
+
if (resolved.disposition === "retry") {
|
|
389
|
+
try {
|
|
390
|
+
await fence.recordNotSent();
|
|
391
|
+
} catch {
|
|
392
|
+
return newMutationRetry(failure("createPage", "AVAILABILITY", "lookup checkpoint unavailable"));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return writeFromLookup(resolved);
|
|
396
|
+
}
|
|
397
|
+
const output = { dataSourceId: resolved };
|
|
398
|
+
const body = { parent: { type: "data_source_id", data_source_id: resolved }, properties, ...children.length ? { children } : {} };
|
|
399
|
+
let result;
|
|
400
|
+
try {
|
|
401
|
+
result = await fence.dispatch((signal) => this.client.exchange(call, "createPage", "page creation", "POST", "/pages", body, "unkeyedWrite", signal, credentials.token));
|
|
402
|
+
} catch {
|
|
403
|
+
return newMutationRetry(failure("createPage", "TRANSPORT", "page dispatch checkpoint unavailable"));
|
|
404
|
+
}
|
|
405
|
+
if (!("response" in result)) {
|
|
406
|
+
if (result.disposition === "retry") {
|
|
407
|
+
try {
|
|
408
|
+
if (result.isProvablyNotSent) await fence.recordCanResend();
|
|
409
|
+
else await fence.recordNotSent();
|
|
410
|
+
} catch {
|
|
411
|
+
return newMutationRetry(failure("createPage", "AVAILABILITY", "retry checkpoint unavailable"));
|
|
412
|
+
}
|
|
413
|
+
return newMutationRetry(result.failure, result.retryAfterMs);
|
|
414
|
+
}
|
|
415
|
+
if (result.disposition === "committed" && result.providerId) {
|
|
416
|
+
try {
|
|
417
|
+
await fence.recordProviderId(result.providerId);
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
return this.confirmPage(call, result.providerId, result.receipt, true, resolved);
|
|
421
|
+
}
|
|
422
|
+
if (result.disposition === "notFound") return mutationBranch("createPage", "notFound", output, result.failure, result.receipt);
|
|
423
|
+
if (result.disposition === "providerRejected") return mutationBranch("createPage", "providerRejected", output, result.failure, result.receipt);
|
|
424
|
+
if (result.disposition === "defect") return mutationBranch("createPage", "defect", output, result.failure, result.receipt);
|
|
425
|
+
return newMutationUncertain(output, result.failure, result.receipt);
|
|
426
|
+
}
|
|
427
|
+
let page;
|
|
428
|
+
try {
|
|
429
|
+
page = decodePage(objectJSON(result.response.body));
|
|
430
|
+
} catch {
|
|
431
|
+
try {
|
|
432
|
+
const body2 = objectJSON(result.response.body);
|
|
433
|
+
if (body2.object === "page" && typeof body2.id === "string") {
|
|
434
|
+
const pageId = parseID(body2.id);
|
|
435
|
+
try {
|
|
436
|
+
await fence.recordProviderId(pageId);
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
return this.confirmPage(call, pageId, result.receipt, false, resolved);
|
|
440
|
+
}
|
|
441
|
+
} catch {
|
|
442
|
+
}
|
|
443
|
+
return newMutationUncertain(output, failure("createPage", "PROTOCOL", "Notion accepted the page but returned an unusable response"), result.receipt);
|
|
444
|
+
}
|
|
445
|
+
try {
|
|
446
|
+
await fence.recordProviderId(page.id);
|
|
447
|
+
} catch {
|
|
448
|
+
}
|
|
449
|
+
return mutationBranch("createPage", "created", { dataSourceId: resolved, pageId: page.id, page }, void 0, { ...result.receipt, providerObjectId: page.id });
|
|
450
|
+
}
|
|
451
|
+
async confirmPage(call, pageId, receipt, confirmedAfterTimeout, dataSourceId = "") {
|
|
452
|
+
const output = { ...dataSourceId ? { dataSourceId } : {}, pageId, ...confirmedAfterTimeout ? { confirmedAfterTimeout: true } : {} };
|
|
453
|
+
const result = await this.client.exchange(call, "createPage", "page creation", "GET", `/pages/${pathEscape(pageId)}`);
|
|
454
|
+
if (!("response" in result)) return result.disposition === "retry" ? newMutationRetry(result.failure, result.retryAfterMs) : newMutationUncertain(output, failure("createPage", "PROTOCOL", "accepted page could not be confirmed"), { ...receipt, providerObjectId: pageId });
|
|
455
|
+
try {
|
|
456
|
+
const page = decodePage(objectJSON(result.response.body));
|
|
457
|
+
if (page.id !== pageId) throw new Error("page ID mismatch");
|
|
458
|
+
return mutationBranch("createPage", "created", { ...output, dataSourceId: page.parent.type === "data_source_id" ? page.parent.id : dataSourceId, page }, void 0, { ...receipt, providerObjectId: pageId });
|
|
459
|
+
} catch {
|
|
460
|
+
return newMutationUncertain(output, failure("createPage", "PROTOCOL", "accepted page read-back did not match"), { ...receipt, providerObjectId: pageId });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
var UpdatePagePropertiesOperation = class {
|
|
465
|
+
/** Bind one Notion client. */
|
|
466
|
+
constructor(client) {
|
|
467
|
+
this.client = client;
|
|
468
|
+
}
|
|
469
|
+
client;
|
|
470
|
+
/** Return the manifest definition. */
|
|
471
|
+
definition() {
|
|
472
|
+
return UpdatePagePropertiesDefinition;
|
|
473
|
+
}
|
|
474
|
+
/** Repeating absolute values converges on the same page state. */
|
|
475
|
+
idempotencyKey(callId) {
|
|
476
|
+
return callId;
|
|
477
|
+
}
|
|
478
|
+
/** Validate and send one repeat-safe update. */
|
|
479
|
+
async invoke(call, input) {
|
|
480
|
+
let pageId;
|
|
481
|
+
let properties;
|
|
482
|
+
try {
|
|
483
|
+
pageId = parseID(input.pageId);
|
|
484
|
+
if (!input.properties || Object.keys(input.properties).length === 0) throw new Error("properties required");
|
|
485
|
+
properties = encodeProperties(input.properties);
|
|
486
|
+
} catch {
|
|
487
|
+
return mutationBranch("updatePageProperties", "defect", emptyUpdate, failure("updatePageProperties", "VALIDATION", "invalid page update"));
|
|
488
|
+
}
|
|
489
|
+
const result = await this.client.exchange(call, "updatePageProperties", "page update", "PATCH", `/pages/${pathEscape(pageId)}`, { properties }, "repeatableWrite", void 0, void 0, pageId);
|
|
490
|
+
if (!("response" in result)) return writeAttempt("updatePageProperties", result, emptyUpdate, "providerRejected", "notFound");
|
|
491
|
+
try {
|
|
492
|
+
const page = decodePage(objectJSON(result.response.body));
|
|
493
|
+
if (page.id !== pageId) throw new Error("page ID mismatch");
|
|
494
|
+
return mutationBranch("updatePageProperties", "updated", { page }, void 0, result.receipt);
|
|
495
|
+
} catch {
|
|
496
|
+
return mutationBranch("updatePageProperties", "invalidResponse", emptyUpdate, failure("updatePageProperties", "PROTOCOL", "Notion returned an unusable page after update"), result.receipt);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
function queryBranch(operation, branch, value, issue, receipt = {}) {
|
|
501
|
+
void operation;
|
|
502
|
+
return newQueryBranch(branch, value, receipt, issue);
|
|
503
|
+
}
|
|
504
|
+
function mutationBranch(operation, branch, value, issue, receipt = {}) {
|
|
505
|
+
void operation;
|
|
506
|
+
return newMutationBranch(branch, value, receipt, issue);
|
|
507
|
+
}
|
|
508
|
+
function readAttempt(operation, result, zero, rejected, notFound = rejected, receipt = result.receipt) {
|
|
509
|
+
if (result.disposition === "retry") return newQueryRetry(result.failure, result.retryAfterMs);
|
|
510
|
+
return queryBranch(operation, result.disposition === "notFound" ? notFound : result.disposition === "providerRejected" ? rejected : result.disposition === "defect" ? "defect" : "invalidResponse", zero, result.failure, receipt);
|
|
511
|
+
}
|
|
512
|
+
function writeAttempt(operation, result, zero, rejected, notFound = rejected) {
|
|
513
|
+
if (result.disposition === "retry") return newMutationRetry(result.failure, result.retryAfterMs);
|
|
514
|
+
return mutationBranch(operation, result.disposition === "notFound" ? notFound : result.disposition === "providerRejected" ? rejected : result.disposition === "defect" ? "defect" : "invalidResponse", zero, result.failure, result.receipt);
|
|
515
|
+
}
|
|
516
|
+
function writeFromLookup(result) {
|
|
517
|
+
return writeAttempt("createPage", result, emptyCreate, "providerRejected", "notFound");
|
|
518
|
+
}
|
|
519
|
+
function object(value) {
|
|
520
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected object");
|
|
521
|
+
return value;
|
|
522
|
+
}
|
|
523
|
+
function objectOrEmpty(value) {
|
|
524
|
+
try {
|
|
525
|
+
return object(value);
|
|
526
|
+
} catch {
|
|
527
|
+
return {};
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function array(value) {
|
|
531
|
+
if (!Array.isArray(value)) throw new Error("expected array");
|
|
532
|
+
return value;
|
|
533
|
+
}
|
|
534
|
+
function arrayOrEmpty(value) {
|
|
535
|
+
return value == null ? [] : array(value);
|
|
536
|
+
}
|
|
537
|
+
function text(value) {
|
|
538
|
+
return typeof value === "string" ? value : "";
|
|
539
|
+
}
|
|
540
|
+
function string(value) {
|
|
541
|
+
if (typeof value !== "string") throw new Error("expected string");
|
|
542
|
+
return value;
|
|
543
|
+
}
|
|
544
|
+
function objectJSON(bytes) {
|
|
545
|
+
return object(JSON.parse(Buffer.from(bytes).toString("utf8")));
|
|
546
|
+
}
|
|
547
|
+
function queryEscape(value) {
|
|
548
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replaceAll("%20", "+");
|
|
549
|
+
}
|
|
550
|
+
function pathEscape(value) {
|
|
551
|
+
return queryEscape(value).replaceAll("+", "%20").replace(/%(24|26|2B|3D|3A|40)/gi, (encoded) => String.fromCharCode(Number.parseInt(encoded.slice(1), 16)));
|
|
552
|
+
}
|
|
553
|
+
function parseID(value) {
|
|
554
|
+
const candidate = value.trim();
|
|
555
|
+
if (!candidate || Buffer.byteLength(candidate) > 2048) throw new Error("invalid Notion ID");
|
|
556
|
+
let id = candidate;
|
|
557
|
+
if (/^https:\/\//i.test(candidate)) {
|
|
558
|
+
const url = new URL(candidate);
|
|
559
|
+
if (!/(^|\.)notion\.(so|com|site)$/i.test(url.hostname)) throw new Error("invalid Notion URL");
|
|
560
|
+
const segment = url.pathname.split("/").filter(Boolean).at(-1) ?? "";
|
|
561
|
+
id = /^[0-9a-f-]{36}$/i.test(segment) ? segment : segment.replaceAll("-", "").match(/([0-9a-f]{32})$/i)?.[1] ?? "";
|
|
562
|
+
}
|
|
563
|
+
const compact = id.replaceAll("-", "").toLowerCase();
|
|
564
|
+
if (!/^[0-9a-f]{32}$/.test(compact) || id.includes("-") && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("invalid Notion ID");
|
|
565
|
+
return `${compact.slice(0, 8)}-${compact.slice(8, 12)}-${compact.slice(12, 16)}-${compact.slice(16, 20)}-${compact.slice(20)}`;
|
|
566
|
+
}
|
|
567
|
+
function canonicalOrRaw(value) {
|
|
568
|
+
try {
|
|
569
|
+
return parseID(string(value));
|
|
570
|
+
} catch {
|
|
571
|
+
return text(value);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function validateCursor(value) {
|
|
575
|
+
const cursor = value.trim();
|
|
576
|
+
if (Buffer.byteLength(cursor) > 1024 || cursor && !/^[!-~]+$/.test(cursor)) throw new Error("invalid cursor");
|
|
577
|
+
return cursor;
|
|
578
|
+
}
|
|
579
|
+
function selectDataSource(dataSourceId, databaseId) {
|
|
580
|
+
if (Boolean(dataSourceId?.trim()) === Boolean(databaseId?.trim())) throw new Error("select one data source");
|
|
581
|
+
return dataSourceId?.trim() ? { dataSourceId: parseID(dataSourceId) } : { databaseId: parseID(databaseId) };
|
|
582
|
+
}
|
|
583
|
+
async function resolveDataSource(client, call, operation, selection, resolvedToken) {
|
|
584
|
+
if (selection.dataSourceId) return selection.dataSourceId;
|
|
585
|
+
const result = await client.exchange(call, operation, "database lookup", "GET", `/databases/${pathEscape(selection.databaseId)}`, void 0, "read", void 0, resolvedToken, selection.databaseId);
|
|
586
|
+
if (!("response" in result)) return result;
|
|
587
|
+
try {
|
|
588
|
+
const body = objectJSON(result.response.body);
|
|
589
|
+
if (body.object !== "database") throw new Error("invalid database");
|
|
590
|
+
const sources = array(body.data_sources).map((value) => parseID(string(object(value).id)));
|
|
591
|
+
if (sources.length > 100) throw new Error("too many data sources");
|
|
592
|
+
if (sources.length !== 1) return { disposition: "defect", failure: failure(operation, "VALIDATION", "database must contain one data source"), receipt: result.receipt };
|
|
593
|
+
return sources[0];
|
|
594
|
+
} catch {
|
|
595
|
+
return { disposition: "invalidResponse", failure: failure(operation, "PROTOCOL", "Notion returned an invalid database"), receipt: result.receipt };
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function decodeParent(value) {
|
|
599
|
+
const resource = objectOrEmpty(value);
|
|
600
|
+
const type = text(resource.type);
|
|
601
|
+
const id = type === "data_source_id" ? canonicalOrRaw(resource.data_source_id) : type === "database_id" ? canonicalOrRaw(resource.database_id) : type === "page_id" ? canonicalOrRaw(resource.page_id) : type === "block_id" ? canonicalOrRaw(resource.block_id) : "";
|
|
602
|
+
return { type, ...id ? { id } : {}, ...type === "data_source_id" && canonicalOrRaw(resource.database_id) ? { databaseId: canonicalOrRaw(resource.database_id) } : {} };
|
|
603
|
+
}
|
|
604
|
+
function joinRichText(value) {
|
|
605
|
+
return Array.isArray(value) ? value.map((item) => text(objectOrEmpty(item).plain_text)).join("") : "";
|
|
606
|
+
}
|
|
607
|
+
function decodePage(value) {
|
|
608
|
+
const resource = object(value);
|
|
609
|
+
if (resource.object !== "page") throw new Error("not a page");
|
|
610
|
+
const id = parseID(string(resource.id));
|
|
611
|
+
const properties = decodeProperties(resource.properties);
|
|
612
|
+
return {
|
|
613
|
+
id,
|
|
614
|
+
title: titleOfProperties(properties),
|
|
615
|
+
parent: decodeParent(resource.parent),
|
|
616
|
+
inTrash: resource.in_trash === true,
|
|
617
|
+
archived: resource.is_archived === true,
|
|
618
|
+
properties,
|
|
619
|
+
...text(resource.url) ? { url: text(resource.url) } : {},
|
|
620
|
+
...text(resource.created_time) ? { createdTime: text(resource.created_time) } : {},
|
|
621
|
+
...text(resource.last_edited_time) ? { lastEditedTime: text(resource.last_edited_time) } : {}
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
function decodeProperties(value) {
|
|
625
|
+
if (value === null || value === void 0) return {};
|
|
626
|
+
const source = object(value);
|
|
627
|
+
const properties = {};
|
|
628
|
+
for (const [name, raw] of Object.entries(source)) properties[name] = decodeProperty(raw);
|
|
629
|
+
return properties;
|
|
630
|
+
}
|
|
631
|
+
function titleOfProperties(properties) {
|
|
632
|
+
if (!properties) return "";
|
|
633
|
+
return Object.values(properties).find((property) => property.type === "title")?.text ?? "";
|
|
634
|
+
}
|
|
635
|
+
function decodeProperty(value, canNest = true) {
|
|
636
|
+
const resource = objectOrEmpty(value);
|
|
637
|
+
const type = text(resource.type);
|
|
638
|
+
const property = { id: text(resource.id), type, plainText: "" };
|
|
639
|
+
if (type === "title" || type === "rich_text") {
|
|
640
|
+
const rendered = joinRichText(resource[type]);
|
|
641
|
+
if (rendered) property.text = rendered;
|
|
642
|
+
property.plainText = rendered;
|
|
643
|
+
} else if (type === "number" && typeof resource.number === "number") {
|
|
644
|
+
property.number = resource.number;
|
|
645
|
+
property.plainText = decimalNumber(resource.number);
|
|
646
|
+
} else if (type === "checkbox" && typeof resource.checkbox === "boolean") {
|
|
647
|
+
property.checkbox = resource.checkbox;
|
|
648
|
+
property.plainText = String(resource.checkbox);
|
|
649
|
+
} else if (type === "select" || type === "status") {
|
|
650
|
+
const name = text(objectOrEmpty(resource[type]).name);
|
|
651
|
+
if (name) property.option = name;
|
|
652
|
+
property.plainText = name;
|
|
653
|
+
} else if (type === "multi_select") {
|
|
654
|
+
const options = Array.isArray(resource.multi_select) ? resource.multi_select.map((item) => text(objectOrEmpty(item).name)) : [];
|
|
655
|
+
if (options.length) property.options = options;
|
|
656
|
+
property.plainText = options.join(", ");
|
|
657
|
+
} else if (type === "date") assignDate(property, resource.date);
|
|
658
|
+
else if (type === "url" || type === "email") {
|
|
659
|
+
const content = text(resource[type]);
|
|
660
|
+
if (content) property[type] = content;
|
|
661
|
+
property.plainText = content;
|
|
662
|
+
} else if (type === "phone_number") {
|
|
663
|
+
const phone = text(resource.phone_number);
|
|
664
|
+
if (phone) property.phoneNumber = phone;
|
|
665
|
+
property.plainText = phone;
|
|
666
|
+
} else if (type === "people") {
|
|
667
|
+
const people = arrayOrEmpty(resource.people).map(objectOrEmpty);
|
|
668
|
+
if (people.length) property.userIds = people.map((item) => text(item.id));
|
|
669
|
+
property.plainText = people.map((item) => text(item.name) || text(item.id)).join(", ");
|
|
670
|
+
} else if (type === "relation") {
|
|
671
|
+
const ids = arrayOrEmpty(resource.relation).map((item) => text(objectOrEmpty(item).id));
|
|
672
|
+
if (ids.length) property.pageIds = ids;
|
|
673
|
+
property.plainText = ids.join(", ");
|
|
674
|
+
if (resource.has_more === true) property.truncated = true;
|
|
675
|
+
} else if (type === "formula") assignComputed(property, resource.formula, false);
|
|
676
|
+
else if (type === "rollup") assignComputed(property, resource.rollup, canNest);
|
|
677
|
+
else if (type === "created_time" || type === "last_edited_time") {
|
|
678
|
+
const start = text(resource[type]);
|
|
679
|
+
property.date = { start };
|
|
680
|
+
property.plainText = start;
|
|
681
|
+
} else if (type === "created_by" || type === "last_edited_by") {
|
|
682
|
+
const user = objectOrEmpty(resource[type]);
|
|
683
|
+
if (Object.keys(user).length) {
|
|
684
|
+
property.userIds = [text(user.id)];
|
|
685
|
+
property.plainText = text(user.name) || text(user.id);
|
|
686
|
+
}
|
|
687
|
+
} else if (type === "unique_id") {
|
|
688
|
+
const unique = objectOrEmpty(resource.unique_id);
|
|
689
|
+
if (typeof unique.number === "number") {
|
|
690
|
+
property.number = unique.number;
|
|
691
|
+
property.text = text(unique.prefix) ? `${text(unique.prefix)}-${decimalNumber(unique.number)}` : decimalNumber(unique.number);
|
|
692
|
+
property.plainText = property.text;
|
|
693
|
+
}
|
|
694
|
+
} else if (type === "verification") property.plainText = text(objectOrEmpty(resource.verification).state);
|
|
695
|
+
else if (type === "files") property.plainText = Array.isArray(resource.files) ? resource.files.map((item) => text(objectOrEmpty(item).name)).join(", ") : "";
|
|
696
|
+
return property;
|
|
697
|
+
}
|
|
698
|
+
function assignDate(property, raw) {
|
|
699
|
+
if (!raw) return;
|
|
700
|
+
const date = objectOrEmpty(raw);
|
|
701
|
+
const start = text(date.start);
|
|
702
|
+
if (!start) return;
|
|
703
|
+
const end = text(date.end);
|
|
704
|
+
const timeZone = text(date.time_zone);
|
|
705
|
+
property.date = { start, ...end ? { end } : {}, ...timeZone ? { timeZone } : {} };
|
|
706
|
+
property.plainText = end ? `${start}/${end}` : start;
|
|
707
|
+
}
|
|
708
|
+
function assignComputed(property, raw, isRollup) {
|
|
709
|
+
if (!raw) return;
|
|
710
|
+
const computed = objectOrEmpty(raw);
|
|
711
|
+
if (computed.type === "string") {
|
|
712
|
+
const value = text(computed.string);
|
|
713
|
+
if (value) property.text = value;
|
|
714
|
+
property.plainText = value;
|
|
715
|
+
} else if (computed.type === "number" && typeof computed.number === "number") {
|
|
716
|
+
property.number = computed.number;
|
|
717
|
+
property.plainText = decimalNumber(computed.number);
|
|
718
|
+
} else if (computed.type === "boolean" && typeof computed.boolean === "boolean") {
|
|
719
|
+
property.checkbox = computed.boolean;
|
|
720
|
+
property.plainText = String(computed.boolean);
|
|
721
|
+
} else if (computed.type === "date") assignDate(property, computed.date);
|
|
722
|
+
else if (isRollup && computed.type === "array") {
|
|
723
|
+
const entries = arrayOrEmpty(computed.array);
|
|
724
|
+
if (entries.length > 25) property.truncated = true;
|
|
725
|
+
property.plainText = entries.slice(0, 25).map((entry) => decodeProperty(entry, false)).map((item) => item.plainText).filter(Boolean).join(", ");
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
function renderBlock(block, number) {
|
|
729
|
+
const type = text(block.type);
|
|
730
|
+
const content = objectOrEmpty(block[type]);
|
|
731
|
+
const richText2 = joinRichText(content.rich_text);
|
|
732
|
+
if (["paragraph", "heading_1", "heading_2", "heading_3", "heading_4", "quote", "callout", "toggle", "code", "template"].includes(type)) return richText2;
|
|
733
|
+
if (type === "bulleted_list_item") return `- ${richText2}`;
|
|
734
|
+
if (type === "numbered_list_item") return `${number + 1}. ${richText2}`;
|
|
735
|
+
if (type === "to_do") return `${content.checked === true ? "[x]" : "[ ]"} ${richText2}`;
|
|
736
|
+
if (type === "child_page" || type === "child_database") return text(content.title) || null;
|
|
737
|
+
if (type === "equation") return text(content.expression) || null;
|
|
738
|
+
if (["bookmark", "embed", "link_preview"].includes(type)) return text(content.url) || null;
|
|
739
|
+
if (type === "table_row") return Array.isArray(content.cells) && content.cells.length > 0 ? content.cells.map(joinRichText).join(" | ") : null;
|
|
740
|
+
if (["image", "video", "file", "pdf", "audio"].includes(type)) return joinRichText(content.caption) || null;
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
function encodeFilter(filter, depth = 0, counter = { count: 0 }) {
|
|
744
|
+
const compounds = [filter.and !== void 0, filter.or !== void 0].filter(Boolean).length;
|
|
745
|
+
const leaves = [Boolean(filter.property), Boolean(filter.timestamp)].filter(Boolean).length;
|
|
746
|
+
if (compounds + leaves !== 1) throw new Error("one filter kind required");
|
|
747
|
+
if (compounds) {
|
|
748
|
+
if (depth >= 2 || filter.type || filter.condition || filter.text || filter.number !== void 0 || filter.checkbox !== void 0 || filter.date || filter.id) throw new Error("invalid compound filter");
|
|
749
|
+
const key = filter.and !== void 0 ? "and" : "or";
|
|
750
|
+
const children = filter.and ?? filter.or ?? [];
|
|
751
|
+
if (!children.length || children.length > 100) throw new Error("invalid filter count");
|
|
752
|
+
return { [key]: children.map((child) => encodeFilter(child, depth + 1, counter)) };
|
|
753
|
+
}
|
|
754
|
+
const kind = filter.timestamp ? "date" : filter.type;
|
|
755
|
+
if (filter.timestamp && (filter.type || !["created_time", "last_edited_time"].includes(filter.timestamp))) throw new Error("invalid timestamp filter");
|
|
756
|
+
if (filter.property && (!filter.property.trim() || filter.property.trim() !== filter.property || [...filter.property].length > 256)) throw new Error("invalid property");
|
|
757
|
+
const condition = filter.condition ?? "";
|
|
758
|
+
if (!condition) throw new Error("condition required");
|
|
759
|
+
counter.count++;
|
|
760
|
+
if (counter.count > 100) throw new Error("too many conditions");
|
|
761
|
+
const empty = { is_empty: "none", is_not_empty: "none" };
|
|
762
|
+
const text2 = { equals: "text", does_not_equal: "text", contains: "text", does_not_contain: "text", starts_with: "text", ends_with: "text", ...empty };
|
|
763
|
+
const number = { equals: "number", does_not_equal: "number", greater_than: "number", less_than: "number", greater_than_or_equal_to: "number", less_than_or_equal_to: "number", ...empty };
|
|
764
|
+
const uniqueId = { ...number };
|
|
765
|
+
delete uniqueId.is_empty;
|
|
766
|
+
delete uniqueId.is_not_empty;
|
|
767
|
+
const date = { equals: "date", before: "date", after: "date", on_or_before: "date", on_or_after: "date", past_week: "relative", past_month: "relative", past_year: "relative", next_week: "relative", next_month: "relative", next_year: "relative", this_week: "relative" };
|
|
768
|
+
const conditions = {
|
|
769
|
+
title: text2,
|
|
770
|
+
rich_text: text2,
|
|
771
|
+
url: text2,
|
|
772
|
+
email: text2,
|
|
773
|
+
phone_number: text2,
|
|
774
|
+
number,
|
|
775
|
+
unique_id: uniqueId,
|
|
776
|
+
checkbox: { equals: "checkbox", does_not_equal: "checkbox" },
|
|
777
|
+
select: { equals: "text", does_not_equal: "text", ...empty },
|
|
778
|
+
status: { equals: "text", does_not_equal: "text", ...empty },
|
|
779
|
+
multi_select: { contains: "text", does_not_contain: "text", ...empty },
|
|
780
|
+
people: { contains: "id", does_not_contain: "id", ...empty },
|
|
781
|
+
relation: { contains: "id", does_not_contain: "id", ...empty },
|
|
782
|
+
created_by: { contains: "id", does_not_contain: "id", ...empty },
|
|
783
|
+
last_edited_by: { contains: "id", does_not_contain: "id", ...empty },
|
|
784
|
+
date: { ...date, ...empty },
|
|
785
|
+
created_time: { ...date, ...empty },
|
|
786
|
+
last_edited_time: { ...date, ...empty },
|
|
787
|
+
files: empty
|
|
788
|
+
};
|
|
789
|
+
const expected = (filter.timestamp ? date : conditions[kind ?? ""])?.[condition] ?? "";
|
|
790
|
+
if (!expected) throw new Error("unsupported filter condition");
|
|
791
|
+
const supplied = [filter.text ? "text" : "", filter.number !== void 0 ? "number" : "", filter.checkbox !== void 0 ? "checkbox" : "", filter.date ? "date" : "", filter.id ? "id" : ""].filter(Boolean);
|
|
792
|
+
if (expected === "none" || expected === "relative") {
|
|
793
|
+
if (supplied.length) throw new Error("unexpected condition value");
|
|
794
|
+
} else if (supplied.length !== 1 || supplied[0] !== expected) throw new Error("wrong condition value");
|
|
795
|
+
const value = expected === "none" ? true : expected === "relative" ? {} : expected === "text" ? filter.text : expected === "number" ? filter.number : expected === "checkbox" ? filter.checkbox : expected === "date" ? validDate(filter.date) : parseID(filter.id);
|
|
796
|
+
if (expected === "text" && (!filter.text?.trim() || [...filter.text].length > 2e3)) throw new Error("invalid filter text");
|
|
797
|
+
if (expected === "number" && !Number.isFinite(filter.number)) throw new Error("invalid filter number");
|
|
798
|
+
const field = filter.timestamp || filter.type;
|
|
799
|
+
return { ...filter.timestamp ? { timestamp: filter.timestamp } : { property: filter.property }, [field]: { [condition]: value } };
|
|
800
|
+
}
|
|
801
|
+
function encodeSort(sort) {
|
|
802
|
+
const direction = sort.direction || "ascending";
|
|
803
|
+
if (!["ascending", "descending"].includes(direction) || Boolean(sort.property) === Boolean(sort.timestamp)) throw new Error("invalid sort");
|
|
804
|
+
if (sort.timestamp && !["created_time", "last_edited_time"].includes(sort.timestamp)) throw new Error("invalid timestamp sort");
|
|
805
|
+
if (sort.property && (!sort.property.trim() || sort.property.trim() !== sort.property || [...sort.property].length > 256)) throw new Error("invalid property sort");
|
|
806
|
+
return sort.timestamp ? { timestamp: sort.timestamp, direction } : { property: sort.property, direction };
|
|
807
|
+
}
|
|
808
|
+
function encodeProperties(properties) {
|
|
809
|
+
if (Object.keys(properties).length > 100) throw new Error("too many properties");
|
|
810
|
+
const encoded = {};
|
|
811
|
+
for (const key of Object.keys(properties).sort()) {
|
|
812
|
+
if (!key.trim() || key !== key.trim() || [...key].length > 256 || /[\r\n]/.test(key)) throw new Error("invalid property name");
|
|
813
|
+
encoded[key] = encodeProperty(properties[key]);
|
|
814
|
+
}
|
|
815
|
+
return encoded;
|
|
816
|
+
}
|
|
817
|
+
function encodeProperty(value) {
|
|
818
|
+
const type = value.type;
|
|
819
|
+
const permitted = { title: ["text"], rich_text: ["text"], number: ["number"], checkbox: ["checkbox"], select: ["option"], status: ["option"], multi_select: ["options"], date: ["date"], url: ["url"], email: ["email"], phone_number: ["phoneNumber"], people: ["userIds"], relation: ["pageIds"] };
|
|
820
|
+
const fields = ["text", "number", "checkbox", "option", "options", "date", "url", "email", "phoneNumber", "userIds", "pageIds"];
|
|
821
|
+
if (!permitted[type] || fields.some((field) => value[field] !== void 0 && value[field] !== "" && !(Array.isArray(value[field]) && value[field].length === 0) && !permitted[type].includes(field))) throw new Error("invalid property type or field");
|
|
822
|
+
if (type === "title" || type === "rich_text") return { [type]: richText(value.text ?? "", 2e4) };
|
|
823
|
+
if (type === "number") {
|
|
824
|
+
if (value.number !== void 0 && !Number.isFinite(value.number)) throw new Error("invalid number");
|
|
825
|
+
return { number: value.number ?? null };
|
|
826
|
+
}
|
|
827
|
+
if (type === "checkbox") {
|
|
828
|
+
if (value.checkbox === void 0) throw new Error("checkbox required");
|
|
829
|
+
return { checkbox: value.checkbox };
|
|
830
|
+
}
|
|
831
|
+
if (type === "select" || type === "status") {
|
|
832
|
+
if (!value.option) {
|
|
833
|
+
if (type === "status") throw new Error("status required");
|
|
834
|
+
return { select: null };
|
|
835
|
+
}
|
|
836
|
+
return { [type]: { name: optionName(value.option) } };
|
|
837
|
+
}
|
|
838
|
+
if (type === "multi_select") {
|
|
839
|
+
const options = value.options ?? [];
|
|
840
|
+
if (options.length > 100) throw new Error("too many options");
|
|
841
|
+
const names = options.map(optionName);
|
|
842
|
+
if (new Set(names).size !== names.length) throw new Error("repeated option");
|
|
843
|
+
return { multi_select: names.map((name) => ({ name })) };
|
|
844
|
+
}
|
|
845
|
+
if (type === "date") {
|
|
846
|
+
if (!value.date) return { date: null };
|
|
847
|
+
const timeZone = value.date.timeZone?.trim() ?? "";
|
|
848
|
+
if (timeZone && (timeZone.length > 64 || !/^[A-Za-z][A-Za-z0-9_+-]*(\/[A-Za-z0-9_+-]+){0,3}$/.test(timeZone))) throw new Error("invalid timeZone");
|
|
849
|
+
return { date: { start: validDate(value.date.start), ...value.date.end?.trim() ? { end: validDate(value.date.end) } : {}, ...timeZone ? { time_zone: timeZone } : {} } };
|
|
850
|
+
}
|
|
851
|
+
if (type === "url") {
|
|
852
|
+
if (value.url) {
|
|
853
|
+
const url = new URL(value.url.trim());
|
|
854
|
+
if (!url.host || value.url.length > 2e3) throw new Error("invalid URL");
|
|
855
|
+
}
|
|
856
|
+
return { url: value.url?.trim() || null };
|
|
857
|
+
}
|
|
858
|
+
if (type === "email") {
|
|
859
|
+
const email = value.email?.trim() ?? "";
|
|
860
|
+
if (email && !isPlainEmailAddress(email)) throw new Error("invalid email");
|
|
861
|
+
return { email: email || null };
|
|
862
|
+
}
|
|
863
|
+
if (type === "phone_number") {
|
|
864
|
+
const phone = value.phoneNumber?.trim() ?? "";
|
|
865
|
+
if ([...phone].length > 200 || /[\r\n]/.test(phone)) throw new Error("invalid phone");
|
|
866
|
+
return { phone_number: phone || null };
|
|
867
|
+
}
|
|
868
|
+
if (type === "people" || type === "relation") {
|
|
869
|
+
const ids = (type === "people" ? value.userIds : value.pageIds) ?? [];
|
|
870
|
+
if (ids.length > 100) throw new Error("too many IDs");
|
|
871
|
+
const unique = [...new Set(ids.map(parseID))];
|
|
872
|
+
return { [type]: unique.map((id) => type === "people" ? { object: "user", id } : { id }) };
|
|
873
|
+
}
|
|
874
|
+
throw new Error("unsupported property");
|
|
875
|
+
}
|
|
876
|
+
function richText(value, limit) {
|
|
877
|
+
if ([...value].length > limit) throw new Error("text too long");
|
|
878
|
+
const chunks = [];
|
|
879
|
+
let current = "";
|
|
880
|
+
for (const character of value) {
|
|
881
|
+
if (current.length + character.length > 2e3) {
|
|
882
|
+
chunks.push(current);
|
|
883
|
+
current = "";
|
|
884
|
+
}
|
|
885
|
+
current += character;
|
|
886
|
+
}
|
|
887
|
+
if (current) chunks.push(current);
|
|
888
|
+
if (chunks.length > 100) throw new Error("too many text chunks");
|
|
889
|
+
return chunks.map((content) => ({ type: "text", text: { content } }));
|
|
890
|
+
}
|
|
891
|
+
function encodeParagraphs(value) {
|
|
892
|
+
if ([...value].length > 5e4) throw new Error("body too long");
|
|
893
|
+
const normalized = value.replaceAll("\r\n", "\n").trim();
|
|
894
|
+
if (!normalized) return [];
|
|
895
|
+
const paragraphs = normalized.split(/\n[ \t]*\n\s*/);
|
|
896
|
+
if (paragraphs.length > 100) throw new Error("too many paragraphs");
|
|
897
|
+
return paragraphs.map((paragraph) => ({ object: "block", type: "paragraph", paragraph: { rich_text: richText(paragraph.replace(/[ \t\n]+$/, ""), 5e4) } }));
|
|
898
|
+
}
|
|
899
|
+
function optionName(value) {
|
|
900
|
+
const name = value.trim();
|
|
901
|
+
if (!name || [...name].length > 100 || /[,\r\n]/.test(name)) throw new Error("invalid option name");
|
|
902
|
+
return name;
|
|
903
|
+
}
|
|
904
|
+
function validDate(value) {
|
|
905
|
+
const date = value.trim();
|
|
906
|
+
const match = date.match(/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-]\d{2}:\d{2}))?$/);
|
|
907
|
+
if (!match) throw new Error("invalid date");
|
|
908
|
+
const year = Number(match[1]);
|
|
909
|
+
const month = Number(match[2]);
|
|
910
|
+
const day = Number(match[3]);
|
|
911
|
+
const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
912
|
+
const daysInMonth = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
913
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth) throw new Error("invalid date");
|
|
914
|
+
if (match[4] !== void 0 && (Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59)) throw new Error("invalid date");
|
|
915
|
+
const zone = match[7];
|
|
916
|
+
if (zone && zone !== "Z" && (Number(zone.slice(1, 3)) > 24 || Number(zone.slice(4, 6)) > 60)) throw new Error("invalid date");
|
|
917
|
+
return date;
|
|
918
|
+
}
|
|
919
|
+
function decimalNumber(value) {
|
|
920
|
+
const rendered = String(value);
|
|
921
|
+
if (!/[eE]/.test(rendered)) return rendered;
|
|
922
|
+
const [mantissa, exponentText] = rendered.toLowerCase().split("e");
|
|
923
|
+
const exponent = Number(exponentText);
|
|
924
|
+
const sign = mantissa.startsWith("-") ? "-" : "";
|
|
925
|
+
const digits = mantissa.replace("-", "").replace(".", "");
|
|
926
|
+
const integerDigits = mantissa.replace("-", "").split(".")[0].length + exponent;
|
|
927
|
+
if (integerDigits <= 0) return `${sign}0.${"0".repeat(-integerDigits)}${digits}`;
|
|
928
|
+
if (integerDigits >= digits.length) return `${sign}${digits}${"0".repeat(integerDigits - digits.length)}`;
|
|
929
|
+
return `${sign}${digits.slice(0, integerDigits)}.${digits.slice(integerDigits)}`;
|
|
930
|
+
}
|
|
931
|
+
function isPlainEmailAddress(value) {
|
|
932
|
+
if (Buffer.byteLength(value) > 200 || /[\r\n]/.test(value)) return false;
|
|
933
|
+
const at = value.indexOf("@");
|
|
934
|
+
if (at < 1 || at !== value.lastIndexOf("@")) return false;
|
|
935
|
+
const local = value.slice(0, at);
|
|
936
|
+
const domain = value.slice(at + 1);
|
|
937
|
+
const atom = (part) => part.length > 0 && !part.startsWith(".") && !part.endsWith(".") && !part.includes("..") && [...part].every((character) => {
|
|
938
|
+
const codePoint = character.codePointAt(0);
|
|
939
|
+
return (codePoint >= 33 && codePoint <= 126 || codePoint >= 128) && !'()<>[]:;@\\,"'.includes(character);
|
|
940
|
+
});
|
|
941
|
+
if (!atom(local)) return false;
|
|
942
|
+
if (domain.startsWith("[") && domain.endsWith("]")) return !domain.includes("%") && isIP(domain.slice(1, -1)) !== 0;
|
|
943
|
+
return atom(domain);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// src/client.ts
|
|
947
|
+
var defaultEndpoint = "https://api.notion.com";
|
|
948
|
+
var notionVersion = "2026-03-11";
|
|
949
|
+
var NotionClient = class {
|
|
950
|
+
/** Validate the endpoint and required credential source without contacting Notion. */
|
|
951
|
+
constructor(config, credentials, options = {}) {
|
|
952
|
+
this.credentials = credentials;
|
|
953
|
+
if (!credentials) throw new TypeError("Notion credential source is required");
|
|
954
|
+
this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
955
|
+
this.maxResponseBytes = config.maxResponseBytes || 4194304;
|
|
956
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Notion maxResponseBytes must be positive");
|
|
957
|
+
this.send = options.send ?? sendProviderRequest;
|
|
958
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
959
|
+
}
|
|
960
|
+
credentials;
|
|
961
|
+
endpoint;
|
|
962
|
+
maxResponseBytes;
|
|
963
|
+
send;
|
|
964
|
+
now;
|
|
965
|
+
/** Bind title search. */
|
|
966
|
+
search() {
|
|
967
|
+
return new SearchOperation(this);
|
|
968
|
+
}
|
|
969
|
+
/** Bind database row query. */
|
|
970
|
+
queryDatabase() {
|
|
971
|
+
return new QueryDatabaseOperation(this);
|
|
972
|
+
}
|
|
973
|
+
/** Bind page read. */
|
|
974
|
+
getPage() {
|
|
975
|
+
return new GetPageOperation(this);
|
|
976
|
+
}
|
|
977
|
+
/** Bind single-dispatch page creation. */
|
|
978
|
+
createPage() {
|
|
979
|
+
return new CreatePageOperation(this);
|
|
980
|
+
}
|
|
981
|
+
/** Bind absolute page property update. */
|
|
982
|
+
updatePageProperties() {
|
|
983
|
+
return new UpdatePagePropertiesOperation(this);
|
|
984
|
+
}
|
|
985
|
+
/** Build a secret-safe receipt. */
|
|
986
|
+
receipt(call, response, providerObjectId = "") {
|
|
987
|
+
const requestId = response?.headers["x-notion-request-id"];
|
|
988
|
+
const providerRequestId = Array.isArray(requestId) ? requestId[0] : requestId;
|
|
989
|
+
return {
|
|
990
|
+
callId: call.id,
|
|
991
|
+
provider: "notion",
|
|
992
|
+
observedAt: this.now().toISOString(),
|
|
993
|
+
...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
|
|
994
|
+
...providerObjectId ? { providerObjectId } : {},
|
|
995
|
+
...providerRequestId && /^[!-~]{1,128}$/.test(providerRequestId) ? { providerRequestId } : {}
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
/** Resolve a credential before a single-dispatch write is claimed. */
|
|
999
|
+
async resolveToken(call, operation, signal) {
|
|
1000
|
+
const emptyReceipt = this.receipt(call);
|
|
1001
|
+
try {
|
|
1002
|
+
const credentials = await this.credentials.resolve(call, signal ?? call.context.cancellationSignal);
|
|
1003
|
+
const token = credentials.apiToken instanceof SecretString ? credentials.apiToken.reveal() : "";
|
|
1004
|
+
if (!isHeaderSafeCredential(token)) throw new TypeError("invalid Notion token");
|
|
1005
|
+
return { token };
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
if (error instanceof ReauthorizationRequiredError) return { outcome: { disposition: "defect", failure: failure(operation, "AUTHENTICATION", "Notion connection must be authorized again"), receipt: emptyReceipt, isProvablyNotSent: true } };
|
|
1008
|
+
if (error instanceof CredentialBrokerUnavailableError || error instanceof DOMException && error.name === "AbortError") return { outcome: { disposition: "retry", failure: failure(operation, "AUTHENTICATION", "Notion credential broker is temporarily unavailable"), receipt: emptyReceipt, isProvablyNotSent: true } };
|
|
1009
|
+
return { outcome: { disposition: "defect", failure: failure(operation, "AUTHENTICATION", "Notion connection credentials are unavailable"), receipt: emptyReceipt, isProvablyNotSent: true } };
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
/** Send one bounded API request and classify its transport and HTTP outcome. */
|
|
1013
|
+
async exchange(call, operation, subject, method, path, body, mode = "read", signal, resolvedToken, providerObjectId = "") {
|
|
1014
|
+
const emptyReceipt = this.receipt(call, void 0, providerObjectId);
|
|
1015
|
+
const credentials = resolvedToken ? { token: resolvedToken } : await this.resolveToken(call, operation, signal);
|
|
1016
|
+
if ("outcome" in credentials) return credentials.outcome;
|
|
1017
|
+
const token = credentials.token;
|
|
1018
|
+
let encoded;
|
|
1019
|
+
try {
|
|
1020
|
+
if (body !== void 0) encoded = Buffer.from(JSON.stringify(body));
|
|
1021
|
+
} catch {
|
|
1022
|
+
return { disposition: "defect", failure: failure(operation, "LOCAL_DEFECT", "Notion request could not be built"), receipt: emptyReceipt };
|
|
1023
|
+
}
|
|
1024
|
+
const request = {
|
|
1025
|
+
url: `${this.endpoint}/v1${path}`,
|
|
1026
|
+
method,
|
|
1027
|
+
headers: { Authorization: `Bearer ${token}`, "Notion-Version": notionVersion, Accept: "application/json", ...encoded ? { "Content-Type": "application/json" } : {} },
|
|
1028
|
+
...encoded ? { body: encoded } : {},
|
|
1029
|
+
maxResponseBytes: Math.max(this.maxResponseBytes, 16384),
|
|
1030
|
+
timeoutMs: mode === "read" ? 2e4 : 6e4,
|
|
1031
|
+
addressPolicy: this.endpoint === defaultEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
|
|
1032
|
+
signal: signal ?? call.context.cancellationSignal
|
|
1033
|
+
};
|
|
1034
|
+
let response;
|
|
1035
|
+
try {
|
|
1036
|
+
response = await this.send(request);
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
if (error instanceof BodyTooLargeError && error.status !== void 0) {
|
|
1039
|
+
response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(this.maxResponseBytes + 1) };
|
|
1040
|
+
} else {
|
|
1041
|
+
const isProvablyNotSent = error instanceof ProviderTransportError && error.isProvablyNotSent;
|
|
1042
|
+
const disposition = mode === "unkeyedWrite" && !isProvablyNotSent ? "uncertain" : "retry";
|
|
1043
|
+
return { disposition, failure: failure(operation, "TRANSPORT", `Notion ${subject} is temporarily unavailable`), receipt: emptyReceipt, isProvablyNotSent };
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
const receipt = this.receipt(call, response, providerObjectId);
|
|
1047
|
+
const status = response.status;
|
|
1048
|
+
const isBlocked = status === 429 && readToken(response.body, "additional_data", "rate_limit_reason") === "public_api_request_blocked";
|
|
1049
|
+
if (isBlocked) return { disposition: "providerRejected", failure: failure(operation, "PROVIDER_REJECTION", "Notion blocked API access"), receipt };
|
|
1050
|
+
if (status === 429 || status === 529 || status === 409 || mode !== "unkeyedWrite" && (status === 408 || status >= 500)) {
|
|
1051
|
+
const retryAfter = response.headers["retry-after"];
|
|
1052
|
+
const retryAfterMs = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] ?? "" : retryAfter ?? "", this.now());
|
|
1053
|
+
return { disposition: "retry", failure: failure(operation, status === 429 || status === 529 ? "RATE_LIMIT" : status === 409 ? "CONFLICT" : "AVAILABILITY", `Notion ${subject} is temporarily unavailable`), retryAfterMs, receipt, isProvablyNotSent: mode === "unkeyedWrite" };
|
|
1054
|
+
}
|
|
1055
|
+
if (status === 503 && mode === "unkeyedWrite") {
|
|
1056
|
+
let providerId = "";
|
|
1057
|
+
const candidate = readToken(response.body, "additional_data", "committed_resource_id");
|
|
1058
|
+
if (/^[0-9a-f]{32}$|^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(candidate)) {
|
|
1059
|
+
const compact = candidate.replaceAll("-", "").toLowerCase();
|
|
1060
|
+
providerId = `${compact.slice(0, 8)}-${compact.slice(8, 12)}-${compact.slice(12, 16)}-${compact.slice(16, 20)}-${compact.slice(20)}`;
|
|
1061
|
+
}
|
|
1062
|
+
if (providerId) return { disposition: "committed", failure: failure(operation, "AVAILABILITY", "Notion saved the page"), providerId, receipt };
|
|
1063
|
+
}
|
|
1064
|
+
if (status === 404) return { disposition: "notFound", failure: failure(operation, "NOT_FOUND", `Notion ${subject} was not found`), receipt };
|
|
1065
|
+
if (status >= 400 && status < 500 && status !== 408) return { disposition: "providerRejected", failure: failure(operation, status === 400 ? "VALIDATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION", `Notion rejected ${subject} with HTTP ${status}`), receipt };
|
|
1066
|
+
if (status < 200 || status >= 300) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, status >= 500 ? "AVAILABILITY" : "PROTOCOL", `Notion returned HTTP ${status}`), receipt };
|
|
1067
|
+
if (response.body.length > this.maxResponseBytes) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, "RESPONSE_TOO_LARGE", "Notion response exceeds the configured limit"), receipt };
|
|
1068
|
+
if (Buffer.from(response.body).includes(Buffer.from(token))) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, "PROTOCOL", "Notion response contains credential material"), receipt };
|
|
1069
|
+
return { response, receipt };
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
function failure(operation, kind, message) {
|
|
1073
|
+
return { provider: "notion", operation, kind, message };
|
|
1074
|
+
}
|
|
1075
|
+
function readToken(body, parent, key) {
|
|
1076
|
+
try {
|
|
1077
|
+
const data = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
1078
|
+
if (typeof data !== "object" || data === null) return "";
|
|
1079
|
+
const value = data[parent];
|
|
1080
|
+
if (typeof value === "object" && value !== null) {
|
|
1081
|
+
const token = value[key];
|
|
1082
|
+
return typeof token === "string" && /^[!-~]{1,128}$/.test(token) ? token : "";
|
|
1083
|
+
}
|
|
1084
|
+
return "";
|
|
1085
|
+
} catch {
|
|
1086
|
+
return "";
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// src/project.ts
|
|
1091
|
+
function newProjectConnection2(project, connectionName) {
|
|
1092
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
1093
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "notion" && entry.connectionName === name);
|
|
1094
|
+
if (!selected) throw new TypeError("Notion project connection is not configured");
|
|
1095
|
+
const config = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
|
|
1096
|
+
const credentials = {
|
|
1097
|
+
async resolve(call, signal) {
|
|
1098
|
+
void call;
|
|
1099
|
+
const fields = await loadedProject.resolveCredential("notion", name, signal);
|
|
1100
|
+
const decoded = z.object({ api_token: z.string().min(1) }).parse(fields);
|
|
1101
|
+
return { apiToken: new SecretString2(decoded.api_token) };
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
return new NotionClient(config, credentials);
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
export {
|
|
1108
|
+
ConfigSchema,
|
|
1109
|
+
Connection,
|
|
1110
|
+
ConnectorID,
|
|
1111
|
+
CreatePageBranch,
|
|
1112
|
+
CreatePageBranchCreated,
|
|
1113
|
+
CreatePageBranchDefect,
|
|
1114
|
+
CreatePageBranchInvalidResponse,
|
|
1115
|
+
CreatePageBranchNotFound,
|
|
1116
|
+
CreatePageBranchProviderRejected,
|
|
1117
|
+
CreatePageBranchUncertain,
|
|
1118
|
+
CreatePageDefinition,
|
|
1119
|
+
CreatePageInputSchema,
|
|
1120
|
+
CreatePageMetadata,
|
|
1121
|
+
CreatePageOperation,
|
|
1122
|
+
CreatePageOutputSchema,
|
|
1123
|
+
DateRangeSchema,
|
|
1124
|
+
GetPageBranch,
|
|
1125
|
+
GetPageBranchDefect,
|
|
1126
|
+
GetPageBranchFound,
|
|
1127
|
+
GetPageBranchInvalidResponse,
|
|
1128
|
+
GetPageBranchNotFound,
|
|
1129
|
+
GetPageBranchProviderRejected,
|
|
1130
|
+
GetPageDefinition,
|
|
1131
|
+
GetPageInputSchema,
|
|
1132
|
+
GetPageMetadata,
|
|
1133
|
+
GetPageOperation,
|
|
1134
|
+
GetPageOutputSchema,
|
|
1135
|
+
NotionClient,
|
|
1136
|
+
PageContentSchema,
|
|
1137
|
+
PagePropertySchema,
|
|
1138
|
+
PageSchema,
|
|
1139
|
+
ParentSchema,
|
|
1140
|
+
PropertyValueSchema,
|
|
1141
|
+
ProviderID,
|
|
1142
|
+
QueryDatabaseBranch,
|
|
1143
|
+
QueryDatabaseBranchDefect,
|
|
1144
|
+
QueryDatabaseBranchInvalidResponse,
|
|
1145
|
+
QueryDatabaseBranchNotFound,
|
|
1146
|
+
QueryDatabaseBranchProviderRejected,
|
|
1147
|
+
QueryDatabaseBranchQueried,
|
|
1148
|
+
QueryDatabaseDefinition,
|
|
1149
|
+
QueryDatabaseInputSchema,
|
|
1150
|
+
QueryDatabaseMetadata,
|
|
1151
|
+
QueryDatabaseOperation,
|
|
1152
|
+
QueryDatabaseOutputSchema,
|
|
1153
|
+
QueryFilterSchema,
|
|
1154
|
+
QuerySortSchema,
|
|
1155
|
+
SearchBranch,
|
|
1156
|
+
SearchBranchDefect,
|
|
1157
|
+
SearchBranchInvalidResponse,
|
|
1158
|
+
SearchBranchNoMatch,
|
|
1159
|
+
SearchBranchProviderRejected,
|
|
1160
|
+
SearchBranchSearched,
|
|
1161
|
+
SearchDefinition,
|
|
1162
|
+
SearchInputSchema,
|
|
1163
|
+
SearchMatchSchema,
|
|
1164
|
+
SearchMetadata,
|
|
1165
|
+
SearchOperation,
|
|
1166
|
+
SearchOutputSchema,
|
|
1167
|
+
UpdatePagePropertiesBranch,
|
|
1168
|
+
UpdatePagePropertiesBranchDefect,
|
|
1169
|
+
UpdatePagePropertiesBranchInvalidResponse,
|
|
1170
|
+
UpdatePagePropertiesBranchNotFound,
|
|
1171
|
+
UpdatePagePropertiesBranchProviderRejected,
|
|
1172
|
+
UpdatePagePropertiesBranchUpdated,
|
|
1173
|
+
UpdatePagePropertiesDefinition,
|
|
1174
|
+
UpdatePagePropertiesInputSchema,
|
|
1175
|
+
UpdatePagePropertiesMetadata,
|
|
1176
|
+
UpdatePagePropertiesOperation,
|
|
1177
|
+
UpdatePagePropertiesOutputSchema,
|
|
1178
|
+
decodeCredentials,
|
|
1179
|
+
newConnection,
|
|
1180
|
+
newConnectionWithOperations,
|
|
1181
|
+
newCreatePageStep,
|
|
1182
|
+
newGetPageStep,
|
|
1183
|
+
newProjectConnection2 as newProjectConnection,
|
|
1184
|
+
newQueryDatabaseStep,
|
|
1185
|
+
newSearchStep,
|
|
1186
|
+
newUpdatePagePropertiesStep
|
|
1187
|
+
};
|