crossnote 0.9.36 → 0.9.37

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
@@ -23825,7 +23825,13 @@ function getCrossnoteBuildDirectory() {
23825
23825
  }
23826
23826
  var _externalAddFileProtocolFunction = null;
23827
23827
  function useExternalAddFileProtocolFunction(func) {
23828
+ const previous = _externalAddFileProtocolFunction;
23828
23829
  _externalAddFileProtocolFunction = func;
23830
+ return () => {
23831
+ if (_externalAddFileProtocolFunction === func) {
23832
+ _externalAddFileProtocolFunction = previous;
23833
+ }
23834
+ };
23829
23835
  }
23830
23836
  function addFileProtocol(filePath, vscodePreviewPanel) {
23831
23837
  if (_externalAddFileProtocolFunction && vscodePreviewPanel) {
@@ -34883,11 +34889,11 @@ function isPathInsideDirectory(parentDirectoryPath, filePath) {
34883
34889
  return p;
34884
34890
  }
34885
34891
  };
34886
- const relative10 = path18.relative(
34892
+ const relative11 = path18.relative(
34887
34893
  realpath(parentDirectoryPath),
34888
34894
  realpath(filePath)
34889
34895
  );
34890
- return relative10 !== "" && !relative10.startsWith("..") && !path18.isAbsolute(relative10);
34896
+ return relative11 !== "" && !relative11.startsWith("..") && !path18.isAbsolute(relative11);
34891
34897
  }
34892
34898
  function isExistingFile(filePath) {
34893
34899
  try {
@@ -35379,9 +35385,10 @@ window["initRevealPresentation"] = async function() {
35379
35385
  config,
35380
35386
  vscodePreviewPanel = null,
35381
35387
  contentSecurityPolicy = "",
35382
- isVSCodeWebExtension: isVSCodeWebExtension2
35388
+ isVSCodeWebExtension: isVSCodeWebExtension2,
35389
+ parsedOutput
35383
35390
  }) {
35384
- if (!inputString) {
35391
+ if (!inputString && !parsedOutput) {
35385
35392
  inputString = await this.fs.readFile(this.filePath);
35386
35393
  }
35387
35394
  let webviewCss = "";
@@ -35404,15 +35411,12 @@ window["initRevealPresentation"] = async function() {
35404
35411
  if (!body) {
35405
35412
  body = ``;
35406
35413
  }
35407
- const { yamlConfig, JSAndCssFiles, html } = await this.parseMD(
35408
- inputString,
35409
- {
35410
- isForPreview: true,
35411
- useRelativeFilePath: false,
35412
- hideFrontMatter: false,
35413
- vscodePreviewPanel
35414
- }
35415
- );
35414
+ const { yamlConfig, JSAndCssFiles, html } = parsedOutput ?? await this.parseMD(inputString, {
35415
+ isForPreview: true,
35416
+ useRelativeFilePath: false,
35417
+ hideFrontMatter: false,
35418
+ vscodePreviewPanel
35419
+ });
35416
35420
  const isPresentationMode = yamlConfig["isPresentationMode"];
35417
35421
  const htmlTemplate = `<!DOCTYPE html>
35418
35422
  <html>
@@ -35467,7 +35471,7 @@ window["initRevealPresentation"] = async function() {
35467
35471
  )}
35468
35472
  ${head}
35469
35473
  </head>
35470
- <body class="preview-container ${isVSCodeWebExtension2 ? "vscode-web-extension" : ""}" data-html="${(0, import_html_escaper13.escape)(html)}" ${isPresentationMode ? "data-presentation-mode" : ""}>
35474
+ <body class="preview-container ${isVSCodeWebExtension2 ? "vscode-web-extension" : ""} ${config.isWiki ? "wiki-readonly" : ""}" data-html="${(0, import_html_escaper13.escape)(html)}" ${isPresentationMode ? "data-presentation-mode" : ""}>
35471
35475
  ${body}
35472
35476
  </body>
35473
35477
  ${this.generateScriptsForPreview(
@@ -36717,11 +36721,11 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36717
36721
  * @param filePath
36718
36722
  * @param relative: whether to use the path relative to filePath or not.
36719
36723
  */
36720
- resolveFilePath(filePath = "", relative10, fileDirectoryPath = "") {
36724
+ resolveFilePath(filePath = "", relative11, fileDirectoryPath = "") {
36721
36725
  if (filePath.match(this.protocolsWhiteListRegExp) || filePath.startsWith("data:image/") || filePath.startsWith("tag://") || filePath[0] === "#") {
36722
36726
  return filePath;
36723
36727
  } else if (filePath[0] === "/") {
36724
- if (relative10) {
36728
+ if (relative11) {
36725
36729
  return path18.relative(
36726
36730
  fileDirectoryPath || this.fileDirectoryPath,
36727
36731
  path18.resolve(this.projectDirectoryPath.fsPath, "." + filePath)
@@ -36733,7 +36737,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36733
36737
  );
36734
36738
  }
36735
36739
  } else {
36736
- if (relative10) {
36740
+ if (relative11) {
36737
36741
  return filePath;
36738
36742
  } else {
36739
36743
  return addFileProtocol(
@@ -37352,10 +37356,56 @@ ${result}
37352
37356
  };
37353
37357
 
37354
37358
  // src/wiki/index.ts
37355
- var cheerio4 = __toESM(require("cheerio"));
37356
37359
  var fs18 = __toESM(require("fs"));
37357
37360
  var path22 = __toESM(require("path"));
37358
37361
 
37362
+ // src/serve/preview-host-shim.ts
37363
+ function previewHostShimScript(targetOriginExpression) {
37364
+ return `<script>
37365
+ (function () {
37366
+ if (window.acquireVsCodeApi) { return; }
37367
+ var api = null;
37368
+ window.acquireVsCodeApi = function () {
37369
+ if (api) { return api; }
37370
+ api = {
37371
+ postMessage: function (message) {
37372
+ window.parent.postMessage(message, ${targetOriginExpression});
37373
+ },
37374
+ getState: function () {
37375
+ try {
37376
+ return JSON.parse(localStorage.getItem('crossnote-preview-state') || 'null');
37377
+ } catch (error) { return null; }
37378
+ },
37379
+ setState: function (state) {
37380
+ try {
37381
+ localStorage.setItem('crossnote-preview-state', JSON.stringify(state));
37382
+ } catch (error) { /* storage unavailable */ }
37383
+ },
37384
+ };
37385
+ return api;
37386
+ };
37387
+ document.addEventListener('keydown', function (event) {
37388
+ var key = event.key.toLowerCase();
37389
+ var action = null;
37390
+ if ((event.metaKey || event.ctrlKey) && !event.altKey && key === 'p') {
37391
+ action = 'open-file-picker';
37392
+ } else if ((event.metaKey || event.ctrlKey) && !event.altKey && key === '\\\\') {
37393
+ action = 'split-pane';
37394
+ } else if (event.altKey && key === 'w') {
37395
+ action = 'close-tab';
37396
+ }
37397
+ if (action) {
37398
+ event.preventDefault();
37399
+ window.parent.postMessage(
37400
+ { command: '__serverAppShortcut', args: [action] },
37401
+ ${targetOriginExpression}
37402
+ );
37403
+ }
37404
+ }, true);
37405
+ })();
37406
+ </script>`;
37407
+ }
37408
+
37359
37409
  // src/serve/config.ts
37360
37410
  var fs16 = __toESM(require("fs"));
37361
37411
  var os3 = __toESM(require("os"));
@@ -37666,35 +37716,27 @@ async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37666
37716
  }
37667
37717
 
37668
37718
  // src/wiki/index.ts
37669
- var WIKI_RELAY_SCRIPT = `(function () {
37670
- document.addEventListener('click', function (event) {
37671
- var node = event.target;
37672
- var anchor = node && node.closest ? node.closest('a') : null;
37673
- if (!anchor) {
37674
- if (node && node.classList && node.classList.contains('task-list-item-checkbox')) {
37675
- event.preventDefault();
37676
- }
37677
- return;
37678
- }
37679
- var href = anchor.getAttribute('href');
37680
- if (!href || href.charAt(0) === '#') {
37681
- return;
37682
- }
37683
- if (anchor.target === '_blank') {
37684
- return;
37685
- }
37686
- event.preventDefault();
37687
- if (/^https?:/i.test(href)) {
37688
- window.open(anchor.href, '_blank', 'noopener');
37689
- return;
37690
- }
37691
- if (/^(mailto:|tel:)/i.test(href)) {
37692
- window.location.href = href;
37693
- return;
37694
- }
37695
- parent.postMessage({ command: 'wiki-navigate', href: href }, '*');
37696
- }, true);
37697
- })();`;
37719
+ var ASSET_TOKEN_PREFIX = "crossnote-wiki-asset:";
37720
+ var WIKI_PREVIEW_HOST_SHIM = previewHostShimScript("'*'");
37721
+ var IMAGE_MIME_TYPES = {
37722
+ avif: "image/avif",
37723
+ bmp: "image/bmp",
37724
+ gif: "image/gif",
37725
+ ico: "image/x-icon",
37726
+ jpeg: "image/jpeg",
37727
+ jpg: "image/jpeg",
37728
+ png: "image/png",
37729
+ svg: "image/svg+xml",
37730
+ webp: "image/webp"
37731
+ };
37732
+ var SCRIPT_STYLE_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".css"]);
37733
+ function isImagePath(filePath) {
37734
+ const extension = path22.extname(filePath).toLowerCase().slice(1);
37735
+ return extension in IMAGE_MIME_TYPES;
37736
+ }
37737
+ function toPosixPath(filePath) {
37738
+ return filePath.split(path22.sep).join("/");
37739
+ }
37698
37740
  async function buildWiki(options) {
37699
37741
  const buildDirectory = path22.resolve(
37700
37742
  options.crossnoteBuildDirectory ?? getCrossnoteBuildDirectory()
@@ -37708,73 +37750,206 @@ async function buildWiki(options) {
37708
37750
  globalConfigDirectory: options.globalConfigDirectory
37709
37751
  }
37710
37752
  );
37753
+ const assetIds = /* @__PURE__ */ new Map();
37754
+ let assetCounter = 0;
37755
+ const tokenFor = (filePath) => {
37756
+ const resolved = path22.resolve(filePath);
37757
+ let id = assetIds.get(resolved);
37758
+ if (id === void 0) {
37759
+ id = String(assetCounter++);
37760
+ assetIds.set(resolved, id);
37761
+ }
37762
+ return `${ASSET_TOKEN_PREFIX}${id}`;
37763
+ };
37764
+ const dataUriForImage = (filePath) => {
37765
+ try {
37766
+ const extension = path22.extname(filePath).toLowerCase().slice(1);
37767
+ const mime = IMAGE_MIME_TYPES[extension];
37768
+ if (!mime) {
37769
+ return null;
37770
+ }
37771
+ const base64 = fs18.readFileSync(resolvedPath(filePath)).toString("base64");
37772
+ return `data:${mime};base64,${base64}`;
37773
+ } catch {
37774
+ return null;
37775
+ }
37776
+ };
37777
+ function resolvedPath(filePath) {
37778
+ return filePath.replace(/\?.+$/, "");
37779
+ }
37780
+ const dummyPanel = {};
37781
+ const restoreMapper = useExternalAddFileProtocolFunction(
37782
+ (filePath) => {
37783
+ const cleanPath = resolvedPath(filePath);
37784
+ if (isPathWithinRoot(buildDirectory, cleanPath)) {
37785
+ return tokenFor(cleanPath);
37786
+ }
37787
+ for (const root of rootDirectories) {
37788
+ if (!isPathWithinRoot(root, cleanPath)) {
37789
+ continue;
37790
+ }
37791
+ if (isImagePath(cleanPath)) {
37792
+ const dataUri = dataUriForImage(cleanPath);
37793
+ if (dataUri) {
37794
+ return dataUri;
37795
+ }
37796
+ return addFileProtocol(cleanPath);
37797
+ }
37798
+ if (SCRIPT_STYLE_EXTENSIONS.has(path22.extname(cleanPath).toLowerCase())) {
37799
+ return tokenFor(cleanPath);
37800
+ }
37801
+ const relative11 = path22.relative(root, cleanPath);
37802
+ return `/${toPosixPath(relative11)}`;
37803
+ }
37804
+ return addFileProtocol(cleanPath);
37805
+ }
37806
+ );
37711
37807
  const files = [];
37712
37808
  const failures = [];
37713
- for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
37714
- const root = rootDirectories[rootIndex];
37715
- const notebook = notebooks[rootIndex];
37716
- const markdownFiles = await listMarkdownFiles(root);
37717
- let processedInRoot = 0;
37718
- for (const file of markdownFiles) {
37719
- try {
37720
- const engine = notebook.getNoteMarkdownEngine(file.absolutePath);
37721
- let html2 = await engine.htmlExportDocument({
37722
- offline: false,
37723
- // A wiki is meant to be shared, so local images/SVGs travel with
37724
- // it as data URIs (front matter can still turn this off).
37725
- embedLocalImages: true,
37726
- embedSVG: true
37727
- });
37728
- let title = path22.basename(
37729
- file.absolutePath,
37730
- path22.extname(file.absolutePath)
37731
- );
37732
- const $ = cheerio4.load(html2);
37733
- $("head").prepend(`<script>${WIKI_RELAY_SCRIPT}</script>`);
37734
- const titleElement = $("title").first().text().trim();
37735
- if (titleElement) {
37736
- title = titleElement;
37737
- }
37738
- html2 = $.html();
37739
- files.push({ path: file.absolutePath, root, title, html: html2 });
37740
- } catch (error) {
37741
- failures.push({
37742
- path: file.absolutePath,
37743
- error: String(error)
37809
+ try {
37810
+ for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
37811
+ const root = rootDirectories[rootIndex];
37812
+ const notebook = notebooks[rootIndex];
37813
+ const markdownFiles = await listMarkdownFiles(root);
37814
+ let processedInRoot = 0;
37815
+ for (const file of markdownFiles) {
37816
+ try {
37817
+ const text = await fs18.promises.readFile(file.absolutePath, "utf-8");
37818
+ const engine = notebook.getNoteMarkdownEngine(file.absolutePath);
37819
+ const output = await engine.parseMD(text, {
37820
+ isForPreview: true,
37821
+ useRelativeFilePath: false,
37822
+ hideFrontMatter: false,
37823
+ vscodePreviewPanel: dummyPanel
37824
+ });
37825
+ const html2 = await engine.generateHTMLTemplateForPreview({
37826
+ inputString: text,
37827
+ parsedOutput: output,
37828
+ vscodePreviewPanel: dummyPanel,
37829
+ config: {
37830
+ sourceUri: file.absolutePath,
37831
+ isVSCode: false,
37832
+ isServerApp: true,
37833
+ isWiki: true
37834
+ },
37835
+ scripts: WIKI_PREVIEW_HOST_SHIM,
37836
+ // No <base>: same-document `#anchor` links must keep resolving to
37837
+ // the note document itself.
37838
+ head: ""
37839
+ });
37840
+ const yamlConfig = output.yamlConfig;
37841
+ const title = typeof yamlConfig["title"] === "string" && yamlConfig["title"].trim() || path22.basename(file.absolutePath, path22.extname(file.absolutePath));
37842
+ const mtimeMs = (await fs18.promises.stat(file.absolutePath)).mtimeMs;
37843
+ files.push({
37844
+ path: file.absolutePath,
37845
+ root,
37846
+ title,
37847
+ mtimeMs,
37848
+ html: html2,
37849
+ update: {
37850
+ markdown: text,
37851
+ html: output.html,
37852
+ tocHTML: output.tocHTML,
37853
+ totalLineCount: text.split("\n").length,
37854
+ sourceUri: file.absolutePath,
37855
+ sourceScheme: "file",
37856
+ id: yamlConfig["id"] || "",
37857
+ class: yamlConfig["class"] || "",
37858
+ jsAndCssFiles: output.JSAndCssFiles
37859
+ }
37860
+ });
37861
+ } catch (error) {
37862
+ failures.push({
37863
+ path: file.absolutePath,
37864
+ error: String(error)
37865
+ });
37866
+ }
37867
+ processedInRoot += 1;
37868
+ options.onProgress?.({
37869
+ rendered: processedInRoot,
37870
+ total: markdownFiles.length,
37871
+ root
37744
37872
  });
37745
37873
  }
37746
- processedInRoot += 1;
37747
- options.onProgress?.({
37748
- rendered: processedInRoot,
37749
- total: markdownFiles.length,
37750
- root
37751
- });
37752
37874
  }
