Repository: MikhailKravets/mkdocs_puml

Issue:
IndexError on version 1.4.0
**Describe the bug**
When building `mkdocs` documentation with `mkdocs_puml==1.4.0` we are seeing the following error:

```
  File "/usr/local/lib/python3.10/dist-packages/mkdocs/__main__.py", line 288, in build_command
    build.build(cfg, dirty=not clean)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs/commands/build.py", line 319, in build
    env = config.plugins.on_env(env, config=config, files=files)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs/plugins.py", line 599, in on_env
    return self.run_event('env', env, config=config, files=files)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs/plugins.py", line 566, in run_event
    result = method(item, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs_puml/plugin.py", line 137, in on_env
    dark_svgs = self.puml_dark.translate(diagram_contents)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs_puml/puml.py", line 66, in translate
    return [self.postprocess(v) for v in svg_images]
  File "/usr/local/lib/python3.10/dist-packages/mkdocs_puml/puml.py", line 66, in <listcomp>
    return [self.postprocess(v) for v in svg_images]
  File "/usr/local/lib/python3.10/dist-packages/mkdocs_puml/puml.py", line 96, in postprocess
    svg = self._convert_to_dom(diagram_content)
  File "/usr/local/lib/python3.10/dist-packages/mkdocs_puml/puml.py", line 123, in _convert_to_dom
    svg = dom.getElementsByTagName("svg")[0]
IndexError: list index out of range
```

With version 1.3.1 it worked fine 2 hours ago.

**To Reproduce**
Steps to reproduce the behavior:
1. Run `pip install 'mkdocs-material>=9,<10' 'mkdocs_puml>=1,<2' && mkdocs build`
2. See error

**Expected behavior**
Build passes as it does on version 1.3.1.

**Desktop:**
 - OS: Ubuntu 22.04 with Python 3.10
 - Dependency versions: `babel-2.16.0 ghp-import-2.1.0 markdown-3.7 mergedeep-1.3.4 mkdocs-1.6.1 mkdocs-get-deps-0.2.0 mkdocs-material-9.5.39 mkdocs-material-extensions-1.3.1 mkdocs_puml-1.4.0 paginate-0.5.7 pathspec-0.12.1 pymdown-extensions-10.11.2 pyyaml-env-tag-0.1 regex-2024.9.11 watchdog-5.0.3`

Hints from issue comments:
@MikhailKravets: Thanks for raising this issue @smartYSC. I'll research this asap@MikhailKravets: @smartYSC, could you please also share your `mkdocs.yml` configuration?

**UPD** I couldn't recreate the error using my default `mkdocs.yml` and the libs and python of versions you provided. I assume there can be a conflict among plugins that triggers this behavior.@MaciejKucia: Sample mkdocs:

```yaml
---
site_name: Documentation
site_url: https://site/documentation
theme: material
plugins:
  - mermaid2
  - techdocs-core
  - plantuml:
      puml_url: https://plantuml.site
      puml_keyword: plantuml
markdown_extensions:
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:mermaid2.fence_mermaid
  - pymdownx.extra:
      pymdownx.superfences:
        custom_fences:
          - name: mermaid
            class: mermaid
            format: !!python/name:pymdownx.superfences.fence_code_format
  - pymdownx.emoji:
      emoji_index: !!python/name:material.extensions.emoji.twemoji
      emoji_generator: !!python/name:material.extensions.emoji.to_svg
extra_javascript:
  - https://unpkg.com/mermaid@11.2.1/dist/mermaid.min.js
```

Pyproject
```toml
[tool.poetry]
name = "docs"
package-mode = false

[tool.poetry.dependencies]
python = "^3.12"
mkdocs-material = ">=9.5,<10.0"
mkdocs-mermaid2-plugin = ">=1.1,<2.0"
mkdocs-techdocs-core = ">=1.3,<2.0"
mkdocs-puml = ">=1.3,<2.0"
```

This problem is caused by the dark mode + custom plantuml. 

The page returned from `/dsvg` endpoint is a 404 html with no svg element hence the index error on `getElementsByTagName`


@MaciejKucia: The workaround is to disable the automatic dark mode.

```yaml
  - plantuml:
      puml_url: https://plantuml.site
      puml_keyword: plantuml
      auto_dark: false
```

This resolves the error.

