markdown-pdf-export 0.0.0-stage → 2.0.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,280 @@
1
+ /**
2
+ * @fileoverview Editor wiring: builds the exact task + MCP snippets (and target
3
+ * files) for Zed, VS Code, Cursor, Claude Code and Claude Desktop.
4
+ *
5
+ * Pure functions — no I/O except `fs.existsSync` for detection — so the
6
+ * output is unit-testable with a fake home directory.
7
+ */
8
+ import { spawnSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+
13
+ /** npm package name (what npx runs). */
14
+ export const SERVER_NAME = "markdown-pdf-export";
15
+ /** Key of the MCP server entry and task label — match the docs. */
16
+ export const MCP_KEY = "markdown-pdf";
17
+ export const TASK_LABEL = "Markdown: Export to PDF";
18
+ export const EDITOR_IDS = ["zed", "vscode", "cursor", "claude-code", "claude-desktop"];
19
+
20
+ /**
21
+ * Version managers install node under a version-specific directory; editors
22
+ * should call the manager's stable shim instead so the entry survives a
23
+ * Node upgrade. Returns `execPath` unchanged when no shim applies.
24
+ * @param {string} execPath
25
+ * @param {string} [home]
26
+ * @param {(p: string) => boolean} [exists]
27
+ */
28
+ export function stableNodePath(execPath, home = os.homedir(), exists = fs.existsSync) {
29
+ const exe = process.platform === "win32" ? "node.exe" : "node";
30
+ const shims = [
31
+ [/[\\/]\.volta[\\/]tools[\\/]image[\\/]node[\\/]/, path.join(home, ".volta", "bin", exe)],
32
+ [/[\\/]\.asdf[\\/]installs[\\/]nodejs[\\/]/, path.join(home, ".asdf", "shims", "node")],
33
+ [/[\\/]mise[\\/]installs[\\/]node[\\/]/, path.join(home, ".local", "share", "mise", "shims", "node")],
34
+ ];
35
+ for (const [pattern, shim] of shims) {
36
+ if (pattern.test(execPath) && exists(shim)) return shim;
37
+ }
38
+ return execPath;
39
+ }
40
+
41
+ /**
42
+ * How to launch the tool. `npx -y` when we were started through npx,
43
+ * otherwise an absolute `node <cli.mjs>` (immune to PATH problems with
44
+ * GUI-launched editors), using a version-manager shim for node when available.
45
+ * @param {string} [cliPath] absolute path of cli.mjs
46
+ * @param {string} [execPath] node binary
47
+ * @param {string} [home]
48
+ */
49
+ export function launchSpec(cliPath, execPath = process.execPath, home = os.homedir()) {
50
+ const viaNpx = typeof cliPath === "string" && /[\\/]_npx[\\/]/.test(cliPath);
51
+ if (viaNpx || !cliPath) {
52
+ return { command: "npx", args: ["-y", SERVER_NAME] };
53
+ }
54
+ return { command: stableNodePath(execPath, home), args: [path.resolve(cliPath)] };
55
+ }
56
+
57
+ /**
58
+ * Quote argv for display / execution through the platform shell
59
+ * (POSIX sh single quotes, cmd.exe double quotes).
60
+ * @param {string[]} argv
61
+ * @param {string} [platform]
62
+ */
63
+ export function shellJoin(argv, platform = process.platform) {
64
+ return argv
65
+ .map((arg) => {
66
+ if (/^[\w@%+=:,./\\-]+$/.test(arg)) return arg;
67
+ return platform === "win32"
68
+ ? `"${arg.replaceAll('"', '\\"')}"`
69
+ : `'${arg.replaceAll("'", "'\\''")}'`;
70
+ })
71
+ .join(" ");
72
+ }
73
+
74
+ const json = (value) => JSON.stringify(value, null, 2);
75
+
76
+ /** Per-OS config roots. */
77
+ function roots({ home, platform, env }) {
78
+ if (platform === "win32") {
79
+ const appData = env.APPDATA || path.join(home, "AppData", "Roaming");
80
+ return { appData, userData: appData, zed: path.join(appData, "Zed") };
81
+ }
82
+ if (platform === "darwin") {
83
+ const appSupport = path.join(home, "Library", "Application Support");
84
+ return {
85
+ appData: appSupport,
86
+ userData: appSupport,
87
+ zed: path.join(home, ".config", "zed"),
88
+ };
89
+ }
90
+ const xdg = env.XDG_CONFIG_HOME || path.join(home, ".config");
91
+ return { appData: xdg, userData: xdg, zed: path.join(xdg, "zed") };
92
+ }
93
+
94
+ /**
95
+ * @typedef {object} SetupItem
96
+ * @property {"mcp"|"task"} kind
97
+ * @property {string} label
98
+ * @property {string|null} file target file (null for CLI-only)
99
+ * @property {string} snippet text to show / write
100
+ * @property {"create"|"print"|"command"} write safe-write strategy
101
+ * @property {{cmd: string, args: string[]}} [run] CLI to run for "command"
102
+ */
103
+
104
+ /**
105
+ * @param {string} editor one of EDITOR_IDS
106
+ * @param {{command: string, args: string[]}} launch
107
+ * @param {{home?: string, platform?: string, env?: NodeJS.ProcessEnv}} [ctx]
108
+ * @returns {{id: string, name: string, detected: boolean, items: SetupItem[]}}
109
+ */
110
+ export function buildEditorSetup(editor, launch, ctx = {}) {
111
+ const home = ctx.home ?? os.homedir();
112
+ const platform = ctx.platform ?? process.platform;
113
+ const env = ctx.env ?? process.env;
114
+ const r = roots({ home, platform, env });
115
+ const server = { command: launch.command, args: [...launch.args, "mcp"] };
116
+ const exportArgs = (fileVar) => [...launch.args, fileVar];
117
+ const exists = (p) => fs.existsSync(p);
118
+
119
+ switch (editor) {
120
+ case "zed": {
121
+ const dir = r.zed;
122
+ return {
123
+ id: "zed",
124
+ name: "Zed",
125
+ detected: exists(dir),
126
+ items: [
127
+ {
128
+ kind: "task",
129
+ label: "Zed task (add to tasks.json)",
130
+ file: path.join(dir, "tasks.json"),
131
+ write: "print",
132
+ snippet: json([
133
+ {
134
+ label: TASK_LABEL,
135
+ command: launch.command,
136
+ args: exportArgs("$ZED_FILE"),
137
+ use_new_terminal: false,
138
+ reveal: "never",
139
+ },
140
+ ]),
141
+ },
142
+ {
143
+ kind: "mcp",
144
+ label: "Zed MCP server (merge into settings.json)",
145
+ file: path.join(dir, "settings.json"),
146
+ write: "print",
147
+ snippet: json({ context_servers: { [MCP_KEY]: server } }),
148
+ },
149
+ ],
150
+ };
151
+ }
152
+
153
+ case "vscode":
154
+ case "cursor": {
155
+ const isCursor = editor === "cursor";
156
+ const userDir = path.join(r.userData, isCursor ? "Cursor" : "Code", "User");
157
+ const mcpFile = path.join(home, ".cursor", "mcp.json");
158
+ const addMcp = JSON.stringify({ name: MCP_KEY, ...server });
159
+ /** @type {SetupItem[]} */
160
+ const items = [
161
+ {
162
+ kind: "task",
163
+ label: `${isCursor ? "Cursor" : "VS Code"} task (add to tasks.json)`,
164
+ file: path.join(userDir, "tasks.json"),
165
+ write: "print",
166
+ snippet: json({
167
+ version: "2.0.0",
168
+ tasks: [
169
+ {
170
+ label: TASK_LABEL,
171
+ type: "process",
172
+ command: launch.command,
173
+ args: exportArgs("${file}"),
174
+ problemMatcher: [],
175
+ },
176
+ ],
177
+ }),
178
+ },
179
+ isCursor
180
+ ? {
181
+ kind: "mcp",
182
+ label: "Cursor MCP server",
183
+ file: mcpFile,
184
+ write: exists(mcpFile) ? "print" : "create",
185
+ snippet: json({ mcpServers: { [MCP_KEY]: server } }),
186
+ }
187
+ : {
188
+ // VS Code's own CLI writes the right file for the installed version.
189
+ kind: "mcp",
190
+ label: "VS Code MCP server",
191
+ file: null,
192
+ write: "command",
193
+ run: { cmd: "code", args: ["--add-mcp", addMcp] },
194
+ snippet: shellJoin(["code", "--add-mcp", addMcp], platform),
195
+ },
196
+ ];
197
+ return {
198
+ id: editor,
199
+ name: isCursor ? "Cursor" : "VS Code",
200
+ detected: exists(userDir) || (isCursor && exists(path.join(home, ".cursor"))),
201
+ items,
202
+ };
203
+ }
204
+
205
+ case "claude-code":
206
+ return {
207
+ id: "claude-code",
208
+ name: "Claude Code",
209
+ detected: exists(path.join(home, ".claude")),
210
+ items: [
211
+ {
212
+ kind: "mcp",
213
+ label: "Claude Code MCP server",
214
+ file: null,
215
+ write: "command",
216
+ run: {
217
+ cmd: "claude",
218
+ args: ["mcp", "add", MCP_KEY, "--", server.command, ...server.args],
219
+ },
220
+ snippet: shellJoin(
221
+ ["claude", "mcp", "add", MCP_KEY, "--", server.command, ...server.args],
222
+ platform,
223
+ ),
224
+ },
225
+ ],
226
+ };
227
+
228
+ case "claude-desktop": {
229
+ const file = path.join(r.appData, "Claude", "claude_desktop_config.json");
230
+ return {
231
+ id: "claude-desktop",
232
+ name: "Claude Desktop",
233
+ detected: exists(path.dirname(file)),
234
+ items: [
235
+ {
236
+ kind: "mcp",
237
+ label: "Claude Desktop MCP server",
238
+ file,
239
+ write: exists(file) ? "print" : "create",
240
+ snippet: json({ mcpServers: { [MCP_KEY]: server } }),
241
+ },
242
+ ],
243
+ };
244
+ }
245
+
246
+ default:
247
+ throw new Error(`Unknown editor "${editor}". Use one of: ${EDITOR_IDS.join(", ")}, all`);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Carry out one setup item when that is safe: create a file that does not
253
+ * exist yet, or run the editor's own CLI. Existing files are never modified.
254
+ * @param {SetupItem} item
255
+ * @param {{stdio?: import("node:child_process").StdioOptions}} [opts]
256
+ * @returns {{done: boolean, message: string}}
257
+ */
258
+ export function applySetupItem(item, { stdio = "inherit" } = {}) {
259
+ if (item.write === "create") {
260
+ try {
261
+ fs.mkdirSync(path.dirname(item.file), { recursive: true });
262
+ fs.writeFileSync(item.file, `${item.snippet}\n`, { flag: "wx" });
263
+ return { done: true, message: `created ${item.file}` };
264
+ } catch (error) {
265
+ return { done: false, message: `could not create ${item.file}: ${error.message}` };
266
+ }
267
+ }
268
+ if (item.write === "command") {
269
+ // Windows: code/claude are .cmd shims, which need the shell; pass one
270
+ // pre-quoted command line so JSON arguments survive cmd.exe.
271
+ const result =
272
+ process.platform === "win32"
273
+ ? spawnSync(item.snippet, { stdio, shell: true })
274
+ : spawnSync(item.run.cmd, item.run.args, { stdio });
275
+ return result.status === 0
276
+ ? { done: true, message: `ran: ${item.snippet}` }
277
+ : { done: false, message: `could not run "${item.run.cmd}" — run the command yourself` };
278
+ }
279
+ return { done: false, message: "existing file: paste the snippet yourself" };
280
+ }