37875
+ } finally {
37876
+ restoreMapper();
37753
37877
  }
37754
37878
  if (files.length === 0) {
37755
37879
  throw new Error(
37756
37880
  "no markdown notes found to build a wiki from" + (failures.length > 0 ? ` (${failures.length} notes failed to render)` : "")
37757
37881
  );
37758
37882
  }
37883
+ const assets = {};
37884
+ for (const [filePath, id] of assetIds) {
37885
+ assets[id] = path22.extname(filePath).toLowerCase() === ".css" ? await readStylesheetWithInlinedUrls(filePath) : await fs18.promises.readFile(filePath, "utf-8").catch(() => "");
37886
+ }
37759
37887
  const html = buildShellHTML({
37760
37888
  rootDirectories,
37761
37889
  files,
37890
+ assets,
37762
37891
  buildDirectory
37763
37892
  });
37764
37893
  return {
37765
37894
  html,
37766
- files: files.map(({ path: path27, root, title }) => ({ path: path27, root, title })),
37895
+ files: files.map(({ path: path27, root, title, mtimeMs }) => ({
37896
+ path: path27,
37897
+ root,
37898
+ title,
37899
+ mtimeMs
37900
+ })),
37767
37901
  rootDirectories,
37768
37902
  failures
37769
37903
  };
