cursor-canvas-export 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,733 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import path4 from "node:path";
5
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
6
+
7
+ // src/convert.ts
8
+ import * as esbuild from "esbuild";
9
+ import { createRequire as createRequire2 } from "node:module";
10
+ import fs from "node:fs";
11
+ import path2 from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ // src/browser.ts
15
+ import { spawn } from "node:child_process";
16
+ import { createRequire } from "node:module";
17
+ import path from "node:path";
18
+ import { chromium } from "playwright";
19
+ var require2 = createRequire(import.meta.url);
20
+ var browserPromise;
21
+ var users = 0;
22
+ var hold = false;
23
+ function holdBrowserProcess() {
24
+ hold = true;
25
+ }
26
+ function acquireBrowser() {
27
+ users += 1;
28
+ if (!browserPromise) {
29
+ browserPromise = launchChromium().catch((error) => {
30
+ browserPromise = void 0;
31
+ throw error;
32
+ });
33
+ }
34
+ return browserPromise;
35
+ }
36
+ async function releaseBrowser() {
37
+ users = Math.max(0, users - 1);
38
+ if (users === 0 && !hold) await shutdown();
39
+ }
40
+ async function closeBrowser() {
41
+ hold = false;
42
+ if (users === 0) await shutdown();
43
+ }
44
+ async function shutdown() {
45
+ if (users > 0 || hold || !browserPromise) return;
46
+ const pending = browserPromise;
47
+ browserPromise = void 0;
48
+ const browser = await pending.catch(() => void 0);
49
+ if (users > 0 && browser) {
50
+ browserPromise = Promise.resolve(browser);
51
+ return;
52
+ }
53
+ await browser?.close().catch(() => {
54
+ });
55
+ }
56
+ async function launchChromium() {
57
+ try {
58
+ return await chromium.launch({ headless: true });
59
+ } catch (error) {
60
+ if (!isMissingBrowser(error)) throw error;
61
+ await installChromium();
62
+ return await chromium.launch({ headless: true });
63
+ }
64
+ }
65
+ function isMissingBrowser(error) {
66
+ const message = error instanceof Error ? error.message : String(error);
67
+ return message.includes("Executable doesn't exist") || message.includes("Please run");
68
+ }
69
+ function installChromium() {
70
+ const cli = path.join(path.dirname(require2.resolve("playwright/package.json")), "cli.js");
71
+ process.stderr.write("Downloading headless Chromium. No browser window will open.\n");
72
+ return new Promise((resolve, reject) => {
73
+ const child = spawn(process.execPath, [cli, "install", "chromium"], {
74
+ stdio: ["ignore", "pipe", "pipe"]
75
+ });
76
+ child.stdout.on("data", (chunk) => process.stderr.write(chunk));
77
+ child.stderr.on("data", (chunk) => process.stderr.write(chunk));
78
+ child.on("error", reject);
79
+ child.on("close", (code) => {
80
+ if (code === 0) resolve();
81
+ else reject(new Error(`playwright install chromium exited with code ${code ?? "unknown"}`));
82
+ });
83
+ });
84
+ }
85
+
86
+ // src/sdk/tokens.ts
87
+ var chartPalette = {
88
+ green: "#1F8A65E8",
89
+ darkGreen: "#0D855AE0",
90
+ lightGreen: "#52B896E0",
91
+ mintGreen: "#7DCAB0E0",
92
+ blue: "#2E79B5E0",
93
+ lightBlue: "#70B0D8E0",
94
+ indigo: "#5A6CC0F0",
95
+ lightIndigo: "#9AAADCE0",
96
+ purple: "#7B64B8F0",
97
+ lightPurple: "#AA98D8E0",
98
+ warmPink: "#C85898E0",
99
+ lightPink: "#E8A0C4E0",
100
+ brightOrange: "#F0A040E0",
101
+ deepOrange: "#C06028E0",
102
+ goldenYellow: "#E8C030E0",
103
+ darkAmber: "#C04848E0",
104
+ warmPeach: "#F0A088E0",
105
+ vibrantTeal: "#2A9A8AE0",
106
+ muted: "#8888A8E0",
107
+ neutralLine: "#888899D0"
108
+ };
109
+ var chartColorSequence = [
110
+ chartPalette.green,
111
+ chartPalette.blue,
112
+ chartPalette.purple,
113
+ chartPalette.brightOrange,
114
+ chartPalette.lightBlue,
115
+ chartPalette.warmPink,
116
+ chartPalette.goldenYellow,
117
+ chartPalette.vibrantTeal,
118
+ chartPalette.indigo,
119
+ chartPalette.deepOrange
120
+ ];
121
+ var categoryDark = {
122
+ gray: "#F0F0F099",
123
+ purple: "#7B64B8",
124
+ green: "#1F8A65",
125
+ yellow: "#E8C030",
126
+ cyan: "#2A9A8A",
127
+ pink: "#C85898",
128
+ blue: "#2E79B5",
129
+ orange: "#F0A040",
130
+ red: "#C04848"
131
+ };
132
+ var categoryLight = {
133
+ gray: "#14141499",
134
+ purple: "#6A54A8",
135
+ green: "#1A7A58",
136
+ yellow: "#8A6A10",
137
+ cyan: "#1E7A6C",
138
+ pink: "#A84880",
139
+ blue: "#2E79B5",
140
+ orange: "#C06028",
141
+ red: "#A83838"
142
+ };
143
+ function mix(base, percent) {
144
+ const alpha = Math.round(percent / 100 * 255).toString(16).padStart(2, "0");
145
+ return `${base}${alpha}`;
146
+ }
147
+ function palette(kind) {
148
+ const dark = kind === "dark";
149
+ const ink = dark ? "#F0F0F0" : "#141414";
150
+ const editor = dark ? "#181818" : "#FCFCFC";
151
+ const chrome = dark ? "#141414" : "#F3F3F3";
152
+ const accent = dark ? "#70B0D8" : "#2E79B5";
153
+ return {
154
+ foreground: ink,
155
+ foregroundSecondary: mix(ink, 74),
156
+ foregroundTertiary: mix(ink, 60),
157
+ foregroundQuaternary: mix(ink, 36),
158
+ editor,
159
+ chrome,
160
+ sidebar: chrome,
161
+ elevated: editor,
162
+ fillPrimary: mix(ink, 20),
163
+ fillSecondary: mix(ink, 14),
164
+ fillTertiary: mix(ink, 8),
165
+ fillQuaternary: mix(ink, 6),
166
+ strokePrimary: mix(ink, 20),
167
+ strokeSecondary: mix(ink, 12),
168
+ strokeTertiary: mix(ink, 8),
169
+ strokeFocused: accent,
170
+ accent,
171
+ buttonBackground: accent,
172
+ buttonForeground: dark ? "#141414" : "#FCFCFC",
173
+ buttonHoverBackground: dark ? "#8EC0E4" : "#24689F",
174
+ link: accent,
175
+ diffInsertedLine: dark ? "#1F8A652E" : "#1F8A6524",
176
+ diffRemovedLine: dark ? "#C048482E" : "#C0484824",
177
+ diffStripAdded: "#1F8A65",
178
+ diffStripRemoved: "#C04848"
179
+ };
180
+ }
181
+ function buildTheme(kind) {
182
+ const p = palette(kind);
183
+ const category = kind === "dark" ? categoryDark : categoryLight;
184
+ const tokens = {
185
+ bg: { editor: p.editor, chrome: p.chrome, elevated: p.elevated },
186
+ text: {
187
+ primary: p.foreground,
188
+ secondary: p.foregroundSecondary,
189
+ tertiary: p.foregroundTertiary,
190
+ quaternary: p.foregroundQuaternary,
191
+ link: p.link,
192
+ onAccent: p.buttonForeground
193
+ },
194
+ stroke: {
195
+ primary: p.strokePrimary,
196
+ secondary: p.strokeSecondary,
197
+ tertiary: p.strokeTertiary,
198
+ focused: p.strokeFocused
199
+ },
200
+ fill: {
201
+ primary: p.fillPrimary,
202
+ secondary: p.fillSecondary,
203
+ tertiary: p.fillTertiary,
204
+ quaternary: p.fillQuaternary
205
+ },
206
+ accent: {
207
+ primary: p.accent,
208
+ control: p.buttonBackground,
209
+ controlHover: p.buttonHoverBackground
210
+ },
211
+ diff: {
212
+ insertedLine: p.diffInsertedLine,
213
+ removedLine: p.diffRemovedLine,
214
+ stripAdded: p.diffStripAdded,
215
+ stripRemoved: p.diffStripRemoved
216
+ },
217
+ category
218
+ };
219
+ return {
220
+ kind,
221
+ ...tokens,
222
+ tokens,
223
+ palette: p,
224
+ category
225
+ };
226
+ }
227
+ var canvasPaletteDark = palette("dark");
228
+ var canvasPaletteLight = palette("light");
229
+ var canvasTokens = buildTheme("dark").tokens;
230
+ var canvasTokensLight = buildTheme("light").tokens;
231
+ var fontStack = '"Segoe UI Variable", "Segoe UI", system-ui, sans-serif';
232
+
233
+ // src/convert.ts
234
+ var require3 = createRequire2(import.meta.url);
235
+ var PDF_MAX_PX = 200 * 96;
236
+ function pdfTooLarge(width, height) {
237
+ return width > PDF_MAX_PX || height + 1 > PDF_MAX_PX;
238
+ }
239
+ function pdfLimitWarning(width, height) {
240
+ return `PDF skipped: page ${width}x${height}px exceeds Chromium's 200 inch limit.`;
241
+ }
242
+ function readState(input) {
243
+ const sidecar = input.replace(/\.canvas\.tsx$/, ".canvas.data.json");
244
+ if (!fs.existsSync(sidecar)) return {};
245
+ const parsed = JSON.parse(fs.readFileSync(sidecar, "utf8"));
246
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
247
+ return parsed;
248
+ }
249
+ return {};
250
+ }
251
+ function centerHtmlForBrowser(html) {
252
+ const head = html.lastIndexOf("</head>");
253
+ if (head === -1) return html;
254
+ return `${html.slice(0, head)}<style>#root{margin-left:auto;margin-right:auto}</style>${html.slice(head)}`;
255
+ }
256
+ function outputStem(out, input) {
257
+ if (!out) return input.replace(/\.canvas\.tsx$/, "");
258
+ const resolved = path2.resolve(out);
259
+ if (/\.(html|pdf)$/i.test(resolved)) return resolved.replace(/\.(html|pdf)$/i, "");
260
+ return resolved;
261
+ }
262
+ async function convert(options) {
263
+ const input = path2.resolve(options.input);
264
+ if (!fs.existsSync(input)) throw new Error(`Canvas file not found: ${input}`);
265
+ const theme = options.theme ?? "dark";
266
+ const width = options.width ?? 800;
267
+ const format = options.format ?? "both";
268
+ const tokens = buildTheme(theme);
269
+ const specifier = input.replaceAll("\\", "/");
270
+ const wrapper = [
271
+ 'import { createRoot } from "react-dom/client";',
272
+ 'import { setCanvasStateSeed, setExportTheme } from "cursor/canvas";',
273
+ `import Canvas from ${JSON.stringify(specifier)};`,
274
+ `setExportTheme(${JSON.stringify(theme)});`,
275
+ `setCanvasStateSeed(${JSON.stringify(readState(input))});`,
276
+ 'const root = document.getElementById("root");',
277
+ 'if (!root) throw new Error("Canvas root element was not found.");',
278
+ "createRoot(root).render(<Canvas />);",
279
+ ""
280
+ ].join("\n");
281
+ let built;
282
+ try {
283
+ built = await esbuild.build({
284
+ stdin: {
285
+ contents: wrapper,
286
+ resolveDir: path2.dirname(input),
287
+ sourcefile: "canvas-entry.tsx",
288
+ loader: "tsx"
289
+ },
290
+ bundle: true,
291
+ format: "iife",
292
+ platform: "browser",
293
+ write: false,
294
+ jsx: "automatic",
295
+ target: "es2022",
296
+ alias: { "cursor/canvas": sdkEntryPath() },
297
+ plugins: [reactFromPackage()],
298
+ define: { "process.env.NODE_ENV": '"production"' },
299
+ logLevel: "silent"
300
+ });
301
+ } catch (error) {
302
+ const formatted = formatEsbuildError(error);
303
+ if (formatted) throw new Error(formatted);
304
+ throw error;
305
+ }
306
+ const script = built.outputFiles?.[0]?.text?.replaceAll("</script", "<\\/script");
307
+ if (!script) throw new Error("Canvas build produced no code.");
308
+ const shell = `<!DOCTYPE html>
309
+ <html lang="ru">
310
+ <head>
311
+ <meta charset="utf-8" />
312
+ <meta name="viewport" content="width=${width}" />
313
+ <title>Canvas</title>
314
+ <style>
315
+ :root { color-scheme: ${theme}; }
316
+ html, body { margin: 0; padding: 0; background: ${tokens.bg.editor}; }
317
+ body { font-family: ${fontStack}; }
318
+ #root { width: ${width}px; box-sizing: border-box; padding: 24px 28px 32px; }
319
+ </style>
320
+ </head>
321
+ <body>
322
+ <div id="root"></div>
323
+ <script>${script}</script>
324
+ </body>
325
+ </html>`;
326
+ const browser = await acquireBrowser();
327
+ let page;
328
+ try {
329
+ page = await browser.newPage({ viewport: { width, height: 900 }, deviceScaleFactor: 1 });
330
+ const errors = [];
331
+ let settleRuntime = () => {
332
+ };
333
+ const runtimeFailure = new Promise((resolve, reject) => {
334
+ settleRuntime = (error) => error ? reject(error) : resolve();
335
+ });
336
+ void runtimeFailure.catch(() => {
337
+ });
338
+ const reportRuntime = (message) => {
339
+ errors.push(message);
340
+ settleRuntime(new Error(errors.join("\n")));
341
+ };
342
+ page.on("pageerror", (error) => reportRuntime(error.message));
343
+ page.on("console", (message) => {
344
+ if (message.type() === "error") reportRuntime(message.text());
345
+ });
346
+ try {
347
+ await Promise.race([
348
+ (async () => {
349
+ await page.setContent(shell, { waitUntil: "load" });
350
+ await page.waitForSelector("#root > *", { timeout: 15e3 });
351
+ await page.evaluate(async () => {
352
+ await document.fonts.ready;
353
+ await new Promise((resolve) => {
354
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
355
+ });
356
+ });
357
+ })(),
358
+ runtimeFailure
359
+ ]);
360
+ } catch (error) {
361
+ const message = error instanceof Error ? error.message : String(error);
362
+ const extra = errors.filter((entry) => !message.includes(entry));
363
+ throw new Error(extra.length > 0 ? `${message}
364
+ ${extra.join("\n")}` : message);
365
+ } finally {
366
+ settleRuntime();
367
+ }
368
+ if (errors.length > 0) throw new Error(errors.join("\n"));
369
+ await page.evaluate(() => {
370
+ const heading = document.querySelector("h1");
371
+ if (heading?.textContent) document.title = heading.textContent.trim();
372
+ document.querySelectorAll("script").forEach((node) => node.remove());
373
+ });
374
+ const size = await page.evaluate(() => ({
375
+ width: document.documentElement.scrollWidth,
376
+ height: document.documentElement.scrollHeight
377
+ }));
378
+ const warnings = [];
379
+ const wantsPdf = !options.preview && (format === "pdf" || format === "both");
380
+ const tooLarge = wantsPdf && pdfTooLarge(size.width, size.height);
381
+ if (!tooLarge) {
382
+ await page.setViewportSize({ width: size.width, height: Math.max(size.height, 1) });
383
+ }
384
+ const stem = outputStem(options.out, input);
385
+ const result = { width: size.width, height: size.height, warnings };
386
+ if (!options.preview) fs.mkdirSync(path2.dirname(stem), { recursive: true });
387
+ if (!options.preview && (format === "html" || format === "both")) {
388
+ const file = `${stem}.html`;
389
+ fs.writeFileSync(file, centerHtmlForBrowser(await page.content()), "utf8");
390
+ result.html = file;
391
+ }
392
+ if (options.preview) {
393
+ const limit = 1600;
394
+ result.previewClipped = size.height > limit;
395
+ result.preview = await page.screenshot(
396
+ size.height > limit ? { clip: { x: 0, y: 0, width: size.width, height: limit } } : { fullPage: true }
397
+ );
398
+ }
399
+ if (options.screenshot) {
400
+ const shot = path2.resolve(options.screenshot);
401
+ fs.mkdirSync(path2.dirname(shot), { recursive: true });
402
+ await page.screenshot({ path: shot, fullPage: true });
403
+ result.screenshot = shot;
404
+ }
405
+ if (wantsPdf && tooLarge) {
406
+ warnings.push(pdfLimitWarning(size.width, size.height));
407
+ if (format === "pdf") throw new Error(warnings[0]);
408
+ } else if (wantsPdf) {
409
+ const file = `${stem}.pdf`;
410
+ try {
411
+ await page.emulateMedia({ media: "screen" });
412
+ await page.pdf({
413
+ path: file,
414
+ width: `${size.width}px`,
415
+ height: `${size.height + 1}px`,
416
+ printBackground: true,
417
+ margin: { top: "0", right: "0", bottom: "0", left: "0" }
418
+ });
419
+ result.pdf = file;
420
+ } catch (error) {
421
+ fs.rmSync(file, { force: true });
422
+ const message = error instanceof Error ? error.message : String(error);
423
+ if (result.html) warnings.push(`PDF was not written: ${message}`);
424
+ else throw error;
425
+ }
426
+ }
427
+ return result;
428
+ } finally {
429
+ await page?.close().catch(() => {
430
+ });
431
+ await releaseBrowser();
432
+ }
433
+ }
434
+ function sdkEntryPath() {
435
+ const here = path2.dirname(fileURLToPath(import.meta.url));
436
+ const candidates = [
437
+ path2.join(here, "sdk", "index.tsx"),
438
+ path2.join(here, "../src/sdk/index.tsx")
439
+ ];
440
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
441
+ if (!found) throw new Error("Canvas SDK sources were not found in the package.");
442
+ return found;
443
+ }
444
+ function reactFromPackage() {
445
+ return {
446
+ name: "react-from-package",
447
+ setup(build2) {
448
+ build2.onResolve({ filter: /^react(-dom)?(\/|$)/ }, (args) => ({
449
+ path: require3.resolve(args.path)
450
+ }));
451
+ }
452
+ };
453
+ }
454
+ function formatEsbuildError(error) {
455
+ if (!error || typeof error !== "object" || !("errors" in error)) return void 0;
456
+ const errors = error.errors;
457
+ if (!Array.isArray(errors)) return void 0;
458
+ return errors.map((item) => {
459
+ const entry = item;
460
+ const loc = entry.location;
461
+ const where = loc?.file ? `${loc.file}:${loc.line ?? 1}:${loc.column ?? 0}` : "build";
462
+ return `${where}: ${entry.text ?? "build failed"}`;
463
+ }).join("\n");
464
+ }
465
+
466
+ // src/mcp.ts
467
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
468
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
469
+ import { z } from "zod";
470
+
471
+ // src/discover.ts
472
+ import fs2 from "node:fs";
473
+ import os from "node:os";
474
+ import path3 from "node:path";
475
+ function projectsRoot() {
476
+ return process.env.CANVAS_PROJECTS_DIR ?? path3.join(os.homedir(), ".cursor", "projects");
477
+ }
478
+ function listCanvases(workspace, root = projectsRoot()) {
479
+ if (!fs2.existsSync(root)) return [];
480
+ const needle = workspace ? slug(workspace) : "";
481
+ const hits = [];
482
+ for (const project of fs2.readdirSync(root)) {
483
+ if (needle && !slug(project).includes(needle) && !needle.includes(slug(project))) continue;
484
+ const dir = path3.join(root, project, "canvases");
485
+ if (!fs2.existsSync(dir)) continue;
486
+ for (const file of fs2.readdirSync(dir)) {
487
+ if (!file.endsWith(".canvas.tsx")) continue;
488
+ const full = path3.join(dir, file);
489
+ const stat = fs2.statSync(full);
490
+ if (!stat.isFile()) continue;
491
+ hits.push({
492
+ name: file.slice(0, -".canvas.tsx".length),
493
+ path: full,
494
+ project,
495
+ mtimeMs: stat.mtimeMs
496
+ });
497
+ }
498
+ }
499
+ hits.sort((a, b) => b.mtimeMs - a.mtimeMs);
500
+ return hits;
501
+ }
502
+ function resolveCanvas(query, root) {
503
+ const direct = path3.resolve(query);
504
+ if (fs2.existsSync(direct) && direct.endsWith(".canvas.tsx")) {
505
+ return { match: hitFromFile(direct), matches: [] };
506
+ }
507
+ if (query.includes("/") || query.includes("\\") || query.endsWith(".canvas.tsx")) {
508
+ return { matches: [] };
509
+ }
510
+ const all = listCanvases(void 0, root);
511
+ const exact = all.filter((hit) => hit.name === query);
512
+ if (exact.length === 1) return { match: exact[0], matches: [] };
513
+ if (exact.length > 1) return { matches: exact };
514
+ const partial = all.filter((hit) => hit.name.includes(query));
515
+ if (partial.length === 1) return { match: partial[0], matches: [] };
516
+ return { matches: partial };
517
+ }
518
+ function hitFromFile(file) {
519
+ const stat = fs2.statSync(file);
520
+ return {
521
+ name: path3.basename(file).slice(0, -".canvas.tsx".length),
522
+ path: file,
523
+ project: path3.basename(path3.dirname(path3.dirname(file))),
524
+ mtimeMs: stat.mtimeMs
525
+ };
526
+ }
527
+ function slug(value) {
528
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
529
+ }
530
+
531
+ // src/mcp.ts
532
+ var themeSchema = z.enum(["dark", "light"]).describe("Canvas theme. Defaults to dark.");
533
+ var widthSchema = z.number().int().min(320).optional().describe("Page width in pixels. Defaults to 800.");
534
+ function createServer() {
535
+ holdBrowserProcess();
536
+ const server = new McpServer({ name: "cursor-canvas-export", version: "0.1.0" });
537
+ server.registerTool(
538
+ "list_canvases",
539
+ {
540
+ title: "List canvases",
541
+ description: "Find Cursor canvas files (.canvas.tsx) under ~/.cursor/projects. Newest first. Pass workspace to keep only that project's canvases.",
542
+ inputSchema: {
543
+ workspace: z.string().optional().describe("Workspace path or name fragment. Omit to list every local canvas.")
544
+ }
545
+ },
546
+ async ({ workspace }) => {
547
+ const hits = listCanvases(workspace);
548
+ return text(
549
+ hits.length === 0 ? "No canvases found." : hits.map((hit) => `${hit.name} ${hit.path}`).join("\n")
550
+ );
551
+ }
552
+ );
553
+ server.registerTool(
554
+ "export_canvas",
555
+ {
556
+ title: "Export canvas",
557
+ description: "Render a Cursor canvas to HTML and/or a one-page PDF. Pass a full path or a canvas name. Files are written next to the canvas unless out is set. Returns output paths, page size, and warnings. The browser runs headless.",
558
+ inputSchema: {
559
+ canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
560
+ format: z.enum(["html", "pdf", "both"]).optional().describe("Defaults to both."),
561
+ theme: themeSchema.optional(),
562
+ width: widthSchema,
563
+ out: z.string().optional().describe("Output stem. Extension is ignored. Defaults to beside the canvas.")
564
+ }
565
+ },
566
+ async ({ canvas, format, theme, width, out }) => {
567
+ const resolved = resolveCanvas(canvas);
568
+ if (!resolved.match) return unresolvedCanvas(canvas, resolved.matches);
569
+ const result = await convert({
570
+ input: resolved.match.path,
571
+ out,
572
+ format: format ?? "both",
573
+ theme,
574
+ width
575
+ });
576
+ const lines = [
577
+ result.html ? `html: ${result.html}` : "",
578
+ result.pdf ? `pdf: ${result.pdf}` : "",
579
+ `page: ${result.width}x${result.height}px`,
580
+ ...result.warnings.map((warning) => `warning: ${warning}`)
581
+ ].filter(Boolean);
582
+ return text(lines.join("\n"));
583
+ }
584
+ );
585
+ server.registerTool(
586
+ "preview_canvas",
587
+ {
588
+ title: "Preview canvas",
589
+ description: "Render a canvas and return a PNG of the page so you can check layout before handing the file over. Tall pages are clipped to the top 1600px. Nothing is written next to the canvas.",
590
+ inputSchema: {
591
+ canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
592
+ theme: themeSchema.optional(),
593
+ width: widthSchema
594
+ }
595
+ },
596
+ async ({ canvas, theme, width }) => {
597
+ const resolved = resolveCanvas(canvas);
598
+ if (!resolved.match) return unresolvedCanvas(canvas, resolved.matches);
599
+ const result = await convert({
600
+ input: resolved.match.path,
601
+ preview: true,
602
+ theme,
603
+ width
604
+ });
605
+ const note = result.previewClipped ? `Preview clipped to the top 1600px of a ${result.height}px page.` : `Preview of ${resolved.match.name}, ${result.width}x${result.height}px.`;
606
+ return {
607
+ content: [
608
+ { type: "text", text: note },
609
+ {
610
+ type: "image",
611
+ data: (result.preview ?? Buffer.alloc(0)).toString("base64"),
612
+ mimeType: "image/png"
613
+ }
614
+ ]
615
+ };
616
+ }
617
+ );
618
+ return server;
619
+ }
620
+ async function serveStdio() {
621
+ const server = createServer();
622
+ process.stdin.on("end", () => {
623
+ void closeBrowser();
624
+ });
625
+ await server.connect(new StdioServerTransport());
626
+ }
627
+ function unresolvedCanvas(canvas, matches) {
628
+ if (matches.length === 0) {
629
+ throw new Error(`No canvas found for "${canvas}". Call list_canvases to see available files.`);
630
+ }
631
+ return text(
632
+ `Several canvases match "${canvas}". Pass one full path:
633
+ ${matches.map((hit) => hit.path).join("\n")}`
634
+ );
635
+ }
636
+ function text(value) {
637
+ return { content: [{ type: "text", text: value }] };
638
+ }
639
+
640
+ // src/cli.ts
641
+ async function main(argv = process.argv.slice(2)) {
642
+ const { flags, positionals } = readArgs(argv);
643
+ if (positionals[0] === "mcp") {
644
+ await serveStdio();
645
+ return;
646
+ }
647
+ if (flags.has("help") || positionals.length === 0) {
648
+ process.stdout.write(help());
649
+ process.exit(positionals.length === 0 && !flags.has("help") ? 1 : 0);
650
+ }
651
+ const themeFlag = flags.get("theme");
652
+ if (themeFlag != null && themeFlag !== true && themeFlag !== "dark" && themeFlag !== "light") {
653
+ process.stderr.write("Theme must be dark or light.\n");
654
+ process.exit(1);
655
+ }
656
+ const theme = themeFlag === "light" ? "light" : "dark";
657
+ const envFormat = process.env.CANVAS_EXPORT_FORMAT;
658
+ const formatFlag = flags.get("format") ?? (envFormat === "html" || envFormat === "pdf" ? envFormat : "both");
659
+ if (formatFlag !== "html" && formatFlag !== "pdf" && formatFlag !== "both") {
660
+ process.stderr.write("Format must be html, pdf, or both.\n");
661
+ process.exit(1);
662
+ }
663
+ const widthFlag = flags.get("width");
664
+ const width = widthFlag == null || widthFlag === true ? 800 : Number(widthFlag);
665
+ if (!Number.isFinite(width) || width < 320) {
666
+ process.stderr.write("Width must be a number of pixels, at least 320.\n");
667
+ process.exit(1);
668
+ }
669
+ const outFlag = flags.get("out");
670
+ const shotFlag = flags.get("screenshot");
671
+ try {
672
+ const result = await convert({
673
+ input: positionals[0],
674
+ out: outFlag === true ? void 0 : outFlag,
675
+ theme,
676
+ width,
677
+ format: formatFlag,
678
+ screenshot: shotFlag === true ? void 0 : shotFlag
679
+ });
680
+ if (result.html) process.stdout.write(`${result.html}
681
+ `);
682
+ if (result.pdf) process.stdout.write(`${result.pdf}
683
+ `);
684
+ if (result.screenshot) process.stdout.write(`${result.screenshot}
685
+ `);
686
+ for (const warning of result.warnings) process.stderr.write(`warning: ${warning}
687
+ `);
688
+ } catch (error) {
689
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
690
+ `);
691
+ process.exit(1);
692
+ }
693
+ }
694
+ function help() {
695
+ return `cursor-canvas-export <file.canvas.tsx> [options]
696
+ cursor-canvas-export mcp
697
+
698
+ --out <path> output stem; .html and .pdf are stripped
699
+ --theme dark|light default dark
700
+ --width <px> page width, default 800
701
+ --format html|pdf|both default both
702
+ --screenshot <png> full-page PNG
703
+
704
+ canvas-to-html and canvas-to-pdf are the same command with --format defaulting to html or pdf.
705
+ The browser runs headless. Exports are written next to the canvas.
706
+ `;
707
+ }
708
+ function readArgs(tokens) {
709
+ const flags = /* @__PURE__ */ new Map();
710
+ const positionals = [];
711
+ for (let index = 0; index < tokens.length; index += 1) {
712
+ const token = tokens[index];
713
+ if (!token.startsWith("--")) {
714
+ positionals.push(token);
715
+ continue;
716
+ }
717
+ const key = token.slice(2);
718
+ const next = tokens[index + 1];
719
+ if (next == null || next.startsWith("--")) flags.set(key, true);
720
+ else {
721
+ flags.set(key, next);
722
+ index += 1;
723
+ }
724
+ }
725
+ return { flags, positionals };
726
+ }
727
+ var invoked = process.argv[1] ? path4.resolve(process.argv[1]) : "";
728
+ if (invoked === fileURLToPath2(import.meta.url)) {
729
+ await main();
730
+ }
731
+ export {
732
+ main
733
+ };