crossnote 0.9.38 → 0.9.40

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/out/cli/index.cjs CHANGED
@@ -2775,7 +2775,7 @@ var require_vega_min = __commonJS({
2775
2775
  function is(t2, e2) {
2776
2776
  null != t2 && "" !== t2 ? t2 == t2 && (++this.valid, this._ops.forEach(((n2) => n2.add(this, t2, e2)))) : ++this.missing;
2777
2777
  }
2778
- function os4(t2, e2) {
2778
+ function os5(t2, e2) {
2779
2779
  null != t2 && "" !== t2 ? t2 == t2 && (--this.valid, this._ops.forEach(((n2) => n2.rem(this, t2, e2)))) : --this.missing;
2780
2780
  }
2781
2781
  function as(t2) {
@@ -2795,7 +2795,7 @@ var require_vega_min = __commonJS({
2795
2795
  function o2(t3) {
2796
2796
  this._ops = r2, this._out = i2, this.cell = t3, this.init();
2797
2797
  }
2798
- return o2.prototype.init = rs, o2.prototype.add = is, o2.prototype.rem = os4, o2.prototype.set = as, o2.prototype.get = n2, o2.fields = t2.map(((t3) => t3.out)), o2;
2798
+ return o2.prototype.init = rs, o2.prototype.add = is, o2.prototype.rem = os5, o2.prototype.set = as, o2.prototype.get = n2, o2.fields = t2.map(((t3) => t3.out)), o2;
2799
2799
  }
2800
2800
  function ss(t2) {
2801
2801
  this._key = t2 ? l(t2) : _a, this.reset();
@@ -16102,7 +16102,7 @@ var require_vega_lite_min = __commonJS({
16102
16102
  const f2 = Va(l2, o2, r2, a2, n2.errorbar), d2 = l2.thickness, m2 = l2.size, p2 = { type: "tick", orient: s2, aria: false, ...void 0 !== d2 ? { thickness: d2 } : {}, ...void 0 !== m2 ? { size: m2 } : {} }, g2 = [...f2({ partName: "ticks", mark: p2, positionPrefix: "lower", extraEncoding: u2 }), ...f2({ partName: "ticks", mark: p2, positionPrefix: "upper", extraEncoding: u2 }), ...f2({ partName: "rule", mark: { type: "rule", ariaRoleDescription: "errorbar", ...void 0 !== d2 ? { size: d2 } : {} }, positionPrefix: "lower", endPositionPrefix: "upper", extraEncoding: u2 })];
16103
16103
  return { ...c2, transform: i2, ...g2.length > 1 ? { layer: g2 } : { ...g2[0] } };
16104
16104
  }
16105
- function os4(e2, t2) {
16105
+ function os5(e2, t2) {
16106
16106
  const { encoding: n2 } = e2;
16107
16107
  if ((function(e3) {
16108
16108
  return (Jo(e3.x) || Jo(e3.y)) && !Jo(e3.x2) && !Jo(e3.y2) && !Jo(e3.xError) && !Jo(e3.xError2) && !Jo(e3.yError) && !Jo(e3.yError2);
@@ -16145,7 +16145,7 @@ var require_vega_lite_min = __commonJS({
16145
16145
  function as(e2, t2, n2) {
16146
16146
  const { mark: i2, encoding: r2, params: o2, projection: a2, ...s2 } = e2, l2 = Zr(i2) ? i2 : { type: i2 };
16147
16147
  o2 && $i(Jn(t2));
16148
- const { orient: c2, inputType: u2 } = os4(e2, t2), { continuousAxisChannelDef: f2, continuousAxisChannelDef2: d2, continuousAxisChannelDefError: m2, continuousAxisChannelDefError2: p2, continuousAxis: g2 } = Ya(e2, c2, t2), { errorBarSpecificAggregate: h2, postAggregateCalculates: y2, tooltipSummary: v2, tooltipTitleWithFieldName: b2 } = (function(e3, t3, n3, i3, r3, o3, a3, s3) {
16148
+ const { orient: c2, inputType: u2 } = os5(e2, t2), { continuousAxisChannelDef: f2, continuousAxisChannelDef2: d2, continuousAxisChannelDefError: m2, continuousAxisChannelDefError2: p2, continuousAxis: g2 } = Ya(e2, c2, t2), { errorBarSpecificAggregate: h2, postAggregateCalculates: y2, tooltipSummary: v2, tooltipTitleWithFieldName: b2 } = (function(e3, t3, n3, i3, r3, o3, a3, s3) {
16149
16149
  let l3 = [], c3 = [];
16150
16150
  const u3 = t3.field;
16151
16151
  let f3, d3 = false;
@@ -23364,12 +23364,12 @@ __export(index_exports, {
23364
23364
  });
23365
23365
  module.exports = __toCommonJS(index_exports);
23366
23366
  var fs22 = __toESM(require("fs"));
23367
- var path26 = __toESM(require("path"));
23367
+ var path27 = __toESM(require("path"));
23368
23368
 
23369
23369
  // src/serve/index.ts
23370
23370
  var fs21 = __toESM(require("fs"));
23371
23371
  var http = __toESM(require("http"));
23372
- var path25 = __toESM(require("path"));
23372
+ var path26 = __toESM(require("path"));
23373
23373
  var import_url2 = require("url");
23374
23374
  var import_crypto_js2 = require("crypto-js");
23375
23375
 
@@ -23651,7 +23651,7 @@ async function smmsUploadImage(filePath) {
23651
23651
  }
23652
23652
  }
23653
23653
  function qiniuUploadImage(filePath, AccessKey, SecretKey, Bucket, Domain) {
23654
- return new Promise((resolve20, reject) => {
23654
+ return new Promise((resolve21, reject) => {
23655
23655
  if (!AccessKey) {
23656
23656
  return reject("Error: Qiniu AccessKey is missing");
23657
23657
  }
@@ -23684,7 +23684,7 @@ function qiniuUploadImage(filePath, AccessKey, SecretKey, Bucket, Domain) {
23684
23684
  if (respInfo.statusCode === 200) {
23685
23685
  const bucketManager = new qiniu.rs.BucketManager(mac, config);
23686
23686
  const url = bucketManager.publicDownloadUrl(Domain, key);
23687
- return resolve20(url);
23687
+ return resolve21(url);
23688
23688
  } else {
23689
23689
  return reject(respInfo.error);
23690
23690
  }
@@ -23749,8 +23749,8 @@ function openFile(filePath) {
23749
23749
  }
23750
23750
  }
23751
23751
  function openFileInWSL(filePath) {
23752
- const attempt = (spawn5, fallback) => {
23753
- const child = spawn5();
23752
+ const attempt = (spawn7, fallback) => {
23753
+ const child = spawn7();
23754
23754
  let settled = false;
23755
23755
  const tryFallback = () => {
23756
23756
  if (!settled) {
@@ -23818,8 +23818,8 @@ var crossnoteBuildDirectory_ = (() => {
23818
23818
  return "";
23819
23819
  }
23820
23820
  })();
23821
- function setCrossnoteBuildDirectory(path27) {
23822
- crossnoteBuildDirectory_ = path27;
23821
+ function setCrossnoteBuildDirectory(path28) {
23822
+ crossnoteBuildDirectory_ = path28;
23823
23823
  }
23824
23824
  function getCrossnoteBuildDirectory() {
23825
23825
  return crossnoteBuildDirectory_;
@@ -23933,12 +23933,12 @@ function replaceVariablesInString(inputString, replacements = {}) {
23933
23933
 
23934
23934
  // src/markdown-engine/index.ts
23935
23935
  var cheerio3 = __toESM(require("cheerio"));
23936
- var import_child_process13 = require("child_process");
23936
+ var import_child_process11 = require("child_process");
23937
23937
  var import_copy_anything = require("copy-anything");
23938
23938
  var import_crypto_js = __toESM(require("crypto-js"));
23939
23939
  var fs14 = __toESM(require("fs"));
23940
23940
  var import_html_escaper13 = require("html-escaper");
23941
- var path18 = __toESM(require("path"));
23941
+ var path19 = __toESM(require("path"));
23942
23942
  var YAML7 = __toESM(require("yaml"));
23943
23943
 
23944
23944
  // src/converters/ebook-convert.ts
@@ -24077,7 +24077,7 @@ function processPDF(config = {}, args) {
24077
24077
  }
24078
24078
  }
24079
24079
  function ebookConvert(src, dest, config = {}) {
24080
- return new Promise((resolve20, reject) => {
24080
+ return new Promise((resolve21, reject) => {
24081
24081
  const args = [
24082
24082
  src,
24083
24083
  dest,
@@ -24106,7 +24106,7 @@ function ebookConvert(src, dest, config = {}) {
24106
24106
  if (error2) {
24107
24107
  return reject(error2.toString());
24108
24108
  } else {
24109
- return resolve20();
24109
+ return resolve21();
24110
24110
  }
24111
24111
  });
24112
24112
  }).catch((error) => {
@@ -24567,7 +24567,7 @@ function toSVGMarkdown(pdfFilePath, {
24567
24567
  svgWidth,
24568
24568
  svgHeight
24569
24569
  }) {
24570
- return new Promise((resolve20, reject) => {
24570
+ return new Promise((resolve21, reject) => {
24571
24571
  if (!svgDirectoryPath) {
24572
24572
  if (!SVG_DIRECTORY_PATH) {
24573
24573
  SVG_DIRECTORY_PATH = mkdirSync("crossnote_pdf");
@@ -24629,7 +24629,7 @@ function toSVGMarkdown(pdfFilePath, {
24629
24629
  }
24630
24630
  }
24631
24631
  });
24632
- return resolve20(svgMarkdown);
24632
+ return resolve21(svgMarkdown);
24633
24633
  });
24634
24634
  }
24635
24635
  });
@@ -24949,7 +24949,7 @@ async function loadFile(filePath, {
24949
24949
  }
24950
24950
  if (filePath.endsWith(".less")) {
24951
24951
  const data = await notebook.fs.readFile(filePath);
24952
- return await new Promise((resolve20, reject) => {
24952
+ return await new Promise((resolve21, reject) => {
24953
24953
  less.render(
24954
24954
  data,
24955
24955
  { paths: [path5.dirname(filePath)] },
@@ -24957,7 +24957,7 @@ async function loadFile(filePath, {
24957
24957
  if (error) {
24958
24958
  return reject(error);
24959
24959
  } else {
24960
- return resolve20(output?.css || "");
24960
+ return resolve21(output?.css || "");
24961
24961
  }
24962
24962
  }
24963
24963
  );
@@ -25885,7 +25885,7 @@ function toSVGMarkdown2(texFilePath, {
25885
25885
  svgWidth,
25886
25886
  svgHeight
25887
25887
  }) {
25888
- return new Promise((resolve20, reject) => {
25888
+ return new Promise((resolve21, reject) => {
25889
25889
  const task = (0, import_child_process3.spawn)(latexEngine, [texFilePath], {
25890
25890
  cwd: path6.dirname(texFilePath)
25891
25891
  });
@@ -25919,7 +25919,7 @@ function toSVGMarkdown2(texFilePath, {
25919
25919
  svgHeight
25920
25920
  }).then((svgMarkdown) => {
25921
25921
  cleanUpFiles(texFilePath);
25922
- return resolve20(svgMarkdown);
25922
+ return resolve21(svgMarkdown);
25923
25923
  }).catch((error) => {
25924
25924
  cleanUpFiles(texFilePath);
25925
25925
  return reject(error);
@@ -26024,7 +26024,7 @@ except Exception:
26024
26024
  if (!findInputFileMacro && !normalizedAttributes["stdin"]) {
26025
26025
  args.push(savePath);
26026
26026
  }
26027
- return await new Promise((resolve20) => {
26027
+ return await new Promise((resolve21) => {
26028
26028
  const task = (0, import_child_process4.spawn)(cmd, args, { cwd: fileDirectoryPath });
26029
26029
  if (normalizedAttributes["stdin"]) {
26030
26030
  task.stdin.write(content);
@@ -26043,7 +26043,7 @@ except Exception:
26043
26043
  task.on("close", async () => {
26044
26044
  await (0, import_promises.unlink)(savePath);
26045
26045
  const data = Buffer.concat(chunks).toString();
26046
- resolve20(data);
26046
+ resolve21(data);
26047
26047
  });
26048
26048
  });
26049
26049
  }
@@ -26114,8 +26114,8 @@ var PlantUMLTask = class {
26114
26114
  this.startTask();
26115
26115
  }
26116
26116
  generateSVG(content) {
26117
- return new Promise((resolve20) => {
26118
- this.callbacks.push(resolve20);
26117
+ return new Promise((resolve21) => {
26118
+ this.callbacks.push(resolve21);
26119
26119
  this.task?.stdin.write(content + "\n");
26120
26120
  });
26121
26121
  }
@@ -26305,8 +26305,8 @@ async function svgElementToPNGFile(svgElement, pngFilePath, imageMagickPath = ""
26305
26305
  }
26306
26306
 
26307
26307
  // src/tools/mermaid.ts
26308
- var import_child_process7 = require("child_process");
26309
26308
  var fs7 = __toESM(require("fs"));
26309
+ var import_cross_spawn = __toESM(require("cross-spawn"));
26310
26310
  async function mermaidToPNG(mermaidCode, pngFilePath, projectDirectoryPath, themeName) {
26311
26311
  const info = await tempOpen({
26312
26312
  prefix: "crossnote-mermaid",
@@ -26317,7 +26317,7 @@ async function mermaidToPNG(mermaidCode, pngFilePath, projectDirectoryPath, them
26317
26317
  themeName = "null";
26318
26318
  }
26319
26319
  try {
26320
- (0, import_child_process7.execFileSync)(
26320
+ const result = import_cross_spawn.default.sync(
26321
26321
  "npx",
26322
26322
  [
26323
26323
  "-p",
@@ -26331,10 +26331,18 @@ async function mermaidToPNG(mermaidCode, pngFilePath, projectDirectoryPath, them
26331
26331
  pngFilePath
26332
26332
  ],
26333
26333
  {
26334
- shell: true,
26335
- cwd: projectDirectoryPath
26334
+ cwd: projectDirectoryPath,
26335
+ // Match the old `execFileSync` behavior: the CLI's errors stream to
26336
+ // our stderr; neither stream is read here.
26337
+ stdio: ["ignore", "ignore", "inherit"]
26336
26338
  }
26337
26339
  );
26340
+ if (result.error) {
26341
+ throw result.error;
26342
+ }
26343
+ if (result.status !== 0) {
26344
+ throw new Error(`mermaid CLI exited with code ${result.status}`);
26345
+ }
26338
26346
  return pngFilePath;
26339
26347
  } catch (error) {
26340
26348
  throw new Error(
@@ -26369,8 +26377,8 @@ Please make sure you have libvips installed.`,
26369
26377
  }
26370
26378
 
26371
26379
  // src/tools/wavedrom.ts
26372
- var import_child_process8 = require("child_process");
26373
26380
  var fs8 = __toESM(require("fs"));
26381
+ var import_cross_spawn2 = __toESM(require("cross-spawn"));
26374
26382
  async function render3(wavedromCode, projectDirectoryPath) {
26375
26383
  const info = await tempOpen({
26376
26384
  prefix: "crossnote-wavedrom",
@@ -26378,11 +26386,19 @@ async function render3(wavedromCode, projectDirectoryPath) {
26378
26386
  });
26379
26387
  await fs8.writeFileSync(info.fd, wavedromCode);
26380
26388
  try {
26381
- const svg = (await (0, import_child_process8.execFileSync)("npx", ["wavedrom-cli", "-i", info.path], {
26382
- shell: true,
26383
- cwd: projectDirectoryPath
26384
- })).toString("utf-8");
26385
- return svg;
26389
+ const result = import_cross_spawn2.default.sync("npx", ["wavedrom-cli", "-i", info.path], {
26390
+ cwd: projectDirectoryPath,
26391
+ // stdout carries the SVG; stderr streams to our console like the old
26392
+ // `execFileSync` call did.
26393
+ stdio: ["ignore", "pipe", "inherit"]
26394
+ });
26395
+ if (result.error) {
26396
+ throw result.error;
26397
+ }
26398
+ if (result.status !== 0) {
26399
+ throw new Error(`wavedrom CLI exited with code ${result.status}`);
26400
+ }
26401
+ return result.stdout.toString("utf-8");
26386
26402
  } catch (error) {
26387
26403
  throw new Error(
26388
26404
  "wavedrom CLI is required to be installed.\nCheck http://github.com/wavedrom/cli for more information.",
@@ -26934,7 +26950,7 @@ async function markdownConvert(text, {
26934
26950
  mathBlockDelimiters: notebook.config.mathBlockDelimiters,
26935
26951
  mathRenderingOnlineService: notebook.config.mathRenderingOnlineService
26936
26952
  }) : text;
26937
- return await new Promise((resolve20, reject) => {
26953
+ return await new Promise((resolve21, reject) => {
26938
26954
  (0, import_mkdirp2.mkdirp)(imageDirectoryPath).then(() => {
26939
26955
  processGraphs(text, {
26940
26956
  fileDirectoryPath,
@@ -26957,7 +26973,7 @@ async function markdownConvert(text, {
26957
26973
  if (error2) {
26958
26974
  return reject(error2.toString());
26959
26975
  }
26960
- return resolve20(outputFilePath);
26976
+ return resolve21(outputFilePath);
26961
26977
  }
26962
26978
  );
26963
26979
  });
@@ -26970,7 +26986,7 @@ async function markdownConvert(text, {
26970
26986
  }
26971
26987
 
26972
26988
  // src/converters/pandoc-convert.ts
26973
- var import_child_process9 = require("child_process");
26989
+ var import_child_process7 = require("child_process");
26974
26990
  var fs10 = __toESM(require("fs"));
26975
26991
  var mkdirp3 = __toESM(require("mkdirp"));
26976
26992
  var path11 = __toESM(require("path"));
@@ -27278,8 +27294,8 @@ async function pandocConvert(text, {
27278
27294
  notebook
27279
27295
  });
27280
27296
  await mkdirp3.sync(path11.dirname(outputFilePath));
27281
- return await new Promise((resolve20, reject) => {
27282
- const program = (0, import_child_process9.execFile)(
27297
+ return await new Promise((resolve21, reject) => {
27298
+ const program = (0, import_child_process7.execFile)(
27283
27299
  notebook.config.pandocPath,
27284
27300
  args,
27285
27301
  { cwd: fileDirectoryPath },
@@ -27287,7 +27303,7 @@ async function pandocConvert(text, {
27287
27303
  if (error) {
27288
27304
  return reject(error.toString());
27289
27305
  } else {
27290
- return resolve20(outputFilePath);
27306
+ return resolve21(outputFilePath);
27291
27307
  }
27292
27308
  }
27293
27309
  );
@@ -27296,10 +27312,10 @@ async function pandocConvert(text, {
27296
27312
  }
27297
27313
 
27298
27314
  // src/converters/prince-convert.ts
27299
- var import_child_process10 = require("child_process");
27315
+ var import_child_process8 = require("child_process");
27300
27316
  function princeConvert(src, dest) {
27301
- return new Promise((resolve20, reject) => {
27302
- (0, import_child_process10.execFile)(
27317
+ return new Promise((resolve21, reject) => {
27318
+ (0, import_child_process8.execFile)(
27303
27319
  "prince",
27304
27320
  [src, "--javascript", "-o", dest],
27305
27321
  (error) => {
@@ -27310,17 +27326,86 @@ function princeConvert(src, dest) {
27310
27326
  }
27311
27327
  return reject(errorMessage);
27312
27328
  }
27313
- return resolve20();
27329
+ return resolve21();
27314
27330
  }
27315
27331
  );
27316
27332
  });
27317
27333
  }
27318
27334
 
27335
+ // src/lib/css-urls.ts
27336
+ var path12 = __toESM(require("path"));
27337
+ var ABSOLUTE_URL = /^(data:|https?:|file:|\/\/)/i;
27338
+ var CSS_URL = /url\(\s*(['"]?)([^'")]+)\1\s*\)(\s*format\([^)]+\))?/gi;
27339
+ var ABSOLUTE_FS_PATH = /^(\/|[A-Za-z]:[\\/])/;
27340
+ async function resolveRelativeCssUrls(css, baseDir, exists) {
27341
+ const root = path12.resolve(baseDir);
27342
+ const candidates = [];
27343
+ css.replace(CSS_URL, (_whole, _quote, rawUrl) => {
27344
+ candidates.push(rawUrl.trim());
27345
+ return "";
27346
+ });
27347
+ const resolutions = await Promise.all(
27348
+ candidates.map(async (url) => {
27349
+ if (!url || url.startsWith("#") || ABSOLUTE_URL.test(url)) {
27350
+ return null;
27351
+ }
27352
+ if (ABSOLUTE_FS_PATH.test(url)) {
27353
+ return null;
27354
+ }
27355
+ const [, filePart, suffix = ""] = url.match(/^([^?#]*)([?#].*)?$/) ?? [];
27356
+ if (!filePart) {
27357
+ return null;
27358
+ }
27359
+ const resolved = path12.resolve(baseDir, filePart);
27360
+ if (resolved !== root && !resolved.startsWith(root + path12.sep)) {
27361
+ return null;
27362
+ }
27363
+ if (!await exists(resolved)) {
27364
+ return null;
27365
+ }
27366
+ return resolved + suffix;
27367
+ })
27368
+ );
27369
+ let i = 0;
27370
+ return css.replace(
27371
+ CSS_URL,
27372
+ (whole, _quote, _rawUrl, formatPart = "") => {
27373
+ const resolved = resolutions[i++];
27374
+ if (resolved === null) {
27375
+ return whole;
27376
+ }
27377
+ return `url("${escapeCssUrl(resolved)}")${formatPart}`;
27378
+ }
27379
+ );
27380
+ }
27381
+ function mapAbsoluteCssUrls(css, toUrl) {
27382
+ return css.replace(
27383
+ CSS_URL,
27384
+ (whole, _quote, rawUrl, formatPart = "") => {
27385
+ const url = rawUrl.trim();
27386
+ if (ABSOLUTE_URL.test(url) || !ABSOLUTE_FS_PATH.test(url)) {
27387
+ return whole;
27388
+ }
27389
+ const [, filePart, suffix = ""] = url.match(/^([^?#]*)([?#].*)?$/) ?? [];
27390
+ if (!filePart) {
27391
+ return whole;
27392
+ }
27393
+ return `url("${escapeCssUrl(toUrl(unescapeCssUrl(filePart)) + suffix)}")${formatPart}`;
27394
+ }
27395
+ );
27396
+ }
27397
+ function escapeCssUrl(value) {
27398
+ return value.replace(/(["\\])/g, "\\$1").replace(/\n/g, "");
27399
+ }
27400
+ function unescapeCssUrl(value) {
27401
+ return value.replace(/\\(["\\])/g, "$1");
27402
+ }
27403
+
27319
27404
  // src/notebook/index.ts
27320
27405
  var import_async_mutex = require("async-mutex");
27321
27406
  var caseAnything = __toESM(require("case-anything"));
27322
27407
  var import_ignore = __toESM(require("ignore"));
27323
- var import_child_process11 = require("child_process");
27408
+ var import_child_process9 = require("child_process");
27324
27409
  var import_markdown_it = __toESM(require("markdown-it"));
27325
27410
  var import_markdown_it_abbr = __toESM(require("markdown-it-abbr"));
27326
27411
  var import_markdown_it_deflist = __toESM(require("markdown-it-deflist"));
@@ -27328,7 +27413,8 @@ var import_markdown_it_footnote = __toESM(require("markdown-it-footnote"));
27328
27413
  var import_markdown_it_mark = __toESM(require("markdown-it-mark"));
27329
27414
  var import_markdown_it_sub = __toESM(require("markdown-it-sub"));
27330
27415
  var import_markdown_it_sup = __toESM(require("markdown-it-sup"));
27331
- var path14 = __toESM(require("path"));
27416
+ var os = __toESM(require("os"));
27417
+ var path15 = __toESM(require("path"));
27332
27418
  var import_vscode_uri = require("vscode-uri");
27333
27419
 
27334
27420
  // src/renderers/parse-math.ts
@@ -31061,7 +31147,7 @@ var widget_default = (md, notebook) => {
31061
31147
  };
31062
31148
 
31063
31149
  // src/custom-markdown-it-features/wikilink.ts
31064
- var path12 = __toESM(require("path"));
31150
+ var path13 = __toESM(require("path"));
31065
31151
  var wikilink_default = (md, notebook) => {
31066
31152
  md.inline.ruler.before("autolink", "wikilink", (state, silent) => {
31067
31153
  if (!notebook.config.enableWikiLinkSyntax || !state.src.startsWith("[[", state.pos)) {
@@ -31106,9 +31192,9 @@ var wikilink_default = (md, notebook) => {
31106
31192
  filePart,
31107
31193
  notebook.currentRenderFilePath
31108
31194
  );
31109
- const currentFileDir = path12.dirname(notebook.currentRenderFilePath).replace(/\\/g, "/");
31195
+ const currentFileDir = path13.dirname(notebook.currentRenderFilePath).replace(/\\/g, "/");
31110
31196
  const resolvedNorm = resolvedPath.replace(/\\/g, "/");
31111
- const fileRelativeHref = path12.posix.relative(currentFileDir, resolvedNorm);
31197
+ const fileRelativeHref = path13.posix.relative(currentFileDir, resolvedNorm);
31112
31198
  const resolvedLink = fileRelativeHref + fragment;
31113
31199
  const displayText = content.includes("|") ? text : formatWikilinkDisplay(text);
31114
31200
  return `<a href="${md.utils.escapeHtml(resolvedLink)}">${md.utils.escapeHtml(
@@ -31145,7 +31231,7 @@ function formatWikilinkDisplay(raw) {
31145
31231
  // src/notebook/config-helper.ts
31146
31232
  var fs11 = __toESM(require("fs"));
31147
31233
  var less2 = __toESM(require("less"));
31148
- var path13 = __toESM(require("path"));
31234
+ var path14 = __toESM(require("path"));
31149
31235
 
31150
31236
  // src/lib/js-sandbox.ts
31151
31237
  var import_quickjs_singlefile_cjs_release_sync = __toESM(require("@jitl/quickjs-singlefile-cjs-release-sync"));
@@ -31458,7 +31544,7 @@ async function loadConfigsInDirectory(directoryPath, fileSystem, createDirectory
31458
31544
  return loadedConfig;
31459
31545
  }
31460
31546
  async function getGlobalStyles(configPath, fs23) {
31461
- const globalLessPath = path13.join(configPath, "./style.less");
31547
+ const globalLessPath = path14.join(configPath, "./style.less");
31462
31548
  let fileContent;
31463
31549
  try {
31464
31550
  fileContent = await fs23.readFile(globalLessPath);
@@ -31474,7 +31560,7 @@ async function getGlobalStyles(configPath, fs23) {
31474
31560
  `;
31475
31561
  await fs23.writeFile(globalLessPath, fileContent);
31476
31562
  }
31477
- return await new Promise((resolve20) => {
31563
+ return await new Promise((resolve21) => {
31478
31564
  const generateErrorMessage = (error) => {
31479
31565
  return `html body:before {
31480
31566
  content: "Failed to compile \`style.less\`. ${error}" !important;
@@ -31484,19 +31570,25 @@ async function getGlobalStyles(configPath, fs23) {
31484
31570
  };
31485
31571
  less2.render(
31486
31572
  fileContent,
31487
- { paths: [path13.dirname(globalLessPath)] },
31573
+ { paths: [path14.dirname(globalLessPath)] },
31488
31574
  (error, output) => {
31489
31575
  if (error) {
31490
- return resolve20(generateErrorMessage(error));
31576
+ return resolve21(generateErrorMessage(error));
31491
31577
  } else {
31492
- return resolve20(output?.css || "");
31578
+ return resolve21(
31579
+ resolveRelativeCssUrls(
31580
+ output?.css || "",
31581
+ path14.dirname(globalLessPath),
31582
+ (filePath) => fs23.exists(filePath)
31583
+ )
31584
+ );
31493
31585
  }
31494
31586
  }
31495
31587
  );
31496
31588
  });
31497
31589
  }
31498
31590
  async function getHeaderIncludes(configPath, fs23) {
31499
- const headerIncludesPath = path13.join(configPath, "./head.html");
31591
+ const headerIncludesPath = path14.join(configPath, "./head.html");
31500
31592
  let fileContent;
31501
31593
  try {
31502
31594
  fileContent = await fs23.readFile(headerIncludesPath);
@@ -31512,7 +31604,7 @@ async function getHeaderIncludes(configPath, fs23) {
31512
31604
  return fileContent;
31513
31605
  }
31514
31606
  async function getConfigs(configPath, fs23) {
31515
- const configScriptPath = path13.join(configPath, "./config.js");
31607
+ const configScriptPath = path14.join(configPath, "./config.js");
31516
31608
  const setupDefaultConfigScript = async () => {
31517
31609
  const defaultKatexConfig = getDefaultKatexConfig();
31518
31610
  const defaultMathjaxConfig = getDefaultMathjaxConfig();
@@ -31551,7 +31643,7 @@ async function getConfigs(configPath, fs23) {
31551
31643
  }
31552
31644
  async function getParserConfig(configPath, fs23) {
31553
31645
  const defaultParserConfig = getDefaultParserConfig();
31554
- const parserConfigPath = path13.join(configPath, "./parser.js");
31646
+ const parserConfigPath = path14.join(configPath, "./parser.js");
31555
31647
  if (await fs23.exists(parserConfigPath)) {
31556
31648
  try {
31557
31649
  const script = await fs23.readFile(parserConfigPath);
@@ -31924,6 +32016,13 @@ var defaultMarkdownItConfig = {
31924
32016
  sourceMap: true
31925
32017
  // Enable source map
31926
32018
  };
32019
+ var OVERSIZED_WALK_WARN_THRESHOLD = 1e4;
32020
+ function isSamePath(a, b) {
32021
+ if (process.platform === "win32") {
32022
+ return a.toLowerCase() === b.toLowerCase();
32023
+ }
32024
+ return a === b;
32025
+ }
31927
32026
  var Notebook = class _Notebook {
31928
32027
  constructor() {
31929
32028
  /**
@@ -31958,10 +32057,19 @@ var Notebook = class _Notebook {
31958
32057
  this.notes = {};
31959
32058
  this.hasLoadedNotes = false;
31960
32059
  /**
31961
- * Whether `skipIndexingIfFilesystemRoot` has already warned for this
32060
+ * Whether `skipIndexingIfRootIsRefused` has already warned for this
31962
32061
  * notebook, so the refusal is logged once per instance.
31963
32062
  */
31964
- this.filesystemRootWarned = false;
32063
+ this.refusedRootWarned = false;
32064
+ /**
32065
+ * Filesystem entries stat'ed by the note-index walk currently running
32066
+ * (or most recently finished). Reset by `refreshNotes` /
32067
+ * `refreshNotesIncremental` — both run under `refreshNotesMutex`, so
32068
+ * concurrent walks cannot interleave counts.
32069
+ */
32070
+ this.walkedEntriesThisRefresh = 0;
32071
+ /** Whether the oversized-walk warning already fired for this notebook. */
32072
+ this.oversizedWalkWarned = false;
31965
32073
  /**
31966
32074
  * The notebook-relative path of the note currently being rendered.
31967
32075
  * Set by MarkdownEngine.parseMD() before calling renderMarkdown().
@@ -32027,7 +32135,7 @@ var Notebook = class _Notebook {
32027
32135
  fs: fs23
32028
32136
  }) {
32029
32137
  const uri = import_vscode_uri.URI.parse(notebookPath);
32030
- if (!path14.isAbsolute(uri.fsPath) || uri.path.startsWith("/./")) {
32138
+ if (!path15.isAbsolute(uri.fsPath) || uri.path.startsWith("/./")) {
32031
32139
  throw new Error(
32032
32140
  `\`notebookPath\`: "${notebookPath}" must be an absolute path`
32033
32141
  );
@@ -32048,7 +32156,7 @@ var Notebook = class _Notebook {
32048
32156
  }
32049
32157
  async initConfig(config) {
32050
32158
  const extraConfig = await loadConfigsInDirectory(
32051
- path14.join(this.notebookPath.fsPath, "./.crossnote"),
32159
+ path15.join(this.notebookPath.fsPath, "./.crossnote"),
32052
32160
  this.fs
32053
32161
  );
32054
32162
  this.config = {
@@ -32206,7 +32314,7 @@ var Notebook = class _Notebook {
32206
32314
  let html;
32207
32315
  if (binaryPath) {
32208
32316
  const args = this.buildMarkdownYoBinaryArgs(renderOpts);
32209
- html = (0, import_child_process11.execFileSync)(binaryPath, args, {
32317
+ html = (0, import_child_process9.execFileSync)(binaryPath, args, {
32210
32318
  input: markdown,
32211
32319
  encoding: "utf8",
32212
32320
  maxBuffer: 256 * 1024 * 1024
@@ -32461,7 +32569,7 @@ var Notebook = class _Notebook {
32461
32569
  const fragmentMarker = rawLink.match(/[#^]/);
32462
32570
  const fileLink = fragmentMarker ? rawLink.slice(0, fragmentMarker.index) : rawLink;
32463
32571
  const fragment = fragmentMarker ? rawLink.slice(fragmentMarker.index) : "";
32464
- const ext = path14.extname(fileLink);
32572
+ const ext = path15.extname(fileLink);
32465
32573
  if (ext && !this.config.markdownFileExtensions.includes(ext)) {
32466
32574
  continue;
32467
32575
  }
@@ -32495,7 +32603,7 @@ var Notebook = class _Notebook {
32495
32603
  if (token.attrs?.length && token.attrs[0][0] === "href") {
32496
32604
  let link = decodeURI(token.attrs[0][1]);
32497
32605
  const text = tokens2[i + 1].content.trim();
32498
- const linkExt = path14.extname(link).toLowerCase();
32606
+ const linkExt = path15.extname(link).toLowerCase();
32499
32607
  if (link.match(/https?:\/\//) || !text.length || !this.config.markdownFileExtensions.includes(linkExt)) {
32500
32608
  continue;
32501
32609
  }
@@ -32583,7 +32691,7 @@ var Notebook = class _Notebook {
32583
32691
  } catch {
32584
32692
  return null;
32585
32693
  }
32586
- if (!stats.isFile() || !this.config.markdownFileExtensions.includes(path14.extname(filePath))) {
32694
+ if (!stats.isFile() || !this.config.markdownFileExtensions.includes(path15.extname(filePath))) {
32587
32695
  return null;
32588
32696
  }
32589
32697
  const sizeLimit = this.config.maxNoteFileSize ?? 0;
@@ -32637,12 +32745,12 @@ var Notebook = class _Notebook {
32637
32745
  if (oldNote) {
32638
32746
  oldMentions = oldNote.mentions;
32639
32747
  }
32640
- const baseExt = path14.extname(absFilePath);
32641
- const title = this.config.markdownFileExtensions.includes(baseExt) ? path14.basename(absFilePath, baseExt) : path14.basename(absFilePath);
32748
+ const baseExt = path15.extname(absFilePath);
32749
+ const title = this.config.markdownFileExtensions.includes(baseExt) ? path15.basename(absFilePath, baseExt) : path15.basename(absFilePath);
32642
32750
  return {
32643
32751
  note: {
32644
32752
  notebookPath: this.notebookPath,
32645
- filePath: path14.relative(this.notebookPath.fsPath, absFilePath),
32753
+ filePath: path15.relative(this.notebookPath.fsPath, absFilePath),
32646
32754
  title,
32647
32755
  config: noteConfig,
32648
32756
  mentions: oldMentions
@@ -32667,23 +32775,36 @@ var Notebook = class _Notebook {
32667
32775
  return this.notes;
32668
32776
  }
32669
32777
  /**
32670
- * True when the notebook is rooted at a filesystem root (`/` on
32671
- * macOS/Linux, `C:\` on Windows) rather than an actual folder —
32672
- * including dot-path spellings of it such as `/.`, which hosts can
32673
- * produce for untitled documents (they resolve to `/`). Indexing
32674
- * such a "notebook" would recursively stat and read files across
32675
- * the whole machine (vscode-markdown-preview-enhanced#2376), so
32676
- * every refresh entry point refuses to walk it. Warns once.
32778
+ * True when the notebook is rooted at a directory the index must
32779
+ * refuse to walk:
32780
+ *
32781
+ * - a filesystem root (`/` on macOS/Linux, `C:\` on Windows),
32782
+ * including dot-path spellings of it such as `/.`, which hosts can
32783
+ * produce for untitled documents (they resolve to `/`);
32784
+ * - the user's home directory — hosts that resolve a loose markdown
32785
+ * file's notebook root to its parent directory produce `~` whenever
32786
+ * the file sits directly in it, and indexing `~` recursively stats
32787
+ * and reads files all over it (on macOS `~/Library` alone spans
32788
+ * Mail, Messages and iCloud data), which is the filesystem scan of
32789
+ * vscode-markdown-preview-enhanced#2376 all over again.
32790
+ *
32791
+ * Every refresh entry point refuses to walk such a root. Warns once.
32677
32792
  */
32678
- skipIndexingIfFilesystemRoot() {
32679
- const resolved = path14.resolve(this.notebookPath.fsPath);
32680
- if (path14.parse(resolved).root !== resolved) {
32793
+ skipIndexingIfRootIsRefused() {
32794
+ const resolved = path15.resolve(this.notebookPath.fsPath);
32795
+ let reason;
32796
+ if (path15.parse(resolved).root === resolved) {
32797
+ reason = "a filesystem root";
32798
+ } else if (isSamePath(resolved, path15.resolve(os.homedir()))) {
32799
+ reason = "the home directory";
32800
+ }
32801
+ if (!reason) {
32681
32802
  return false;
32682
32803
  }
32683
- if (!this.filesystemRootWarned) {
32684
- this.filesystemRootWarned = true;
32804
+ if (!this.refusedRootWarned) {
32805
+ this.refusedRootWarned = true;
32685
32806
  console.warn(
32686
- `Crossnote: notebook root "${this.notebookPath.fsPath}" is a filesystem root; skipping note indexing (wikilinks/backlinks/graph will find nothing). Open a specific folder as the notebook root instead.`
32807
+ `Crossnote: notebook root "${this.notebookPath.fsPath}" is ${reason}; skipping note indexing (wikilinks/backlinks/graph will find nothing). Open a specific folder as the notebook root instead.`
32687
32808
  );
32688
32809
  }
32689
32810
  return true;
@@ -32692,7 +32813,7 @@ var Notebook = class _Notebook {
32692
32813
  async loadGitignoreForDir(dirAbsPath) {
32693
32814
  try {
32694
32815
  const content = await this.fs.readFile(
32695
- path14.join(dirAbsPath, ".gitignore")
32816
+ path15.join(dirAbsPath, ".gitignore")
32696
32817
  );
32697
32818
  return (0, import_ignore.default)().add(content);
32698
32819
  } catch {
@@ -32701,9 +32822,10 @@ var Notebook = class _Notebook {
32701
32822
  }
32702
32823
  async refreshNotes(args) {
32703
32824
  return this.refreshNotesMutex.runExclusive(async () => {
32704
- if (this.skipIndexingIfFilesystemRoot()) {
32825
+ if (this.skipIndexingIfRootIsRefused()) {
32705
32826
  return this.notes;
32706
32827
  }
32828
+ this.walkedEntriesThisRefresh = 0;
32707
32829
  const { refreshRelations = true } = args;
32708
32830
  if (refreshRelations) {
32709
32831
  this.notes = {};
@@ -32737,9 +32859,10 @@ var Notebook = class _Notebook {
32737
32859
  */
32738
32860
  async refreshNotesIncremental(args) {
32739
32861
  return this.refreshNotesMutex.runExclusive(async () => {
32740
- if (this.skipIndexingIfFilesystemRoot()) {
32862
+ if (this.skipIndexingIfRootIsRefused()) {
32741
32863
  return this.notes;
32742
32864
  }
32865
+ this.walkedEntriesThisRefresh = 0;
32743
32866
  const { dir = "./", includeSubdirectories = false } = args;
32744
32867
  const onDisk = /* @__PURE__ */ new Map();
32745
32868
  await this._collectOnDiskMtimes(dir, includeSubdirectories, [], onDisk);
@@ -32808,13 +32931,13 @@ var Notebook = class _Notebook {
32808
32931
  * the duplication when adding new walk-driven features.
32809
32932
  */
32810
32933
  async _walkNotebookDir(dir, includeSubdirectories, gitignoreStack, onFile) {
32811
- const dirAbsPath = path14.resolve(this.notebookPath.fsPath, dir);
32812
- const normalizedDir = path14.relative(this.notebookPath.fsPath, dirAbsPath).replace(/\\/g, "/");
32934
+ const dirAbsPath = path15.resolve(this.notebookPath.fsPath, dir);
32935
+ const normalizedDir = path15.relative(this.notebookPath.fsPath, dirAbsPath).replace(/\\/g, "/");
32813
32936
  const localIg = await this.loadGitignoreForDir(dirAbsPath);
32814
32937
  const currentStack = localIg ? [...gitignoreStack, { ig: localIg, base: normalizedDir || "." }] : gitignoreStack;
32815
32938
  const isIgnoredByGitignore = (relPath) => {
32816
32939
  for (const { ig, base } of currentStack) {
32817
- const relFromBase = base === "." || base === "" ? relPath : path14.posix.relative(base, relPath);
32940
+ const relFromBase = base === "." || base === "" ? relPath : path15.posix.relative(base, relPath);
32818
32941
  if (relFromBase.startsWith("..")) {
32819
32942
  continue;
32820
32943
  }
@@ -32835,8 +32958,8 @@ var Notebook = class _Notebook {
32835
32958
  if (file.match(/^(node_modules|\.git)$/)) {
32836
32959
  continue;
32837
32960
  }
32838
- const absFilePath = path14.resolve(dirAbsPath, file);
32839
- const relFromNotebook = path14.relative(this.notebookPath.fsPath, absFilePath).replace(/\\/g, "/");
32961
+ const absFilePath = path15.resolve(dirAbsPath, file);
32962
+ const relFromNotebook = path15.relative(this.notebookPath.fsPath, absFilePath).replace(/\\/g, "/");
32840
32963
  if (currentStack.length > 0 && isIgnoredByGitignore(relFromNotebook)) {
32841
32964
  continue;
32842
32965
  }
@@ -32846,6 +32969,13 @@ var Notebook = class _Notebook {
32846
32969
  } catch {
32847
32970
  continue;
32848
32971
  }
32972
+ this.walkedEntriesThisRefresh += 1;
32973
+ if (!this.oversizedWalkWarned && this.walkedEntriesThisRefresh > OVERSIZED_WALK_WARN_THRESHOLD) {
32974
+ this.oversizedWalkWarned = true;
32975
+ console.warn(
32976
+ `Crossnote: the note index walk under "${this.notebookPath.fsPath}" has passed ${OVERSIZED_WALK_WARN_THRESHOLD} filesystem entries \u2014 this notebook root is unusually broad, so wikilink/backlink/graph indexing may be slow. If this is unexpected, open a smaller folder as the notebook root.`
32977
+ );
32978
+ }
32849
32979
  if (stats.isSymbolicLink()) {
32850
32980
  continue;
32851
32981
  }
@@ -32883,7 +33013,7 @@ var Notebook = class _Notebook {
32883
33013
  includeSubdirectories,
32884
33014
  gitignoreStack,
32885
33015
  async ({ relPath, stats }) => {
32886
- const ext = path14.extname(relPath);
33016
+ const ext = path15.extname(relPath);
32887
33017
  if (this.config.markdownFileExtensions.includes(ext) && (sizeLimit <= 0 || stats.size <= sizeLimit)) {
32888
33018
  out.set(relPath, Math.floor(stats.mtimeMs));
32889
33019
  }
@@ -33006,10 +33136,10 @@ var Notebook = class _Notebook {
33006
33136
  * @returns
33007
33137
  */
33008
33138
  resolveNoteAbsolutePath(filePath) {
33009
- if (path14.isAbsolute(filePath)) {
33139
+ if (path15.isAbsolute(filePath)) {
33010
33140
  return filePath;
33011
33141
  } else {
33012
- return path14.resolve(this.notebookPath.fsPath, filePath);
33142
+ return path15.resolve(this.notebookPath.fsPath, filePath);
33013
33143
  }
33014
33144
  }
33015
33145
  /**
@@ -33018,8 +33148,8 @@ var Notebook = class _Notebook {
33018
33148
  * @returns
33019
33149
  */
33020
33150
  resolveNoteRelativePath(filePath) {
33021
- if (path14.isAbsolute(filePath)) {
33022
- return path14.relative(this.notebookPath.fsPath, filePath);
33151
+ if (path15.isAbsolute(filePath)) {
33152
+ return path15.relative(this.notebookPath.fsPath, filePath);
33023
33153
  } else {
33024
33154
  return filePath;
33025
33155
  }
@@ -33080,7 +33210,7 @@ var Notebook = class _Notebook {
33080
33210
  blockRef = link.slice(blockRefIndex);
33081
33211
  link = link.slice(0, blockRefIndex);
33082
33212
  }
33083
- const parsed = path14.parse(link);
33213
+ const parsed = path15.parse(link);
33084
33214
  let fileName = parsed.name;
33085
33215
  let fileExtension = parsed.ext;
33086
33216
  if (fileExtension.match(/^\.\d+$/)) {
@@ -33093,7 +33223,7 @@ var Notebook = class _Notebook {
33093
33223
  if (!fileExtension) {
33094
33224
  fileExtension = this.config.wikiLinkTargetFileExtension;
33095
33225
  }
33096
- link = path14.join(parsed.dir, fileName + fileExtension);
33226
+ link = path15.join(parsed.dir, fileName + fileExtension);
33097
33227
  if (hash2) {
33098
33228
  link += hash2;
33099
33229
  }
@@ -33114,20 +33244,20 @@ var Notebook = class _Notebook {
33114
33244
  * @returns notebook-root-relative file path
33115
33245
  */
33116
33246
  resolveWikilink(link, currentNoteFilePath) {
33117
- if (!path14.extname(link)) {
33247
+ if (!path15.extname(link)) {
33118
33248
  link = link + this.config.wikiLinkTargetFileExtension;
33119
33249
  }
33120
33250
  if (link.startsWith("/")) {
33121
- return path14.relative(
33251
+ return path15.relative(
33122
33252
  this.notebookPath.fsPath,
33123
- path14.join(this.notebookPath.fsPath, "." + link)
33253
+ path15.join(this.notebookPath.fsPath, "." + link)
33124
33254
  );
33125
33255
  }
33126
33256
  const mode = this.config.wikiLinkResolution;
33127
33257
  if (mode === "absolute") {
33128
- return path14.relative(
33258
+ return path15.relative(
33129
33259
  this.notebookPath.fsPath,
33130
- path14.join(this.notebookPath.fsPath, link)
33260
+ path15.join(this.notebookPath.fsPath, link)
33131
33261
  );
33132
33262
  }
33133
33263
  if (mode === "shortest") {
@@ -33148,7 +33278,7 @@ var Notebook = class _Notebook {
33148
33278
  const shortest = candidates.filter(
33149
33279
  (c) => normalize(c).split("/").length === bestDepth
33150
33280
  );
33151
- const normalizedDir = normalize(path14.dirname(currentNoteFilePath));
33281
+ const normalizedDir = normalize(path15.dirname(currentNoteFilePath));
33152
33282
  const inDir = shortest.find((c) => {
33153
33283
  const nc = normalize(c);
33154
33284
  if (normalizedDir === ".") {
@@ -33159,8 +33289,8 @@ var Notebook = class _Notebook {
33159
33289
  return inDir || shortest[0];
33160
33290
  }
33161
33291
  }
33162
- const noteDir = currentNoteFilePath ? path14.dirname(path14.join(this.notebookPath.fsPath, currentNoteFilePath)) : this.notebookPath.fsPath;
33163
- return path14.relative(this.notebookPath.fsPath, path14.join(noteDir, link));
33292
+ const noteDir = currentNoteFilePath ? path15.dirname(path15.join(this.notebookPath.fsPath, currentNoteFilePath)) : this.notebookPath.fsPath;
33293
+ return path15.relative(this.notebookPath.fsPath, path15.join(noteDir, link));
33164
33294
  }
33165
33295
  };
33166
33296
 
@@ -33487,16 +33617,16 @@ async function enhance2($, notebook, resolveFilePath) {
33487
33617
  return;
33488
33618
  }
33489
33619
  asyncFunctions.push(
33490
- new Promise((resolve20) => {
33620
+ new Promise((resolve21) => {
33491
33621
  notebook.fs.readFile(src, "base64").then((base64) => {
33492
33622
  $img.attr(
33493
33623
  "src",
33494
33624
  `data:image/${imageType};charset=utf-8;base64,${base64}`
33495
33625
  );
33496
- return resolve20(base64);
33626
+ return resolve21(base64);
33497
33627
  }).catch((error) => {
33498
33628
  console.error(error);
33499
- return resolve20(null);
33629
+ return resolve21(null);
33500
33630
  });
33501
33631
  })
33502
33632
  );
@@ -33521,15 +33651,15 @@ async function enhance3($, notebook, resolveFilePath) {
33521
33651
  return;
33522
33652
  }
33523
33653
  asyncFunctions.push(
33524
- new Promise((resolve20) => {
33654
+ new Promise((resolve21) => {
33525
33655
  notebook.fs.readFile(src, "base64").then((base64) => {
33526
33656
  $img.attr(
33527
33657
  "src",
33528
33658
  `data:image/svg+xml;charset=utf-8;base64,${base64}`
33529
33659
  );
33530
- return resolve20(base64);
33660
+ return resolve21(base64);
33531
33661
  }).catch(() => {
33532
- return resolve20(null);
33662
+ return resolve21(null);
33533
33663
  });
33534
33664
  })
33535
33665
  );
@@ -33540,7 +33670,7 @@ async function enhance3($, notebook, resolveFilePath) {
33540
33670
 
33541
33671
  // src/render-enhancers/embedded-wikilinks.ts
33542
33672
  var import_html_escaper6 = require("html-escaper");
33543
- var path15 = __toESM(require("path"));
33673
+ var path16 = __toESM(require("path"));
33544
33674
  var cheerio2 = __toESM(require("cheerio"));
33545
33675
  var MAX_EMBED_DEPTH = 3;
33546
33676
  var BINARY_EMBED_EXTENSIONS = /* @__PURE__ */ new Set([
@@ -33632,9 +33762,9 @@ async function resolveEmbed(_$, notebook, fileDirectoryPath, $placeholder, embed
33632
33762
  }
33633
33763
  let resolvedPath;
33634
33764
  if (embedPath.startsWith("/")) {
33635
- resolvedPath = path15.resolve(notebook.notebookPath.fsPath, "." + embedPath);
33765
+ resolvedPath = path16.resolve(notebook.notebookPath.fsPath, "." + embedPath);
33636
33766
  } else {
33637
- resolvedPath = path15.resolve(fileDirectoryPath, embedPath);
33767
+ resolvedPath = path16.resolve(fileDirectoryPath, embedPath);
33638
33768
  }
33639
33769
  let hash2 = "";
33640
33770
  const hashIndex = resolvedPath.lastIndexOf("#");
@@ -33642,7 +33772,7 @@ async function resolveEmbed(_$, notebook, fileDirectoryPath, $placeholder, embed
33642
33772
  hash2 = resolvedPath.substring(hashIndex);
33643
33773
  resolvedPath = resolvedPath.substring(0, hashIndex);
33644
33774
  }
33645
- const extname14 = path15.extname(resolvedPath).toLowerCase();
33775
+ const extname14 = path16.extname(resolvedPath).toLowerCase();
33646
33776
  if (IMAGE_EMBED_RE.test(extname14)) {
33647
33777
  $placeholder.replaceWith(
33648
33778
  `<div class="wikilink-embed-content"><img src="${(0, import_html_escaper6.escape)(
@@ -33719,7 +33849,7 @@ async function resolveEmbed(_$, notebook, fileDirectoryPath, $placeholder, embed
33719
33849
  return;
33720
33850
  }
33721
33851
  }
33722
- const embedFileDir = path15.dirname(resolvedPath);
33852
+ const embedFileDir = path16.dirname(resolvedPath);
33723
33853
  const engine = notebook.getNoteMarkdownEngine(resolvedPath);
33724
33854
  const { html } = await engine.parseMD(markdownContent, {
33725
33855
  useRelativeFilePath: false,
@@ -34032,23 +34162,23 @@ async function renderBitfield(code, options) {
34032
34162
  }
34033
34163
 
34034
34164
  // src/renderers/d2.ts
34035
- var import_child_process12 = require("child_process");
34165
+ var import_child_process10 = require("child_process");
34036
34166
  var crypto = __toESM(require("crypto"));
34037
34167
  var import_html_escaper9 = require("html-escaper");
34038
34168
  var fs12 = __toESM(require("fs"));
34039
- var os = __toESM(require("os"));
34040
- var path16 = __toESM(require("path"));
34169
+ var os2 = __toESM(require("os"));
34170
+ var path17 = __toESM(require("path"));
34041
34171
  var D2_NOT_FOUND = /* @__PURE__ */ Symbol("D2_NOT_FOUND");
34042
34172
  async function writeInputFile(fileDirectoryPath, name, code) {
34043
34173
  if (fileDirectoryPath) {
34044
- const preferred = path16.join(fileDirectoryPath, name);
34174
+ const preferred = path17.join(fileDirectoryPath, name);
34045
34175
  try {
34046
34176
  await fs12.promises.writeFile(preferred, code, "utf8");
34047
34177
  return preferred;
34048
34178
  } catch {
34049
34179
  }
34050
34180
  }
34051
- const fallback = path16.join(os.tmpdir(), name);
34181
+ const fallback = path17.join(os2.tmpdir(), name);
34052
34182
  await fs12.promises.writeFile(fallback, code, "utf8");
34053
34183
  return fallback;
34054
34184
  }
@@ -34056,12 +34186,12 @@ async function renderD2(code, opts, fileDirectoryPath) {
34056
34186
  if (typeof crypto?.randomBytes !== "function") return D2_NOT_FOUND;
34057
34187
  const id = crypto.randomBytes(8).toString("hex");
34058
34188
  const inputName = `.crossnote-d2-${id}.d2`;
34059
- const tmpOut = path16.join(os.tmpdir(), `d2-${id}.svg`);
34189
+ const tmpOut = path17.join(os2.tmpdir(), `d2-${id}.svg`);
34060
34190
  let tmpIn;
34061
34191
  try {
34062
34192
  tmpIn = await writeInputFile(fileDirectoryPath, inputName, code);
34063
34193
  const inputPath = tmpIn;
34064
- await new Promise((resolve20, reject) => {
34194
+ await new Promise((resolve21, reject) => {
34065
34195
  const args = [
34066
34196
  `--theme=${opts.d2Theme}`,
34067
34197
  `--layout=${opts.d2Layout}`,
@@ -34069,7 +34199,7 @@ async function renderD2(code, opts, fileDirectoryPath) {
34069
34199
  inputPath,
34070
34200
  tmpOut
34071
34201
  ];
34072
- (0, import_child_process12.execFile)(
34202
+ (0, import_child_process10.execFile)(
34073
34203
  opts.d2Path,
34074
34204
  args,
34075
34205
  { timeout: 3e4 },
@@ -34079,7 +34209,7 @@ async function renderD2(code, opts, fileDirectoryPath) {
34079
34209
  wrapped.code = err.code;
34080
34210
  reject(wrapped);
34081
34211
  } else {
34082
- resolve20();
34212
+ resolve21();
34083
34213
  }
34084
34214
  }
34085
34215
  );
@@ -34715,9 +34845,7 @@ async function enhance9($, options, resolveFilePath) {
34715
34845
 
34716
34846
  // src/markdown-engine/inline-offline-assets.ts
34717
34847
  var fs13 = __toESM(require("fs"));
34718
- var path17 = __toESM(require("path"));
34719
- var ABSOLUTE_URL = /^(data:|https?:|file:|\/\/)/i;
34720
- var CSS_URL = /url\(\s*(['"]?)([^'")]+)\1\s*\)(\s*format\([^)]+\))?/gi;
34848
+ var path18 = __toESM(require("path"));
34721
34849
  var FALLBACK_FONT_EXTS = /* @__PURE__ */ new Set([".woff", ".ttf", ".eot", ".otf"]);
34722
34850
  var MIME_BY_EXT = {
34723
34851
  ".woff2": "font/woff2",
@@ -34741,7 +34869,7 @@ ${escaped}
34741
34869
  }
34742
34870
  async function readOfflineCss(absPath) {
34743
34871
  const css = await fs13.promises.readFile(absPath, "utf8");
34744
- const rewritten = rewriteCssUrls(css, path17.dirname(absPath));
34872
+ const rewritten = rewriteCssUrls(css, path18.dirname(absPath));
34745
34873
  const escaped = rewritten.replace(/<\/style/gi, "<\\/style");
34746
34874
  return `<style>
34747
34875
  ${escaped}
@@ -34755,11 +34883,11 @@ function rewriteCssUrls(css, cssDir) {
34755
34883
  if (ABSOLUTE_URL.test(url)) {
34756
34884
  return whole;
34757
34885
  }
34758
- const resolved = path17.resolve(cssDir, url.replace(/[?#].*$/, ""));
34759
- if (resolved !== cssDir && !resolved.startsWith(cssDir + path17.sep)) {
34886
+ const resolved = path18.resolve(cssDir, url.replace(/[?#].*$/, ""));
34887
+ if (resolved !== cssDir && !resolved.startsWith(cssDir + path18.sep)) {
34760
34888
  return "";
34761
34889
  }
34762
- const ext = path17.extname(resolved).toLowerCase();
34890
+ const ext = path18.extname(resolved).toLowerCase();
34763
34891
  if (FALLBACK_FONT_EXTS.has(ext)) {
34764
34892
  const woff2 = resolved.slice(0, -ext.length) + ".woff2";
34765
34893
  if (fs13.existsSync(woff2)) {
@@ -34942,11 +35070,11 @@ function isPathInsideDirectory(parentDirectoryPath, filePath) {
34942
35070
  return p;
34943
35071
  }
34944
35072
  };
34945
- const relative11 = path18.relative(
35073
+ const relative11 = path19.relative(
34946
35074
  realpath(parentDirectoryPath),
34947
35075
  realpath(filePath)
34948
35076
  );
34949
- return relative11 !== "" && !relative11.startsWith("..") && !path18.isAbsolute(relative11);
35077
+ return relative11 !== "" && !relative11.startsWith("..") && !path19.isAbsolute(relative11);
34950
35078
  }
34951
35079
  function isExistingFile(filePath) {
34952
35080
  try {
@@ -34978,7 +35106,7 @@ var MarkdownEngine = class _MarkdownEngine {
34978
35106
  this.isPreviewInPresentationMode = false;
34979
35107
  this.filePath = filePath;
34980
35108
  this.notebook = notebook;
34981
- this.fileDirectoryPath = path18.dirname(this.filePath);
35109
+ this.fileDirectoryPath = path19.dirname(this.filePath);
34982
35110
  this.projectDirectoryPath = this.notebook.notebookPath || this.fileDirectoryPath;
34983
35111
  this.fs = this.notebook.fs;
34984
35112
  this.headings = [];
@@ -35004,7 +35132,7 @@ var MarkdownEngine = class _MarkdownEngine {
35004
35132
  let scripts = "";
35005
35133
  scripts += `<script>var exports = undefined</script>`;
35006
35134
  scripts += `<script type="text/javascript" src="${addFileProtocol(
35007
- path18.resolve(
35135
+ path19.resolve(
35008
35136
  getCrossnoteBuildDirectory(),
35009
35137
  `./dependencies/mermaid/mermaid.min.js`
35010
35138
  ),
@@ -35015,21 +35143,21 @@ var MarkdownEngine = class _MarkdownEngine {
35015
35143
  await mermaid.registerExternalDiagrams([zenuml]);
35016
35144
  </script>`;
35017
35145
  scripts += `<script type="text/javascript" src="${addFileProtocol(
35018
- path18.resolve(
35146
+ path19.resolve(
35019
35147
  getCrossnoteBuildDirectory(),
35020
35148
  "./dependencies/wavedrom/skins/default.js"
35021
35149
  ),
35022
35150
  vscodePreviewPanel
35023
35151
  )}" charset="UTF-8"></script>`;
35024
35152
  scripts += `<script type="text/javascript" src="${addFileProtocol(
35025
- path18.resolve(
35153
+ path19.resolve(
35026
35154
  getCrossnoteBuildDirectory(),
35027
35155
  "./dependencies/wavedrom/skins/narrow.js"
35028
35156
  ),
35029
35157
  vscodePreviewPanel
35030
35158
  )}" charset="UTF-8"></script>`;
35031
35159
  scripts += `<script type="text/javascript" src="${addFileProtocol(
35032
- path18.resolve(
35160
+ path19.resolve(
35033
35161
  getCrossnoteBuildDirectory(),
35034
35162
  "./dependencies/wavedrom/wavedrom.min.js"
35035
35163
  ),
@@ -35062,7 +35190,7 @@ var MarkdownEngine = class _MarkdownEngine {
35062
35190
  let presentationInitScript = "";
35063
35191
  if (isForPresentation) {
35064
35192
  scripts += `<script src='${addFileProtocol(
35065
- path18.resolve(
35193
+ path19.resolve(
35066
35194
  getCrossnoteBuildDirectory(),
35067
35195
  "./dependencies/reveal/js/reveal.js"
35068
35196
  ),
@@ -35126,7 +35254,7 @@ if (typeof(window['Reveal']) !== 'undefined') {
35126
35254
  }
35127
35255
  dependentLibraryMaterials.forEach(({ key }) => {
35128
35256
  scripts += `<script src="${addFileProtocol(
35129
- path18.resolve(
35257
+ path19.resolve(
35130
35258
  getCrossnoteBuildDirectory(),
35131
35259
  `./dependencies/${key}/${key}.min.js`
35132
35260
  ),
@@ -35303,7 +35431,7 @@ window["initRevealPresentation"] = async function() {
35303
35431
  let styles = "";
35304
35432
  if (this.notebook.config.mathRenderingOption === "KaTeX" && this.notebook.config.markdownParser !== "pandoc") {
35305
35433
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35306
- path18.resolve(
35434
+ path19.resolve(
35307
35435
  getCrossnoteBuildDirectory(),
35308
35436
  "./dependencies/katex/katex.min.css"
35309
35437
  ),
@@ -35311,7 +35439,7 @@ window["initRevealPresentation"] = async function() {
35311
35439
  )}">`;
35312
35440
  }
35313
35441
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35314
- path18.resolve(
35442
+ path19.resolve(
35315
35443
  getCrossnoteBuildDirectory(),
35316
35444
  `./dependencies/font-awesome/css/all.min.css`
35317
35445
  ),
@@ -35319,7 +35447,7 @@ window["initRevealPresentation"] = async function() {
35319
35447
  )}">`;
35320
35448
  if (!isPresentationMode) {
35321
35449
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35322
- path18.resolve(
35450
+ path19.resolve(
35323
35451
  getCrossnoteBuildDirectory(),
35324
35452
  `./styles/preview_theme/${this.notebook.config.previewTheme}`
35325
35453
  ),
@@ -35327,14 +35455,14 @@ window["initRevealPresentation"] = async function() {
35327
35455
  )}">`;
35328
35456
  } else {
35329
35457
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35330
- path18.resolve(
35458
+ path19.resolve(
35331
35459
  getCrossnoteBuildDirectory(),
35332
35460
  "./dependencies/reveal/css/reveal.css"
35333
35461
  ),
35334
35462
  vscodePreviewPanel
35335
35463
  )}" >`;
35336
35464
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35337
- path18.resolve(
35465
+ path19.resolve(
35338
35466
  getCrossnoteBuildDirectory(),
35339
35467
  `./dependencies/reveal/css/theme/${(() => {
35340
35468
  const presObj = typeof yamlConfig["presentation"] === "object" && yamlConfig["presentation"] !== null && !Array.isArray(yamlConfig["presentation"]) ? yamlConfig["presentation"] : null;
@@ -35345,7 +35473,7 @@ window["initRevealPresentation"] = async function() {
35345
35473
  )}" >`;
35346
35474
  }
35347
35475
  styles += `<link rel="stylesheet" href="${addFileProtocol(
35348
- path18.resolve(
35476
+ path19.resolve(
35349
35477
  getCrossnoteBuildDirectory(),
35350
35478
  `./styles/prism_theme/${this.getPrismTheme(
35351
35479
  isPresentationMode,
@@ -35355,27 +35483,30 @@ window["initRevealPresentation"] = async function() {
35355
35483
  vscodePreviewPanel
35356
35484
  )}">`;
35357
35485
  styles += `<link rel="stylesheet" media="screen" href="${addFileProtocol(
35358
- path18.resolve(
35486
+ path19.resolve(
35359
35487
  getCrossnoteBuildDirectory(),
35360
35488
  "./styles/style-template.css"
35361
35489
  ),
35362
35490
  vscodePreviewPanel
35363
35491
  )}">`;
35364
35492
  styles += `<link rel="stylesheet" media="screen" href="${addFileProtocol(
35365
- path18.resolve(
35493
+ path19.resolve(
35366
35494
  getCrossnoteBuildDirectory(),
35367
35495
  "./styles/markdown-it-admonition.css"
35368
35496
  ),
35369
35497
  vscodePreviewPanel
35370
35498
  )}">`;
35371
35499
  styles += `<link rel="stylesheet" media="screen" href="${addFileProtocol(
35372
- path18.resolve(
35500
+ path19.resolve(
35373
35501
  getCrossnoteBuildDirectory(),
35374
35502
  "./styles/markdown-it-callout.css"
35375
35503
  ),
35376
35504
  vscodePreviewPanel
35377
35505
  )}">`;
35378
- styles += `<style>${this.notebook.config.globalCss}</style>`;
35506
+ styles += `<style>${this.resolvePathsInStyles(
35507
+ this.notebook.config.globalCss,
35508
+ vscodePreviewPanel
35509
+ )}</style>`;
35379
35510
  return styles;
35380
35511
  }
35381
35512
  /**
@@ -35389,7 +35520,7 @@ window["initRevealPresentation"] = async function() {
35389
35520
  if (!this.notebook.previewScriptsEnabled || sourcePath.startsWith("//") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(sourcePath)) {
35390
35521
  return;
35391
35522
  }
35392
- const resolvedPath = sourcePath[0] === "/" ? path18.resolve(this.projectDirectoryPath.fsPath, "." + sourcePath) : path18.resolve(this.fileDirectoryPath, sourcePath);
35523
+ const resolvedPath = sourcePath[0] === "/" ? path19.resolve(this.projectDirectoryPath.fsPath, "." + sourcePath) : path19.resolve(this.fileDirectoryPath, sourcePath);
35393
35524
  if (!this.isPathInsideProjectDirectory(resolvedPath)) {
35394
35525
  return;
35395
35526
  }
@@ -35402,13 +35533,13 @@ window["initRevealPresentation"] = async function() {
35402
35533
  let absoluteFilePath = sourcePath;
35403
35534
  if (sourcePath[0] === "/") {
35404
35535
  absoluteFilePath = addFileProtocol(
35405
- path18.resolve(this.projectDirectoryPath.fsPath, "." + sourcePath),
35536
+ path19.resolve(this.projectDirectoryPath.fsPath, "." + sourcePath),
35406
35537
  vscodePreviewPanel
35407
35538
  );
35408
35539
  } else if (sourcePath.match(/^file:\/\//) || sourcePath.match(/^https?:\/\//)) {
35409
35540
  } else {
35410
35541
  absoluteFilePath = addFileProtocol(
35411
- path18.resolve(this.fileDirectoryPath, sourcePath),
35542
+ path19.resolve(this.fileDirectoryPath, sourcePath),
35412
35543
  vscodePreviewPanel
35413
35544
  );
35414
35545
  }
@@ -35447,14 +35578,14 @@ window["initRevealPresentation"] = async function() {
35447
35578
  let webviewCss = "";
35448
35579
  if (!webviewScript) {
35449
35580
  webviewScript = addFileProtocol(
35450
- path18.resolve(
35581
+ path19.resolve(
35451
35582
  getCrossnoteBuildDirectory(),
35452
35583
  "./webview/preview.js"
35453
35584
  ),
35454
35585
  vscodePreviewPanel
35455
35586
  );
35456
35587
  webviewCss = addFileProtocol(
35457
- path18.resolve(
35588
+ path19.resolve(
35458
35589
  getCrossnoteBuildDirectory(),
35459
35590
  "./webview/preview.css"
35460
35591
  ),
@@ -35505,7 +35636,7 @@ window["initRevealPresentation"] = async function() {
35505
35636
  </style>
35506
35637
  ` : ""}
35507
35638
  <link rel="stylesheet" href="${addFileProtocol(
35508
- path18.resolve(
35639
+ path19.resolve(
35509
35640
  getCrossnoteBuildDirectory(),
35510
35641
  "./styles/preview.css"
35511
35642
  ),
@@ -35547,14 +35678,14 @@ window["initRevealPresentation"] = async function() {
35547
35678
  contentSecurityPolicy = ""
35548
35679
  }) {
35549
35680
  const webviewScript = addFileProtocol(
35550
- path18.resolve(
35681
+ path19.resolve(
35551
35682
  getCrossnoteBuildDirectory(),
35552
35683
  "./webview/graph-view.js"
35553
35684
  ),
35554
35685
  vscodePreviewPanel
35555
35686
  );
35556
35687
  const webviewCss = addFileProtocol(
35557
- path18.resolve(
35688
+ path19.resolve(
35558
35689
  getCrossnoteBuildDirectory(),
35559
35690
  "./webview/graph-view.css"
35560
35691
  ),
@@ -35585,7 +35716,7 @@ window["initRevealPresentation"] = async function() {
35585
35716
  async generateHTMLTemplateForExport(html, yamlConfig = {}, options) {
35586
35717
  const fileURL = (p) => toFileURL(p, { useWSL: !!options.isForBrowser });
35587
35718
  const embedAssets = !!(options.offline && options.embedOfflineAssets);
35588
- const depPath = (...parts) => path18.resolve(getCrossnoteBuildDirectory(), ...parts);
35719
+ const depPath = (...parts) => path19.resolve(getCrossnoteBuildDirectory(), ...parts);
35589
35720
  const offlineStyle = async (rel) => {
35590
35721
  const abs = depPath(rel);
35591
35722
  if (embedAssets) {
@@ -35665,7 +35796,7 @@ window["initRevealPresentation"] = async function() {
35665
35796
  "./dependencies/mermaid/mermaid.min.js"
35666
35797
  );
35667
35798
  } else {
35668
- mermaidScript = `<script src="https://${this.notebook.config.jsdelivrCdnHost}/npm/mermaid@11.17.2/dist/mermaid.min.js"></script>`;
35799
+ mermaidScript = `<script src="https://${this.notebook.config.jsdelivrCdnHost}/npm/mermaid@12.0.0/dist/mermaid.min.js"></script>`;
35669
35800
  }
35670
35801
  mermaidInitScript += `<script type="module">
35671
35802
  // TODO: If ZenUML gets integrated into mermaid in the future,
@@ -35778,7 +35909,7 @@ if (typeof(window['Reveal']) !== 'undefined') {
35778
35909
  if (presentationConfig["enableSpeakerNotes"]) {
35779
35910
  if (options.offline) {
35780
35911
  dependencies.push({
35781
- src: path18.resolve(
35912
+ src: path19.resolve(
35782
35913
  getCrossnoteBuildDirectory(),
35783
35914
  "./dependencies/reveal/plugin/notes/notes.js"
35784
35915
  ),
@@ -35792,13 +35923,13 @@ if (typeof(window['Reveal']) !== 'undefined') {
35792
35923
  presentationStyle = `
35793
35924
  <style>
35794
35925
  ${await this.fs.readFile(
35795
- path18.resolve(
35926
+ path19.resolve(
35796
35927
  getCrossnoteBuildDirectory(),
35797
35928
  "./dependencies/reveal/css/reveal.css"
35798
35929
  )
35799
35930
  )}
35800
35931
  ${options.isForPrint ? await this.fs.readFile(
35801
- path18.resolve(
35932
+ path19.resolve(
35802
35933
  getCrossnoteBuildDirectory(),
35803
35934
  "./dependencies/reveal/css/print/pdf.css"
35804
35935
  )
@@ -35818,8 +35949,8 @@ if (typeof(window['Reveal']) !== 'undefined') {
35818
35949
  if (options.isForPrince) {
35819
35950
  princeClass = "prince";
35820
35951
  }
35821
- let title = path18.basename(this.filePath);
35822
- title = title.slice(0, title.length - path18.extname(title).length);
35952
+ let title = path19.basename(this.filePath);
35953
+ title = title.slice(0, title.length - path19.extname(title).length);
35823
35954
  if (yamlConfig["title"]) {
35824
35955
  title = yamlConfig["title"];
35825
35956
  }
@@ -35832,7 +35963,7 @@ if (typeof(window['Reveal']) !== 'undefined') {
35832
35963
  try {
35833
35964
  if (forceLightTheme && !yamlConfig["isPresentationMode"]) {
35834
35965
  styleCSS += await this.fs.readFile(
35835
- path18.resolve(
35966
+ path19.resolve(
35836
35967
  getCrossnoteBuildDirectory(),
35837
35968
  `./styles/prism_theme/github.css`
35838
35969
  )
@@ -35852,14 +35983,14 @@ if (typeof(window['Reveal']) !== 'undefined') {
35852
35983
  if (darkPrismTheme) {
35853
35984
  colorSchemeMeta = '<meta name="color-scheme" content="light dark">';
35854
35985
  styleCSS += await this.fs.readFile(
35855
- path18.resolve(
35986
+ path19.resolve(
35856
35987
  getCrossnoteBuildDirectory(),
35857
35988
  `./styles/prism_theme/${prismTheme}`
35858
35989
  )
35859
35990
  );
35860
35991
  styleCSS += `@media (prefers-color-scheme: dark) {
35861
35992
  ${await this.fs.readFile(
35862
- path18.resolve(
35993
+ path19.resolve(
35863
35994
  getCrossnoteBuildDirectory(),
35864
35995
  `./styles/prism_theme/${darkPrismTheme}`
35865
35996
  )
@@ -35868,7 +35999,7 @@ ${await this.fs.readFile(
35868
35999
  `;
35869
36000
  } else {
35870
36001
  styleCSS += await this.fs.readFile(
35871
- path18.resolve(
36002
+ path19.resolve(
35872
36003
  getCrossnoteBuildDirectory(),
35873
36004
  `./styles/prism_theme/${prismTheme}`
35874
36005
  )
@@ -35900,7 +36031,7 @@ ${await this.fs.readFile(
35900
36031
  ) : null;
35901
36032
  if (forceLightTheme) {
35902
36033
  styleCSS += await this.fs.readFile(
35903
- path18.resolve(
36034
+ path19.resolve(
35904
36035
  getCrossnoteBuildDirectory(),
35905
36036
  `./styles/preview_theme/github-light.css`
35906
36037
  )
@@ -35909,14 +36040,14 @@ ${await this.fs.readFile(
35909
36040
  const lightPreviewTheme = darkPreviewTheme === previewTheme ? _MarkdownEngine.PreviewThemeColorCounterparts[previewTheme] : previewTheme;
35910
36041
  colorSchemeMeta = '<meta name="color-scheme" content="light dark">';
35911
36042
  styleCSS += await this.fs.readFile(
35912
- path18.resolve(
36043
+ path19.resolve(
35913
36044
  getCrossnoteBuildDirectory(),
35914
36045
  `./styles/preview_theme/${lightPreviewTheme}`
35915
36046
  )
35916
36047
  );
35917
36048
  styleCSS += `@media (prefers-color-scheme: dark) {
35918
36049
  ${await this.fs.readFile(
35919
- path18.resolve(
36050
+ path19.resolve(
35920
36051
  getCrossnoteBuildDirectory(),
35921
36052
  `./styles/preview_theme/${darkPreviewTheme}`
35922
36053
  )
@@ -35925,7 +36056,7 @@ ${await this.fs.readFile(
35925
36056
  `;
35926
36057
  } else {
35927
36058
  styleCSS += await this.fs.readFile(
35928
- path18.resolve(
36059
+ path19.resolve(
35929
36060
  getCrossnoteBuildDirectory(),
35930
36061
  `./styles/preview_theme/${previewTheme}`
35931
36062
  )
@@ -35933,14 +36064,14 @@ ${await this.fs.readFile(
35933
36064
  }
35934
36065
  }
35935
36066
  styleCSS += await this.fs.readFile(
35936
- path18.resolve(
36067
+ path19.resolve(
35937
36068
  getCrossnoteBuildDirectory(),
35938
36069
  "./styles/style-template.css"
35939
36070
  )
35940
36071
  );
35941
36072
  if (html.indexOf("admonition") > 0) {
35942
36073
  styleCSS += await this.fs.readFile(
35943
- path18.resolve(
36074
+ path19.resolve(
35944
36075
  getCrossnoteBuildDirectory(),
35945
36076
  "./styles/markdown-it-admonition.css"
35946
36077
  )
@@ -35948,7 +36079,7 @@ ${await this.fs.readFile(
35948
36079
  }
35949
36080
  if (html.indexOf("callout") > 0) {
35950
36081
  styleCSS += await this.fs.readFile(
35951
- path18.resolve(
36082
+ path19.resolve(
35952
36083
  getCrossnoteBuildDirectory(),
35953
36084
  "./styles/markdown-it-callout.css"
35954
36085
  )
@@ -35957,7 +36088,9 @@ ${await this.fs.readFile(
35957
36088
  } catch {
35958
36089
  styleCSS = "";
35959
36090
  }
35960
- const globalStyles = this.notebook.config.globalCss;
36091
+ const globalStyles = this.resolvePathsInStyles(
36092
+ this.notebook.config.globalCss
36093
+ );
35961
36094
  let sidebarTOC = "";
35962
36095
  let sidebarTOCScript = "";
35963
36096
  let sidebarTOCBtn = "";
@@ -36096,26 +36229,26 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36096
36229
  runAllCodeChunks = false
36097
36230
  } = {}) {
36098
36231
  let dest = this.filePath;
36099
- const extname14 = path18.extname(dest);
36232
+ const extname14 = path19.extname(dest);
36100
36233
  dest = dest.replace(new RegExp(extname14 + "$"), ".html");
36101
36234
  const html = await this.htmlExportDocument({ offline, runAllCodeChunks });
36102
36235
  if (!offline && html.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]') >= 0) {
36103
- const depsDirName = path18.resolve(path18.dirname(dest), "revealjs_deps");
36236
+ const depsDirName = path19.resolve(path19.dirname(dest), "revealjs_deps");
36104
36237
  if (!fs14.existsSync(depsDirName)) {
36105
36238
  fs14.mkdirSync(depsDirName);
36106
36239
  }
36107
36240
  fs14.createReadStream(
36108
- path18.resolve(
36241
+ path19.resolve(
36109
36242
  getCrossnoteBuildDirectory(),
36110
36243
  "./dependencies/reveal/plugin/notes/notes.js"
36111
36244
  )
36112
- ).pipe(fs14.createWriteStream(path18.resolve(depsDirName, "notes.js")));
36245
+ ).pipe(fs14.createWriteStream(path19.resolve(depsDirName, "notes.js")));
36113
36246
  fs14.createReadStream(
36114
- path18.resolve(
36247
+ path19.resolve(
36115
36248
  getCrossnoteBuildDirectory(),
36116
36249
  "./dependencies/reveal/plugin/notes/notes.html"
36117
36250
  )
36118
- ).pipe(fs14.createWriteStream(path18.resolve(depsDirName, "notes.html")));
36251
+ ).pipe(fs14.createWriteStream(path19.resolve(depsDirName, "notes.html")));
36119
36252
  }
36120
36253
  await this.fs.writeFile(dest, html);
36121
36254
  return dest;
@@ -36182,7 +36315,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36182
36315
  runAllCodeChunks
36183
36316
  }));
36184
36317
  let dest = this.filePath;
36185
- const extname14 = path18.extname(dest);
36318
+ const extname14 = path19.extname(dest);
36186
36319
  dest = dest.replace(new RegExp(extname14 + "$"), "." + fileType);
36187
36320
  html = await this.generateHTMLTemplateForExport(html, yamlConfig, {
36188
36321
  isForPrint: true,
@@ -36232,10 +36365,10 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36232
36365
  timeout = puppeteerConfig2["timeout"];
36233
36366
  }
36234
36367
  if (timeout && typeof timeout === "number") {
36235
- await new Promise((resolve20) => setTimeout(resolve20, timeout));
36368
+ await new Promise((resolve21) => setTimeout(resolve21, timeout));
36236
36369
  } else if (this.notebook.config.puppeteerWaitForTimeout && this.notebook.config.puppeteerWaitForTimeout > 0) {
36237
36370
  await new Promise(
36238
- (resolve20) => setTimeout(resolve20, this.notebook.config.puppeteerWaitForTimeout)
36371
+ (resolve21) => setTimeout(resolve21, this.notebook.config.puppeteerWaitForTimeout)
36239
36372
  );
36240
36373
  }
36241
36374
  if (fileType === "pdf") {
@@ -36244,7 +36377,8 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36244
36377
  puppeteerConfig["fullPage"] = true;
36245
36378
  await page.screenshot(puppeteerConfig);
36246
36379
  }
36247
- browser.close();
36380
+ browser.close().catch(() => {
36381
+ });
36248
36382
  if (openFileAfterGeneration) {
36249
36383
  openFile(dest);
36250
36384
  }
@@ -36268,7 +36402,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36268
36402
  runAllCodeChunks
36269
36403
  }));
36270
36404
  let dest = this.filePath;
36271
- const extname14 = path18.extname(dest);
36405
+ const extname14 = path19.extname(dest);
36272
36406
  dest = dest.replace(new RegExp(extname14 + "$"), ".pdf");
36273
36407
  html = await this.generateHTMLTemplateForExport(html, yamlConfig, {
36274
36408
  isForPrint: true,
@@ -36294,7 +36428,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36294
36428
  }
36295
36429
  async eBookDownloadImages($, dest) {
36296
36430
  const imagesToDownload = [];
36297
- if (path18.extname(dest) === ".epub" || path18.extname("dest") === ".mobi") {
36431
+ if (path19.extname(dest) === ".epub" || path19.extname("dest") === ".mobi") {
36298
36432
  $("img").each((offset, img) => {
36299
36433
  const $img = $(img);
36300
36434
  const src = $img.attr("src") || "";
@@ -36305,8 +36439,8 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36305
36439
  }
36306
36440
  const asyncFunctions = imagesToDownload.map(async ($img) => {
36307
36441
  const httpSrc = $img.attr("src") ?? "";
36308
- let savePath = Math.random().toString(36).substr(2, 9) + "_" + path18.basename(httpSrc);
36309
- savePath = path18.resolve(this.fileDirectoryPath, savePath);
36442
+ let savePath = Math.random().toString(36).substr(2, 9) + "_" + path19.basename(httpSrc);
36443
+ savePath = path19.resolve(this.fileDirectoryPath, savePath);
36310
36444
  const response = await fetch(httpSrc);
36311
36445
  if (!response.ok || !response.body) {
36312
36446
  throw new Error(`Failed to download image from ${httpSrc}`);
@@ -36345,7 +36479,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36345
36479
  emojiToSvg
36346
36480
  }));
36347
36481
  let dest = this.filePath;
36348
- const extname14 = path18.extname(dest);
36482
+ const extname14 = path19.extname(dest);
36349
36483
  dest = dest.replace(
36350
36484
  new RegExp(extname14 + "$"),
36351
36485
  "." + fileType.toLowerCase()
@@ -36406,24 +36540,24 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36406
36540
  }
36407
36541
  const asyncFunctions = tocStructure.map(
36408
36542
  ({ heading, id, level, filePath }, offset) => {
36409
- return new Promise((resolve20, reject) => {
36543
+ return new Promise((resolve21, reject) => {
36410
36544
  filePath = removeFileProtocol(filePath);
36411
36545
  if (filePath.match(/^https?:\/\//)) {
36412
- return resolve20({ heading, id, level, filePath, html: "", offset });
36546
+ return resolve21({ heading, id, level, filePath, html: "", offset });
36413
36547
  }
36414
36548
  fs14.readFile(filePath, { encoding: "utf-8" }, (error, text) => {
36415
36549
  if (error) {
36416
36550
  return reject(error.toString());
36417
36551
  }
36418
- const rootPath = path18.dirname(this.filePath);
36552
+ const rootPath = path19.dirname(this.filePath);
36419
36553
  text = text.replace(
36420
36554
  /(!\[[^\]]*\]\()(\.[^)\s]*)/g,
36421
36555
  (whole, openTag, imageLink) => {
36422
- const fullPath = path18.resolve(
36423
- path18.dirname(filePath),
36556
+ const fullPath = path19.resolve(
36557
+ path19.dirname(filePath),
36424
36558
  imageLink
36425
36559
  );
36426
- const relativePath = path18.relative(rootPath, fullPath);
36560
+ const relativePath = path19.relative(rootPath, fullPath);
36427
36561
  return openTag + relativePath;
36428
36562
  }
36429
36563
  );
@@ -36432,10 +36566,10 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36432
36566
  isForPreview: false,
36433
36567
  hideFrontMatter: true,
36434
36568
  emojiToSvg,
36435
- fileDirectoryPath: path18.dirname(filePath)
36569
+ fileDirectoryPath: path19.dirname(filePath)
36436
36570
  /* tslint:disable-next-line:no-shadowed-variable */
36437
36571
  }).then(({ html: html2 }) => {
36438
- return resolve20({ heading, id, level, filePath, html: html2, offset });
36572
+ return resolve21({ heading, id, level, filePath, html: html2, offset });
36439
36573
  });
36440
36574
  });
36441
36575
  });
@@ -36461,7 +36595,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36461
36595
  });
36462
36596
  $ = cheerio3.load(outputHTML);
36463
36597
  const downloadedImagePaths = await this.eBookDownloadImages($, dest);
36464
- if (path18.extname(dest) === ".html") {
36598
+ if (path19.extname(dest) === ".html") {
36465
36599
  if (ebookConfig["cover"]) {
36466
36600
  const cover = ebookConfig["cover"];
36467
36601
  const coverUrl = cover[0] === "/" ? toFileURL(cover) : cover;
@@ -36479,11 +36613,11 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36479
36613
  const title = ebookConfig["title"] || "no title";
36480
36614
  let mathStyle = "";
36481
36615
  if (outputHTML.indexOf('class="katex"') > 0) {
36482
- if (path18.extname(dest) === ".html" && ebookConfig["html"] && ebookConfig["html"]["cdn"]) {
36616
+ if (path19.extname(dest) === ".html" && ebookConfig["html"] && ebookConfig["html"]["cdn"]) {
36483
36617
  mathStyle = `<link rel="stylesheet" href="https://${this.notebook.config.jsdelivrCdnHost}/npm/katex@0.16.47/dist/katex.min.css">`;
36484
36618
  } else {
36485
36619
  mathStyle = `<link rel="stylesheet" href="${toFileURL(
36486
- path18.resolve(
36620
+ path19.resolve(
36487
36621
  getCrossnoteBuildDirectory(),
36488
36622
  "./dependencies/katex/katex.min.css"
36489
36623
  )
@@ -36495,14 +36629,14 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36495
36629
  const styles = await Promise.all([
36496
36630
  // style template
36497
36631
  await this.fs.readFile(
36498
- path18.resolve(
36632
+ path19.resolve(
36499
36633
  getCrossnoteBuildDirectory(),
36500
36634
  "./styles/style-template.css"
36501
36635
  )
36502
36636
  ),
36503
36637
  // prism *.css
36504
36638
  await this.fs.readFile(
36505
- path18.resolve(
36639
+ path19.resolve(
36506
36640
  getCrossnoteBuildDirectory(),
36507
36641
  `./styles/prism_theme/${_MarkdownEngine.resolveThemeForExport(
36508
36642
  _MarkdownEngine.AutoPrismThemeMap[ebookConfig["theme"] || this.notebook.config.previewTheme] ?? "default.css",
@@ -36512,14 +36646,14 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36512
36646
  ),
36513
36647
  // twemoji css style
36514
36648
  await this.fs.readFile(
36515
- path18.resolve(
36649
+ path19.resolve(
36516
36650
  getCrossnoteBuildDirectory(),
36517
36651
  "./styles/twemoji.css"
36518
36652
  )
36519
36653
  ),
36520
36654
  // preview theme
36521
36655
  await this.fs.readFile(
36522
- path18.resolve(
36656
+ path19.resolve(
36523
36657
  getCrossnoteBuildDirectory(),
36524
36658
  `./styles/preview_theme/${_MarkdownEngine.resolveThemeForExport(
36525
36659
  ebookConfig["theme"] || this.notebook.config.previewTheme,
@@ -36529,14 +36663,14 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36529
36663
  ),
36530
36664
  // markdown-it-admonition
36531
36665
  outputHTML.indexOf("admonition") > 0 ? await this.fs.readFile(
36532
- path18.resolve(
36666
+ path19.resolve(
36533
36667
  getCrossnoteBuildDirectory(),
36534
36668
  "./styles/markdown-it-admonition.css"
36535
36669
  )
36536
36670
  ) : "",
36537
36671
  // markdown-it-callout
36538
36672
  outputHTML.indexOf("callout") > 0 ? await this.fs.readFile(
36539
- path18.resolve(
36673
+ path19.resolve(
36540
36674
  getCrossnoteBuildDirectory(),
36541
36675
  "./styles/markdown-it-callout.css"
36542
36676
  )
@@ -36548,7 +36682,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36548
36682
  }
36549
36683
  let globalStyles = "";
36550
36684
  try {
36551
- globalStyles = this.notebook.config.globalCss;
36685
+ globalStyles = this.resolvePathsInStyles(this.notebook.config.globalCss);
36552
36686
  } catch {
36553
36687
  }
36554
36688
  html = `
@@ -36565,14 +36699,14 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36565
36699
  ${mathStyle}
36566
36700
  ${await this.resolvePathsInHeader(this.notebook.config.includeInHeader)}
36567
36701
  </head>
36568
- <body ${path18.extname(dest) === ".html" ? 'for="html-export"' : ""}>
36702
+ <body ${path19.extname(dest) === ".html" ? 'for="html-export"' : ""}>
36569
36703
  <div class="crossnote markdown-preview">
36570
36704
  ${outputHTML}
36571
36705
  </div>
36572
36706
  </body>
36573
36707
  </html>
36574
36708
  `;
36575
- if (path18.extname(dest) === ".html") {
36709
+ if (path19.extname(dest) === ".html") {
36576
36710
  await this.fs.writeFile(dest, html);
36577
36711
  return dest;
36578
36712
  }
@@ -36688,11 +36822,11 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36688
36822
  markdownConfig["path"] = this.filePath.replace(/\.src\./, ".");
36689
36823
  } else {
36690
36824
  markdownConfig["path"] = this.filePath.replace(
36691
- new RegExp(path18.extname(this.filePath)),
36692
- "_" + path18.extname(this.filePath)
36825
+ new RegExp(path19.extname(this.filePath)),
36826
+ "_" + path19.extname(this.filePath)
36693
36827
  );
36694
36828
  }
36695
- markdownConfig["path"] = path18.basename(markdownConfig["path"]);
36829
+ markdownConfig["path"] = path19.basename(markdownConfig["path"]);
36696
36830
  }
36697
36831
  if (markdownConfig["ignore_from_front_matter"] || !("ignore_from_front_matter" in markdownConfig)) {
36698
36832
  delete config["markdown"];
@@ -36779,13 +36913,13 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36779
36913
  return filePath;
36780
36914
  } else if (filePath[0] === "/") {
36781
36915
  if (relative11) {
36782
- return path18.relative(
36916
+ return path19.relative(
36783
36917
  fileDirectoryPath || this.fileDirectoryPath,
36784
- path18.resolve(this.projectDirectoryPath.fsPath, "." + filePath)
36918
+ path19.resolve(this.projectDirectoryPath.fsPath, "." + filePath)
36785
36919
  );
36786
36920
  } else {
36787
36921
  return addFileProtocol(
36788
- path18.resolve(this.projectDirectoryPath.fsPath, "." + filePath),
36922
+ path19.resolve(this.projectDirectoryPath.fsPath, "." + filePath),
36789
36923
  this.vscodePreviewPanel
36790
36924
  );
36791
36925
  }
@@ -36794,12 +36928,33 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36794
36928
  return filePath;
36795
36929
  } else {
36796
36930
  return addFileProtocol(
36797
- path18.resolve(fileDirectoryPath || this.fileDirectoryPath, filePath),
36931
+ path19.resolve(fileDirectoryPath || this.fileDirectoryPath, filePath),
36798
36932
  this.vscodePreviewPanel
36799
36933
  );
36800
36934
  }
36801
36935
  }
36802
36936
  }
36937
+ /**
36938
+ * Turn the absolute filesystem paths that `resolveRelativeCssUrls` left in
36939
+ * the user's compiled `style.less` into URLs the current render target can
36940
+ * load — `vscode-webview://…` inside a VS Code webview, `file://…` for every
36941
+ * export path and for `crossnote serve`.
36942
+ *
36943
+ * Without this the preview inlines `<style>` with the paths still raw, and a
36944
+ * relative `@font-face src` (or `background-image`) resolves against the
36945
+ * webview document instead of the stylesheet, so local fonts silently fall
36946
+ * back while remote ones keep working
36947
+ * ([vscode-mpe#2424](https://github.com/shd101wyy/vscode-markdown-preview-enhanced/issues/2424)).
36948
+ */
36949
+ resolvePathsInStyles(css, vscodePreviewPanel) {
36950
+ if (!css) {
36951
+ return css;
36952
+ }
36953
+ return mapAbsoluteCssUrls(
36954
+ css,
36955
+ (filePath) => addFileProtocol(filePath, vscodePreviewPanel)
36956
+ );
36957
+ }
36803
36958
  // FIXME: This function actually doesn't help in the web version.
36804
36959
  async resolvePathsInHeader(header, {
36805
36960
  allowScripts = false,
@@ -36814,9 +36969,9 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36814
36969
  $(element).remove();
36815
36970
  return;
36816
36971
  }
36817
- const candidatePaths = src.startsWith("/") ? [path18.resolve(this.projectDirectoryPath.fsPath, "." + src)] : [
36818
- path18.resolve(this.fileDirectoryPath, src),
36819
- ...trustedScriptRoots.map((root) => path18.resolve(root, src))
36972
+ const candidatePaths = src.startsWith("/") ? [path19.resolve(this.projectDirectoryPath.fsPath, "." + src)] : [
36973
+ path19.resolve(this.fileDirectoryPath, src),
36974
+ ...trustedScriptRoots.map((root) => path19.resolve(root, src))
36820
36975
  ];
36821
36976
  const resolvedPath = candidatePaths.find(
36822
36977
  (p) => isExistingFile(p) && (this.isPathInsideProjectDirectory(p) || trustedScriptRoots.some(
@@ -37076,9 +37231,9 @@ sidebarTOCBtn.addEventListener('click', function(event) {
37076
37231
  i += 1;
37077
37232
  }
37078
37233
  const pandocPath = this.notebook.config.pandocPath;
37079
- return await new Promise((resolve20, reject) => {
37234
+ return await new Promise((resolve21, reject) => {
37080
37235
  try {
37081
- const program = (0, import_child_process13.execFile)(
37236
+ const program = (0, import_child_process11.execFile)(
37082
37237
  pandocPath,
37083
37238
  args,
37084
37239
  { cwd: this.fileDirectoryPath, maxBuffer: Infinity },
@@ -37086,11 +37241,11 @@ sidebarTOCBtn.addEventListener('click', function(event) {
37086
37241
  if (error) {
37087
37242
  return reject(error);
37088
37243
  } else if (stderr) {
37089
- return resolve20(
37244
+ return resolve21(
37090
37245
  '<pre class="language-text"><code>' + (0, import_html_escaper13.escape)(stderr) + "</code></pre>" + stdout
37091
37246
  );
37092
37247
  } else {
37093
- return resolve20(stdout);
37248
+ return resolve21(stdout);
37094
37249
  }
37095
37250
  }
37096
37251
  );
@@ -37167,7 +37322,7 @@ Check "http://pandoc.org/installing.html" website.`;
37167
37322
  )}</code></pre>`;
37168
37323
  }
37169
37324
  } else {
37170
- this.notebook.currentRenderFilePath = path18.relative(
37325
+ this.notebook.currentRenderFilePath = path19.relative(
37171
37326
  this.notebook.notebookPath.fsPath,
37172
37327
  this.filePath
37173
37328
  );
@@ -37411,7 +37566,7 @@ ${result}
37411
37566
  // src/wiki/index.ts
37412
37567
  var cheerio4 = __toESM(require("cheerio"));
37413
37568
  var fs18 = __toESM(require("fs"));
37414
- var path22 = __toESM(require("path"));
37569
+ var path23 = __toESM(require("path"));
37415
37570
 
37416
37571
  // src/serve/preview-host-shim.ts
37417
37572
  function previewHostShimScript(targetOriginExpression) {
@@ -37438,15 +37593,6 @@ function previewHostShimScript(targetOriginExpression) {
37438
37593
  };
37439
37594
  return api;
37440
37595
  };
37441
- // The shell tells the frames when zen mode is on: Esc must then exit zen
37442
- // (the welcome card and the exit button both promise that), instead of the
37443
- // preview's own Esc behavior of toggling the sidebar TOC.
37444
- var zenMode = false;
37445
- window.addEventListener('message', function (event) {
37446
- if (event.data && event.data.command === '__serverAppZenMode') {
37447
- zenMode = !!event.data.enabled;
37448
- }
37449
- });
37450
37596
  document.addEventListener('keydown', function (event) {
37451
37597
  var key = event.key.toLowerCase();
37452
37598
  var action = null;
@@ -37456,8 +37602,6 @@ function previewHostShimScript(targetOriginExpression) {
37456
37602
  action = 'split-pane';
37457
37603
  } else if (event.altKey && key === 'w') {
37458
37604
  action = 'close-tab';
37459
- } else if (key === 'escape' && zenMode) {
37460
- action = 'exit-zen-mode';
37461
37605
  }
37462
37606
  if (action) {
37463
37607
  event.preventDefault();
@@ -37473,35 +37617,35 @@ function previewHostShimScript(targetOriginExpression) {
37473
37617
 
37474
37618
  // src/serve/config.ts
37475
37619
  var fs16 = __toESM(require("fs"));
37476
- var os3 = __toESM(require("os"));
37477
- var path20 = __toESM(require("path"));
37620
+ var os4 = __toESM(require("os"));
37621
+ var path21 = __toESM(require("path"));
37478
37622
 
37479
37623
  // src/serve/config-writer.ts
37480
37624
  var fs15 = __toESM(require("fs"));
37481
- var os2 = __toESM(require("os"));
37482
- var path19 = __toESM(require("path"));
37625
+ var os3 = __toESM(require("os"));
37626
+ var path20 = __toESM(require("path"));
37483
37627
  var import_json53 = __toESM(require("json5"));
37484
37628
  var MPE_SETTINGS_PREFIX = "markdown-preview-enhanced.";
37485
37629
  function detectVSCodeSettingsPath(explicitPath) {
37486
37630
  if (explicitPath) {
37487
- return path19.resolve(explicitPath);
37631
+ return path20.resolve(explicitPath);
37488
37632
  }
37489
- const home = os2.homedir();
37633
+ const home = os3.homedir();
37490
37634
  const candidates = process.platform === "win32" ? [
37491
- path19.join(home, "AppData/Roaming/Code - Insiders/User/settings.json"),
37492
- path19.join(home, "AppData/Roaming/Code/User/settings.json")
37635
+ path20.join(home, "AppData/Roaming/Code - Insiders/User/settings.json"),
37636
+ path20.join(home, "AppData/Roaming/Code/User/settings.json")
37493
37637
  ] : process.platform === "darwin" ? [
37494
- path19.join(
37638
+ path20.join(
37495
37639
  home,
37496
37640
  "Library/Application Support/Code - Insiders/User/settings.json"
37497
37641
  ),
37498
- path19.join(
37642
+ path20.join(
37499
37643
  home,
37500
37644
  "Library/Application Support/Code/User/settings.json"
37501
37645
  )
37502
37646
  ] : [
37503
- path19.join(home, ".config/Code - Insiders/User/settings.json"),
37504
- path19.join(home, ".config/Code/User/settings.json")
37647
+ path20.join(home, ".config/Code - Insiders/User/settings.json"),
37648
+ path20.join(home, ".config/Code/User/settings.json")
37505
37649
  ];
37506
37650
  for (const candidate of candidates) {
37507
37651
  if (fs15.existsSync(candidate)) {
@@ -37565,18 +37709,42 @@ async function updateVSCodeSetting(settingsPath, key, value) {
37565
37709
  `;
37566
37710
  } else {
37567
37711
  const head = trimmed.slice(0, lastBrace).replace(/\s+$/, "");
37568
- const needsComma = head.length > 0 && !head.endsWith("{");
37569
- text = head + (needsComma ? "," : "") + `
37712
+ const candidates = [",", "\n,", ""];
37713
+ const insertions = candidates.map(
37714
+ (separator) => head + separator + `
37570
37715
  "${MPE_SETTINGS_PREFIX}${key}": ${serialized}
37571
37716
  }
37572
- `;
37717
+ `
37718
+ );
37719
+ const valid = insertions.find((candidate) => {
37720
+ try {
37721
+ import_json53.default.parse(candidate);
37722
+ return true;
37723
+ } catch {
37724
+ return false;
37725
+ }
37726
+ });
37727
+ if (!valid) {
37728
+ throw new Error(
37729
+ `cannot insert "${MPE_SETTINGS_PREFIX}${key}" into ${settingsPath} while keeping it parseable`
37730
+ );
37731
+ }
37732
+ text = valid;
37573
37733
  }
37574
37734
  }
37575
- await fs15.promises.mkdir(path19.dirname(settingsPath), { recursive: true });
37735
+ try {
37736
+ import_json53.default.parse(text);
37737
+ } catch (error) {
37738
+ throw new Error(
37739
+ `refusing to write settings.json that no longer parses (${settingsPath}): ${error}`,
37740
+ { cause: error }
37741
+ );
37742
+ }
37743
+ await fs15.promises.mkdir(path20.dirname(settingsPath), { recursive: true });
37576
37744
  await fs15.promises.writeFile(settingsPath, text, "utf-8");
37577
37745
  }
37578
37746
  async function updateGlobalConfigKey(globalConfigDirectory, key, value) {
37579
- const configScriptPath = path19.join(globalConfigDirectory, "./config.js");
37747
+ const configScriptPath = path20.join(globalConfigDirectory, "./config.js");
37580
37748
  let parsed = {};
37581
37749
  if (fs15.existsSync(configScriptPath)) {
37582
37750
  const raw = await fs15.promises.readFile(configScriptPath, "utf-8");
@@ -37618,17 +37786,17 @@ ${JSON.stringify(
37618
37786
  // src/serve/config.ts
37619
37787
  function getGlobalConfigDirectory() {
37620
37788
  if (process.platform === "win32") {
37621
- return path20.join(os3.homedir(), "./.crossnote");
37789
+ return path21.join(os4.homedir(), "./.crossnote");
37622
37790
  }
37623
37791
  if (typeof process.env.XDG_CONFIG_HOME === "string" && process.env.XDG_CONFIG_HOME !== "") {
37624
- return path20.resolve(process.env.XDG_CONFIG_HOME, "./crossnote");
37792
+ return path21.resolve(process.env.XDG_CONFIG_HOME, "./crossnote");
37625
37793
  }
37626
- return path20.resolve(os3.homedir(), "./.local/state/crossnote");
37794
+ return path21.resolve(os4.homedir(), "./.local/state/crossnote");
37627
37795
  }
37628
37796
  async function createConfigContext(options) {
37629
37797
  const globalConfigDirectory = options.globalConfigDirectory ?? getGlobalConfigDirectory();
37630
37798
  return {
37631
- rootDirectory: path20.resolve(options.rootDirectory),
37799
+ rootDirectory: path21.resolve(options.rootDirectory),
37632
37800
  vscode: !!options.vscode,
37633
37801
  globalConfigDirectory,
37634
37802
  vscodeSettingsPath: options.vscode ? detectVSCodeSettingsPath(options.vscodeSettingsPath) : null
@@ -37650,7 +37818,7 @@ async function loadServerConfig(context) {
37650
37818
  console.error("Failed to load global crossnote config:", error);
37651
37819
  }
37652
37820
  let workspaceConfig = {};
37653
- const workspaceConfigDirectory = path20.join(
37821
+ const workspaceConfigDirectory = path21.join(
37654
37822
  context.rootDirectory,
37655
37823
  "./.crossnote"
37656
37824
  );
@@ -37687,7 +37855,7 @@ async function updateServerConfigKey(context, key, value) {
37687
37855
  async function createNotebooksForDirectories(directories, options = {}) {
37688
37856
  const rootDirectories = [];
37689
37857
  for (const directory of directories) {
37690
- const resolved = path20.resolve(directory);
37858
+ const resolved = path21.resolve(directory);
37691
37859
  const stat3 = await fs16.promises.stat(resolved).catch(() => null);
37692
37860
  if (!stat3?.isDirectory()) {
37693
37861
  throw new Error(`Not a directory: ${resolved}`);
@@ -37719,12 +37887,12 @@ async function createNotebooksForDirectories(directories, options = {}) {
37719
37887
 
37720
37888
  // src/serve/markdown-files.ts
37721
37889
  var fs17 = __toESM(require("fs"));
37722
- var path21 = __toESM(require("path"));
37890
+ var path22 = __toESM(require("path"));
37723
37891
  var import_ignore2 = __toESM(require("ignore"));
37724
37892
  var MARKDOWN_EXTENSIONS = [".md", ".markdown", ".mdx"];
37725
37893
  var SKIPPED_DIRECTORY_NAMES = /* @__PURE__ */ new Set(["node_modules", ".git"]);
37726
37894
  function isMarkdownFile(filePath) {
37727
- return MARKDOWN_EXTENSIONS.includes(path21.extname(filePath).toLowerCase());
37895
+ return MARKDOWN_EXTENSIONS.includes(path22.extname(filePath).toLowerCase());
37728
37896
  }
37729
37897
  function encodePathSegments(relativePath) {
37730
37898
  return relativePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
@@ -37742,7 +37910,7 @@ function isPathWithinRootOn(platform, root, candidate) {
37742
37910
  return candidate === root || candidate.startsWith(root + "/");
37743
37911
  }
37744
37912
  async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37745
- const gitignorePath = path21.join(rootDirectory, ".gitignore");
37913
+ const gitignorePath = path22.join(rootDirectory, ".gitignore");
37746
37914
  let isIgnored = () => false;
37747
37915
  try {
37748
37916
  if (fs17.existsSync(gitignorePath)) {
@@ -37763,8 +37931,8 @@ async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37763
37931
  continue;
37764
37932
  }
37765
37933
  for (const entry of entries) {
37766
- const absolutePath = path21.join(directory, entry.name);
37767
- const relativePath = path21.relative(rootDirectory, absolutePath).split(path21.sep).join("/");
37934
+ const absolutePath = path22.join(directory, entry.name);
37935
+ const relativePath = path22.relative(rootDirectory, absolutePath).split(path22.sep).join("/");
37768
37936
  if (isIgnored(relativePath) || entry.isDirectory() && isIgnored(`${relativePath}/`)) {
37769
37937
  continue;
37770
37938
  }
@@ -37806,14 +37974,14 @@ var IMAGE_MIME_TYPES = {
37806
37974
  };
37807
37975
  var SCRIPT_STYLE_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".css"]);
37808
37976
  function isImagePath(filePath) {
37809
- const extension = path22.extname(filePath).toLowerCase().slice(1);
37977
+ const extension = path23.extname(filePath).toLowerCase().slice(1);
37810
37978
  return extension in IMAGE_MIME_TYPES;
37811
37979
  }
37812
37980
  function toPosixPath(filePath) {
37813
- return filePath.split(path22.sep).join("/");
37981
+ return filePath.split(path23.sep).join("/");
37814
37982
  }
37815
37983
  async function buildWiki(options) {
37816
- const buildDirectory = path22.resolve(
37984
+ const buildDirectory = path23.resolve(
37817
37985
  options.crossnoteBuildDirectory ?? getCrossnoteBuildDirectory()
37818
37986
  );
37819
37987
  setCrossnoteBuildDirectory(buildDirectory);
@@ -37826,17 +37994,17 @@ async function buildWiki(options) {
37826
37994
  }
37827
37995
  );
37828
37996
  const multiRoot = rootDirectories.length > 1;
37829
- const rootNames = rootDirectories.map((root) => path22.basename(root) || root);
37997
+ const rootNames = rootDirectories.map((root) => path23.basename(root) || root);
37830
37998
  const noteKeyFor = (absolutePath, rootIndex) => {
37831
37999
  const relative11 = toPosixPath(
37832
- path22.relative(rootDirectories[rootIndex], absolutePath)
38000
+ path23.relative(rootDirectories[rootIndex], absolutePath)
37833
38001
  );
37834
38002
  return multiRoot ? `${rootNames[rootIndex]}/${relative11}` : relative11;
37835
38003
  };
37836
38004
  const assetIds = /* @__PURE__ */ new Map();
37837
38005
  let assetCounter = 0;
37838
38006
  const tokenFor = (filePath) => {
37839
- const resolved = path22.resolve(filePath);
38007
+ const resolved = path23.resolve(filePath);
37840
38008
  let id = assetIds.get(resolved);
37841
38009
  if (id === void 0) {
37842
38010
  id = String(assetCounter++);
@@ -37845,7 +38013,7 @@ async function buildWiki(options) {
37845
38013
  return `${ASSET_TOKEN_PREFIX}${id}`;
37846
38014
  };
37847
38015
  const dataUriForImage = (filePath) => {
37848
- const extension = path22.extname(filePath).toLowerCase().slice(1);
38016
+ const extension = path23.extname(filePath).toLowerCase().slice(1);
37849
38017
  const mime = IMAGE_MIME_TYPES[extension];
37850
38018
  if (!mime) {
37851
38019
  return null;
@@ -37877,7 +38045,7 @@ async function buildWiki(options) {
37877
38045
  const cleanPath = resolvedPath(filePath);
37878
38046
  if (isPathWithinRoot(buildDirectory, cleanPath)) {
37879
38047
  const relativeToBuild = toPosixPath(
37880
- path22.relative(buildDirectory, cleanPath)
38048
+ path23.relative(buildDirectory, cleanPath)
37881
38049
  );
37882
38050
  if (relativeToBuild.startsWith("styles/preview_theme/")) {
37883
38051
  return `${THEME_TOKEN_PREFIX}preview`;
@@ -37901,10 +38069,10 @@ async function buildWiki(options) {
37901
38069
  }
37902
38070
  return addFileProtocol(cleanPath);
37903
38071
  }
37904
- if (SCRIPT_STYLE_EXTENSIONS.has(path22.extname(cleanPath).toLowerCase())) {
38072
+ if (SCRIPT_STYLE_EXTENSIONS.has(path23.extname(cleanPath).toLowerCase())) {
37905
38073
  return tokenFor(cleanPath);
37906
38074
  }
37907
- const relative11 = path22.relative(root, cleanPath);
38075
+ const relative11 = path23.relative(root, cleanPath);
37908
38076
  return `/${toPosixPath(relative11)}`;
37909
38077
  }
37910
38078
  return addFileProtocol(cleanPath);
@@ -37947,7 +38115,7 @@ async function buildWiki(options) {
37947
38115
  head: ""
37948
38116
  });
37949
38117
  const yamlConfig = output.yamlConfig;
37950
- const title = typeof yamlConfig["title"] === "string" && yamlConfig["title"].trim() || path22.basename(file.absolutePath, path22.extname(file.absolutePath));
38118
+ const title = typeof yamlConfig["title"] === "string" && yamlConfig["title"].trim() || path23.basename(file.absolutePath, path23.extname(file.absolutePath));
37951
38119
  const mtimeMs = (await fs18.promises.stat(file.absolutePath)).mtimeMs;
37952
38120
  files.push({
37953
38121
  path: noteKey,
@@ -37991,11 +38159,11 @@ async function buildWiki(options) {
37991
38159
  }
37992
38160
  const assets = {};
37993
38161
  for (const [filePath, id] of assetIds) {
37994
- assets[id] = path22.extname(filePath).toLowerCase() === ".css" ? await readStylesheetWithInlinedUrls(filePath) : await fs18.promises.readFile(filePath, "utf-8").catch(() => "");
38162
+ assets[id] = path23.extname(filePath).toLowerCase() === ".css" ? await readStylesheetWithInlinedUrls(filePath) : await fs18.promises.readFile(filePath, "utf-8").catch(() => "");
37995
38163
  }
37996
- assets["graph-view.js"] = await fs18.promises.readFile(path22.join(buildDirectory, "webview", "graph-view.js"), "utf-8").catch(() => "");
38164
+ assets["graph-view.js"] = await fs18.promises.readFile(path23.join(buildDirectory, "webview", "graph-view.js"), "utf-8").catch(() => "");
37997
38165
  assets["graph-view.css"] = await readStylesheetWithInlinedUrls(
37998
- path22.join(buildDirectory, "webview", "graph-view.css")
38166
+ path23.join(buildDirectory, "webview", "graph-view.css")
37999
38167
  ).catch(() => "");
38000
38168
  const themes = await collectThemeAssets(buildDirectory, notebooks[0]);
38001
38169
  const graph = {};
@@ -38022,7 +38190,7 @@ async function buildWiki(options) {
38022
38190
  }
38023
38191
  try {
38024
38192
  backlinks[file.path] = (await notebook.getNoteBacklinks(
38025
- path22.join(rootDirectories[rootIndex], ...file.path.split("/"))
38193
+ path23.join(rootDirectories[rootIndex], ...file.path.split("/"))
38026
38194
  ) ?? []).map(
38027
38195
  (backlink) => scrubBacklinkForWiki(backlink, rootDirectories[rootIndex])
38028
38196
  );
@@ -38036,14 +38204,17 @@ async function buildWiki(options) {
38036
38204
  files,
38037
38205
  assets,
38038
38206
  themes,
38207
+ // The zen state the notes were built with — the baseline the
38208
+ // context-menu toggle flips (first root anchors, like the themes).
38209
+ zenEnabled: notebooks[0].config.enablePreviewZenMode,
38039
38210
  graph,
38040
38211
  backlinks,
38041
38212
  buildDirectory
38042
38213
  });
38043
38214
  return {
38044
38215
  html,
38045
- files: files.map(({ path: path27, root, title, mtimeMs }) => ({
38046
- path: path27,
38216
+ files: files.map(({ path: path28, root, title, mtimeMs }) => ({
38217
+ path: path28,
38047
38218
  root,
38048
38219
  title,
38049
38220
  mtimeMs
@@ -38090,11 +38261,11 @@ function scrubWikiHtmlLinks(html, rootDirectory) {
38090
38261
  decoded = "/" + decoded;
38091
38262
  }
38092
38263
  }
38093
- const normalized = decoded.replace(/\//g, path22.sep);
38264
+ const normalized = decoded.replace(/\//g, path23.sep);
38094
38265
  if (!isPathWithinRoot(rootDirectory, normalized)) {
38095
38266
  continue;
38096
38267
  }
38097
- const relative11 = path22.relative(rootDirectory, normalized).split(path22.sep).join("/");
38268
+ const relative11 = path23.relative(rootDirectory, normalized).split(path23.sep).join("/");
38098
38269
  $(element).attr(attribute, `file:///${relative11}`);
38099
38270
  }
38100
38271
  });
@@ -38105,7 +38276,7 @@ function scrubWikiHtmlLinks(html, rootDirectory) {
38105
38276
  }
38106
38277
  async function collectThemeAssets(buildDirectory, notebook) {
38107
38278
  const readThemeDirectory = async (relativeDirectory) => {
38108
- const absoluteDirectory = path22.join(
38279
+ const absoluteDirectory = path23.join(
38109
38280
  buildDirectory,
38110
38281
  ...relativeDirectory.split("/")
38111
38282
  );
@@ -38116,7 +38287,7 @@ async function collectThemeAssets(buildDirectory, notebook) {
38116
38287
  continue;
38117
38288
  }
38118
38289
  map[entry] = await readStylesheetWithInlinedUrls(
38119
- path22.join(absoluteDirectory, entry)
38290
+ path23.join(absoluteDirectory, entry)
38120
38291
  );
38121
38292
  }
38122
38293
  return map;
@@ -38200,7 +38371,7 @@ async function readStylesheetWithInlinedUrls(cssPath) {
38200
38371
  } catch {
38201
38372
  return "";
38202
38373
  }
38203
- const directory = path22.dirname(cssPath);
38374
+ const directory = path23.dirname(cssPath);
38204
38375
  const cache = /* @__PURE__ */ new Map();
38205
38376
  return css.replace(
38206
38377
  /url\(\s*(['"]?)([^'")]+)\1\s*\)/g,
@@ -38212,8 +38383,8 @@ async function readStylesheetWithInlinedUrls(cssPath) {
38212
38383
  if (dataUri === void 0) {
38213
38384
  dataUri = "";
38214
38385
  try {
38215
- const assetPath = path22.resolve(directory, decodeURIComponent(ref));
38216
- const extension = path22.extname(assetPath).toLowerCase().slice(1);
38386
+ const assetPath = path23.resolve(directory, decodeURIComponent(ref));
38387
+ const extension = path23.extname(assetPath).toLowerCase().slice(1);
38217
38388
  const mime = IMAGE_MIME_TYPES[extension] ?? (extension === "woff2" ? "font/woff2" : extension === "woff" ? "font/woff" : extension === "ttf" ? "font/ttf" : extension === "otf" ? "font/otf" : extension === "eot" ? "application/vnd.ms-fontobject" : "application/octet-stream");
38218
38389
  const base64 = fs18.readFileSync(assetPath).toString("base64");
38219
38390
  dataUri = `data:${mime};base64,${base64}`;
@@ -38230,16 +38401,17 @@ function buildShellHTML({
38230
38401
  files,
38231
38402
  assets,
38232
38403
  themes,
38404
+ zenEnabled,
38233
38405
  graph,
38234
38406
  backlinks,
38235
38407
  buildDirectory
38236
38408
  }) {
38237
- const appScriptPath = path22.join(
38409
+ const appScriptPath = path23.join(
38238
38410
  buildDirectory,
38239
38411
  "server-app",
38240
38412
  "server-app.js"
38241
38413
  );
38242
- const appStylePath = path22.join(
38414
+ const appStylePath = path23.join(
38243
38415
  buildDirectory,
38244
38416
  "server-app",
38245
38417
  "server-app.css"
@@ -38259,6 +38431,7 @@ function buildShellHTML({
38259
38431
  rootDirectories: rootNames,
38260
38432
  assets,
38261
38433
  themes,
38434
+ zenEnabled,
38262
38435
  graph,
38263
38436
  backlinks,
38264
38437
  files
@@ -38440,7 +38613,7 @@ var SSEHub = class {
38440
38613
 
38441
38614
  // src/serve/static.ts
38442
38615
  var fs19 = __toESM(require("fs"));
38443
- var path23 = __toESM(require("path"));
38616
+ var path24 = __toESM(require("path"));
38444
38617
  var CONTENT_TYPES = {
38445
38618
  ".js": "text/javascript; charset=utf-8",
38446
38619
  ".mjs": "text/javascript; charset=utf-8",
@@ -38500,10 +38673,10 @@ function resolveMountedFile(mountRoots, urlPrefix, urlPath, preferredRootIndex)
38500
38673
  }
38501
38674
  }
38502
38675
  for (const index of candidates) {
38503
- const root = path23.resolve(mountRoots[index]);
38504
- const filePath = path23.resolve(
38676
+ const root = path24.resolve(mountRoots[index]);
38677
+ const filePath = path24.resolve(
38505
38678
  root,
38506
- `.${path23.sep}${relativePath.replace(/\//g, path23.sep)}`
38679
+ `.${path24.sep}${relativePath.replace(/\//g, path24.sep)}`
38507
38680
  );
38508
38681
  if (!isPathWithinRoot(root, filePath)) {
38509
38682
  continue;
@@ -38524,7 +38697,7 @@ function serveFileFromPath(response, filePath) {
38524
38697
  response.end("not found");
38525
38698
  return;
38526
38699
  }
38527
- const extension = path23.extname(filePath).toLowerCase();
38700
+ const extension = path24.extname(filePath).toLowerCase();
38528
38701
  const contentType = CONTENT_TYPES[extension] ?? "application/octet-stream";
38529
38702
  response.writeHead(200, {
38530
38703
  "content-type": contentType,
@@ -38543,7 +38716,7 @@ function serveFileFromPath(response, filePath) {
38543
38716
 
38544
38717
  // src/serve/watcher.ts
38545
38718
  var fs20 = __toESM(require("fs"));
38546
- var path24 = __toESM(require("path"));
38719
+ var path25 = __toESM(require("path"));
38547
38720
  var MarkdownWatcher = class {
38548
38721
  constructor(rootDirectory, onChange, pollIntervalMs = 1e3) {
38549
38722
  this.rootDirectory = rootDirectory;
@@ -38564,7 +38737,7 @@ var MarkdownWatcher = class {
38564
38737
  if (!filename) {
38565
38738
  return;
38566
38739
  }
38567
- const absolutePath = path24.resolve(this.rootDirectory, filename);
38740
+ const absolutePath = path25.resolve(this.rootDirectory, filename);
38568
38741
  if (!isMarkdownFile(absolutePath)) {
38569
38742
  return;
38570
38743
  }
@@ -38653,12 +38826,12 @@ var RequestError = class extends Error {
38653
38826
  };
38654
38827
  var MAX_COMMAND_BODY_BYTES = 64 * 1024 * 1024;
38655
38828
  async function nonConflictingWikiPath(rootDirectory) {
38656
- const base = path25.join(rootDirectory, "crossnote-wiki.html");
38829
+ const base = path26.join(rootDirectory, "crossnote-wiki.html");
38657
38830
  if (!fs21.existsSync(base)) {
38658
38831
  return base;
38659
38832
  }
38660
38833
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
38661
- return path25.join(rootDirectory, `crossnote-wiki-${stamp}.html`);
38834
+ return path26.join(rootDirectory, `crossnote-wiki-${stamp}.html`);
38662
38835
  }
38663
38836
  var PREVIEW_HOST_SHIM = previewHostShimScript("window.location.origin");
38664
38837
  var GRAPH_HOST_SHIM = graphHostShimScript({
@@ -38683,33 +38856,39 @@ function appShellHTML(serverInfo) {
38683
38856
  </html>`;
38684
38857
  }
38685
38858
  async function startServeServer(options) {
38859
+ process.on("unhandledRejection", (reason) => {
38860
+ console.error("crossnote serve: unhandled rejection:", reason);
38861
+ });
38686
38862
  const { rootDirectories, configContexts, notebooks } = await createNotebooksForDirectories(options.directories, {
38687
38863
  vscode: options.vscode,
38688
38864
  vscodeSettingsPath: options.vscodeSettingsPath,
38689
38865
  globalConfigDirectory: options.globalConfigDirectory
38690
38866
  });
38691
38867
  const rootDirectory = rootDirectories[0];
38692
- const buildDirectory = path25.resolve(
38868
+ const buildDirectory = path26.resolve(
38693
38869
  options.crossnoteBuildDirectory ?? utility.getCrossnoteBuildDirectory()
38694
38870
  );
38695
38871
  utility.setCrossnoteBuildDirectory(buildDirectory);
38696
38872
  const dummyPanel = {};
38697
38873
  utility.useExternalAddFileProtocolFunction((filePath) => {
38698
38874
  if (isPathWithinRoot(buildDirectory, filePath)) {
38699
- const relativePath = path25.relative(buildDirectory, filePath).split(path25.sep).join("/");
38875
+ const relativePath = path26.relative(buildDirectory, filePath).split(path26.sep).join("/");
38700
38876
  return `/assets/${encodePathSegments(relativePath)}`;
38701
38877
  }
38702
38878
  for (let index = 0; index < rootDirectories.length; index++) {
38703
38879
  if (isPathWithinRoot(rootDirectories[index], filePath)) {
38704
- const relativePath = path25.relative(rootDirectories[index], filePath).split(path25.sep).join("/");
38880
+ const relativePath = path26.relative(rootDirectories[index], filePath).split(path26.sep).join("/");
38705
38881
  const rootHint = rootDirectories.length > 1 ? `?root=${index}` : "";
38706
38882
  return `/files/${encodePathSegments(relativePath)}${rootHint}`;
38707
38883
  }
38708
38884
  }
38885
+ if (/^\/(?:files|assets)\//.test(filePath)) {
38886
+ return filePath;
38887
+ }
38709
38888
  return (0, import_url2.pathToFileURL)(filePath).href;
38710
38889
  });
38711
38890
  function rootIndexOf(absolutePath) {
38712
- const resolved = path25.resolve(absolutePath);
38891
+ const resolved = path26.resolve(absolutePath);
38713
38892
  return rootDirectories.findIndex(
38714
38893
  (root) => isPathWithinRoot(root, resolved)
38715
38894
  );
@@ -38786,7 +38965,7 @@ async function startServeServer(options) {
38786
38965
  });
38787
38966
  }
38788
38967
  function assertFileWithinRoots(absolutePath) {
38789
- const resolved = path25.resolve(absolutePath);
38968
+ const resolved = path26.resolve(absolutePath);
38790
38969
  return rootIndexOf(resolved) === -1 ? null : resolved;
38791
38970
  }
38792
38971
  async function readJSONBody(request) {
@@ -38882,14 +39061,15 @@ async function startServeServer(options) {
38882
39061
  }
38883
39062
  case "setPreviewTheme":
38884
39063
  case "setCodeBlockTheme":
38885
- case "setRevealjsTheme": {
38886
- const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : "revealjsTheme";
38887
- const theme = typeof args[1] === "string" ? args[1] : null;
38888
- if (!theme) {
39064
+ case "setRevealjsTheme":
39065
+ case "togglePreviewZenMode": {
39066
+ const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : command === "setRevealjsTheme" ? "revealjsTheme" : "enablePreviewZenMode";
39067
+ const value = command === "togglePreviewZenMode" ? !notebooks[0].config.enablePreviewZenMode : typeof args[1] === "string" ? args[1] : null;
39068
+ if (value === null) {
38889
39069
  return;
38890
39070
  }
38891
39071
  try {
38892
- await updateServerConfigKey(configContexts[0], configKey, theme);
39072
+ await updateServerConfigKey(configContexts[0], configKey, value);
38893
39073
  await Promise.all(
38894
39074
  configContexts.map(async (context, index) => {
38895
39075
  const mergedConfig = await loadServerConfig(
@@ -38908,6 +39088,11 @@ async function startServeServer(options) {
38908
39088
  `crossnote serve: failed to persist ${configKey}:`,
38909
39089
  error
38910
39090
  );
39091
+ sse.broadcast({
39092
+ type: "notification",
39093
+ level: "error",
39094
+ message: `Failed to save "${configKey}": ${error instanceof Error ? error.message : String(error)}`
39095
+ });
38911
39096
  }
38912
39097
  return;
38913
39098
  }
@@ -38980,6 +39165,64 @@ async function startServeServer(options) {
38980
39165
  }
38981
39166
  return;
38982
39167
  }
39168
+ case "htmlExport":
39169
+ case "chromeExport":
39170
+ case "princeExport":
39171
+ case "eBookExport":
39172
+ case "pandocExport":
39173
+ case "markdownExport": {
39174
+ const sourceUri = assertFileWithinRoots(String(args[0] ?? ""));
39175
+ const param = args[1];
39176
+ if (!sourceUri || !isMarkdownFile(sourceUri)) {
39177
+ return;
39178
+ }
39179
+ const engine = notebookForFile(sourceUri)?.getNoteMarkdownEngine(sourceUri);
39180
+ if (!engine) {
39181
+ return;
39182
+ }
39183
+ try {
39184
+ let dest;
39185
+ if (command === "htmlExport") {
39186
+ dest = await engine.htmlExport({ offline: param === true });
39187
+ } else if (command === "chromeExport") {
39188
+ dest = await engine.chromeExport({
39189
+ fileType: typeof param === "string" ? param : "pdf"
39190
+ });
39191
+ } else if (command === "princeExport") {
39192
+ dest = await engine.princeExport({});
39193
+ if (dest.endsWith("?print-pdf")) {
39194
+ sse.broadcast({
39195
+ type: "notification",
39196
+ level: "info",
39197
+ message: `Please open the link below in Chrome and print it as PDF: ${dest}`
39198
+ });
39199
+ return;
39200
+ }
39201
+ } else if (command === "eBookExport") {
39202
+ dest = await engine.eBookExport({
39203
+ fileType: typeof param === "string" ? param : "epub",
39204
+ runAllCodeChunks: false
39205
+ });
39206
+ } else if (command === "pandocExport") {
39207
+ dest = await engine.pandocExport({});
39208
+ } else {
39209
+ dest = await engine.markdownExport({});
39210
+ }
39211
+ sse.broadcast({
39212
+ type: "notification",
39213
+ level: "info",
39214
+ message: `Exported ${path26.basename(sourceUri)} to ${dest}`
39215
+ });
39216
+ } catch (error) {
39217
+ console.error(`crossnote serve: ${command} failed:`, error);
39218
+ sse.broadcast({
39219
+ type: "notification",
39220
+ level: "error",
39221
+ message: `${command} failed: ${error instanceof Error ? error.message : String(error)}`
39222
+ });
39223
+ }
39224
+ return;
39225
+ }
38983
39226
  case "exportStandaloneWiki": {
38984
39227
  try {
38985
39228
  const result = await buildWiki({
@@ -39153,7 +39396,7 @@ async function startServeServer(options) {
39153
39396
  });
39154
39397
  const data = constructGraphView(graphNotebook);
39155
39398
  const rootIndex = rootIndexOf(file);
39156
- const relativePath = rootIndex === -1 ? "" : path25.relative(rootDirectories[rootIndex], file).split(path25.sep).join("/");
39399
+ const relativePath = rootIndex === -1 ? "" : path26.relative(rootDirectories[rootIndex], file).split(path26.sep).join("/");
39157
39400
  sendJSON(response, 200, { data, activeFilePath: relativePath });
39158
39401
  } catch (error) {
39159
39402
  console.error("crossnote serve: failed to build graph data:", error);
@@ -39244,7 +39487,7 @@ async function startServeServer(options) {
39244
39487
  watchers.forEach((watcher) => watcher.close());
39245
39488
  sse.dispose();
39246
39489
  await new Promise(
39247
- (resolve20, reject) => server.close((error) => error ? reject(error) : resolve20())
39490
+ (resolve21, reject) => server.close((error) => error ? reject(error) : resolve21())
39248
39491
  );
39249
39492
  }
39250
39493
  };
@@ -39313,7 +39556,7 @@ function isAllowedOrigin(originHeader, bindHost, port) {
39313
39556
  return isAllowedRequestHost(origin.host, bindHost, port);
39314
39557
  }
39315
39558
  function listenWithFallback(server, host, port) {
39316
- return new Promise((resolve20, reject) => {
39559
+ return new Promise((resolve21, reject) => {
39317
39560
  const tryPort = (candidate, remainingAttempts) => {
39318
39561
  const onError = (error) => {
39319
39562
  if (error.code === "EADDRINUSE" && remainingAttempts > 0 && candidate !== 0) {
@@ -39330,7 +39573,7 @@ function listenWithFallback(server, host, port) {
39330
39573
  reject(new Error("failed to bind server"));
39331
39574
  return;
39332
39575
  }
39333
- resolve20(address.port);
39576
+ resolve21(address.port);
39334
39577
  });
39335
39578
  };
39336
39579
  tryPort(port, port === 3e3 ? 20 : 0);
@@ -39421,7 +39664,7 @@ function parseCommandLine(argv, spec) {
39421
39664
  console.error(`Unknown option: ${arg}`);
39422
39665
  return null;
39423
39666
  }
39424
- directories.push(path26.resolve(process.cwd(), arg));
39667
+ directories.push(path27.resolve(process.cwd(), arg));
39425
39668
  i += 1;
39426
39669
  }
39427
39670
  return { values, directories };
@@ -39523,7 +39766,7 @@ async function serve(argv) {
39523
39766
  // The CLI bundle lives in <package>/out/cli, so the build directory with
39524
39767
  // webview/, dependencies/ and styles/ is one level up unless a host that
39525
39768
  // bundles the CLI elsewhere passes its own copy via --build-dir.
39526
- crossnoteBuildDirectory: parsed.buildDirectory ?? path26.resolve(__dirname, "../")
39769
+ crossnoteBuildDirectory: parsed.buildDirectory ?? path27.resolve(__dirname, "../")
39527
39770
  });
39528
39771
  if (parsed.json) {
39529
39772
  console.log(
@@ -39572,17 +39815,17 @@ async function buildWikiCommand(argv) {
39572
39815
  process.exitCode = 1;
39573
39816
  return;
39574
39817
  }
39575
- const outputPath = path26.resolve(
39818
+ const outputPath = path27.resolve(
39576
39819
  process.cwd(),
39577
39820
  parsed.output ?? "./index.html"
39578
39821
  );
39579
- await fs22.promises.mkdir(path26.dirname(outputPath), { recursive: true });
39822
+ await fs22.promises.mkdir(path27.dirname(outputPath), { recursive: true });
39580
39823
  let lastRoot = null;
39581
39824
  const result = await buildWiki({
39582
39825
  directories,
39583
39826
  vscode: parsed.vscode,
39584
39827
  vscodeSettingsPath: parsed.vscodeSettingsPath,
39585
- crossnoteBuildDirectory: parsed.buildDirectory ?? path26.resolve(__dirname, "../"),
39828
+ crossnoteBuildDirectory: parsed.buildDirectory ?? path27.resolve(__dirname, "../"),
39586
39829
  onProgress: ({ rendered, total, root }) => {
39587
39830
  if (root !== lastRoot) {
39588
39831
  if (lastRoot !== null) {