@secret-momo/notion 3.0.0 → 4.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.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -4
  3. package/dist/helpers/append-markdown.d.ts +2 -0
  4. package/dist/helpers/append-markdown.js +95 -0
  5. package/dist/helpers/custom-fetch.d.ts +1 -0
  6. package/dist/helpers/custom-fetch.js +50 -0
  7. package/{lib → dist}/helpers/page.d.ts +0 -1
  8. package/dist/helpers/page.js +22 -0
  9. package/{lib → dist}/helpers/upload/config.d.ts +0 -1
  10. package/dist/helpers/upload/config.js +33 -0
  11. package/{lib → dist}/helpers/upload/helper.d.ts +1 -3
  12. package/dist/helpers/upload/helper.js +72 -0
  13. package/{lib → dist}/helpers/upload/index.d.ts +0 -1
  14. package/dist/helpers/upload/index.js +115 -0
  15. package/dist/index.d.ts +4 -0
  16. package/dist/index.js +3 -0
  17. package/{lib → dist}/notion-client.d.ts +8 -6
  18. package/dist/notion-client.js +181 -0
  19. package/{lib → dist}/utils.d.ts +0 -1
  20. package/dist/utils.js +11 -0
  21. package/package.json +28 -49
  22. package/lib/helpers/custom-fetch.d.ts +0 -2
  23. package/lib/helpers/custom-fetch.d.ts.map +0 -1
  24. package/lib/helpers/custom-fetch.js +0 -1
  25. package/lib/helpers/page.d.ts.map +0 -1
  26. package/lib/helpers/page.js +0 -1
  27. package/lib/helpers/upload/config.d.ts.map +0 -1
  28. package/lib/helpers/upload/config.js +0 -1
  29. package/lib/helpers/upload/helper.d.ts.map +0 -1
  30. package/lib/helpers/upload/helper.js +0 -1
  31. package/lib/helpers/upload/index.d.ts.map +0 -1
  32. package/lib/helpers/upload/index.js +0 -1
  33. package/lib/index.d.ts +0 -6
  34. package/lib/index.d.ts.map +0 -1
  35. package/lib/index.js +0 -1
  36. package/lib/notion-client.d.ts.map +0 -1
  37. package/lib/notion-client.js +0 -1
  38. package/lib/utils.d.ts.map +0 -1
  39. package/lib/utils.js +0 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 secretmomo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,8 +1,68 @@
1
1
  # @secret-momo/notion
2
2
 
3
- 封装 Notion 的一些 API,方便个人使用。
3
+ 封装 Notion 页面创建与更新、数据源分页、Markdown 写入和本地文件上传。工作区版本提供 ESM 入口和 TypeScript 类型声明,运行环境为 Node.js **>=26**。
4
4
 
5
- ## 环境变量
5
+ ## 安装
6
6
 
