From 81924f72c8b2ee4dd2079d0d3d74f46830bc352a Mon Sep 17 00:00:00 2001 From: Alois Klink Date: Thu, 27 Oct 2022 16:43:09 +0100 Subject: [PATCH 1/5] Revert "Merge branch 'release_9.2.0_buggfixes'" This reverts commit 1a0309fb8758518b9f99dbdc406094db85e3885a, reversing changes made to 56a8068a7f0cc9784f875a6d385bf9414eeab98b. This is because the PR https://github.com/mermaid-js/mermaid/pull/3702 worked fine on the `develop` and `release_9.2.0_buggfixes` branches, but had a bunch of git merge conflicts on the `release/9.2.0` branch. --- cypress/platform/knsv2.html | 2 +- packages/mermaid/src/mermaid.spec.ts | 23 +--------------- packages/mermaid/src/mermaid.ts | 41 ++++++---------------------- 3 files changed, 11 insertions(+), 55 deletions(-) diff --git a/cypress/platform/knsv2.html b/cypress/platform/knsv2.html index 968d04f72..de9780185 100644 --- a/cypress/platform/knsv2.html +++ b/cypress/platform/knsv2.html @@ -72,7 +72,7 @@ classDiagram Student "1" --o "1" IdCard : carries Student "1" --o "1" Bike : rides -
+    
 mindmap
   root
     child1((Circle))
diff --git a/packages/mermaid/src/mermaid.spec.ts b/packages/mermaid/src/mermaid.spec.ts
index e3bc69448..8cf180ae7 100644
--- a/packages/mermaid/src/mermaid.spec.ts
+++ b/packages/mermaid/src/mermaid.spec.ts
@@ -48,32 +48,11 @@ describe('when using mermaid and ', function () {
       const node = document.createElement('div');
       node.appendChild(document.createTextNode('graph TD;\na;'));
 
-      await mermaid.initThrowsErrors(undefined, node);
+      mermaid.initThrowsErrors(undefined, node);
       // mermaidAPI.render function has been mocked, since it doesn't yet work
       // in Node.JS (only works in browser)
       expect(mermaidAPI.render).toHaveBeenCalled();
     });
