@secret-momo/notion 1.0.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/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # notion
2
+ 封装 Notion 的一些 API,方便个人使用。
@@ -0,0 +1,3 @@
1
+ import { Client } from '@notionhq/client';
2
+ export declare function newNotionClient(): Client;
3
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AA+C1C,wBAAgB,eAAe,WAK9B"}
package/lib/client.js ADDED
@@ -0,0 +1,39 @@
1
+ import { Client } from '@notionhq/client';
2
+ import { warn, sleep } from '@secret-momo/utils';
3
+
4
+ const NOTION_TLS_MAX_RETRIES = 5;
5
+ function isCertOrTlsError(message) {
6
+ return ["certificate", "unknown cert", "ssl", "tls"].some((m) => message.includes(m));
7
+ }
8
+ async function customFetch(input, init) {
9
+ const mergedInit = {
10
+ ...init,
11
+ headers: {
12
+ ...init?.headers,
13
+ Connection: "close"
14
+ // 关闭 HTTP keep-alive,防止 Bun 底层连接复用带来的问题
15
+ }
16
+ };
17
+ for (let attempt = 0; attempt <= NOTION_TLS_MAX_RETRIES; attempt++) {
18
+ try {
19
+ return await fetch(input, mergedInit);
20
+ } catch (error) {
21
+ const message = (error?.message ?? String(error)).toLowerCase();
22
+ const isLastAttempt = attempt >= NOTION_TLS_MAX_RETRIES;
23
+ if (isLastAttempt || !isCertOrTlsError(message)) {
24
+ throw error;
25
+ }
26
+ warn(`Notion TLS \u91CD\u8BD5\u7B2C ${attempt + 1} \u6B21, \u9519\u8BEF\u4FE1\u606F\uFF1A${message}`);
27
+ await sleep(1e3 * attempt);
28
+ }
29
+ }
30
+ throw new Error("Unexpected notion fetch retry failure");
31
+ }
32
+ function newNotionClient() {
33
+ return new Client({
34
+ auth: process.env.NOTION_AUTH_TOKEN,
35
+ fetch: customFetch
36
+ });
37
+ }
38
+
39
+ export { newNotionClient };
package/lib/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type NumberPropertyItemObjectResponse, type PageObjectResponse, type RichTextItemResponse } from '@notionhq/client';
2
+ import { newNotionClient } from './client';
3
+ export { uploadLocalFileToPageBody, uploadLocalImageToPageBody, uploadLocalVideoToPageBody, } from './upload';
4
+ export { newNotionClient };
5
+ export type { NumberPropertyItemObjectResponse, PageObjectResponse, RichTextItemResponse };
6
+ export declare function n(num?: number): number | null;
7
+ export declare function traverseDataSource(cb: (item: PageObjectResponse) => void): Promise<void>;
8
+ /**
9
+ * 从 API 返回的 page(或任意带 `id` 的对象)拼出可在浏览器打开的 Notion 页面地址
10
+ * @param pageId - 页面 ID
11
+ * @returns 可在浏览器打开的 Notion 页面地址
12
+ */
13
+ export declare function buildNotionPageWebUrl(pageId: string): string;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gCAAgC,EACrC,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EAC1B,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,eAAe,EAAE,CAAC;AAC3B,YAAY,EAAE,gCAAgC,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,CAAC;AAE3F,wBAAgB,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,iBAE7B;AAED,wBAAsB,kBAAkB,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,kBAAkB,KAAK,IAAI,iBAM9E;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE5D"}
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import '@notionhq/client';
2
+ import { newNotionClient } from './client.js';
3
+ export { uploadLocalFileToPageBody, uploadLocalImageToPageBody, uploadLocalVideoToPageBody } from './upload.js';
4
+
5
+ function n(num) {
6
+ return num ?? null;
7
+ }
8
+ async function traverseDataSource(cb) {
9
+ const data = await newNotionClient().dataSources.query({
10
+ data_source_id: process.env.NOTION_DATA_SOURCE_ID ?? ""
11
+ });
12
+ data.results.forEach((item) => cb(item));
13
+ }
14
+ function buildNotionPageWebUrl(pageId) {
15
+ return `https://www.notion.so/${pageId.replace(/-/g, "")}`;
16
+ }
17
+
18
+ export { buildNotionPageWebUrl, n, newNotionClient, traverseDataSource };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 将本地文件经 Notion File Upload API 上传后,作为「文件」块挂到页面正文中。
3
+ * @param pageId - 页面 ID
4
+ * @param absolutePath - 本地文件路径
5
+ * @param contentType - 可选;默认按扩展名推断,未知则为 application/octet-stream
6
+ */
7
+ export declare function uploadLocalFileToPageBody(pageId: string, absolutePath: string): Promise<void>;
8
+ /**
9
+ * 上传本地图片并在页面正文插入「图片」块(`image`)。
10
+ * @param contentType - 可选;默认按扩展名推断,须为 image/*
11
+ */
12
+ export declare function uploadLocalImageToPageBody(pageId: string, absolutePath: string): Promise<void>;
13
+ /**
14
+ * 上传本地视频并在页面正文插入「视频」块(`video`)。
15
+ * @param contentType - 可选;默认按扩展名推断,须为 video/*
16
+ */
17
+ export declare function uploadLocalVideoToPageBody(pageId: string, absolutePath: string): Promise<void>;
18
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AA+IA;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,iBAuBnF;AAED;;;GAGG;AACH,wBAAsB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,iBAqBpF;AAED;;;GAGG;AACH,wBAAsB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,iBAqBpF"}
package/lib/upload.js ADDED
@@ -0,0 +1,166 @@
1
+ import { basename, extname } from 'node:path';
2
+ import { readFile, access } from 'node:fs/promises';
3
+ import { gzipSync } from 'node:zlib';
4
+ import '@notionhq/client';
5
+ import { newNotionClient } from './client.js';
6
+
7
+ const SINGLE_PART_MAX_BYTES = 20 * 1024 * 1024;
8
+ const MULTIPART_CHUNK_BYTES = 10 * 1024 * 1024;
9
+ const MIME_BY_EXT = {
10
+ ".avif": "image/avif",
11
+ ".bmp": "image/bmp",
12
+ ".gif": "image/gif",
13
+ ".heic": "image/heic",
14
+ ".heif": "image/heif",
15
+ ".ico": "image/x-icon",
16
+ ".jpeg": "image/jpeg",
17
+ ".jpg": "image/jpeg",
18
+ ".png": "image/png",
19
+ ".svg": "image/svg+xml",
20
+ ".webp": "image/webp",
21
+ ".html": "text/html",
22
+ ".htm": "text/html",
23
+ ".mp4": "video/mp4",
24
+ ".webm": "video/webm",
25
+ ".mov": "video/quicktime",
26
+ ".m4v": "video/x-m4v",
27
+ ".mkv": "video/x-matroska",
28
+ ".mpeg": "video/mpeg",
29
+ ".mpg": "video/mpeg",
30
+ ".avi": "video/x-msvideo",
31
+ ".pdf": "application/pdf",
32
+ ".zip": "application/zip",
33
+ ".json": "application/json",
34
+ ".txt": "text/plain"
35
+ };
36
+ function contentTypeFromPath(absolutePath) {
37
+ const ext = extname(absolutePath).toLowerCase();
38
+ return MIME_BY_EXT[ext] ?? "application/octet-stream";
39
+ }
40
+ function prepareBufferForNotionUpload(absolutePath, fileBuffer, displayName, mime) {
41
+ const ext = extname(absolutePath).toLowerCase();
42
+ if (ext !== ".html") {
43
+ return { buffer: fileBuffer, displayName, mime };
44
+ }
45
+ return {
46
+ buffer: gzipSync(fileBuffer),
47
+ displayName: displayName.endsWith(".gz") ? displayName : `${displayName}.gz`,
48
+ mime: "application/gzip"
49
+ };
50
+ }
51
+ async function ensureLocalFileReadable(absolutePath) {
52
+ try {
53
+ await access(absolutePath);
54
+ } catch {
55
+ throw new Error(`\u627E\u4E0D\u5230\u8981\u4E0A\u4F20\u7684\u6587\u4EF6: ${absolutePath}`);
56
+ }
57
+ }
58
+ async function completeFileUpload(displayName, contentType, fileBuffer) {
59
+ const notion = newNotionClient();
60
+ if (fileBuffer.length <= SINGLE_PART_MAX_BYTES) {
61
+ const data = new Blob([fileBuffer], { type: contentType });
62
+ const created2 = await notion.fileUploads.create({
63
+ mode: "single_part",
64
+ filename: displayName,
65
+ content_type: contentType
66
+ });
67
+ const afterSend = await notion.fileUploads.send({
68
+ file_upload_id: created2.id,
69
+ file: { filename: displayName, data }
70
+ });
71
+ if (afterSend.status !== "uploaded") {
72
+ throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u672A\u5C31\u7EEA\uFF0C\u72B6\u6001: ${afterSend.status}`);
73
+ }
74
+ return created2.id;
75
+ }
76
+ const number_of_parts = Math.ceil(fileBuffer.length / MULTIPART_CHUNK_BYTES);
77
+ const created = await notion.fileUploads.create({
78
+ mode: "multi_part",
79
+ filename: displayName,
80
+ content_type: contentType,
81
+ number_of_parts
82
+ });
83
+ for (let part = 1; part <= number_of_parts; part++) {
84
+ const start = (part - 1) * MULTIPART_CHUNK_BYTES;
85
+ const end = Math.min(start + MULTIPART_CHUNK_BYTES, fileBuffer.length);
86
+ const slice = fileBuffer.subarray(start, end);
87
+ const data = new Blob([slice], { type: contentType });
88
+ await notion.fileUploads.send({
89
+ file_upload_id: created.id,
90
+ part_number: String(part),
91
+ file: { filename: displayName, data }
92
+ });
93
+ }
94
+ const afterComplete = await notion.fileUploads.complete({
95
+ file_upload_id: created.id
96
+ });
97
+ if (afterComplete.status !== "uploaded") {
98
+ throw new Error(`\u591A\u6BB5\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF0C\u72B6\u6001: ${afterComplete.status}`);
99
+ }
100
+ return created.id;
101
+ }
102
+ async function appendBlocksToPage(pageId, children) {
103
+ await newNotionClient().blocks.children.append({ block_id: pageId, children });
104
+ }
105
+ async function uploadLocalFileToPageBody(pageId, absolutePath) {
106
+ const displayName = basename(absolutePath);
107
+ await ensureLocalFileReadable(absolutePath);
108
+ const mime = contentTypeFromPath(absolutePath);
109
+ const rawBuffer = await readFile(absolutePath);
110
+ const {
111
+ buffer,
112
+ displayName: uploadName,
113
+ mime: uploadMime
114
+ } = prepareBufferForNotionUpload(absolutePath, rawBuffer, displayName, mime);
115
+ const fileUploadId = await completeFileUpload(uploadName, uploadMime, buffer);
116
+ await appendBlocksToPage(pageId, [
117
+ {
118
+ type: "file",
119
+ file: {
120
+ type: "file_upload",
121
+ file_upload: { id: fileUploadId },
122
+ name: uploadName
123
+ }
124
+ }
125
+ ]);
126
+ }
127
+ async function uploadLocalImageToPageBody(pageId, absolutePath) {
128
+ const displayName = basename(absolutePath);
129
+ await ensureLocalFileReadable(absolutePath);
130
+ const mime = contentTypeFromPath(absolutePath);
131
+ if (!mime.startsWith("image/")) {
132
+ throw new Error(`\u4E0D\u662F\u56FE\u7247 MIME\uFF08${mime}\uFF09\uFF0C\u8BF7\u4F20\u56FE\u7247\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);
133
+ }
134
+ const fileBuffer = await readFile(absolutePath);
135
+ const fileUploadId = await completeFileUpload(displayName, mime, fileBuffer);
136
+ await appendBlocksToPage(pageId, [
137
+ {
138
+ type: "image",
139
+ image: {
140
+ type: "file_upload",
141
+ file_upload: { id: fileUploadId }
142
+ }
143
+ }
144
+ ]);
145
+ }
146
+ async function uploadLocalVideoToPageBody(pageId, absolutePath) {
147
+ const displayName = basename(absolutePath);
148
+ await ensureLocalFileReadable(absolutePath);
149
+ const mime = contentTypeFromPath(absolutePath);
150
+ if (!mime.startsWith("video/")) {
151
+ throw new Error(`\u4E0D\u662F\u89C6\u9891 MIME\uFF08${mime}\uFF09\uFF0C\u8BF7\u4F20\u89C6\u9891\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);
152
+ }
153
+ const fileBuffer = await readFile(absolutePath);
154
+ const fileUploadId = await completeFileUpload(displayName, mime, fileBuffer);
155
+ await appendBlocksToPage(pageId, [
156
+ {
157
+ type: "video",
158
+ video: {
159
+ type: "file_upload",
160
+ file_upload: { id: fileUploadId }
161
+ }
162
+ }
163
+ ]);
164
+ }
165
+
166
+ export { uploadLocalFileToPageBody, uploadLocalImageToPageBody, uploadLocalVideoToPageBody };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@secret-momo/notion",
3
+ "version": "1.0.0",
4
+ "files": [
5
+ "lib"
6
+ ],
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "main": "./lib/index.js",
11
+ "module": "src/index.ts",
12
+ "type": "module",
13
+ "types": "./lib/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./lib/index.d.ts",
17
+ "import": "./lib/index.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "postinstall": "bun outdated",
22
+ "prepublishOnly": "bun run build",
23
+ "build": "rm -rf lib && rollup -c && tsc -p tsconfig.json"
24
+ },
25
+ "dependencies": {
26
+ "@notionhq/client": "5.22.0",
27
+ "@secret-momo/utils": "1.0.2"
28
+ },
29
+ "devDependencies": {
30
+ "@eslint/config-helpers": "0.6.0",
31
+ "@eslint/js": "10.0.1",
32
+ "@types/bun": "1.3.14",
33
+ "eslint": "10.4.1",
34
+ "eslint-plugin-import-x": "4.16.2",
35
+ "eslint-plugin-react": "7.37.5",
36
+ "eslint-plugin-react-hooks": "7.1.1",
37
+ "eslint-plugin-unused-imports": "4.4.1",
38
+ "husky": "9.1.7",
39
+ "jiti": "2.7.0",
40
+ "lint-staged": "17.0.7",
41
+ "prettier": "3.8.3",
42
+ "rollup": "4.61.1",
43
+ "rollup-plugin-esbuild": "6.2.1",
44
+ "typescript": "6.0.3",
45
+ "typescript-eslint": "8.60.1"
46
+ },
47
+ "lint-staged": {
48
+ "*.{ts,tsx,js,jsx}": [
49
+ "bunx eslint --fix",
50
+ "bunx prettier --write"
51
+ ],
52
+ "*.{json,md}": [
53
+ "bunx prettier --write"
54
+ ]
55
+ }
56
+ }