@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.
@@ -0,0 +1,179 @@
1
+ // Excalidraw share links: parse, download + decrypt, encrypt + upload.
2
+ //
3
+ // Wire format mirrors upstream excalidraw `compressData` / `encryption`:
4
+ // concatBuffers(...bufs) = uint32BE(1) + for each buf: uint32BE(len) + bytes
5
+ // inner = deflate(concatBuffers(utf8("null"), utf8(sceneJSON)))
6
+ // payload = concatBuffers(utf8(encodingMetadata), iv12, AES-GCM-128(key, iv, inner))
7
+ // The key lives only in the link fragment (`#json=<id>,<jwk.k>`), so the backend
8
+ // never sees plaintext.
9
+ //
10
+ // Platform-neutral on purpose: only `fetch`, WebCrypto and pako, so the page and
11
+ // the Node CLI share this file. `fetch` is always injectable for tests.
12
+
13
+ import { deflate, inflate } from 'pako';
14
+
15
+ export const DEFAULT_BACKEND_BASE = 'https://json.excalidraw.com/api/v2/';
16
+ const SHARE_ORIGIN = 'https://excalidraw.com/';
17
+ const CONCAT_BUFFERS_VERSION = 1;
18
+ const ENCODING_METADATA = { version: 2, compression: 'pako@1', encryption: 'AES-GCM' };
19
+
20
+ // Hosts whose `#json=` links are served by the public excalidraw.com backend.
21
+ // Self-hosted backends are out of scope: client-facing links stay on excalidraw.com.
22
+ const SHARE_HOSTS = { 'excalidraw.com': DEFAULT_BACKEND_BASE, 'www.excalidraw.com': DEFAULT_BACKEND_BASE };
23
+
24
+ // Matches a share link anywhere in text. Backslashes are allowed inside the id and
25
+ // key because Google's Markdown export escapes `_` and `-` as `\_` and `\-`.
26
+ export const SHARE_LINK_PATTERN = /https?:\/\/(?:www\.)?excalidraw\.com\/?#json=[A-Za-z0-9_\-\\]+,[A-Za-z0-9_\-\\]+/g;
27
+
28
+ export function parseShareLink(url) {
29
+ if (typeof url !== 'string') return null;
30
+ var cleaned = url.trim().replace(/\\([_\-#=,.\/:])/g, '$1').replace(/\\+$/, '');
31
+ var match = /^https?:\/\/((?:www\.)?excalidraw\.com)\/?#json=([A-Za-z0-9_-]+),([A-Za-z0-9_-]+)$/.exec(cleaned);
32
+ if (!match) return null;
33
+ var host = match[1].toLowerCase();
34
+ return {
35
+ id: match[2],
36
+ key: match[3],
37
+ backendBase: SHARE_HOSTS[host],
38
+ url: SHARE_ORIGIN + '#json=' + match[2] + ',' + match[3],
39
+ };
40
+ }
41
+
42
+ export function buildShareUrl(id, key) {
43
+ return SHARE_ORIGIN + '#json=' + id + ',' + key;
44
+ }
45
+
46
+ // ---------------------------------------------------------------- buffers ---
47
+
48
+ function concatBuffers() {
49
+ var buffers = Array.prototype.slice.call(arguments);
50
+ var total = 4 + buffers.reduce(function (sum, b) { return sum + 4 + b.byteLength; }, 0);
51
+ var out = new Uint8Array(total);
52
+ var view = new DataView(out.buffer);
53
+ view.setUint32(0, CONCAT_BUFFERS_VERSION);
54
+ var cursor = 4;
55
+ buffers.forEach(function (b) {
56
+ view.setUint32(cursor, b.byteLength);
57
+ cursor += 4;
58
+ out.set(b, cursor);
59
+ cursor += b.byteLength;
60
+ });
61
+ return out;
62
+ }
63
+
64
+ function splitBuffers(bytes) {
65
+ var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
66
+ var version = view.getUint32(0);
67
+ if (version !== CONCAT_BUFFERS_VERSION) {
68
+ throw new Error('unsupported buffer version ' + version);
69
+ }
70
+ var parts = [];
71
+ var cursor = 4;
72
+ while (cursor < bytes.byteLength) {
73
+ var len = view.getUint32(cursor);
74
+ cursor += 4;
75
+ parts.push(bytes.subarray(cursor, cursor + len));
76
+ cursor += len;
77
+ }
78
+ return parts;
79
+ }
80
+
81
+ var utf8 = {
82
+ encode: function (s) { return new TextEncoder().encode(s); },
83
+ decode: function (b) { return new TextDecoder().decode(b); },
84
+ };
85
+
86
+ // ----------------------------------------------------------------- crypto ---
87
+
88
+ function subtle() {
89
+ var c = globalThis.crypto;
90
+ if (!c || !c.subtle) throw new Error('WebCrypto (crypto.subtle) is not available');
91
+ return c.subtle;
92
+ }
93
+
94
+ function importKey(k, usage) {
95
+ return subtle().importKey('jwk', { kty: 'oct', k: k, alg: 'A128GCM', ext: true }, { name: 'AES-GCM', length: 128 }, false, [usage]);
96
+ }
97
+
98
+ async function generateKey() {
99
+ var key = await subtle().generateKey({ name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt']);
100
+ var jwk = await subtle().exportKey('jwk', key);
101
+ return jwk.k;
102
+ }
103
+
104
+ export async function decodePayload(bytes, k) {
105
+ var key = await importKey(k, 'decrypt');
106
+ var parts;
107
+ try {
108
+ parts = splitBuffers(bytes);
109
+ } catch (e) {
110
+ parts = null;
111
+ }
112
+ if (!parts || parts.length !== 3) {
113
+ // Pre-2021 links: whole body is AES-GCM with a zero IV, no compression.
114
+ var legacy = await subtle().decrypt({ name: 'AES-GCM', iv: new Uint8Array(12) }, key, bytes);
115
+ return JSON.parse(utf8.decode(new Uint8Array(legacy)));
116
+ }
117
+ var iv = parts[1];
118
+ var decrypted = await subtle().decrypt({ name: 'AES-GCM', iv: iv }, key, parts[2]);
119
+ var inner = splitBuffers(inflate(new Uint8Array(decrypted)));
120
+ return JSON.parse(utf8.decode(inner[1]));
121
+ }
122
+
123
+ export async function encodePayload(scene, k) {
124
+ var key = await importKey(k, 'encrypt');
125
+ var inner = concatBuffers(utf8.encode(JSON.stringify(null)), utf8.encode(JSON.stringify(scene)));
126
+ var iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
127
+ var encrypted = await subtle().encrypt({ name: 'AES-GCM', iv: iv }, key, deflate(inner));
128
+ return concatBuffers(utf8.encode(JSON.stringify(ENCODING_METADATA)), iv, new Uint8Array(encrypted));
129
+ }
130
+
131
+ // ---------------------------------------------------------------- network ---
132
+
133
+ function pickFetch(options) {
134
+ var f = (options && options.fetch) || globalThis.fetch;
135
+ if (typeof f !== 'function') throw new Error('no fetch implementation available');
136
+ return f;
137
+ }
138
+
139
+ // Read-only: one GET to the backend named by the link.
140
+ export async function loadScene(url, options) {
141
+ var link = parseShareLink(url);
142
+ if (!link) throw new Error('not an excalidraw.com share link');
143
+ var res = await pickFetch(options)(link.backendBase + link.id, { method: 'GET' });
144
+ if (!res.ok) {
145
+ throw new Error(res.status === 404 ? 'scene not found (HTTP 404)' : 'HTTP ' + res.status);
146
+ }
147
+ var bytes = new Uint8Array(await res.arrayBuffer());
148
+ var data;
149
+ try {
150
+ data = await decodePayload(bytes, link.key);
151
+ } catch (e) {
152
+ throw new Error('could not decrypt scene (wrong key or corrupt payload)');
153
+ }
154
+ return normalizeScene(data);
155
+ }
156
+
157
+ export function normalizeScene(data) {
158
+ return {
159
+ type: 'excalidraw',
160
+ version: 2,
161
+ source: (data && data.source) || 'https://excalidraw.com',
162
+ elements: (data && data.elements) || [],
163
+ appState: (data && data.appState) || {},
164
+ files: (data && data.files) || {},
165
+ };
166
+ }
167
+
168
+ // Uploads under a fresh key and returns the new share link. Share links are
169
+ // immutable: the old link keeps working.
170
+ export async function saveScene(scene, options) {
171
+ var base = (options && options.backendBase) || DEFAULT_BACKEND_BASE;
172
+ var k = await generateKey();
173
+ var body = await encodePayload(normalizeScene(scene), k);
174
+ var res = await pickFetch(options)(base + 'post/', { method: 'POST', body: body });
175
+ if (!res.ok) throw new Error('upload failed: HTTP ' + res.status);
176
+ var json = await res.json();
177
+ if (!json || !json.id) throw new Error('upload failed: ' + JSON.stringify(json));
178
+ return buildShareUrl(json.id, k);
179
+ }
@@ -0,0 +1,321 @@
1
+ // Short JSON diagram description -> full Excalidraw scene, a Mermaid preview
2
+ // and layout warnings. Pure: nothing here touches the network; the CLI uploads.
3
+ //
4
+ // The agent places shapes itself; this module fills Excalidraw's required
5
+ // fields, turns `label` into bound text, binds arrows both ways and sizes text,
6
+ // because excalidraw.com does not recompute text dimensions on load.
7
+
8
+ import { measureText, containerFactor, TEXT_METRICS } from './edit.js';
9
+ import { sceneToMermaid } from './scene-to-mermaid.js';
10
+ import { bounds } from './scene-model.js';
11
+
12
+ const SHAPES = new Set(['rectangle', 'ellipse', 'diamond']);
13
+ const LINEAR = new Set(['arrow', 'line']);
14
+ // Excalidraw MCP pseudo-elements: camera moves and checkpoint commands, not drawing.
15
+ const MCP_PSEUDO = new Set(['cameraUpdate', 'delete', 'restoreCheckpoint']);
16
+ // Skeleton-only fields that must not leak into the scene.
17
+ const SKELETON_FIELDS = ['label', 'start', 'end'];
18
+ const BINDING_GAP = 4;
19
+
20
+ function randomInt() { return Math.floor(Math.random() * 2 ** 31); }
21
+
22
+ function base(type, id) {
23
+ return {
24
+ id: id, type: type, x: 0, y: 0, width: 0, height: 0, angle: 0,
25
+ strokeColor: '#1e1e1e', backgroundColor: 'transparent', fillStyle: 'solid', strokeWidth: 2,
26
+ strokeStyle: 'solid', roughness: 1, opacity: 100, groupIds: [], frameId: null, roundness: null,
27
+ seed: randomInt(), version: 1, versionNonce: randomInt(), isDeleted: false, boundElements: null,
28
+ updated: Date.now(), link: null, locked: false,
29
+ };
30
+ }
31
+
32
+ function textElement(id, text, fontSize, extra) {
33
+ var size = measureText(text, fontSize);
34
+ return Object.assign(base('text', id), {
35
+ width: size.width, height: size.height, text: text, originalText: text, fontSize: fontSize,
36
+ fontFamily: 5, textAlign: 'left', verticalAlign: 'top', containerId: null, autoResize: true,
37
+ lineHeight: TEXT_METRICS.lineHeight,
38
+ }, extra);
39
+ }
40
+
41
+ function addBound(el, ref) {
42
+ el.boundElements = (el.boundElements || []).filter(function (b) { return b.id !== ref.id; }).concat([ref]);
43
+ }
44
+
45
+ function isNum(v) { return typeof v === 'number' && isFinite(v); }
46
+
47
+ function describe(raw, i) {
48
+ return 'element ' + i + (raw && raw.id ? ' ("' + raw.id + '")' : '');
49
+ }
50
+
51
+ // `start: {id}` and MCP-style `startBinding: {elementId}` mean the same thing.
52
+ function bindingTarget(raw, end) {
53
+ var short = raw[end];
54
+ var long = raw[end + 'Binding'];
55
+ if (short && short.id != null) return String(short.id);
56
+ if (long && long.elementId != null) return String(long.elementId);
57
+ return null;
58
+ }
59
+
60
+ function labelOf(raw) {
61
+ if (raw.label == null) return null;
62
+ if (typeof raw.label === 'string') return { text: raw.label };
63
+ if (typeof raw.label === 'object' && raw.label.text != null) return raw.label;
64
+ return null;
65
+ }
66
+
67
+ // Where the ray from a shape's centre towards `toward` leaves its bounding box.
68
+ function edgePoint(el, toward) {
69
+ var cx = el.x + el.width / 2, cy = el.y + el.height / 2;
70
+ var dx = toward[0] - cx, dy = toward[1] - cy;
71
+ if (!dx && !dy) return [cx, cy];
72
+ var sx = dx ? (el.width / 2) / Math.abs(dx) : Infinity;
73
+ var sy = dy ? (el.height / 2) / Math.abs(dy) : Infinity;
74
+ var s = Math.min(sx, sy);
75
+ return [cx + dx * s, cy + dy * s];
76
+ }
77
+
78
+ function centre(el) { return [el.x + el.width / 2, el.y + el.height / 2]; }
79
+
80
+ function arrowMidpoint(el) {
81
+ var pts = el.points;
82
+ var a = pts[Math.floor((pts.length - 1) / 2)], b = pts[Math.ceil((pts.length - 1) / 2)];
83
+ return [el.x + (a[0] + b[0]) / 2, el.y + (a[1] + b[1]) / 2];
84
+ }
85
+
86
+ function routeArrow(el, from, to) {
87
+ var start = edgePoint(from, centre(to));
88
+ var end = edgePoint(to, centre(from));
89
+ var len = Math.hypot(end[0] - start[0], end[1] - start[1]) || 1;
90
+ // Pull both ends back by the binding gap so the arrowhead does not sit on the stroke.
91
+ var ux = (end[0] - start[0]) / len, uy = (end[1] - start[1]) / len;
92
+ start = [start[0] + ux * BINDING_GAP, start[1] + uy * BINDING_GAP];
93
+ end = [end[0] - ux * BINDING_GAP, end[1] - uy * BINDING_GAP];
94
+ el.x = start[0];
95
+ el.y = start[1];
96
+ el.points = [[0, 0], [end[0] - start[0], end[1] - start[1]]];
97
+ }
98
+
99
+ function fitLinear(el) {
100
+ var xs = el.points.map(function (p) { return p[0]; }), ys = el.points.map(function (p) { return p[1]; });
101
+ el.width = Math.max.apply(null, xs) - Math.min.apply(null, xs);
102
+ el.height = Math.max.apply(null, ys) - Math.min.apply(null, ys);
103
+ }
104
+
105
+ // Throws on input that cannot become a scene at all; everything recoverable is
106
+ // a warning instead, so the agent still gets a link.
107
+ export function normalizeSkeleton(input) {
108
+ var list = Array.isArray(input) ? input : input && Array.isArray(input.elements) ? input.elements : null;
109
+ if (!list) throw new Error('input must be a JSON array of elements (or an object with an "elements" array)');
110
+
111
+ var warnings = [];
112
+ var kept = [];
113
+ list.forEach(function (raw, i) {
114
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(describe(raw, i) + ' is not an object');
115
+ if (MCP_PSEUDO.has(raw.type)) {
116
+ warnings.push('dropped ' + describe(raw, i) + ': "' + raw.type + '" is an Excalidraw MCP command, not a drawable element');
117
+ return;
118
+ }
119
+ if (!SHAPES.has(raw.type) && !LINEAR.has(raw.type) && raw.type !== 'text') {
120
+ warnings.push('dropped ' + describe(raw, i) + ': unsupported type "' + raw.type + '" (use rectangle, ellipse, diamond, text, arrow, line)');
121
+ return;
122
+ }
123
+ if (raw.id == null || raw.id === '') throw new Error(describe(raw, i) + ' needs an "id"');
124
+ if (SHAPES.has(raw.type) || raw.type === 'text') {
125
+ if (!isNum(raw.x) || !isNum(raw.y)) throw new Error(describe(raw, i) + ' needs numeric "x" and "y"');
126
+ }
127
+ if (SHAPES.has(raw.type) && (!isNum(raw.width) || !isNum(raw.height) || raw.width <= 0 || raw.height <= 0)) {
128
+ throw new Error(describe(raw, i) + ' needs positive numeric "width" and "height"');
129
+ }
130
+ if (raw.type === 'text' && (raw.text == null || raw.text === '')) throw new Error(describe(raw, i) + ' needs "text"');
131
+ kept.push({ raw: raw, index: i });
132
+ });
133
+
134
+ var elements = [];
135
+ var byId = new Map();
136
+ var labels = [];
137
+ var arrows = [];
138
+
139
+ kept.forEach(function (k) {
140
+ var raw = k.raw;
141
+ var id = String(raw.id);
142
+ var el = base(raw.type, id);
143
+ Object.keys(raw).forEach(function (key) {
144
+ if (SKELETON_FIELDS.indexOf(key) === -1) el[key] = raw[key];
145
+ });
146
+ el.id = id;
147
+ if (raw.type === 'rectangle' && raw.roundness === undefined) el.roundness = { type: 3 };
148
+ if (raw.type === 'diamond' && raw.roundness === undefined) el.roundness = { type: 2 };
149
+
150
+ if (raw.type === 'text') {
151
+ var fs = raw.fontSize || 20;
152
+ var t = textElement(id, String(raw.text), fs, {});
153
+ Object.keys(raw).forEach(function (key) { if (SKELETON_FIELDS.indexOf(key) === -1) t[key] = raw[key]; });
154
+ var size = measureText(t.text, fs);
155
+ t.id = id;
156
+ t.text = String(raw.text);
157
+ t.originalText = t.text;
158
+ t.fontSize = fs;
159
+ t.width = size.width;
160
+ t.height = size.height;
161
+ el = t;
162
+ }
163
+
164
+ if (LINEAR.has(raw.type)) {
165
+ el.x = isNum(raw.x) ? raw.x : 0;
166
+ el.y = isNum(raw.y) ? raw.y : 0;
167
+ el.startArrowhead = raw.startArrowhead !== undefined ? raw.startArrowhead : null;
168
+ el.endArrowhead = raw.endArrowhead !== undefined ? raw.endArrowhead : raw.type === 'arrow' ? 'arrow' : null;
169
+ el.roundness = raw.roundness !== undefined ? raw.roundness : { type: 2 };
170
+ el.lastCommittedPoint = null;
171
+ el.startBinding = null;
172
+ el.endBinding = null;
173
+ arrows.push({ el: el, raw: raw, index: k.index, start: bindingTarget(raw, 'start'), end: bindingTarget(raw, 'end') });
174
+ }
175
+
176
+ var label = labelOf(raw);
177
+ if (label && (SHAPES.has(raw.type) || LINEAR.has(raw.type))) {
178
+ labels.push({ container: el, text: String(label.text), fontSize: label.fontSize || raw.fontSize || 20, strokeColor: label.strokeColor || raw.strokeColor });
179
+ }
180
+ elements.push(el);
181
+ if (!byId.has(id)) byId.set(id, el);
182
+ });
183
+
184
+ // Arrows: resolve bindings, route between bound shapes when no points were given.
185
+ arrows.forEach(function (a) {
186
+ var el = a.el, raw = a.raw;
187
+ var from = a.start != null ? byId.get(a.start) : null;
188
+ var to = a.end != null ? byId.get(a.end) : null;
189
+ if (from && !SHAPES.has(from.type) && from.type !== 'text') from = null;
190
+ if (to && !SHAPES.has(to.type) && to.type !== 'text') to = null;
191
+
192
+ var hasPoints = Array.isArray(raw.points) && raw.points.length >= 2;
193
+ if (hasPoints) {
194
+ el.points = raw.points.map(function (p) { return [p[0], p[1]]; });
195
+ } else if (from && to && !isNum(raw.width) && !isNum(raw.height)) {
196
+ routeArrow(el, from, to);
197
+ } else {
198
+ el.points = [[0, 0], [isNum(raw.width) ? raw.width : 100, isNum(raw.height) ? raw.height : 0]];
199
+ }
200
+ fitLinear(el);
201
+
202
+ if (from) {
203
+ el.startBinding = { elementId: from.id, focus: 0, gap: BINDING_GAP };
204
+ addBound(from, { id: el.id, type: 'arrow' });
205
+ }
206
+ if (to) {
207
+ el.endBinding = { elementId: to.id, focus: 0, gap: BINDING_GAP };
208
+ addBound(to, { id: el.id, type: 'arrow' });
209
+ }
210
+ a.from = from;
211
+ a.to = to;
212
+ });
213
+
214
+ // Labels become bound text, centred in the shape or on the arrow's midpoint.
215
+ var usedIds = new Set(elements.map(function (e) { return e.id; }));
216
+ labels.forEach(function (l) {
217
+ var id = l.container.id + '-label';
218
+ for (var n = 2; usedIds.has(id); n++) id = l.container.id + '-label' + n;
219
+ usedIds.add(id);
220
+ var t = textElement(id, l.text, l.fontSize, { textAlign: 'center', verticalAlign: 'middle', containerId: l.container.id });
221
+ if (l.strokeColor) t.strokeColor = l.strokeColor;
222
+ var c = LINEAR.has(l.container.type) ? arrowMidpoint(l.container) : centre(l.container);
223
+ t.x = c[0] - t.width / 2;
224
+ t.y = c[1] - t.height / 2;
225
+ addBound(l.container, { id: id, type: 'text' });
226
+ elements.push(t);
227
+ });
228
+
229
+ var scene = {
230
+ type: 'excalidraw',
231
+ version: 2,
232
+ source: 'https://github.com/luutuankiet/clipboard2markdown',
233
+ elements: elements,
234
+ appState: { viewBackgroundColor: '#ffffff', gridSize: null },
235
+ files: {},
236
+ };
237
+ return { scene: scene, warnings: warnings, arrows: arrows, kept: kept };
238
+ }
239
+
240
+ // ------------------------------------------------------------------- lint ---
241
+
242
+ function box(el) {
243
+ if (el.type === 'text' || SHAPES.has(el.type)) return { x: el.x, y: el.y, w: el.width, h: el.height };
244
+ return bounds(el);
245
+ }
246
+
247
+ function overlapArea(a, b) {
248
+ var w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
249
+ var h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
250
+ return w > 0 && h > 0 ? w * h : 0;
251
+ }
252
+
253
+ function contains(outer, inner) {
254
+ return inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h;
255
+ }
256
+
257
+ export function lintSkeleton(normalized) {
258
+ var warnings = [];
259
+ var elements = normalized.scene.elements;
260
+
261
+ var seen = new Map();
262
+ normalized.kept.forEach(function (k) {
263
+ var id = String(k.raw.id);
264
+ if (seen.has(id)) warnings.push('duplicate id "' + id + '" (elements ' + seen.get(id) + ' and ' + k.index + '); bindings attach to the first one');
265
+ else seen.set(id, k.index);
266
+ });
267
+
268
+ var shapes = elements.filter(function (e) { return SHAPES.has(e.type) || (e.type === 'text' && !e.containerId); });
269
+ for (var i = 0; i < shapes.length; i++) {
270
+ for (var j = i + 1; j < shapes.length; j++) {
271
+ var a = box(shapes[i]), b = box(shapes[j]);
272
+ if (overlapArea(a, b) && !contains(a, b) && !contains(b, a)) {
273
+ warnings.push('"' + shapes[i].id + '" and "' + shapes[j].id + '" overlap; move them apart or nest one fully inside the other');
274
+ }
275
+ }
276
+ }
277
+
278
+ var byId = new Map();
279
+ elements.forEach(function (e) { if (!byId.has(e.id)) byId.set(e.id, e); });
280
+ elements.forEach(function (t) {
281
+ if (t.type !== 'text' || !t.containerId) return;
282
+ var c = byId.get(t.containerId);
283
+ if (!c || !SHAPES.has(c.type)) return;
284
+ var f = containerFactor(c.type);
285
+ var availW = c.width / f - 2 * TEXT_METRICS.padding;
286
+ var availH = c.height / f - 2 * TEXT_METRICS.padding;
287
+ if (t.width > availW || t.height > availH) {
288
+ var needW = Math.ceil((t.width + 2 * TEXT_METRICS.padding) * f);
289
+ var needH = Math.ceil((t.height + 2 * TEXT_METRICS.padding) * f);
290
+ warnings.push('label of "' + c.id + '" does not fit (' + c.width + 'x' + c.height + ', needs about ' +
291
+ Math.max(needW, c.width) + 'x' + Math.max(needH, c.height) + '); widen the shape, add a line break, or shorten the text');
292
+ }
293
+ });
294
+
295
+ normalized.arrows.forEach(function (a) {
296
+ ['start', 'end'].forEach(function (end) {
297
+ var target = a[end];
298
+ var bound = end === 'start' ? a.from : a.to;
299
+ if (target != null && !bound) {
300
+ warnings.push(a.el.type + ' "' + a.el.id + '" ' + end + ' points at "' + target + '", which is not a shape or text in this diagram');
301
+ } else if (target == null && a.el.type === 'arrow') {
302
+ warnings.push('arrow "' + a.el.id + '" ' + end + ' is not attached to a shape; add "' + end + '": {"id": "<shape id>"}');
303
+ }
304
+ });
305
+ });
306
+
307
+ return warnings;
308
+ }
309
+
310
+ // The one pure seam: skeleton in, everything but the upload out.
311
+ export function buildSkeleton(input) {
312
+ var normalized = normalizeSkeleton(input);
313
+ var lint = lintSkeleton(normalized);
314
+ var preview = sceneToMermaid(normalized.scene, { sourceUrl: 'c2m excalidraw' });
315
+ return {
316
+ scene: normalized.scene,
317
+ // The header line names a source link; there is none yet.
318
+ preview: preview.text.replace(/^%% generated from .*\n/, ''),
319
+ warnings: normalized.warnings.concat(lint, preview.warnings),
320
+ };
321
+ }