notion-batch-apply-template 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yuta Nagamiya
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 ADDED
@@ -0,0 +1,57 @@
1
+ # Notion Batch Apply Template
2
+
3
+ This Node.js script allows you to batch apply a Notion template to all existing pages within a specific data source.
4
+
5
+ > [!WARNING]
6
+ > This script is configured with `erase_content: true`.
7
+ > All existing content within the target pages will be permanently deleted and replaced by the specified template.
8
+ > Please test this on a duplicate or dummy database before running it on production data.
9
+
10
+ ## Installation
11
+
12
+ > [!NOTE]
13
+ > If you are using npx, you can skip the installation step and run the script directly with `npx notion-batch-apply-template ...`.
14
+
15
+ Install the package using npm:
16
+
17
+ ```bash
18
+ npm install notion-batch-apply-template
19
+ ```
20
+
21
+ ## Setup
22
+
23
+ Set your [Notion integration token](https://www.notion.com/help/create-integrations-with-the-notion-api) as an environment variable:
24
+
25
+ ```bash
26
+ export NOTION_TOKEN="your_integration_token"
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ Run the script:
32
+
33
+ ```bash
34
+ notion-batch-apply-template --data-source <data_source_id> [options]
35
+ ```
36
+
37
+ ### Arguments
38
+
39
+ | Argument | Required | Default | Description |
40
+ |-----------------------------|----------|-----------|-----------------------------------------------------------------------------------|
41
+ | `--data-source` (or `--ds`) | Yes | - | The ID of the target data source. |
42
+ | `--template` | No | `default` | The ID or URL of the template to apply. If omitted, the default template is used. |
43
+ | `--delay` | No | `150` | Delay in milliseconds between API calls to avoid rate limiting. |
44
+
45
+ > [!TIP]
46
+ > To get a data source ID from the Notion app, the settings menu for a database includes a "Copy data source ID" button under "Manage data sources":
47
+ > ![](https://mintcdn.com/notion-demo/S-I3qLQnwRa7HjdK/images/reference/image-4.png?w=2500&fit=max&auto=format&n=S-I3qLQnwRa7HjdK&q=85&s=02948f93889722aa8adfce042bdd8b54)
48
+
49
+ ## License
50
+
51
+ Notion Batch Apply Template is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
52
+
53
+ ### Disclaimer
54
+
55
+ This tool performs destructive operations.
56
+ The author is not responsible for any data loss or damages resulting from the use of this script.
57
+ Use it at your own risk.
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Client } from '@notionhq/client';
4
+
5
+ const notion = new Client({ auth: process.env.NOTION_TOKEN });
6
+
7
+ function normalizeUuid(uuid) {
8
+ const hex = uuid.replace(/-/g, '');
9
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
10
+ }
11
+
12
+ function extractUuid(str) {
13
+ const m = String(str).match(
14
+ /\b[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\b/
15
+ );
16
+ if (!m) {
17
+ throw new Error(`No UUID found in input: ${str}`);
18
+ }
19
+ return normalizeUuid(m[0]);
20
+ }
21
+
22
+ function parseArgs(argv) {
23
+ const args = {
24
+ dataSource: null,
25
+ template: null,
26
+ delayMs: 150,
27
+ };
28
+
29
+ for (let i = 2; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ if (a === '--data-source' || a === '--ds') {
32
+ args.dataSource = argv[++i];
33
+ } else if (a === '--template') {
34
+ args.template = argv[++i];
35
+ } else if (a === '--delay') {
36
+ args.delayMs = Number(argv[++i] ?? '150');
37
+ } else {
38
+ throw new Error(`Unknown argument: ${a}`);
39
+ }
40
+ }
41
+
42
+ if (!args.dataSource) {
43
+ throw new Error('Missing required argument: --data-source (or --ds)');
44
+ }
45
+ if (Number.isNaN(args.delayMs) || args.delayMs < 0) {
46
+ throw new Error('Invalid value for --delay (must be a non-negative number)');
47
+ }
48
+
49
+ return args;
50
+ }
51
+
52
+ async function sleep(ms) {
53
+ return new Promise((r) => setTimeout(r, ms));
54
+ }
55
+
56
+ async function listAllPagesInDataSource(dataSourceId) {
57
+ const pages = [];
58
+ let cursor = undefined;
59
+
60
+ while (true) {
61
+ const res = await notion.dataSources.query({
62
+ data_source_id: dataSourceId,
63
+ start_cursor: cursor,
64
+ page_size: 100,
65
+ });
66
+
67
+ pages.push(...res.results);
68
+ if (!res.has_more) {
69
+ break;
70
+ }
71
+ cursor = res.next_cursor;
72
+ }
73
+
74
+ return pages;
75
+ }
76
+
77
+ async function applyTemplateToPage(pageId, templateId) {
78
+ const template = templateId
79
+ ? { type: 'template_id', template_id: templateId }
80
+ : { type: 'default' };
81
+
82
+ return notion.pages.update({
83
+ page_id: pageId,
84
+ erase_content: true,
85
+ template: template,
86
+ });
87
+ }
88
+
89
+ async function main() {
90
+ if (!process.env.NOTION_TOKEN) {
91
+ throw new Error('Missing environment variable: NOTION_TOKEN');
92
+ }
93
+
94
+ const { dataSource, template, delayMs } = parseArgs(process.argv);
95
+
96
+ const dataSourceId = extractUuid(dataSource);
97
+ const templateId = template ? extractUuid(template) : null;
98
+
99
+ console.log(`Data source: ${dataSourceId}`);
100
+ console.log(`Template: ${templateId ?? 'default'}`);
101
+ console.log(`Delay: ${delayMs} ms`);
102
+
103
+ const pages = await listAllPagesInDataSource(dataSourceId);
104
+ console.log(`Pages: ${pages.length}`);
105
+
106
+ for (let i = 0; i < pages.length; i++) {
107
+ const pageId = pages[i].id;
108
+
109
+ try {
110
+ await applyTemplateToPage(pageId, templateId);
111
+ console.log(`[${i + 1}/${pages.length}] OK: ${pageId}`);
112
+ } catch (e) {
113
+ const details = e?.body ? JSON.stringify(e.body) : String(e);
114
+ console.error(`[${i + 1}/${pages.length}] FAILED: ${pageId} | ${details}`);
115
+ }
116
+
117
+ await sleep(delayMs);
118
+ }
119
+ }
120
+
121
+ main().catch((e) => {
122
+ console.error(e?.message ? `ERROR: ${e.message}` : `ERROR: ${String(e)}`);
123
+ process.exit(1);
124
+ });
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "notion-batch-apply-template",
3
+ "type": "module",
4
+ "version": "0.2.0",
5
+ "description": "This Node.js script allows you to batch apply a Notion template to all existing pages within a specific database.",
6
+ "keywords": [
7
+ "notion",
8
+ "cli",
9
+ "batch-apply-template"
10
+ ],
11
+ "license": "MIT",
12
+ "bin": {
13
+ "notion-batch-apply-template": "batch-apply-template.js"
14
+ },
15
+ "dependencies": {
16
+ "@notionhq/client": "^5.11.1"
17
+ }
18
+ }