@luutuankiet/clipboard2markdown 0.3.0 → 0.4.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.
Files changed (31) hide show
  1. package/README.md +9 -0
  2. package/bin/excalidraw.js +133 -12
  3. package/package.json +10 -3
  4. package/src/excalidraw-png.js +217 -0
  5. package/vendor/excalidraw/VERSION +1 -0
  6. package/vendor/excalidraw/excalidraw.bundle.mjs +3384 -0
  7. package/vendor/excalidraw/fonts/Assistant/Assistant-Bold.woff2 +0 -0
  8. package/vendor/excalidraw/fonts/Assistant/Assistant-Medium.woff2 +0 -0
  9. package/vendor/excalidraw/fonts/Assistant/Assistant-Regular.woff2 +0 -0
  10. package/vendor/excalidraw/fonts/Assistant/Assistant-SemiBold.woff2 +0 -0
  11. package/vendor/excalidraw/fonts/Cascadia/CascadiaCode-Regular.woff2 +0 -0
  12. package/vendor/excalidraw/fonts/ComicShanns/ComicShanns-Regular-279a7b317d12eb88de06167bd672b4b4.woff2 +0 -0
  13. package/vendor/excalidraw/fonts/ComicShanns/ComicShanns-Regular-6e066e8de2ac57ea9283adb9c24d7f0c.woff2 +0 -0
  14. package/vendor/excalidraw/fonts/ComicShanns/ComicShanns-Regular-dc6a8806fa96795d7b3be5026f989a17.woff2 +0 -0
  15. package/vendor/excalidraw/fonts/ComicShanns/ComicShanns-Regular-fcb0fc02dcbee4c9846b3e2508668039.woff2 +0 -0
  16. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-349fac6ca4700ffec595a7150a0d1e1d.woff2 +0 -0
  17. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-3f2c5db56cc93c5a6873b1361d730c16.woff2 +0 -0
  18. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-41b173a47b57366892116a575a43e2b6.woff2 +0 -0
  19. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-623ccf21b21ef6b3a0d87738f77eb071.woff2 +0 -0
  20. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-a88b72a24fb54c9f94e3b5fdaa7481c9.woff2 +0 -0
  21. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-b9dcf9d2e50a1eaf42fc664b50a3fd0d.woff2 +0 -0
  22. package/vendor/excalidraw/fonts/Excalifont/Excalifont-Regular-be310b9bcd4f1a43f571c46df7809174.woff2 +0 -0
  23. package/vendor/excalidraw/fonts/Liberation/LiberationSans-Regular.woff2 +0 -0
  24. package/vendor/excalidraw/fonts/Lilita/Lilita-Regular-i7dPIFZ9Zz-WBtRtedDbYE98RXi4EwSsbg.woff2 +0 -0
  25. package/vendor/excalidraw/fonts/Lilita/Lilita-Regular-i7dPIFZ9Zz-WBtRtedDbYEF8RXi4EwQ.woff2 +0 -0
  26. package/vendor/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTA3j6zbXWjgevT5.woff2 +0 -0
  27. package/vendor/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTQ3j6zbXWjgeg.woff2 +0 -0
  28. package/vendor/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTk3j6zbXWjgevT5.woff2 +0 -0
  29. package/vendor/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTo3j6zbXWjgevT5.woff2 +0 -0
  30. package/vendor/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTs3j6zbXWjgevT5.woff2 +0 -0
  31. package/vendor/excalidraw/fonts/Virgil/Virgil-Regular.woff2 +0 -0
package/README.md CHANGED
@@ -58,6 +58,15 @@ cat diagram.json | c2m excalidraw - # same, from stdin
58
58
 
59
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
60
 