I would personally see 2 outcomes here:

* keep the old behaviour by having `auto_dark: false` as a default option
* better handle plantuml 404 response on the `/dsvg` endpoint
@kserard: I would be in favor of the second solution, gracefully handling old plantuml servers.@MikhailKravets: Thanks for your help @MaciejKucia! I guess for now it would be the best to fallback to light diagrams in case of error. I'll investigate this problem in more details. We anyway build 2 versions of diagrams, so perhaps it'll be better to integrate theme directly inside `puml` code.@outadoc: Hi! First of all, thanks for the project :)

We're getting this error as well on the latest version.

> I would be in favor of the second solution, gracefully handling old plantuml servers.

I'm curious of the root cause for this issue -- is it related to the PlantUML server version? We're getting this error even though we're running the latest version (1.2024.7) of https://github.com/plantuml/plantuml-server 's docker image.@MikhailKravets: Thanks @outadoc :) 

Perhaps this may be related. From time to time I get `509 Bandwidth Limit Exceeded` from PlantUML. I may suppose `/dsvg` path is not intended for use in cases like ours. I hope #49 will hotfix the `IndexError` issue. I have a plan to allow user to choose between light and dark themes, which will be inserted directly into puml diagrams rather than relying on `/dsvg`@MikhailKravets: Hotfix should be available in `mkdocs_puml==1.4.1`. Thanks everyone for participation!@MikhailKravets: Guys, you may try now `2.0.0rc1` version. 

```
pip install mkdocs_puml==2.0.0rc1
```

this significantly improves theming in mkdocs_puml. [Read more about release](https://github.com/MikhailKravets/mkdocs_puml/releases/tag/v2.0.0rc1).@smartYSC: Sorry for not responding to your questions! Version 1.4.1 gives at least a proper error message, that it could not build dark mode diagrams, but then a dark mode documentation without diagrams is created. Light mode has working diagrams.

Version 2.0.0 creates dark mode diagrams correctly. We just see a certificate error, because our PUML server uses a self-signed certificate and `httpx` wants to see the [`SSL_CERT_DIR`](https://www.python-httpx.org/environment_variables/#ssl_cert_dir) environment variable to use system certificates (just putting this here so others can find it).@MikhailKravets: @smartYSC thanks for this note. At minimum I should add this to documentation.

Solution patch:
diff --git a/mkdocs_puml/puml.py b/mkdocs_puml/puml.py
index 0ec9467..6826ee5 100644
--- a/mkdocs_puml/puml.py
+++ b/mkdocs_puml/puml.py
@@ -28,6 +28,7 @@ class PlantUML:
     """
 
     _html_comment_regex = re.compile(r"<!--.*?-->", flags=re.DOTALL)
+    ERROR_SVG = '<svg><text>Error</text></svg>'
 
     def __init__(
         self,
@@ -109,6 +110,9 @@ def request(self, encoded_diagram: str) -> str:
         """
         resp = requests.get(urljoin(self.base_url, encoded_diagram), verify=self.verify_ssl)
 
+        if not resp.ok:
+            return self.ERROR_SVG
+
         # Use 'ignore' to strip non-utf chars
         return resp.content.decode("utf-8", errors="ignore")
 


Test patch:
diff --git a/tests/plugins/test_plugin.py b/tests/plugins/test_plugin.py
index 84d6036..59eba07 100644
--- a/tests/plugins/test_plugin.py
+++ b/tests/plugins/test_plugin.py
@@ -151,3 +151,17 @@ def test_replace_method(plant_uml_plugin):
     result = plant_uml_plugin._replace(key, content)
     assert '<div class="puml light"><svg>light</svg></div>' in result
     assert '<div class="puml dark"><svg>dark</svg></div>' in result
+
+
+def test_unsupported_output(mock_requests, plant_uml_plugin, diagrams_dict, plugin_environment):
+    # All requests return an erroneous response
+    mock_requests.return_value.ok = False
+
+    # Try converting to SVG
+    plant_uml_plugin.auto_dark = True
+    plant_uml_plugin.diagrams = diagrams_dict
+    plant_uml_plugin.on_env(plugin_environment)
+
+    for diagram in plant_uml_plugin.diagrams.values():
+        for variant in diagram:
+            assert '<text>Error</text>' in variant