javascript regex can not find and replace markdown codeblock correctly

I have installed a mermaid plugin for Gitbook via gitbook-plugin-mermaid-gb3, this plugin can parse code via markdown code block markup and translate it to a svg file, the code block is like below:

```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```

But when I use it I found for some code it will not working, after check I found it was a bug inside the plugin.

The code is come from index.js and related parse code listed below:

var mermaidRegex = /^```mermaid((.*[rn]+)+?)?```$/im;

function processMermaidBlockList(page) {

  var match;

  while ((match = mermaidRegex.exec(page.content))) {
    var rawBlock = match[0];
    var mermaidContent = match[1];
    page.content = page.content.replace(rawBlock, '<div class="mermaid">' +
      mermaidContent + '</div>');
  }

  return page;
}

The regex expression is /^```mermaid((.*[rn]+)+?)?```$/im,but it can only find code bock starts with “`mermaid,if there are space before or after it,it will not working

What I expected is like below

-- valid
```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```

-- valid, there can be space between ``` and mermaid
``` mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```

-- valid, there can be space before or after ```
 ```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
  ```
  
--invalid, there can not be have extra characters before ```
abc```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```  

--invalid, there can not be have extra characters before ```
abc ```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```  

--invalid, there can not be have extra characters after ```
```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```  abc

I changed /^```mermaid((.*[rn]+)+?)?```$/im to /s*```s*mermaid((.*[rn]+)+?)?```$/gm and test it via https://regex101.com/r/CIrooL/1,it seems okay,but not working inside javascript, I do not know why.

// this line will be blocked using the updated regex
while ((match = mermaidRegex.exec(page.content))) {
}

Can anyone help me,please?
Thanks in advance!