-    it('should throw error (but still render) if lazyLoadedDiagram fails', async () => {
-      const node = document.createElement('div');
-      node.appendChild(document.createTextNode('graph TD;\na;'));
-
-      mermaidAPI.setConfig({
-        lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'],
-      });
-      await expect(mermaid.initThrowsErrors(undefined, node)).rejects.toThrowError(
-        // this error message is probably different on every platform
-        // this one is just for vite-note (node/jest/browser may be different)
-        'Failed to load this-file-does-not-exist.mjs'
-      );
-
-      // should still render, even if lazyLoadedDiagrams fails
-      expect(mermaidAPI.render).toHaveBeenCalled();
-    });
-
-    afterEach(() => {
-      // we modify mermaid config in some tests, so we need to make sure to reset them
-      mermaidAPI.reset();
-    });
   });
 
   describe('checking validity of input ', function () {
diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index 5867dc3b2..b1700253b 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -47,7 +47,13 @@ const init = async function (
   callback?: Function
 ) {
   try {
-    await initThrowsErrors(config, nodes, callback);
+    const conf = mermaidAPI.getConfig();
+    if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
+      await registerLazyLoadedDiagrams(conf);
+      await initThrowsErrorsAsync(config, nodes, callback);
+    } else {
+      initThrowsErrors(config, nodes, callback);
+    }
   } catch (e) {
     log.warn('Syntax Error rendering');
     if (isDetailedError(e)) {
@@ -84,19 +90,7 @@ const handleError = (error: unknown, errors: DetailedError[], parseError?: Funct
     }
   }
 };
-/**
- * Equivalent to {@link init()}, except an error will be thrown on error.
- *
- * @param config - **Deprecated** Mermaid sequenceConfig.
- * @param nodes - One of:
- * - A DOM Node
- * - An array of DOM nodes (as would come from a jQuery selector)
- * - A W3C selector, a la `.mermaid` (default)
- * @param callback - Function that is called with the id of each generated mermaid diagram.
- *
- * @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
- */
-const initThrowsErrors = async function (
+const initThrowsErrors = function (
   config?: MermaidConfig,
   // eslint-disable-next-line no-undef
   nodes?: string | HTMLElement | NodeListOf,
@@ -110,24 +104,6 @@ const initThrowsErrors = async function (
     mermaid.sequenceConfig = config;
   }
 
-  const errors = [];
-
-  if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
-    // Load all lazy loaded diagrams in parallel
-    const results = await Promise.allSettled(
-      conf.lazyLoadedDiagrams.map(async (diagram: string) => {
-        const { id, detector, loadDiagram } = await import(diagram);
-        addDetector(id, detector, loadDiagram);
-      })
-    );
-    for (const result of results) {
-      if (result.status == 'rejected') {
-        log.warn(`Failed to lazyLoadedDiagram due to `, result.reason);
-        errors.push(result.reason);
-      }
-    }
-  }
-
   // if last argument is a function this is the callback function
   log.debug(`${!callback ? 'No ' : ''}Callback function found`);
   let nodesToProcess: ArrayLike;
@@ -153,6 +129,7 @@ const initThrowsErrors = async function (
   const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
 
   let txt: string;
+  const errors: DetailedError[] = [];
 
   // element is the current div with mermaid class
   for (const element of Array.from(nodesToProcess)) {

From 327fcbf902581e7e6d519803ba62f3658166dc9d Mon Sep 17 00:00:00 2001
From: Alois Klink 
Date: Thu, 27 Oct 2022 16:50:57 +0100
Subject: [PATCH 2/5] fix: lazy load diagrams in initThrowsErrorsAsync

Previously, calling initThrowsErrorsAsync would not
load any of the lazyLoadedDiagrams entries.

Adaptated from reverted commit 4601c90904fb57f54ed91e31ea235b24de5add45
---
 packages/mermaid/src/mermaid.ts | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index b1700253b..c1b164b67 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -49,7 +49,6 @@ const init = async function (
   try {
     const conf = mermaidAPI.getConfig();
     if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
-      await registerLazyLoadedDiagrams(conf);
       await initThrowsErrorsAsync(config, nodes, callback);
     } else {
       initThrowsErrors(config, nodes, callback);
@@ -229,6 +228,9 @@ const initThrowsErrorsAsync = async function (
   callback?: Function
 ) {
   const conf = mermaidAPI.getConfig();
+
+  await registerLazyLoadedDiagrams(conf);
+
   if (config) {
     // This is a legacy way of setting config. It is not documented and should be removed in the future.
     // @ts-ignore: TODO Fix ts errors

From 13110c4ed9c431a7dadd82c6179796ee8071eba7 Mon Sep 17 00:00:00 2001
From: Alois Klink 
Date: Thu, 20 Oct 2022 10:53:08 +0100
Subject: [PATCH 3/5] docs(mermaid): document initThrowsErrorsAsync

Add some basic tsdoc for initThrowsErrorsAsync.
---
 packages/mermaid/src/mermaid.ts | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index c1b164b67..a49e4b700 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -217,9 +217,20 @@ const loadExternalDiagrams = async (conf: MermaidConfig) => {
 };
 
 /**
- * @deprecated This is an internal function and should not be used. Will be removed in v10.
+ * Equivalent to {@link init()}, except an error will be thrown on error.
+ *
+ * @alpha
+ * @deprecated This is an internal function and will very likely be modified in v10, or earlier.
+ * We recommend staying with {@link initThrowsErrors} if you don't need `lazyLoadedDiagrams`.
+ *
+ * @param config - **Deprecated** Mermaid sequenceConfig.
+ * @param nodes - One of:
+ * - A DOM Node
+ * - An array of DOM nodes (as would come from a jQuery selector)
+ * - A W3C selector, a la `.mermaid` (default)
+ * @param callback - Function that is called with the id of each generated mermaid diagram.
+ * @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
  */
-
 const initThrowsErrorsAsync = async function (
   config?: MermaidConfig,
   // eslint-disable-next-line no-undef

From e62dd255bc27d9a3e2e051698742437769cde95e Mon Sep 17 00:00:00 2001
From: Alois Klink 
Date: Thu, 27 Oct 2022 17:18:41 +0100
Subject: [PATCH 4/5] feat: expose initThrowsErrorsAsync publicly

Expose the function `initThrowsErrorsAsync()` publicly
as `mermaid.initThrowsErrorsAsync()`.

It has the TSDoc `@alpha` and `@deprecated` tags, so people should
be warned that it might be modified in Mermaid v10 or earlier.

Needed for `mermaid-cli` to handle `lazyLoadedDiagrams`.
---
 packages/mermaid/src/mermaid.ts | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index a49e4b700..98111886e 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -513,6 +513,7 @@ const mermaid: {
   renderAsync: typeof renderAsync;
   init: typeof init;
   initThrowsErrors: typeof initThrowsErrors;
+  initThrowsErrorsAsync: typeof initThrowsErrorsAsync;
   initialize: typeof initialize;
   initializeAsync: typeof initializeAsync;
   contentLoaded: typeof contentLoaded;
@@ -527,6 +528,7 @@ const mermaid: {
   renderAsync,
   init,
   initThrowsErrors,
+  initThrowsErrorsAsync,
   initialize,
   initializeAsync,
   parseError: undefined,

From 48b1f489fc022438672090c75d13af067605a186 Mon Sep 17 00:00:00 2001
From: Alois Klink 
Date: Thu, 27 Oct 2022 17:30:11 +0100
Subject: [PATCH 5/5] fix(mermaid): error if lazyLoadedDiagrams fails

Throws and logs a warning if lazyLoadedDiagrams fails to load properly.

Rendering is still performed, even on a lazyLoadedDiagrams failure.
---
 packages/mermaid/src/__mocks__/mermaidAPI.ts |  1 +
 packages/mermaid/src/mermaid.spec.ts         | 23 +++++++++++++++++++
 packages/mermaid/src/mermaid.ts              | 24 +++++++++++++-------
 3 files changed, 40 insertions(+), 8 deletions(-)

diff --git a/packages/mermaid/src/__mocks__/mermaidAPI.ts b/packages/mermaid/src/__mocks__/mermaidAPI.ts
index 08c5b7eea..6eccaac48 100644
--- a/packages/mermaid/src/__mocks__/mermaidAPI.ts
+++ b/packages/mermaid/src/__mocks__/mermaidAPI.ts
@@ -25,6 +25,7 @@ function parse(text: string, parseError?: Function): boolean {
 // original version cannot be modified since it was frozen with `Object.freeze()`
 export const mermaidAPI = {
   render: vi.fn(),
+  renderAsync: vi.fn(),
   parse,
   parseDirective: vi.fn(),
   initialize: vi.fn(),
diff --git a/packages/mermaid/src/mermaid.spec.ts b/packages/mermaid/src/mermaid.spec.ts
index 8cf180ae7..534b3e964 100644
--- a/packages/mermaid/src/mermaid.spec.ts
+++ b/packages/mermaid/src/mermaid.spec.ts
@@ -54,6 +54,29 @@ describe('when using mermaid and ', function () {
       expect(mermaidAPI.render).toHaveBeenCalled();
     });
   });
+  describe('when using #initThrowsErrorsAsync', function () {
+    it('should throw error (but still render) if lazyLoadedDiagram fails', async () => {
+      const node = document.createElement('div');
+      node.appendChild(document.createTextNode('graph TD;\na;'));
+
+      mermaidAPI.setConfig({
+        lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'],
+      });
+      await expect(mermaid.initThrowsErrorsAsync(undefined, node)).rejects.toThrowError(
+        // this error message is probably different on every platform
+        // this one is just for vite-note (node/jest/browser may be different)
+        'Failed to load this-file-does-not-exist.mjs'
+      );
+
+      // should still render, even if lazyLoadedDiagrams fails
+      expect(mermaidAPI.renderAsync).toHaveBeenCalled();
+    });
+
+    afterEach(() => {
+      // we modify mermaid config in some tests, so we need to make sure to reset them
+      mermaidAPI.reset();
+    });
+  });
 
   describe('checking validity of input ', function () {
     it('should throw for an invalid definition', function () {
diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index 98111886e..2a11088e6 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -177,10 +177,12 @@ const initThrowsErrors = function (
   }
 };
 
-let lazyLoadingPromise: Promise | undefined = undefined;
+let lazyLoadingPromise: Promise[]> | undefined = undefined;
 /**
- * @param conf
- * @deprecated This is an internal function and should not be used. Will be removed in v10.
+ * This is an internal function and should not be made public, as it will likely change.
+ * @internal
+ * @param conf - Mermaid config.
+ * @returns An array of {@link PromiseSettledResult}, showing the status of imports.
  */
 const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
   // Only lazy load once
@@ -194,7 +196,7 @@ const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
       })
     );
   }
-  await lazyLoadingPromise;
+  return await lazyLoadingPromise;
 };
 
 let loadingPromise: Promise | undefined = undefined;
@@ -229,7 +231,7 @@ const loadExternalDiagrams = async (conf: MermaidConfig) => {
  * - An array of DOM nodes (as would come from a jQuery selector)
  * - A W3C selector, a la `.mermaid` (default)
  * @param callback - Function that is called with the id of each generated mermaid diagram.
- * @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
+ * @returns Resolves on success, otherwise the {@link Promise} will be rejected.
  */
 const initThrowsErrorsAsync = async function (
   config?: MermaidConfig,
@@ -240,7 +242,12 @@ const initThrowsErrorsAsync = async function (
 ) {
   const conf = mermaidAPI.getConfig();
 
-  await registerLazyLoadedDiagrams(conf);
+  const registerLazyLoadedDiagramsErrors: Error[] = [];
+  for (const registerResult of await registerLazyLoadedDiagrams(conf)) {
+    if (registerResult.status == 'rejected') {
+      registerLazyLoadedDiagramsErrors.push(registerResult.reason);
+    }
+  }
 
   if (config) {
     // This is a legacy way of setting config. It is not documented and should be removed in the future.
@@ -316,9 +323,10 @@ const initThrowsErrorsAsync = async function (
       handleError(error, errors, mermaid.parseError);
     }
   }
-  if (errors.length > 0) {
+  const allErrors = [...registerLazyLoadedDiagramsErrors, ...errors];
+  if (allErrors.length > 0) {
     // TODO: We should be throwing an error object.
-    throw errors[0];
+    throw allErrors[0];
   }
 };