@superdurable/connector-notion 0.0.0-stage → 0.2.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 +32 -2
- package/dex-connector.json +748 -0
- package/dist/chunk-5TNYF4VH.js +395 -0
- package/dist/connection-C7B_dh-s.d.ts +768 -0
- package/dist/index.d.ts +530 -0
- package/dist/index.js +1804 -0
- package/dist/mock.d.ts +159 -0
- package/dist/mock.js +381 -0
- package/package.json +60 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1804 @@
|
|
|
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-5TNYF4VH.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 isLeapYear2 = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
912
|
+
const daysInMonth2 = [31, isLeapYear2 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
913
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth2) 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 minimumPollIntervalMs = 5e3;
|
|
950
|
+
var maximumPollPageSize = 100;
|
|
951
|
+
var NotionClient = class {
|
|
952
|
+
/** Validate the endpoint and required credential source without contacting Notion. */
|
|
953
|
+
constructor(config, credentials, options = {}) {
|
|
954
|
+
this.credentials = credentials;
|
|
955
|
+
if (!credentials) throw new TypeError("Notion credential source is required");
|
|
956
|
+
this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
957
|
+
this.maxResponseBytes = config.maxResponseBytes || 4194304;
|
|
958
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Notion maxResponseBytes must be positive");
|
|
959
|
+
this.pollIntervalMs = config.pollIntervalMs || 3e4;
|
|
960
|
+
if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Notion pollInterval must be at least 5s");
|
|
961
|
+
this.pollPageSize = config.pollPageSize || maximumPollPageSize;
|
|
962
|
+
if (!Number.isSafeInteger(this.pollPageSize) || this.pollPageSize < 1 || this.pollPageSize > maximumPollPageSize) throw new TypeError("Notion pollPageSize must be between 1 and 100");
|
|
963
|
+
this.triggerLogger = options.logger;
|
|
964
|
+
this.send = options.send ?? sendProviderRequest;
|
|
965
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
966
|
+
}
|
|
967
|
+
credentials;
|
|
968
|
+
endpoint;
|
|
969
|
+
maxResponseBytes;
|
|
970
|
+
/** Wait between databaseRowChanged polls of one binding, in milliseconds; at least 5000, 30000 by default. */
|
|
971
|
+
pollIntervalMs;
|
|
972
|
+
/** Rows per databaseRowChanged query page, 1 to 100, 100 by default. */
|
|
973
|
+
pollPageSize;
|
|
974
|
+
/** The databaseRowChanged Trigger logger from the options, or undefined for the SDK default. */
|
|
975
|
+
triggerLogger;
|
|
976
|
+
send;
|
|
977
|
+
now;
|
|
978
|
+
/** Bind title search. */
|
|
979
|
+
search() {
|
|
980
|
+
return new SearchOperation(this);
|
|
981
|
+
}
|
|
982
|
+
/** Bind database row query. */
|
|
983
|
+
queryDatabase() {
|
|
984
|
+
return new QueryDatabaseOperation(this);
|
|
985
|
+
}
|
|
986
|
+
/** Bind page read. */
|
|
987
|
+
getPage() {
|
|
988
|
+
return new GetPageOperation(this);
|
|
989
|
+
}
|
|
990
|
+
/** Bind single-dispatch page creation. */
|
|
991
|
+
createPage() {
|
|
992
|
+
return new CreatePageOperation(this);
|
|
993
|
+
}
|
|
994
|
+
/** Bind absolute page property update. */
|
|
995
|
+
updatePageProperties() {
|
|
996
|
+
return new UpdatePagePropertiesOperation(this);
|
|
997
|
+
}
|
|
998
|
+
/** Build a secret-safe receipt. */
|
|
999
|
+
receipt(call, response, providerObjectId = "") {
|
|
1000
|
+
const requestId = response?.headers["x-notion-request-id"];
|
|
1001
|
+
const providerRequestId = Array.isArray(requestId) ? requestId[0] : requestId;
|
|
1002
|
+
return {
|
|
1003
|
+
callId: call.id,
|
|
1004
|
+
provider: "notion",
|
|
1005
|
+
observedAt: this.now().toISOString(),
|
|
1006
|
+
...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
|
|
1007
|
+
...providerObjectId ? { providerObjectId } : {},
|
|
1008
|
+
...providerRequestId && /^[!-~]{1,128}$/.test(providerRequestId) ? { providerRequestId } : {}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
/** Resolve a credential before a single-dispatch write is claimed. */
|
|
1012
|
+
async resolveToken(call, operation, signal) {
|
|
1013
|
+
const emptyReceipt = this.receipt(call);
|
|
1014
|
+
try {
|
|
1015
|
+
const credentials = await this.credentials.resolve(call, signal ?? call.context.cancellationSignal);
|
|
1016
|
+
const token = credentials.apiToken instanceof SecretString ? credentials.apiToken.reveal() : "";
|
|
1017
|
+
if (!isHeaderSafeCredential(token)) throw new TypeError("invalid Notion token");
|
|
1018
|
+
return { token };
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
if (error instanceof ReauthorizationRequiredError) return { outcome: { disposition: "defect", failure: failure(operation, "AUTHENTICATION", "Notion connection must be authorized again"), receipt: emptyReceipt, isProvablyNotSent: true } };
|
|
1021
|
+
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 } };
|
|
1022
|
+
return { outcome: { disposition: "defect", failure: failure(operation, "AUTHENTICATION", "Notion connection credentials are unavailable"), receipt: emptyReceipt, isProvablyNotSent: true } };
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
/** Send one bounded API request and classify its transport and HTTP outcome. */
|
|
1026
|
+
async exchange(call, operation, subject, method, path, body, mode = "read", signal, resolvedToken, providerObjectId = "") {
|
|
1027
|
+
const emptyReceipt = this.receipt(call, void 0, providerObjectId);
|
|
1028
|
+
const credentials = resolvedToken ? { token: resolvedToken } : await this.resolveToken(call, operation, signal);
|
|
1029
|
+
if ("outcome" in credentials) return credentials.outcome;
|
|
1030
|
+
const token = credentials.token;
|
|
1031
|
+
let encoded;
|
|
1032
|
+
try {
|
|
1033
|
+
if (body !== void 0) encoded = Buffer.from(JSON.stringify(body));
|
|
1034
|
+
} catch {
|
|
1035
|
+
return { disposition: "defect", failure: failure(operation, "LOCAL_DEFECT", "Notion request could not be built"), receipt: emptyReceipt };
|
|
1036
|
+
}
|
|
1037
|
+
const request = {
|
|
1038
|
+
url: `${this.endpoint}/v1${path}`,
|
|
1039
|
+
method,
|
|
1040
|
+
headers: { Authorization: `Bearer ${token}`, "Notion-Version": notionVersion, Accept: "application/json", ...encoded ? { "Content-Type": "application/json" } : {} },
|
|
1041
|
+
...encoded ? { body: encoded } : {},
|
|
1042
|
+
maxResponseBytes: Math.max(this.maxResponseBytes, 16384),
|
|
1043
|
+
timeoutMs: mode === "read" ? 2e4 : 6e4,
|
|
1044
|
+
addressPolicy: this.endpoint === defaultEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
|
|
1045
|
+
signal: signal ?? call.context.cancellationSignal
|
|
1046
|
+
};
|
|
1047
|
+
let response;
|
|
1048
|
+
try {
|
|
1049
|
+
response = await this.send(request);
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
if (error instanceof BodyTooLargeError && error.status !== void 0) {
|
|
1052
|
+
response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(this.maxResponseBytes + 1) };
|
|
1053
|
+
} else {
|
|
1054
|
+
const isProvablyNotSent = error instanceof ProviderTransportError && error.isProvablyNotSent;
|
|
1055
|
+
const disposition = mode === "unkeyedWrite" && !isProvablyNotSent ? "uncertain" : "retry";
|
|
1056
|
+
return { disposition, failure: failure(operation, "TRANSPORT", `Notion ${subject} is temporarily unavailable`), receipt: emptyReceipt, isProvablyNotSent };
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
const receipt = this.receipt(call, response, providerObjectId);
|
|
1060
|
+
const status = response.status;
|
|
1061
|
+
const isBlocked = status === 429 && readToken(response.body, "additional_data", "rate_limit_reason") === "public_api_request_blocked";
|
|
1062
|
+
if (isBlocked) return { disposition: "providerRejected", failure: failure(operation, "PROVIDER_REJECTION", "Notion blocked API access"), receipt };
|
|
1063
|
+
if (status === 429 || status === 529 || status === 409 || mode !== "unkeyedWrite" && (status === 408 || status >= 500)) {
|
|
1064
|
+
const retryAfter = response.headers["retry-after"];
|
|
1065
|
+
const retryAfterMs = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] ?? "" : retryAfter ?? "", this.now());
|
|
1066
|
+
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" };
|
|
1067
|
+
}
|
|
1068
|
+
if (status === 503 && mode === "unkeyedWrite") {
|
|
1069
|
+
let providerId = "";
|
|
1070
|
+
const candidate = readToken(response.body, "additional_data", "committed_resource_id");
|
|
1071
|
+
if (/^[0-9a-f]{32}$|^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(candidate)) {
|
|
1072
|
+
const compact = candidate.replaceAll("-", "").toLowerCase();
|
|
1073
|
+
providerId = `${compact.slice(0, 8)}-${compact.slice(8, 12)}-${compact.slice(12, 16)}-${compact.slice(16, 20)}-${compact.slice(20)}`;
|
|
1074
|
+
}
|
|
1075
|
+
if (providerId) return { disposition: "committed", failure: failure(operation, "AVAILABILITY", "Notion saved the page"), providerId, receipt };
|
|
1076
|
+
}
|
|
1077
|
+
if (status === 404) return { disposition: "notFound", failure: failure(operation, "NOT_FOUND", `Notion ${subject} was not found`), receipt };
|
|
1078
|
+
if (status >= 400 && status < 500 && status !== 408) {
|
|
1079
|
+
const providerErrorCode = readTopLevelToken(response.body, "code");
|
|
1080
|
+
return { disposition: "providerRejected", failure: failure(operation, status === 400 ? "VALIDATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION", `Notion rejected ${subject} with HTTP ${status}`), receipt, ...providerErrorCode ? { providerErrorCode } : {} };
|
|
1081
|
+
}
|
|
1082
|
+
if (status < 200 || status >= 300) return { disposition: mode === "unkeyedWrite" ? "uncertain" : "invalidResponse", failure: failure(operation, status >= 500 ? "AVAILABILITY" : "PROTOCOL", `Notion returned HTTP ${status}`), receipt };
|
|
1083
|
+
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 };
|
|
1084
|
+
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 };
|
|
1085
|
+
return { response, receipt };
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
function failure(operation, kind, message) {
|
|
1089
|
+
return { provider: "notion", operation, kind, message };
|
|
1090
|
+
}
|
|
1091
|
+
function readTopLevelToken(body, key) {
|
|
1092
|
+
try {
|
|
1093
|
+
const data = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
1094
|
+
if (typeof data !== "object" || data === null) return "";
|
|
1095
|
+
const token = data[key];
|
|
1096
|
+
return typeof token === "string" && /^[!-~]{1,128}$/.test(token) ? token : "";
|
|
1097
|
+
} catch {
|
|
1098
|
+
return "";
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
function readToken(body, parent, key) {
|
|
1102
|
+
try {
|
|
1103
|
+
const data = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
1104
|
+
if (typeof data !== "object" || data === null) return "";
|
|
1105
|
+
const value = data[parent];
|
|
1106
|
+
if (typeof value === "object" && value !== null) {
|
|
1107
|
+
const token = value[key];
|
|
1108
|
+
return typeof token === "string" && /^[!-~]{1,128}$/.test(token) ? token : "";
|
|
1109
|
+
}
|
|
1110
|
+
return "";
|
|
1111
|
+
} catch {
|
|
1112
|
+
return "";
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// src/project.ts
|
|
1117
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
1118
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
1119
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "notion" && entry.connectionName === name);
|
|
1120
|
+
if (!selected) throw new TypeError("Notion project connection is not configured");
|
|
1121
|
+
const settings = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional(), pollInterval: z.number().int().nonnegative().optional(), pollPageSize: z.number().int().optional() }).parse(selected.configuration);
|
|
1122
|
+
const config = {
|
|
1123
|
+
...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
|
|
1124
|
+
...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
|
|
1125
|
+
...settings.pollInterval ? { pollIntervalMs: Math.max(1, Math.floor(settings.pollInterval / 1e6)) } : {},
|
|
1126
|
+
...settings.pollPageSize !== void 0 ? { pollPageSize: settings.pollPageSize } : {}
|
|
1127
|
+
};
|
|
1128
|
+
const credentials = {
|
|
1129
|
+
async resolve(call, signal) {
|
|
1130
|
+
void call;
|
|
1131
|
+
const fields = await loadedProject.resolveCredential("notion", name, signal);
|
|
1132
|
+
const decoded = z.object({ api_token: z.string().min(1) }).parse(fields);
|
|
1133
|
+
return { apiToken: new SecretString2(decoded.api_token) };
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
return new NotionClient(config, credentials, options);
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// src/database_row_trigger.ts
|
|
1141
|
+
import {
|
|
1142
|
+
mustTriggerBindingDefinition,
|
|
1143
|
+
newTrigger
|
|
1144
|
+
} from "@superdurable/connectors-sdk";
|
|
1145
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1146
|
+
import {
|
|
1147
|
+
ObjectNotFoundError,
|
|
1148
|
+
decodeTriggerConfiguration,
|
|
1149
|
+
newDurableTriggerTarget,
|
|
1150
|
+
parseTriggerPayloadJSON
|
|
1151
|
+
} from "@superdurable/connectors-sdk/projectconfig";
|
|
1152
|
+
|
|
1153
|
+
// src/database_row_cursor.ts
|
|
1154
|
+
import { createHash } from "crypto";
|
|
1155
|
+
import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
|
|
1156
|
+
|
|
1157
|
+
// src/go_time.ts
|
|
1158
|
+
var rfc3339 = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{1,2}):([0-9]{2}):([0-9]{2})(?:[.,]([0-9]+))?(Z|[+-][0-9]{2}:[0-9]{2})$/;
|
|
1159
|
+
var nanosecondsPerSecond = 1000000000n;
|
|
1160
|
+
var secondsPerDay = 86400;
|
|
1161
|
+
var GoTime = class _GoTime {
|
|
1162
|
+
/** Wrap an instant; offsetSeconds only changes how it is rendered. */
|
|
1163
|
+
constructor(unixNanoseconds, offsetSeconds = 0) {
|
|
1164
|
+
this.unixNanoseconds = unixNanoseconds;
|
|
1165
|
+
this.offsetSeconds = offsetSeconds;
|
|
1166
|
+
}
|
|
1167
|
+
unixNanoseconds;
|
|
1168
|
+
offsetSeconds;
|
|
1169
|
+
/** Return the instant moved by nanoseconds, keeping the offset as Go's Time.Add does. */
|
|
1170
|
+
add(nanoseconds) {
|
|
1171
|
+
return new _GoTime(this.unixNanoseconds + nanoseconds, this.offsetSeconds);
|
|
1172
|
+
}
|
|
1173
|
+
/** Return the same instant rendered in UTC, as Go's Time.UTC does. */
|
|
1174
|
+
inUTC() {
|
|
1175
|
+
return new _GoTime(this.unixNanoseconds);
|
|
1176
|
+
}
|
|
1177
|
+
/** Report whether this instant precedes other. */
|
|
1178
|
+
isBefore(other) {
|
|
1179
|
+
return this.unixNanoseconds < other.unixNanoseconds;
|
|
1180
|
+
}
|
|
1181
|
+
/** Report whether this instant follows other. */
|
|
1182
|
+
isAfter(other) {
|
|
1183
|
+
return this.unixNanoseconds > other.unixNanoseconds;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Render Go's time.RFC3339Nano: trailing fractional zeros dropped, Z for a zero offset. Throws RangeError for
|
|
1187
|
+
* a year outside 0 to 9999, which Go's JSON encoding refuses as well.
|
|
1188
|
+
*/
|
|
1189
|
+
formatRFC3339Nano() {
|
|
1190
|
+
const local = this.unixNanoseconds + BigInt(this.offsetSeconds) * nanosecondsPerSecond;
|
|
1191
|
+
const seconds = floorDivide(local, nanosecondsPerSecond);
|
|
1192
|
+
const fraction = local - seconds * nanosecondsPerSecond;
|
|
1193
|
+
const days = Number(floorDivide(seconds, BigInt(secondsPerDay)));
|
|
1194
|
+
const secondOfDay = Number(seconds - BigInt(days) * BigInt(secondsPerDay));
|
|
1195
|
+
const [year, month, day] = civilFromDays(days);
|
|
1196
|
+
if (year < 0 || year > 9999) throw new RangeError("Go time year is outside the range [0,9999]");
|
|
1197
|
+
let text2 = `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}T${pad(Math.floor(secondOfDay / 3600), 2)}:${pad(Math.floor(secondOfDay / 60) % 60, 2)}:${pad(secondOfDay % 60, 2)}`;
|
|
1198
|
+
if (fraction !== 0n) text2 += `.${fraction.toString().padStart(9, "0").replace(/0+$/, "")}`;
|
|
1199
|
+
if (this.offsetSeconds === 0) return `${text2}Z`;
|
|
1200
|
+
const offsetMinutes = Math.floor(Math.abs(this.offsetSeconds) / 60);
|
|
1201
|
+
return `${text2}${this.offsetSeconds < 0 ? "-" : "+"}${pad(Math.floor(offsetMinutes / 60), 2)}:${pad(offsetMinutes % 60, 2)}`;
|
|
1202
|
+
}
|
|
1203
|
+
/** Return the instant as a Date, truncated to milliseconds. */
|
|
1204
|
+
toDate() {
|
|
1205
|
+
return new Date(Number(floorDivide(this.unixNanoseconds, 1000000n)));
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
var unixEpoch = new GoTime(0n);
|
|
1209
|
+
function parseGoTime(value) {
|
|
1210
|
+
const match = rfc3339.exec(value);
|
|
1211
|
+
if (!match) throw new RangeError("time is not RFC 3339");
|
|
1212
|
+
const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
|
|
1213
|
+
const fraction = match[7] ?? "";
|
|
1214
|
+
const offset = match[8];
|
|
1215
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) throw new RangeError("time has an invalid date");
|
|
1216
|
+
if (hour > 23 || minute > 59 || second > 59) throw new RangeError("time has an invalid clock time");
|
|
1217
|
+
let offsetSeconds = 0;
|
|
1218
|
+
if (offset !== "Z") {
|
|
1219
|
+
const offsetHours = Number(offset.slice(1, 3));
|
|
1220
|
+
const offsetMinutes = Number(offset.slice(4, 6));
|
|
1221
|
+
if (offsetHours > 24 || offsetMinutes > 60) throw new RangeError("time has an invalid zone offset");
|
|
1222
|
+
offsetSeconds = (offsetHours * 3600 + offsetMinutes * 60) * (offset.startsWith("-") ? -1 : 1);
|
|
1223
|
+
}
|
|
1224
|
+
const nanoseconds = BigInt(`${fraction}000000000`.slice(0, 9));
|
|
1225
|
+
const localSeconds = BigInt(daysFromCivil(year, month, day)) * BigInt(secondsPerDay) + BigInt(hour * 3600 + minute * 60 + second);
|
|
1226
|
+
return new GoTime((localSeconds - BigInt(offsetSeconds)) * nanosecondsPerSecond + nanoseconds, offsetSeconds);
|
|
1227
|
+
}
|
|
1228
|
+
function floorDivide(dividend, divisor) {
|
|
1229
|
+
const quotient = dividend / divisor;
|
|
1230
|
+
return dividend % divisor !== 0n && dividend < 0n !== divisor < 0n ? quotient - 1n : quotient;
|
|
1231
|
+
}
|
|
1232
|
+
function pad(value, width) {
|
|
1233
|
+
return String(value).padStart(width, "0");
|
|
1234
|
+
}
|
|
1235
|
+
function isLeapYear(year) {
|
|
1236
|
+
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
1237
|
+
}
|
|
1238
|
+
function daysInMonth(year, month) {
|
|
1239
|
+
if (month === 2) return isLeapYear(year) ? 29 : 28;
|
|
1240
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
1241
|
+
}
|
|
1242
|
+
function daysFromCivil(year, month, day) {
|
|
1243
|
+
const shiftedYear = month <= 2 ? year - 1 : year;
|
|
1244
|
+
const era = Math.floor(shiftedYear / 400);
|
|
1245
|
+
const yearOfEra = shiftedYear - era * 400;
|
|
1246
|
+
const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
|
|
1247
|
+
const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
|
|
1248
|
+
return era * 146097 + dayOfEra - 719468;
|
|
1249
|
+
}
|
|
1250
|
+
function civilFromDays(days) {
|
|
1251
|
+
const shifted = days + 719468;
|
|
1252
|
+
const era = Math.floor(shifted / 146097);
|
|
1253
|
+
const dayOfEra = shifted - era * 146097;
|
|
1254
|
+
const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
|
|
1255
|
+
const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
|
|
1256
|
+
const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
|
|
1257
|
+
const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
|
|
1258
|
+
const month = monthIndex + (monthIndex < 10 ? 3 : -9);
|
|
1259
|
+
return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/database_row_cursor.ts
|
|
1263
|
+
var databaseRowCursorVersion = 1;
|
|
1264
|
+
var databaseRowLookbackNanoseconds = 120000000000n;
|
|
1265
|
+
var maximumSeenDatabaseRows = 2e3;
|
|
1266
|
+
var maximumSeenRowBytes = 48 << 10;
|
|
1267
|
+
var int64Minimum = -(1n << 63n);
|
|
1268
|
+
var int64Maximum = (1n << 63n) - 1n;
|
|
1269
|
+
var goZeroTime = parseGoTime("0001-01-01T00:00:00Z");
|
|
1270
|
+
var DatabaseRowCursorDecodeError = class extends Error {
|
|
1271
|
+
constructor(message) {
|
|
1272
|
+
super(message);
|
|
1273
|
+
this.name = "DatabaseRowCursorDecodeError";
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
var SourceNumber = class {
|
|
1277
|
+
constructor(source) {
|
|
1278
|
+
this.source = source;
|
|
1279
|
+
}
|
|
1280
|
+
source;
|
|
1281
|
+
};
|
|
1282
|
+
function decodeDatabaseRowCursor(token) {
|
|
1283
|
+
let document;
|
|
1284
|
+
const keepNumberSource = (_key, value, context) => typeof value === "number" ? new SourceNumber(context?.source ?? String(value)) : value;
|
|
1285
|
+
try {
|
|
1286
|
+
document = JSON.parse(token, keepNumberSource);
|
|
1287
|
+
} catch {
|
|
1288
|
+
throw new DatabaseRowCursorDecodeError("cursor is not JSON");
|
|
1289
|
+
}
|
|
1290
|
+
const cursor = { version: 0, dataSourceId: "", highWater: goZeroTime, queryFrom: null, startCursor: "", seen: [] };
|
|
1291
|
+
if (document === null) return cursor;
|
|
1292
|
+
if (!isPlainObject(document)) throw new DatabaseRowCursorDecodeError("cursor is not an object");
|
|
1293
|
+
for (const [name, value] of foldMembers(document, ["v", "dataSourceId", "highWater", "queryFrom", "startCursor", "seen"])) {
|
|
1294
|
+
if (value === null) {
|
|
1295
|
+
if (name === "queryFrom") cursor.queryFrom = null;
|
|
1296
|
+
else if (name === "seen") cursor.seen = [];
|
|
1297
|
+
continue;
|
|
1298
|
+
}
|
|
1299
|
+
switch (name) {
|
|
1300
|
+
case "v":
|
|
1301
|
+
cursor.version = decodeInt64(value);
|
|
1302
|
+
break;
|
|
1303
|
+
case "dataSourceId":
|
|
1304
|
+
cursor.dataSourceId = decodeString(value);
|
|
1305
|
+
break;
|
|
1306
|
+
case "highWater":
|
|
1307
|
+
cursor.highWater = decodeTime(value);
|
|
1308
|
+
break;
|
|
1309
|
+
case "queryFrom":
|
|
1310
|
+
cursor.queryFrom = decodeTime(value);
|
|
1311
|
+
break;
|
|
1312
|
+
case "startCursor":
|
|
1313
|
+
cursor.startCursor = decodeString(value);
|
|
1314
|
+
break;
|
|
1315
|
+
default:
|
|
1316
|
+
cursor.seen = decodeSeen(value);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
return cursor;
|
|
1320
|
+
}
|
|
1321
|
+
function encodeDatabaseRowCursor(cursor) {
|
|
1322
|
+
let encoded = `{"v":${cursor.version},"dataSourceId":${encodeGoJSONValue(cursor.dataSourceId)},"highWater":"${cursor.highWater.formatRFC3339Nano()}"`;
|
|
1323
|
+
if (cursor.queryFrom) encoded += `,"queryFrom":"${cursor.queryFrom.formatRFC3339Nano()}"`;
|
|
1324
|
+
if (cursor.startCursor) encoded += `,"startCursor":${encodeGoJSONValue(cursor.startCursor)}`;
|
|
1325
|
+
if (cursor.seen.length) {
|
|
1326
|
+
const groups = cursor.seen.map((group) => `{"at":"${group.lastEditedTime.formatRFC3339Nano()}","rows":${group.rowKeys === null ? "null" : `[${group.rowKeys.map((key) => encodeGoJSONValue(key)).join(",")}]`}}`);
|
|
1327
|
+
encoded += `,"seen":[${groups.join(",")}]`;
|
|
1328
|
+
}
|
|
1329
|
+
return `${encoded}}`;
|
|
1330
|
+
}
|
|
1331
|
+
var SeenRows = class {
|
|
1332
|
+
keysByInstant = /* @__PURE__ */ new Map();
|
|
1333
|
+
/** Index the committed groups. */
|
|
1334
|
+
constructor(groups) {
|
|
1335
|
+
for (const group of groups) for (const key of group.rowKeys ?? []) this.addKey(group.lastEditedTime, key);
|
|
1336
|
+
}
|
|
1337
|
+
/** Report whether this row version was already delivered or baselined. */
|
|
1338
|
+
contains(lastEditedTime2, rowId) {
|
|
1339
|
+
return this.keysByInstant.get(lastEditedTime2.unixNanoseconds)?.has(seenRowKey(rowId)) ?? false;
|
|
1340
|
+
}
|
|
1341
|
+
/** Remember one row version. */
|
|
1342
|
+
add(lastEditedTime2, rowId) {
|
|
1343
|
+
this.addKey(lastEditedTime2, seenRowKey(rowId));
|
|
1344
|
+
}
|
|
1345
|
+
/** Keep the newest row versions edited inside the lookback, bounded in count and encoded bytes. */
|
|
1346
|
+
groupsWithin(highWater) {
|
|
1347
|
+
const lowerBound = highWater.unixNanoseconds - databaseRowLookbackNanoseconds;
|
|
1348
|
+
const instants = [...this.keysByInstant.keys()].filter((instant) => instant >= lowerBound).sort((left, right) => left < right ? 1 : left > right ? -1 : 0);
|
|
1349
|
+
const groups = [];
|
|
1350
|
+
let remaining = maximumSeenDatabaseRows;
|
|
1351
|
+
let remainingBytes = maximumSeenRowBytes;
|
|
1352
|
+
const keyBytes = '"",'.length + seenRowKey("").length;
|
|
1353
|
+
for (const instant of instants) {
|
|
1354
|
+
const lastEditedTime2 = new GoTime(instant);
|
|
1355
|
+
const groupBytes = '{"at":"","rows":[]},'.length + lastEditedTime2.formatRFC3339Nano().length;
|
|
1356
|
+
const fitting = Math.min(remaining, Math.trunc((remainingBytes - groupBytes) / keyBytes));
|
|
1357
|
+
if (fitting <= 0) break;
|
|
1358
|
+
const keys = [...this.keysByInstant.get(instant)].sort(compareUTF8).slice(0, fitting);
|
|
1359
|
+
remaining -= keys.length;
|
|
1360
|
+
remainingBytes -= groupBytes + keys.length * keyBytes;
|
|
1361
|
+
groups.push({ lastEditedTime: lastEditedTime2, rowKeys: keys });
|
|
1362
|
+
}
|
|
1363
|
+
return groups.reverse();
|
|
1364
|
+
}
|
|
1365
|
+
addKey(lastEditedTime2, key) {
|
|
1366
|
+
const keys = this.keysByInstant.get(lastEditedTime2.unixNanoseconds) ?? /* @__PURE__ */ new Set();
|
|
1367
|
+
keys.add(key);
|
|
1368
|
+
this.keysByInstant.set(lastEditedTime2.unixNanoseconds, keys);
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
function seenRowKey(rowId) {
|
|
1372
|
+
return createHash("sha256").update(rowId).digest().subarray(0, 12).toString("base64url");
|
|
1373
|
+
}
|
|
1374
|
+
function compareUTF8(left, right) {
|
|
1375
|
+
return Buffer.compare(Buffer.from(left), Buffer.from(right));
|
|
1376
|
+
}
|
|
1377
|
+
function isPlainObject(value) {
|
|
1378
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof SourceNumber);
|
|
1379
|
+
}
|
|
1380
|
+
function foldMembers(document, names) {
|
|
1381
|
+
const members = [];
|
|
1382
|
+
for (const [key, value] of Object.entries(document)) {
|
|
1383
|
+
const name = names.includes(key) ? key : names.find((candidate) => candidate.toLowerCase() === key.toLowerCase());
|
|
1384
|
+
if (name !== void 0) members.push([name, value]);
|
|
1385
|
+
}
|
|
1386
|
+
return members;
|
|
1387
|
+
}
|
|
1388
|
+
function decodeInt64(value) {
|
|
1389
|
+
if (!(value instanceof SourceNumber) || !/^-?(0|[1-9][0-9]*)$/.test(value.source)) throw new DatabaseRowCursorDecodeError("cursor version is not an integer");
|
|
1390
|
+
const parsed = BigInt(value.source);
|
|
1391
|
+
if (parsed < int64Minimum || parsed > int64Maximum) throw new DatabaseRowCursorDecodeError("cursor version is out of range");
|
|
1392
|
+
return parsed === BigInt(databaseRowCursorVersion) ? databaseRowCursorVersion : -1;
|
|
1393
|
+
}
|
|
1394
|
+
function decodeString(value) {
|
|
1395
|
+
if (typeof value !== "string") throw new DatabaseRowCursorDecodeError("cursor string field has another type");
|
|
1396
|
+
return value;
|
|
1397
|
+
}
|
|
1398
|
+
function decodeTime(value) {
|
|
1399
|
+
try {
|
|
1400
|
+
return parseGoTime(decodeString(value));
|
|
1401
|
+
} catch {
|
|
1402
|
+
throw new DatabaseRowCursorDecodeError("cursor time is not RFC 3339");
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function decodeSeen(value) {
|
|
1406
|
+
if (!Array.isArray(value)) throw new DatabaseRowCursorDecodeError("cursor seen is not an array");
|
|
1407
|
+
return value.map((item) => {
|
|
1408
|
+
const group = { lastEditedTime: goZeroTime, rowKeys: null };
|
|
1409
|
+
if (item === null) return group;
|
|
1410
|
+
if (!isPlainObject(item)) throw new DatabaseRowCursorDecodeError("cursor seen group is not an object");
|
|
1411
|
+
for (const [name, member] of foldMembers(item, ["at", "rows"])) {
|
|
1412
|
+
if (member === null) {
|
|
1413
|
+
if (name === "rows") group.rowKeys = null;
|
|
1414
|
+
continue;
|
|
1415
|
+
}
|
|
1416
|
+
if (name === "at") {
|
|
1417
|
+
group.lastEditedTime = decodeTime(member);
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
if (!Array.isArray(member)) throw new DatabaseRowCursorDecodeError("cursor seen rows is not an array");
|
|
1421
|
+
group.rowKeys = member.map((key) => key === null ? "" : decodeString(key));
|
|
1422
|
+
}
|
|
1423
|
+
return group;
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// src/database_row_fetcher.ts
|
|
1428
|
+
import { createHash as createHash2 } from "crypto";
|
|
1429
|
+
import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1430
|
+
var operationId = "databaseRowChanged";
|
|
1431
|
+
var lastEditedTime = "last_edited_time";
|
|
1432
|
+
var maximumSeedPages = 20;
|
|
1433
|
+
var emptyDataSourceHighWater = unixEpoch.add(databaseRowLookbackNanoseconds);
|
|
1434
|
+
var DatabaseRowPollError = class extends Error {
|
|
1435
|
+
constructor(message, options) {
|
|
1436
|
+
super(message, options);
|
|
1437
|
+
this.name = "DatabaseRowPollError";
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
var StaleStartCursorError = class extends DatabaseRowPollError {
|
|
1441
|
+
};
|
|
1442
|
+
var DatabaseRowFetcher = class {
|
|
1443
|
+
/** Bind the client and the dashed watched data source ID; it sends nothing. */
|
|
1444
|
+
constructor(client, connection, trigger, dataSourceId) {
|
|
1445
|
+
this.client = client;
|
|
1446
|
+
this.connection = connection;
|
|
1447
|
+
this.trigger = trigger;
|
|
1448
|
+
this.dataSourceId = dataSourceId;
|
|
1449
|
+
}
|
|
1450
|
+
client;
|
|
1451
|
+
connection;
|
|
1452
|
+
trigger;
|
|
1453
|
+
dataSourceId;
|
|
1454
|
+
/** Read the newest last edited time, then remember every row edited inside the lookback before it. */
|
|
1455
|
+
async seedCursor(context) {
|
|
1456
|
+
const newest = await this.query(context, null, "", 1, true);
|
|
1457
|
+
const position = { version: databaseRowCursorVersion, dataSourceId: this.dataSourceId, highWater: emptyDataSourceHighWater, queryFrom: null, startCursor: "", seen: [] };
|
|
1458
|
+
if (newest.rows[0]) position.highWater = newest.rows[0].lastEditedTime;
|
|
1459
|
+
const seen = new SeenRows([]);
|
|
1460
|
+
const queryFrom = position.highWater.add(-databaseRowLookbackNanoseconds);
|
|
1461
|
+
let startCursor = "";
|
|
1462
|
+
for (let page = 0; page < maximumSeedPages; page++) {
|
|
1463
|
+
const queried = await this.query(context, queryFrom, startCursor, this.client.pollPageSize);
|
|
1464
|
+
for (const row of queried.rows) {
|
|
1465
|
+
seen.add(row.lastEditedTime, row.page.id);
|
|
1466
|
+
position.highWater = laterTime(position.highWater, row.lastEditedTime);
|
|
1467
|
+
}
|
|
1468
|
+
if (!queried.nextCursor) break;
|
|
1469
|
+
startCursor = queried.nextCursor;
|
|
1470
|
+
}
|
|
1471
|
+
position.seen = seen.groupsWithin(position.highWater);
|
|
1472
|
+
return encode(position);
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Query rows edited at or after the lookback before the high water, oldest first, and return each row version
|
|
1476
|
+
* not yet seen. An undecodable cursor, or one for another data source, is marked invalid so the kit records a
|
|
1477
|
+
* new baseline; a start cursor Notion rejects restarts the query instead.
|
|
1478
|
+
*/
|
|
1479
|
+
async fetchChanges(context, cursor) {
|
|
1480
|
+
let position;
|
|
1481
|
+
try {
|
|
1482
|
+
position = decodeDatabaseRowCursor(cursor.token);
|
|
1483
|
+
} catch (error) {
|
|
1484
|
+
if (!(error instanceof DatabaseRowCursorDecodeError)) throw error;
|
|
1485
|
+
}
|
|
1486
|
+
if (!position || position.version !== databaseRowCursorVersion || position.highWater.unixNanoseconds === goZeroTime.unixNanoseconds) {
|
|
1487
|
+
throw markCursorInvalid(new DatabaseRowPollError("Notion databaseRowChanged cursor is not decodable"));
|
|
1488
|
+
}
|
|
1489
|
+
if (position.dataSourceId !== this.dataSourceId) throw markCursorInvalid(new DatabaseRowPollError("Notion databaseRowChanged cursor belongs to another data source"));
|
|
1490
|
+
let queryFrom = position.highWater.add(-databaseRowLookbackNanoseconds);
|
|
1491
|
+
if (position.startCursor && position.queryFrom) queryFrom = position.queryFrom;
|
|
1492
|
+
let queried;
|
|
1493
|
+
try {
|
|
1494
|
+
queried = await this.query(context, queryFrom, position.startCursor, this.client.pollPageSize);
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
if (!(error instanceof StaleStartCursorError)) throw error;
|
|
1497
|
+
position.startCursor = "";
|
|
1498
|
+
position.queryFrom = null;
|
|
1499
|
+
return { changes: [], next: encode(position), hasMorePages: true };
|
|
1500
|
+
}
|
|
1501
|
+
const seen = new SeenRows(position.seen);
|
|
1502
|
+
const changes = [];
|
|
1503
|
+
for (const row of queried.rows) {
|
|
1504
|
+
if (row.lastEditedTime.isBefore(queryFrom) || seen.contains(row.lastEditedTime, row.page.id)) continue;
|
|
1505
|
+
seen.add(row.lastEditedTime, row.page.id);
|
|
1506
|
+
position.highWater = laterTime(position.highWater, row.lastEditedTime);
|
|
1507
|
+
changes.push(newDatabaseRowChangedTriggerEvent(this.dataSourceId, row.page, row.lastEditedTime));
|
|
1508
|
+
}
|
|
1509
|
+
position.startCursor = "";
|
|
1510
|
+
position.queryFrom = null;
|
|
1511
|
+
const hasMorePages = queried.nextCursor !== "";
|
|
1512
|
+
if (hasMorePages) {
|
|
1513
|
+
position.startCursor = queried.nextCursor;
|
|
1514
|
+
position.queryFrom = queryFrom;
|
|
1515
|
+
}
|
|
1516
|
+
position.seen = seen.groupsWithin(position.highWater);
|
|
1517
|
+
return { changes, next: encode(position), hasMorePages };
|
|
1518
|
+
}
|
|
1519
|
+
async query(context, editedOnOrAfter, startCursor, pageSize, isNewestFirst = false) {
|
|
1520
|
+
await waitForPollRequest(context);
|
|
1521
|
+
const call = newTriggerCredentialCall(this.connection, this.trigger, context.signal);
|
|
1522
|
+
const resolved = await this.client.resolveToken(call, operationId, context.signal);
|
|
1523
|
+
if ("outcome" in resolved) throw new DatabaseRowPollError("Notion databaseRowChanged credentials are unavailable; save the connection's API token again");
|
|
1524
|
+
const body = {
|
|
1525
|
+
...editedOnOrAfter ? { filter: { [lastEditedTime]: { on_or_after: editedOnOrAfter.inUTC().formatRFC3339Nano() }, timestamp: lastEditedTime } } : {},
|
|
1526
|
+
sorts: [{ direction: isNewestFirst ? "descending" : "ascending", timestamp: lastEditedTime }],
|
|
1527
|
+
...startCursor ? { start_cursor: startCursor } : {},
|
|
1528
|
+
page_size: pageSize,
|
|
1529
|
+
result_type: "page"
|
|
1530
|
+
};
|
|
1531
|
+
const result = await this.client.exchange(call, operationId, "databaseRowChanged data source query", "POST", `/data_sources/${encodeURIComponent(this.dataSourceId)}/query`, body, "read", context.signal, resolved.token, this.dataSourceId);
|
|
1532
|
+
if ("response" in result) return decodeRowsPage(result.response.body, pageSize);
|
|
1533
|
+
if (startCursor && result.disposition === "providerRejected" && result.failure.kind === "VALIDATION" && result.providerErrorCode === "validation_error") {
|
|
1534
|
+
throw new StaleStartCursorError("Notion rejected the stored query start cursor");
|
|
1535
|
+
}
|
|
1536
|
+
if (result.disposition === "retry" && result.failure.kind === "RATE_LIMIT") throw markRateLimited(new DatabaseRowPollError(result.failure.message), result.retryAfterMs ?? 0);
|
|
1537
|
+
if (result.disposition === "notFound") throw new DatabaseRowPollError("Notion could not find the watched data source; share its database with the connection or pick another data source");
|
|
1538
|
+
throw new DatabaseRowPollError(result.failure.message);
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
function newDatabaseRowChangedTriggerEvent(dataSourceId, row, rowLastEditedTime) {
|
|
1542
|
+
return { id: databaseRowChangeId(dataSourceId, row.id, rowLastEditedTime), occurredAt: rowLastEditedTime.toDate(), payload: { dataSourceId, changeKind: databaseRowChangeKind(row), row } };
|
|
1543
|
+
}
|
|
1544
|
+
function databaseRowChangeId(dataSourceId, rowId, rowLastEditedTime) {
|
|
1545
|
+
const identity = [dataSourceId, rowId, rowLastEditedTime.inUTC().formatRFC3339Nano()].join("\0");
|
|
1546
|
+
return `notion-row-${createHash2("sha256").update(identity).digest().subarray(0, 16).toString("hex")}`;
|
|
1547
|
+
}
|
|
1548
|
+
function databaseRowChangeKind(row) {
|
|
1549
|
+
try {
|
|
1550
|
+
return parseGoTime(row.createdTime ?? "").unixNanoseconds === parseGoTime(row.lastEditedTime ?? "").unixNanoseconds ? "created" : "updated";
|
|
1551
|
+
} catch {
|
|
1552
|
+
return "updated";
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
function decodeRowsPage(body, pageSize) {
|
|
1556
|
+
const invalidPage = (cause) => new DatabaseRowPollError("Notion returned an invalid databaseRowChanged query page", { cause });
|
|
1557
|
+
let page;
|
|
1558
|
+
try {
|
|
1559
|
+
page = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
1560
|
+
} catch (error) {
|
|
1561
|
+
throw invalidPage(error);
|
|
1562
|
+
}
|
|
1563
|
+
if (page === null) return { rows: [], nextCursor: "" };
|
|
1564
|
+
if (typeof page !== "object" || Array.isArray(page)) throw invalidPage();
|
|
1565
|
+
const { results, next_cursor: nextCursor, has_more: hasMore, request_status: requestStatus } = page;
|
|
1566
|
+
if (results != null && !Array.isArray(results) || nextCursor != null && typeof nextCursor !== "string" || hasMore != null && typeof hasMore !== "boolean" || requestStatus != null && (typeof requestStatus !== "object" || Array.isArray(requestStatus)) || (results?.length ?? 0) > pageSize) throw invalidPage();
|
|
1567
|
+
let validatedCursor;
|
|
1568
|
+
try {
|
|
1569
|
+
validatedCursor = validateCursor(nextCursor ?? "");
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
throw new DatabaseRowPollError("Notion returned an invalid databaseRowChanged query cursor", { cause: error });
|
|
1572
|
+
}
|
|
1573
|
+
const rows = (results ?? []).map((resource, index) => {
|
|
1574
|
+
let row;
|
|
1575
|
+
try {
|
|
1576
|
+
row = decodePage(resource);
|
|
1577
|
+
} catch (error) {
|
|
1578
|
+
throw new DatabaseRowPollError(`Notion returned an invalid row ${index} in the databaseRowChanged query page`, { cause: error });
|
|
1579
|
+
}
|
|
1580
|
+
try {
|
|
1581
|
+
return { page: row, lastEditedTime: parseGoTime(row.lastEditedTime ?? "").inUTC() };
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
throw new DatabaseRowPollError(`Notion returned row ${index} without a valid last_edited_time`, { cause: error });
|
|
1584
|
+
}
|
|
1585
|
+
});
|
|
1586
|
+
return { rows, nextCursor: hasMore === true ? validatedCursor : "" };
|
|
1587
|
+
}
|
|
1588
|
+
function laterTime(current, candidate) {
|
|
1589
|
+
return candidate.isAfter(current) ? candidate : current;
|
|
1590
|
+
}
|
|
1591
|
+
function encode(position) {
|
|
1592
|
+
try {
|
|
1593
|
+
return { token: encodeDatabaseRowCursor(position) };
|
|
1594
|
+
} catch (error) {
|
|
1595
|
+
throw new DatabaseRowPollError("encode Notion databaseRowChanged cursor", { cause: error });
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
// src/database_row_models.ts
|
|
1600
|
+
import { z as z2 } from "zod";
|
|
1601
|
+
var DatabaseRowChangeKind = {
|
|
1602
|
+
/**
|
|
1603
|
+
* A row whose last edited time equals its created time: Notion reports no change type, and a row edited within
|
|
1604
|
+
* the same minute it was created still reads as created.
|
|
1605
|
+
*/
|
|
1606
|
+
Created: "created",
|
|
1607
|
+
/** Any other edit to a row's properties or content. */
|
|
1608
|
+
Updated: "updated"
|
|
1609
|
+
};
|
|
1610
|
+
var DatabaseRowChangedEventSchema = z2.object({
|
|
1611
|
+
dataSourceId: z2.string(),
|
|
1612
|
+
changeKind: z2.string(),
|
|
1613
|
+
row: PageSchema
|
|
1614
|
+
});
|
|
1615
|
+
var DatabaseRowChangedTriggerConfigurationSchema = z2.strictObject({
|
|
1616
|
+
dataSourceId: z2.string().optional(),
|
|
1617
|
+
dataSourceName: z2.string().optional()
|
|
1618
|
+
});
|
|
1619
|
+
|
|
1620
|
+
// src/database_row_trigger.ts
|
|
1621
|
+
var DatabaseRowLookbackMs = Number(databaseRowLookbackNanoseconds / 1000000n);
|
|
1622
|
+
var MaximumSeenDatabaseRows = maximumSeenDatabaseRows;
|
|
1623
|
+
var UIUnitDataSourcePicker = "dataSourcePicker";
|
|
1624
|
+
var UIDataSourcePickerPortDataSourceID = "dataSourceId";
|
|
1625
|
+
var UIDataSourcePickerPortDataSourceName = "dataSourceName";
|
|
1626
|
+
var DatabaseRowChangedTriggerDefinition = {
|
|
1627
|
+
trigger: { connectorId: ConnectorID, triggerName: "databaseRowChanged" },
|
|
1628
|
+
description: "Receive each row created or edited in one Notion data source, read by polling the data source query sorted by last edited time; the first run records a baseline and delivers no existing rows, and trashed rows are not delivered."
|
|
1629
|
+
};
|
|
1630
|
+
function defineDatabaseRowChangedTriggerBinding(config) {
|
|
1631
|
+
return mustTriggerBindingDefinition({ definition: DatabaseRowChangedTriggerDefinition, ...config });
|
|
1632
|
+
}
|
|
1633
|
+
function validateDatabaseRowChangedTriggerConfiguration(configuration) {
|
|
1634
|
+
if (!configuration?.dataSourceId?.trim()) throw new TypeError("dataSourceId is required; pick the watched Notion data source in Dex Web");
|
|
1635
|
+
try {
|
|
1636
|
+
parseID(configuration.dataSourceId);
|
|
1637
|
+
} catch (error) {
|
|
1638
|
+
throw new TypeError(`dataSourceId: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
function decodeDatabaseRowChangedEventPayload(_payloadJSON, payloadBytes) {
|
|
1642
|
+
return DatabaseRowChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
|
|
1643
|
+
}
|
|
1644
|
+
function newDatabaseRowTriggerRunner(config) {
|
|
1645
|
+
const client = notionClientOf(config.connection);
|
|
1646
|
+
if (!config.databaseRowChangedRoutes?.length) throw new TypeError("Notion databaseRowChanged routes are required");
|
|
1647
|
+
const pollers = config.databaseRowChangedRoutes.map((route) => {
|
|
1648
|
+
if (!route.bindingName?.trim() || !route.target) throw new TypeError("Notion databaseRowChanged binding name and target are required");
|
|
1649
|
+
validateRouteConfiguration(route.configuration);
|
|
1650
|
+
return newBindingPoller({
|
|
1651
|
+
definition: DatabaseRowChangedTriggerDefinition,
|
|
1652
|
+
binding: { connection: config.connection.reference, trigger: DatabaseRowChangedTriggerDefinition.trigger, name: route.bindingName },
|
|
1653
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
1654
|
+
fetcher: newFetcher(client, config.connection, route.configuration),
|
|
1655
|
+
target: route.target
|
|
1656
|
+
});
|
|
1657
|
+
});
|
|
1658
|
+
return newRunner({ connection: config.connection.reference, schedule: pollSchedule(client), pollers, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
|
|
1659
|
+
}
|
|
1660
|
+
function newProjectDatabaseRowTriggerRunner(project, connectionName, config, options = {}) {
|
|
1661
|
+
const connection = newProjectConnection2(project, connectionName, options);
|
|
1662
|
+
const triggerName = DatabaseRowChangedTriggerDefinition.trigger.triggerName;
|
|
1663
|
+
const routes = config.databaseRowChangedRoutes.map((route) => {
|
|
1664
|
+
if (!route.target) throw new TypeError(`Notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} target is required`);
|
|
1665
|
+
const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName: route.bindingName };
|
|
1666
|
+
let configuration;
|
|
1667
|
+
try {
|
|
1668
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, DatabaseRowChangedTriggerConfigurationSchema);
|
|
1669
|
+
} catch (error) {
|
|
1670
|
+
if (error instanceof ObjectNotFoundError) throw new TypeError(`notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} has no saved data source; pick one in Dex Web and restart`, { cause: error });
|
|
1671
|
+
throw new TypeError(`notion databaseRowChanged binding ${JSON.stringify(route.bindingName)} configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1672
|
+
}
|
|
1673
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { ...options.logger ? { logger: options.logger } : {}, decodePayload: decodeDatabaseRowChangedEventPayload });
|
|
1674
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
1675
|
+
});
|
|
1676
|
+
return newDatabaseRowTriggerRunner({ connection, databaseRowChangedRoutes: routes });
|
|
1677
|
+
}
|
|
1678
|
+
function newDatabaseRowChangedTrigger(config) {
|
|
1679
|
+
if (config.connectionName !== config.connection.reference.name) throw new TypeError(`notion connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
|
|
1680
|
+
const client = notionClientOf(config.connection);
|
|
1681
|
+
if (!config.bindingName?.trim() || !config.target) throw new TypeError("Notion databaseRowChanged binding name and target are required");
|
|
1682
|
+
validateRouteConfiguration(config.configuration);
|
|
1683
|
+
const binding = { connection: config.connection.reference, trigger: DatabaseRowChangedTriggerDefinition.trigger, name: config.bindingName };
|
|
1684
|
+
const source = newBindingTriggerSource({
|
|
1685
|
+
definition: DatabaseRowChangedTriggerDefinition,
|
|
1686
|
+
binding,
|
|
1687
|
+
cursor: newMemoryCursorStore(),
|
|
1688
|
+
fetcher: newFetcher(client, config.connection, config.configuration)
|
|
1689
|
+
}, pollSchedule(client), client.triggerLogger);
|
|
1690
|
+
return newTrigger({ definition: DatabaseRowChangedTriggerDefinition, binding, source, target: config.target, ...client.triggerLogger ? { logger: client.triggerLogger } : {} });
|
|
1691
|
+
}
|
|
1692
|
+
function newFetcher(client, connection, configuration) {
|
|
1693
|
+
return new DatabaseRowFetcher(client, connection.reference, DatabaseRowChangedTriggerDefinition.trigger, parseID(configuration.dataSourceId ?? ""));
|
|
1694
|
+
}
|
|
1695
|
+
function validateRouteConfiguration(configuration) {
|
|
1696
|
+
try {
|
|
1697
|
+
validateDatabaseRowChangedTriggerConfiguration(configuration ?? {});
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
throw new TypeError(`notion databaseRowChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
function pollSchedule(client) {
|
|
1703
|
+
return { intervalMs: client.pollIntervalMs };
|
|
1704
|
+
}
|
|
1705
|
+
function notionClientOf(connection) {
|
|
1706
|
+
if (!(connection?.operations instanceof NotionClient)) throw new TypeError("Notion Triggers require a connection from newProjectConnection or newConnection with a NotionClient");
|
|
1707
|
+
return connection.operations;
|
|
1708
|
+
}
|
|
1709
|
+
export {
|
|
1710
|
+
ConfigSchema,
|
|
1711
|
+
Connection,
|
|
1712
|
+
ConnectorID,
|
|
1713
|
+
CreatePageBranch,
|
|
1714
|
+
CreatePageBranchCreated,
|
|
1715
|
+
CreatePageBranchDefect,
|
|
1716
|
+
CreatePageBranchInvalidResponse,
|
|
1717
|
+
CreatePageBranchNotFound,
|
|
1718
|
+
CreatePageBranchProviderRejected,
|
|
1719
|
+
CreatePageBranchUncertain,
|
|
1720
|
+
CreatePageDefinition,
|
|
1721
|
+
CreatePageInputSchema,
|
|
1722
|
+
CreatePageMetadata,
|
|
1723
|
+
CreatePageOperation,
|
|
1724
|
+
CreatePageOutputSchema,
|
|
1725
|
+
DatabaseRowChangeKind,
|
|
1726
|
+
DatabaseRowChangedEventSchema,
|
|
1727
|
+
DatabaseRowChangedTriggerConfigurationSchema,
|
|
1728
|
+
DatabaseRowChangedTriggerDefinition,
|
|
1729
|
+
DatabaseRowLookbackMs,
|
|
1730
|
+
DateRangeSchema,
|
|
1731
|
+
GetPageBranch,
|
|
1732
|
+
GetPageBranchDefect,
|
|
1733
|
+
GetPageBranchFound,
|
|
1734
|
+
GetPageBranchInvalidResponse,
|
|
1735
|
+
GetPageBranchNotFound,
|
|
1736
|
+
GetPageBranchProviderRejected,
|
|
1737
|
+
GetPageDefinition,
|
|
1738
|
+
GetPageInputSchema,
|
|
1739
|
+
GetPageMetadata,
|
|
1740
|
+
GetPageOperation,
|
|
1741
|
+
GetPageOutputSchema,
|
|
1742
|
+
MaximumSeenDatabaseRows,
|
|
1743
|
+
NotionClient,
|
|
1744
|
+
PageContentSchema,
|
|
1745
|
+
PagePropertySchema,
|
|
1746
|
+
PageSchema,
|
|
1747
|
+
ParentSchema,
|
|
1748
|
+
PropertyValueSchema,
|
|
1749
|
+
ProviderID,
|
|
1750
|
+
QueryDatabaseBranch,
|
|
1751
|
+
QueryDatabaseBranchDefect,
|
|
1752
|
+
QueryDatabaseBranchInvalidResponse,
|
|
1753
|
+
QueryDatabaseBranchNotFound,
|
|
1754
|
+
QueryDatabaseBranchProviderRejected,
|
|
1755
|
+
QueryDatabaseBranchQueried,
|
|
1756
|
+
QueryDatabaseDefinition,
|
|
1757
|
+
QueryDatabaseInputSchema,
|
|
1758
|
+
QueryDatabaseMetadata,
|
|
1759
|
+
QueryDatabaseOperation,
|
|
1760
|
+
QueryDatabaseOutputSchema,
|
|
1761
|
+
QueryFilterSchema,
|
|
1762
|
+
QuerySortSchema,
|
|
1763
|
+
SearchBranch,
|
|
1764
|
+
SearchBranchDefect,
|
|
1765
|
+
SearchBranchInvalidResponse,
|
|
1766
|
+
SearchBranchNoMatch,
|
|
1767
|
+
SearchBranchProviderRejected,
|
|
1768
|
+
SearchBranchSearched,
|
|
1769
|
+
SearchDefinition,
|
|
1770
|
+
SearchInputSchema,
|
|
1771
|
+
SearchMatchSchema,
|
|
1772
|
+
SearchMetadata,
|
|
1773
|
+
SearchOperation,
|
|
1774
|
+
SearchOutputSchema,
|
|
1775
|
+
UIDataSourcePickerPortDataSourceID,
|
|
1776
|
+
UIDataSourcePickerPortDataSourceName,
|
|
1777
|
+
UIUnitDataSourcePicker,
|
|
1778
|
+
UpdatePagePropertiesBranch,
|
|
1779
|
+
UpdatePagePropertiesBranchDefect,
|
|
1780
|
+
UpdatePagePropertiesBranchInvalidResponse,
|
|
1781
|
+
UpdatePagePropertiesBranchNotFound,
|
|
1782
|
+
UpdatePagePropertiesBranchProviderRejected,
|
|
1783
|
+
UpdatePagePropertiesBranchUpdated,
|
|
1784
|
+
UpdatePagePropertiesDefinition,
|
|
1785
|
+
UpdatePagePropertiesInputSchema,
|
|
1786
|
+
UpdatePagePropertiesMetadata,
|
|
1787
|
+
UpdatePagePropertiesOperation,
|
|
1788
|
+
UpdatePagePropertiesOutputSchema,
|
|
1789
|
+
decodeCredentials,
|
|
1790
|
+
decodeDatabaseRowChangedEventPayload,
|
|
1791
|
+
defineDatabaseRowChangedTriggerBinding,
|
|
1792
|
+
newConnection,
|
|
1793
|
+
newConnectionWithOperations,
|
|
1794
|
+
newCreatePageStep,
|
|
1795
|
+
newDatabaseRowChangedTrigger,
|
|
1796
|
+
newDatabaseRowTriggerRunner,
|
|
1797
|
+
newGetPageStep,
|
|
1798
|
+
newProjectConnection2 as newProjectConnection,
|
|
1799
|
+
newProjectDatabaseRowTriggerRunner,
|
|
1800
|
+
newQueryDatabaseStep,
|
|
1801
|
+
newSearchStep,
|
|
1802
|
+
newUpdatePagePropertiesStep,
|
|
1803
|
+
validateDatabaseRowChangedTriggerConfiguration
|
|
1804
|
+
};
|