61
+ **Diagrams as PNG** (`c2m excalidraw --png`, Node 20+, any OS): draws one or more diagrams locally, for pasting into a Google Doc. No browser is needed and the drawing makes no network request; the share link is uploaded as usual (skip it with `--no-upload`). Input is the JSON array above or a whole scene (`{"elements": [...]}`, such as a `.excalidraw` file); a scene's elements may use the same shorthand (`label`, `start`/`end`, arrows without `points`), and a scene without it is drawn as is.
62
+
63
+ ```bash
64
+ c2m excalidraw --png a.json b.json # PNGs in ~/.cache/c2m/renders/
65
+ c2m excalidraw --png out/ a.json # PNGs in out/
66
+ ```
67
+
68
+ Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most 25,000,000 pixels, Google Docs' limit) and `<name>.review.png` (at most 1000 px on the long side), then prints an image line `![<name>](attach:<name>)`, an `[Edit this diagram](<share link>)` line and the images map entry `"<name>": "@file64:/abs/path/<name>.png"`. Review agents should read the Mermaid preview first and open the review PNG only when the preview is not enough. Each run first deletes PNGs older than 24 hours in the default cache folder; a folder you name is never cleaned. CJK text is not drawn, because the 13 MB CJK font is left out of the package; such diagrams get a warning.
69
+
61
70
  ## Demo
62
71
 
63
72
  **Live:** https://luutuankiet.github.io/clipboard2markdown/
package/bin/excalidraw.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // The help text below is the agent's whole manual for this command; keep it in
5
5
  // step with src/diagrams/skeleton.js.
6
6
 
7
- import { readFileSync } from 'fs';
7
+ import { mkdirSync, readFileSync, writeFileSync } from 'fs';
8
+ import { basename, resolve } from 'path';
8
9
  import { buildSkeleton } from '../src/diagrams/skeleton.js';
9
10
  import { saveScene } from '../src/diagrams/share-link.js';
10
11
 
@@ -14,6 +15,8 @@ Usage:
14
15
  c2m excalidraw <file.json> read the diagram from a file
15
16
  c2m excalidraw - read the diagram from stdin
16
17
  c2m excalidraw --no-upload ... check only: print preview and warnings, no link
18
+ c2m excalidraw --png [<dir>] <file.json>...
19
+ also draw each diagram as PNG (see PNG below)
17
20
  c2m excalidraw --help show this help
18
21
 
19
22
  OUTPUT (stdout, in this order)
@@ -103,6 +106,32 @@ WARNINGS
103
106
  dropped unsupported type, or an MCP-only command such as
104
107
  cameraUpdate, delete, restoreCheckpoint
105
108
 
109
+ PNG (for pasting into a Google Doc)
110
+ c2m excalidraw --png [<dir>] a.json b.json ...
111
+ Draws each diagram locally (no browser; the drawing itself makes no network
112
+ request) and uploads it for its share link as above. Each input is either
113
+ the element array described here or a whole scene ({"elements": [...]},
114
+ e.g. a .excalidraw file). A scene's elements may use the same shorthand
115
+ (label, start/end, arrows without points); a scene without it is drawn and
116
+ uploaded as is. For each input <name>.json it writes:
117
+ <name>.png for the document: scale 3, lowered until the image
118
+ has at most 25,000,000 pixels (Google Docs' limit)
119
+ <name>.review.png for a quick look: at most 1000 px on the long side
120
+ <dir> defaults to ~/.cache/c2m/renders/ ($XDG_CACHE_HOME/c2m/renders/);
121
+ each run first deletes PNGs there older than 24 h. A <dir> you name is
122
+ never cleaned. --png=<dir> also works.
123
+ Then, per diagram:
124
+ ![<name>](attach:<name>) the image line for the document
125
+ [Edit this diagram](<share link>) omitted with --no-upload
126
+ "<name>": "@file64:/abs/path/<name>.png" the entry for the images map
127
+ review: /abs/path/<name>.review.png
128
+ warning: ... as above, if any
129
+ To check a drawing, read its Mermaid preview first (rerun without --png, or
130
+ c2m diagrams show <file> for a whole scene); open the review PNG only when
131
+ the preview cannot answer the question.
132
+ Text uses Excalidraw's fonts; CJK text is not drawn (the CJK font is not
133
+ shipped) and gets a warning.
134
+
106
135
  NOT SUPPORTED
107
136
  images, frames, freedraw, Mermaid as input, editing an existing link (use
108
137
  c2m diagrams edit for that), writing .excalidraw files.
@@ -129,32 +158,72 @@ async function upload(scene, fetchImpl) {
129
158
  }
130
159
  }
131
160
 
