cursor-canvas-export 0.1.0 → 0.1.2

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 (3) hide show
  1. package/README.md +8 -5
  2. package/dist/cli.js +203 -30
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # cursor-canvas-export
2
2
 
3
- Export a Cursor canvas (`.canvas.tsx`) to a self-contained HTML file and a one-page PDF.
3
+ [![npm](https://img.shields.io/npm/v/cursor-canvas-export.svg)](https://www.npmjs.com/package/cursor-canvas-export)
4
+ [![Add to Cursor](https://img.shields.io/badge/Add_to_Cursor-111111?logo=cursor&logoColor=white)](https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19)
4
5
 
5
- HTML is the rendered page. The PDF is that page printed by headless Chromium, so colors, type, tables, and charts stay together. Nothing opens on screen. The page is one continuous sheet the width of the canvas panel.
6
+ Command-line tool and MCP server. It exports a Cursor canvas (`.canvas.tsx`) to a self-contained HTML file and a one-page PDF.
6
7
 
7
- The same tool is published for agents as an MCP server.
8
+ HTML is the rendered page. The PDF is that page printed by headless Chromium, so colors, type, tables, and charts stay together. Nothing opens on screen. The page is one continuous sheet the width of the canvas panel.
8
9
 
9
10
  ## Install
10
11
 
@@ -15,7 +16,7 @@ npm install
15
16
  npx playwright install chromium
16
17
  ```
17
18
 
18
- The first export downloads Chromium if it is not cached yet. Later runs reuse that copy on Windows, macOS, and Linux.
19
+ The first export downloads Chromium if it is not cached yet. On the command line that download happens inside the command. The MCP tools return immediately and ask for a short wait while the download continues in the background. Later runs reuse that copy on Windows, macOS, and Linux.
19
20
 
20
21
  ## Command line
21
22
 
@@ -64,7 +65,7 @@ Add this to `~/.cursor/mcp.json`:
64
65
  }
65
66
  ```
66
67
 
67
- [Add to Cursor](https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19)
68
+ <a href="https://cursor.com/install-mcp?name=canvas-export&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImN1cnNvci1jYW52YXMtZXhwb3J0IiwibWNwIl19"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/deeplink/mcp-install-dark.svg"><img alt="Add to Cursor" src="https://cursor.com/deeplink/mcp-install-light.svg"></picture></a>
68
69
 
69
70
  The server exposes three tools:
70
71
 
@@ -76,6 +77,8 @@ The server exposes three tools:
76
77
 
77
78
  Ask the agent to export a canvas. It calls the tool and returns the file paths.
78
79
 
80
+ The first time Chromium is not cached, `export_canvas` and `preview_canvas` return at once and tell the agent to wait about 30 seconds, then call the same tool again with the same arguments. That reply is not a failed export. The file appears when a later call returns the output paths.
81
+
79
82
  ## How it works
80
83
 
81
84
  A canvas only imports `cursor/canvas`. This package bundles the file with esbuild against a local implementation of that SDK, mounts it in headless Chromium, and saves the DOM. Chart colors and the type scale come from the public canvas tokens.
package/dist/cli.js CHANGED
@@ -17,20 +17,46 @@ import { createRequire } from "node:module";
17
17
  import path from "node:path";
18
18
  import { chromium } from "playwright";
19
19
  var require2 = createRequire(import.meta.url);
20
+ var BrowserNotReady = class extends Error {
21
+ gate;
22
+ constructor(gate) {
23
+ super(gate.state === "failed" ? gate.message : "Chromium is still downloading");
24
+ this.name = "BrowserNotReady";
25
+ this.gate = gate;
26
+ }
27
+ };
20
28
  var browserPromise;
21
29
  var users = 0;
22
30
  var hold = false;
31
+ var phase = "idle";
32
+ var failureMessage = "";
33
+ var downloadListeners = [];
34
+ var forcedGate;
35
+ var launchGeneration = 0;
36
+ var installChild;
23
37
  function holdBrowserProcess() {
24
38
  hold = true;
25
39
  }
40
+ function warmBrowser() {
41
+ if (forcedGate) return;
42
+ if (phase === "failed" || browserPromise) return;
43
+ startLaunch();
44
+ }
45
+ function browserGate() {
46
+ if (forcedGate) return Promise.resolve(forcedGate);
47
+ if (phase === "failed") {
48
+ const message = failureMessage;
49
+ startLaunch();
50
+ return Promise.resolve({ state: "failed", message });
51
+ }
52
+ if (phase === "downloading") return Promise.resolve({ state: "downloading" });
53
+ if (!browserPromise) startLaunch();
54
+ if (phase === "ready") return Promise.resolve({ state: "ready" });
55
+ return waitForLaunch(browserPromise);
56
+ }
26
57
  function acquireBrowser() {
27
58
  users += 1;
28
- if (!browserPromise) {
29
- browserPromise = launchChromium().catch((error) => {
30
- browserPromise = void 0;
31
- throw error;
32
- });
33
- }
59
+ if (!browserPromise) startLaunch();
34
60
  return browserPromise;
35
61
  }
36
62
  async function releaseBrowser() {
@@ -41,24 +67,100 @@ async function closeBrowser() {
41
67
  hold = false;
42
68
  if (users === 0) await shutdown();
43
69
  }
70
+ function startLaunch() {
71
+ if (browserPromise) return browserPromise;
72
+ const generation = launchGeneration;
73
+ phase = "launching";
74
+ failureMessage = "";
75
+ const pending = launchChromium(generation).then(
76
+ (browser) => {
77
+ if (browserPromise === pending) phase = "ready";
78
+ return browser;
79
+ },
80
+ (error) => {
81
+ if (browserPromise !== pending) throw error;
82
+ browserPromise = void 0;
83
+ phase = "failed";
84
+ failureMessage = error instanceof Error ? error.message : String(error);
85
+ throw error;
86
+ }
87
+ );
88
+ void pending.catch(() => {
89
+ });
90
+ browserPromise = pending;
91
+ return pending;
92
+ }
93
+ function waitForLaunch(pending) {
94
+ return new Promise((resolve) => {
95
+ let settled = false;
96
+ const finish = (gate) => {
97
+ if (settled) return;
98
+ settled = true;
99
+ downloadListeners = downloadListeners.filter((listener) => listener !== onDownload);
100
+ resolve(gate);
101
+ };
102
+ const onDownload = () => finish({ state: "downloading" });
103
+ downloadListeners.push(onDownload);
104
+ if (phase === "downloading") {
105
+ finish({ state: "downloading" });
106
+ return;
107
+ }
108
+ pending.then(
109
+ () => finish({ state: "ready" }),
110
+ (error) => {
111
+ const message = failureMessage || (error instanceof Error ? error.message : String(error));
112
+ const alreadySettled = settled;
113
+ finish({ state: "failed", message });
114
+ if (!alreadySettled && phase === "failed" && !browserPromise) startLaunch();
115
+ }
116
+ );
117
+ });
118
+ }
119
+ function notifyDownloading() {
120
+ phase = "downloading";
121
+ const listeners = downloadListeners;
122
+ downloadListeners = [];
123
+ for (const listener of listeners) listener();
124
+ }
44
125
  async function shutdown() {
45
126
  if (users > 0 || hold || !browserPromise) return;
127
+ launchGeneration += 1;
128
+ stopInstallChild();
46
129
  const pending = browserPromise;
130
+ const wasReady = phase === "ready";
47
131
  browserPromise = void 0;
132
+ downloadListeners = [];
133
+ if (!wasReady) {
134
+ phase = "idle";
135
+ failureMessage = "";
136
+ return;
137
+ }
48
138
  const browser = await pending.catch(() => void 0);
49
139
  if (users > 0 && browser) {
50
140
  browserPromise = Promise.resolve(browser);
141
+ phase = "ready";
51
142
  return;
52
143
  }
53
144
  await browser?.close().catch(() => {
54
145
  });
146
+ if (!browserPromise && phase !== "failed") phase = "idle";
55
147
  }
56
- async function launchChromium() {
148
+ async function launchChromium(generation) {
57
149
  try {
58
- return await chromium.launch({ headless: true });
150
+ const browser = await chromium.launch({ headless: true });
151
+ if (generation !== launchGeneration) {
152
+ await browser.close().catch(() => {
153
+ });
154
+ throw new Error("browser launch cancelled");
155
+ }
156
+ return browser;
59
157
  } catch (error) {
158
+ if (generation !== launchGeneration) throw error;
60
159
  if (!isMissingBrowser(error)) throw error;
160
+ notifyDownloading();
161
+ if (generation !== launchGeneration) throw new Error("browser launch cancelled");
61
162
  await installChromium();
163
+ if (generation !== launchGeneration) throw new Error("browser launch cancelled");
62
164
  return await chromium.launch({ headless: true });
63
165
  }
64
166
  }
@@ -73,15 +175,34 @@ function installChromium() {
73
175
  const child = spawn(process.execPath, [cli, "install", "chromium"], {
74
176
  stdio: ["ignore", "pipe", "pipe"]
75
177
  });
178
+ installChild = child;
179
+ let settled = false;
180
+ const finish = (error) => {
181
+ if (settled) return;
182
+ settled = true;
183
+ if (installChild === child) installChild = void 0;
184
+ if (error) reject(error);
185
+ else resolve();
186
+ };
76
187
  child.stdout.on("data", (chunk) => process.stderr.write(chunk));
77
188
  child.stderr.on("data", (chunk) => process.stderr.write(chunk));
78
- child.on("error", reject);
189
+ child.on("error", (error) => finish(error));
79
190
  child.on("close", (code) => {
80
- if (code === 0) resolve();
81
- else reject(new Error(`playwright install chromium exited with code ${code ?? "unknown"}`));
191
+ if (code === 0) finish();
192
+ else finish(new Error(`playwright install chromium exited with code ${code ?? "unknown"}`));
82
193
  });
83
194
  });
84
195
  }
196
+ function stopInstallChild() {
197
+ const child = installChild;
198
+ installChild = void 0;
199
+ if (!child?.pid || child.killed) return;
200
+ if (process.platform === "win32") {
201
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
202
+ return;
203
+ }
204
+ child.kill("SIGKILL");
205
+ }
85
206
 
86
207
  // src/sdk/tokens.ts
87
208
  var chartPalette = {
@@ -323,6 +444,10 @@ async function convert(options) {
323
444
  <script>${script}</script>
324
445
  </body>
325
446
  </html>`;
447
+ if (options.deferBrowser) {
448
+ const gate = await browserGate();
449
+ if (gate.state !== "ready") throw new BrowserNotReady(gate);
450
+ }
326
451
  const browser = await acquireBrowser();
327
452
  let page;
328
453
  try {
@@ -529,11 +654,21 @@ function slug(value) {
529
654
  }
530
655
 
531
656
  // src/mcp.ts
532
- var themeSchema = z.enum(["dark", "light"]).describe("Canvas theme. Defaults to dark.");
657
+ var exportThemeSchema = z.enum(["dark", "light"]).describe(
658
+ "Canvas theme. Defaults to dark. Prefer dark: the output is usually read by a developer working in a dark IDE, who may strongly dislike a light page. Use light only if the user explicitly asks for it."
659
+ );
660
+ var previewThemeSchema = z.enum(["dark", "light"]).describe("Canvas theme. Defaults to dark.");
533
661
  var widthSchema = z.number().int().min(320).optional().describe("Page width in pixels. Defaults to 800.");
662
+ var browserWait = "If the result tells you to wait because Chromium is downloading, that is not an error. Wait about 30 seconds and call this tool again with the same arguments. Nothing is written until a later call finishes the render.";
534
663
  function createServer() {
535
664
  holdBrowserProcess();
536
- const server = new McpServer({ name: "cursor-canvas-export", version: "0.1.0" });
665
+ warmBrowser();
666
+ const server = new McpServer(
667
+ { name: "cursor-canvas-export", version: "0.1.2" },
668
+ {
669
+ instructions: "If export_canvas or preview_canvas tells you to wait because Chromium is downloading, that is not an error. Wait about 30 seconds and call the same tool again with the same arguments. The file or preview is ready only when that later call returns it."
670
+ }
671
+ );
537
672
  server.registerTool(
538
673
  "list_canvases",
539
674
  {
@@ -554,11 +689,11 @@ function createServer() {
554
689
  "export_canvas",
555
690
  {
556
691
  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.",
692
+ 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. ${browserWait}`,
558
693
  inputSchema: {
559
694
  canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
560
695
  format: z.enum(["html", "pdf", "both"]).optional().describe("Defaults to both."),
561
- theme: themeSchema.optional(),
696
+ theme: exportThemeSchema.optional(),
562
697
  width: widthSchema,
563
698
  out: z.string().optional().describe("Output stem. Extension is ignored. Defaults to beside the canvas.")
564
699
  }
@@ -566,13 +701,21 @@ function createServer() {
566
701
  async ({ canvas, format, theme, width, out }) => {
567
702
  const resolved = resolveCanvas(canvas);
568
703
  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
- });
704
+ let result;
705
+ try {
706
+ result = await convert({
707
+ input: resolved.match.path,
708
+ out,
709
+ format: format ?? "both",
710
+ theme,
711
+ width,
712
+ deferBrowser: true
713
+ });
714
+ } catch (error) {
715
+ const waiting = browserWaitReply("export_canvas", error);
716
+ if (waiting) return waiting;
717
+ throw error;
718
+ }
576
719
  const lines = [
577
720
  result.html ? `html: ${result.html}` : "",
578
721
  result.pdf ? `pdf: ${result.pdf}` : "",
@@ -586,22 +729,30 @@ function createServer() {
586
729
  "preview_canvas",
587
730
  {
588
731
  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.",
732
+ 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. ${browserWait}`,
590
733
  inputSchema: {
591
734
  canvas: z.string().describe("Absolute path to a .canvas.tsx file, or its name without the extension."),
592
- theme: themeSchema.optional(),
735
+ theme: previewThemeSchema.optional(),
593
736
  width: widthSchema
594
737
  }
595
738
  },
596
739
  async ({ canvas, theme, width }) => {
597
740
  const resolved = resolveCanvas(canvas);
598
741
  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
- });
742
+ let result;
743
+ try {
744
+ result = await convert({
745
+ input: resolved.match.path,
746
+ preview: true,
747
+ theme,
748
+ width,
749
+ deferBrowser: true
750
+ });
751
+ } catch (error) {
752
+ const waiting = browserWaitReply("preview_canvas", error);
753
+ if (waiting) return waiting;
754
+ throw error;
755
+ }
605
756
  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
757
  return {
607
758
  content: [
@@ -633,6 +784,28 @@ function unresolvedCanvas(canvas, matches) {
633
784
  ${matches.map((hit) => hit.path).join("\n")}`
634
785
  );
635
786
  }
787
+ function browserWaitReply(tool, error) {
788
+ if (!(error instanceof BrowserNotReady)) return;
789
+ return text(error.gate.state === "downloading" ? downloadingMessage(tool) : failedDownloadMessage(tool, error.gate.message));
790
+ }
791
+ function downloadingMessage(tool) {
792
+ const until = tool === "export_canvas" ? "it returns the output paths" : "it returns the preview image";
793
+ return [
794
+ `Wait about 30 seconds, then call ${tool} again with the same arguments. Chromium is still downloading.`,
795
+ "This is not an error. The canvas and the arguments are fine. Nothing was rendered or written yet.",
796
+ "The download is already running. Calling the tool again does not start a second download.",
797
+ `After waiting, call ${tool} once more with the same arguments. Repeat until ${until}.`
798
+ ].join("\n");
799
+ }
800
+ function failedDownloadMessage(tool, message) {
801
+ return [
802
+ `Chromium download failed: ${message}`,
803
+ `Wait about 30 seconds, then call ${tool} again with the same arguments. A new download is already running.`,
804
+ "This is not a problem with the canvas or the arguments.",
805
+ "If the same failure comes back, install Chromium from a terminal and call the tool again:",
806
+ "npx playwright install chromium"
807
+ ].join("\n");
808
+ }
636
809
  function text(value) {
637
810
  return { content: [{ type: "text", text: value }] };
638
811
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-canvas-export",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Export a Cursor canvas to HTML and a one-page PDF. Headless, for agents and the command line.",
5
5
  "license": "MIT",
6
6
  "type": "module",