7
- - `NOTION_AUTH_TOKEN`: Notion 鉴权 token
8
- - `NOTION_DATA_SOURCE_ID`: Notion 数据源 ID
7
+ ```bash
8
+ pnpm add @secret-momo/notion
9
+ ```
10
+
11
+ ## 配置
12
+
13
+ | 环境变量 | 用途 |
14
+ | ----------------------- | ----------------------------------------------------------------------------------- |
15
+ | `NOTION_AUTH_TOKEN` | 构造客户端时使用的 Notion 集成令牌。也可以通过 `new NotionClient(token)` 显式传入。 |
16
+ | `NOTION_DATA_SOURCE_ID` | `traverseDataSource` 默认查询的数据源 ID,可在调用时覆盖。 |
17
+
18
+ 在 Notion 中为集成授权需要读写的页面或数据源。创建数据源页面时,向 `createPageWithTitle` 显式传入 `dataSourceId`。
19
+
20
+ ## 页面与数据源
21
+
22
+ ```ts
23
+ import { getNotionPageInfo, NotionClient } from '@secret-momo/notion';
24
+
25
+ const notion = new NotionClient();
26
+ const page = await notion.createPageWithTitle({
27
+ dataSourceId: '你的数据源 ID',
28
+ title: '项目笔记',
29
+ titlePropertyName: '名称',
30
+ url: 'https://example.com/',
31
+ });
32
+
33
+ await notion.appendMarkdown(page.id, '## 摘要\n\n项目进展。');
34
+
35
+ // 数据源中的 ID 属性须为 Notion 的唯一 ID 类型。
36
+ await notion.traverseDataSource((item) => {
37
+ console.log(getNotionPageInfo(item));
38
+ }, '你的数据源 ID');
39
+ ```
40
+
41
+ - `createPage`、`updatePage` 直接接受 Notion SDK 的请求参数。`createPageWithTitle` 默认使用 `DEFAULT_TITLE_PROPERTY_NAME`(`名称`),并支持为标题附加链接。
42
+ - `traverseDataSource` 按游标查询结果,支持同步或异步回调,并按返回顺序逐项等待。回调报错时遍历停止,错误由调用方处理。
43
+ - `appendMarkdown` 使用页面的原生 Markdown 接口。`appendMarkdownToBlock` 把 Markdown 转为块后按顺序追加,每批最多 100 个直接子块、1,000 个块元素(含嵌套块)和 500 KB 的 UTF-8 JSON。需要拆分时先创建父块,再向它分批追加子块。不可拆分的块超过请求体大小限制时会在发送请求前报错。后续 API 请求失败时,已写入的块仍保留。
44
+ - `appendHeading1Block` 返回新标题块 ID,响应没有块时返回空字符串。`appendDivider` 追加分隔线。
45
+ - `buildNotionPageWebUrl(pageId)` 生成浏览器链接。`getId(page)` 读取 `ID` 属性的 `unique_id.number`,缺少有效值时抛出错误。`getNotionPageInfo(page)` 返回 `{ notionId, notionLink }`,有页面 URL 时优先采用接口返回的地址。`n(value)` 将缺省数值转为 `null`。
46
+ - 包入口同时导出 `CreatePageWithTitleParameters`、`PageObjectResponse`、`NumberPropertyItemObjectResponse` 和 `RichTextItemResponse` 类型。
47
+
48
+ ## 文件上传
49
+
50
+ - `uploadFileToNotion`、`uploadImageToNotion` 和 `uploadVideoToNotion` 接受本地绝对路径,返回可用于 Notion 附件属性的文件上传 ID。上传方法只应接收受信来源的路径,调用方负责按自己的访问策略授权文件。
51
+ - `uploadFileToPageBody`、`uploadImageToPageBody` 和 `uploadVideoToPageBody` 接受页面 ID 与本地绝对路径,在页面正文中插入对应类型的块。
52
+ - 上传按扩展名判断 MIME 类型。`uploadFileToNotion` 将 `.html` 和 `.htm` 文件压缩为 gzip 后上传,在原文件名后追加 `.gz`,并清理临时文件。实际上传大小不超过 20 MiB 时走单段流程,更大的文件按 18 MiB 分段,最多同时发送三段。
53
+
54
+ ```ts
55
+ await notion.uploadImageToPageBody(page.id, '/absolute/path/cover.png');
56
+
57
+ const fileUploadId = await notion.uploadFileToNotion('/absolute/path/report.pdf');
58
+ await notion.updatePage({
59
+ page_id: page.id,
60
+ properties: {
61
+ 附件: { files: [{ name: 'report.pdf', type: 'file_upload', file_upload: { id: fileUploadId } }] },
62
+ },
63
+ });
64
+ ```
65
+
66
+ ## 开发与测试
67
+
68
+ 在仓库根目录运行 `pnpm --filter @secret-momo/notion test`。测试使用模拟 HTTP 请求和本地临时文件,语句、分支、函数和行覆盖率分别要求至少 90%。HTML 覆盖率报告生成在包目录的 `coverage/index.html`。运行 `pnpm --filter @secret-momo/notion... build` 会按依赖顺序构建 Notion 和 utils。
@@ -0,0 +1,2 @@
1
+ import type { Client } from '@notionhq/client';
2
+ export declare function appendMarkdownBlocks(client: Client, blockId: string, markdown: string): Promise<void>;
@@ -0,0 +1,95 @@
1
+ import { markdownToBlocks } from '@tryfabric/martian';
2
+ // https://developers.notion.com/reference/request-limits
3
+ // https://developers.notion.com/reference/patch-block-children
4
+ const MAX_CHILDREN = 100;
5
+ const MAX_BLOCK_ELEMENTS = 1000;
6
+ const MAX_REQUEST_BYTES = 500_000;
7
+ const MAX_NESTING_DEPTH = 2;
8
+ const EMPTY_REQUEST_BYTES = Buffer.byteLength(JSON.stringify({ children: [] }));
9
+ function getBlockContent(block) {
10
+ return block.type ? block[block.type] : undefined;
11
+ }
12
+ function countBlockElements(block, depth = 0) {
13
+ const children = getBlockContent(block)?.children ?? [];
14
+ if (children.length > MAX_CHILDREN || (children.length > 0 && depth === MAX_NESTING_DEPTH)) {
15
+ return Infinity;
16
+ }
17
+ return children.reduce((count, child) => count + countBlockElements(child, depth + 1), 1);
18
+ }
19
+ function splitBlock(block) {
20
+ const type = block.type;
21
+ const content = getBlockContent(block);
22
+ const children = content?.children ?? [];
23
+ const tooLarge = () => new Error(`Markdown 的 ${type ?? '未知类型'} 块超过 Notion 单次追加限制,无法拆分`);
24
+ if (!type || children.length === 0)
25
+ throw tooLarge();
26
+ // Notion 要求创建表格时至少包含一行,保留原首行以维持表头语义。
27
+ const firstRows = type === 'table' ? children.slice(0, 1) : [];
28
+ const parent = {
29
+ ...block,
30
+ [type]: { ...content, children: firstRows.length ? firstRows : undefined },
31
+ };
32
+ if (Buffer.byteLength(JSON.stringify({ children: [parent] })) > MAX_REQUEST_BYTES) {
33
+ throw tooLarge();
34
+ }
35
+ return {
36
+ blocks: [parent],
37
+ deferredChildren: planBatches(children.slice(firstRows.length)),
38
+ };
39
+ }
40
+ function planBatches(blocks) {
41
+ const batches = [];
42
+ let pending = [];
43
+ let elements = 0;
44
+ let bytes = EMPTY_REQUEST_BYTES;
45
+ function flush() {
46
+ if (pending.length === 0)
47
+ return;
48
+ batches.push({ blocks: pending });
49
+ pending = [];
50
+ elements = 0;
51
+ bytes = EMPTY_REQUEST_BYTES;
52
+ }
53
+ for (const block of blocks) {
54
+ const blockElements = countBlockElements(block);
55
+ const blockBytes = Buffer.byteLength(JSON.stringify(block));
56
+ if (blockElements > MAX_BLOCK_ELEMENTS ||
57
+ EMPTY_REQUEST_BYTES + blockBytes > MAX_REQUEST_BYTES) {
58
+ flush();
59
+ batches.push(splitBlock(block));
60
+ continue;
61
+ }
62
+ if (pending.length === MAX_CHILDREN ||
63
+ elements + blockElements > MAX_BLOCK_ELEMENTS ||
64
+ bytes + blockBytes + (pending.length ? 1 : 0) > MAX_REQUEST_BYTES) {
65
+ flush();
66
+ }
67
+ // SDK 只将 children 写入 JSON 请求体。非首个块前有一个逗号。
68
+ bytes += blockBytes + (pending.length ? 1 : 0);
69
+ elements += blockElements;
70
+ pending.push(block);
71
+ }
72
+ flush();
73
+ return batches;
74
+ }
75
+ async function appendBatches(client, blockId, batches) {
76
+ for (const { blocks, deferredChildren } of batches) {
77
+ const { results } = await client.blocks.children.append({
78
+ block_id: blockId,
79
+ children: blocks,
80
+ });
81
+ if (deferredChildren) {
82
+ const parentId = results?.[0]?.id;
83
+ if (!parentId)
84
+ throw new Error('Notion 未返回新建父块的 ID,无法追加剩余子块');
85
+ await appendBatches(client, parentId, deferredChildren);
86
+ }
87
+ }
88
+ }
89
+ export async function appendMarkdownBlocks(client, blockId, markdown) {
90
+ const blocks = markdownToBlocks(markdown, {
91
+ notionLimits: { truncate: false },
92
+ });
93
+ const batches = planBatches(blocks);
94
+ await appendBatches(client, blockId, batches);
95
+ }
@@ -0,0 +1 @@
1
+ export declare function customFetch(input: string | URL, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,50 @@
1
+ import { logger, sleep } from '@secret-momo/utils';
2
+ const NOTION_TLS_MAX_RETRIES = 5;
3
+ const TLS_CODE_PREFIX = /^(?:ERR_(?:TLS|SSL)_|CERT_|CRL_|ERROR_IN_(?:CERT|CRL)_)/;
4
+ const TLS_CERTIFICATE_CODES = new Set([
5
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
6
+ 'HOSTNAME_MISMATCH',
7
+ 'INVALID_CA',
8
+ 'SELF_SIGNED_CERT_IN_CHAIN',
9
+ 'UNABLE_TO_GET_CRL',
10
+ 'UNABLE_TO_GET_ISSUER_CERT',
11
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
12
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
13
+ ]);
14
+ const TLS_ERROR_MESSAGE = /certificate|unknown cert|\b(?:ssl|tls)\s+(?:alert|error|handshake|protocol)\b/i;
15
+ function errorCode(error) {
16
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string') {
17
+ return error.code;
18
+ }
19
+ return undefined;
20
+ }
21
+ export async function customFetch(input, init) {
22
+ const headers = new Headers(init?.headers);
23
+ headers.set('Connection', 'close');
24
+ const requestInit = { ...init, headers };
25
+ const signal = init?.signal ?? undefined;
26
+ for (let attempt = 0;; attempt++) {
27
+ try {
28
+ return await fetch(input, requestInit);
29
+ }
30
+ catch (error) {
31
+ if (attempt >= NOTION_TLS_MAX_RETRIES || signal?.aborted)
32
+ throw error;
33
+ // Node fetch 的 TLS 错误通常在 cause 中。错误码优先于错误文案。
34
+ const cause = error instanceof Error ? error.cause : undefined;
35
+ const code = errorCode(cause) ?? errorCode(error);
36
+ const detail = cause instanceof Error ? cause : error;
37
+ const message = detail instanceof Error ? detail.message : String(detail);
38
+ const isTlsError = code
39
+ ? TLS_CODE_PREFIX.test(code) || TLS_CERTIFICATE_CODES.has(code)
40
+ : TLS_ERROR_MESSAGE.test(message);
41
+ if (!isTlsError) {
42
+ throw error;
43
+ }
44
+ logger
45
+ .child({ name: 'notion' })
46
+ .warn(`Notion TLS 重试第 ${attempt + 1} 次,错误信息:${message}`);
47
+ await sleep(1000 * (attempt + 1), signal);
48
+ }
49
+ }
50
+ }
@@ -9,4 +9,3 @@ export declare function buildNotionPageWebUrl(pageId: string): string;
9
9
  * 获取数据库页面的 ID