132
- // Returns the exit code. `io.fetch` and `io.stdin` exist for tests.
161
+ // The help's shorthand: `label`, `start`/`end`, or an arrow/line left without
162
+ // points for the builder to route. A real Excalidraw element has none of these.
163
+ function usesShorthand(el) {
164
+ if (!el || typeof el !== 'object') return false;
165
+ if ('label' in el || 'start' in el || 'end' in el) return true;
166
+ return (el.type === 'arrow' || el.type === 'line') && !Array.isArray(el.points);
167
+ }
168
+
169
+ // A whole scene ({elements: [...]}, as in a .excalidraw file) is drawn as is,
170
+ // unless it uses the shorthand: then it goes through the skeleton builder like
171
+ // an element array, keeping the scene's own appState and files.
172
+ function toScene(input) {
173
+ if (input && !Array.isArray(input) && Array.isArray(input.elements)) {
174
+ if (!input.elements.some(usesShorthand)) return { scene: input, preview: null, warnings: [] };
175
+ var built = buildSkeleton(input.elements);
176
+ if (input.appState) built.scene.appState = input.appState;
177
+ if (input.files) built.scene.files = input.files;
178
+ return built;
179
+ }
180
+ return buildSkeleton(input);
181
+ }
182
+
183
+ function parseJson(text) {
184
+ try {
185
+ return JSON.parse(text);
186
+ } catch (e) {
187
+ throw new Error('input is not valid JSON: ' + e.message);
188
+ }
189
+ }
190
+
191
+ function sceneName(target) {
192
+ return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw)$/i, '');
193
+ }
194
+
195
+ // `--png` takes an optional folder: the next argument is the folder unless it
196
+ // looks like an input (-, *.json, *.excalidraw) or an option.
197
+ function looksLikeInput(a) {
198
+ return a === '-' || a.startsWith('--') || /\.(json|excalidraw)$/i.test(a);
199
+ }
200
+
201
+ // Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
133
202
  export async function runExcalidraw(argv, io) {
134
203
  var stdout = io.stdout, stderr = io.stderr;
135
204
  var noUpload = false;
205
+ var png = false, pngDir = null;
136
206
  var targets = [];
137
207
  for (var i = 0; i < argv.length; i++) {
138
208
  var a = argv[i];
139
209
  if (a === '--help' || a === '-h') { stdout.write(EXCALIDRAW_HELP); return 0; }
140
210
  if (a === '--no-upload') noUpload = true;
211
+ else if (a === '--png') {
212
+ png = true;
213
+ if (i + 1 < argv.length && !looksLikeInput(argv[i + 1])) pngDir = argv[++i];
214
+ } else if (a.startsWith('--png=')) { png = true; pngDir = a.slice(6); }
141
215
  else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
142
216
  else targets.push(a);
143
217
  }
144
- if (targets.length !== 1) {
145
- stderr.write('c2m excalidraw: expected one <file.json> or - for stdin. See c2m excalidraw --help.\n');
218
+ if (png ? targets.length < 1 : targets.length !== 1) {
219
+ stderr.write('c2m excalidraw: expected ' + (png ? 'one or more <file.json>' : 'one <file.json>') +
220
+ ' or - for stdin. See c2m excalidraw --help.\n');
146
221
  return 1;
147
222
  }
148
223
 
149
224
  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);
225
+ if (png) return await runPng(targets, { dir: pngDir, noUpload: noUpload }, io);
226
+ var built = buildSkeleton(parseJson(readInput(targets[0], io.stdin)));
158
227
  var url = noUpload ? null : await upload(built.scene, io.fetch);
159
228
  if (url) stdout.write(url + '\n');
160
229
  stdout.write('```mermaid\n' + built.preview + '\n```\n');
@@ -165,3 +234,55 @@ export async function runExcalidraw(argv, io) {
165
234
  return 1;
166
235
  }
167
236
  }
