notion-to-md 1.0.8 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,10 +20,11 @@ Convert notion pages, block and list of blocks to markdown (supports nesting) us
20
20
  - [x] nested blocks
21
21
  - [ ] pages inside pages/child page
22
22
  - [x] embeds, bookmarks, videos, files (converted to links)
23
- - [ ] tables
23
+ - [x] Simple tables
24
24
  - [x] divider
25
25
  - [x] equation block (converted to code blocks)
26
26
  - [x] convert returned markdown object to string (`toMarkdownString()`)
27
+ - [x] typescript support
27
28
  - [ ] add tests
28
29
 
29
30
  ## Install
@@ -34,6 +35,8 @@ $ npm install notion-to-md
34
35
 
35
36
  ## Usage
36
37
 
38
+ > **Note:** Details on methods can be found in [API section](https://github.com/souvikinator/notion-to-md#api)
39
+
37
40
  ### converting markdown objects to markdown string
38
41
 
39
42
  This is how the notion page looks for this example:
@@ -42,14 +45,16 @@ This is how the notion page looks for this example:
42
45
 
43
46
  ```js
44
47
  const { Client } = require("@notionhq/client");
45
- const notion2md = require("notion-to-md");
48
+ const { NotionToMarkdown } = require("notion-to-md");
49
+ // or
50
+ // import {NotionToMarkdown} from "notion-to-md";
46
51
 
47
52
  const notion = new Client({
48
53
  auth: "your integration token",
49
54
  });
50
55
 
51
56
  // passing notion client to the option
52
- const n2m = new notion2md({ notionClient: notion });
57
+ const n2m = new NotionToMarkdown({ notionClient: notion });
53
58
 
54
59
  (async () => {
55
60
  const mdblocks = await n2m.pageToMarkdown("target_page_id");
@@ -66,24 +71,22 @@ const n2m = new notion2md({ notionClient: notion });
66
71
 
67
72
  ![output](https://imgur.com/XrUYrZ0.png)
68
73
 
69
- > **Note:** Details on provided methods can be found in [API section](https://github.com/souvikinator/notion-to-md#api)
70
-
71
74
  ### converting page to markdown object
72
75
 
73
- This is how the notion page looks for this example:
76
+ Example notion page:
74
77
 
75
78
  ![Imgur](https://imgur.com/9iqRpBl.png)
76
79
 
77
80
  ```js
78
81
  const { Client } = require("@notionhq/client");
79
- const notion2md = require("notion-to-md");
82
+ const { NotionToMarkdown } = require("notion-to-md");
80
83
 
81
84
  const notion = new Client({
82
85
  auth: "your integration token",
83
86
  });
84
87
 
85
88
  // passing notion client to the option
86
- const n2m = new notion2md({ notionClient: notion });
89
+ const n2m = new NotionToMarkdown({ notionClient: notion });
87
90
 
88
91
  (async () => {
89
92
  // notice second argument, totalPage.
@@ -92,11 +95,6 @@ const n2m = new notion2md({ notionClient: notion });
92
95
  })();
93
96
  ```
94
97
 
95
- > `totalPage`: Default value is `1` which means only `100` blocks will be converted to markdown and rest will be ignored (due to notion api limitations, ref: [#9](https://github.com/souvikinator/notion-to-md/pull/9)).
96
- >
97
- > - if the notion page contains less than or equal `100` blocks then `totalPage` arg is not required.
98
- > - if the notion page contains `150` blocks then `totalPage` argument should be greater than or equal to `2` leading to `pageSize = 2 * 100` and rendering all `150` blocks.
99
-
100
98
  **Output:**
101
99
 
102
100
  ```json
@@ -144,20 +142,18 @@ const n2m = new notion2md({ notionClient: notion });
144
142
 
145
143
  ### converting list of blocks to markdown object
146
144
 
147
- > This example blocks from a single page is used. One construct array of blocks from different notion pages and pass in to the `blocksToMarkdown()`
148
-
149
145
  same notion page as before
150
146
 
151
147
  ```js
152
148
  const { Client } = require("@notionhq/client");
153
- const notion2md = require("notion-to-md");
149
+ const { NotionToMarkdown } = require("notion-to-md");
154
150
 
155
151
  const notion = new Client({
156
152
  auth: "your integration token",
157
153
  });
158
154
 
159
155
  // passing notion client to the option
160
- const n2m = new notion2md({ notionClient: notion });
156
+ const n2m = new NotionToMarkdown({ notionClient: notion });
161
157
 
162
158
  (async () => {
163
159
  // get all blocks in the page
@@ -177,13 +173,13 @@ const n2m = new notion2md({ notionClient: notion });
177
173
 
178
174
  - only takes a single notion block and returns corresponding markdown string
179
175
  - nesting is ignored
180
- - not dependent on @notionhq/client
176
+ - depends on @notionhq/client
181
177
 
182
178
  ```js
183
- const notion2md = require("notion-to-md");
179
+ const { NotionToMarkdown } = require("notion-to-md");
184
180
 
185
- // notion client not required
186
- const n2m = new notion2md();
181
+ // passing notion client to the option
182
+ const n2m = new NotionToMarkdown({ notionClient: notion });
187
183
 
188
184
  const result = n2m.blockToMarkdown(block);
189
185
  console.log(result);
@@ -197,37 +193,41 @@ console.log(result);
197
193
 
198
194
  ## API
199
195
 
200
- ### `toMarkdownString(markdownObjects)`
201
-
202
- - takes output of `pageToMarkdown` or `blocksToMarkdown` as argument
203
- - convert to markdown string.
204
-
205
- ### `pageToMarkdown(page_id,totalPage)`
196
+ > ### `toMarkdownString(mdBlock[])`
197
+ >
198
+ > - takes output of `pageToMarkdown` or `blocksToMarkdown` as argument
199
+ > - converts to markdown string.
206
200
 
207
- - Uses `blocksToMarkdown` internally.
208
- - Takes `page_id` as input and converts all the blocks in the page to corresponding markdown object
209
- - `totalPage` is the retrieve block children request number i.e `page_size Maximum = totalPage * 100`.
201
+ > ### `pageToMarkdown(id,totalPage)`
202
+ >
203
+ > - Uses `blocksToMarkdown` internally.
204
+ > - `id`(pageid) as input and converts all the blocks in the page to corresponding markdown object
205
+ > - `totalPage` is the retrieve block children request number i.e `page_size Maximum = totalPage * 100`.
210
206
 
211
- > `totalPage`: Default value is `1` which means only `100` blocks will be converted to markdown and rest will be ignored (due to notion api limitations, ref: [#9](https://github.com/souvikinator/notion-to-md/pull/9)).
207
+ > ### totalPage
208
+ >
209
+ > Default value is `1` which means only `100` blocks will be converted to markdown and rest will be ignored (due to notion api limitations, ref: [#9](https://github.com/souvikinator/notion-to-md/pull/9)).
210
+ >
211
+ > ### How to use `totalPage` arg ?
212
212
  >
213
213
  > - if the notion page contains less than or equal `100` blocks then `totalPage` arg is not required.
214
- > - if the notion page contains `150` blocks then `totalPage` argument should be greater than or equal to `2` leading to `pageSize = 2 * 100` and rendering all blocks withing limit `200`.
215
-
216
- ### `blocksToMarkdown(blocks,totalPage)`
217
-
218
- > **Note**: requires <u>**notion-sdk-js**</u> unlike `blockToMarkdown`
219
-
220
- - `blocks`: array of notion blocks
221
- - `totalPage`: the retrieve block children request number i.e `page_size Maximum = totalPage * 100`.
222
- - deals with <u>**nested blocks**</u>
223
- - uses `blockToMarkdown` internally.
214
+ > - if the notion page contains `150` blocks then `totalPage` argument should be greater than or equal to `2` leading to `pageSize = 2 * 100` and rendering all `150` blocks.
224
215
 
225
- ### `blockToMarkdown(block)`
216
+ > ### `blocksToMarkdown(blocks,totalPage)`
217
+ >
218
+ > **Note**: requires <u>**notion-sdk-js**</u>
219
+ >
220
+ > - `blocks`: array of notion blocks
221
+ > - `totalPage`: the retrieve block children request number i.e `page_size Maximum = totalPage * 100`.
222
+ > - deals with <u>**nested blocks**</u>
223
+ > - uses `blockToMarkdown` internally.
226
224
 
227
- - Takes single notion block and converts to markdown string
228
- - does not deal with nested notion blocks
229
- - This method doesn't require the `notion-sdk-js`.
230
- - Refer docs to know more about [notion blocks](https://developers.notion.com/reference/block)
225
+ > ### `blockToMarkdown(block)`
226
+ >
227
+ > - Takes single notion block and converts to markdown string
228
+ > - does not deal with nested notion blocks
229
+ > - depends on `notion-sdk-js`.
230
+ > - Refer docs to know more about [notion blocks](https://developers.notion.com/reference/block)
231
231
 
232
232
  ## Contribution
233
233
 
@@ -0,0 +1,2 @@
1
+ export * from "./notion-to-md";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC"}
package/build/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./notion-to-md"), exports);
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iDAA+B","sourcesContent":["export * from \"./notion-to-md\";\n"]}
@@ -0,0 +1,44 @@
1
+ import { Annotations, ListBlockChildrenResponseResult, ListBlockChildrenResponseResults, MdBlock, NotionToMarkdownOptions } from "./types";
2
+ /**
3
+ * Converts a Notion page to Markdown.
4
+ */
5
+ export declare class NotionToMarkdown {
6
+ private notionClient;
7
+ constructor(options: NotionToMarkdownOptions);
8
+ /**
9
+ * Converts Markdown Blocks to string
10
+ * @param {MdBlock[]} mdBlocks - Array of markdown blocks
11
+ * @param {number} nestingLevel - Defines max depth of nesting
12
+ * @returns {string} - Returns markdown string
13
+ */
14
+ toMarkdownString(mdBlocks?: MdBlock[], nestingLevel?: number): string;
15
+ /**
16
+ * Retrieves Notion Blocks based on ID and converts them to Markdown Blocks
17
+ * @param {string} id - notion page id (not database id)
18
+ * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100 (Default=1)
19
+ * @returns {Promise<MdBlock[]>} - List of markdown blocks
20
+ */
21
+ pageToMarkdown(id: string, totalPage?: number): Promise<MdBlock[]>;
22
+ /**
23
+ * Converts list of Notion Blocks to Markdown Blocks
24
+ * @param {ListBlockChildrenResponseResults | undefined} blocks - List of notion blocks
25
+ * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100
26
+ * @param {MdBlock[]} mdBlocks - Defines max depth of nesting
27
+ * @returns {Promise<MdBlock[]>} - Array of markdown blocks with their children
28
+ */
29
+ blocksToMarkdown(blocks?: ListBlockChildrenResponseResults, totalPage?: number, mdBlocks?: MdBlock[]): Promise<MdBlock[]>;
30
+ /**
31
+ * Converts a Notion Block to a Markdown Block
32
+ * @param {ListBlockChildrenResponseResult} block - single notion block
33
+ * @returns {string} corresponding markdown string of the passed block
34
+ */
35
+ blockToMarkdown(block: ListBlockChildrenResponseResult): Promise<string>;
36
+ /**
37
+ * Annoate text using provided annotations
38
+ * @param {string} text - String to be annotated
39
+ * @param {Annotations} annotations - Annotation object of a notion block
40
+ * @returns {string} - Annotated text
41
+ */
42
+ annotatePlainText(text: string, annotations: Annotations): string;
43
+ }
44
+ //# sourceMappingURL=notion-to-md.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notion-to-md.d.ts","sourceRoot":"","sources":["../src/notion-to-md.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EACX,+BAA+B,EAC/B,gCAAgC,EAChC,OAAO,EAEP,uBAAuB,EACxB,MAAM,SAAS,CAAC;AAIjB;;GAEG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,EAAE,uBAAuB;IAI5C;;;;;OAKG;IACH,gBAAgB,CAAC,QAAQ,GAAE,OAAO,EAAO,EAAE,YAAY,GAAE,MAAU,GAAG,MAAM;IAe5E;;;;;OAKG;IACG,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,GAAE,MAAU,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAa3E;;;;;;OAMG;IACG,gBAAgB,CACpB,MAAM,CAAC,EAAE,gCAAgC,EACzC,SAAS,GAAE,MAAU,EACrB,QAAQ,GAAE,OAAO,EAAO,GACvB,OAAO,CAAC,OAAO,EAAE,CAAC;IAsDrB;;;;OAIG;IACG,eAAe,CAAC,KAAK,EAAE,+BAA+B;IAyL5D;;;;;OAKG;IACH,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,GAAG,MAAM;CAsBlE"}
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.NotionToMarkdown = void 0;
23
+ const md = __importStar(require("./utils/md"));
24
+ const notion_1 = require("./utils/notion");
25
+ /**
26
+ * Converts a Notion page to Markdown.
27
+ */
28
+ class NotionToMarkdown {
29
+ constructor(options) {
30
+ this.notionClient = options.notionClient;
31
+ }
32
+ /**
33
+ * Converts Markdown Blocks to string
34
+ * @param {MdBlock[]} mdBlocks - Array of markdown blocks
35
+ * @param {number} nestingLevel - Defines max depth of nesting
36
+ * @returns {string} - Returns markdown string
37
+ */
38
+ toMarkdownString(mdBlocks = [], nestingLevel = 0) {
39
+ let mdString = "";
40
+ mdBlocks.forEach((mdBlocks) => {
41
+ if (mdBlocks.parent) {
42
+ mdString += `
43
+ ${md.addTabSpace(mdBlocks.parent, nestingLevel)}
44
+ `;
45
+ }
46
+ if (mdBlocks.children && mdBlocks.children.length > 0) {
47
+ mdString += this.toMarkdownString(mdBlocks.children, nestingLevel + 1);
48
+ }
49
+ });
50
+ return mdString;
51
+ }
52
+ /**
53
+ * Retrieves Notion Blocks based on ID and converts them to Markdown Blocks
54
+ * @param {string} id - notion page id (not database id)
55
+ * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100 (Default=1)
56
+ * @returns {Promise<MdBlock[]>} - List of markdown blocks
57
+ */
58
+ async pageToMarkdown(id, totalPage = 1) {
59
+ if (!this.notionClient) {
60
+ throw new Error("notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md");
61
+ }
62
+ if (!id)
63
+ throw new Error("pageToMarkdown takes page_id as argument");
64
+ const blocks = await (0, notion_1.getBlockChildren)(this.notionClient, id, totalPage);
65
+ const parsedData = await this.blocksToMarkdown(blocks);
66
+ return parsedData;
67
+ }
68
+ /**
69
+ * Converts list of Notion Blocks to Markdown Blocks
70
+ * @param {ListBlockChildrenResponseResults | undefined} blocks - List of notion blocks
71
+ * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100
72
+ * @param {MdBlock[]} mdBlocks - Defines max depth of nesting
73
+ * @returns {Promise<MdBlock[]>} - Array of markdown blocks with their children
74
+ */
75
+ async blocksToMarkdown(blocks, totalPage = 1, mdBlocks = []) {
76
+ if (!this.notionClient) {
77
+ throw new Error("notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md");
78
+ }
79
+ if (!blocks)
80
+ return mdBlocks;
81
+ /**
82
+ * notion's table response is weird. It two objects for same table
83
+ * first object with table width -> 2
84
+ * second object with the actual table width
85
+ * to keep track of table blocks and ignore the first one,
86
+ * tableBlockCount is used.
87
+ */
88
+ let tableBlockCount = 0;
89
+ for (let i = 0; i < blocks.length; i++) {
90
+ let block = blocks[i];
91
+ if (block.type === "table" && tableBlockCount <= 0) {
92
+ tableBlockCount++;
93
+ continue;
94
+ }
95
+ tableBlockCount++;
96
+ if ("has_children" in block && block.has_children) {
97
+ let child_blocks = await (0, notion_1.getBlockChildren)(this.notionClient, block.id, totalPage);
98
+ mdBlocks.push({
99
+ parent: await this.blockToMarkdown(block),
100
+ children: [],
101
+ });
102
+ let l = mdBlocks.length;
103
+ await this.blocksToMarkdown(child_blocks, totalPage, mdBlocks[l - 1].children);
104
+ continue;
105
+ }
106
+ let tmp = await this.blockToMarkdown(block);
107
+ mdBlocks.push({ parent: tmp, children: [] });
108
+ }
109
+ return mdBlocks;
110
+ }
111
+ /**
112
+ * Converts a Notion Block to a Markdown Block
113
+ * @param {ListBlockChildrenResponseResult} block - single notion block
114
+ * @returns {string} corresponding markdown string of the passed block
115
+ */
116
+ async blockToMarkdown(block) {
117
+ if (!("type" in block))
118
+ return "";
119
+ let parsedData = "";
120
+ const { type } = block;
121
+ // console.log({ block });
122
+ switch (type) {
123
+ case "image":
124
+ {
125
+ let blockContent = block.image;
126
+ const image_caption_plain = blockContent.caption
127
+ .map((item) => item.plain_text)
128
+ .join("");
129
+ const image_type = blockContent.type;
130
+ if (image_type === "external")
131
+ return md.image(image_caption_plain, blockContent.external.url);
132
+ if (image_type === "file")
133
+ return md.image(image_caption_plain, blockContent.file.url);
134
+ }
135
+ break;
136
+ case "divider": {
137
+ return md.divider();
138
+ }
139
+ case "equation": {
140
+ return md.codeBlock(block.equation.expression);
141
+ }
142
+ case "video":
143
+ case "file":
144
+ case "pdf":
145
+ {
146
+ let blockContent;
147
+ if (type === "video")
148
+ blockContent = block.video;
149
+ if (type === "file")
150
+ blockContent = block.file;
151
+ if (type === "pdf")
152
+ blockContent = block.pdf;
153
+ if (blockContent) {
154
+ const file_type = blockContent.type;
155
+ if (file_type === "external")
156
+ return md.link("image", blockContent.external.url);
157
+ if (file_type === "file")
158
+ return md.link("image", blockContent.file.url);
159
+ }
160
+ }
161
+ break;
162
+ case "bookmark":
163
+ case "embed":
164
+ case "link_preview":
165
+ {
166
+ let blockContent;
167
+ if (type === "bookmark")
168
+ blockContent = block.bookmark;
169
+ if (type === "embed")
170
+ blockContent = block.embed;
171
+ if (type === "link_preview")
172
+ blockContent = block.link_preview;
173
+ if (blockContent)
174
+ return md.link(type, blockContent.url);
175
+ }
176
+ break;
177
+ case "table": {
178
+ const { id, has_children } = block;
179
+ let tableArr = [];
180
+ if (has_children) {
181
+ const tableRows = await (0, notion_1.getBlockChildren)(this.notionClient, id, 100);
182
+ // console.log(">>", tableRows);
183
+ let rowsPromise = tableRows === null || tableRows === void 0 ? void 0 : tableRows.map(async (row) => {
184
+ const { type } = row;
185
+ const cells = row[type]["cells"];
186
+ /**
187
+ * this is more like a hack since matching the type text was
188
+ * difficult. So converting each cell to paragraph type to
189
+ * reuse the blockToMarkdown function
190
+ */
191
+ let cellStringPromise = cells.map(async (cell) => await this.blockToMarkdown({
192
+ type: "paragraph",
193
+ paragraph: { text: cell },
194
+ }));
195
+ const cellStringArr = await Promise.all(cellStringPromise);
196
+ // console.log("~~", cellStringArr);
197
+ tableArr.push(cellStringArr);
198
+ // console.log(tableArr);
199
+ });
200
+ await Promise.all(rowsPromise || []);
201
+ }
202
+ parsedData = md.table(tableArr);
203
+ return parsedData;
204
+ }
205
+ // Rest of the types
206
+ // "paragraph"
207
+ // "heading_1"
208
+ // "heading_2"
209
+ // "heading_3"
210
+ // "bulleted_list_item"
211
+ // "numbered_list_item"
212
+ // "quote"
213
+ // "to_do"
214
+ // "toggle"
215
+ // "template"
216
+ // "synced_block"
217
+ // "child_page"
218
+ // "child_database"
219
+ // "code"
220
+ // "callout"
221
+ // "breadcrumb"
222
+ // "table_of_contents"
223
+ // "column_list"
224
+ // "column"
225
+ // "link_to_page"
226
+ // "audio"
227
+ // "unsupported"
228
+ default: {
229
+ // In this case typescript is not able to index the types properly, hence ignoring the error
230
+ // @ts-ignore
231
+ let blockContent = block[type].text || [];
232
+ blockContent.map((content) => {
233
+ const annotations = content.annotations;
234
+ let plain_text = content.plain_text;
235
+ plain_text = this.annotatePlainText(plain_text, annotations);
236
+ if (content["href"])
237
+ plain_text = md.link(plain_text, content["href"]);
238
+ parsedData += plain_text;
239
+ });
240
+ }
241
+ }
242
+ switch (type) {
243
+ case "code":
244
+ {
245
+ parsedData = md.codeBlock(parsedData, block[type].language);
246
+ }
247
+ break;
248
+ case "heading_1":
249
+ {
250
+ parsedData = md.heading1(parsedData);
251
+ }
252
+ break;
253
+ case "heading_2":
254
+ {
255
+ parsedData = md.heading2(parsedData);
256
+ }
257
+ break;
258
+ case "heading_3":
259
+ {
260
+ parsedData = md.heading3(parsedData);
261
+ }
262
+ break;
263
+ case "quote":
264
+ {
265
+ parsedData = md.quote(parsedData);
266
+ }
267
+ break;
268
+ case "bulleted_list_item":
269
+ case "numbered_list_item":
270
+ {
271
+ parsedData = md.bullet(parsedData);
272
+ }
273
+ break;
274
+ case "to_do":
275
+ {
276
+ parsedData = md.todo(parsedData, block.to_do.checked);
277
+ }
278
+ break;
279
+ }
280
+ return parsedData;
281
+ }
282
+ /**
283
+ * Annoate text using provided annotations
284
+ * @param {string} text - String to be annotated
285
+ * @param {Annotations} annotations - Annotation object of a notion block
286
+ * @returns {string} - Annotated text
287
+ */
288
+ annotatePlainText(text, annotations) {
289
+ // if text is all spaces, don't annotate
290
+ if (text.match(/^\s*$/))
291
+ return text;
292
+ const leadingSpaceMatch = text.match(/^(\s*)/);
293
+ const trailingSpaceMatch = text.match(/(\s*)$/);
294
+ const leading_space = leadingSpaceMatch ? leadingSpaceMatch[0] : "";
295
+ const trailing_space = trailingSpaceMatch ? trailingSpaceMatch[0] : "";
296
+ text = text.trim();
297
+ if (text !== "") {
298
+ if (annotations.code)
299
+ text = md.inlineCode(text);
300
+ if (annotations.bold)
301
+ text = md.bold(text);
302
+ if (annotations.italic)
303
+ text = md.italic(text);
304
+ if (annotations.strikethrough)
305
+ text = md.strikethrough(text);
306
+ if (annotations.underline)
307
+ text = md.underline(text);
308
+ }
309
+ return leading_space + text + trailing_space;
310
+ }
311
+ }
312
+ exports.NotionToMarkdown = NotionToMarkdown;
313
+ //# sourceMappingURL=notion-to-md.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notion-to-md.js","sourceRoot":"","sources":["../src/notion-to-md.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AASA,+CAAiC;AACjC,2CAAkD;AAElD;;GAEG;AACH,MAAa,gBAAgB;IAG3B,Y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B;QACtD,wCAAwC;QACxC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,OAAO,IAAI,CAAC;QAErC,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC/C,MAAM,kBAAkB,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEhD,MAAM,aAAa,GAAG,iBAAiB,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACpE,MAAM,cAAc,GAAG,kBAAkB,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAEvE,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAEnB,IAAI,IAAI,KAAK,EAAE,EAAE;YACf,IAAI,WAAW,CAAC,IAAI;gBAAE,IAAI,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YACjD,IAAI,WAAW,CAAC,IAAI;gBAAE,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC3C,IAAI,WAAW,CAAC,MAAM;gBAAE,IAAI,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC/C,IAAI,WAAW,CAAC,aAAa;gBAAE,IAAI,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC7D,IAAI,WAAW,CAAC,SAAS;gBAAE,IAAI,GAAG,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SACtD;QAED,OAAO,aAAa,GAAG,IAAI,GAAG,cAAc,CAAC;IAC/C,CAAC;CACF;AA1UD,4CA0UC","sourcesContent":["import { Client } from \"@notionhq/client\";\nimport {\n Annotations,\n ListBlockChildrenResponseResult,\n ListBlockChildrenResponseResults,\n MdBlock,\n Text,\n NotionToMarkdownOptions,\n} from \"./types\";\nimport * as md from \"./utils/md\";\nimport { getBlockChildren } from \"./utils/notion\";\n\n/**\n * Converts a Notion page to Markdown.\n */\nexport class NotionToMarkdown {\n private notionClient: Client;\n\n constructor(options: NotionToMarkdownOptions) {\n this.notionClient = options.notionClient;\n }\n\n /**\n * Converts Markdown Blocks to string\n * @param {MdBlock[]} mdBlocks - Array of markdown blocks\n * @param {number} nestingLevel - Defines max depth of nesting\n * @returns {string} - Returns markdown string\n */\n toMarkdownString(mdBlocks: MdBlock[] = [], nestingLevel: number = 0): string {\n let mdString = \"\";\n mdBlocks.forEach((mdBlocks) => {\n if (mdBlocks.parent) {\n mdString += `\n${md.addTabSpace(mdBlocks.parent, nestingLevel)}\n`;\n }\n if (mdBlocks.children && mdBlocks.children.length > 0) {\n mdString += this.toMarkdownString(mdBlocks.children, nestingLevel + 1);\n }\n });\n return mdString;\n }\n\n /**\n * Retrieves Notion Blocks based on ID and converts them to Markdown Blocks\n * @param {string} id - notion page id (not database id)\n * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100 (Default=1)\n * @returns {Promise<MdBlock[]>} - List of markdown blocks\n */\n async pageToMarkdown(id: string, totalPage: number = 1): Promise<MdBlock[]> {\n if (!this.notionClient) {\n throw new Error(\n \"notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md\"\n );\n }\n if (!id) throw new Error(\"pageToMarkdown takes page_id as argument\");\n const blocks = await getBlockChildren(this.notionClient, id, totalPage);\n\n const parsedData = await this.blocksToMarkdown(blocks);\n return parsedData;\n }\n\n /**\n * Converts list of Notion Blocks to Markdown Blocks\n * @param {ListBlockChildrenResponseResults | undefined} blocks - List of notion blocks\n * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100\n * @param {MdBlock[]} mdBlocks - Defines max depth of nesting\n * @returns {Promise<MdBlock[]>} - Array of markdown blocks with their children\n */\n async blocksToMarkdown(\n blocks?: ListBlockChildrenResponseResults,\n totalPage: number = 1,\n mdBlocks: MdBlock[] = []\n ): Promise<MdBlock[]> {\n if (!this.notionClient) {\n throw new Error(\n \"notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md\"\n );\n }\n\n if (!blocks) return mdBlocks;\n\n /**\n * notion's table response is weird. It two objects for same table\n * first object with table width -> 2\n * second object with the actual table width\n * to keep track of table blocks and ignore the first one,\n * tableBlockCount is used.\n */\n let tableBlockCount = 0;\n\n for (let i = 0; i < blocks.length; i++) {\n let block = blocks[i];\n\n if ((block as any).type === \"table\" && tableBlockCount <= 0) {\n tableBlockCount++;\n continue;\n }\n\n tableBlockCount++;\n\n if (\"has_children\" in block && block.has_children) {\n let child_blocks = await getBlockChildren(\n this.notionClient,\n block.id,\n totalPage\n );\n mdBlocks.push({\n parent: await this.blockToMarkdown(block),\n children: [],\n });\n\n let l = mdBlocks.length;\n await this.blocksToMarkdown(\n child_blocks,\n totalPage,\n mdBlocks[l - 1].children\n );\n continue;\n }\n let tmp = await this.blockToMarkdown(block);\n\n mdBlocks.push({ parent: tmp, children: [] });\n }\n return mdBlocks;\n }\n\n /**\n * Converts a Notion Block to a Markdown Block\n * @param {ListBlockChildrenResponseResult} block - single notion block\n * @returns {string} corresponding markdown string of the passed block\n */\n async blockToMarkdown(block: ListBlockChildrenResponseResult) {\n if (!(\"type\" in block)) return \"\";\n\n let parsedData = \"\";\n const { type } = block;\n // console.log({ block });\n\n switch (type) {\n case \"image\":\n {\n let blockContent = block.image;\n const image_caption_plain = blockContent.caption\n .map((item) => item.plain_text)\n .join(\"\");\n const image_type = blockContent.type;\n if (image_type === \"external\")\n return md.image(image_caption_plain, blockContent.external.url);\n if (image_type === \"file\")\n return md.image(image_caption_plain, blockContent.file.url);\n }\n break;\n\n case \"divider\": {\n return md.divider();\n }\n\n case \"equation\": {\n return md.codeBlock(block.equation.expression);\n }\n\n case \"video\":\n case \"file\":\n case \"pdf\":\n {\n let blockContent;\n if (type === \"video\") blockContent = block.video;\n if (type === \"file\") blockContent = block.file;\n if (type === \"pdf\") blockContent = block.pdf;\n if (blockContent) {\n const file_type = blockContent.type;\n if (file_type === \"external\")\n return md.link(\"image\", blockContent.external.url);\n if (file_type === \"file\")\n return md.link(\"image\", blockContent.file.url);\n }\n }\n break;\n\n case \"bookmark\":\n case \"embed\":\n case \"link_preview\":\n {\n let blockContent;\n if (type === \"bookmark\") blockContent = block.bookmark;\n if (type === \"embed\") blockContent = block.embed;\n if (type === \"link_preview\") blockContent = block.link_preview;\n if (blockContent) return md.link(type, blockContent.url);\n }\n break;\n\n case \"table\": {\n const { id, has_children } = block;\n let tableArr: string[][] = [];\n if (has_children) {\n const tableRows = await getBlockChildren(this.notionClient, id, 100);\n // console.log(\">>\", tableRows);\n let rowsPromise = tableRows?.map(async (row) => {\n const { type } = row as any;\n const cells = (row as any)[type][\"cells\"];\n\n /**\n * this is more like a hack since matching the type text was\n * difficult. So converting each cell to paragraph type to\n * reuse the blockToMarkdown function\n */\n let cellStringPromise = cells.map(\n async (cell: any) =>\n await this.blockToMarkdown({\n type: \"paragraph\",\n paragraph: { text: cell },\n } as ListBlockChildrenResponseResult)\n );\n\n const cellStringArr = await Promise.all(cellStringPromise);\n // console.log(\"~~\", cellStringArr);\n tableArr.push(cellStringArr);\n // console.log(tableArr);\n });\n await Promise.all(rowsPromise || []);\n }\n parsedData = md.table(tableArr);\n return parsedData;\n }\n\n // Rest of the types\n // \"paragraph\"\n // \"heading_1\"\n // \"heading_2\"\n // \"heading_3\"\n // \"bulleted_list_item\"\n // \"numbered_list_item\"\n // \"quote\"\n // \"to_do\"\n // \"toggle\"\n // \"template\"\n // \"synced_block\"\n // \"child_page\"\n // \"child_database\"\n // \"code\"\n // \"callout\"\n // \"breadcrumb\"\n // \"table_of_contents\"\n // \"column_list\"\n // \"column\"\n // \"link_to_page\"\n // \"audio\"\n // \"unsupported\"\n\n default: {\n // In this case typescript is not able to index the types properly, hence ignoring the error\n\n // @ts-ignore\n let blockContent = block[type].text || [];\n blockContent.map((content: Text) => {\n const annotations = content.annotations;\n let plain_text = content.plain_text;\n\n plain_text = this.annotatePlainText(plain_text, annotations);\n\n if (content[\"href\"])\n plain_text = md.link(plain_text, content[\"href\"]);\n\n parsedData += plain_text;\n });\n }\n }\n\n switch (type) {\n case \"code\":\n {\n parsedData = md.codeBlock(parsedData, block[type].language);\n }\n break;\n\n case \"heading_1\":\n {\n parsedData = md.heading1(parsedData);\n }\n break;\n\n case \"heading_2\":\n {\n parsedData = md.heading2(parsedData);\n }\n break;\n\n case \"heading_3\":\n {\n parsedData = md.heading3(parsedData);\n }\n break;\n\n case \"quote\":\n {\n parsedData = md.quote(parsedData);\n }\n break;\n\n case \"bulleted_list_item\":\n case \"numbered_list_item\":\n {\n parsedData = md.bullet(parsedData);\n }\n break;\n\n case \"to_do\":\n {\n parsedData = md.todo(parsedData, block.to_do.checked);\n }\n break;\n }\n\n return parsedData;\n }\n\n /**\n * Annoate text using provided annotations\n * @param {string} text - String to be annotated\n * @param {Annotations} annotations - Annotation object of a notion block\n * @returns {string} - Annotated text\n */\n annotatePlainText(text: string, annotations: Annotations): string {\n // if text is all spaces, don't annotate\n if (text.match(/^\\s*$/)) return text;\n\n const leadingSpaceMatch = text.match(/^(\\s*)/);\n const trailingSpaceMatch = text.match(/(\\s*)$/);\n\n const leading_space = leadingSpaceMatch ? leadingSpaceMatch[0] : \"\";\n const trailing_space = trailingSpaceMatch ? trailingSpaceMatch[0] : \"\";\n\n text = text.trim();\n\n if (text !== \"\") {\n if (annotations.code) text = md.inlineCode(text);\n if (annotations.bold) text = md.bold(text);\n if (annotations.italic) text = md.italic(text);\n if (annotations.strikethrough) text = md.strikethrough(text);\n if (annotations.underline) text = md.underline(text);\n }\n\n return leading_space + text + trailing_space;\n }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { ListBlockChildrenResponse } from "@notionhq/client/build/src/api-endpoints";
2
+ import { Client } from "@notionhq/client";
3
+ export declare type ListBlockChildrenResponseResults = ListBlockChildrenResponse["results"];
4
+ export declare type ListBlockChildrenResponseResult = ListBlockChildrenResponseResults[0];
5
+ export declare type TextRequest = string;
6
+ export interface NotionToMarkdownOptions {
7
+ notionClient: Client;
8
+ }
9
+ export declare type MdBlock = {
10
+ parent: string;
11
+ children: MdBlock[];
12
+ };
13
+ export declare type Annotations = {
14
+ bold: boolean;
15
+ italic: boolean;
16
+ strikethrough: boolean;
17
+ underline: boolean;
18
+ code: boolean;
19
+ color: "default" | "gray" | "brown" | "orange" | "yellow" | "green" | "blue" | "purple" | "pink" | "red" | "gray_background" | "brown_background" | "orange_background" | "yellow_background" | "green_background" | "blue_background" | "purple_background" | "pink_background" | "red_background";
20
+ };
21
+ export declare type Text = {
22
+ type: "text";
23
+ text: {
24
+ content: string;
25
+ link: {
26
+ url: TextRequest;
27
+ } | null;
28
+ };
29
+ annotations: Annotations;
30
+ plain_text: string;
31
+ href: string | null;
32
+ };
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,oBAAY,gCAAgC,GAC1C,yBAAyB,CAAC,SAAS,CAAC,CAAC;AAEvC,oBAAY,+BAA+B,GACzC,gCAAgC,CAAC,CAAC,CAAC,CAAC;AAEtC,oBAAY,WAAW,GAAG,MAAM,CAAC;AAEjC,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,oBAAY,OAAO,GAAG;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,EAAE,CAAC;CACrB,CAAC;AAEF,oBAAY,WAAW,GAAG;IACxB,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EACD,SAAS,GACT,MAAM,GACN,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,OAAO,GACP,MAAM,GACN,QAAQ,GACR,MAAM,GACN,KAAK,GACL,iBAAiB,GACjB,kBAAkB,GAClB,mBAAmB,GACnB,mBAAmB,GACnB,kBAAkB,GAClB,iBAAiB,GACjB,mBAAmB,GACnB,iBAAiB,GACjB,gBAAgB,CAAC;CACtB,CAAC;AAEF,oBAAY,IAAI,GAAG;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE;QACJ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE;YACJ,GAAG,EAAE,WAAW,CAAC;SAClB,GAAG,IAAI,CAAC;KACV,CAAC;IACF,WAAW,EAAE,WAAW,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { ListBlockChildrenResponse } from \"@notionhq/client/build/src/api-endpoints\";\nimport { Client } from \"@notionhq/client\";\n\nexport type ListBlockChildrenResponseResults =\n ListBlockChildrenResponse[\"results\"];\n\nexport type ListBlockChildrenResponseResult =\n ListBlockChildrenResponseResults[0];\n\nexport type TextRequest = string;\n\nexport interface NotionToMarkdownOptions {\n notionClient: Client;\n}\n\nexport type MdBlock = {\n parent: string;\n children: MdBlock[];\n};\n\nexport type Annotations = {\n bold: boolean;\n italic: boolean;\n strikethrough: boolean;\n underline: boolean;\n code: boolean;\n color:\n | \"default\"\n | \"gray\"\n | \"brown\"\n | \"orange\"\n | \"yellow\"\n | \"green\"\n | \"blue\"\n | \"purple\"\n | \"pink\"\n | \"red\"\n | \"gray_background\"\n | \"brown_background\"\n | \"orange_background\"\n | \"yellow_background\"\n | \"green_background\"\n | \"blue_background\"\n | \"purple_background\"\n | \"pink_background\"\n | \"red_background\";\n};\n\nexport type Text = {\n type: \"text\";\n text: {\n content: string;\n link: {\n url: TextRequest;\n } | null;\n };\n annotations: Annotations;\n plain_text: string;\n href: string | null;\n};\n"]}
@@ -0,0 +1,20 @@
1
+ export declare const inlineCode: (text: string) => string;
2
+ export declare const bold: (text: string) => string;
3
+ export declare const italic: (text: string) => string;
4
+ export declare const strikethrough: (text: string) => string;
5
+ export declare const underline: (text: string) => string;
6
+ export declare const link: (text: string, href: string) => string;
7
+ export declare const codeBlock: (text: string, language?: string | undefined) => string;
8
+ export declare const heading1: (text: string) => string;
9
+ export declare const heading2: (text: string) => string;
10
+ export declare const heading3: (text: string) => string;
11
+ export declare const quote: (text: string) => string;
12
+ export declare const bullet: (text: string) => string;
13
+ export declare const todo: (text: string, checked: boolean) => string;
14
+ export declare const image: (alt: string, href: string) => string;
15
+ export declare const addTabSpace: (text: string, n?: number) => string;
16
+ export declare const divider: () => string;
17
+ export declare const tableRowHeader: (row: string[]) => string;
18
+ export declare const tableRowBody: (row: string[]) => string;
19
+ export declare const table: (cells: string[][]) => string;
20
+ //# sourceMappingURL=md.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"md.d.ts","sourceRoot":"","sources":["../../src/utils/md.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,SAAU,MAAM,WAEtC,CAAC;AAEF,eAAO,MAAM,IAAI,SAAU,MAAM,WAEhC,CAAC;AAEF,eAAO,MAAM,MAAM,SAAU,MAAM,WAElC,CAAC;AAEF,eAAO,MAAM,aAAa,SAAU,MAAM,WAEzC,CAAC;AAEF,eAAO,MAAM,SAAS,SAAU,MAAM,WAErC,CAAC;AAEF,eAAO,MAAM,IAAI,SAAU,MAAM,QAAQ,MAAM,WAE9C,CAAC;AAEF,eAAO,MAAM,SAAS,SAAU,MAAM,0CAIrC,CAAC;AAEF,eAAO,MAAM,QAAQ,SAAU,MAAM,WAEpC,CAAC;AAEF,eAAO,MAAM,QAAQ,SAAU,MAAM,WAEpC,CAAC;AAEF,eAAO,MAAM,QAAQ,SAAU,MAAM,WAEpC,CAAC;AAEF,eAAO,MAAM,KAAK,SAAU,MAAM,WAGjC,CAAC;AAEF,eAAO,MAAM,MAAM,SAAU,MAAM,WAElC,CAAC;AAEF,eAAO,MAAM,IAAI,SAAU,MAAM,WAAW,OAAO,WAElD,CAAC;AAEF,eAAO,MAAM,KAAK,QAAS,MAAM,QAAQ,MAAM,WAE9C,CAAC;AAEF,eAAO,MAAM,WAAW,SAAU,MAAM,uBAIvC,CAAC;AAEF,eAAO,MAAM,OAAO,cAEnB,CAAC;AAEF,eAAO,MAAM,cAAc,QAAS,MAAM,EAAE,WAI3C,CAAC;AAEF,eAAO,MAAM,YAAY,QAAS,MAAM,EAAE,WAEzC,CAAC;AAEF,eAAO,MAAM,KAAK,UAAW,MAAM,EAAE,EAAE,WAKtC,CAAC"}
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.table = exports.tableRowBody = exports.tableRowHeader = exports.divider = exports.addTabSpace = exports.image = exports.todo = exports.bullet = exports.quote = exports.heading3 = exports.heading2 = exports.heading1 = exports.codeBlock = exports.link = exports.underline = exports.strikethrough = exports.italic = exports.bold = exports.inlineCode = void 0;
4
+ const inlineCode = (text) => {
5
+ return `\`${text}\``;
6
+ };
7
+ exports.inlineCode = inlineCode;
8
+ const bold = (text) => {
9
+ return `**${text}**`;
10
+ };
11
+ exports.bold = bold;
12
+ const italic = (text) => {
13
+ return `_${text}_`;
14
+ };
15
+ exports.italic = italic;
16
+ const strikethrough = (text) => {
17
+ return `~~${text}~~`;
18
+ };
19
+ exports.strikethrough = strikethrough;
20
+ const underline = (text) => {
21
+ return `<u>${text}</u>`;
22
+ };
23
+ exports.underline = underline;
24
+ const link = (text, href) => {
25
+ return `[${text}](${href})`;
26
+ };
27
+ exports.link = link;
28
+ const codeBlock = (text, language) => {
29
+ return `\`\`\`${language}
30
+ ${text}
31
+ \`\`\``;
32
+ };
33
+ exports.codeBlock = codeBlock;
34
+ const heading1 = (text) => {
35
+ return `# ${text}`;
36
+ };
37
+ exports.heading1 = heading1;
38
+ const heading2 = (text) => {
39
+ return `## ${text}`;
40
+ };
41
+ exports.heading2 = heading2;
42
+ const heading3 = (text) => {
43
+ return `### ${text}`;
44
+ };
45
+ exports.heading3 = heading3;
46
+ const quote = (text) => {
47
+ // the replace is done to handle multiple lines
48
+ return `> ${text.replace(/\n/g, " \n>")}`;
49
+ };
50
+ exports.quote = quote;
51
+ const bullet = (text) => {
52
+ return `- ${text}`;
53
+ };
54
+ exports.bullet = bullet;
55
+ const todo = (text, checked) => {
56
+ return checked ? `- [x] ${text}` : `- [ ] ${text}`;
57
+ };
58
+ exports.todo = todo;
59
+ const image = (alt, href) => {
60
+ return `![${alt}](${href})`;
61
+ };
62
+ exports.image = image;
63
+ const addTabSpace = (text, n = 0) => {
64
+ const tab = " ";
65
+ for (let i = 0; i < n; i++)
66
+ text = tab + text;
67
+ return text;
68
+ };
69
+ exports.addTabSpace = addTabSpace;
70
+ const divider = () => {
71
+ return "---";
72
+ };
73
+ exports.divider = divider;
74
+ const tableRowHeader = (row) => {
75
+ let header = row.join("|");
76
+ let divider = row.map((_) => "---").join("|");
77
+ return `${header}\n${divider}`;
78
+ };
79
+ exports.tableRowHeader = tableRowHeader;
80
+ const tableRowBody = (row) => {
81
+ return row.join("|");
82
+ };
83
+ exports.tableRowBody = tableRowBody;
84
+ const table = (cells) => {
85
+ const tableRows = cells.map((row, i) => !i ? (0, exports.tableRowHeader)(row) : (0, exports.tableRowBody)(row));
86
+ return tableRows.join("\n");
87
+ };
88
+ exports.table = table;
89
+ //# sourceMappingURL=md.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"md.js","sourceRoot":"","sources":["../../src/utils/md.ts"],"names":[],"mappings":";;;AAAO,MAAM,UAAU,GAAG,CAA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,GAAG,CAAC,CAAC;IAC3B,IAAI,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9C,OAAO,GAAG,MAAM,KAAK,OAAO,EAAE,CAAC;AACjC,CAAC,CAAC;AAJW,QAAA,cAAc,kBAIzB;AAEK,MAAM,YAAY,GAAG,CAAC,GAAa,EAAE,EAAE;IAC5C,OAAO,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC;AAFW,QAAA,YAAY,gBAEvB;AAEK,MAAM,KAAK,GAAG,CAAC,KAAiB,EAAE,EAAE;IACzC,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CACrC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,sBAAc,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAA,oBAAY,EAAC,GAAG,CAAC,CAC7C,CAAC;IACF,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC,CAAC;AALW,QAAA,KAAK,SAKhB","sourcesContent":["export const inlineCode = (text: string) => {\n return `\\`${text}\\``;\n};\n\nexport const bold = (text: string) => {\n return `**${text}**`;\n};\n\nexport const italic = (text: string) => {\n return `_${text}_`;\n};\n\nexport const strikethrough = (text: string) => {\n return `~~${text}~~`;\n};\n\nexport const underline = (text: string) => {\n return `<u>${text}</u>`;\n};\n\nexport const link = (text: string, href: string) => {\n return `[${text}](${href})`;\n};\n\nexport const codeBlock = (text: string, language?: string) => {\n return `\\`\\`\\`${language}\n${text}\n\\`\\`\\``;\n};\n\nexport const heading1 = (text: string) => {\n return `# ${text}`;\n};\n\nexport const heading2 = (text: string) => {\n return `## ${text}`;\n};\n\nexport const heading3 = (text: string) => {\n return `### ${text}`;\n};\n\nexport const quote = (text: string) => {\n // the replace is done to handle multiple lines\n return `> ${text.replace(/\\n/g, \" \\n>\")}`;\n};\n\nexport const bullet = (text: string) => {\n return `- ${text}`;\n};\n\nexport const todo = (text: string, checked: boolean) => {\n return checked ? `- [x] ${text}` : `- [ ] ${text}`;\n};\n\nexport const image = (alt: string, href: string) => {\n return `![${alt}](${href})`;\n};\n\nexport const addTabSpace = (text: string, n = 0) => {\n const tab = \"\t\";\n for (let i = 0; i < n; i++) text = tab + text;\n return text;\n};\n\nexport const divider = () => {\n return \"---\";\n};\n\nexport const tableRowHeader = (row: string[]) => {\n let header = row.join(\"|\");\n let divider = row.map((_) => \"---\").join(\"|\");\n return `${header}\\n${divider}`;\n};\n\nexport const tableRowBody = (row: string[]) => {\n return row.join(\"|\");\n};\n\nexport const table = (cells: string[][]) => {\n const tableRows = cells.map((row, i) =>\n !i ? tableRowHeader(row) : tableRowBody(row)\n );\n return tableRows.join(\"\\n\");\n};\n"]}
@@ -0,0 +1,6 @@
1
+ import { Client } from "@notionhq/client";
2
+ export declare const getBlockChildren: (notionClient: Client, block_id: string, totalPage: number) => Promise<{
3
+ object: "block";
4
+ id: string;
5
+ }[] | undefined>;
6
+ //# sourceMappingURL=notion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notion.d.ts","sourceRoot":"","sources":["../../src/utils/notion.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAG1C,eAAO,MAAM,gBAAgB,iBACb,MAAM,YACV,MAAM,aACL,MAAM;;;gBA6BlB,CAAC"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getBlockChildren = void 0;
4
+ const getBlockChildren = async (notionClient, block_id, totalPage) => {
5
+ try {
6
+ let result = [];
7
+ let start_cursor;
8
+ let pageSize = 100;
9
+ for (let i = 0; i < totalPage; i++) {
10
+ // contain start_cursor
11
+ const response = (await notionClient.blocks.children.list({
12
+ start_cursor: start_cursor,
13
+ page_size: pageSize,
14
+ block_id: block_id,
15
+ }));
16
+ let current = response.results;
17
+ // delete start_cursor
18
+ if (start_cursor) {
19
+ current.shift();
20
+ }
21
+ result.push(...current);
22
+ if (current.length < 100) {
23
+ break;
24
+ }
25
+ pageSize = 101;
26
+ start_cursor = current[current.length - 1].id;
27
+ }
28
+ return result;
29
+ }
30
+ catch (e) {
31
+ console.log(e);
32
+ }
33
+ };
34
+ exports.getBlockChildren = getBlockChildren;
35
+ //# sourceMappingURL=notion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notion.js","sourceRoot":"","sources":["../../src/utils/notion.ts"],"names":[],"mappings":";;;AAGO,MAAM,gBAAgB,GAAG,KAAK,EACnC,YAAoB,EACpB,QAAgB,EAChB,SAAiB,EACjB,EAAE;IACF,IAAI;QACF,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,IAAI,YAAY,CAAC;QACjB,IAAI,QAAQ,GAAG,GAAG,CAAC;QACnB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,EAAE,EAAE;YAClC,uBAAuB;YACvB,MAAM,QAAQ,GAAG,CAAC,MAAM,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACxD,YAAY,EAAE,YAAY;gBAC1B,SAAS,EAAE,QAAQ;gBACnB,QAAQ,EAAE,QAAQ;aACnB,CAAC,CAA8B,CAAC;YACjC,IAAI,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;YAC/B,sBAAsB;YACtB,IAAI,YAAY,EAAE;gBAChB,OAAO,CAAC,KAAK,EAAE,CAAC;aACjB;YACD,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC;YACxB,IAAI,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;gBACxB,MAAM;aACP;YACD,QAAQ,GAAG,GAAG,CAAC;YACf,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C;QACD,OAAO,MAAM,CAAC;KACf;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KAChB;AACH,CAAC,CAAC;AAhCW,QAAA,gBAAgB,oBAgC3B","sourcesContent":["import { Client } from \"@notionhq/client\";\nimport { ListBlockChildrenResponse } from \"@notionhq/client/build/src/api-endpoints\";\n\nexport const getBlockChildren = async (\n notionClient: Client,\n block_id: string,\n totalPage: number\n) => {\n try {\n let result = [];\n let start_cursor;\n let pageSize = 100;\n for (let i = 0; i < totalPage; i++) {\n // contain start_cursor\n const response = (await notionClient.blocks.children.list({\n start_cursor: start_cursor,\n page_size: pageSize,\n block_id: block_id,\n })) as ListBlockChildrenResponse;\n let current = response.results;\n // delete start_cursor\n if (start_cursor) {\n current.shift();\n }\n result.push(...current);\n if (current.length < 100) {\n break;\n }\n pageSize = 101;\n start_cursor = current[current.length - 1].id;\n }\n return result;\n } catch (e) {\n console.log(e);\n }\n};\n"]}
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "notion-to-md",
3
- "version": "1.0.8",
4
- "main": "main.js",
5
- "typings": "main.d.ts",
3
+ "version": "2.2.0",
4
+ "engines": {
5
+ "node": ">=12"
6
+ },
7
+ "main": "./build",
8
+ "types": "./build/index.d.ts",
6
9
  "scripts": {
10
+ "prepare": "npm run build",
11
+ "build": "tsc",
12
+ "prebuild": "npm run clean",
13
+ "clean": "rm -rf ./build",
7
14
  "test": "echo \"Error: no test specified\" && exit 1"
8
15
  },
9
16
  "keywords": [
@@ -17,6 +24,9 @@
17
24
  ],
18
25
  "author": "",
19
26
  "license": "ISC",
27
+ "files": [
28
+ "build/**"
29
+ ],
20
30
  "repository": {
21
31
  "type": "git",
22
32
  "url": "git+https://github.com/souvikinator/notion-to-md.git"
@@ -26,7 +36,8 @@
26
36
  },
27
37
  "homepage": "https://github.com/souvikinator/notion-to-md#readme",
28
38
  "description": "convert notion pages, block and list of blocks to markdown (supports nesting)",
29
- "dependencies": {
30
- "@notionhq/client": "^0.4.11"
39
+ "devDependencies": {
40
+ "@notionhq/client": "^0.4.12",
41
+ "typescript": "^4.5.4"
31
42
  }
32
43
  }
package/main.d.ts DELETED
@@ -1,18 +0,0 @@
1
- interface MdBlock {
2
- parent: string;
3
- children: MdBlock[];
4
- }
5
-
6
- declare module "notion-to-md" {
7
- export default class Notion2md {
8
- constructor({ notionClient }: { notionClient: any });
9
- pageToMarkdown(page_id: string, totalPage: number = 1): Promise<MdBlock[]>;
10
- toMarkdownString(mdBlocks: MdBlock[]): string;
11
- blocksToMarkdown(
12
- blocks: any,
13
- mdBlocks: MdBlock[],
14
- totalPage: number = 1
15
- ): Promise<MdBlock[]>;
16
- blockToMarkdown(block: any): string;
17
- }
18
- }
package/notion-to-md.js DELETED
@@ -1,151 +0,0 @@
1
- const md = require("./utils/md");
2
- const { getBlockChildren } = require("./utils/notion");
3
- class notion2md {
4
- constructor(options) {
5
- if (!options) {
6
- this.notionClient = undefined;
7
- } else {
8
- this.notionClient = options.notionClient || undefined;
9
- }
10
- }
11
-
12
- toMarkdownString(mdBlocks = [], nestingLevel = 0) {
13
- let mdString = "";
14
- mdBlocks.forEach((mdBlocks) => {
15
- if (mdBlocks.parent) {
16
- mdString += `
17
- ${md.addTabSpace(mdBlocks.parent, nestingLevel)}
18
- `;
19
- }
20
- if (mdBlocks.children && mdBlocks.children.length > 0) {
21
- mdString += this.toMarkdownString(mdBlocks.children, nestingLevel + 1);
22
- }
23
- });
24
- return mdString;
25
- }
26
-
27
- /**
28
- * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100
29
- */
30
- async pageToMarkdown(id, totalPage = 1) {
31
- if (!id) throw new Error("pageToMarkdown takes page_id as argument");
32
- const blocks = await getBlockChildren(this.notionClient, id, totalPage);
33
- const parsedData = await this.blocksToMarkdown(blocks);
34
- return parsedData;
35
- }
36
-
37
- /**
38
- * @param {object} blocks - list of notion blocks
39
- * @param {number} totalPage - Retrieve block children request number, page_size Maximum = totalPage * 100
40
- * @returns array of md blocks with their children
41
- */
42
- async blocksToMarkdown(blocks, mdBlocks = [], totalPage = 1) {
43
- if (!this.notionClient) {
44
- throw new Error(
45
- "notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md"
46
- );
47
- }
48
-
49
- for (let i = 0; i < blocks.length; i++) {
50
- let block = blocks[i];
51
- if (block.has_children) {
52
- let child_blocks = await getBlockChildren(
53
- this.notionClient,
54
- block.id,
55
- totalPage
56
- );
57
- mdBlocks.push({ parent: this.blockToMarkdown(block), children: [] });
58
- let l = mdBlocks.length;
59
- await this.blocksToMarkdown(child_blocks, mdBlocks[l - 1].children);
60
- continue;
61
- }
62
- let tmp = this.blockToMarkdown(block);
63
-
64
- mdBlocks.push({ parent: tmp, children: [] });
65
- }
66
- return mdBlocks;
67
- }
68
-
69
- /**
70
- * @param {object} block - single notion block
71
- * @returns markdown form of the passed block
72
- */
73
- blockToMarkdown(block) {
74
- if (!block) throw new Error("notion block required");
75
-
76
- let parsedData = "",
77
- blockContent;
78
- const { type } = block;
79
- if (type === "image") {
80
- blockContent = block[type];
81
- const image_type = blockContent["type"];
82
-
83
- return md.image("image", blockContent[image_type].url);
84
- } else if (type === "divider") {
85
- return md.divider();
86
- } else if (type === "equation") {
87
- return md.codeBlock(block[type].expression);
88
- } else if (type === "video" || type === "file" || type === "pdf") {
89
- blockContent = block[type];
90
- const urlType = blockContent["type"];
91
-
92
- return md.link(type, blockContent[urlType].url);
93
- } else if (
94
- type === "bookmark" ||
95
- type === "embed" ||
96
- type === "link_preview"
97
- ) {
98
- blockContent = block[type];
99
-
100
- return md.link(type, blockContent.url);
101
- } else {
102
- blockContent = block[type]["text"] || [];
103
- blockContent.map((content) => {
104
- const annotations = content.annotations;
105
- let plain_text = content.plain_text;
106
-
107
- plain_text = this.annotatePlainText(plain_text, annotations);
108
-
109
- if (content["href"]) plain_text = md.link(plain_text, content["href"]);
110
-
111
- parsedData += plain_text;
112
- });
113
- }
114
-
115
- if (type === "code")
116
- parsedData = md.codeBlock(parsedData, block[type].language);
117
- if (type === "heading_1") parsedData = md.heading1(parsedData);
118
- if (type === "heading_2") parsedData = md.heading2(parsedData);
119
- if (type === "heading_3") parsedData = md.heading3(parsedData);
120
- if (type === "quote") parsedData = md.quote(parsedData);
121
-
122
- if (type === "numbered_list_item" || type === "bulleted_list_item")
123
- parsedData = md.bullet(parsedData);
124
-
125
- if (type === "to_do") parsedData = md.todo(parsedData, block[type].checked);
126
-
127
- return parsedData;
128
- }
129
-
130
- /**
131
- * @param {string} text string to be annotated
132
- * @param {object} annotations annotation object of a notion block
133
- */
134
- annotatePlainText(text, annotations) {
135
- const leading_space = text.match(/^\s*/)[0];
136
- const trailing_space = text.match(/\s*$/)[0];
137
- text = text.trim();
138
-
139
- if (text !== "") {
140
- if (annotations.code) text = md.inlineCode(text);
141
- if (annotations.bold) text = md.bold(text);
142
- if (annotations.italic) text = md.italic(text);
143
- if (annotations.strikethrough) text = md.strikethrough(text);
144
- if (annotations.underline) text = md.underline(text);
145
- }
146
-
147
- return leading_space + text + trailing_space;
148
- }
149
- }
150
-
151
- module.exports = notion2md;
package/utils/md.js DELETED
@@ -1,68 +0,0 @@
1
- exports.inlineCode = (text) => {
2
- return `\`${text}\``;
3
- };
4
-
5
- exports.bold = (text) => {
6
- return `**${text}**`;
7
- };
8
-
9
- exports.italic = (text) => {
10
- return `_${text}_`;
11
- };
12
-
13
- exports.strikethrough = (text) => {
14
- return `~~${text}~~`;
15
- };
16
-
17
- exports.underline = (text) => {
18
- return `<u>${text}</u>`;
19
- };
20
-
21
- exports.link = (text, href) => {
22
- return `[${text}](${href})`;
23
- };
24
-
25
- exports.codeBlock = (text, language) => {
26
- return `\`\`\`${language}
27
- ${text}
28
- \`\`\``;
29
- };
30
-
31
- exports.heading1 = (text) => {
32
- return `# ${text}`;
33
- };
34
-
35
- exports.heading2 = (text) => {
36
- return `## ${text}`;
37
- };
38
-
39
- exports.heading3 = (text) => {
40
- return `### ${text}`;
41
- };
42
-
43
- exports.quote = (text) => {
44
- // the replace is done to handle multiple lines
45
- return `> ${text.replace(/\n/g, " \n>")}`;
46
- };
47
-
48
- exports.bullet = (text) => {
49
- return `- ${text}`;
50
- };
51
-
52
- exports.todo = (text, checked) => {
53
- return checked ? `- [x] ${text}` : `- [ ] ${text}`;
54
- };
55
-
56
- exports.image = (alt, href) => {
57
- return `![${alt}](${href})`;
58
- };
59
-
60
- exports.addTabSpace = (text, n = 0) => {
61
- const tab = " ";
62
- for (i = 0; i < n; i++) text = tab + text;
63
- return text;
64
- };
65
-
66
- exports.divider = () => {
67
- return "---";
68
- };
package/utils/notion.js DELETED
@@ -1,34 +0,0 @@
1
- exports.getBlockChildren = async (notionClient, block_id, totalPage) => {
2
- try {
3
- if (!notionClient) {
4
- throw new Error(
5
- "notion client is not provided, for more details check out https://github.com/souvikinator/notion-to-md"
6
- );
7
- }
8
- let result = [];
9
- let start_cursor;
10
- let pageSize = 100;
11
- for (i = 0; i < totalPage; i++) {
12
- // contain start_cursor
13
- const response = await notionClient.blocks.children.list({
14
- start_cursor: start_cursor,
15
- page_size: pageSize,
16
- block_id: block_id,
17
- });
18
- let current = response.results;
19
- // delete start_cursor
20
- if (start_cursor) {
21
- current.shift();
22
- }
23
- result.push(...current);
24
- if (current.length < 100) {
25
- break;
26
- }
27
- pageSize = 101;
28
- start_cursor = current[current.length - 1].id;
29
- }
30
- return result;
31
- } catch (e) {
32
- console.log(e);
33
- }
34
- };