10
10
  */
11
11
  export declare function getId(page: PageObjectResponse): number;
12
- //# sourceMappingURL=page.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 从 API 返回的 page(或任意带 `id` 的对象)拼出可在浏览器打开的 Notion 页面地址
3
+ * @param pageId - 页面 ID
4
+ * @returns 可在浏览器打开的 Notion 页面地址
5
+ */
6
+ export function buildNotionPageWebUrl(pageId) {
7
+ return `https://www.notion.so/${pageId.replace(/-/g, '')}`;
8
+ }
9
+ /**
10
+ * 获取数据库页面的 ID
11
+ */
12
+ export function getId(page) {
13
+ const idProperty = page.properties['ID'];
14
+ if (idProperty?.type !== 'unique_id') {
15
+ throw new Error('ID 属性不是 unique_id 类型');
16
+ }
17
+ const id = idProperty.unique_id.number;
18
+ if (id === null) {
19
+ throw new Error('ID 属性为空');
20
+ }
21
+ return id;
22
+ }
@@ -5,4 +5,3 @@ export declare const MULTIPART_CHUNK_BYTES: number;
5
5
  /** Notion multipart part 可并行发送;保守控制并发,避免触发 API rate limit */
6
6
  export declare const MULTIPART_UPLOAD_CONCURRENCY = 3;
7
7
  export declare const MIME_BY_EXT: Record<string, string>;
8
- //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,33 @@
1
+ /** Notion 单段上传上限(二进制 MiB,与官方文档一致) */
2
+ export const SINGLE_PART_MAX_BYTES = 20 * 1024 * 1024;
3
+ /** 多段上传每段建议 18 MiB;非末段须在 5-20 MiB 之间 */
4
+ export const MULTIPART_CHUNK_BYTES = 18 * 1024 * 1024;
5
+ /** Notion multipart part 可并行发送;保守控制并发,避免触发 API rate limit */
6
+ export const MULTIPART_UPLOAD_CONCURRENCY = 3;
7
+ export const MIME_BY_EXT = {
8
+ '.avif': 'image/avif',
9
+ '.bmp': 'image/bmp',
10
+ '.gif': 'image/gif',
11
+ '.heic': 'image/heic',
12
+ '.heif': 'image/heif',
13
+ '.ico': 'image/x-icon',
14
+ '.jpeg': 'image/jpeg',
15
+ '.jpg': 'image/jpeg',
16
+ '.png': 'image/png',
17
+ '.svg': 'image/svg+xml',
18
+ '.webp': 'image/webp',
19
+ '.html': 'text/html',
20
+ '.htm': 'text/html',
21
+ '.mp4': 'video/mp4',
22
+ '.webm': 'video/webm',
23
+ '.mov': 'video/quicktime',
24
+ '.m4v': 'video/x-m4v',
25
+ '.mkv': 'video/x-matroska',
26
+ '.mpeg': 'video/mpeg',
27
+ '.mpg': 'video/mpeg',
28
+ '.avi': 'video/x-msvideo',
29
+ '.pdf': 'application/pdf',
30
+ '.zip': 'application/zip',
31
+ '.json': 'application/json',
32
+ '.txt': 'text/plain',
33
+ };
@@ -5,9 +5,7 @@ export interface TemporaryGzipFile {
5
5
  cleanup: () => Promise<void>;
6
6
  }
7
7
  /**
8
- * Notion 的 send 接口经 Cloudflare;原始 HTML(尤其公众号全文)易触发 WAF 403。
9
- * 流式压缩到临时文件,避免同时在内存中保留原文件和完整 gzip 结果。
8
+ * 将 HTML 流式压缩到临时文件,避免同时在内存中保留原文件和完整 gzip 结果。
10
9
  */
11
10
  export declare function createTemporaryGzipFile(absolutePath: string): Promise<TemporaryGzipFile>;
