@elumixor/notion-orm 0.1.1

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/dist/index.js ADDED
@@ -0,0 +1,1803 @@
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __toESM = (mod, isNodeMode, target) => {
7
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
8
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
9
+ for (let key of __getOwnPropNames(mod))
10
+ if (!__hasOwnProp.call(to, key))
11
+ __defProp(to, key, {
12
+ get: () => mod[key],
13
+ enumerable: true
14
+ });
15
+ return to;
16
+ };
17
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
+
19
+ // node_modules/@notionhq/client/build/src/utils.js
20
+ var require_utils = __commonJS((exports) => {
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.assertNever = assertNever;
23
+ exports.pick = pick;
24
+ exports.isObject = isObject;
25
+ function assertNever(value) {
26
+ throw new Error(`Unexpected value should never occur: ${value}`);
27
+ }
28
+ function pick(base, keys) {
29
+ const entries = keys.map((key) => [key, base === null || base === undefined ? undefined : base[key]]);
30
+ return Object.fromEntries(entries);
31
+ }
32
+ function isObject(o) {
33
+ return typeof o === "object" && o !== null;
34
+ }
35
+ });
36
+
37
+ // node_modules/@notionhq/client/build/src/logging.js
38
+ var require_logging = __commonJS((exports) => {
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.LogLevel = undefined;
41
+ exports.makeConsoleLogger = makeConsoleLogger;
42
+ exports.logLevelSeverity = logLevelSeverity;
43
+ var utils_1 = require_utils();
44
+ var LogLevel;
45
+ (function(LogLevel2) {
46
+ LogLevel2["DEBUG"] = "debug";
47
+ LogLevel2["INFO"] = "info";
48
+ LogLevel2["WARN"] = "warn";
49
+ LogLevel2["ERROR"] = "error";
50
+ })(LogLevel || (exports.LogLevel = LogLevel = {}));
51
+ function makeConsoleLogger(name) {
52
+ return (level, message, extraInfo) => {
53
+ console[level](`${name} ${level}:`, message, extraInfo);
54
+ };
55
+ }
56
+ function logLevelSeverity(level) {
57
+ switch (level) {
58
+ case LogLevel.DEBUG:
59
+ return 20;
60
+ case LogLevel.INFO:
61
+ return 40;
62
+ case LogLevel.WARN:
63
+ return 60;
64
+ case LogLevel.ERROR:
65
+ return 80;
66
+ default:
67
+ return (0, utils_1.assertNever)(level);
68
+ }
69
+ }
70
+ });
71
+
72
+ // node_modules/@notionhq/client/build/src/errors.js
73
+ var require_errors = __commonJS((exports) => {
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.APIResponseError = exports.UnknownHTTPResponseError = exports.RequestTimeoutError = exports.ClientErrorCode = exports.APIErrorCode = undefined;
76
+ exports.isNotionClientError = isNotionClientError;
77
+ exports.isHTTPResponseError = isHTTPResponseError;
78
+ exports.buildRequestError = buildRequestError;
79
+ var utils_1 = require_utils();
80
+ var APIErrorCode;
81
+ (function(APIErrorCode2) {
82
+ APIErrorCode2["Unauthorized"] = "unauthorized";
83
+ APIErrorCode2["RestrictedResource"] = "restricted_resource";
84
+ APIErrorCode2["ObjectNotFound"] = "object_not_found";
85
+ APIErrorCode2["RateLimited"] = "rate_limited";
86
+ APIErrorCode2["InvalidJSON"] = "invalid_json";
87
+ APIErrorCode2["InvalidRequestURL"] = "invalid_request_url";
88
+ APIErrorCode2["InvalidRequest"] = "invalid_request";
89
+ APIErrorCode2["ValidationError"] = "validation_error";
90
+ APIErrorCode2["ConflictError"] = "conflict_error";
91
+ APIErrorCode2["InternalServerError"] = "internal_server_error";
92
+ APIErrorCode2["ServiceUnavailable"] = "service_unavailable";
93
+ })(APIErrorCode || (exports.APIErrorCode = APIErrorCode = {}));
94
+ var ClientErrorCode;
95
+ (function(ClientErrorCode2) {
96
+ ClientErrorCode2["RequestTimeout"] = "notionhq_client_request_timeout";
97
+ ClientErrorCode2["ResponseError"] = "notionhq_client_response_error";
98
+ })(ClientErrorCode || (exports.ClientErrorCode = ClientErrorCode = {}));
99
+
100
+ class NotionClientErrorBase extends Error {
101
+ }
102
+ function isNotionClientError(error) {
103
+ return (0, utils_1.isObject)(error) && error instanceof NotionClientErrorBase;
104
+ }
105
+ function isNotionClientErrorWithCode(error, codes) {
106
+ return isNotionClientError(error) && error.code in codes;
107
+ }
108
+
109
+ class RequestTimeoutError extends NotionClientErrorBase {
110
+ constructor(message = "Request to Notion API has timed out") {
111
+ super(message);
112
+ this.code = ClientErrorCode.RequestTimeout;
113
+ this.name = "RequestTimeoutError";
114
+ }
115
+ static isRequestTimeoutError(error) {
116
+ return isNotionClientErrorWithCode(error, {
117
+ [ClientErrorCode.RequestTimeout]: true
118
+ });
119
+ }
120
+ static rejectAfterTimeout(promise, timeoutMS) {
121
+ return new Promise((resolve, reject) => {
122
+ const timeoutId = setTimeout(() => {
123
+ reject(new RequestTimeoutError);
124
+ }, timeoutMS);
125
+ promise.then(resolve).catch(reject).then(() => clearTimeout(timeoutId));
126
+ });
127
+ }
128
+ }
129
+ exports.RequestTimeoutError = RequestTimeoutError;
130
+
131
+ class HTTPResponseError extends NotionClientErrorBase {
132
+ constructor(args) {
133
+ super(args.message);
134
+ this.name = "HTTPResponseError";
135
+ const { code, status, headers, rawBodyText, additional_data, request_id } = args;
136
+ this.code = code;
137
+ this.status = status;
138
+ this.headers = headers;
139
+ this.body = rawBodyText;
140
+ this.additional_data = additional_data;
141
+ this.request_id = request_id;
142
+ }
143
+ }
144
+ var httpResponseErrorCodes = {
145
+ [ClientErrorCode.ResponseError]: true,
146
+ [APIErrorCode.Unauthorized]: true,
147
+ [APIErrorCode.RestrictedResource]: true,
148
+ [APIErrorCode.ObjectNotFound]: true,
149
+ [APIErrorCode.RateLimited]: true,
150
+ [APIErrorCode.InvalidJSON]: true,
151
+ [APIErrorCode.InvalidRequestURL]: true,
152
+ [APIErrorCode.InvalidRequest]: true,
153
+ [APIErrorCode.ValidationError]: true,
154
+ [APIErrorCode.ConflictError]: true,
155
+ [APIErrorCode.InternalServerError]: true,
156
+ [APIErrorCode.ServiceUnavailable]: true
157
+ };
158
+ function isHTTPResponseError(error) {
159
+ if (!isNotionClientErrorWithCode(error, httpResponseErrorCodes)) {
160
+ return false;
161
+ }
162
+ return true;
163
+ }
164
+
165
+ class UnknownHTTPResponseError extends HTTPResponseError {
166
+ constructor(args) {
167
+ var _a;
168
+ super({
169
+ ...args,
170
+ code: ClientErrorCode.ResponseError,
171
+ message: (_a = args.message) !== null && _a !== undefined ? _a : `Request to Notion API failed with status: ${args.status}`,
172
+ additional_data: undefined,
173
+ request_id: undefined
174
+ });
175
+ this.name = "UnknownHTTPResponseError";
176
+ }
177
+ static isUnknownHTTPResponseError(error) {
178
+ return isNotionClientErrorWithCode(error, {
179
+ [ClientErrorCode.ResponseError]: true
180
+ });
181
+ }
182
+ }
183
+ exports.UnknownHTTPResponseError = UnknownHTTPResponseError;
184
+ var apiErrorCodes = {
185
+ [APIErrorCode.Unauthorized]: true,
186
+ [APIErrorCode.RestrictedResource]: true,
187
+ [APIErrorCode.ObjectNotFound]: true,
188
+ [APIErrorCode.RateLimited]: true,
189
+ [APIErrorCode.InvalidJSON]: true,
190
+ [APIErrorCode.InvalidRequestURL]: true,
191
+ [APIErrorCode.InvalidRequest]: true,
192
+ [APIErrorCode.ValidationError]: true,
193
+ [APIErrorCode.ConflictError]: true,
194
+ [APIErrorCode.InternalServerError]: true,
195
+ [APIErrorCode.ServiceUnavailable]: true
196
+ };
197
+
198
+ class APIResponseError extends HTTPResponseError {
199
+ constructor() {
200
+ super(...arguments);
201
+ this.name = "APIResponseError";
202
+ }
203
+ static isAPIResponseError(error) {
204
+ return isNotionClientErrorWithCode(error, apiErrorCodes);
205
+ }
206
+ }
207
+ exports.APIResponseError = APIResponseError;
208
+ function buildRequestError(response, bodyText) {
209
+ const apiErrorResponseBody = parseAPIErrorResponseBody(bodyText);
210
+ if (apiErrorResponseBody !== undefined) {
211
+ return new APIResponseError({
212
+ code: apiErrorResponseBody.code,
213
+ message: apiErrorResponseBody.message,
214
+ headers: response.headers,
215
+ status: response.status,
216
+ rawBodyText: bodyText,
217
+ additional_data: apiErrorResponseBody.additional_data,
218
+ request_id: apiErrorResponseBody.request_id
219
+ });
220
+ }
221
+ return new UnknownHTTPResponseError({
222
+ message: undefined,
223
+ headers: response.headers,
224
+ status: response.status,
225
+ rawBodyText: bodyText
226
+ });
227
+ }
228
+ function parseAPIErrorResponseBody(body) {
229
+ if (typeof body !== "string") {
230
+ return;
231
+ }
232
+ let parsed;
233
+ try {
234
+ parsed = JSON.parse(body);
235
+ } catch (parseError) {
236
+ return;
237
+ }
238
+ if (!(0, utils_1.isObject)(parsed) || typeof parsed["message"] !== "string" || !isAPIErrorCode(parsed["code"])) {
239
+ return;
240
+ }
241
+ const additional_data = parsed["additional_data"];
242
+ const request_id = parsed["request_id"];
243
+ return {
244
+ ...parsed,
245
+ code: parsed["code"],
246
+ message: parsed["message"],
247
+ additional_data,
248
+ request_id
249
+ };
250
+ }
251
+ function isAPIErrorCode(code) {
252
+ return typeof code === "string" && code in apiErrorCodes;
253
+ }
254
+ });
255
+
256
+ // node_modules/@notionhq/client/build/src/api-endpoints.js
257
+ var require_api_endpoints = __commonJS((exports) => {
258
+ Object.defineProperty(exports, "__esModule", { value: true });
259
+ exports.listDataSourceTemplates = exports.oauthIntrospect = exports.oauthRevoke = exports.oauthToken = exports.getFileUpload = exports.completeFileUpload = exports.sendFileUpload = exports.listFileUploads = exports.createFileUpload = exports.getComment = exports.listComments = exports.createComment = exports.search = exports.createDatabase = exports.updateDatabase = exports.getDatabase = exports.createDataSource = exports.queryDataSource = exports.updateDataSource = exports.getDataSource = exports.appendBlockChildren = exports.listBlockChildren = exports.deleteBlock = exports.updateBlock = exports.getBlock = exports.getPageProperty = exports.updatePage = exports.getPage = exports.createPage = exports.listUsers = exports.getUser = exports.getSelf = undefined;
260
+ exports.getSelf = {
261
+ method: "get",
262
+ pathParams: [],
263
+ queryParams: [],
264
+ bodyParams: [],
265
+ path: () => `users/me`
266
+ };
267
+ exports.getUser = {
268
+ method: "get",
269
+ pathParams: ["user_id"],
270
+ queryParams: [],
271
+ bodyParams: [],
272
+ path: (p) => `users/${p.user_id}`
273
+ };
274
+ exports.listUsers = {
275
+ method: "get",
276
+ pathParams: [],
277
+ queryParams: ["start_cursor", "page_size"],
278
+ bodyParams: [],
279
+ path: () => `users`
280
+ };
281
+ exports.createPage = {
282
+ method: "post",
283
+ pathParams: [],
284
+ queryParams: [],
285
+ bodyParams: [
286
+ "parent",
287
+ "properties",
288
+ "icon",
289
+ "cover",
290
+ "content",
291
+ "children",
292
+ "template"
293
+ ],
294
+ path: () => `pages`
295
+ };
296
+ exports.getPage = {
297
+ method: "get",
298
+ pathParams: ["page_id"],
299
+ queryParams: ["filter_properties"],
300
+ bodyParams: [],
301
+ path: (p) => `pages/${p.page_id}`
302
+ };
303
+ exports.updatePage = {
304
+ method: "patch",
305
+ pathParams: ["page_id"],
306
+ queryParams: [],
307
+ bodyParams: [
308
+ "properties",
309
+ "icon",
310
+ "cover",
311
+ "is_locked",
312
+ "template",
313
+ "erase_content",
314
+ "archived",
315
+ "in_trash"
316
+ ],
317
+ path: (p) => `pages/${p.page_id}`
318
+ };
319
+ exports.getPageProperty = {
320
+ method: "get",
321
+ pathParams: ["page_id", "property_id"],
322
+ queryParams: ["start_cursor", "page_size"],
323
+ bodyParams: [],
324
+ path: (p) => `pages/${p.page_id}/properties/${p.property_id}`
325
+ };
326
+ exports.getBlock = {
327
+ method: "get",
328
+ pathParams: ["block_id"],
329
+ queryParams: [],
330
+ bodyParams: [],
331
+ path: (p) => `blocks/${p.block_id}`
332
+ };
333
+ exports.updateBlock = {
334
+ method: "patch",
335
+ pathParams: ["block_id"],
336
+ queryParams: [],
337
+ bodyParams: [
338
+ "embed",
339
+ "type",
340
+ "archived",
341
+ "in_trash",
342
+ "bookmark",
343
+ "image",
344
+ "video",
345
+ "pdf",
346
+ "file",
347
+ "audio",
348
+ "code",
349
+ "equation",
350
+ "divider",
351
+ "breadcrumb",
352
+ "table_of_contents",
353
+ "link_to_page",
354
+ "table_row",
355
+ "heading_1",
356
+ "heading_2",
357
+ "heading_3",
358
+ "paragraph",
359
+ "bulleted_list_item",
360
+ "numbered_list_item",
361
+ "quote",
362
+ "to_do",
363
+ "toggle",
364
+ "template",
365
+ "callout",
366
+ "synced_block",
367
+ "table",
368
+ "column"
369
+ ],
370
+ path: (p) => `blocks/${p.block_id}`
371
+ };
372
+ exports.deleteBlock = {
373
+ method: "delete",
374
+ pathParams: ["block_id"],
375
+ queryParams: [],
376
+ bodyParams: [],
377
+ path: (p) => `blocks/${p.block_id}`
378
+ };
379
+ exports.listBlockChildren = {
380
+ method: "get",
381
+ pathParams: ["block_id"],
382
+ queryParams: ["start_cursor", "page_size"],
383
+ bodyParams: [],
384
+ path: (p) => `blocks/${p.block_id}/children`
385
+ };
386
+ exports.appendBlockChildren = {
387
+ method: "patch",
388
+ pathParams: ["block_id"],
389
+ queryParams: [],
390
+ bodyParams: ["children", "after"],
391
+ path: (p) => `blocks/${p.block_id}/children`
392
+ };
393
+ exports.getDataSource = {
394
+ method: "get",
395
+ pathParams: ["data_source_id"],
396
+ queryParams: [],
397
+ bodyParams: [],
398
+ path: (p) => `data_sources/${p.data_source_id}`
399
+ };
400
+ exports.updateDataSource = {
401
+ method: "patch",
402
+ pathParams: ["data_source_id"],
403
+ queryParams: [],
404
+ bodyParams: ["title", "icon", "properties", "in_trash", "archived", "parent"],
405
+ path: (p) => `data_sources/${p.data_source_id}`
406
+ };
407
+ exports.queryDataSource = {
408
+ method: "post",
409
+ pathParams: ["data_source_id"],
410
+ queryParams: ["filter_properties"],
411
+ bodyParams: [
412
+ "sorts",
413
+ "filter",
414
+ "start_cursor",
415
+ "page_size",
416
+ "archived",
417
+ "in_trash",
418
+ "result_type"
419
+ ],
420
+ path: (p) => `data_sources/${p.data_source_id}/query`
421
+ };
422
+ exports.createDataSource = {
423
+ method: "post",
424
+ pathParams: [],
425
+ queryParams: [],
426
+ bodyParams: ["parent", "properties", "title", "icon"],
427
+ path: () => `data_sources`
428
+ };
429
+ exports.getDatabase = {
430
+ method: "get",
431
+ pathParams: ["database_id"],
432
+ queryParams: [],
433
+ bodyParams: [],
434
+ path: (p) => `databases/${p.database_id}`
435
+ };
436
+ exports.updateDatabase = {
437
+ method: "patch",
438
+ pathParams: ["database_id"],
439
+ queryParams: [],
440
+ bodyParams: [
441
+ "parent",
442
+ "title",
443
+ "description",
444
+ "is_inline",
445
+ "icon",
446
+ "cover",
447
+ "in_trash",
448
+ "is_locked"
449
+ ],
450
+ path: (p) => `databases/${p.database_id}`
451
+ };
452
+ exports.createDatabase = {
453
+ method: "post",
454
+ pathParams: [],
455
+ queryParams: [],
456
+ bodyParams: [
457
+ "parent",
458
+ "title",
459
+ "description",
460
+ "is_inline",
461
+ "initial_data_source",
462
+ "icon",
463
+ "cover"
464
+ ],
465
+ path: () => `databases`
466
+ };
467
+ exports.search = {
468
+ method: "post",
469
+ pathParams: [],
470
+ queryParams: [],
471
+ bodyParams: ["sort", "query", "start_cursor", "page_size", "filter"],
472
+ path: () => `search`
473
+ };
474
+ exports.createComment = {
475
+ method: "post",
476
+ pathParams: [],
477
+ queryParams: [],
478
+ bodyParams: [
479
+ "rich_text",
480
+ "attachments",
481
+ "display_name",
482
+ "parent",
483
+ "discussion_id"
484
+ ],
485
+ path: () => `comments`
486
+ };
487
+ exports.listComments = {
488
+ method: "get",
489
+ pathParams: [],
490
+ queryParams: ["block_id", "start_cursor", "page_size"],
491
+ bodyParams: [],
492
+ path: () => `comments`
493
+ };
494
+ exports.getComment = {
495
+ method: "get",
496
+ pathParams: ["comment_id"],
497
+ queryParams: [],
498
+ bodyParams: [],
499
+ path: (p) => `comments/${p.comment_id}`
500
+ };
501
+ exports.createFileUpload = {
502
+ method: "post",
503
+ pathParams: [],
504
+ queryParams: [],
505
+ bodyParams: [
506
+ "mode",
507
+ "filename",
508
+ "content_type",
509
+ "number_of_parts",
510
+ "external_url"
511
+ ],
512
+ path: () => `file_uploads`
513
+ };
514
+ exports.listFileUploads = {
515
+ method: "get",
516
+ pathParams: [],
517
+ queryParams: ["status", "start_cursor", "page_size"],
518
+ bodyParams: [],
519
+ path: () => `file_uploads`
520
+ };
521
+ exports.sendFileUpload = {
522
+ method: "post",
523
+ pathParams: ["file_upload_id"],
524
+ queryParams: [],
525
+ bodyParams: [],
526
+ formDataParams: ["file", "part_number"],
527
+ path: (p) => `file_uploads/${p.file_upload_id}/send`
528
+ };
529
+ exports.completeFileUpload = {
530
+ method: "post",
531
+ pathParams: ["file_upload_id"],
532
+ queryParams: [],
533
+ bodyParams: [],
534
+ path: (p) => `file_uploads/${p.file_upload_id}/complete`
535
+ };
536
+ exports.getFileUpload = {
537
+ method: "get",
538
+ pathParams: ["file_upload_id"],
539
+ queryParams: [],
540
+ bodyParams: [],
541
+ path: (p) => `file_uploads/${p.file_upload_id}`
542
+ };
543
+ exports.oauthToken = {
544
+ method: "post",
545
+ pathParams: [],
546
+ queryParams: [],
547
+ bodyParams: [
548
+ "grant_type",
549
+ "code",
550
+ "redirect_uri",
551
+ "external_account",
552
+ "refresh_token"
553
+ ],
554
+ path: () => `oauth/token`
555
+ };
556
+ exports.oauthRevoke = {
557
+ method: "post",
558
+ pathParams: [],
559
+ queryParams: [],
560
+ bodyParams: ["token"],
561
+ path: () => `oauth/revoke`
562
+ };
563
+ exports.oauthIntrospect = {
564
+ method: "post",
565
+ pathParams: [],
566
+ queryParams: [],
567
+ bodyParams: ["token"],
568
+ path: () => `oauth/introspect`
569
+ };
570
+ exports.listDataSourceTemplates = {
571
+ method: "get",
572
+ pathParams: ["data_source_id"],
573
+ queryParams: ["name", "start_cursor", "page_size"],
574
+ bodyParams: [],
575
+ path: (p) => `data_sources/${p.data_source_id}/templates`
576
+ };
577
+ });
578
+
579
+ // node_modules/@notionhq/client/build/package.json
580
+ var require_package = __commonJS((exports, module) => {
581
+ module.exports = {
582
+ name: "@notionhq/client",
583
+ version: "5.3.0",
584
+ description: "A simple and easy to use client for the Notion API",
585
+ engines: {
586
+ node: ">=18"
587
+ },
588
+ homepage: "https://developers.notion.com/docs/getting-started",
589
+ bugs: {
590
+ url: "https://github.com/makenotion/notion-sdk-js/issues"
591
+ },
592
+ repository: {
593
+ type: "git",
594
+ url: "https://github.com/makenotion/notion-sdk-js/"
595
+ },
596
+ keywords: [
597
+ "notion",
598
+ "notionapi",
599
+ "rest",
600
+ "notion-api"
601
+ ],
602
+ main: "./build/src",
603
+ types: "./build/src/index.d.ts",
604
+ scripts: {
605
+ prepare: "npm run build",
606
+ prepublishOnly: "npm run checkLoggedIn && npm run lint && npm run test",
607
+ build: "tsc",
608
+ prettier: "prettier --write .",
609
+ lint: "prettier --check . && eslint . --ext .ts && cspell '**/*' ",
610
+ test: "jest ./test",
611
+ "check-links": "git ls-files | grep md$ | xargs -n 1 markdown-link-check",
612
+ prebuild: "npm run clean",
613
+ clean: "rm -rf ./build",
614
+ checkLoggedIn: "./scripts/verifyLoggedIn.sh",
615
+ "install:examples": 'for dir in examples/*/; do echo "Installing dependencies in $dir..."; (cd "$dir" && npm install); done',
616
+ "examples:install": "npm run install:examples",
617
+ "examples:typecheck": 'for dir in examples/*/; do echo "Typechecking $dir..."; (cd "$dir" && npx tsc --noEmit) || exit 1; done'
618
+ },
619
+ author: "",
620
+ license: "MIT",
621
+ files: [
622
+ "build/package.json",
623
+ "build/src/**"
624
+ ],
625
+ devDependencies: {
626
+ "@types/jest": "28.1.4",
627
+ "@typescript-eslint/eslint-plugin": "5.39.0",
628
+ "@typescript-eslint/parser": "5.39.0",
629
+ cspell: "5.4.1",
630
+ eslint: "7.24.0",
631
+ jest: "28.1.2",
632
+ "markdown-link-check": "3.13.7",
633
+ prettier: "2.8.8",
634
+ "ts-jest": "28.0.5",
635
+ typescript: "5.9.2"
636
+ }
637
+ };
638
+ });
639
+
640
+ // node_modules/@notionhq/client/build/src/Client.js
641
+ var require_Client = __commonJS((exports) => {
642
+ var __classPrivateFieldSet = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f) {
643
+ if (kind === "m")
644
+ throw new TypeError("Private method is not writable");
645
+ if (kind === "a" && !f)
646
+ throw new TypeError("Private accessor was defined without a setter");
647
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
648
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
649
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
650
+ };
651
+ var __classPrivateFieldGet = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f) {
652
+ if (kind === "a" && !f)
653
+ throw new TypeError("Private accessor was defined without a getter");
654
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
655
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
656
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
657
+ };
658
+ var _Client_auth;
659
+ var _Client_logLevel;
660
+ var _Client_logger;
661
+ var _Client_prefixUrl;
662
+ var _Client_timeoutMs;
663
+ var _Client_notionVersion;
664
+ var _Client_fetch;
665
+ var _Client_agent;
666
+ var _Client_userAgent;
667
+ Object.defineProperty(exports, "__esModule", { value: true });
668
+ var logging_1 = require_logging();
669
+ var errors_1 = require_errors();
670
+ var utils_1 = require_utils();
671
+ var api_endpoints_1 = require_api_endpoints();
672
+ var package_json_1 = require_package();
673
+
674
+ class Client {
675
+ constructor(options) {
676
+ var _a, _b, _c, _d, _e, _f;
677
+ _Client_auth.set(this, undefined);
678
+ _Client_logLevel.set(this, undefined);
679
+ _Client_logger.set(this, undefined);
680
+ _Client_prefixUrl.set(this, undefined);
681
+ _Client_timeoutMs.set(this, undefined);
682
+ _Client_notionVersion.set(this, undefined);
683
+ _Client_fetch.set(this, undefined);
684
+ _Client_agent.set(this, undefined);
685
+ _Client_userAgent.set(this, undefined);
686
+ this.blocks = {
687
+ retrieve: (args) => {
688
+ return this.request({
689
+ path: api_endpoints_1.getBlock.path(args),
690
+ method: api_endpoints_1.getBlock.method,
691
+ query: (0, utils_1.pick)(args, api_endpoints_1.getBlock.queryParams),
692
+ body: (0, utils_1.pick)(args, api_endpoints_1.getBlock.bodyParams),
693
+ auth: args === null || args === undefined ? undefined : args.auth
694
+ });
695
+ },
696
+ update: (args) => {
697
+ return this.request({
698
+ path: api_endpoints_1.updateBlock.path(args),
699
+ method: api_endpoints_1.updateBlock.method,
700
+ query: (0, utils_1.pick)(args, api_endpoints_1.updateBlock.queryParams),
701
+ body: (0, utils_1.pick)(args, api_endpoints_1.updateBlock.bodyParams),
702
+ auth: args === null || args === undefined ? undefined : args.auth
703
+ });
704
+ },
705
+ delete: (args) => {
706
+ return this.request({
707
+ path: api_endpoints_1.deleteBlock.path(args),
708
+ method: api_endpoints_1.deleteBlock.method,
709
+ query: (0, utils_1.pick)(args, api_endpoints_1.deleteBlock.queryParams),
710
+ body: (0, utils_1.pick)(args, api_endpoints_1.deleteBlock.bodyParams),
711
+ auth: args === null || args === undefined ? undefined : args.auth
712
+ });
713
+ },
714
+ children: {
715
+ append: (args) => {
716
+ return this.request({
717
+ path: api_endpoints_1.appendBlockChildren.path(args),
718
+ method: api_endpoints_1.appendBlockChildren.method,
719
+ query: (0, utils_1.pick)(args, api_endpoints_1.appendBlockChildren.queryParams),
720
+ body: (0, utils_1.pick)(args, api_endpoints_1.appendBlockChildren.bodyParams),
721
+ auth: args === null || args === undefined ? undefined : args.auth
722
+ });
723
+ },
724
+ list: (args) => {
725
+ return this.request({
726
+ path: api_endpoints_1.listBlockChildren.path(args),
727
+ method: api_endpoints_1.listBlockChildren.method,
728
+ query: (0, utils_1.pick)(args, api_endpoints_1.listBlockChildren.queryParams),
729
+ body: (0, utils_1.pick)(args, api_endpoints_1.listBlockChildren.bodyParams),
730
+ auth: args === null || args === undefined ? undefined : args.auth
731
+ });
732
+ }
733
+ }
734
+ };
735
+ this.databases = {
736
+ retrieve: (args) => {
737
+ return this.request({
738
+ path: api_endpoints_1.getDatabase.path(args),
739
+ method: api_endpoints_1.getDatabase.method,
740
+ query: (0, utils_1.pick)(args, api_endpoints_1.getDatabase.queryParams),
741
+ body: (0, utils_1.pick)(args, api_endpoints_1.getDatabase.bodyParams),
742
+ auth: args === null || args === undefined ? undefined : args.auth
743
+ });
744
+ },
745
+ create: (args) => {
746
+ return this.request({
747
+ path: api_endpoints_1.createDatabase.path(),
748
+ method: api_endpoints_1.createDatabase.method,
749
+ query: (0, utils_1.pick)(args, api_endpoints_1.createDatabase.queryParams),
750
+ body: (0, utils_1.pick)(args, api_endpoints_1.createDatabase.bodyParams),
751
+ auth: args === null || args === undefined ? undefined : args.auth
752
+ });
753
+ },
754
+ update: (args) => {
755
+ return this.request({
756
+ path: api_endpoints_1.updateDatabase.path(args),
757
+ method: api_endpoints_1.updateDatabase.method,
758
+ query: (0, utils_1.pick)(args, api_endpoints_1.updateDatabase.queryParams),
759
+ body: (0, utils_1.pick)(args, api_endpoints_1.updateDatabase.bodyParams),
760
+ auth: args === null || args === undefined ? undefined : args.auth
761
+ });
762
+ }
763
+ };
764
+ this.dataSources = {
765
+ retrieve: (args) => {
766
+ return this.request({
767
+ path: api_endpoints_1.getDataSource.path(args),
768
+ method: api_endpoints_1.getDataSource.method,
769
+ query: (0, utils_1.pick)(args, api_endpoints_1.getDataSource.queryParams),
770
+ body: (0, utils_1.pick)(args, api_endpoints_1.getDataSource.bodyParams),
771
+ auth: args === null || args === undefined ? undefined : args.auth
772
+ });
773
+ },
774
+ query: (args) => {
775
+ return this.request({
776
+ path: api_endpoints_1.queryDataSource.path(args),
777
+ method: api_endpoints_1.queryDataSource.method,
778
+ query: (0, utils_1.pick)(args, api_endpoints_1.queryDataSource.queryParams),
779
+ body: (0, utils_1.pick)(args, api_endpoints_1.queryDataSource.bodyParams),
780
+ auth: args === null || args === undefined ? undefined : args.auth
781
+ });
782
+ },
783
+ create: (args) => {
784
+ return this.request({
785
+ path: api_endpoints_1.createDataSource.path(),
786
+ method: api_endpoints_1.createDataSource.method,
787
+ query: (0, utils_1.pick)(args, api_endpoints_1.createDataSource.queryParams),
788
+ body: (0, utils_1.pick)(args, api_endpoints_1.createDataSource.bodyParams),
789
+ auth: args === null || args === undefined ? undefined : args.auth
790
+ });
791
+ },
792
+ update: (args) => {
793
+ return this.request({
794
+ path: api_endpoints_1.updateDataSource.path(args),
795
+ method: api_endpoints_1.updateDataSource.method,
796
+ query: (0, utils_1.pick)(args, api_endpoints_1.updateDataSource.queryParams),
797
+ body: (0, utils_1.pick)(args, api_endpoints_1.updateDataSource.bodyParams),
798
+ auth: args === null || args === undefined ? undefined : args.auth
799
+ });
800
+ },
801
+ listTemplates: (args) => {
802
+ return this.request({
803
+ path: api_endpoints_1.listDataSourceTemplates.path(args),
804
+ method: api_endpoints_1.listDataSourceTemplates.method,
805
+ query: (0, utils_1.pick)(args, api_endpoints_1.listDataSourceTemplates.queryParams),
806
+ body: (0, utils_1.pick)(args, api_endpoints_1.listDataSourceTemplates.bodyParams),
807
+ auth: args === null || args === undefined ? undefined : args.auth
808
+ });
809
+ }
810
+ };
811
+ this.pages = {
812
+ create: (args) => {
813
+ return this.request({
814
+ path: api_endpoints_1.createPage.path(),
815
+ method: api_endpoints_1.createPage.method,
816
+ query: (0, utils_1.pick)(args, api_endpoints_1.createPage.queryParams),
817
+ body: (0, utils_1.pick)(args, api_endpoints_1.createPage.bodyParams),
818
+ auth: args === null || args === undefined ? undefined : args.auth
819
+ });
820
+ },
821
+ retrieve: (args) => {
822
+ return this.request({
823
+ path: api_endpoints_1.getPage.path(args),
824
+ method: api_endpoints_1.getPage.method,
825
+ query: (0, utils_1.pick)(args, api_endpoints_1.getPage.queryParams),
826
+ body: (0, utils_1.pick)(args, api_endpoints_1.getPage.bodyParams),
827
+ auth: args === null || args === undefined ? undefined : args.auth
828
+ });
829
+ },
830
+ update: (args) => {
831
+ return this.request({
832
+ path: api_endpoints_1.updatePage.path(args),
833
+ method: api_endpoints_1.updatePage.method,
834
+ query: (0, utils_1.pick)(args, api_endpoints_1.updatePage.queryParams),
835
+ body: (0, utils_1.pick)(args, api_endpoints_1.updatePage.bodyParams),
836
+ auth: args === null || args === undefined ? undefined : args.auth
837
+ });
838
+ },
839
+ properties: {
840
+ retrieve: (args) => {
841
+ return this.request({
842
+ path: api_endpoints_1.getPageProperty.path(args),
843
+ method: api_endpoints_1.getPageProperty.method,
844
+ query: (0, utils_1.pick)(args, api_endpoints_1.getPageProperty.queryParams),
845
+ body: (0, utils_1.pick)(args, api_endpoints_1.getPageProperty.bodyParams),
846
+ auth: args === null || args === undefined ? undefined : args.auth
847
+ });
848
+ }
849
+ }
850
+ };
851
+ this.users = {
852
+ retrieve: (args) => {
853
+ return this.request({
854
+ path: api_endpoints_1.getUser.path(args),
855
+ method: api_endpoints_1.getUser.method,
856
+ query: (0, utils_1.pick)(args, api_endpoints_1.getUser.queryParams),
857
+ body: (0, utils_1.pick)(args, api_endpoints_1.getUser.bodyParams),
858
+ auth: args === null || args === undefined ? undefined : args.auth
859
+ });
860
+ },
861
+ list: (args) => {
862
+ return this.request({
863
+ path: api_endpoints_1.listUsers.path(),
864
+ method: api_endpoints_1.listUsers.method,
865
+ query: (0, utils_1.pick)(args, api_endpoints_1.listUsers.queryParams),
866
+ body: (0, utils_1.pick)(args, api_endpoints_1.listUsers.bodyParams),
867
+ auth: args === null || args === undefined ? undefined : args.auth
868
+ });
869
+ },
870
+ me: (args) => {
871
+ return this.request({
872
+ path: api_endpoints_1.getSelf.path(),
873
+ method: api_endpoints_1.getSelf.method,
874
+ query: (0, utils_1.pick)(args, api_endpoints_1.getSelf.queryParams),
875
+ body: (0, utils_1.pick)(args, api_endpoints_1.getSelf.bodyParams),
876
+ auth: args === null || args === undefined ? undefined : args.auth
877
+ });
878
+ }
879
+ };
880
+ this.comments = {
881
+ create: (args) => {
882
+ return this.request({
883
+ path: api_endpoints_1.createComment.path(),
884
+ method: api_endpoints_1.createComment.method,
885
+ query: (0, utils_1.pick)(args, api_endpoints_1.createComment.queryParams),
886
+ body: (0, utils_1.pick)(args, api_endpoints_1.createComment.bodyParams),
887
+ auth: args === null || args === undefined ? undefined : args.auth
888
+ });
889
+ },
890
+ list: (args) => {
891
+ return this.request({
892
+ path: api_endpoints_1.listComments.path(),
893
+ method: api_endpoints_1.listComments.method,
894
+ query: (0, utils_1.pick)(args, api_endpoints_1.listComments.queryParams),
895
+ body: (0, utils_1.pick)(args, api_endpoints_1.listComments.bodyParams),
896
+ auth: args === null || args === undefined ? undefined : args.auth
897
+ });
898
+ },
899
+ retrieve: (args) => {
900
+ return this.request({
901
+ path: api_endpoints_1.getComment.path(args),
902
+ method: api_endpoints_1.getComment.method,
903
+ query: (0, utils_1.pick)(args, api_endpoints_1.getComment.queryParams),
904
+ body: (0, utils_1.pick)(args, api_endpoints_1.getComment.bodyParams),
905
+ auth: args === null || args === undefined ? undefined : args.auth
906
+ });
907
+ }
908
+ };
909
+ this.fileUploads = {
910
+ create: (args) => {
911
+ return this.request({
912
+ path: api_endpoints_1.createFileUpload.path(),
913
+ method: api_endpoints_1.createFileUpload.method,
914
+ query: (0, utils_1.pick)(args, api_endpoints_1.createFileUpload.queryParams),
915
+ body: (0, utils_1.pick)(args, api_endpoints_1.createFileUpload.bodyParams),
916
+ auth: args === null || args === undefined ? undefined : args.auth
917
+ });
918
+ },
919
+ retrieve: (args) => {
920
+ return this.request({
921
+ path: api_endpoints_1.getFileUpload.path(args),
922
+ method: api_endpoints_1.getFileUpload.method,
923
+ query: (0, utils_1.pick)(args, api_endpoints_1.getFileUpload.queryParams),
924
+ auth: args === null || args === undefined ? undefined : args.auth
925
+ });
926
+ },
927
+ list: (args) => {
928
+ return this.request({
929
+ path: api_endpoints_1.listFileUploads.path(),
930
+ method: api_endpoints_1.listFileUploads.method,
931
+ query: (0, utils_1.pick)(args, api_endpoints_1.listFileUploads.queryParams),
932
+ auth: args === null || args === undefined ? undefined : args.auth
933
+ });
934
+ },
935
+ send: (args) => {
936
+ return this.request({
937
+ path: api_endpoints_1.sendFileUpload.path(args),
938
+ method: api_endpoints_1.sendFileUpload.method,
939
+ query: (0, utils_1.pick)(args, api_endpoints_1.sendFileUpload.queryParams),
940
+ formDataParams: (0, utils_1.pick)(args, api_endpoints_1.sendFileUpload.formDataParams),
941
+ auth: args === null || args === undefined ? undefined : args.auth
942
+ });
943
+ },
944
+ complete: (args) => {
945
+ return this.request({
946
+ path: api_endpoints_1.completeFileUpload.path(args),
947
+ method: api_endpoints_1.completeFileUpload.method,
948
+ query: (0, utils_1.pick)(args, api_endpoints_1.completeFileUpload.queryParams),
949
+ auth: args === null || args === undefined ? undefined : args.auth
950
+ });
951
+ }
952
+ };
953
+ this.search = (args) => {
954
+ return this.request({
955
+ path: api_endpoints_1.search.path(),
956
+ method: api_endpoints_1.search.method,
957
+ query: (0, utils_1.pick)(args, api_endpoints_1.search.queryParams),
958
+ body: (0, utils_1.pick)(args, api_endpoints_1.search.bodyParams),
959
+ auth: args === null || args === undefined ? undefined : args.auth
960
+ });
961
+ };
962
+ this.oauth = {
963
+ token: (args) => {
964
+ return this.request({
965
+ path: api_endpoints_1.oauthToken.path(),
966
+ method: api_endpoints_1.oauthToken.method,
967
+ query: (0, utils_1.pick)(args, api_endpoints_1.oauthToken.queryParams),
968
+ body: (0, utils_1.pick)(args, api_endpoints_1.oauthToken.bodyParams),
969
+ auth: {
970
+ client_id: args.client_id,
971
+ client_secret: args.client_secret
972
+ }
973
+ });
974
+ },
975
+ introspect: (args) => {
976
+ return this.request({
977
+ path: api_endpoints_1.oauthIntrospect.path(),
978
+ method: api_endpoints_1.oauthIntrospect.method,
979
+ query: (0, utils_1.pick)(args, api_endpoints_1.oauthIntrospect.queryParams),
980
+ body: (0, utils_1.pick)(args, api_endpoints_1.oauthIntrospect.bodyParams),
981
+ auth: {
982
+ client_id: args.client_id,
983
+ client_secret: args.client_secret
984
+ }
985
+ });
986
+ },
987
+ revoke: (args) => {
988
+ return this.request({
989
+ path: api_endpoints_1.oauthRevoke.path(),
990
+ method: api_endpoints_1.oauthRevoke.method,
991
+ query: (0, utils_1.pick)(args, api_endpoints_1.oauthRevoke.queryParams),
992
+ body: (0, utils_1.pick)(args, api_endpoints_1.oauthRevoke.bodyParams),
993
+ auth: {
994
+ client_id: args.client_id,
995
+ client_secret: args.client_secret
996
+ }
997
+ });
998
+ }
999
+ };
1000
+ __classPrivateFieldSet(this, _Client_auth, options === null || options === undefined ? undefined : options.auth, "f");
1001
+ __classPrivateFieldSet(this, _Client_logLevel, (_a = options === null || options === undefined ? undefined : options.logLevel) !== null && _a !== undefined ? _a : logging_1.LogLevel.WARN, "f");
1002
+ __classPrivateFieldSet(this, _Client_logger, (_b = options === null || options === undefined ? undefined : options.logger) !== null && _b !== undefined ? _b : (0, logging_1.makeConsoleLogger)(package_json_1.name), "f");
1003
+ __classPrivateFieldSet(this, _Client_prefixUrl, `${(_c = options === null || options === undefined ? undefined : options.baseUrl) !== null && _c !== undefined ? _c : "https://api.notion.com"}/v1/`, "f");
1004
+ __classPrivateFieldSet(this, _Client_timeoutMs, (_d = options === null || options === undefined ? undefined : options.timeoutMs) !== null && _d !== undefined ? _d : 60000, "f");
1005
+ __classPrivateFieldSet(this, _Client_notionVersion, (_e = options === null || options === undefined ? undefined : options.notionVersion) !== null && _e !== undefined ? _e : Client.defaultNotionVersion, "f");
1006
+ __classPrivateFieldSet(this, _Client_fetch, (_f = options === null || options === undefined ? undefined : options.fetch) !== null && _f !== undefined ? _f : fetch, "f");
1007
+ __classPrivateFieldSet(this, _Client_agent, options === null || options === undefined ? undefined : options.agent, "f");
1008
+ __classPrivateFieldSet(this, _Client_userAgent, `notionhq-client/${package_json_1.version}`, "f");
1009
+ }
1010
+ async request(args) {
1011
+ const { path, method, query, body, formDataParams, auth } = args;
1012
+ this.log(logging_1.LogLevel.INFO, "request start", { method, path });
1013
+ const bodyAsJsonString = !body || Object.entries(body).length === 0 ? undefined : JSON.stringify(body);
1014
+ const url = new URL(`${__classPrivateFieldGet(this, _Client_prefixUrl, "f")}${path}`);
1015
+ if (query) {
1016
+ for (const [key, value] of Object.entries(query)) {
1017
+ if (value !== undefined) {
1018
+ if (Array.isArray(value)) {
1019
+ for (const val of value) {
1020
+ url.searchParams.append(key, decodeURIComponent(val));
1021
+ }
1022
+ } else {
1023
+ url.searchParams.append(key, String(value));
1024
+ }
1025
+ }
1026
+ }
1027
+ }
1028
+ let authorizationHeader;
1029
+ if (typeof auth === "object") {
1030
+ const unencodedCredential = `${auth.client_id}:${auth.client_secret}`;
1031
+ const encodedCredential = Buffer.from(unencodedCredential).toString("base64");
1032
+ authorizationHeader = { authorization: `Basic ${encodedCredential}` };
1033
+ } else {
1034
+ authorizationHeader = this.authAsHeaders(auth);
1035
+ }
1036
+ const headers = {
1037
+ ...args.headers,
1038
+ ...authorizationHeader,
1039
+ "Notion-Version": __classPrivateFieldGet(this, _Client_notionVersion, "f"),
1040
+ "user-agent": __classPrivateFieldGet(this, _Client_userAgent, "f")
1041
+ };
1042
+ if (bodyAsJsonString !== undefined) {
1043
+ headers["content-type"] = "application/json";
1044
+ }
1045
+ let formData;
1046
+ if (formDataParams) {
1047
+ delete headers["content-type"];
1048
+ formData = new FormData;
1049
+ for (const [key, value] of Object.entries(formDataParams)) {
1050
+ if (typeof value === "string") {
1051
+ formData.append(key, value);
1052
+ } else if (typeof value === "object") {
1053
+ formData.append(key, typeof value.data === "object" ? value.data : new Blob([value.data]), value.filename);
1054
+ }
1055
+ }
1056
+ }
1057
+ try {
1058
+ const response = await errors_1.RequestTimeoutError.rejectAfterTimeout(__classPrivateFieldGet(this, _Client_fetch, "f").call(this, url.toString(), {
1059
+ method: method.toUpperCase(),
1060
+ headers,
1061
+ body: bodyAsJsonString !== null && bodyAsJsonString !== undefined ? bodyAsJsonString : formData,
1062
+ agent: __classPrivateFieldGet(this, _Client_agent, "f")
1063
+ }), __classPrivateFieldGet(this, _Client_timeoutMs, "f"));
1064
+ const responseText = await response.text();
1065
+ if (!response.ok) {
1066
+ throw (0, errors_1.buildRequestError)(response, responseText);
1067
+ }
1068
+ const responseJson = JSON.parse(responseText);
1069
+ this.log(logging_1.LogLevel.INFO, "request success", {
1070
+ method,
1071
+ path,
1072
+ ..."request_id" in responseJson && responseJson.request_id ? { requestId: responseJson.request_id } : {}
1073
+ });
1074
+ return responseJson;
1075
+ } catch (error) {
1076
+ if (!(0, errors_1.isNotionClientError)(error)) {
1077
+ throw error;
1078
+ }
1079
+ this.log(logging_1.LogLevel.WARN, "request fail", {
1080
+ code: error.code,
1081
+ message: error.message,
1082
+ ..."request_id" in error && error.request_id ? { requestId: error.request_id } : {}
1083
+ });
1084
+ if ((0, errors_1.isHTTPResponseError)(error)) {
1085
+ this.log(logging_1.LogLevel.DEBUG, "failed response body", {
1086
+ body: error.body
1087
+ });
1088
+ }
1089
+ throw error;
1090
+ }
1091
+ }
1092
+ log(level, message, extraInfo) {
1093
+ if ((0, logging_1.logLevelSeverity)(level) >= (0, logging_1.logLevelSeverity)(__classPrivateFieldGet(this, _Client_logLevel, "f"))) {
1094
+ __classPrivateFieldGet(this, _Client_logger, "f").call(this, level, message, extraInfo);
1095
+ }
1096
+ }
1097
+ authAsHeaders(auth) {
1098
+ const headers = {};
1099
+ const authHeaderValue = auth !== null && auth !== undefined ? auth : __classPrivateFieldGet(this, _Client_auth, "f");
1100
+ if (authHeaderValue !== undefined) {
1101
+ headers["authorization"] = `Bearer ${authHeaderValue}`;
1102
+ }
1103
+ return headers;
1104
+ }
1105
+ }
1106
+ _Client_auth = new WeakMap, _Client_logLevel = new WeakMap, _Client_logger = new WeakMap, _Client_prefixUrl = new WeakMap, _Client_timeoutMs = new WeakMap, _Client_notionVersion = new WeakMap, _Client_fetch = new WeakMap, _Client_agent = new WeakMap, _Client_userAgent = new WeakMap;
1107
+ Client.defaultNotionVersion = "2025-09-03";
1108
+ exports.default = Client;
1109
+ });
1110
+
1111
+ // node_modules/@notionhq/client/build/src/helpers.js
1112
+ var require_helpers = __commonJS((exports) => {
1113
+ Object.defineProperty(exports, "__esModule", { value: true });
1114
+ exports.iteratePaginatedAPI = iteratePaginatedAPI;
1115
+ exports.collectPaginatedAPI = collectPaginatedAPI;
1116
+ exports.iterateDataSourceTemplates = iterateDataSourceTemplates;
1117
+ exports.collectDataSourceTemplates = collectDataSourceTemplates;
1118
+ exports.isFullBlock = isFullBlock;
1119
+ exports.isFullPage = isFullPage;
1120
+ exports.isFullDataSource = isFullDataSource;
1121
+ exports.isFullDatabase = isFullDatabase;
1122
+ exports.isFullPageOrDataSource = isFullPageOrDataSource;
1123
+ exports.isFullUser = isFullUser;
1124
+ exports.isFullComment = isFullComment;
1125
+ exports.isTextRichTextItemResponse = isTextRichTextItemResponse;
1126
+ exports.isEquationRichTextItemResponse = isEquationRichTextItemResponse;
1127
+ exports.isMentionRichTextItemResponse = isMentionRichTextItemResponse;
1128
+ exports.extractNotionId = extractNotionId;
1129
+ exports.extractDatabaseId = extractDatabaseId;
1130
+ exports.extractPageId = extractPageId;
1131
+ exports.extractBlockId = extractBlockId;
1132
+ async function* iteratePaginatedAPI(listFn, firstPageArgs) {
1133
+ let nextCursor = firstPageArgs.start_cursor;
1134
+ do {
1135
+ const response = await listFn({
1136
+ ...firstPageArgs,
1137
+ start_cursor: nextCursor
1138
+ });
1139
+ yield* response.results;
1140
+ nextCursor = response.next_cursor;
1141
+ } while (nextCursor);
1142
+ }
1143
+ async function collectPaginatedAPI(listFn, firstPageArgs) {
1144
+ const results = [];
1145
+ for await (const item of iteratePaginatedAPI(listFn, firstPageArgs)) {
1146
+ results.push(item);
1147
+ }
1148
+ return results;
1149
+ }
1150
+ async function* iterateDataSourceTemplates(client, args) {
1151
+ let nextCursor = args.start_cursor;
1152
+ do {
1153
+ const response = await client.dataSources.listTemplates({
1154
+ ...args,
1155
+ start_cursor: nextCursor
1156
+ });
1157
+ yield* response.templates;
1158
+ nextCursor = response.next_cursor;
1159
+ } while (nextCursor);
1160
+ }
1161
+ async function collectDataSourceTemplates(client, args) {
1162
+ const results = [];
1163
+ for await (const template of iterateDataSourceTemplates(client, args)) {
1164
+ results.push(template);
1165
+ }
1166
+ return results;
1167
+ }
1168
+ function isFullBlock(response) {
1169
+ return response.object === "block" && "type" in response;
1170
+ }
1171
+ function isFullPage(response) {
1172
+ return response.object === "page" && "url" in response;
1173
+ }
1174
+ function isFullDataSource(response) {
1175
+ return response.object === "data_source";
1176
+ }
1177
+ function isFullDatabase(response) {
1178
+ return response.object === "database";
1179
+ }
1180
+ function isFullPageOrDataSource(response) {
1181
+ if (response.object === "data_source") {
1182
+ return isFullDataSource(response);
1183
+ } else {
1184
+ return isFullPage(response);
1185
+ }
1186
+ }
1187
+ function isFullUser(response) {
1188
+ return "type" in response;
1189
+ }
1190
+ function isFullComment(response) {
1191
+ return "created_by" in response;
1192
+ }
1193
+ function isTextRichTextItemResponse(richText) {
1194
+ return richText.type === "text";
1195
+ }
1196
+ function isEquationRichTextItemResponse(richText) {
1197
+ return richText.type === "equation";
1198
+ }
1199
+ function isMentionRichTextItemResponse(richText) {
1200
+ return richText.type === "mention";
1201
+ }
1202
+ function extractNotionId(urlOrId) {
1203
+ if (!urlOrId || typeof urlOrId !== "string") {
1204
+ return null;
1205
+ }
1206
+ const trimmed = urlOrId.trim();
1207
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1208
+ if (uuidRegex.test(trimmed)) {
1209
+ return trimmed.toLowerCase();
1210
+ }
1211
+ const compactUuidRegex = /^[0-9a-f]{32}$/i;
1212
+ if (compactUuidRegex.test(trimmed)) {
1213
+ return formatUuid(trimmed);
1214
+ }
1215
+ const pathMatch = trimmed.match(/\/[^/?#]*-([0-9a-f]{32})(?:[/?#]|$)/i);
1216
+ if (pathMatch && pathMatch[1]) {
1217
+ return formatUuid(pathMatch[1]);
1218
+ }
1219
+ const queryMatch = trimmed.match(/[?&](?:p|page_id|database_id)=([0-9a-f]{32})/i);
1220
+ if (queryMatch && queryMatch[1]) {
1221
+ return formatUuid(queryMatch[1]);
1222
+ }
1223
+ const anyMatch = trimmed.match(/([0-9a-f]{32})/i);
1224
+ if (anyMatch && anyMatch[1]) {
1225
+ return formatUuid(anyMatch[1]);
1226
+ }
1227
+ return null;
1228
+ }
1229
+ function formatUuid(compactId) {
1230
+ const clean = compactId.toLowerCase();
1231
+ return `${clean.slice(0, 8)}-${clean.slice(8, 12)}-${clean.slice(12, 16)}-${clean.slice(16, 20)}-${clean.slice(20, 32)}`;
1232
+ }
1233
+ function extractDatabaseId(databaseUrl) {
1234
+ return extractNotionId(databaseUrl);
1235
+ }
1236
+ function extractPageId(pageUrl) {
1237
+ return extractNotionId(pageUrl);
1238
+ }
1239
+ function extractBlockId(urlWithBlock) {
1240
+ if (!urlWithBlock || typeof urlWithBlock !== "string") {
1241
+ return null;
1242
+ }
1243
+ const blockMatch = urlWithBlock.match(/#(?:block-)?([0-9a-f]{32})/i);
1244
+ if (blockMatch && blockMatch[1]) {
1245
+ return formatUuid(blockMatch[1]);
1246
+ }
1247
+ return null;
1248
+ }
1249
+ });
1250
+
1251
+ // node_modules/@notionhq/client/build/src/index.js
1252
+ var require_src = __commonJS((exports) => {
1253
+ Object.defineProperty(exports, "__esModule", { value: true });
1254
+ exports.extractBlockId = exports.extractPageId = exports.extractDatabaseId = exports.extractNotionId = exports.isFullPageOrDataSource = exports.isFullComment = exports.isFullUser = exports.isFullPage = exports.isFullDatabase = exports.isFullDataSource = exports.isFullBlock = exports.iterateDataSourceTemplates = exports.collectDataSourceTemplates = exports.iteratePaginatedAPI = exports.collectPaginatedAPI = exports.isNotionClientError = exports.RequestTimeoutError = exports.UnknownHTTPResponseError = exports.APIResponseError = exports.ClientErrorCode = exports.APIErrorCode = exports.LogLevel = exports.Client = undefined;
1255
+ var Client_1 = require_Client();
1256
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function() {
1257
+ return Client_1.default;
1258
+ } });
1259
+ var logging_1 = require_logging();
1260
+ Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
1261
+ return logging_1.LogLevel;
1262
+ } });
1263
+ var errors_1 = require_errors();
1264
+ Object.defineProperty(exports, "APIErrorCode", { enumerable: true, get: function() {
1265
+ return errors_1.APIErrorCode;
1266
+ } });
1267
+ Object.defineProperty(exports, "ClientErrorCode", { enumerable: true, get: function() {
1268
+ return errors_1.ClientErrorCode;
1269
+ } });
1270
+ Object.defineProperty(exports, "APIResponseError", { enumerable: true, get: function() {
1271
+ return errors_1.APIResponseError;
1272
+ } });
1273
+ Object.defineProperty(exports, "UnknownHTTPResponseError", { enumerable: true, get: function() {
1274
+ return errors_1.UnknownHTTPResponseError;
1275
+ } });
1276
+ Object.defineProperty(exports, "RequestTimeoutError", { enumerable: true, get: function() {
1277
+ return errors_1.RequestTimeoutError;
1278
+ } });
1279
+ Object.defineProperty(exports, "isNotionClientError", { enumerable: true, get: function() {
1280
+ return errors_1.isNotionClientError;
1281
+ } });
1282
+ var helpers_1 = require_helpers();
1283
+ Object.defineProperty(exports, "collectPaginatedAPI", { enumerable: true, get: function() {
1284
+ return helpers_1.collectPaginatedAPI;
1285
+ } });
1286
+ Object.defineProperty(exports, "iteratePaginatedAPI", { enumerable: true, get: function() {
1287
+ return helpers_1.iteratePaginatedAPI;
1288
+ } });
1289
+ Object.defineProperty(exports, "collectDataSourceTemplates", { enumerable: true, get: function() {
1290
+ return helpers_1.collectDataSourceTemplates;
1291
+ } });
1292
+ Object.defineProperty(exports, "iterateDataSourceTemplates", { enumerable: true, get: function() {
1293
+ return helpers_1.iterateDataSourceTemplates;
1294
+ } });
1295
+ Object.defineProperty(exports, "isFullBlock", { enumerable: true, get: function() {
1296
+ return helpers_1.isFullBlock;
1297
+ } });
1298
+ Object.defineProperty(exports, "isFullDataSource", { enumerable: true, get: function() {
1299
+ return helpers_1.isFullDataSource;
1300
+ } });
1301
+ Object.defineProperty(exports, "isFullDatabase", { enumerable: true, get: function() {
1302
+ return helpers_1.isFullDatabase;
1303
+ } });
1304
+ Object.defineProperty(exports, "isFullPage", { enumerable: true, get: function() {
1305
+ return helpers_1.isFullPage;
1306
+ } });
1307
+ Object.defineProperty(exports, "isFullUser", { enumerable: true, get: function() {
1308
+ return helpers_1.isFullUser;
1309
+ } });
1310
+ Object.defineProperty(exports, "isFullComment", { enumerable: true, get: function() {
1311
+ return helpers_1.isFullComment;
1312
+ } });
1313
+ Object.defineProperty(exports, "isFullPageOrDataSource", { enumerable: true, get: function() {
1314
+ return helpers_1.isFullPageOrDataSource;
1315
+ } });
1316
+ Object.defineProperty(exports, "extractNotionId", { enumerable: true, get: function() {
1317
+ return helpers_1.extractNotionId;
1318
+ } });
1319
+ Object.defineProperty(exports, "extractDatabaseId", { enumerable: true, get: function() {
1320
+ return helpers_1.extractDatabaseId;
1321
+ } });
1322
+ Object.defineProperty(exports, "extractPageId", { enumerable: true, get: function() {
1323
+ return helpers_1.extractPageId;
1324
+ } });
1325
+ Object.defineProperty(exports, "extractBlockId", { enumerable: true, get: function() {
1326
+ return helpers_1.extractBlockId;
1327
+ } });
1328
+ });
1329
+
1330
+ // src/db-client/DatabaseClient.ts
1331
+ var import_client = __toESM(require_src(), 1);
1332
+
1333
+ // src/ast/constants.ts
1334
+ import path from "path";
1335
+ import { fileURLToPath } from "url";
1336
+ var __filename2 = fileURLToPath(import.meta.url);
1337
+ var __dirname2 = path.dirname(__filename2);
1338
+ var PACKAGE_ROOT = path.resolve(__dirname2, "../../");
1339
+ var IS_DEV = process.cwd() === PACKAGE_ROOT;
1340
+ var DATABASES_DIR = path.join(process.cwd(), "generated");
1341
+ var AST_RUNTIME_CONSTANTS = {
1342
+ NOTION_API_VERSION: "2025-09-03",
1343
+ PACKAGE_LOG_PREFIX: "[@elumixor/notion-orm]",
1344
+ CLI_GENERATE_COMMAND: "notion generate",
1345
+ SCHEMA_DRIFT_PREFIX: "Schema drift detected",
1346
+ SCHEMA_DRIFT_HELP_MESSAGE: "Run `notion generate` to refresh all database schemas."
1347
+ };
1348
+
1349
+ // src/db-client/add.ts
1350
+ function buildPropertyValueForAddPage(args) {
1351
+ const { type, value } = args;
1352
+ if (type === "select" && typeof value === "string") {
1353
+ return selectCall({ value });
1354
+ } else if (type === "multi_select" && Array.isArray(value)) {
1355
+ return multiSelectCall({ value });
1356
+ } else if (type === "status" && typeof value === "string") {
1357
+ return statusCall({ option: value });
1358
+ } else if (type === "number" && typeof value === "number") {
1359
+ return numberCall({ value });
1360
+ } else if (type === "email" && typeof value === "string") {
1361
+ return emailCall({ value });
1362
+ } else if (type === "date" && typeof value === "object") {
1363
+ return dateCall({ value });
1364
+ } else if (type === "phone_number" && typeof value === "string") {
1365
+ return phoneNumberCall({ value });
1366
+ } else if (type === "url" && typeof value === "string") {
1367
+ return urlCall({ url: value });
1368
+ } else if (type === "checkbox" && typeof value === "boolean") {
1369
+ return checkboxCall({ checked: value });
1370
+ } else if (type === "title" && typeof value === "string") {
1371
+ return titleCall({ title: value });
1372
+ } else if (type === "rich_text" && typeof value === "string") {
1373
+ return textCall({ text: value });
1374
+ } else {
1375
+ console.error(`'${AST_RUNTIME_CONSTANTS.PACKAGE_LOG_PREFIX} ${type}' column type currently not supported`);
1376
+ }
1377
+ }
1378
+ var selectCall = (args) => {
1379
+ const { value } = args;
1380
+ const select = {
1381
+ name: value
1382
+ };
1383
+ return { select };
1384
+ };
1385
+ var dateCall = (args) => {
1386
+ const { value } = args;
1387
+ return { date: value };
1388
+ };
1389
+ var phoneNumberCall = (args) => {
1390
+ const { value } = args;
1391
+ return { phone_number: value };
1392
+ };
1393
+ var statusCall = (args) => {
1394
+ const { option } = args;
1395
+ const status = {
1396
+ name: option
1397
+ };
1398
+ return { status };
1399
+ };
1400
+ var multiSelectCall = (args) => {
1401
+ const { value } = args;
1402
+ const multi_select = value.map((option) => ({ name: option }));
1403
+ return { multi_select };
1404
+ };
1405
+ var textCall = (args) => {
1406
+ const { text } = args;
1407
+ const rich_text = [
1408
+ {
1409
+ text: {
1410
+ content: text
1411
+ }
1412
+ }
1413
+ ];
1414
+ return { rich_text };
1415
+ };
1416
+ var titleCall = (args) => {
1417
+ const { title } = args;
1418
+ const titleObject = [
1419
+ {
1420
+ text: {
1421
+ content: title
1422
+ }
1423
+ }
1424
+ ];
1425
+ return { title: titleObject };
1426
+ };
1427
+ var numberCall = (args) => {
1428
+ const { value: number } = args;
1429
+ return { number };
1430
+ };
1431
+ var urlCall = (args) => {
1432
+ const { url } = args;
1433
+ return { url };
1434
+ };
1435
+ var checkboxCall = (args) => {
1436
+ const { checked: checkbox } = args;
1437
+ return { checkbox };
1438
+ };
1439
+ var emailCall = (args) => {
1440
+ const { value } = args;
1441
+ return { email: value };
1442
+ };
1443
+
1444
+ // src/helpers.ts
1445
+ function camelize(str) {
1446
+ const cleaned = str.replace(/[^a-zA-Z0-9\s]/g, "");
1447
+ return cleaned.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
1448
+ if (+match === 0)
1449
+ return "";
1450
+ return index === 0 ? match.toLowerCase() : match.toUpperCase();
1451
+ });
1452
+ }
1453
+
1454
+ // src/db-client/query.ts
1455
+ function buildQueryResponse(res, camelPropertyNameToNameAndTypeMap, validateSchema) {
1456
+ const results = res.results.map((result, index) => {
1457
+ if (result.object === "page" && !("properties" in result)) {
1458
+ console.log("Skipping this page: ", { result });
1459
+ return;
1460
+ }
1461
+ const simpleResult = { id: result.id };
1462
+ const properties = Object.entries(result.properties);
1463
+ for (const [columnName, result2] of properties) {
1464
+ const camelizeColumnName = camelize(columnName);
1465
+ const columnType = camelPropertyNameToNameAndTypeMap[camelizeColumnName]?.type;
1466
+ if (columnType) {
1467
+ simpleResult[camelizeColumnName] = getResponseValue(columnType, result2);
1468
+ }
1469
+ }
1470
+ if (index === 0) {
1471
+ validateSchema(simpleResult);
1472
+ }
1473
+ return simpleResult;
1474
+ }).filter((result) => result !== undefined);
1475
+ return results;
1476
+ }
1477
+ function getResponseValue(prop, x) {
1478
+ switch (prop) {
1479
+ case "select": {
1480
+ const { select } = x;
1481
+ if (select) {
1482
+ return select["name"];
1483
+ }
1484
+ return null;
1485
+ }
1486
+ case "title": {
1487
+ const { title } = x;
1488
+ if (title) {
1489
+ const combinedText = title.map(({ plain_text }) => plain_text);
1490
+ return combinedText.join("");
1491
+ }
1492
+ return null;
1493
+ }
1494
+ case "url": {
1495
+ const { url } = x;
1496
+ return url;
1497
+ }
1498
+ case "multi_select": {
1499
+ const { multi_select } = x;
1500
+ if (multi_select) {
1501
+ const multi_selectArr = multi_select.map(({ name }) => name);
1502
+ return multi_selectArr;
1503
+ }
1504
+ return null;
1505
+ }
1506
+ case "checkbox": {
1507
+ const { checkbox } = x;
1508
+ return Boolean(checkbox);
1509
+ }
1510
+ case "status": {
1511
+ const { status } = x;
1512
+ if (status) {
1513
+ return status["name"];
1514
+ }
1515
+ return null;
1516
+ }
1517
+ case "rich_text": {
1518
+ const { rich_text } = x;
1519
+ if (rich_text && Array.isArray(rich_text)) {
1520
+ const combinedText = rich_text.map(({ plain_text }) => plain_text);
1521
+ return combinedText.join("");
1522
+ }
1523
+ return null;
1524
+ }
1525
+ case "number": {
1526
+ const { number } = x;
1527
+ return number;
1528
+ }
1529
+ case "formula": {
1530
+ const { formula } = x;
1531
+ if (!formula)
1532
+ return null;
1533
+ if (formula.type === "date")
1534
+ return formula.date;
1535
+ return formula[formula.type] ?? null;
1536
+ }
1537
+ case "rollup": {
1538
+ const { rollup } = x;
1539
+ if (!rollup)
1540
+ return null;
1541
+ switch (rollup.type) {
1542
+ case "number":
1543
+ return rollup.number;
1544
+ case "date":
1545
+ return rollup.date;
1546
+ case "array":
1547
+ return rollup.array;
1548
+ default:
1549
+ return null;
1550
+ }
1551
+ }
1552
+ case "relation": {
1553
+ const { relation } = x;
1554
+ if (!Array.isArray(relation))
1555
+ return null;
1556
+ return relation.map(({ id }) => id);
1557
+ }
1558
+ default: {
1559
+ return null;
1560
+ }
1561
+ }
1562
+ }
1563
+ function recursivelyBuildFilter(queryFilter, camelPropertyNameToNameAndTypeMap) {
1564
+ for (const prop in queryFilter) {
1565
+ if (prop === "and" || prop === "or") {
1566
+ const compoundFilters = queryFilter[prop];
1567
+ const compoundApiFilters = compoundFilters.map((i) => {
1568
+ return recursivelyBuildFilter(i, camelPropertyNameToNameAndTypeMap);
1569
+ });
1570
+ const temp = {
1571
+ ...prop === "and" ? { and: compoundApiFilters } : { or: compoundApiFilters }
1572
+ };
1573
+ return temp;
1574
+ } else {
1575
+ const propType = camelPropertyNameToNameAndTypeMap[prop].type;
1576
+ const temp = {
1577
+ property: camelPropertyNameToNameAndTypeMap[prop].columnName
1578
+ };
1579
+ temp[propType] = queryFilter[prop];
1580
+ return temp;
1581
+ }
1582
+ }
1583
+ }
1584
+
1585
+ // src/db-client/DatabaseClient.ts
1586
+ class DatabaseClient {
1587
+ client;
1588
+ id;
1589
+ camelPropertyNameToNameAndTypeMap;
1590
+ schema;
1591
+ name;
1592
+ loggedSchemaValidationIssues;
1593
+ constructor(args) {
1594
+ const fetchImpl = typeof fetch !== "undefined" ? fetch.bind(globalThis) : undefined;
1595
+ this.client = new import_client.Client({
1596
+ auth: args.auth,
1597
+ notionVersion: AST_RUNTIME_CONSTANTS.NOTION_API_VERSION,
1598
+ fetch: fetchImpl
1599
+ });
1600
+ this.id = args.id;
1601
+ this.camelPropertyNameToNameAndTypeMap = args.camelPropertyNameToNameAndTypeMap;
1602
+ this.schema = args.schema;
1603
+ this.name = args.name;
1604
+ this.loggedSchemaValidationIssues = new Set;
1605
+ }
1606
+ async add(args) {
1607
+ const { properties: pageObject, icon } = args;
1608
+ const callBody = {
1609
+ parent: {
1610
+ data_source_id: this.id,
1611
+ type: "data_source_id"
1612
+ },
1613
+ properties: {}
1614
+ };
1615
+ callBody.icon = icon;
1616
+ Object.entries(pageObject).forEach(([propertyName, value]) => {
1617
+ const { type, columnName } = this.camelPropertyNameToNameAndTypeMap[propertyName];
1618
+ const columnObject = buildPropertyValueForAddPage({
1619
+ type,
1620
+ value
1621
+ });
1622
+ if (callBody.properties && columnObject) {
1623
+ callBody.properties[columnName] = columnObject;
1624
+ }
1625
+ });
1626
+ return await this.client.pages.create(callBody);
1627
+ }
1628
+ async update(id, properties, icon) {
1629
+ const callBody = { page_id: id, properties: {} };
1630
+ if (icon !== undefined)
1631
+ callBody.icon = icon;
1632
+ Object.entries(properties).forEach(([propertyName, value]) => {
1633
+ const { type, columnName } = this.camelPropertyNameToNameAndTypeMap[propertyName];
1634
+ const columnObject = buildPropertyValueForAddPage({ type, value });
1635
+ if (callBody.properties && columnObject) {
1636
+ callBody.properties[columnName] = columnObject;
1637
+ }
1638
+ });
1639
+ await this.client.pages.update(callBody);
1640
+ }
1641
+ async delete(id) {
1642
+ await this.client.pages.update({ page_id: id, archived: true });
1643
+ }
1644
+ async upsert(args) {
1645
+ const queryCall = this.buildQueryCall({ filter: args.where });
1646
+ const response = await this.client.dataSources.query({ ...queryCall, page_size: 1 });
1647
+ if (response.results.length > 0) {
1648
+ const existingId = response.results[0].id;
1649
+ await this.update(existingId, args.properties, args.icon);
1650
+ return { created: false, id: existingId };
1651
+ }
1652
+ const created = await this.add({ properties: args.properties, icon: args.icon });
1653
+ return { created: true, id: created.id };
1654
+ }
1655
+ query(query) {
1656
+ const queryCall = this.buildQueryCall(query);
1657
+ if (query.pagination)
1658
+ return this.paginatedIterable(queryCall, query);
1659
+ return this.fetchAllPages(queryCall, query);
1660
+ }
1661
+ buildQueryCall(query) {
1662
+ const queryCall = { data_source_id: this.id };
1663
+ if (query.sort?.length) {
1664
+ queryCall["sorts"] = query.sort.map((s) => {
1665
+ if (!("property" in s))
1666
+ return s;
1667
+ return { ...s, property: this.camelPropertyNameToNameAndTypeMap[s.property]?.columnName ?? s.property };
1668
+ });
1669
+ }
1670
+ if (query.filter) {
1671
+ queryCall["filter"] = recursivelyBuildFilter(query.filter, this.camelPropertyNameToNameAndTypeMap);
1672
+ }
1673
+ return queryCall;
1674
+ }
1675
+ async fetchAllPages(queryCall, query) {
1676
+ const allResults = [];
1677
+ let cursor;
1678
+ let isFirst = true;
1679
+ do {
1680
+ const response = await this.client.dataSources.query({ ...queryCall, start_cursor: cursor, page_size: 100 });
1681
+ const page = buildQueryResponse(response, this.camelPropertyNameToNameAndTypeMap, isFirst ? (r) => this.validateDatabaseSchema(r) : () => {});
1682
+ isFirst = false;
1683
+ allResults.push(...this.applySelectOmit(page, query.select, query.omit));
1684
+ cursor = response.has_more ? response.next_cursor ?? undefined : undefined;
1685
+ } while (cursor && (!query.limit || allResults.length < query.limit));
1686
+ return query.limit ? allResults.slice(0, query.limit) : allResults;
1687
+ }
1688
+ paginatedIterable(queryCall, query) {
1689
+ const self = this;
1690
+ const pageSize = query.pagination.pageSize;
1691
+ return {
1692
+ [Symbol.asyncIterator]: async function* () {
1693
+ let cursor;
1694
+ let isFirst = true;
1695
+ let yielded = 0;
1696
+ do {
1697
+ const response = await self.client.dataSources.query({ ...queryCall, start_cursor: cursor, page_size: pageSize });
1698
+ const page = buildQueryResponse(response, self.camelPropertyNameToNameAndTypeMap, isFirst ? (r) => self.validateDatabaseSchema(r) : () => {});
1699
+ isFirst = false;
1700
+ for (const item of self.applySelectOmit(page, query.select, query.omit)) {
1701
+ yield item;
1702
+ if (query.limit && ++yielded >= query.limit)
1703
+ return;
1704
+ }
1705
+ cursor = response.has_more ? response.next_cursor ?? undefined : undefined;
1706
+ } while (cursor);
1707
+ }
1708
+ };
1709
+ }
1710
+ applySelectOmit(results, select, omit) {
1711
+ if (!select && !omit)
1712
+ return results;
1713
+ return results.map((result) => {
1714
+ const out = { id: result.id };
1715
+ if (select) {
1716
+ for (const key of Object.keys(select))
1717
+ if (key in result)
1718
+ out[key] = result[key];
1719
+ } else if (omit) {
1720
+ for (const key of Object.keys(result))
1721
+ if (key !== "id" && !omit[key])
1722
+ out[key] = result[key];
1723
+ }
1724
+ return out;
1725
+ });
1726
+ }
1727
+ validateDatabaseSchema(result) {
1728
+ if (!this.schema) {
1729
+ return;
1730
+ }
1731
+ const schemaLabel = this.name ?? this.id;
1732
+ const remoteColumnNames = new Set(Object.keys(result));
1733
+ const missingProperties = [];
1734
+ for (const propName in this.camelPropertyNameToNameAndTypeMap) {
1735
+ if (!remoteColumnNames.has(propName)) {
1736
+ missingProperties.push(propName);
1737
+ }
1738
+ }
1739
+ if (missingProperties.length > 0) {
1740
+ const issueSignature2 = JSON.stringify({
1741
+ type: "missing_properties",
1742
+ properties: missingProperties
1743
+ });
1744
+ if (!this.loggedSchemaValidationIssues.has(issueSignature2)) {
1745
+ this.loggedSchemaValidationIssues.add(issueSignature2);
1746
+ console.error(`⚠️ ${AST_RUNTIME_CONSTANTS.PACKAGE_LOG_PREFIX} ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_PREFIX} for the following Notion database ${schemaLabel}
1747
+
1748
+ Missing properties: ${missingProperties.map((prop) => `\`${prop}\``).join(", ")}
1749
+
1750
+
1751
+ ✅ ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_HELP_MESSAGE}
1752
+ `);
1753
+ }
1754
+ }
1755
+ for (const remoteColName of remoteColumnNames) {
1756
+ if (remoteColName === "id")
1757
+ continue;
1758
+ if (!this.camelPropertyNameToNameAndTypeMap[remoteColName]) {
1759
+ const issueSignature2 = JSON.stringify({
1760
+ type: "unexpected_property",
1761
+ property: remoteColName
1762
+ });
1763
+ if (!this.loggedSchemaValidationIssues.has(issueSignature2)) {
1764
+ this.loggedSchemaValidationIssues.add(issueSignature2);
1765
+ console.error(`⚠️ ${AST_RUNTIME_CONSTANTS.PACKAGE_LOG_PREFIX} ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_PREFIX} for the following Notion database ${schemaLabel}
1766
+
1767
+ Unexpected property found in remote data: \`${remoteColName}\`
1768
+
1769
+
1770
+ ✅ ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_HELP_MESSAGE}
1771
+ `);
1772
+ }
1773
+ }
1774
+ }
1775
+ const parseResult = this.schema.safeParse(result);
1776
+ if (parseResult.success) {
1777
+ return;
1778
+ }
1779
+ const issueSignature = JSON.stringify(parseResult.error.issues.map((issue) => ({
1780
+ code: issue.code,
1781
+ path: issue.path,
1782
+ message: issue.message
1783
+ })));
1784
+ if (this.loggedSchemaValidationIssues.has(issueSignature)) {
1785
+ return;
1786
+ }
1787
+ this.loggedSchemaValidationIssues.add(issueSignature);
1788
+ console.error(`⚠️ ${AST_RUNTIME_CONSTANTS.PACKAGE_LOG_PREFIX} ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_PREFIX} for the following Notion database ${schemaLabel}
1789
+
1790
+ Validation issues: ${parseResult.error.issues.map((issue) => `\`${issue.path.join(".")}: ${issue.message}\``).join(", ")}
1791
+
1792
+
1793
+ ✅ ${AST_RUNTIME_CONSTANTS.SCHEMA_DRIFT_HELP_MESSAGE}
1794
+ `);
1795
+ console.log("Validation details:", {
1796
+ issues: parseResult.error.issues,
1797
+ result
1798
+ });
1799
+ }
1800
+ }
1801
+ export {
1802
+ DatabaseClient
1803
+ };