37770
37904
  }
37905
+ async function readStylesheetWithInlinedUrls(cssPath) {
37906
+ let css;
37907
+ try {
37908
+ css = await fs18.promises.readFile(cssPath, "utf-8");
37909
+ } catch {
37910
+ return "";
37911
+ }
37912
+ const directory = path22.dirname(cssPath);
37913
+ const cache = /* @__PURE__ */ new Map();
37914
+ return css.replace(
37915
+ /url\(\s*(['"]?)([^'")]+)\1\s*\)/g,
37916
+ (match, _quote, ref) => {
37917
+ if (ref.startsWith("data:") || ref.startsWith("#") || /^[a-z][a-z0-9+.-]*:/i.test(ref) || ref.startsWith("//")) {
37918
+ return match;
37919
+ }
37920
+ let dataUri = cache.get(ref);
37921
+ if (dataUri === void 0) {
37922
+ dataUri = "";
37923
+ try {
37924
+ const assetPath = path22.resolve(directory, decodeURIComponent(ref));
37925
+ const extension = path22.extname(assetPath).toLowerCase().slice(1);
37926
+ 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");
37927
+ const base64 = fs18.readFileSync(assetPath).toString("base64");
37928
+ dataUri = `data:${mime};base64,${base64}`;
37929
+ } catch {
37930
+ }
37931
+ cache.set(ref, dataUri);
37932
+ }
37933
+ return dataUri ? `url("${dataUri}")` : match;
37934
+ }
37935
+ );
37936
+ }
37771
37937
  function buildShellHTML({
37772
37938
  rootDirectories,
37773
37939
  files,
37940
+ assets,
37774
37941
  buildDirectory
37775
37942
  }) {
37776
- const appScriptPath = path22.join(buildDirectory, "wiki-app", "wiki-app.js");
37777
- const appStylePath = path22.join(buildDirectory, "wiki-app", "wiki-app.css");
37943
+ const appScriptPath = path22.join(
37944
+ buildDirectory,
37945
+ "server-app",
37946
+ "server-app.js"
37947
+ );
37948
+ const appStylePath = path22.join(
37949
+ buildDirectory,
37950
+ "server-app",
37951
+ "server-app.css"
37952
+ );
37778
37953
  let appScript;
37779
37954
  let appStyle;
37780
37955
  try {
@@ -37782,12 +37957,13 @@ function buildShellHTML({
37782
37957
  appStyle = fs18.readFileSync(appStylePath, "utf-8");
37783
37958
  } catch (error) {
37784
37959
  throw new Error(
37785
- `the wiki app bundle is missing (looked at ${appScriptPath}); rebuild crossnote so out/wiki-app/ exists`,
37960
+ `the server app bundle is missing (looked at ${appScriptPath}); rebuild crossnote so out/server-app/ exists`,
37786
37961
  { cause: error }
37787
37962
  );
37788
37963
  }
37789
37964
  const payload = JSON.stringify({
37790
37965
  rootDirectories,
37966
+ assets,
37791
37967
  files
37792
37968
  }).replace(/</g, "\\u003c");
37793
37969
  const safeAppScript = appScript.replace(/<\/script/g, "<\\/script");
@@ -38104,49 +38280,7 @@ async function nonConflictingWikiPath(rootDirectory) {
38104
38280
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
38105
38281
  return path25.join(rootDirectory, `crossnote-wiki-${stamp}.html`);
38106
38282
  }
38107
- var PREVIEW_HOST_SHIM = `<script>
38108
- (function () {
38109
- if (window.acquireVsCodeApi) { return; }
38110
- var api = null;
38111
- window.acquireVsCodeApi = function () {
38112
- if (api) { return api; }
38113
- api = {
38114
- postMessage: function (message) {
38115
- window.parent.postMessage(message, window.location.origin);
38116
- },
38117
- getState: function () {
38118
- try {
38119
- return JSON.parse(localStorage.getItem('crossnote-preview-state') || 'null');
38120
- } catch (error) { return null; }
38121
- },
38122
- setState: function (state) {
38123
- try {
38124
- localStorage.setItem('crossnote-preview-state', JSON.stringify(state));
38125
- } catch (error) { /* storage unavailable */ }
38126
- },
38127
- };
38128
- return api;
38129
- };
38130
- document.addEventListener('keydown', function (event) {
38131
- var key = event.key.toLowerCase();
38132
- var action = null;
38133
- if ((event.metaKey || event.ctrlKey) && !event.altKey && key === 'p') {
38134
- action = 'open-file-picker';
38135
- } else if ((event.metaKey || event.ctrlKey) && !event.altKey && key === '\\\\') {
38136
- action = 'split-pane';
38137
- } else if (event.altKey && key === 'w') {
38138
- action = 'close-tab';
38139
- }
38140
- if (action) {
38141
- event.preventDefault();
38142
- window.parent.postMessage(
38143
- { command: '__serverAppShortcut', args: [action] },
38144
- window.location.origin
38145
- );
38146
- }
38147
- }, true);
38148
- })();
38149
- </script>`;
38283
+ var PREVIEW_HOST_SHIM = previewHostShimScript("window.location.origin");
38150
38284
  function appShellHTML(serverInfo) {
38151
38285
  const serialized = JSON.stringify(serverInfo).replace(/</g, "\\u003c");
38152
38286
  return `<!DOCTYPE html>