qodalis-cli-server-plugin-docs 1.0.0b29__py3-none-any.whl

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.
@@ -0,0 +1,18 @@
1
+ """Qodalis CLI docs plugin — markdown guides from folders or code, with front
2
+ matter and variables, served as JSON for the portal site."""
3
+
4
+ from __future__ import annotations
5
+
6
+ #: The package's icon on the admin dashboard's plugins page (``CliInstalledPlugin.icon``).
7
+ __plugin_icon__ = "📚"
8
+
9
+ from .cli_docs_builder import DEFAULT_BASE_PATH, CliDocsBuilder, CliDocsPlugin
10
+ from .pages import DocsPage, parse_page
11
+
12
+ __all__ = [
13
+ "CliDocsBuilder",
14
+ "CliDocsPlugin",
15
+ "DEFAULT_BASE_PATH",
16
+ "DocsPage",
17
+ "parse_page",
18
+ ]
@@ -0,0 +1,200 @@
1
+ """Fluent builder for the docs plugin.
2
+
3
+ Usage::
4
+
5
+ docs_plugin = (
6
+ CliDocsBuilder()
7
+ .set_name("RateBell API")
8
+ .set_variable("support", "help@ratebell.app")
9
+ .add_folder("docs")
10
+ .build()
11
+ )
12
+ result.mount_plugin(docs_plugin)
13
+
14
+ ``GET /qcli/docs/pages`` lists the pages, ``GET /qcli/docs/pages/<slug>``
15
+ returns one with its markdown; ``{{baseUrl}}``, ``{{name}}`` and the host's
16
+ variables are replaced per request.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Union
23
+
24
+ from fastapi import APIRouter, Request
25
+ from fastapi.responses import JSONResponse
26
+
27
+ from .pages import (
28
+ DocsPage,
29
+ apply_variables,
30
+ parse_page,
31
+ read_folder,
32
+ sort_pages,
33
+ validate_slug,
34
+ validate_variable,
35
+ )
36
+
37
+ DEFAULT_BASE_PATH = "/qcli/docs"
38
+ DEFAULT_TITLE = "Guides"
39
+ DEFAULT_NAME = "Documentation"
40
+ PAGE_NOT_FOUND = "page not found"
41
+ _NO_CACHE = {"Cache-Control": "no-cache"}
42
+
43
+
44
+ class _Json(JSONResponse):
45
+ media_type = "application/json; charset=utf-8"
46
+
47
+
48
+
49
+ def validate_base_path(path: Any) -> str:
50
+ """Starts with ``/``, no trailing ``/``, not ``/`` itself."""
51
+ if (
52
+ not isinstance(path, str)
53
+ or not path.startswith("/")
54
+ or path == "/"
55
+ or path.endswith("/")
56
+ or "//" in path
57
+ or any(c.isspace() or ord(c) < 0x20 or c in "?#\\" for c in path)
58
+ ):
59
+ raise ValueError(f"invalid docs base path: {path}")
60
+ return path
61
+
62
+
63
+ @dataclass
64
+ class CliDocsPlugin:
65
+ """The built docs plugin: mount it with ``CliServerResult.mount_plugin``."""
66
+
67
+ prefix: str
68
+ router: APIRouter
69
+ #: The pages in page order, variables not replaced.
70
+ pages: list[DocsPage]
71
+ #: What the portal plugin shows (``CliPortalBuilder().add_section(...)``).
72
+ portal_section: dict[str, str]
73
+ name: str = DEFAULT_NAME
74
+ base_url: str | None = None
75
+ variables: dict[str, str] = field(default_factory=dict)
76
+ #: Host routes: never counted among the CLI's routes.
77
+ cli_routes: bool = False
78
+ #: Served without sign-in, also under ``/api/`` on a protected server
79
+ #: (the router answers everything under ``pages/`` itself).
80
+ public_paths: list[str] = field(default_factory=list)
81
+
82
+ def variables_for(self, request: Request) -> dict[str, str]:
83
+ base_url = self.base_url or (str(request.base_url).rstrip("/"))
84
+ return {**self.variables, "baseUrl": base_url, "name": self.name}
85
+
86
+
87
+ class CliDocsBuilder:
88
+ """Fluent builder for the docs plugin. Everything is checked by
89
+ :meth:`build` (``ValueError``)."""
90
+
91
+ def __init__(self) -> None:
92
+ self._base_path: Any = DEFAULT_BASE_PATH
93
+ self._title = DEFAULT_TITLE
94
+ self._name = DEFAULT_NAME
95
+ self._base_url: str | None = None
96
+ self._variables: dict[Any, str] = {}
97
+ #: Folders (``str``) and code pages (``(slug, markdown)``), in order.
98
+ self._sources: list[Union[str, tuple[Any, str]]] = []
99
+
100
+ def set_base_path(self, path: str) -> CliDocsBuilder:
101
+ """Where the pages are served (default ``/qcli/docs``)."""
102
+ self._base_path = path
103
+ return self
104
+
105
+ def set_title(self, title: str) -> CliDocsBuilder:
106
+ """The portal's label of the guides (default ``Guides``)."""
107
+ self._title = title
108
+ return self
109
+
110
+ def set_name(self, name: str) -> CliDocsBuilder:
111
+ """``{{name}}`` (default ``Documentation``)."""
112
+ self._name = name
113
+ return self
114
+
115
+ def set_base_url(self, url: str | None) -> CliDocsBuilder:
116
+ """``{{baseUrl}}`` (default: the request's ``scheme://host`` and
117
+ root path); a trailing ``/`` is dropped."""
118
+ self._base_url = url
119
+ return self
120
+
121
+ def set_variable(self, key: str, value: str) -> CliDocsBuilder:
122
+ """A host variable, ``{{ key }}`` in titles and markdown."""
123
+ self._variables[key] = value
124
+ return self
125
+
126
+ def add_folder(self, path: str) -> CliDocsBuilder:
127
+ """Every ``*.md`` file directly in ``path`` (relative to the working
128
+ directory), read once by :meth:`build`."""
129
+ self._sources.append(path)
130
+ return self
131
+
132
+ def add_page(self, slug: str, markdown: str) -> CliDocsBuilder:
133
+ """A page given in code (same front matter rules as files)."""
134
+ self._sources.append((slug, markdown))
135
+ return self
136
+
137
+ def build(self) -> CliDocsPlugin:
138
+ base_path = validate_base_path(self._base_path)
139
+ variables = {validate_variable(k): str(v) for k, v in self._variables.items()}
140
+ pages: list[DocsPage] = []
141
+ seen: set[str] = set()
142
+ for source in self._sources:
143
+ if isinstance(source, str):
144
+ found = read_folder(source)
145
+ else:
146
+ slug, markdown = source
147
+ found = [parse_page(validate_slug(slug), markdown)]
148
+ for page in found:
149
+ if page.slug in seen:
150
+ raise ValueError(f"duplicate docs page: {page.slug}")
151
+ seen.add(page.slug)
152
+ pages.append(page)
153
+
154
+ plugin = CliDocsPlugin(
155
+ prefix=base_path,
156
+ router=APIRouter(),
157
+ pages=sort_pages(pages),
158
+ portal_section={"kind": "docs", "title": self._title, "base_path": base_path},
159
+ name=self._name,
160
+ base_url=self._base_url.rstrip("/") if self._base_url else None,
161
+ variables=variables,
162
+ )
163
+ plugin.router = _router(plugin)
164
+ plugin.public_paths = [f"{base_path}/pages", f"{base_path}/pages/*"]
165
+ return plugin
166
+
167
+
168
+ INVALID_PATH_BASE = "invalid path base"
169
+
170
+
171
+ def _path_base_invalid(request: Request) -> bool:
172
+ """A root path that would make ``{{baseUrl}}`` leave the host: ``//``,
173
+ ``/\\``, or whitespace / control characters (browsers drop them)."""
174
+ root = request.scope.get("root_path", "") or ""
175
+ return root.startswith("//") or root.startswith("/\\") or any(c.isspace() or ord(c) < 0x20 or 0x7F <= ord(c) <= 0x9F for c in root)
176
+
177
+
178
+ def _router(plugin: CliDocsPlugin) -> APIRouter:
179
+ router = APIRouter()
180
+ by_slug = {page.slug: page for page in plugin.pages}
181
+
182
+ async def list_pages(request: Request) -> _Json:
183
+ if _path_base_invalid(request):
184
+ return _Json({"error": INVALID_PATH_BASE}, status_code=400)
185
+ # Page order is the titles' as written, before variables are replaced.
186
+ variables = plugin.variables_for(request)
187
+ return _Json([apply_variables(p, variables).summary() for p in plugin.pages], headers=_NO_CACHE)
188
+
189
+ async def get_page(slug: str, request: Request) -> _Json:
190
+ if _path_base_invalid(request):
191
+ return _Json({"error": INVALID_PATH_BASE}, status_code=400)
192
+ page = by_slug.get(slug)
193
+ if page is None:
194
+ return _Json({"error": PAGE_NOT_FOUND}, status_code=404)
195
+ return _Json(apply_variables(page, plugin.variables_for(request)).to_dict(), headers=_NO_CACHE)
196
+
197
+ router.add_api_route("/pages", list_pages, methods=["GET", "HEAD"], include_in_schema=False)
198
+ # ``path`` so an encoded ``/`` (``..%2Fsecret``) still gets the plugin's 404.
199
+ router.add_api_route("/pages/{slug:path}", get_page, methods=["GET", "HEAD"], include_in_schema=False)
200
+ return router
@@ -0,0 +1,147 @@
1
+ """Markdown pages: folders, front matter and variables (contract C9).
2
+
3
+ The front matter is parsed here, line by line (no YAML library): it is present
4
+ only when the first line is exactly ``---`` and ends at the next line that is
5
+ exactly ``---``; each line is ``key: value`` and only ``title``, ``group`` and
6
+ ``order`` are read.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ import re
14
+ from dataclasses import dataclass, replace
15
+ from typing import Mapping
16
+
17
+ SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
18
+ VARIABLE_KEY_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]*$")
19
+ VARIABLE_RE = re.compile(r"\{\{\s*([A-Za-z][A-Za-z0-9_.-]*)\s*\}\}")
20
+ ORDER_RE = re.compile(r"^[+-]?\d+$")
21
+ BUILT_IN_VARIABLES = ("baseUrl", "name")
22
+ DEFAULT_GROUP = "Guides"
23
+ #: Larger files are skipped (logged).
24
+ MAX_PAGE_BYTES = 1024 * 1024
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class DocsPage:
31
+ slug: str
32
+ title: str
33
+ group: str
34
+ order: int
35
+ markdown: str
36
+
37
+ def summary(self) -> dict[str, object]:
38
+ return {"slug": self.slug, "title": self.title, "group": self.group, "order": self.order}
39
+
40
+ def to_dict(self) -> dict[str, object]:
41
+ return {**self.summary(), "markdown": self.markdown}
42
+
43
+
44
+ def normalize_newlines(text: str) -> str:
45
+ return text.replace("\r\n", "\n").replace("\r", "\n")
46
+
47
+
48
+ def _unquote(value: str) -> str:
49
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
50
+ return value[1:-1]
51
+ return value
52
+
53
+
54
+ def parse_page(slug: str, text: str) -> DocsPage:
55
+ """A page from its markdown: the front matter (``title``, ``group``,
56
+ ``order``) removed, defaults applied (the first ``# `` heading, else the
57
+ slug; ``Guides``; ``0``). Raises ``ValueError`` for an ``order`` that
58
+ is not an integer."""
59
+ text = normalize_newlines(text)
60
+ lines = text.split("\n")
61
+ meta: dict[str, str] = {}
62
+ body = text
63
+ if lines and lines[0] == "---":
64
+ try:
65
+ end = lines.index("---", 1)
66
+ except ValueError:
67
+ end = -1
68
+ if end > 0:
69
+ for line in lines[1:end]:
70
+ key, sep, value = line.partition(":")
71
+ if not sep:
72
+ continue
73
+ key = key.strip()
74
+ if key in ("title", "group", "order"):
75
+ meta[key] = _unquote(value.strip())
76
+ body = "\n".join(lines[end + 1:])
77
+
78
+ order = 0
79
+ if "order" in meta:
80
+ if not ORDER_RE.match(meta["order"]):
81
+ raise ValueError(f"invalid order in docs page: {slug}")
82
+ order = int(meta["order"])
83
+ title = meta.get("title")
84
+ if title is None:
85
+ heading = next((line[2:].strip() for line in body.split("\n") if line.startswith("# ")), None)
86
+ title = heading or slug
87
+ return DocsPage(slug=slug, title=title, group=meta.get("group", DEFAULT_GROUP), order=order, markdown=body)
88
+
89
+
90
+ def validate_slug(slug: object) -> str:
91
+ if not isinstance(slug, str) or not SLUG_RE.match(slug):
92
+ raise ValueError(f"invalid docs page slug: {slug}")
93
+ return slug
94
+
95
+
96
+ def read_folder(path: str) -> list[DocsPage]:
97
+ """Every ``*.md`` file directly in ``path`` (names starting with ``.`` or
98
+ ``_`` ignored), in file-name order; ``path`` is relative to the working
99
+ directory. Symbolic links and files over 1 MB are skipped (logged)."""
100
+ if not os.path.isdir(path):
101
+ raise ValueError(f"docs folder not found: {path}")
102
+ pages: list[DocsPage] = []
103
+ for name in sorted(os.listdir(path)):
104
+ full = os.path.join(path, name)
105
+ if name.startswith((".", "_")) or not name.endswith(".md"):
106
+ continue
107
+ if os.path.islink(full):
108
+ logger.warning("[qcli] docs: skipped %s (a symbolic link)", full)
109
+ continue
110
+ if not os.path.isfile(full):
111
+ continue
112
+ if os.path.getsize(full) > MAX_PAGE_BYTES:
113
+ logger.warning("[qcli] docs: skipped %s (larger than 1 MB)", full)
114
+ continue
115
+ slug = name[: -len(".md")].lower()
116
+ if not SLUG_RE.match(slug):
117
+ raise ValueError(f"invalid docs page name: {name}")
118
+ with open(full, encoding="utf-8", newline="") as handle:
119
+ pages.append(parse_page(slug, handle.read()))
120
+ return pages
121
+
122
+
123
+ def validate_variable(key: object) -> str:
124
+ if key in BUILT_IN_VARIABLES:
125
+ raise ValueError(f"docs variable is built in: {key}")
126
+ if not isinstance(key, str) or not VARIABLE_KEY_RE.match(key):
127
+ raise ValueError(f"invalid docs variable: {key}")
128
+ return key
129
+
130
+
131
+ def substitute(text: str, variables: Mapping[str, str]) -> str:
132
+ """``{{ key }}`` replaced by its value; unknown keys left as written."""
133
+ return VARIABLE_RE.sub(lambda m: variables.get(m.group(1), m.group(0)), text)
134
+
135
+
136
+ def apply_variables(page: DocsPage, variables: Mapping[str, str]) -> DocsPage:
137
+ return replace(page, title=substitute(page.title, variables), markdown=substitute(page.markdown, variables))
138
+
139
+
140
+ def page_order_key(page: DocsPage) -> tuple[int, str, str]:
141
+ """``order``, then ``title`` (ordinal, case-insensitive), then ``slug``."""
142
+ return (page.order, page.title.upper(), page.slug)
143
+
144
+
145
+ def sort_pages(pages: list[DocsPage]) -> list[DocsPage]:
146
+ return sorted(pages, key=page_order_key)
147
+
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.5
2
+ Name: qodalis-cli-server-plugin-docs
3
+ Version: 1.0.0b29
4
+ Summary: Docs plugin for Qodalis CLI servers — markdown guides from folders or code, with front matter and variables, served as JSON for the portal
5
+ Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
6
+ Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
7
+ Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
8
+ Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,docs,guides,markdown,plugin,qodalis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: fastapi>=0.100.0
22
+ Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b17
@@ -0,0 +1,7 @@
1
+ qodalis_cli_docs/__init__.py,sha256=JBqBrL0hOcEmWkIRcsscuYvRm9PIlpLYbOP2JSO0pOw,531
2
+ qodalis_cli_docs/cli_docs_builder.py,sha256=Sa-XH08fhwYglKTBIC-eHCEc4n-M-Rn9qPMBf4ZYlIQ,7228
3
+ qodalis_cli_docs/pages.py,sha256=u9wavbPx84tKfuhl_6cbCpjZ0qEwnfwl1kFfGt1L_WY,5256
4
+ qodalis_cli_server_plugin_docs-1.0.0b29.dist-info/METADATA,sha256=EJUARvftXw-nx6mdQC4djBrB15lp2I5LSV7DBWAnPV8,1123
5
+ qodalis_cli_server_plugin_docs-1.0.0b29.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ qodalis_cli_server_plugin_docs-1.0.0b29.dist-info/licenses/LICENSE,sha256=uagko_O2JboeVOW3cldvxKW4QIDjTHCCk5T32qqg_As,1079
7
+ qodalis_cli_server_plugin_docs-1.0.0b29.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 Qodalis Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.