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,490 @@
1
+ /**
2
+ * @fileoverview Studio: a local page for designing the PDF layout with a live
3
+ * preview drawn by the real engine.
4
+ *
5
+ * This server writes files and starts a browser, so it is deliberately narrow:
6
+ * - listens on 127.0.0.1 only
7
+ * - every /api call needs the per-launch token in the x-studio-token header
8
+ * (a custom header also forces a CORS preflight, which is never answered)
9
+ * - Host and Origin must be this server (blocks DNS rebinding)
10
+ * - writes go to the settings file and its assets/ folder, nowhere else
11
+ * - exits by itself when the page has been closed for a while
12
+ */
13
+ import crypto from "node:crypto";
14
+ import fs from "node:fs";
15
+ import http from "node:http";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ import {
21
+ ALLOWED_PAGE_FORMATS,
22
+ HIGHLIGHT_STYLES,
23
+ SERVER_VERSION,
24
+ doctorMarkdownPdf,
25
+ exportMarkdownPdf,
26
+ setProjectDiscovery,
27
+ setSettings,
28
+ } from "../export.mjs";
29
+ import { CODE_THEMES, FONTS, FONT_LABELS, LOOKS, TEMPLATES, readTemplate } from "./looks.mjs";
30
+ import { SETTINGS_SCHEMA_URL } from "./settings-schema.mjs";
31
+ import {
32
+ PROJECT_SETTINGS_FILENAME,
33
+ deepMerge,
34
+ findProjectSettingsFile,
35
+ prepareSettings,
36
+ readSettingsFile,
37
+ userSettingsPath,
38
+ } from "./settings-loader.mjs";
39
+ import { EDITOR_IDS, applySetupItem, buildEditorSetup, launchSpec } from "./editor-setup.mjs";
40
+ import { IMAGE_FORMATS } from "./types.mjs";
41
+
42
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
43
+ const STUDIO_DIR = path.join(ROOT, "studio");
44
+
45
+ /** The only files the server hands out. */
46
+ const STATIC = {
47
+ "/": ["index.html", "text/html; charset=utf-8"],
48
+ "/style.css": ["style.css", "text/css; charset=utf-8"],
49
+ "/app.mjs": ["app.mjs", "text/javascript; charset=utf-8"],
50
+ "/model.mjs": ["model.mjs", "text/javascript; charset=utf-8"],
51
+ };
52
+
53
+ /** List of logo files Studio uploaded, kept next to them. */
54
+ const MANIFEST = ".studio-files.json";
55
+
56
+ const MAX_JSON = 1024 * 1024;
57
+ const MAX_LOGO = 5 * 1024 * 1024;
58
+
59
+ const SECURITY_HEADERS = {
60
+ "Content-Security-Policy":
61
+ "default-src 'self'; frame-src blob:; img-src 'self' blob: data:; object-src blob:; base-uri 'none'; form-action 'none'",
62
+ "X-Content-Type-Options": "nosniff",
63
+ "Referrer-Policy": "no-referrer",
64
+ "Cache-Control": "no-store",
65
+ };
66
+
67
+ class HttpError extends Error {
68
+ constructor(status, message) {
69
+ super(message);
70
+ this.status = status;
71
+ }
72
+ }
73
+
74
+ function sameToken(given, expected) {
75
+ if (typeof given !== "string") return false;
76
+ const a = Buffer.from(given);
77
+ const b = Buffer.from(expected);
78
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
79
+ }
80
+
81
+ function readBody(req, limit) {
82
+ return new Promise((resolve, reject) => {
83
+ const chunks = [];
84
+ let size = 0;
85
+ req.on("data", (chunk) => {
86
+ size += chunk.length;
87
+ if (size > limit) {
88
+ // Keep reading (and discarding) so the answer reaches the sender.
89
+ chunks.length = 0;
90
+ reject(new HttpError(413, `Too large (limit ${Math.round(limit / 1024 / 1024)} MB).`));
91
+ return;
92
+ }
93
+ if (size <= limit) chunks.push(chunk);
94
+ });
95
+ req.on("end", () => resolve(Buffer.concat(chunks)));
96
+ req.on("error", reject);
97
+ });
98
+ }
99
+
100
+ async function readJson(req) {
101
+ const body = await readBody(req, MAX_JSON);
102
+ try {
103
+ const parsed = JSON.parse(body.toString("utf8") || "{}");
104
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
105
+ return parsed;
106
+ } catch {
107
+ throw new HttpError(400, "Body must be a JSON object.");
108
+ }
109
+ }
110
+
111
+ /** Keep a logo file name harmless: no folders, plain characters, known image type. */
112
+ export function safeLogoName(name) {
113
+ const base = path.basename(String(name ?? "").replaceAll("\\", "/"));
114
+ const ext = path.extname(base).toLowerCase();
115
+ if (!IMAGE_FORMATS[ext]) return null;
116
+ const stem = base
117
+ .slice(0, -ext.length)
118
+ .replace(/[^A-Za-z0-9_-]+/g, "-")
119
+ .replace(/^-+|-+$/g, "")
120
+ .slice(0, 60);
121
+ return `${stem || "logo"}${ext}`;
122
+ }
123
+
124
+ /**
125
+ * Image files a header/footer points to that are not on disk. The engine
126
+ * skips them quietly; in Studio the person choosing a logo needs to be told.
127
+ * @param {object} settings prepared settings (paths already absolute)
128
+ * @returns {string[]}
129
+ */
130
+ export function missingImages(settings) {
131
+ return imageRefs(settings).filter((value) => path.isAbsolute(value) && !fs.existsSync(value));
132
+ }
133
+
134
+ /** Every image path a header/footer refers to (shorthand keys and structured elements). */
135
+ export function imageRefs(settings) {
136
+ const refs = [];
137
+ const add = (value) => {
138
+ if (typeof value === "string" && value) refs.push(value);
139
+ };
140
+ const walk = (node) => {
141
+ if (Array.isArray(node)) return node.forEach(walk);
142
+ if (node === null || typeof node !== "object") return;
143
+ if (node.type === "image") add(node.src);
144
+ for (const [key, value] of Object.entries(node)) {
145
+ if (/^(left|center|right)_image$/.test(key)) add(value);
146
+ else if (typeof value === "object") walk(value);
147
+ }
148
+ };
149
+ walk(settings?.header);
150
+ walk(settings?.footer);
151
+ return refs;
152
+ }
153
+
154
+ /**
155
+ * @param {object} [opts]
156
+ * @param {"user"|"project"} [opts.scope] which settings file Studio edits
157
+ * @param {string} [opts.cwd] project folder for scope "project"
158
+ * @param {string} [opts.file] Markdown file to preview (default: built-in sample)
159
+ * @param {number} [opts.port] 0 = any free port
160
+ * @param {number} [opts.idleMs] exit after this long without a request
161
+ * @param {() => void} [opts.onIdle]
162
+ * @returns {Promise<{url: string, port: number, token: string, settingsPath: string, close: () => Promise<void>}>}
163
+ */
164
+ export async function startStudio(opts = {}) {
165
+ const scope = opts.scope === "project" ? "project" : "user";
166
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
167
+ const settingsPath =
168
+ scope === "project" ? path.join(cwd, PROJECT_SETTINGS_FILENAME) : userSettingsPath();
169
+ const settingsDir = path.dirname(settingsPath);
170
+ const previewFile = opts.file ? path.resolve(opts.file) : path.join(STUDIO_DIR, "sample.md");
171
+ if (!fs.statSync(previewFile, { throwIfNoEntry: false })?.isFile()) {
172
+ throw new Error(`Cannot read ${previewFile}`);
173
+ }
174
+ const token = crypto.randomBytes(24).toString("hex");
175
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "mdpdf-studio-"));
176
+ const idleMs = opts.idleMs ?? 5 * 60 * 1000;
177
+ let port = 0;
178
+ let idleTimer = null;
179
+
180
+ const touch = () => {
181
+ clearTimeout(idleTimer);
182
+ if (idleMs > 0 && opts.onIdle) {
183
+ idleTimer = setTimeout(opts.onIdle, idleMs);
184
+ idleTimer.unref();
185
+ }
186
+ };
187
+
188
+ // ── logo files ─────────────────────────────────────────────────────────────
189
+ // Studio removes logos nobody uses any more, but only its own: files it
190
+ // uploaded (listed in a small manifest) and, in the user settings folder,
191
+ // files the saved layout pointed to. A project's assets/ folder may hold
192
+ // files Studio knows nothing about, so nothing else there is ever touched.
193
+ const assetsDir = path.join(settingsDir, "assets");
194
+ const manifestPath = path.join(assetsDir, MANIFEST);
195
+
196
+ const readManifest = () => {
197
+ try {
198
+ const list = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
199
+ return new Set(Array.isArray(list) ? list.filter((n) => typeof n === "string") : []);
200
+ } catch {
201
+ return new Set();
202
+ }
203
+ };
204
+ const writeManifest = (names) => {
205
+ if (names.size === 0) fs.rmSync(manifestPath, { force: true });
206
+ else fs.writeFileSync(manifestPath, `${JSON.stringify([...names].sort(), null, 2)}\n`);
207
+ };
208
+ /** File names inside assets/ that a settings object uses as header/footer images. */
209
+ const logosUsedBy = (settings) => {
210
+ const used = new Set();
211
+ for (const value of imageRefs(settings)) {
212
+ if (/^(~|@[\\/]|[a-z][a-z0-9+.-]*:)/i.test(value) && !path.isAbsolute(value)) continue;
213
+ const abs = path.resolve(settingsDir, value);
214
+ if (path.dirname(abs) === assetsDir) used.add(path.basename(abs));
215
+ }
216
+ return used;
217
+ };
218
+ const removeUnusedLogos = (before, after) => {
219
+ const manifest = readManifest();
220
+ const candidates = new Set(manifest);
221
+ if (scope === "user") for (const name of logosUsedBy(before)) candidates.add(name);
222
+ const keep = logosUsedBy(after);
223
+ const removed = [];
224
+ for (const name of candidates) {
225
+ if (keep.has(name)) continue;
226
+ manifest.delete(name);
227
+ const file = path.join(assetsDir, name);
228
+ const plainName = path.basename(name) === name && IMAGE_FORMATS[path.extname(name).toLowerCase()];
229
+ if (!plainName || !fs.lstatSync(file, { throwIfNoEntry: false })?.isFile()) continue;
230
+ fs.rmSync(file, { force: true });
231
+ removed.push(name);
232
+ }
233
+ if (fs.existsSync(assetsDir)) {
234
+ writeManifest(manifest);
235
+ if (fs.readdirSync(assetsDir).length === 0) fs.rmdirSync(assetsDir);
236
+ }
237
+ return removed;
238
+ };
239
+
240
+ // ── settings file ──────────────────────────────────────────────────────────
241
+ const readRaw = () => {
242
+ if (!fs.existsSync(settingsPath)) return { exists: false, raw: {}, error: null };
243
+ try {
244
+ const parsed = JSON.parse(fs.readFileSync(settingsPath, "utf8").replace(/^\uFEFF/, ""));
245
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
246
+ return { exists: true, raw: {}, error: "The file does not contain a JSON object." };
247
+ }
248
+ return { exists: true, raw: parsed, error: null };
249
+ } catch (error) {
250
+ return { exists: true, raw: {}, error: `The file is not valid JSON: ${error.message}` };
251
+ }
252
+ };
253
+
254
+ const state = () => {
255
+ const file = readRaw();
256
+ const templates = {};
257
+ for (const name of TEMPLATES) templates[name] = readTemplate(name);
258
+ const looks = {};
259
+ for (const [name, def] of Object.entries(LOOKS)) {
260
+ looks[name] = {
261
+ description: def.description,
262
+ margin: def.settings.margin ?? null,
263
+ highlight: def.settings.highlight_style ?? null,
264
+ };
265
+ }
266
+ return {
267
+ version: SERVER_VERSION,
268
+ scope,
269
+ settingsPath,
270
+ displayPath: settingsPath.startsWith(os.homedir())
271
+ ? `~${settingsPath.slice(os.homedir().length)}`
272
+ : settingsPath,
273
+ exists: file.exists,
274
+ fileError: file.error,
275
+ raw: file.raw,
276
+ looks,
277
+ fonts: FONTS,
278
+ fontLabels: FONT_LABELS,
279
+ codeThemes: CODE_THEMES.filter((t) => HIGHLIGHT_STYLES.has(t.file)),
280
+ pageFormats: [...ALLOWED_PAGE_FORMATS],
281
+ templates,
282
+ preview: {
283
+ name: path.basename(previewFile),
284
+ sample: !opts.file,
285
+ },
286
+ envOverride: Boolean((process.env.MARKDOWN_PDF_SETTINGS ?? "").trim()),
287
+ };
288
+ };
289
+
290
+ const save = (settings) => {
291
+ const before = readRaw().raw;
292
+ const rest = { ...settings };
293
+ delete rest.$schema;
294
+ const text = `${JSON.stringify({ $schema: SETTINGS_SCHEMA_URL, ...rest }, null, 2)}\n`;
295
+ fs.mkdirSync(settingsDir, { recursive: true });
296
+ let backup = null;
297
+ if (fs.existsSync(settingsPath)) {
298
+ backup = `${settingsPath}.bak`;
299
+ fs.copyFileSync(settingsPath, backup);
300
+ }
301
+ const tmp = `${settingsPath}.${process.pid}.tmp`;
302
+ fs.writeFileSync(tmp, text);
303
+ fs.renameSync(tmp, settingsPath);
304
+ // Only after the new layout is safely on disk: drop logos it replaced.
305
+ return { path: settingsPath, backup, removed: removeUnusedLogos(before, rest) };
306
+ };
307
+
308
+ const saveLogo = (name, bytes) => {
309
+ const safe = safeLogoName(name);
310
+ if (!safe) {
311
+ throw new HttpError(
312
+ 415,
313
+ `Use an image file (${Object.keys(IMAGE_FORMATS).join(", ")}).`,
314
+ );
315
+ }
316
+ if (bytes.length === 0) throw new HttpError(400, "The file is empty.");
317
+ const dir = assetsDir;
318
+ fs.mkdirSync(dir, { recursive: true });
319
+ const ext = path.extname(safe);
320
+ const stem = safe.slice(0, -ext.length);
321
+ // Never overwrite a different file: reuse an identical one or add a number.
322
+ for (let n = 0; n < 100; n++) {
323
+ const candidate = path.join(dir, n === 0 ? safe : `${stem}-${n}${ext}`);
324
+ if (!fs.existsSync(candidate)) {
325
+ fs.writeFileSync(candidate, bytes, { flag: "wx" });
326
+ writeManifest(readManifest().add(path.basename(candidate))); // ours to clean up later
327
+ return { path: `assets/${path.basename(candidate)}` };
328
+ }
329
+ if (fs.readFileSync(candidate).equals(bytes)) {
330
+ return { path: `assets/${path.basename(candidate)}` };
331
+ }
332
+ }
333
+ throw new HttpError(409, "Too many files with that name.");
334
+ };
335
+
336
+ // ── preview: one render at a time, the newest request wins ──────────────────
337
+ let rendering = Promise.resolve();
338
+ let renderSeq = 0;
339
+
340
+ const render = (settings) => {
341
+ const seq = ++renderSeq;
342
+ const job = rendering.then(async () => {
343
+ if (seq !== renderSeq) throw new HttpError(409, "Superseded by a newer preview.");
344
+ const { data } = prepareSettings(settings, settingsDir);
345
+ // Rebuild the layers the real export would use, with the draft in place
346
+ // of the file being edited.
347
+ let stack = data;
348
+ if (scope === "project") {
349
+ const user = fs.existsSync(userSettingsPath()) ? readSettingsFile(userSettingsPath()) : null;
350
+ if (user?.data) stack = deepMerge(user.data, data);
351
+ } else if (opts.file) {
352
+ const projectFile = findProjectSettingsFile(path.dirname(previewFile));
353
+ const project = projectFile ? readSettingsFile(projectFile) : null;
354
+ if (project?.data) stack = deepMerge(data, project.data);
355
+ }
356
+ const missing = missingImages(stack);
357
+ if (missing.length) {
358
+ throw new HttpError(422, `This image file was not found:\n${missing.join("\n")}`);
359
+ }
360
+ setProjectDiscovery(false);
361
+ setSettings(stack, settingsPath);
362
+ const output = path.join(workDir, `preview-${seq}.pdf`);
363
+ const started = Date.now();
364
+ await exportMarkdownPdf({
365
+ input_path: previewFile,
366
+ output_path: output,
367
+ open_after_export: false,
368
+ });
369
+ const pdf = fs.readFileSync(output);
370
+ fs.rmSync(output, { force: true });
371
+ return { pdf, ms: Date.now() - started };
372
+ });
373
+ rendering = job.catch(() => {});
374
+ return job;
375
+ };
376
+
377
+ // ── editors ────────────────────────────────────────────────────────────────
378
+ const editors = () => {
379
+ const launch = launchSpec(path.join(ROOT, "cli.mjs"));
380
+ return EDITOR_IDS.map((id) => buildEditorSetup(id, launch));
381
+ };
382
+
383
+ // ── http ───────────────────────────────────────────────────────────────────
384
+ const send = (res, status, body, type = "application/json; charset=utf-8", extra = {}) => {
385
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(type.startsWith("application/json") ? JSON.stringify(body) : body);
386
+ res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type, "Content-Length": payload.length, ...extra });
387
+ res.end(payload);
388
+ };
389
+
390
+ const api = async (req, res, route, query) => {
391
+ if (!sameToken(req.headers["x-studio-token"], token)) throw new HttpError(401, "Missing or wrong token.");
392
+ touch();
393
+
394
+ if (req.method === "GET" && route === "/api/state") return send(res, 200, state());
395
+ if (req.method === "GET" && route === "/api/editors") {
396
+ return send(
397
+ res,
398
+ 200,
399
+ editors().map((e) => ({
400
+ id: e.id,
401
+ name: e.name,
402
+ detected: e.detected,
403
+ items: e.items.map((i) => ({ label: i.label, file: i.file ?? null, snippet: i.snippet, write: i.write })),
404
+ })),
405
+ );
406
+ }
407
+ if (req.method === "GET" && route === "/api/check") {
408
+ const report = await doctorMarkdownPdf({});
409
+ return send(res, 200, { browser: report.browser });
410
+ }
411
+ if (req.method !== "POST") throw new HttpError(404, "Not found.");
412
+
413
+ if (route === "/api/ping") return send(res, 200, { ok: true });
414
+ if (route === "/api/preview") {
415
+ const { settings } = await readJson(req);
416
+ if (!settings || typeof settings !== "object") throw new HttpError(400, "settings is required.");
417
+ try {
418
+ const { pdf, ms } = await render(settings);
419
+ return send(res, 200, pdf, "application/pdf", { "X-Render-Ms": String(ms) });
420
+ } catch (error) {
421
+ if (error instanceof HttpError) throw error;
422
+ throw new HttpError(422, error instanceof Error ? error.message : String(error));
423
+ }
424
+ }
425
+ if (route === "/api/save") {
426
+ const { settings } = await readJson(req);
427
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
428
+ throw new HttpError(400, "settings is required.");
429
+ }
430
+ return send(res, 200, save(settings));
431
+ }
432
+ if (route === "/api/logo") {
433
+ const bytes = await readBody(req, MAX_LOGO);
434
+ return send(res, 200, saveLogo(query.get("name"), bytes));
435
+ }
436
+ if (route === "/api/editors/apply") {
437
+ const { id, index } = await readJson(req);
438
+ const editor = editors().find((e) => e.id === id);
439
+ const item = editor?.items[index];
440
+ if (!item) throw new HttpError(404, "Unknown editor step.");
441
+ if (item.write === "print") throw new HttpError(409, "That file already exists: paste the snippet yourself.");
442
+ return send(res, 200, applySetupItem(item, { stdio: "ignore" }));
443
+ }
444
+ throw new HttpError(404, "Not found.");
445
+ };
446
+
447
+ const server = http.createServer((req, res) => {
448
+ const allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
449
+ const origin = req.headers.origin;
450
+ const fail = (status, message) => send(res, status, { error: message });
451
+
452
+ if (!allowedHosts.has(req.headers.host ?? "")) return fail(403, "Wrong host.");
453
+ if (origin && !allowedHosts.has(origin.replace(/^http:\/\//, ""))) return fail(403, "Wrong origin.");
454
+ if (req.headers["sec-fetch-site"] === "cross-site") return fail(403, "Cross-site request.");
455
+
456
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
457
+ if (url.pathname.startsWith("/api/")) {
458
+ api(req, res, url.pathname, url.searchParams).catch((error) => {
459
+ if (res.headersSent) return res.end();
460
+ fail(error instanceof HttpError ? error.status : 500, error instanceof Error ? error.message : String(error));
461
+ });
462
+ return;
463
+ }
464
+ const entry = STATIC[url.pathname];
465
+ if (req.method !== "GET" || !entry) return fail(404, "Not found.");
466
+ send(res, 200, fs.readFileSync(path.join(STUDIO_DIR, entry[0])), entry[1]);
467
+ });
468
+
469
+ await new Promise((resolve, reject) => {
470
+ server.once("error", reject);
471
+ server.listen(opts.port ?? 0, "127.0.0.1", resolve);
472
+ });
473
+ port = server.address().port;
474
+ touch();
475
+
476
+ return {
477
+ url: `http://127.0.0.1:${port}/#${token}`,
478
+ port,
479
+ token,
480
+ settingsPath,
481
+ close: () =>
482
+ new Promise((resolve) => {
483
+ clearTimeout(idleTimer);
484
+ setProjectDiscovery(true);
485
+ fs.rmSync(workDir, { recursive: true, force: true });
486
+ server.closeAllConnections?.();
487
+ server.close(() => resolve());
488
+ }),
489
+ };
490
+ }