237
+
238
+ async function runPng(targets, opts, io) {
239
+ var stdout = io.stdout;
240
+ var names = targets.map(sceneName);
241
+ var dup = names.find(function (n, k) { return names.indexOf(n) !== k; });
242
+ if (dup) throw new Error('two inputs are both named "' + dup + '"; their PNGs would overwrite each other');
243
+ if (targets.filter(function (t) { return t === '-'; }).length > 1) throw new Error('stdin (-) can be read only once');
244
+
245
+ // Read and build every input before drawing anything, so a typo in the
246
+ // last file costs no renders.
247
+ var items = targets.map(function (t, k) {
248
+ var built = toScene(parseJson(readInput(t, io.stdin)));
249
+ return { name: names[k], scene: built.scene, warnings: built.warnings };
250
+ });
251
+
252
+ var render = await import('../src/excalidraw-png.js');
253
+ var dir;
254
+ if (opts.dir) dir = resolve(opts.dir);
255
+ else {
256
+ dir = render.defaultRenderDir(io.env);
257
+ render.cleanRenderCache(dir);
258
+ }
259
+ mkdirSync(dir, { recursive: true });
260
+
261
+ var blocks = [];
262
+ for (var k = 0; k < items.length; k++) {
263
+ var it = items[k];
264
+ var out;
265
+ try {
266
+ out = await render.renderScene(it.scene);
267
+ } catch (e) {
268
+ throw new Error(it.name + ': ' + (e && e.message ? e.message : e));
269
+ }
270
+ var file = resolve(dir, it.name + '.png');
271
+ var reviewFile = resolve(dir, it.name + '.review.png');
272
+ writeFileSync(file, out.png);
273
+ writeFileSync(reviewFile, out.review);
274
+ var url = opts.noUpload ? null : await upload(it.scene, io.fetch);
275
+ var warnings = it.warnings.slice();
276
+ if (out.scale < 3) warnings.push('drawn at scale ' + out.scale + ' to stay under 25,000,000 pixels');
277
+ if (render.hasCjkText(it.scene)) warnings.push('CJK text is not drawn: the CJK font is not shipped');
278
+ var lines = ['![' + it.name + '](attach:' + it.name + ')'];
279
+ if (url) lines.push('[Edit this diagram](' + url + ')');
280
+ lines.push(JSON.stringify(it.name) + ': ' + JSON.stringify('@file64:' + file));
281
+ lines.push('review: ' + reviewFile);
282
+ warnings.forEach(function (w) { lines.push('warning: ' + w); });
283
+ blocks.push(lines.join('\n') + '\n');
284
+ }
285
+ stdout.write(blocks.join('\n'));
286
+ stdout.write('\nCheck a drawing by its Mermaid preview first (c2m excalidraw <file> --no-upload, or c2m diagrams show <file> for a whole scene); open the review PNG only if that is not enough.\n');
287
+ return 0;
288
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luutuankiet/clipboard2markdown",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {
@@ -11,6 +11,7 @@
11
11
  "files": [
12
12
  "bin",
13
13
  "src",
14
+ "vendor",
14
15
  "README.md",
15
16
  "LICENSE"
16
17
  ],
@@ -18,7 +19,9 @@
18
19
  "dev": "vite",
19
20
  "build": "vite build",
20
21
  "preview": "vite preview",
21
- "test": "vitest run"
22
+ "test": "vitest run",
23
+ "prepare": "node scripts/build-excalidraw-bundle.mjs",
24
+ "build:excalidraw": "node scripts/build-excalidraw-bundle.mjs"
22
25
  },
23
26
  "repository": {
24
27
  "type": "git",
@@ -47,15 +50,19 @@
47
50
  "node": ">=20.0.0"
48
51
  },
49
52
  "devDependencies": {
53
+ "@excalidraw/excalidraw": "0.18.1",
54
+ "esbuild": "^0.28.2",
50
55
  "mermaid": "^11.0.0",
51
56
  "vite": "^7.3.1",
52
57
  "vitest": "^4.0.18"
53
58
  },
54
59
  "dependencies": {
60
+ "@resvg/resvg-js": "^2.6.2",
55
61
  "jsdom": "^28.0.0",
56
62
  "marked": "^15.0.0",
57
63
  "pako": "^2.1.0",
58
64
  "turndown": "^7.2.2",
59
- "turndown-plugin-gfm": "^1.0.2"
65
+ "turndown-plugin-gfm": "^1.0.2",
66
+ "wawoff2": "^2.0.1"
60
67
  }
