@luutuankiet/clipboard2markdown 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,91 +1,121 @@
1
- # Clipboard2Markdown
2
-
3
- **Agent-Ready Markdown from Any Webpage.**
4
-
5
- A client-side tool that converts complex HTML (tables, code blocks, nested lists) from authenticated platforms into clean Markdown. Perfect for pasting context into AI agents without granting them API access.
6
-
7
- ## Why This Exists
8
-
9
- Workflow platforms don't let you copy as Markdown — you get rich text. But your AI agents need Markdown. And getting agents to authenticate to Jira/Confluence/Slack is painful or impossible.
10
-
11
- **The solution:** Copy from any authenticated page → Paste here → Get clean Markdown → Paste to your agent.
12
-
13
- ## Supported Platforms
14
-
15
- | Platform | Status | Notable Fixes |
16
- |----------|--------|---------------|
17
- | Jira | ✅ Full | Code blocks preserve newlines & indentation |
18
- | Confluence | ✅ Full | Smart links, emoji, lists inside tables |
19
- | Google Sheets | ✅ Full | Merged cells (rowspan/colspan), pipe escaping |
20
- | Slack | ✅ Full | Code blocks, list formatting |
21
- | Notion | 🔜 Planned | — |
22
-
23
- ## Features
24
-
25
- - **🔄 Turndown.js Engine** — Robust GFM support (tables, task lists, strikethrough)
26
- - **🧹 Platform Sanitizers** — Pre-process quirky HTML before conversion
27
- - **🔒 100% Client-Side** — No data leaves your browser
28
- - **🧪 Automated Testing** — Fixture-based regression suite prevents breakage
29
- - **⚡ Vite Build System** — Hot reload dev server, optimized production builds
30
-
31
- ## Demo
32
-
33
- **Live:** https://luutuankiet.github.io/clipboard2markdown/
34
-
35
- ![Screencast](screencast.gif)
36
-
37
- ## Command Line
38
-
39
- The same converters ship as the `c2m` CLI:
40
-
41
- ```bash
42
- npm install -g @luutuankiet/clipboard2markdown
43
- c2m --help
44
- ```
45
-
46
- `c2m` reads the clipboard, converts it (HTML to Markdown, or Markdown to HTML), and writes the result back. Clipboard conversion needs macOS.
47
-
48
- ## Development
49
-
50
- ```bash
51
- # Install dependencies
52
- npm install
53
-
54
- # Start dev server with hot reload
55
- npm run dev
56
-
57
- # Run regression tests
58
- npm test
59
-
60
- # Build for production
61
- npm run build
62
- ```
63
-
64
- ### Adding Test Cases
65
-
66
- No code required — just add files:
67
-
68
- 1. Save raw HTML to `tests/fixtures/{platform}/{case}.html`
69
- 2. Create expected output in `tests/fixtures/{platform}/{case}.md`
70
- 3. Run `npm test` — the runner auto-discovers new pairs
71
-
72
- **Tip:** Use the "📋 Copy Raw HTML" button in the app to capture clipboard HTML for fixtures.
73
-
74
- ## Credits
75
-
76
- Forked from [clipboard2markdown](https://github.com/euangoddard/clipboard2markdown) by Euan Goddard.
77
-
78
- Modernized with:
79
- - [Turndown.js](https://github.com/mixmark-io/turndown) (replacing to-markdown)
80
- - [Vite](https://vitejs.dev/) build system
81
- - Platform-specific sanitizers for Jira, Confluence, Google Sheets, Slack
82
-
83
- ## License
84
-
85
- [![License][license-image]][license-url]
86
-
87
- Released under the MIT License. See the [LICENSE](LICENSE) file
88
- for details.
89
-
90
- [license-image]: https://img.shields.io/npm/l/markdownlint.svg
91
- [license-url]: http://opensource.org/licenses/MIT
1
+ # Clipboard2Markdown
2
+
3
+ **Agent-Ready Markdown from Any Webpage.**
4
+
5
+ A client-side tool that converts complex HTML (tables, code blocks, nested lists) from authenticated platforms into clean Markdown. Perfect for pasting context into AI agents without granting them API access.
6
+
7
+ ## Why This Exists
8
+
9
+ Workflow platforms don't let you copy as Markdown — you get rich text. But your AI agents need Markdown. And getting agents to authenticate to Jira/Confluence/Slack is painful or impossible.
10
+
11
+ **The solution:** Copy from any authenticated page → Paste here → Get clean Markdown → Paste to your agent.
12
+
13
+ ## Supported Platforms
14
+
15
+ | Platform | Status | Notable Fixes |
16
+ |----------|--------|---------------|
17
+ | Jira | ✅ Full | Code blocks preserve newlines & indentation |
18
+ | Confluence | ✅ Full | Smart links, emoji, lists inside tables |
19
+ | Google Sheets | ✅ Full | Merged cells (rowspan/colspan), pipe escaping |
20
+ | Slack | ✅ Full | Code blocks, list formatting |
21
+ | Notion | 🔜 Planned | — |
22
+
23
+ ## Features
24
+
25
+ - **🔄 Turndown.js Engine** — Robust GFM support (tables, task lists, strikethrough)
26
+ - **🧹 Platform Sanitizers** — Pre-process quirky HTML before conversion
27
+ - **🔒 Client-Side** — Nothing you paste leaves your browser. The one exception to *any* network traffic is the diagrams mode (below), which downloads the Excalidraw scenes your pasted links point to, read-only
28
+ - **🧭 Diagram round trip** — Turn excalidraw.com share links into Mermaid that agents can read, and let agents edit a canvas by link (see below)
29
+ - **🧪 Automated Testing** — Fixture-based regression suite prevents breakage
30
+ - **⚡ Vite Build System** — Hot reload dev server, optimized production builds
31
+
32
+ ## Diagrams: Excalidraw links ⇄ Mermaid
33
+
34
+ For documents whose diagrams live as excalidraw.com share links (a screenshot plus the link, as in a Google Doc).
35
+
36
+ **Page: MD → MD (diagrams).** Paste Markdown; under each share link a fenced Mermaid *reading copy* of the canvas is inserted between `<!-- excalidraw-mermaid:begin <id> -->` / `end` markers. The rest of the text is unchanged byte-for-byte. Re-pasting replaces blocks rather than duplicating them, and **Strip diagram blocks** removes them all before you promote the document again.
37
+
38
+ Privacy: this mode sends one read-only `GET` per link to `json.excalidraw.com` (the backend named by the link) and decrypts the scene in your browser with the key in the link's `#` fragment. Nothing you paste is sent. The HTML → MD and MD → HTML modes make no network requests at all.
39
+
40
+ **CLI for agents** (`bin/diagrams.js`, Node 20+, any OS):
41
+
42
+ ```bash
43
+ node bin/diagrams.js expand doc.md [--write] # same output as the page
44
+ node bin/diagrams.js strip doc.md [--write]
45
+ node bin/diagrams.js show '<share url>' # or a local .excalidraw file
46
+ node bin/diagrams.js edit '<share url>' --ops '[{"op":"rename","node":"auth","label":"Identity"}]'
47
+ ```
48
+
49
+ `edit` patches the existing canvas (rename, add, connect, disconnect, relabel-edge, remove), keeps every untouched element exactly as it was, uploads the result and prints exactly one new share link. The old link keeps working. Node ids are the ones `show` prints. Uploading exists only in the CLI.
50
+
51
+ **New diagram from JSON** (`c2m excalidraw`, Node 20+, any OS): an agent describes boxes, labels and arrows in a short JSON array and gets back a share link, a Mermaid preview of what it drew, and layout warnings (overlaps, labels that do not fit, loose arrows). `c2m excalidraw --help` is the full manual: input format, worked example, sizing rules and the check-fix-upload loop.
52
+
53
+ ```bash
54
+ c2m excalidraw diagram.json --no-upload # check: preview + warnings only
55
+ c2m excalidraw diagram.json # upload: link on line 1
56
+ cat diagram.json | c2m excalidraw - # same, from stdin
57
+ ```
58
+
59
+ The Mermaid is deliberately lossy: positions, colours, fonts and arrow curves are dropped; boxes, labels, connections, line style and grouping are kept. The canvas stays the master copy.
60
+
61
+ ## Demo
62
+
63
+ **Live:** https://luutuankiet.github.io/clipboard2markdown/
64
+
65
+ ![Screencast](screencast.gif)
66
+
67
+ ## Command Line
68
+
69
+ The same converters ship as the `c2m` CLI:
70
+
71
+ ```bash
72
+ npm install -g @luutuankiet/clipboard2markdown
73
+ c2m --help
74
+ ```
75
+
76
+ `c2m` reads the clipboard, converts it (HTML to Markdown, or Markdown to HTML), and writes the result back. Clipboard conversion needs macOS. `c2m excalidraw` and `c2m-diagrams` run anywhere Node 20+ runs.
77
+
78
+ ## Development
79
+
80
+ ```bash
81
+ # Install dependencies
82
+ npm install
83
+
84
+ # Start dev server with hot reload
85
+ npm run dev
86
+
87
+ # Run regression tests
88
+ npm test
89
+
90
+ # Build for production
91
+ npm run build
92
+ ```
93
+
94
+ ### Adding Test Cases
95
+
96
+ No code required — just add files:
97
+
98
+ 1. Save raw HTML to `tests/fixtures/{platform}/{case}.html`
99
+ 2. Create expected output in `tests/fixtures/{platform}/{case}.md`
100
+ 3. Run `npm test` — the runner auto-discovers new pairs
101
+
102
+ **Tip:** Use the "📋 Copy Raw HTML" button in the app to capture clipboard HTML for fixtures.
103
+
104
+ ## Credits
105
+
106
+ Forked from [clipboard2markdown](https://github.com/euangoddard/clipboard2markdown) by Euan Goddard.
107
+
108
+ Modernized with:
109
+ - [Turndown.js](https://github.com/mixmark-io/turndown) (replacing to-markdown)
110
+ - [Vite](https://vitejs.dev/) build system
111
+ - Platform-specific sanitizers for Jira, Confluence, Google Sheets, Slack
112
+
113
+ ## License
114
+
115
+ [![License][license-image]][license-url]
116
+
117
+ Released under the MIT License. See the [LICENSE](LICENSE) file
118
+ for details.
119
+
120
+ [license-image]: https://img.shields.io/npm/l/markdownlint.svg
121
+ [license-url]: http://opensource.org/licenses/MIT
package/bin/cli.js CHANGED
@@ -14,6 +14,9 @@ Usage:
14
14
  c2m --help show this help
15
15
  c2m --version print the version
16
16
 
17
+ c2m excalidraw <file|-> JSON diagram -> excalidraw.com share link and
18
+ Mermaid preview (any OS; see c2m excalidraw --help)
19
+
17
20
  Clipboard conversion needs macOS (it uses osascript).
18
21
  Exit codes: 0 converted, 1 empty clipboard, 2 conversion failed.
19
22
  `;
@@ -42,14 +45,22 @@ function readClipboard() {
42
45
  ObjC.import("AppKit");
43
46
  var pb = $.NSPasteboard.generalPasteboard;
44
47
  var types = ObjC.deepUnwrap(pb.types);
48
+ var result;
45
49
  if (types.indexOf("public.html") !== -1) {
46
50
  var data = pb.dataForType("public.html");
47
- var str = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);
48
- JSON.stringify({ type: "html", content: ObjC.unwrap(str) || "" });
49
- } else {
51
+ if (!data.isNil()) {
52
+ var str = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);
53
+ var content = !str.isNil() ? ObjC.unwrap(str) : "";
54
+ if (content && content.trim().length > 0) {
55
+ result = { type: "html", content: content };
56
+ }
57
+ }
58
+ }
59
+ if (!result) {
50
60
  var plain = ObjC.unwrap(pb.stringForType("public.utf8-plain-text"));
51
- JSON.stringify({ type: "text", content: plain || "" });
61
+ result = { type: "text", content: plain || "" };
52
62
  }
63
+ JSON.stringify(result);
53
64
  `;
54
65
  const result = spawnSync('osascript', ['-l', 'JavaScript', '-e', script], {
55
66
  encoding: 'utf8',
@@ -87,6 +98,7 @@ var htmlData = str.dataUsingEncoding($.NSUTF8StringEncoding);
87
98
  var pb = $.NSPasteboard.generalPasteboard;
88
99
  pb.clearContents;
89
100
  pb.setDataForType(htmlData, "public.html");
101
+ pb.setStringForType(str, "public.utf8-plain-text");
90
102
  `;
91
103
  try {
92
104
  const result = spawnSync('osascript', ['-l', 'JavaScript', '-e', script], { encoding: 'utf8' });
@@ -126,6 +138,12 @@ function isEntryPoint() {
126
138
  if (isEntryPoint()) {
127
139
  const args = process.argv.slice(2);
128
140
 
141
+ // Subcommands dispatch before any clipboard code, so they run off macOS
142
+ if (args[0] === 'excalidraw') {
143
+ const { runExcalidraw } = await import('./excalidraw.js');
144
+ process.exit(await runExcalidraw(args.slice(1), { stdout: process.stdout, stderr: process.stderr }));
145
+ }
146
+
129
147
  if (args.includes('--help') || args.includes('-h')) {
130
148
  process.stdout.write(HELP);
131
149
  process.exit(0);
@@ -146,16 +164,22 @@ if (isEntryPoint()) {
146
164
  const { convert, convertMdToHtml } = await loadConverters();
147
165
  const clipboard = readClipboard();
148
166
  if (!clipboard.content || !clipboard.content.trim()) {
149
- process.exit(1); // no convertible content
167
+ console.error('c2m: empty clipboard');
168
+ process.exit(1);
150
169
  }
151
170
  const direction = detectDirection(clipboard.type, forceToMd, forceToHtml);
152
171
  if (direction === 'to-md') {
153
- writeTextToClipboard(convert(clipboard.content));
172
+ const md = convert(clipboard.content);
173
+ console.error(`c2m: ${clipboard.type} → md (${md.length} chars)`);
174
+ writeTextToClipboard(md);
154
175
  } else {
155
- writeHtmlToClipboard(convertMdToHtml(clipboard.content));
176
+ const html = convertMdToHtml(clipboard.content);
177
+ console.error(`c2m: ${clipboard.type} → html (${html.length} chars)`);
178
+ writeHtmlToClipboard(html);
156
179
  }
157
180
  process.exit(0);
158
- } catch {
181
+ } catch (e) {
182
+ console.error(`c2m: ${e.message}`);
159
183
  process.exit(2);
160
184
  }
161
185
  }
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ // c2m-diagrams: Excalidraw share links <-> Mermaid, for agents.
3
+ // Runs anywhere Node 20+ runs; no clipboard, no browser.
4
+ //
5
+ // stdout carries only the primary result (Markdown, Mermaid or the new link);
6
+ // diagnostics go to stderr; any failure exits non-zero.
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import {
12
+ expandDiagramLinks, stripDiagramBlocks, loadScene, sceneToMermaid, editLink,
13
+ parseShareLink, normalizeScene,
14
+ } from '../src/diagrams/index.js';
15
+
16
+ const USAGE = `usage: c2m-diagrams <command> [options]
17
+
18
+ expand <file.md> [--write] add a Mermaid reading copy under every excalidraw.com link
19
+ strip <file.md> [--write] remove every generated block
20
+ show <url|file.excalidraw> print the Mermaid for one diagram
21
+ edit <url|file.excalidraw> (--ops '<json>' | --ops-file <path>)
22
+ [--show-mermaid] [--out file.excalidraw] [--no-upload]
23
+ apply edit ops, upload, print the new link
24
+ (--no-upload prints the resulting Mermaid instead)
25
+
26
+ ops: [{"op":"rename","node","label"}, {"op":"add","id","label","near","side"?},
27
+ {"op":"connect","from","to","label"?,"dashed"?}, {"op":"disconnect","from","to"},
28
+ {"op":"relabel-edge","from","to","label"}, {"op":"remove","node"}]
29
+ `;
30
+
31
+ // Test hook: a directory standing in for json.excalidraw.com. GET reads
32
+ // <dir>/<id>, POST writes a new file. Never set this outside tests.
33
+ function fileBackendFetch(dir) {
34
+ return async function (url, init) {
35
+ var method = ((init && init.method) || 'GET').toUpperCase();
36
+ var respond = function (status, bytes) {
37
+ return {
38
+ ok: status >= 200 && status < 300,
39
+ status: status,
40
+ json: async function () { return JSON.parse(Buffer.from(bytes).toString('utf8')); },
41
+ arrayBuffer: async function () { var b = Buffer.from(bytes); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); },
42
+ };
43
+ };
44
+ if (method === 'POST') {
45
+ var id = 'local' + fs.readdirSync(dir).length.toString().padStart(4, '0');
46
+ fs.writeFileSync(path.join(dir, id), Buffer.from(init.body));
47
+ return respond(200, Buffer.from(JSON.stringify({ id: id })));
48
+ }
49
+ var file = path.join(dir, url.split('/').pop());
50
+ if (!fs.existsSync(file)) return respond(404, Buffer.from('{}'));
51
+ return respond(200, fs.readFileSync(file));
52
+ };
53
+ }
54
+
55
+ function parseArgs(argv) {
56
+ var args = { _: [] };
57
+ for (var i = 0; i < argv.length; i++) {
58
+ var a = argv[i];
59
+ if (a === '--write' || a === '--show-mermaid' || a === '--no-upload' || a === '--help' || a === '-h') {
60
+ args[a.replace(/^-+/, '')] = true;
61
+ } else if (a === '--ops' || a === '--ops-file' || a === '--out') {
62
+ if (i + 1 >= argv.length) throw new Error(a + ' needs a value');
63
+ args[a.replace(/^-+/, '')] = argv[++i];
64
+ } else if (a.startsWith('--')) {
65
+ throw new Error('unknown option ' + a);
66
+ } else {
67
+ args._.push(a);
68
+ }
69
+ }
70
+ return args;
71
+ }
72
+
73
+ async function readSource(target, fetchImpl) {
74
+ if (parseShareLink(target)) return { scene: await loadScene(target, { fetch: fetchImpl }), url: parseShareLink(target).url };
75
+ if (!fs.existsSync(target)) throw new Error('not a share link or an existing file: ' + target);
76
+ return { scene: normalizeScene(JSON.parse(fs.readFileSync(target, 'utf8'))), url: null };
77
+ }
78
+
79
+ export async function main(argv, io) {
80
+ var stdout = io.stdout, stderr = io.stderr;
81
+ var fetchImpl = process.env.C2M_DIAGRAMS_FAKE_BACKEND ? fileBackendFetch(process.env.C2M_DIAGRAMS_FAKE_BACKEND) : globalThis.fetch;
82
+ var args = parseArgs(argv);
83
+ var cmd = args._[0];
84
+ var target = args._[1];
85
+ if (args.help || !cmd) { (args.help ? stdout : stderr).write(USAGE); return args.help ? 0 : 2; }
86
+ if (!target) throw new Error(cmd + ' needs a target\n\n' + USAGE);
87
+
88
+ if (cmd === 'expand' || cmd === 'strip') {
89
+ var md = fs.readFileSync(target, 'utf8');
90
+ var out;
91
+ if (cmd === 'strip') {
92
+ out = stripDiagramBlocks(md);
93
+ } else {
94
+ var report = {};
95
+ out = await expandDiagramLinks(md, {
96
+ loadScene: function (url) { return loadScene(url, { fetch: fetchImpl }); },
97
+ onProgress: function (p) { if (p.total) stderr.write('expanding ' + p.done + ' of ' + p.total + ' diagrams\n'); },
98
+ report: report,
99
+ });
100
+ stderr.write('expanded ' + (report.total - report.failed) + ' of ' + report.total + ' diagrams' +
101
+ (report.failed ? ', ' + report.failed + ' failed' : '') + (report.outline ? ', ' + report.outline + ' as outline' : '') + '\n');
102
+ }
103
+ if (args.write) fs.writeFileSync(target, out); else stdout.write(out);
104
+ return cmd === 'expand' && report.failed ? 1 : 0;
105
+ }
106
+
107
+ if (cmd === 'show') {
108
+ var src = await readSource(target, fetchImpl);
109
+ var result = sceneToMermaid(src.scene, { sourceUrl: src.url || path.basename(target) });
110
+ result.warnings.forEach(function (w) { stderr.write('warning: ' + w + '\n'); });
111
+ stdout.write(result.text + '\n');
112
+ return 0;
113
+ }
114
+
115
+ if (cmd === 'edit') {
116
+ var opsText = args.ops != null ? args.ops : args['ops-file'] ? fs.readFileSync(args['ops-file'], 'utf8') : null;
117
+ if (opsText == null) throw new Error('edit needs --ops or --ops-file');
118
+ var ops;
119
+ try { ops = JSON.parse(opsText); } catch (e) { throw new Error('ops are not valid JSON: ' + e.message); }
120
+ var source = parseShareLink(target) ? target : (await readSource(target, fetchImpl)).scene;
121
+ var edited = await editLink(source, ops, { fetch: fetchImpl, upload: !args['no-upload'] });
122
+ if (edited.scene.elements.some(function (el) { return el.type === 'image' && !el.isDeleted; })) {
123
+ stderr.write('warning: embedded images do not carry over to a new share link; excalidraw.com will show placeholders until they are re-inserted (docs/traps/EDITED_LINK_LOSES_IMAGES.md)\n');
124
+ }
125
+ edited.report.forEach(function (line) { stderr.write(line + '\n'); });
126
+ if (args.out) fs.writeFileSync(args.out, JSON.stringify(edited.scene, null, 2) + '\n');
127
+ if (args['show-mermaid']) stderr.write(edited.mermaid + '\n');
128
+ stdout.write((args['no-upload'] ? edited.mermaid : edited.url) + '\n');
129
+ return 0;
130
+ }
131
+
132
+ throw new Error('unknown command "' + cmd + '"\n\n' + USAGE);
133
+ }
134
+
135
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) {
136
+ main(process.argv.slice(2), { stdout: process.stdout, stderr: process.stderr }).then(function (code) {
137
+ process.exitCode = code;
138
+ }, function (err) {
139
+ process.stderr.write('error: ' + (err && err.message ? err.message : err) + '\n');
140
+ process.exitCode = 1;
141
+ });
142
+ }
@@ -0,0 +1,167 @@
1
+ // `c2m excalidraw`: JSON diagram description -> excalidraw.com share link,
2
+ // Mermaid preview and layout warnings. No clipboard, runs anywhere Node 20+ runs.
3
+ //
4
+ // The help text below is the agent's whole manual for this command; keep it in
5
+ // step with src/diagrams/skeleton.js.
6
+
7
+ import { readFileSync } from 'fs';
8
+ import { buildSkeleton } from '../src/diagrams/skeleton.js';
9
+ import { saveScene } from '../src/diagrams/share-link.js';
10
+
11
+ export const EXCALIDRAW_HELP = `c2m excalidraw - turn a JSON diagram description into an excalidraw.com share link
12
+
13
+ Usage:
14
+ c2m excalidraw <file.json> read the diagram from a file
15
+ c2m excalidraw - read the diagram from stdin
16
+ c2m excalidraw --no-upload ... check only: print preview and warnings, no link
17
+ c2m excalidraw --help show this help
18
+
19
+ OUTPUT (stdout, in this order)
20
+ line 1 https://excalidraw.com/#json=<id>,<key> (omitted with --no-upload)
21
+ then a \`\`\`mermaid block: the structure you drew (nodes, arrows, labels)
22
+ then zero or more lines starting "warning: "
23
+ Errors go to stderr with exit code 1 and no link is printed. Warnings never
24
+ block the link; decide whether each one matters.
25
+
26
+ LOOP
27
+ 1. Write the diagram JSON to a file.
28
+ 2. Run: c2m excalidraw diagram.json --no-upload
29
+ 3. Read the preview: is every box, arrow and label what you meant?
30
+ Read the warnings: overlaps, labels that do not fit, loose arrows.
31
+ 4. Fix the JSON and rerun until the preview is right and warnings are gone.
32
+ 5. Run without --no-upload and paste the link into the document.
33
+ Every upload makes a new link; old links keep working. The encryption key
34
+ lives only in the link's # fragment, so excalidraw.com cannot read it.
35
+
36
+ INPUT: a JSON array of elements
37
+ [
38
+ {"id": "api", "type": "rectangle", "x": 0, "y": 0, "width": 160, "height": 70,
39
+ "label": {"text": "API"}, "backgroundColor": "#a5d8ff"},
40
+ {"id": "db", "type": "ellipse", "x": 300, "y": 0, "width": 200, "height": 80,
41
+ "label": {"text": "Postgres"}},
42
+ {"id": "ok", "type": "diamond", "x": 280, "y": 180, "width": 240, "height": 120,
43
+ "label": {"text": "Cached?"}},
44
+ {"id": "a1", "type": "arrow", "start": {"id": "api"}, "end": {"id": "db"},
45
+ "label": {"text": "reads"}},
46
+ {"id": "a2", "type": "arrow", "start": {"id": "db"}, "end": {"id": "ok"}},
47
+ {"id": "note", "type": "text", "x": 0, "y": 120, "text": "p95 < 200 ms", "fontSize": 16}
48
+ ]
49
+ Preview of the above:
50
+ flowchart LR
51
+ api[API]
52
+ db((Postgres))
53
+ ok{Cached?}
54
+ api -->|reads| db
55
+ db --> ok
56
+ %% note: p95 < 200 ms
57
+
58
+ ELEMENTS
59
+ rectangle, ellipse, diamond need id, x, y, width, height (x, y = top-left)
60
+ text needs id, x, y, text (free-standing annotation)
61
+ arrow, line need id; bind ends with "start"/"end"
62
+ Every element needs a unique "id"; it becomes the node id in the preview.
63
+
64
+ FIELDS (all optional unless noted above)
65
+ label {"text": "...", "fontSize": 20} or just "..." on shapes and
66
+ arrows; rendered as text centred in the shape / on the arrow.
67
+ Use "\\n" for line breaks; labels are not wrapped for you.
68
+ start, end {"id": "<shape id>"} on arrows and lines. The arrow stays
69
+ attached when someone drags the shape in excalidraw.com.
70
+ MCP style also works: "startBinding": {"elementId": "<id>"}.
71
+ points [[0,0],[dx,dy],...] relative to the arrow's x, y. Leave out
72
+ for a bound arrow: it is routed straight between the two
73
+ shapes' edges. Unbound without points: width/height or 100x0.
74
+ strokeColor "#1e1e1e" (default) or any CSS hex colour
75
+ backgroundColor "transparent" (default), e.g. "#a5d8ff" "#b2f2bb" "#ffec99"
76
+ fillStyle "solid" (default), "hachure", "cross-hatch"
77
+ strokeStyle "solid" (default), "dashed", "dotted"
78
+ fontSize default 20, on text elements (labels: label.fontSize)
79
+ startArrowhead, endArrowhead null, "arrow" (arrow end default), "triangle", "dot", "bar"
80
+ Any other Excalidraw element field is passed through unchanged.
81
+
82
+ SIZING AND SPACING (rules of thumb, font size 20)
83
+ - Text width ~ 14 px per character, line height 25 px.
84
+ - Rectangle: width >= 14 * longest line + 40, height >= 25 * lines + 40.
85
+ - Ellipse needs ~1.4x that, diamond ~2x, in both directions.
86
+ - Leave >= 120 px between shapes that an arrow joins, more if it has a label.
87
+ - A large rectangle drawn first and fully containing others works as a group
88
+ box: full containment is fine, partial overlap is warned about.
89
+ - Lay out on a grid: rows every ~150 px, columns every ~250 px.
90
+
91
+ PREVIEW
92
+ rectangle -> id[label] ellipse -> id((label)) diamond -> id{label}
93
+ An arrow bound at both ends -> edge with its label. A shape fully inside a
94
+ larger labelled shape -> subgraph. Free text -> "%% note:" line. The preview
95
+ shows structure only; Mermaid's layout is not your drawing's layout.
96
+
97
+ WARNINGS
98
+ overlap two shapes partly overlap
99
+ label does not fit the label's estimated size exceeds its shape minus padding
100
+ not attached an arrow end has no "start"/"end"
101
+ points at "<id>" an arrow end names an id that is not a shape here
102
+ duplicate id bindings attach to the first element with that id
103
+ dropped unsupported type, or an MCP-only command such as
104
+ cameraUpdate, delete, restoreCheckpoint
105
+
106
+ NOT SUPPORTED
107
+ images, frames, freedraw, Mermaid as input, editing an existing link (use
108
+ c2m-diagrams edit for that), writing .excalidraw files.
109
+ `;
110
+
111
+ function readInput(target, stdin) {
112
+ if (target === '-') return readFileSync(stdin === undefined ? 0 : stdin, 'utf8');
113
+ try {
114
+ return readFileSync(target, 'utf8');
115
+ } catch (e) {
116
+ throw new Error('cannot read ' + target + ': ' + e.message);
117
+ }
118
+ }
119
+
120
+ // Map upload failures onto something the agent can act on.
121
+ async function upload(scene, fetchImpl) {
122
+ try {
123
+ return await saveScene(scene, { fetch: fetchImpl });
124
+ } catch (e) {
125
+ var msg = e && e.message ? e.message : String(e);
126
+ if (/HTTP 413/.test(msg)) throw new Error('upload failed: scene too large for excalidraw.com; split the diagram into smaller ones');
127
+ if (/^upload failed/.test(msg)) throw new Error(msg);
128
+ throw new Error('upload failed: ' + msg + ' (network error? check connectivity to json.excalidraw.com)');
129
+ }
130
+ }
131
+
132
+ // Returns the exit code. `io.fetch` and `io.stdin` exist for tests.
133
+ export async function runExcalidraw(argv, io) {
134
+ var stdout = io.stdout, stderr = io.stderr;
135
+ var noUpload = false;
136
+ var targets = [];
137
+ for (var i = 0; i < argv.length; i++) {
138
+ var a = argv[i];
139
+ if (a === '--help' || a === '-h') { stdout.write(EXCALIDRAW_HELP); return 0; }
140
+ if (a === '--no-upload') noUpload = true;
141
+ else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
142
+ else targets.push(a);
143
+ }
144
+ if (targets.length !== 1) {
145
+ stderr.write('c2m excalidraw: expected one <file.json> or - for stdin. See c2m excalidraw --help.\n');
146
+ return 1;
147
+ }
148
+
149
+ try {
150
+ var text = readInput(targets[0], io.stdin);
151
+ var input;
152
+ try {
153
+ input = JSON.parse(text);
154
+ } catch (e) {
155
+ throw new Error('input is not valid JSON: ' + e.message);
156
+ }
157
+ var built = buildSkeleton(input);
158
+ var url = noUpload ? null : await upload(built.scene, io.fetch);
159
+ if (url) stdout.write(url + '\n');
160
+ stdout.write('```mermaid\n' + built.preview + '\n```\n');
161
+ built.warnings.forEach(function (w) { stdout.write('warning: ' + w + '\n'); });
162
+ return 0;
163
+ } catch (e) {
164
+ stderr.write('c2m excalidraw: ' + (e && e.message ? e.message : e) + '\n');
165
+ return 1;
166
+ }
167
+ }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@luutuankiet/clipboard2markdown",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Convert rich clipboard HTML from Jira, Confluence, Slack and Google apps into clean Markdown, and back.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "c2m": "./bin/cli.js"
7
+ "c2m": "bin/cli.js",
8
+ "c2m-diagrams": "bin/diagrams.js"
8
9
  },
9
10
  "files": [
10
11
  "bin",
@@ -0,0 +1,4 @@
1
+ // What the page's MD -> MD (diagrams) mode needs: read-only. Uploading lives
2
+ // only in the CLI (bin/diagrams.js).
3
+ export { loadScene } from './share-link.js';
4
+ export { expandDiagramLinks, stripDiagramBlocks } from './markdown.js';