markdown-pdf-export 2.2.2 → 2.3.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/cli.mjs +3 -2
- package/lib/doctor-report.mjs +1 -1
- package/lib/editor-setup.mjs +120 -47
- package/lib/jsonc-merge.mjs +212 -0
- package/lib/studio-server.mjs +5 -0
- package/package.json +2 -1
- package/studio/app.mjs +4 -3
package/cli.mjs
CHANGED
|
@@ -756,8 +756,9 @@ async function runSetup(argv) {
|
|
|
756
756
|
"In a terminal it asks editor by editor and skips what is already set up.\n" +
|
|
757
757
|
"--write set up everything without asking (scripts)\n" +
|
|
758
758
|
"--print only show what to add\n" +
|
|
759
|
-
"
|
|
760
|
-
"
|
|
759
|
+
"Missing files are created and editor CLIs are run. In an existing file only\n" +
|
|
760
|
+
"the new entry is added (comments kept, a copy saved as <file>.markdown-pdf.bak);\n" +
|
|
761
|
+
"a file that cannot be read is left alone and you get the snippet to paste.\n",
|
|
761
762
|
);
|
|
762
763
|
return 0;
|
|
763
764
|
}
|
package/lib/doctor-report.mjs
CHANGED
|
@@ -64,7 +64,7 @@ export function formatDoctor(
|
|
|
64
64
|
return { text: `${head}\n\n${lines.join("\n")}\n${editors}`, ok };
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
const PARTS = { task: "export task", mcp: "AI tools" };
|
|
67
|
+
const PARTS = { task: "export task", key: "keyboard shortcut", mcp: "AI tools" };
|
|
68
68
|
|
|
69
69
|
/**
|
|
70
70
|
* Editors section: what is set up where. Never fails the check — a missing
|
package/lib/editor-setup.mjs
CHANGED
|
@@ -2,19 +2,30 @@
|
|
|
2
2
|
* @fileoverview Editor wiring: builds the exact task + MCP snippets (and target
|
|
3
3
|
* files) for Zed, VS Code, Cursor, Claude Code and Claude Desktop.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* output is unit-testable with a fake home directory.
|
|
5
|
+
* Building is pure — no I/O except `fs.existsSync` for detection — so the
|
|
6
|
+
* output is unit-testable with a fake home directory. `applySetupItem` does
|
|
7
|
+
* the writing: it creates missing files, adds one entry to existing JSON(C)
|
|
8
|
+
* files (lib/jsonc-merge.mjs) or runs an editor CLI.
|
|
7
9
|
*/
|
|
8
10
|
import { spawnSync } from "node:child_process";
|
|
9
11
|
import fs from "node:fs";
|
|
10
12
|
import os from "node:os";
|
|
11
13
|
import path from "node:path";
|
|
12
14
|
|
|
15
|
+
import { formatJson, mergeJsonc } from "./jsonc-merge.mjs";
|
|
16
|
+
|
|
13
17
|
/** npm package name (what npx runs). */
|
|
14
18
|
export const SERVER_NAME = "markdown-pdf-export";
|
|
15
19
|
/** Key of the MCP server entry and task label — match the docs. */
|
|
16
20
|
export const MCP_KEY = "markdown-pdf";
|
|
17
21
|
export const TASK_LABEL = "Markdown: Export to PDF";
|
|
22
|
+
/** Id of the Zed extension (zed-markdown-pdf-export) that provides the MCP server. */
|
|
23
|
+
export const ZED_EXTENSION_ID = "markdown-pdf-export";
|
|
24
|
+
/**
|
|
25
|
+
* Zed shortcut for the export task. Free in Zed's default keymaps on every
|
|
26
|
+
* platform; cmd/ctrl-shift-o would hide the outline (outline::Toggle).
|
|
27
|
+
*/
|
|
28
|
+
export const ZED_EXPORT_KEY = { darwin: "cmd-k cmd-e", other: "ctrl-k ctrl-e" };
|
|
18
29
|
export const EDITOR_IDS = ["zed", "vscode", "cursor", "claude-code", "claude-desktop", "copilot-cli"];
|
|
19
30
|
/** Short names people type for an editor id. */
|
|
20
31
|
export const EDITOR_ALIASES = { claude: "claude-code", code: "vscode", copilot: "copilot-cli" };
|
|
@@ -73,13 +84,14 @@ export function shellJoin(argv, platform = process.platform) {
|
|
|
73
84
|
.join(" ");
|
|
74
85
|
}
|
|
75
86
|
|
|
76
|
-
const json = (value) =>
|
|
87
|
+
const json = (value) => formatJson(value);
|
|
77
88
|
|
|
78
89
|
/** Per-OS config roots. */
|
|
79
90
|
function roots({ home, platform, env }) {
|
|
80
91
|
if (platform === "win32") {
|
|
81
92
|
const appData = env.APPDATA || path.join(home, "AppData", "Roaming");
|
|
82
|
-
|
|
93
|
+
const localAppData = env.LOCALAPPDATA || path.join(home, "AppData", "Local");
|
|
94
|
+
return { appData, userData: appData, zed: path.join(appData, "Zed"), zedData: path.join(localAppData, "Zed") };
|
|
83
95
|
}
|
|
84
96
|
if (platform === "darwin") {
|
|
85
97
|
const appSupport = path.join(home, "Library", "Application Support");
|
|
@@ -87,19 +99,24 @@ function roots({ home, platform, env }) {
|
|
|
87
99
|
appData: appSupport,
|
|
88
100
|
userData: appSupport,
|
|
89
101
|
zed: path.join(home, ".config", "zed"),
|
|
102
|
+
zedData: path.join(appSupport, "Zed"),
|
|
90
103
|
};
|
|
91
104
|
}
|
|
92
105
|
const xdg = env.XDG_CONFIG_HOME || path.join(home, ".config");
|
|
93
|
-
|
|
106
|
+
const data = env.FLATPAK_XDG_DATA_HOME || env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
107
|
+
return { appData: xdg, userData: xdg, zed: path.join(xdg, "zed"), zedData: path.join(data, "zed") };
|
|
94
108
|
}
|
|
95
109
|
|
|
96
110
|
/**
|
|
97
111
|
* @typedef {object} SetupItem
|
|
98
|
-
* @property {"mcp"|"task"} kind
|
|
112
|
+
* @property {"mcp"|"task"|"key"} kind
|
|
99
113
|
* @property {string} label
|
|
100
114
|
* @property {string|null} file target file (null for CLI-only)
|
|
101
115
|
* @property {string} snippet text to show / write
|
|
102
|
-
* @property {"create"|"print"|"command"} write safe-write strategy
|
|
116
|
+
* @property {"create"|"merge"|"print"|"command"} write safe-write strategy:
|
|
117
|
+
* create a missing file, merge one entry into an existing one, only print, or run a CLI
|
|
118
|
+
* @property {{at: (string|number)[], value: unknown, append?: boolean}} [merge]
|
|
119
|
+
* the entry `merge` adds (see mergeJsonc)
|
|
103
120
|
* @property {{cmd: string, args: string[], fallbacks?: string[]}} [run]
|
|
104
121
|
* CLI to run for "command"; `fallbacks` are full paths tried when `cmd` is not on PATH
|
|
105
122
|
*/
|
|
@@ -123,6 +140,25 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
|
|
|
123
140
|
switch (editor) {
|
|
124
141
|
case "zed": {
|
|
125
142
|
const dir = r.zed;
|
|
143
|
+
const tasks = path.join(dir, "tasks.json");
|
|
144
|
+
const keymap = path.join(dir, "keymap.json");
|
|
145
|
+
const settings = path.join(dir, "settings.json");
|
|
146
|
+
const task = {
|
|
147
|
+
label: TASK_LABEL,
|
|
148
|
+
command: launch.command,
|
|
149
|
+
args: exportArgs("$ZED_FILE"),
|
|
150
|
+
use_new_terminal: false,
|
|
151
|
+
reveal: "never",
|
|
152
|
+
};
|
|
153
|
+
const binding = {
|
|
154
|
+
context: "Editor && extension == md",
|
|
155
|
+
bindings: {
|
|
156
|
+
[platform === "darwin" ? ZED_EXPORT_KEY.darwin : ZED_EXPORT_KEY.other]: [
|
|
157
|
+
"task::Spawn",
|
|
158
|
+
{ task_name: TASK_LABEL },
|
|
159
|
+
],
|
|
160
|
+
},
|
|
161
|
+
};
|
|
126
162
|
return {
|
|
127
163
|
id: "zed",
|
|
128
164
|
name: "Zed",
|
|
@@ -130,25 +166,26 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
|
|
|
130
166
|
items: [
|
|
131
167
|
{
|
|
132
168
|
kind: "task",
|
|
133
|
-
label: "Zed task (
|
|
134
|
-
file:
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
snippet: json([
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
]),
|
|
169
|
+
label: "Zed task (tasks.json)",
|
|
170
|
+
file: tasks,
|
|
171
|
+
write: exists(tasks) ? "merge" : "create",
|
|
172
|
+
merge: { at: [], value: task, append: true },
|
|
173
|
+
snippet: json([task]),
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
kind: "key",
|
|
177
|
+
label: "Zed keyboard shortcut (keymap.json)",
|
|
178
|
+
file: keymap,
|
|
179
|
+
write: exists(keymap) ? "merge" : "create",
|
|
180
|
+
merge: { at: [], value: binding, append: true },
|
|
181
|
+
snippet: json([binding]),
|
|
146
182
|
},
|
|
147
183
|
{
|
|
148
184
|
kind: "mcp",
|
|
149
|
-
label: "Zed MCP server (
|
|
150
|
-
file:
|
|
151
|
-
write: "
|
|
185
|
+
label: "Zed MCP server (settings.json)",
|
|
186
|
+
file: settings,
|
|
187
|
+
write: exists(settings) ? "merge" : "create",
|
|
188
|
+
merge: { at: ["context_servers", MCP_KEY], value: server },
|
|
152
189
|
snippet: json({ context_servers: { [MCP_KEY]: server } }),
|
|
153
190
|
},
|
|
154
191
|
],
|
|
@@ -162,32 +199,30 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
|
|
|
162
199
|
const mcpFile = path.join(home, ".cursor", "mcp.json");
|
|
163
200
|
const taskFile = path.join(userDir, "tasks.json");
|
|
164
201
|
const addMcp = JSON.stringify({ name: MCP_KEY, ...server });
|
|
202
|
+
const vscodeTask = {
|
|
203
|
+
label: TASK_LABEL,
|
|
204
|
+
type: "process",
|
|
205
|
+
command: launch.command,
|
|
206
|
+
args: exportArgs("${file}"),
|
|
207
|
+
problemMatcher: [],
|
|
208
|
+
};
|
|
165
209
|
/** @type {SetupItem[]} */
|
|
166
210
|
const items = [
|
|
167
211
|
{
|
|
168
212
|
kind: "task",
|
|
169
|
-
label: `${isCursor ? "Cursor" : "VS Code"} task (
|
|
213
|
+
label: `${isCursor ? "Cursor" : "VS Code"} task (tasks.json)`,
|
|
170
214
|
file: taskFile,
|
|
171
|
-
write: exists(taskFile) ? "
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
tasks: [
|
|
175
|
-
{
|
|
176
|
-
label: TASK_LABEL,
|
|
177
|
-
type: "process",
|
|
178
|
-
command: launch.command,
|
|
179
|
-
args: exportArgs("${file}"),
|
|
180
|
-
problemMatcher: [],
|
|
181
|
-
},
|
|
182
|
-
],
|
|
183
|
-
}),
|
|
215
|
+
write: exists(taskFile) ? "merge" : "create",
|
|
216
|
+
merge: { at: ["tasks"], value: vscodeTask, append: true },
|
|
217
|
+
snippet: json({ version: "2.0.0", tasks: [vscodeTask] }),
|
|
184
218
|
},
|
|
185
219
|
isCursor
|
|
186
220
|
? {
|
|
187
221
|
kind: "mcp",
|
|
188
222
|
label: "Cursor MCP server",
|
|
189
223
|
file: mcpFile,
|
|
190
|
-
write: exists(mcpFile) ? "
|
|
224
|
+
write: exists(mcpFile) ? "merge" : "create",
|
|
225
|
+
merge: { at: ["mcpServers", MCP_KEY], value: server },
|
|
191
226
|
snippet: json({ mcpServers: { [MCP_KEY]: server } }),
|
|
192
227
|
}
|
|
193
228
|
: {
|
|
@@ -274,7 +309,8 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
|
|
|
274
309
|
kind: "mcp",
|
|
275
310
|
label: "Claude Desktop MCP server",
|
|
276
311
|
file,
|
|
277
|
-
write: exists(file) ? "
|
|
312
|
+
write: exists(file) ? "merge" : "create",
|
|
313
|
+
merge: { at: ["mcpServers", MCP_KEY], value: server },
|
|
278
314
|
snippet: json({ mcpServers: { [MCP_KEY]: server } }),
|
|
279
315
|
},
|
|
280
316
|
],
|
|
@@ -286,15 +322,47 @@ export function buildEditorSetup(editor, launch, ctx = {}) {
|
|
|
286
322
|
}
|
|
287
323
|
}
|
|
288
324
|
|
|
325
|
+
/** Backup kept next to a file before `setup` changes it. */
|
|
326
|
+
export const backupPath = (file) => `${file}.markdown-pdf.bak`;
|
|
327
|
+
|
|
289
328
|
/**
|
|
290
|
-
*
|
|
291
|
-
*
|
|
329
|
+
* Replace a file's content safely: write the real file behind a symlink
|
|
330
|
+
* (dotfiles setups), keep its mode, back it up first, and swap it in with a
|
|
331
|
+
* rename so an editor never reads a half-written file.
|
|
332
|
+
*/
|
|
333
|
+
function replaceFile(file, content) {
|
|
334
|
+
const real = fs.realpathSync(file);
|
|
335
|
+
const { mode } = fs.statSync(real);
|
|
336
|
+
fs.copyFileSync(real, backupPath(file));
|
|
337
|
+
const tmp = `${real}.markdown-pdf-${process.pid}.tmp`;
|
|
338
|
+
try {
|
|
339
|
+
fs.writeFileSync(tmp, content, { mode });
|
|
340
|
+
fs.renameSync(tmp, real);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
fs.rmSync(tmp, { force: true });
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Carry out one setup item: create a file that does not exist yet, add one
|
|
349
|
+
* entry to an existing JSON(C) file (nothing else in it changes; a backup is
|
|
350
|
+
* kept), or run the editor's own CLI.
|
|
292
351
|
* @param {SetupItem} item
|
|
293
352
|
* @param {{stdio?: import("node:child_process").StdioOptions}} [opts]
|
|
294
353
|
* @returns {{done: boolean, message: string}}
|
|
295
354
|
*/
|
|
296
355
|
export function applySetupItem(item, { stdio = "inherit" } = {}) {
|
|
297
|
-
if (item.write === "
|
|
356
|
+
if (item.write === "merge" && fs.existsSync(item.file)) {
|
|
357
|
+
try {
|
|
358
|
+
const before = fs.readFileSync(item.file, "utf8");
|
|
359
|
+
replaceFile(item.file, mergeJsonc(before, item.merge));
|
|
360
|
+
return { done: true, message: `added to ${item.file} (backup: ${path.basename(backupPath(item.file))})` };
|
|
361
|
+
} catch (error) {
|
|
362
|
+
return { done: false, message: `could not update ${item.file}: ${error.message}. Paste the snippet yourself` };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (item.write === "create" || item.write === "merge") {
|
|
298
366
|
try {
|
|
299
367
|
fs.mkdirSync(path.dirname(item.file), { recursive: true });
|
|
300
368
|
fs.writeFileSync(item.file, `${item.snippet}\n`, { flag: "wx" });
|
|
@@ -331,9 +399,10 @@ const readText = (file) => {
|
|
|
331
399
|
}
|
|
332
400
|
};
|
|
333
401
|
|
|
334
|
-
/** Task file: names our package. Settings/MCP file: has a "markdown-pdf" entry. */
|
|
402
|
+
/** Task file: names our package. Settings/MCP file: has a "markdown-pdf" entry. Keymap: runs our task. */
|
|
335
403
|
const hasTask = (text) => text !== null && text.includes(SERVER_NAME);
|
|
336
404
|
const hasMcpKey = (text) => text !== null && text.includes(`"${MCP_KEY}"`);
|
|
405
|
+
const hasKey = (text) => text !== null && text.includes(TASK_LABEL);
|
|
337
406
|
|
|
338
407
|
/**
|
|
339
408
|
* Claude Code keeps user-scope servers at the top of ~/.claude.json and
|
|
@@ -355,10 +424,12 @@ function claudeCodeMcp(file) {
|
|
|
355
424
|
|
|
356
425
|
/**
|
|
357
426
|
* What is set up in each editor: read-only, for `doctor`.
|
|
358
|
-
* `task` / `mcp` are undefined when the editor has no such thing.
|
|
427
|
+
* `task` / `mcp` / `key` are undefined when the editor has no such thing.
|
|
428
|
+
* Zed's MCP counts as set up when the Markdown PDF Export extension is
|
|
429
|
+
* installed: it provides the server, and a settings entry would replace it.
|
|
359
430
|
* `warnings` flags configs known to cause trouble (an old settings override).
|
|
360
431
|
* @param {{home?: string, platform?: string, env?: NodeJS.ProcessEnv}} [ctx]
|
|
361
|
-
* @returns {{id: string, name: string, detected: boolean, task?: boolean, mcp?: boolean|"project", warnings: string[]}[]}
|
|
432
|
+
* @returns {{id: string, name: string, detected: boolean, task?: boolean, mcp?: boolean|"project", key?: boolean, extension?: boolean, warnings: string[]}[]}
|
|
362
433
|
*/
|
|
363
434
|
export function editorStatus(ctx = {}) {
|
|
364
435
|
const home = ctx.home ?? os.homedir();
|
|
@@ -373,7 +444,9 @@ export function editorStatus(ctx = {}) {
|
|
|
373
444
|
switch (id) {
|
|
374
445
|
case "zed":
|
|
375
446
|
taskFile = path.join(r.zed, "tasks.json");
|
|
376
|
-
out.
|
|
447
|
+
out.extension = fs.existsSync(path.join(r.zedData, "extensions", "installed", ZED_EXTENSION_ID));
|
|
448
|
+
out.mcp = out.extension || hasMcpKey(readText(path.join(r.zed, "settings.json")));
|
|
449
|
+
out.key = hasKey(readText(path.join(r.zed, "keymap.json")));
|
|
377
450
|
break;
|
|
378
451
|
case "vscode":
|
|
379
452
|
case "cursor": {
|
|
@@ -410,7 +483,7 @@ export function editorStatus(ctx = {}) {
|
|
|
410
483
|
}
|
|
411
484
|
|
|
412
485
|
/** What a setup item adds, in words. */
|
|
413
|
-
export const ITEM_LABELS = { task: "export task", mcp: "AI tools" };
|
|
486
|
+
export const ITEM_LABELS = { task: "export task", key: "keyboard shortcut", mcp: "AI tools" };
|
|
414
487
|
|
|
415
488
|
/**
|
|
416
489
|
* Items of one editor that are not set up yet, given its editorStatus() entry.
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Add one entry to a JSON-with-comments file (Zed settings,
|
|
3
|
+
* keymap and tasks, VS Code tasks, MCP configs) without touching anything
|
|
4
|
+
* else: comments, trailing commas, key order and the user's own formatting
|
|
5
|
+
* stay exactly as they were. The new entry goes on its own lines after the
|
|
6
|
+
* last one, in the file's own indentation.
|
|
7
|
+
*/
|
|
8
|
+
import jsonc from "jsonc-parser";
|
|
9
|
+
|
|
10
|
+
const PARSE_OPTIONS = { allowTrailingComma: true, disallowComments: false };
|
|
11
|
+
|
|
12
|
+
/** Indentation and line ending the file already uses (2 spaces by default). */
|
|
13
|
+
export function detectFormatting(text) {
|
|
14
|
+
const indent = /^([ \t]+)\S/m.exec(text)?.[1] ?? " ";
|
|
15
|
+
return {
|
|
16
|
+
insertSpaces: !indent.startsWith("\t"),
|
|
17
|
+
tabSize: indent.startsWith("\t") ? 1 : indent.length,
|
|
18
|
+
eol: text.includes("\r\n") ? "\r\n" : "\n",
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {string} source current file content ("" for an empty file)
|
|
24
|
+
* @param {{at: (string|number)[], value: unknown, append?: boolean}} change
|
|
25
|
+
* `append`: add `value` to the array at `at` (created when missing);
|
|
26
|
+
* otherwise set the object key path `at` to `value`.
|
|
27
|
+
* @returns {string} the new content
|
|
28
|
+
* @throws {Error} when the file is not valid JSON(C) or has another shape
|
|
29
|
+
*/
|
|
30
|
+
export function mergeJsonc(source, { at, value, append = false }) {
|
|
31
|
+
// Keep a UTF-8 byte order mark (some Windows editors write one) but parse without it.
|
|
32
|
+
const bom = source.startsWith("") ? "" : "";
|
|
33
|
+
const out = mergeText(source.slice(bom.length), at, value, append);
|
|
34
|
+
verify(out, at, value, append);
|
|
35
|
+
return bom + out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function mergeText(text, at, value, append) {
|
|
39
|
+
const fo = detectFormatting(text);
|
|
40
|
+
const unit = fo.insertSpaces ? " ".repeat(fo.tabSize) : "\t";
|
|
41
|
+
|
|
42
|
+
// Only comments (or nothing): no document yet. Keep the comments, add one.
|
|
43
|
+
if (jsonc.stripComments(text).trim() === "") {
|
|
44
|
+
// Spread over lines as far as the entry itself (formatJson's own "top").
|
|
45
|
+
const doc = append ? nest(at, [value]) : nest(at, value);
|
|
46
|
+
const body = formatJson(doc, unit, at.length + 2).split("\n").join(fo.eol);
|
|
47
|
+
const head = text.trimEnd();
|
|
48
|
+
return `${head}${head ? fo.eol : ""}${body}${fo.eol}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const errors = [];
|
|
52
|
+
const root = jsonc.parseTree(text, errors, PARSE_OPTIONS);
|
|
53
|
+
if (errors.length || !root) {
|
|
54
|
+
const { error, offset } = errors[0] ?? { error: 0, offset: 0 };
|
|
55
|
+
const line = text.slice(0, offset).split("\n").length;
|
|
56
|
+
throw new Error(`it is not valid JSON (${jsonc.printParseErrorCode(error)} on line ${line})`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The list (append) or object (set) that receives the entry, and the
|
|
60
|
+
// deepest part of that path that exists already.
|
|
61
|
+
const container = append ? at : at.slice(0, -1);
|
|
62
|
+
let depth = 0;
|
|
63
|
+
let node = root;
|
|
64
|
+
for (; depth < container.length && node.type === "object"; depth++) {
|
|
65
|
+
const next = jsonc.findNodeAtLocation(node, [container[depth]]);
|
|
66
|
+
if (!next) break;
|
|
67
|
+
node = next;
|
|
68
|
+
}
|
|
69
|
+
const missing = container.slice(depth);
|
|
70
|
+
const wantType = missing.length || !append ? "object" : "array";
|
|
71
|
+
if (node.type !== wantType) {
|
|
72
|
+
const where = depth ? `"${container.slice(0, depth).join(".")}"` : "the file";
|
|
73
|
+
throw new Error(`${where} is not ${wantType === "array" ? "a list" : "an object"}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Setting a key that exists already: replace its value in place.
|
|
77
|
+
if (!append && !missing.length && jsonc.findNodeAtLocation(node, [at.at(-1)])) {
|
|
78
|
+
return formatInserted(text, jsonc.modify(text, at, value, {}), fo);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// What goes into `node`: a list item, or one key holding the rest of the path.
|
|
82
|
+
const keys = append ? missing : [...missing, at.at(-1)];
|
|
83
|
+
const leaf = append ? [value] : value;
|
|
84
|
+
const entry = keys.length ? { key: keys[0], value: nest(keys.slice(1), leaf) } : { value };
|
|
85
|
+
|
|
86
|
+
const head = entry.key === undefined ? "" : `${JSON.stringify(entry.key)}: `;
|
|
87
|
+
const last = node.children?.at(-1);
|
|
88
|
+
|
|
89
|
+
// Empty container ("[]", "{ // comment }"): the entry goes just before the
|
|
90
|
+
// closing bracket; anything already inside (comments) stays above it.
|
|
91
|
+
if (!last) {
|
|
92
|
+
const close = node.offset + node.length - 1;
|
|
93
|
+
const outer = lineIndent(text, node.offset);
|
|
94
|
+
const inner = outer + unit;
|
|
95
|
+
const before = text.slice(0, close).trimEnd();
|
|
96
|
+
return `${before}${fo.eol}${inner}${head}${pretty(entry.value, unit, inner, fo.eol, missing.length + 1)}${fo.eol}${outer}${text.slice(close)}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const after = lineAfter(text, last.offset + last.length);
|
|
100
|
+
if (after.sameLineClose) {
|
|
101
|
+
// One-line container ({ "a": 1 }): the library inserts it neatly.
|
|
102
|
+
const path = [...container.slice(0, depth), entry.key ?? -1];
|
|
103
|
+
return formatInserted(text, jsonc.modify(text, path, entry.value, { isArrayInsertion: entry.key === undefined }), fo);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Multi-line container: new lines after the last entry's line, so a comment
|
|
107
|
+
// at the end of that line stays with its entry. A trailing comma is kept
|
|
108
|
+
// as the file's style.
|
|
109
|
+
const indent = lineIndent(text, last.offset);
|
|
110
|
+
const added = `${fo.eol}${indent}${head}${pretty(entry.value, unit, indent, fo.eol, missing.length + 1)}${after.comma ? "," : ""}`;
|
|
111
|
+
const end = last.offset + last.length;
|
|
112
|
+
return after.comma
|
|
113
|
+
? text.slice(0, after.lineEnd) + added + text.slice(after.lineEnd)
|
|
114
|
+
: `${text.slice(0, end)},${text.slice(end, after.lineEnd)}${added}${text.slice(after.lineEnd)}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* From the end of the last entry: is there a comma, where does its line end
|
|
119
|
+
* (after any comment on it), and does the container close on that same line?
|
|
120
|
+
*/
|
|
121
|
+
function lineAfter(text, from) {
|
|
122
|
+
let i = from;
|
|
123
|
+
const skipSpaces = () => {
|
|
124
|
+
while (text[i] === " " || text[i] === "\t") i++;
|
|
125
|
+
};
|
|
126
|
+
skipSpaces();
|
|
127
|
+
const comma = text[i] === ",";
|
|
128
|
+
if (comma) i++;
|
|
129
|
+
skipSpaces();
|
|
130
|
+
// One-line block comments stay on the line; a multi-line one starts the next part.
|
|
131
|
+
while (text.startsWith("/*", i)) {
|
|
132
|
+
const close = text.indexOf("*/", i + 2);
|
|
133
|
+
if (close === -1 || text.slice(i, close).includes("\n")) break;
|
|
134
|
+
i = close + 2;
|
|
135
|
+
skipSpaces();
|
|
136
|
+
}
|
|
137
|
+
const sameLineClose = text[i] === "]" || text[i] === "}";
|
|
138
|
+
if (text.startsWith("//", i)) {
|
|
139
|
+
const nl = text.indexOf("\n", i);
|
|
140
|
+
i = nl === -1 ? text.length : nl;
|
|
141
|
+
if (text[i - 1] === "\r") i--;
|
|
142
|
+
}
|
|
143
|
+
return { comma, sameLineClose, lineEnd: i };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Leading whitespace of the line holding `offset`. */
|
|
147
|
+
function lineIndent(text, offset) {
|
|
148
|
+
const start = text.lastIndexOf("\n", offset - 1) + 1;
|
|
149
|
+
return /^[ \t]*/.exec(text.slice(start, offset))[0];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** JSON in the file's indent unit, every line after the first prefixed. */
|
|
153
|
+
function pretty(value, unit, prefix, eol, spread = 1) {
|
|
154
|
+
return formatJson(value, unit, spread).split("\n").join(eol + prefix);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Longest list or object written on one line, as Zed and VS Code files do. */
|
|
158
|
+
const INLINE_MAX = 60;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* JSON the way people write config files: the outer levels spread over
|
|
162
|
+
* lines, short lists and objects inside them on one line
|
|
163
|
+
* (`"cmd-k cmd-e": ["task::Spawn", { "task_name": "…" }]`).
|
|
164
|
+
* @param {unknown} value
|
|
165
|
+
* @param {string} [unit] one indentation level
|
|
166
|
+
* @param {number} [spread] how many levels are always spread over lines
|
|
167
|
+
*/
|
|
168
|
+
export function formatJson(value, unit = " ", spread = 2) {
|
|
169
|
+
const write = (v, indent, level) => {
|
|
170
|
+
if (v === null || typeof v !== "object") return JSON.stringify(v);
|
|
171
|
+
const isList = Array.isArray(v);
|
|
172
|
+
const parts = isList
|
|
173
|
+
? v.map((x) => write(x, indent + unit, level + 1))
|
|
174
|
+
: Object.entries(v).map(([k, x]) => `${JSON.stringify(k)}: ${write(x, indent + unit, level + 1)}`);
|
|
175
|
+
if (!parts.length) return isList ? "[]" : "{}";
|
|
176
|
+
const [open, close] = isList ? ["[", "]"] : ["{", "}"];
|
|
177
|
+
const inline = isList ? `[${parts.join(", ")}]` : `{ ${parts.join(", ")} }`;
|
|
178
|
+
if (level >= spread && !inline.includes("\n") && inline.length <= INLINE_MAX) return inline;
|
|
179
|
+
return `${open}\n${parts.map((p) => indent + unit + p).join(",\n")}\n${indent}${close}`;
|
|
180
|
+
};
|
|
181
|
+
return write(value, "", 0);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** `{a: {b: value}}` for `at = ["a", "b"]`. */
|
|
185
|
+
function nest(at, value) {
|
|
186
|
+
return at.reduceRight((inner, key) => ({ [key]: inner }), value);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Apply edits, then format only the text they inserted. */
|
|
190
|
+
function formatInserted(text, edits, fo) {
|
|
191
|
+
let out = jsonc.applyEdits(text, edits);
|
|
192
|
+
const ranges = [];
|
|
193
|
+
let shift = 0;
|
|
194
|
+
for (const edit of [...edits].sort((a, b) => a.offset - b.offset)) {
|
|
195
|
+
ranges.push({ offset: edit.offset + shift, length: edit.content.length });
|
|
196
|
+
shift += edit.content.length - edit.length;
|
|
197
|
+
}
|
|
198
|
+
for (const range of ranges.reverse()) out = jsonc.applyEdits(out, jsonc.format(out, range, fo));
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Never write a file that does not parse back to what was asked. */
|
|
203
|
+
function verify(out, at, value, append) {
|
|
204
|
+
const errors = [];
|
|
205
|
+
const data = jsonc.parse(out, errors, PARSE_OPTIONS);
|
|
206
|
+
let node = data;
|
|
207
|
+
for (const key of at) node = node?.[key];
|
|
208
|
+
const found = append ? Array.isArray(node) && node.some((v) => same(v, value)) : same(node, value);
|
|
209
|
+
if (errors.length || !found) throw new Error("the change could not be made safely");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
package/lib/studio-server.mjs
CHANGED
|
@@ -459,6 +459,11 @@ export async function startStudio(opts = {}) {
|
|
|
459
459
|
const item = editor?.items[index];
|
|
460
460
|
if (!item) throw new HttpError(404, "Unknown editor step.");
|
|
461
461
|
if (item.write === "print") throw new HttpError(409, "That file already exists: paste the snippet yourself.");
|
|
462
|
+
// Adding to an existing file is not idempotent: never add the same step twice.
|
|
463
|
+
const status = editorStatus().find((e) => e.id === id);
|
|
464
|
+
if (!pendingItems(editor, status).includes(item)) {
|
|
465
|
+
throw new HttpError(409, "Already set up.");
|
|
466
|
+
}
|
|
462
467
|
return send(res, 200, applySetupItem(item, { stdio: "ignore" }));
|
|
463
468
|
}
|
|
464
469
|
throw new HttpError(404, "Not found.");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markdown-pdf-export",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "Markdown to PDF with your header, footer, page numbers and logo. Design pages in Studio, export from VS Code, Zed, Cursor, Claude or any MCP client, or the command line.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"mcpName": "io.github.matinfo-tech/markdown-pdf-export",
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
"@vscode/markdown-it-katex": "^1.1.2",
|
|
47
47
|
"date-fns": "^4.4.0",
|
|
48
48
|
"highlight.js": "^11.12.0",
|
|
49
|
+
"jsonc-parser": "^3.3.1",
|
|
49
50
|
"katex": "^0.19.1",
|
|
50
51
|
"markdown-it": "^15.0.3",
|
|
51
52
|
"markdown-it-anchor": "^10.1.0",
|
package/studio/app.mjs
CHANGED
|
@@ -635,12 +635,13 @@ function copyButton(text) {
|
|
|
635
635
|
return button;
|
|
636
636
|
}
|
|
637
637
|
|
|
638
|
-
const KIND_LABEL = { task: "export task", mcp: "AI tools" };
|
|
638
|
+
const KIND_LABEL = { task: "export task", key: "keyboard shortcut", mcp: "AI tools" };
|
|
639
639
|
|
|
640
640
|
/**
|
|
641
641
|
* Editors found on this computer, one switch each (on by default). Already
|
|
642
|
-
* set-up parts are skipped
|
|
643
|
-
*
|
|
642
|
+
* set-up parts are skipped. Existing files get only the new entry (the server
|
|
643
|
+
* keeps a backup); a file it cannot read is left alone and the person gets
|
|
644
|
+
* the snippet to paste instead.
|
|
644
645
|
*/
|
|
645
646
|
function quickSetup(found) {
|
|
646
647
|
const box = el("section", { class: "quick", "aria-label": "Editors found on this computer" });
|