61
68
  }
@@ -0,0 +1,217 @@
1
+ // Excalidraw scene -> PNG for `c2m excalidraw --png`. Node only, no browser,
2
+ // no network: excalidraw's own exportToSvg runs under jsdom (bundled into
3
+ // vendor/excalidraw/ by scripts/build-excalidraw-bundle.mjs), then resvg turns
4
+ // the SVG into PNG with the fonts excalidraw embedded in it.
5
+
6
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from 'fs';
7
+ import { homedir, tmpdir } from 'os';
8
+ import { join } from 'path';
9
+ import { fileURLToPath, pathToFileURL } from 'url';
10
+
11
+ const VENDOR = fileURLToPath(new URL('../vendor/excalidraw/', import.meta.url));
12
+ // Font requests go to this origin and are answered from VENDOR/fonts; the
13
+ // .invalid TLD guarantees nothing could ever resolve it.
14
+ const ASSET_ORIGIN = 'http://c2m-fonts.invalid/';
15
+
16
+ export const MAX_PIXELS = 25000000; // Google Docs refuses larger images
17
+ export const DOC_SCALE = 3;
18
+ export const REVIEW_LONG_SIDE = 1000;
19
+ export const CACHE_MAX_AGE_MS = 24 * 3600 * 1000;
20
+
21
+ export function defaultRenderDir(env) {
22
+ env = env || process.env;
23
+ var base = env.XDG_CACHE_HOME || join(env.HOME || homedir(), '.cache');
24
+ return join(base, 'c2m', 'renders');
25
+ }
26
+
27
+ // Deletes PNG renders older than maxAge directly in `dir`. Only ever called on
28
+ // the default cache folder; never recurses, never touches anything but *.png.
29
+ export function cleanRenderCache(dir, options) {
30
+ var now = (options && options.now) || Date.now();
31
+ var maxAge = (options && options.maxAgeMs) || CACHE_MAX_AGE_MS;
32
+ var removed = [];
33
+ if (!existsSync(dir)) return removed;
34
+ readdirSync(dir).forEach(function (name) {
35
+ if (!/\.png$/i.test(name)) return;
36
+ var p = join(dir, name);
37
+ var st;
38
+ try { st = statSync(p); } catch { return; }
39
+ if (!st.isFile() || now - st.mtimeMs <= maxAge) return;
40
+ try { unlinkSync(p); removed.push(p); } catch { /* raced with another run */ }
41
+ });
42
+ return removed;
43
+ }
44
+
45
+ // Largest scale <= DOC_SCALE whose output stays within MAX_PIXELS, stepping
46
+ // down 0.01 at a time from the closed-form guess so rounding never overshoots.
47
+ export function pickScale(width, height) {
48
+ var s = Math.min(DOC_SCALE, Math.floor(Math.sqrt(MAX_PIXELS / (width * height)) * 100) / 100);
49
+ while (s > 0.01 && Math.ceil(width * s) * Math.ceil(height * s) > MAX_PIXELS) s = Math.round((s - 0.01) * 100) / 100;
50
+ return s;
51
+ }
52
+
53
+ // ------------------------------------------------------------ excalidraw ---
54
+
55
+ var exportToSvgPromise;
56
+
57
+ function installDom() {
58
+ var bundle = join(VENDOR, 'excalidraw.bundle.mjs');
59
+ if (!existsSync(bundle)) {
60
+ throw new Error('the Excalidraw renderer is missing (' + bundle + '); in a clone, run npm install');
61
+ }
62
+ return import('jsdom').then(function (m) {
63
+ var dom = new m.JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
64
+ var win = dom.window;
65
+ var g = globalThis;
66
+ ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'SVGElement', 'DOMParser',
67
+ 'XMLSerializer', 'getComputedStyle', 'devicePixelRatio', 'HTMLCanvasElement', 'Image', 'location',
68
+ 'requestAnimationFrame', 'cancelAnimationFrame', 'matchMedia'].forEach(function (k) {
69
+ if (win[k] === undefined) return;
70
+ try { Object.defineProperty(g, k, { value: win[k], configurable: true, writable: true }); } catch { /* read-only */ }
71
+ });
72
+
73
+ // jsdom has no canvas. Excalidraw probes a 2D context when its module
74
+ // loads; export uses the text sizes already stored in the scene, so a
75
+ // stand-in context is enough and produces the same SVG as a real one.
76
+ win.HTMLCanvasElement.prototype.getContext = function () {
77
+ var ctx = {
78
+ filter: 'none', font: '20px sans-serif', canvas: this,
79
+ measureText: function (t) {
80
+ var px = parseFloat((/(\d+(?:\.\d+)?)px/.exec(this.font) || [])[1] || 20);
81
+ return { width: t.length * px * 0.55, actualBoundingBoxAscent: px * 0.8, actualBoundingBoxDescent: px * 0.2, fontBoundingBoxAscent: px * 0.9, fontBoundingBoxDescent: px * 0.25 };
82
+ },
83
+ };
84
+ return new Proxy(ctx, {
85
+ get: function (o, k) { return k in o ? o[k] : function () {}; },
86
+ set: function (o, k, v) { o[k] = v; return true; },
87
+ });
88
+ };
89
+
90
+ // No CSS Font Loading API in jsdom either.
91
+ function FontFace(family, source, desc) { Object.assign(this, { family: family, source: source, status: 'loaded' }, desc); }
92
+ FontFace.prototype.load = function () { return Promise.resolve(this); };
93
+ g.FontFace = win.FontFace = FontFace;
94
+ var fonts = new Set();
95
+ Object.defineProperty(win.document, 'fonts', {
96
+ value: {
97
+ add: function (f) { fonts.add(f); }, delete: function (f) { return fonts.delete(f); },
98
+ has: function (f) { return fonts.has(f); }, check: function () { return true; },
99
+ load: function () { return Promise.resolve([]); }, ready: Promise.resolve(),
100
+ forEach: function (cb) { fonts.forEach(cb); }, [Symbol.iterator]: function () { return fonts[Symbol.iterator](); },
101
+ addEventListener: function () {}, removeEventListener: function () {},
102
+ },
103
+ });
104
+
105
+ // Excalidraw fetches the fonts it embeds from its asset path; answer those
106
+ // from the vendored copies. Everything else goes to the real fetch (the
107
+ // only other request during export is a data: URL for the subsetter).
108
+ var realFetch = g.fetch;
109
+ g.fetch = win.fetch = function (url, init) {
110
+ var s = String(url && url.url ? url.url : url);
111
+ if (s.startsWith(ASSET_ORIGIN)) {
112
+ var rel = decodeURIComponent(s.slice(ASSET_ORIGIN.length).split(/[?#]/)[0]);
113
+ var file = join(VENDOR, rel);
114
+ if (!file.startsWith(VENDOR) || !existsSync(file)) return Promise.resolve(new Response(null, { status: 404 }));
115
+ return Promise.resolve(new Response(readFileSync(file), { headers: { 'content-type': 'font/woff2' } }));
116
+ }
117
+ // A font the vendored copy lacks (Xiaolai, CJK) makes excalidraw retry
118
+ // on a public CDN; answer that locally too so no request leaves.
119
+ if (/\/fonts\/[^/]+\/[^/]+\.woff2(?:$|[?#])/.test(s)) return Promise.resolve(new Response(null, { status: 404 }));
120
+ return realFetch(url, init);
121
+ };
122
+ win.EXCALIDRAW_ASSET_PATH = ASSET_ORIGIN;
123
+ return import(pathToFileURL(bundle).href);
124
+ }).then(function (m) { return m.exportToSvg; });
125
+ }
126
+
127
+ export async function sceneToSvg(scene) {
128
+ if (!exportToSvgPromise) exportToSvgPromise = installDom();
129
+ var exportToSvg = await exportToSvgPromise;
130
+ var elements = (scene.elements || []).filter(function (e) { return !e.isDeleted; });
131
+ if (!elements.length) throw new Error('the scene has no elements to draw');
132
+ // Excalidraw reports the missing CJK font on console.error; the caller gets
133
+ // one warning from hasCjkText instead.
134
+ var consoleError = console.error;
135
+ console.error = function (first) {
136
+ if (typeof first === 'string' && /^Failed to fetch font family/.test(first)) return;
137
+ consoleError.apply(console, arguments);
138
+ };
139
+ try {
140
+ var svg = await exportToSvg({
141
+ elements: elements,
142
+ appState: Object.assign({}, scene.appState, { exportBackground: true, viewBackgroundColor: '#ffffff' }),
143
+ files: scene.files || {},
144
+ });
145
+ return svg.outerHTML;
146
+ } finally {
147
+ console.error = consoleError;
148
+ }
149
+ }
150
+
151
+ // CJK text needs Xiaolai, which the package leaves out (13 MB); it renders blank.
152
+ export function hasCjkText(scene) {
153
+ return (scene.elements || []).some(function (e) {
154
+ return !e.isDeleted && e.type === 'text' && /[⺀-鿿가-힯豈-﫿＀-￯]/.test(e.text || '');
155
+ });
156
+ }
157
+
158
+ // ------------------------------------------------------------------ resvg ---
159
+
160
+ // resvg ignores @font-face, and resvg-js 2.6.2 silently ignores fontBuffers, so
161
+ // the woff2 fonts excalidraw embedded are decoded to TTF files and passed as
162
+ // fontFiles. With system fonts off, a glyph no Excalidraw font has is dropped
163
+ // instead of switching the whole label to a system font.
164
+ async function extractFonts(svgText, dir) {
165
+ var wawoff2 = (await import('wawoff2')).default;
166
+ var files = [];
167
+ var re = /url\(data:font\/woff2;base64,([A-Za-z0-9+/=]+)\)/g;
168
+ var m;
169
+ while ((m = re.exec(svgText))) {
170
+ var f = join(dir, files.length + '.ttf');
171
+ writeFileSync(f, Buffer.from(await wawoff2.decompress(Buffer.from(m[1], 'base64'))));
172
+ files.push(f);
173
+ }
174
+ return files;
175
+ }
176
+
177
+ // Returns { png, review, width, height, scale, reviewWidth, reviewHeight }.
178
+ export async function svgToPngs(svgText) {
179
+ var { Resvg } = await import('@resvg/resvg-js');
180
+ var dir = mkdtempSync(join(tmpdir(), 'c2m-fonts-'));
181
+ try {
182
+ var fontFiles = await extractFonts(svgText, dir);
183
+ if (/<text[\s>]/.test(svgText) && !fontFiles.length) {
184
+ // Without this check the text would quietly come out in a fallback font.
185
+ throw new Error('no fonts were embedded in the SVG, text would render in the wrong font');
186
+ }
187
+ var font = { fontFiles: fontFiles, loadSystemFonts: false, defaultFontFamily: 'Excalifont' };
188
+ var render = function (fitTo) {
189
+ return new Resvg(svgText, { fitTo: fitTo, background: '#ffffff', font: font }).render();
190
+ };
191
+ var probe = new Resvg(svgText, { font: font });
192
+ var w = probe.width, h = probe.height;
193
+
194
+ var scale = pickScale(w, h);
195
+ var doc = render({ mode: 'zoom', value: scale });
196
+ while (doc.width * doc.height > MAX_PIXELS && scale > 0.01) {
197
+ scale = Math.round((scale - 0.01) * 100) / 100;
198
+ doc = render({ mode: 'zoom', value: scale });
199
+ }
200
+
201
+ var long = Math.max(w, h);
202
+ var reviewLong = Math.min(REVIEW_LONG_SIDE, Math.round(long * 2));
203
+ var review = render(w >= h ? { mode: 'width', value: reviewLong } : { mode: 'height', value: reviewLong });
204
+
205
+ return {
206
+ png: doc.asPng(), width: doc.width, height: doc.height, scale: scale,
207
+ review: review.asPng(), reviewWidth: review.width, reviewHeight: review.height,
208
+ fonts: fontFiles.length,
209
+ };
210
+ } finally {
211
+ rmSync(dir, { recursive: true, force: true });
212
+ }
213
+ }
214
+
215
+ export async function renderScene(scene) {
216
+ return svgToPngs(await sceneToSvg(scene));
217
+ }
@@ -0,0 +1 @@
1
+ 0.18.1