12
11
  export declare function runWithConcurrency<T>(items: T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void>;
13
- //# sourceMappingURL=helper.d.ts.map
@@ -0,0 +1,72 @@
1
+ import { constants, createReadStream, createWriteStream } from 'node:fs';
2
+ import { access, mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { extname, isAbsolute, join } from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { createGzip } from 'node:zlib';
7
+ import { MIME_BY_EXT } from './config.js';
8
+ export function contentTypeFromPath(absolutePath) {
9
+ const ext = extname(absolutePath).toLowerCase();
10
+ return MIME_BY_EXT[ext] ?? 'application/octet-stream';
11
+ }
12
+ export async function ensureLocalFileReadable(absolutePath) {
13
+ if (!isAbsolute(absolutePath)) {
14
+ throw new Error('请传入本地文件的绝对路径');
15
+ }
16
+ try {
17
+ await access(absolutePath, constants.R_OK);
18
+ }
19
+ catch {
20
+ throw new Error(`找不到要上传的文件: ${absolutePath}`);
21
+ }
22
+ }
23
+ /**
24
+ * 将 HTML 流式压缩到临时文件,避免同时在内存中保留原文件和完整 gzip 结果。
25
+ */
26
+ export async function createTemporaryGzipFile(absolutePath) {
27
+ const directory = await mkdtemp(join(tmpdir(), 'secret-momo-notion-upload-'));
28
+ const filePath = join(directory, 'payload.gz');
29
+ try {
30
+ await pipeline(createReadStream(absolutePath), createGzip(), createWriteStream(filePath));
31
+ }
32
+ catch (error) {
33
+ await rm(directory, { recursive: true, force: true });
34
+ throw error;
35
+ }
36
+ return {
37
+ filePath,
38
+ cleanup: () => rm(directory, { recursive: true, force: true }),
39
+ };
40
+ }
41
+ export async function runWithConcurrency(items, concurrency, worker) {
42
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
43
+ throw new RangeError('concurrency 必须是大于 0 的整数');
44
+ }
45
+ let nextIndex = 0;
46
+ let stopped = false;
47
+ let hasError = false;
48
+ let firstError;
49
+ const workerCount = Math.min(concurrency, items.length);
50
+ await Promise.all(Array.from({ length: workerCount }, async () => {
51
+ while (!stopped && nextIndex < items.length) {
52
+ const currentIndex = nextIndex++;
53
+ const item = items[currentIndex];
54
+ if (item === undefined) {
55
+ return;
56
+ }
57
+ try {
58
+ await worker(item);
59
+ }
60
+ catch (error) {
61
+ if (!hasError) {
62
+ hasError = true;
63
+ firstError = error;
64
+ }
65
+ stopped = true;
66
+ }
67
+ }
68
+ }));
69
+ if (hasError) {
70
+ throw firstError;
71
+ }
72
+ }
@@ -2,4 +2,3 @@ import type { Client } from '@notionhq/client';
2
2
  export declare function uploadFileToNotion(client: Client, absolutePath: string): Promise<string>;
3
3
  export declare function uploadImageToNotion(client: Client, absolutePath: string): Promise<string>;
4
4
  export declare function uploadVideoToNotion(client: Client, absolutePath: string): Promise<string>;
5
- //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,115 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
3
+ import { SINGLE_PART_MAX_BYTES, MULTIPART_CHUNK_BYTES, MULTIPART_UPLOAD_CONCURRENCY, } from './config.js';
4
+ import { contentTypeFromPath, createTemporaryGzipFile, ensureLocalFileReadable, runWithConcurrency, } from './helper.js';
5
+ async function readFilePart(fileHandle, position, length) {
6
+ const buffer = Buffer.allocUnsafe(length);
7
+ let bytesRead = 0;
8
+ while (bytesRead < length) {
9
+ const result = await fileHandle.read(buffer, bytesRead, length - bytesRead, position + bytesRead);
10
+ if (result.bytesRead === 0) {
11
+ throw new Error('读取上传文件时提前到达文件末尾,文件可能已被修改');
12
+ }
13
+ bytesRead += result.bytesRead;
14
+ }
15
+ return buffer;
16
+ }
17
+ /**
18
+ * 创建并完成 Notion File Upload,返回 `file_upload_id`。
19
+ * ≤20 MiB 用单段;更大文件用官方多段流程(每段 18 MiB,最后一段可更小)。
20
+ * Blob 的 MIME 须与 create 时一致。
21
+ */
22
+ async function completeFileUpload({ client, displayName, contentType, filePath, }) {
23
+ const fileHandle = await open(filePath, 'r');
24
+ try {
25
+ const fileStat = await fileHandle.stat();
26
+ if (!fileStat.isFile()) {
27
+ throw new Error(`要上传的路径不是文件: ${filePath}`);
28
+ }
29
+ if (fileStat.size <= SINGLE_PART_MAX_BYTES) {
30
+ const data = new Blob([await readFilePart(fileHandle, 0, fileStat.size)], {
31
+ type: contentType,
32
+ });
33
+ const created = await client.fileUploads.create({
34
+ mode: 'single_part',
35
+ filename: displayName,
36
+ content_type: contentType,
37
+ });
38
+ const afterSend = await client.fileUploads.send({
39
+ file_upload_id: created.id,
40
+ file: { filename: displayName, data },
41
+ });
42
+ if (afterSend.status !== 'uploaded') {
43
+ throw new Error(`文件上传未就绪,状态: ${afterSend.status}`);
44
+ }
45
+ return created.id;
46
+ }
47
+ const number_of_parts = Math.ceil(fileStat.size / MULTIPART_CHUNK_BYTES);
48
+ const created = await client.fileUploads.create({
49
+ mode: 'multi_part',
50
+ filename: displayName,
51
+ content_type: contentType,
52
+ number_of_parts,
53
+ });
54
+ await runWithConcurrency(Array.from({ length: number_of_parts }, (_, index) => index + 1), MULTIPART_UPLOAD_CONCURRENCY, async (part) => {
55
+ const start = (part - 1) * MULTIPART_CHUNK_BYTES;
56
+ const length = Math.min(MULTIPART_CHUNK_BYTES, fileStat.size - start);
57
+ const data = new Blob([await readFilePart(fileHandle, start, length)], {
58
+ type: contentType,
59
+ });
60
+ await client.fileUploads.send({
61
+ file_upload_id: created.id,
62
+ part_number: String(part),
63
+ file: { filename: displayName, data },
64
+ });
65
+ });
66
+ const afterComplete = await client.fileUploads.complete({
67
+ file_upload_id: created.id,
68
+ });
69
+ if (afterComplete.status !== 'uploaded') {
70
+ throw new Error(`多段文件上传未完成,状态: ${afterComplete.status}`);
71
+ }
72
+ return created.id;
73
+ }
74
+ finally {
75
+ await fileHandle.close();
76
+ }
77
+ }
78
+ export async function uploadFileToNotion(client, absolutePath) {
79
+ const displayName = basename(absolutePath);
80
+ await ensureLocalFileReadable(absolutePath);
81
+ const mime = contentTypeFromPath(absolutePath);
82
+ if (mime !== 'text/html') {
83
+ return completeFileUpload({ client, displayName, contentType: mime, filePath: absolutePath });
84
+ }
85
+ const temporaryFile = await createTemporaryGzipFile(absolutePath);
86
+ try {
87
+ return await completeFileUpload({
88
+ client,
89
+ displayName: `${displayName}.gz`,
90
+ contentType: 'application/gzip',
91
+ filePath: temporaryFile.filePath,
92
+ });
93
+ }
94
+ finally {
95
+ await temporaryFile.cleanup();
96
+ }
97
+ }
98
+ export async function uploadImageToNotion(client, absolutePath) {
99
+ await ensureLocalFileReadable(absolutePath);
100
+ const displayName = basename(absolutePath);
101
+ const contentType = contentTypeFromPath(absolutePath);
102
+ if (!contentType.startsWith('image/')) {
103
+ throw new Error(`不是图片 MIME(${contentType}),请传入受支持的图片扩展名`);
104
+ }
105
+ return completeFileUpload({ client, displayName, contentType, filePath: absolutePath });
106
+ }
107
+ export async function uploadVideoToNotion(client, absolutePath) {
108
+ const displayName = basename(absolutePath);
109
+ await ensureLocalFileReadable(absolutePath);
110
+ const contentType = contentTypeFromPath(absolutePath);
111
+ if (!contentType.startsWith('video/')) {
112
+ throw new Error(`不是视频 MIME(${contentType}),请传入受支持的视频扩展名`);
113
+ }
114
+ return completeFileUpload({ client, displayName, contentType, filePath: absolutePath });
115
+ }
@@ -0,0 +1,4 @@
1
+ export type { NumberPropertyItemObjectResponse, PageObjectResponse, RichTextItemResponse, } from '@notionhq/client';
2
+ export { n, DEFAULT_TITLE_PROPERTY_NAME, getNotionPageInfo } from './utils.js';
3
+ export { buildNotionPageWebUrl, getId } from './helpers/page.js';
4
+ export { NotionClient, type CreatePageWithTitleParameters } from './notion-client.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { n, DEFAULT_TITLE_PROPERTY_NAME, getNotionPageInfo } from './utils.js';
2
+ export { buildNotionPageWebUrl, getId } from './helpers/page.js';
3
+ export { NotionClient } from './notion-client.js';
@@ -17,43 +17,45 @@ export declare class NotionClient {
17
17
  createPage(args: CreatePageParameters): Promise<import("@notionhq/client").CreatePageResponse>;
18
18
  createPageWithTitle(params: CreatePageWithTitleParameters): Promise<import("@notionhq/client").CreatePageResponse>;
19
19
  updatePage(args: UpdatePageParameters): Promise<import("@notionhq/client").UpdatePageResponse>;
20
- traverseDataSource(cb: (item: PageObjectResponse) => void, dataSourceId?: string): Promise<void>;
20
+ /** 按返回顺序等待每次回调。回调抛错或拒绝时停止遍历并向调用方传递错误。 */
21
+ traverseDataSource(cb: (item: PageObjectResponse) => unknown, dataSourceId?: string): Promise<void>;
21
22
  appendHeading1Block(params: AppendHeadingParameters): Promise<string>;
22
23
  appendMarkdownToBlock(blockId: string, markdown: string): Promise<void>;
23
24
  appendDivider(blockId: string): Promise<void>;
24
25
  appendMarkdown(pageId: string, markdown: string): Promise<void>;
25
26
  /**
26
27
  * 上传本地文件到 Notion(数据库中附件属性中需要使用到这个函数)
27
- * @param absolutePath - 本地文件路径
28
+ * @param absolutePath - 来自受信来源的本地绝对路径
28
29
  * @returns - 文件上传 ID
29
30
  */
30
31
  uploadFileToNotion(absolutePath: string): Promise<string>;
31
32
  /**
32
33
  * 将本地文件经 Notion File Upload API 上传后,作为「文件」块挂到页面正文中。
33
34
  * @param pageId - 页面 ID
34
- * @param absolutePath - 本地文件路径
35
+ * @param absolutePath - 来自受信来源的本地绝对路径
35
36
  */
36
37
  uploadFileToPageBody(pageId: string, absolutePath: string): Promise<void>;
37
38
  /**
38
39
  * 上传本地图片到 Notion(数据库中附件属性中需要使用到这个函数)
39
- * @param absolutePath - 本地图片路径
40
+ * @param absolutePath - 来自受信来源的本地图片绝对路径
40
41
  * @returns - 文件上传 ID
41
42
  */
42
43
  uploadImageToNotion(absolutePath: string): Promise<string>;
43
44
  /**
44
45
  * 上传本地图片并在页面正文插入「图片」块(`image`)。
46
+ * @param absolutePath - 来自受信来源的本地图片绝对路径
45
47
  */
46
48
  uploadImageToPageBody(pageId: string, absolutePath: string): Promise<void>;
47
49
  /**
48
50
  * 上传本地视频到 Notion(数据库中附件属性中需要使用到这个函数)
49
- * @param absolutePath - 本地视频路径
51
+ * @param absolutePath - 来自受信来源的本地视频绝对路径
50
52
  * @returns - 文件上传 ID
51
53
  */
52
54
  uploadVideoToNotion(absolutePath: string): Promise<string>;
53
55
  /**
54
56
  * 上传本地视频并在页面正文插入「视频」块(`video`)。
57
+ * @param absolutePath - 来自受信来源的本地视频绝对路径
55
58
  */
56
59
  uploadVideoToPageBody(pageId: string, absolutePath: string): Promise<void>;
57
60
  }
58
61
  export {};
59
- //# sourceMappingURL=notion-client.d.ts.map
@@ -0,0 +1,181 @@
1
+ import { Client, } from '@notionhq/client';
2
+ import { appendMarkdownBlocks } from './helpers/append-markdown.js';
3
+ import { customFetch } from './helpers/custom-fetch.js';
4
+ import { uploadFileToNotion, uploadImageToNotion, uploadVideoToNotion, } from './helpers/upload/index.js';
5
+ import { DEFAULT_TITLE_PROPERTY_NAME } from './utils.js';
6
+ export class NotionClient {
7
+ client;
8
+ constructor(authToken) {
9
+ const auth = (authToken ?? process.env.NOTION_AUTH_TOKEN)?.trim();
10
+ if (!auth) {
11
+ throw new Error('缺少 Notion 集成令牌,请显式传入 authToken 或设置 NOTION_AUTH_TOKEN');
12
+ }
13
+ this.client = new Client({
14
+ auth,
15
+ fetch: customFetch,
16
+ timeoutMs: 1000 * 60 * 10, // 10 分钟超时的时间
17
+ });
18
+ }
19
+ async createPage(args) {
20
+ return this.client.pages.create(args);
21
+ }
22
+ async createPageWithTitle(params) {
23
+ const { dataSourceId, titlePropertyName = DEFAULT_TITLE_PROPERTY_NAME, title, url } = params;
24
+ return this.createPage({
25
+ parent: { data_source_id: dataSourceId },
26
+ properties: {
27
+ [titlePropertyName]: {
28
+ title: [
29
+ {
30
+ type: 'text',
31
+ text: {
32
+ content: title,
33
+ ...(url === undefined ? {} : { link: { url } }),
34
+ },
35
+ },
36
+ ],
37
+ },
38
+ },
39
+ });
40
+ }
41
+ async updatePage(args) {
42
+ return this.client.pages.update(args);
43
+ }
44
+ /** 按返回顺序等待每次回调。回调抛错或拒绝时停止遍历并向调用方传递错误。 */
45
+ async traverseDataSource(cb, dataSourceId) {
46
+ const data_source_id = (dataSourceId ?? process.env.NOTION_DATA_SOURCE_ID)?.trim();
47
+ if (!data_source_id) {
48
+ throw new Error('缺少 Notion 数据源 ID,请传入 dataSourceId 或设置 NOTION_DATA_SOURCE_ID');
49
+ }
50
+ let cursor = null;
51
+ const seenCursors = new Set();
52
+ while (true) {
53
+ const { results, has_more, next_cursor } = await this.client.dataSources.query({
54
+ data_source_id,
55
+ start_cursor: cursor ?? undefined,
56
+ });
57
+ if (has_more) {
58
+ if (!next_cursor)
59
+ throw new Error('Notion 数据源仍有下一页,但响应缺少分页游标');
60
+ if (seenCursors.has(next_cursor))
61
+ throw new Error('Notion 数据源返回了重复的分页游标');
62
+ seenCursors.add(next_cursor);
63
+ }
64
+ for (const item of results) {
65
+ await cb(item);
66
+ }
67
+ if (!has_more)
68
+ return;
69
+ cursor = next_cursor;
70
+ }
71
+ }
72
+ async appendHeading1Block(params) {
73
+ const { blockId, content, color, isToggleable } = params;
74
+ const { results } = await this.client.blocks.children.append({
75
+ block_id: blockId,
76
+ children: [
77
+ {
78
+ type: 'heading_1',
79
+ heading_1: {
80
+ rich_text: [{ type: 'text', text: { content } }],
81
+ color,
82
+ is_toggleable: isToggleable,
83
+ },
84
+ },
85
+ ],
86
+ });
87
+ return results[0]?.id ?? '';
88
+ }
89
+ async appendMarkdownToBlock(blockId, markdown) {
90
+ await appendMarkdownBlocks(this.client, blockId, markdown);
91
+ }
92
+ async appendDivider(blockId) {
93
+ await this.client.blocks.children.append({
94
+ block_id: blockId,
95
+ children: [{ type: 'divider', divider: {} }],
96
+ });
97
+ }
98
+ async appendMarkdown(pageId, markdown) {
99
+ await this.client.pages.updateMarkdown({
100
+ page_id: pageId,
101
+ type: 'insert_content',
102
+ insert_content: { content: markdown },
103
+ });
104
+ }
105
+ /**
106
+ * 上传本地文件到 Notion(数据库中附件属性中需要使用到这个函数)
107
+ * @param absolutePath - 来自受信来源的本地绝对路径
108
+ * @returns - 文件上传 ID
109
+ */
110
+ async uploadFileToNotion(absolutePath) {
111
+ return uploadFileToNotion(this.client, absolutePath);
112
+ }
113
+ /**
114
+ * 将本地文件经 Notion File Upload API 上传后,作为「文件」块挂到页面正文中。
115
+ * @param pageId - 页面 ID
116
+ * @param absolutePath - 来自受信来源的本地绝对路径
117
+ */
118
+ async uploadFileToPageBody(pageId, absolutePath) {
119
+ const fileUploadId = await this.uploadFileToNotion(absolutePath);
120
+ await this.client.blocks.children.append({
121
+ block_id: pageId,
122
+ children: [
123
+ {
124
+ type: 'file',
125
+ file: {
126
+ type: 'file_upload',
127
+ file_upload: { id: fileUploadId },
128
+ },
129
+ },
130
+ ],
131
+ });
132
+ }
133
+ /**
134
+ * 上传本地图片到 Notion(数据库中附件属性中需要使用到这个函数)
135
+ * @param absolutePath - 来自受信来源的本地图片绝对路径
136
+ * @returns - 文件上传 ID
137
+ */
138
+ async uploadImageToNotion(absolutePath) {
139
+ return uploadImageToNotion(this.client, absolutePath);
140
+ }
141
+ /**
142
+ * 上传本地图片并在页面正文插入「图片」块(`image`)。
143
+ * @param absolutePath - 来自受信来源的本地图片绝对路径
144
+ */
145
+ async uploadImageToPageBody(pageId, absolutePath) {
146
+ const fileUploadId = await this.uploadImageToNotion(absolutePath);
147
+ await this.client.blocks.children.append({
148
+ block_id: pageId,
149
+ children: [
150
+ {
151
+ type: 'image',
152
+ image: {
153
+ type: 'file_upload',
154
+ file_upload: { id: fileUploadId },
155
+ },
156
+ },
157
+ ],
158
+ });
159
+ }
160
+ /**
161
+ * 上传本地视频到 Notion(数据库中附件属性中需要使用到这个函数)
162
+ * @param absolutePath - 来自受信来源的本地视频绝对路径
163
+ * @returns - 文件上传 ID
164
+ */
165
+ async uploadVideoToNotion(absolutePath) {
166
+ return uploadVideoToNotion(this.client, absolutePath);
167
+ }
168
+ /**
169
+ * 上传本地视频并在页面正文插入「视频」块(`video`)。
170
+ * @param absolutePath - 来自受信来源的本地视频绝对路径
171
+ */
172
+ async uploadVideoToPageBody(pageId, absolutePath) {
173
+ const fileUploadId = await this.uploadVideoToNotion(absolutePath);
174
+ await this.client.blocks.children.append({
175
+ block_id: pageId,
176
+ children: [
177
+ { type: 'video', video: { type: 'file_upload', file_upload: { id: fileUploadId } } },
178
+ ],
179
+ });
180
+ }
181
+ }
@@ -5,4 +5,3 @@ export declare function getNotionPageInfo(page: PageObjectResponse): {
5
5
  notionId: number;
6
6
  notionLink: string;
7
7
  };
8
- //# sourceMappingURL=utils.d.ts.map
package/dist/utils.js ADDED
@@ -0,0 +1,11 @@
1
+ import { buildNotionPageWebUrl, getId } from './helpers/page.js';
2
+ export const DEFAULT_TITLE_PROPERTY_NAME = '名称';
3
+ export function n(num) {
4
+ return num ?? null;
5
+ }
6
+ export function getNotionPageInfo(page) {
7
+ return {
8
+ notionId: getId(page),
9
+ notionLink: page.url || buildNotionPageWebUrl(page.id),
10
+ };
11
+ }
package/package.json CHANGED
@@ -1,61 +1,40 @@
1
1
  {
2
2
  "name": "@secret-momo/notion",
3
- "version": "3.0.0",
4
- "engines": {
5
- "node": "24.19.0"
6
- },
7
- "files": [
8
- "lib"
9
- ],
10
- "publishConfig": {
11
- "access": "public"
12
- },
13
- "main": "./lib/index.js",
14
- "module": "src/index.ts",
3
+ "version": "4.0.0",
4
+ "description": "Notion 页面、数据源和文件上传工具。",
15
5
  "type": "module",
16
- "types": "./lib/index.d.ts",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/secretmomo/npm-packages.git",
10
+ "directory": "packages/notion"
11
+ },
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
17
14
  "exports": {
18
15
  ".": {
19
- "types": "./lib/index.d.ts",
20
- "import": "./lib/index.js"
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
21
18
  }
22
19
  },
23
- "scripts": {
24
- "postinstall": "bun outdated",
25
- "prepublishOnly": "bun run typecheck && bun run build",
26
- "typecheck": "tsc --noEmit",
27
- "build": "rm -rf lib && rollup -c && tsc -p tsconfig.json"
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "engines": {
24
+ "node": ">=26"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org/"
28
29
  },
29
30
  "dependencies": {
30
- "@notionhq/client": "5.26.0",
31
- "@secret-momo/utils": "1.5.0",
31
+ "@notionhq/client": "5.27.0",
32
+ "@secret-momo/utils": "^2.0.0",
32
33
  "@tryfabric/martian": "1.2.4"
33
34
  },
34
- "devDependencies": {
35
- "@eslint/config-helpers": "0.7.0",
36
- "@eslint/js": "10.0.1",
37
- "@types/bun": "1.4.0",
38
- "eslint": "10.9.1",
39
- "eslint-plugin-import-x": "4.17.1",
40
- "eslint-plugin-react": "7.37.5",
41
- "eslint-plugin-react-hooks": "7.1.1",
42
- "eslint-plugin-unused-imports": "4.4.1",
43
- "husky": "9.1.7",
44
- "jiti": "2.7.0",
45
- "lint-staged": "17.4.1",
46
- "prettier": "3.9.6",
47
- "rollup": "4.63.1",
48
- "rollup-plugin-esbuild": "6.2.1",
49
- "typescript": "6.0.3",
50
- "typescript-eslint": "8.69.0"
51
- },
52
- "lint-staged": {
53
- "*.{ts,tsx,js,jsx}": [
54
- "bunx eslint --fix",
55
- "bunx prettier --write"
56
- ],
57
- "*.{json,md}": [
58
- "bunx prettier --write"
59
- ]
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.build.json",
37
+ "typecheck": "tsc -p tsconfig.json",
38
+ "test": "vitest run --config ../../vitest.config.mts --root ."
60
39
  }
61
- }
40
+ }
@@ -1,2 +0,0 @@
1
- export declare function customFetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
2
- //# sourceMappingURL=custom-fetch.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"custom-fetch.d.ts","sourceRoot":"","sources":["../../src/helpers/custom-fetch.ts"],"names":[],"mappings":"AAiBA,wBAAsB,WAAW,CAC/B,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAC7B,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC,QAAQ,CAAC,CAgCnB"}
@@ -1 +0,0 @@
1
- import{logger as s,sleep as u}from"@secret-momo/utils";const c=5;function a(o){return["certificate","unknown cert","ssl","tls"].some(t=>o.includes(t))}async function f(o,t){const i={...t,timeout:!1,headers:{...t?.headers,Connection:"close"}};for(let e=0;e<=c;e++)try{return await fetch(o,i)}catch(n){const r=(n?.message??String(n)).toLowerCase();if(e>=c||!a(r))throw n;s.child({name:"notion"}).warn(`Notion TLS \u91CD\u8BD5\u7B2C ${e+1} \u6B21, \u9519\u8BEF\u4FE1\u606F\uFF1A${r}`),await u(1e3*e)}throw new Error("Unexpected notion fetch retry failure")}export{f as customFetch};
@@ -1 +0,0 @@
1
- {"version":3,"file":"page.d.ts","sourceRoot":"","sources":["../../src/helpers/page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED;;GAEG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,CActD"}
@@ -1 +0,0 @@
1
- function e(u){return`https://www.notion.so/${u.replace(/-/g,"")}`}function t(u){const n=u.properties.ID;if(n?.type!=="unique_id")throw new Error("ID \u5C5E\u6027\u4E0D\u662F unique_id \u7C7B\u578B");const r=n.unique_id.number;if(r===null)throw new Error("ID \u5C5E\u6027\u4E3A\u7A7A");return r}export{e as buildNotionPageWebUrl,t as getId};
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/helpers/upload/config.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,eAAO,MAAM,qBAAqB,QAAmB,CAAC;AACtD,wCAAwC;AACxC,eAAO,MAAM,qBAAqB,QAAmB,CAAC;AACtD,6DAA6D;AAC7D,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA0B9C,CAAC"}
@@ -1 +0,0 @@
1
- const i=20971520,e=18874368,m=3,p={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".html":"text/html",".htm":"text/html",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".m4v":"video/x-m4v",".mkv":"video/x-matroska",".mpeg":"video/mpeg",".mpg":"video/mpeg",".avi":"video/x-msvideo",".pdf":"application/pdf",".zip":"application/zip",".json":"application/json",".txt":"text/plain"};export{p as MIME_BY_EXT,e as MULTIPART_CHUNK_BYTES,m as MULTIPART_UPLOAD_CONCURRENCY,i as SINGLE_PART_MAX_BYTES};
@@ -1 +0,0 @@
1
- {"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../../../src/helpers/upload/helper.ts"],"names":[],"mappings":"AASA,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAGhE;AAED,wBAAsB,uBAAuB,CAAC,YAAY,EAAE,MAAM,iBAMjE;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAe9F;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EACxC,KAAK,EAAE,CAAC,EAAE,EACV,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,iBAqCnC"}
@@ -1 +0,0 @@
1
- import{constants as l,createReadStream as h,createWriteStream as w}from"node:fs";import{access as y,mkdtemp as E,rm as u}from"node:fs/promises";import{tmpdir as d}from"node:os";import{extname as F,join as m}from"node:path";import{pipeline as g}from"node:stream/promises";import{createGzip as R}from"node:zlib";import{MIME_BY_EXT as v}from"./config.js";function z(t){const r=F(t).toLowerCase();return v[r]??"application/octet-stream"}async function C(t){try{await y(t,l.R_OK)}catch{throw new Error(`\u627E\u4E0D\u5230\u8981\u4E0A\u4F20\u7684\u6587\u4EF6: ${t}`)}}async function M(t){const r=await E(m(d(),"secret-momo-notion-upload-")),e=m(r,"payload.gz");try{await g(h(t),R(),w(e))}catch(o){throw await u(r,{recursive:!0,force:!0}),o}return{filePath:e,cleanup:()=>u(r,{recursive:!0,force:!0})}}async function P(t,r,e){if(!Number.isInteger(r)||r<1)throw new RangeError("concurrency \u5FC5\u987B\u662F\u5927\u4E8E 0 \u7684\u6574\u6570");let o=0,n=!1,a=!1,c;const s=Math.min(r,t.length);if(await Promise.all(Array.from({length:s},async()=>{for(;!n&&o<t.length;){const f=o++,i=t[f];if(i===void 0)return;try{await e(i)}catch(p){a||(a=!0,c=p),n=!0}}})),a)throw c}export{z as contentTypeFromPath,M as createTemporaryGzipFile,C as ensureLocalFileReadable,P as runWithConcurrency};
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/helpers/upload/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AA8H/C,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,mBAoB5E;AAED,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAW/F;AAED,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,mBAU7E"}
@@ -1 +0,0 @@
1
- import{open as h}from"node:fs/promises";import{basename as c,extname as _}from"node:path";import{SINGLE_PART_MAX_BYTES as T,MULTIPART_CHUNK_BYTES as p,MULTIPART_UPLOAD_CONCURRENCY as B}from"./config.js";import{ensureLocalFileReadable as f,contentTypeFromPath as d,createTemporaryGzipFile as A,runWithConcurrency as C}from"./helper.js";async function y(e,t,u){const a=Buffer.allocUnsafe(u);let i=0;for(;i<u;){const o=await e.read(a,i,u-i,t+i);if(o.bytesRead===0)throw new Error("\u8BFB\u53D6\u4E0A\u4F20\u6587\u4EF6\u65F6\u63D0\u524D\u5230\u8FBE\u6587\u4EF6\u672B\u5C3E\uFF0C\u6587\u4EF6\u53EF\u80FD\u5DF2\u88AB\u4FEE\u6539");i+=o.bytesRead}return a}async function s({client:e,displayName:t,contentType:u,filePath:a}){const i=await h(a,"r");try{const o=await i.stat();if(!o.isFile())throw new Error(`\u8981\u4E0A\u4F20\u7684\u8DEF\u5F84\u4E0D\u662F\u6587\u4EF6: ${a}`);if(o.size<=T){const r=new Blob([await y(i,0,o.size)],{type:u}),n=await e.fileUploads.create({mode:"single_part",filename:t,content_type:u}),l=await e.fileUploads.send({file_upload_id:n.id,file:{filename:t,data:r}});if(l.status!=="uploaded")throw new Error(`\u6587\u4EF6\u4E0A\u4F20\u672A\u5C31\u7EEA\uFF0C\u72B6\u6001: ${l.status}`);return n.id}const E=Math.ceil(o.size/p),F=await e.fileUploads.create({mode:"multi_part",filename:t,content_type:u,number_of_parts:E});await C(Array.from({length:E},(r,n)=>n+1),B,async r=>{const n=(r-1)*p,l=Math.min(p,o.size-n),m=new Blob([await y(i,n,l)],{type:u});await e.fileUploads.send({file_upload_id:F.id,part_number:String(r),file:{filename:t,data:m}})});const w=await e.fileUploads.complete({file_upload_id:F.id});if(w.status!=="uploaded")throw new Error(`\u591A\u6BB5\u6587\u4EF6\u4E0A\u4F20\u672A\u5B8C\u6210\uFF0C\u72B6\u6001: ${w.status}`);return F.id}finally{await i.close()}}async function D(e,t){const u=c(t);await f(t);const a=d(t);if(_(t).toLowerCase()!==".html")return s({client:e,displayName:u,contentType:a,filePath:t});const i=await A(t);try{return await s({client:e,displayName:u.endsWith(".gz")?u:`${u}.gz`,contentType:"application/gzip",filePath:i.filePath})}finally{await i.cleanup()}}async function N(e,t){await f(t);const u=c(t),a=d(t);if(!a.startsWith("image/"))throw new Error(`\u4E0D\u662F\u56FE\u7247 MIME\uFF08${a}\uFF09\uFF0C\u8BF7\u4F20\u56FE\u7247\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);return s({client:e,displayName:u,contentType:a,filePath:t})}async function P(e,t){const u=c(t);await f(t);const a=d(t);if(!a.startsWith("video/"))throw new Error(`\u4E0D\u662F\u89C6\u9891 MIME\uFF08${a}\uFF09\uFF0C\u8BF7\u4F20\u89C6\u9891\u8DEF\u5F84\u6216\u663E\u5F0F\u6307\u5B9A contentType`);return s({client:e,displayName:u,contentType:a,filePath:t})}export{D as uploadFileToNotion,N as uploadImageToNotion,P as uploadVideoToNotion};
package/lib/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import { type NumberPropertyItemObjectResponse, type PageObjectResponse, type RichTextItemResponse } from '@notionhq/client';
2
- export type { NumberPropertyItemObjectResponse, PageObjectResponse, RichTextItemResponse };
3
- export { n, DEFAULT_TITLE_PROPERTY_NAME, getNotionPageInfo } from './utils';
4
- export { buildNotionPageWebUrl, getId } from './helpers/page';
5
- export { NotionClient, type CreatePageWithTitleParameters } from './notion-client';
6
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
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,YAAY,EAAE,gCAAgC,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,CAAC;AAE3F,OAAO,EAAE,CAAC,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,KAAK,6BAA6B,EAAE,MAAM,iBAAiB,CAAC"}
package/lib/index.js DELETED
@@ -1 +0,0 @@
1
- import"@notionhq/client";import{DEFAULT_TITLE_PROPERTY_NAME as r,getNotionPageInfo as i,n}from"./utils.js";import{buildNotionPageWebUrl as g,getId as m}from"./helpers/page.js";import{NotionClient as E}from"./notion-client.js";export{r as DEFAULT_TITLE_PROPERTY_NAME,E as NotionClient,g as buildNotionPageWebUrl,m as getId,i as getNotionPageInfo,n};
@@ -1 +0,0 @@
1
- {"version":3,"file":"notion-client.d.ts","sourceRoot":"","sources":["../src/notion-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACxB,MAAM,kBAAkB,CAAC;AAO1B,MAAM,WAAW,6BAA6B;IAC5C,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,UAAU,uBAAuB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAED,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,SAAS,CAAC,EAAE,MAAM;IAQxB,UAAU,CAAC,IAAI,EAAE,oBAAoB;IAIrC,mBAAmB,CAAC,MAAM,EAAE,6BAA6B;IAqBzD,UAAU,CAAC,IAAI,EAAE,oBAAoB;IAIrC,kBAAkB,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,kBAAkB,KAAK,IAAI,EAAE,YAAY,CAAC,EAAE,MAAM;IAehF,mBAAmB,CAAC,MAAM,EAAE,uBAAuB;IAmBnD,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAOvD,aAAa,CAAC,OAAO,EAAE,MAAM;IAO7B,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;IAQrD;;;;OAIG;IACG,kBAAkB,CAAC,YAAY,EAAE,MAAM;IAI7C;;;;OAIG;IACG,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiB/D;;;;OAIG;IACG,mBAAmB,CAAC,YAAY,EAAE,MAAM;IAI9C;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;IAiBhE;;;;OAIG;IACG,mBAAmB,CAAC,YAAY,EAAE,MAAM;IAI9C;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;CAUjE"}
@@ -1 +0,0 @@
1
- import{Client as c}from"@notionhq/client";import{markdownToBlocks as l}from"@tryfabric/martian";import{customFetch as d}from"./helpers/custom-fetch.js";import{uploadFileToNotion as r,uploadImageToNotion as s,uploadVideoToNotion as p}from"./helpers/upload/index.js";import{DEFAULT_TITLE_PROPERTY_NAME as u}from"./utils.js";class h{client;constructor(e){this.client=new c({auth:e??process.env.NOTION_AUTH_TOKEN,fetch:d,timeoutMs:1e3*60*10})}async createPage(e){return this.client.pages.create(e)}async createPageWithTitle(e){const{dataSourceId:t,titlePropertyName:i=u,title:o,url:a}=e;return this.createPage({parent:{data_source_id:t},properties:{[i]:{title:[{type:"text",text:{content:o,...a===void 0?{}:{link:{url:a}}}}]}}})}async updatePage(e){return this.client.pages.update(e)}async traverseDataSource(e,t){const i=t??process.env.NOTION_DATA_SOURCE_ID??"";let o;do{const a=await this.client.dataSources.query({data_source_id:i,start_cursor:o});a.results.forEach(n=>e(n)),o=a.next_cursor??void 0}while(o)}async appendHeading1Block(e){const{blockId:t,content:i,color:o,isToggleable:a}=e,{results:n}=await this.client.blocks.children.append({block_id:t,children:[{type:"heading_1",heading_1:{rich_text:[{type:"text",text:{content:i}}],color:o,is_toggleable:a}}]});return n[0]?.id??""}async appendMarkdownToBlock(e,t){await this.client.blocks.children.append({block_id:e,children:l(t)})}async appendDivider(e){await this.client.blocks.children.append({block_id:e,children:[{type:"divider",divider:{}}]})}async appendMarkdown(e,t){await this.client.pages.updateMarkdown({page_id:e,type:"insert_content",insert_content:{content:t}})}async uploadFileToNotion(e){return r(this.client,e)}async uploadFileToPageBody(e,t){const i=await this.uploadFileToNotion(t);await this.client.blocks.children.append({block_id:e,children:[{type:"file",file:{type:"file_upload",file_upload:{id:i}}}]})}async uploadImageToNotion(e){return s(this.client,e)}async uploadImageToPageBody(e,t){const i=await this.uploadImageToNotion(t);await this.client.blocks.children.append({block_id:e,children:[{type:"image",image:{type:"file_upload",file_upload:{id:i}}}]})}async uploadVideoToNotion(e){return p(this.client,e)}async uploadVideoToPageBody(e,t){const i=await this.uploadVideoToNotion(t);await this.client.blocks.children.append({block_id:e,children:[{type:"video",video:{type:"file_upload",file_upload:{id:i}}}]})}}export{h as NotionClient};
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAI3D,eAAO,MAAM,2BAA2B,iBAAO,CAAC;AAEhD,wBAAgB,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,iBAE7B;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB;;;EAKzD"}
package/lib/utils.js DELETED
@@ -1 +0,0 @@
1
- import{buildNotionPageWebUrl as o,getId as t}from"./helpers/page.js";const i="\u540D\u79F0";function e(n){return n??null}function r(n){return{notionId:t(n),notionLink:o(n.id)}}export{i as DEFAULT_TITLE_PROPERTY_NAME,r as getNotionPageInfo,e as n};