From 4fd50e9994ad318ce64c2c9cfad7d16e804313c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:49:41 +0100 Subject: [PATCH 1/9] Single-page SYSMOD viewer (web/): no Flask server needed The viewer as one web page that reads the model with the SysML v2 API directly from the browser, adapted to SYSMOD v5: - web/index.html + sysmod-viewer.css: the page - web/sysmod-viewer-core.js: reads the SYSMOD project from the elements of a commit (atlas, problem statement, system idea and objectives, stakeholders, needs, requirements, use cases, six context diagrams, completeness checks) - web/sysmod-viewer-api.js: SysML v2 API client (paging via Link or page[after], token, relay) - web/sysmod-viewer.js: the interface, SVG context diagrams without a CDN - web/serve.py: standard library only; serves the page and relays read-only requests to any SysML v2 server (CORS, http), localhost only - tests/test_web_serve.py: rules of the relay and real HTTP with a fake server - README: the single page is the recommended viewer; Flask stays for editing, AI, wizard and MCP The same JavaScript runs on mbse4u.com/tools/sysmod-viewer/ (with an engine for .sysml files and an allowlist relay); its tests (81 checks, Delivery Drone model) pass with these files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- README.md | 31 ++- tests/test_web_serve.py | 138 ++++++++++ web/index.html | 109 ++++++++ web/serve.py | 171 ++++++++++++ web/sysmod-viewer-api.js | 152 +++++++++++ web/sysmod-viewer-core.js | 544 ++++++++++++++++++++++++++++++++++++++ web/sysmod-viewer.css | 123 +++++++++ web/sysmod-viewer.js | 447 +++++++++++++++++++++++++++++++ 8 files changed, 1713 insertions(+), 2 deletions(-) create mode 100644 tests/test_web_serve.py create mode 100644 web/index.html create mode 100644 web/serve.py create mode 100644 web/sysmod-viewer-api.js create mode 100644 web/sysmod-viewer-core.js create mode 100644 web/sysmod-viewer.css create mode 100644 web/sysmod-viewer.js diff --git a/README.md b/README.md index 953efd0..f2586a6 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ **sysmod-sysmlv2-api-mcp** connects to a SysML v2 repository server and provides: +- 📄 **Single-page SYSMOD Viewer** (`web/`) — the recommended viewer: one web page, no Flask server, no Python packages. See [Single-page viewer](#single-page-viewer-web) - 🔌 **REST API + Web UI** — interactive browser-based viewer and wizard for SYSMOD models - 🤖 **MCP Server** — exposes all SYSMOD artifacts as tools for AI agents (Claude, Cursor, GitHub Copilot, etc.) - 🧠 **SYSMOD AI Agent** — an LLM can autonomously query problem statements, contexts, stakeholders, requirements, feature trees, and more directly from the SysML v2 model @@ -38,9 +39,35 @@ --- +## Single-page viewer (`web/`) + +The SYSMOD Viewer as **one web page**: it reads the model with the SysML v2 API directly from the browser. No Flask server, no `pip install`. + +```bash +python web/serve.py # then open http://localhost:8080/ +``` + +`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to any SysML v2 API server: a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. + +What it shows: the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram (actors, interfaces, white box parts) of all six contexts, from the brownfield to the product architecture. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened. + +| File | What | +|---|---| +| `web/index.html`, `web/sysmod-viewer.css` | the page | +| `web/sysmod-viewer-core.js` | reads the SYSMOD project from the elements (pure ES module, no dependencies) | +| `web/sysmod-viewer-api.js` | the requests to the SysML v2 API server, paging, relay | +| `web/sysmod-viewer.js` | the interface; the context diagrams are SVG drawn by the page (no CDN) | +| `web/serve.py` | serves the page and relays the requests | + +The same JavaScript runs on [mbse4u.com/tools/sysmod-viewer](https://mbse4u.com/tools/sysmod-viewer/), which in addition opens the Delivery Drone example and `.sysml` files with a SysML v2 engine in the browser, and reaches servers without CORS through a relay with an allowlist. Changes to the viewer belong here; the site copies them. + +Read-only. Editing the problem statement, AI suggestions, the creation wizard and the feature binding matrix are in the Flask server (below). Tests of `serve.py`: `python -m unittest tests/test_web_serve.py`. + +--- + ## Features -### SYSMOD Viewer (`project.html`) +### SYSMOD Viewer (`project.html`, Flask; for the single-page viewer see above) | Feature | Description | |---|---| @@ -211,7 +238,7 @@ ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://127.0.0.1:9000,http:// python sysmod_api_server.py ``` -Runs on `http://localhost:5000`. Open in browser to use the web UI. +Runs on `http://localhost:5000`. Open in browser to use the web UI (viewer with editing and AI, wizard). For viewing only, the [single-page viewer](#single-page-viewer-web) needs no server packages. --- diff --git a/tests/test_web_serve.py b/tests/test_web_serve.py new file mode 100644 index 0000000..d2e4d66 --- /dev/null +++ b/tests/test_web_serve.py @@ -0,0 +1,138 @@ +"""Tests of web/serve.py: the rules of the relay and real HTTP requests against a fake SysML v2 API server. +Standard library only: python -m unittest tests/test_web_serve.py (pytest runs it too)""" +import json +import sys +import threading +import unittest +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "web")) +import serve # noqa: E402 + + +class FakeSysml(BaseHTTPRequestHandler): + """A tiny SysML v2 API server: echoes what it received, pages elements with a Link header.""" + def log_message(self, *a): + pass + + def send(self, code, body, headers=None): + b = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + u = urllib.parse.urlsplit(self.path) + if u.path == "/projects": + return self.send(200, [{"@id": "p-1", "name": "P", "auth": self.headers.get("Authorization", ""), "query": u.query}]) + if u.path == "/projects/p-1/commits/c/elements": + return self.send(200, [{"@id": "e-1"}], {"Link": f"; rel=\"next\""}) + if u.path == "/projects/redirect": + self.send_response(302); self.send_header("Location", "https://example.org/"); self.end_headers(); return + if u.path == "/projects/html": + b = b"oops" + self.send_response(200); self.send_header("Content-Type", "text/html"); self.end_headers(); self.wfile.write(b); return + if u.path == "/projects/secret": + return self.send(401, {"error": "unauthorized"}) + return self.send(404, {"error": "not found"}) + + +def start(handler): + srv = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv + + +class Rules(unittest.TestCase): + def ok(self, url, expected=None): + target, error = serve.check_url(url) + self.assertEqual(error, "", url) + if expected: + self.assertEqual(target, expected) + + def refused(self, url, reason): + self.assertEqual(serve.check_url(url), (None, reason), url) + + def test_allowed(self): + self.ok("https://h.org/projects") + self.ok("http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000", "http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000") + self.ok("https://h.org/projects?page[size]=10", "https://h.org/projects?page%5Bsize%5D=10") + self.ok("https://h.org/api/v1/projects/p/commits/c/elements?page%5Bafter%5D=x") + self.ok("https://h.org/projects/p/branches/b") + self.ok("https://H.org/projects", "https://h.org/projects") + + def test_refused(self): + self.refused("", "invalid address") + self.refused("file:///etc/passwd", "only http and https") + self.refused("https://u:p@h.org/projects", "invalid address") + self.refused("https://h.org/projects#x", "invalid address") + self.refused("https://h.org/admin", "not a read endpoint of the SysML v2 API") + self.refused("https://h.org/projects/p/query-results", "not a read endpoint of the SysML v2 API") + self.refused("https://h.org/projects/../admin", "invalid path") + self.refused("https://h.org/projects/%2e%2e", "invalid path") + self.refused("https://h.org//projects", "invalid path") + self.refused("https://h.org/projects?x=1", "query not allowed") + self.refused("https://h.org/projects?page%5Bsize%5D=1&page%5Bsize%5D=2", "query not allowed") + self.refused("https://h.org/projects?page%5Bsize%5D=x", "query not allowed") + + +class Relay(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.up = start(FakeSysml) + cls.viewer = start(serve.Handler) + cls.U = f"http://127.0.0.1:{cls.up.server_address[1]}" + cls.R = f"http://127.0.0.1:{cls.viewer.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.up.shutdown(); cls.viewer.shutdown() + + def get(self, path, headers=None): + req = urllib.request.Request(self.R + path, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers, r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() + + def relay(self, url, headers=None): + return self.get("/relay?url=" + urllib.parse.quote(url, safe=""), headers) + + def test_page_and_config(self): + status, _, body = self.get("/") + self.assertEqual(status, 200) + self.assertIn(b'id="sysmod-viewer"', body) + status, _, body = self.get("/viewer-config.json") + self.assertEqual(json.loads(body)["relay"]["servers"], ["*"]) + self.assertEqual(self.get("/serve.py")[0], 404) + + def test_relayed_with_token_and_paging(self): + status, _, body = self.relay(self.U + "/projects?page%5Bsize%5D=1000", {"X-Relay-Authorization": "Bearer t"}) + data = json.loads(body)[0] + self.assertEqual((status, data["auth"], data["query"]), (200, "Bearer t", "page%5Bsize%5D=1000")) + status, headers, _ = self.relay(self.U + "/projects/p-1/commits/c/elements") + self.assertEqual(headers["Link"], f"<{self.U}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\"") + self.assertIsNone(headers.get("Access-Control-Allow-Origin")) + + def test_errors(self): + self.assertEqual(self.relay(self.U + "/projects/secret")[0], 401) + self.assertEqual(self.relay(self.U + "/projects/nothing")[0], 404) + self.assertEqual(self.relay(self.U + "/projects/redirect")[0], 502) + self.assertIn(b"did not answer with JSON", self.relay(self.U + "/projects/html")[2]) + self.assertEqual(self.relay(self.U + "/admin")[0], 400) + self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 502) + self.assertEqual(self.relay(self.U + "/projects", {"Sec-Fetch-Site": "cross-site"})[0], 403) + status, headers, _ = self.relay(self.U + "/admin") + self.assertEqual(headers["X-Relay-Error"], "1") + + +if __name__ == "__main__": + unittest.main() diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..ff2d245 --- /dev/null +++ b/web/index.html @@ -0,0 +1,109 @@ + + + + + + + SYSMOD Viewer + + + + +
+
+

tool

+

SYSMOD Viewer

+

+ Shows a SYSMOD project of a SysML v2 model the way the method structures it: the SYSMOD Atlas, the problem statement, + the system idea and its objectives, stakeholders, needs, system requirements, system use cases and the system context of every architecture. + It reads the model with the SysML v2 API (OMG Systems Modeling API). A single page, no server of its own: everything runs in your browser. +

+
+ +
+ + + + +
+
+ +
+

Good to know

+
    +
  • Run it: python web/serve.py, then open http://localhost:8080/. The script needs only Python 3, no packages. Browsers do not run the page from a file:// address.
  • +
  • CORS and http: a page can only read servers that allow requests from it. serve.py also relays the requests (read-only) to any SysML v2 server, so with it every server works, including plain http:// ones.
  • +
  • Token: optional, passed on as header Authorization; it stays in the page and is never stored. The page address records server, project and commit (not the token).
  • +
  • SYSMOD v5: the project is an occurrence def with #project or a specialization of SYSMOD::Project; the SYSMOD library must be in the same project.
  • +
  • Read-only. Editing, the AI suggestions and the creation wizard are in the Flask server of this repository (sysmod_api_server.py).
  • +
+
+
+ + + diff --git a/web/serve.py b/web/serve.py new file mode 100644 index 0000000..b02b1cf --- /dev/null +++ b/web/serve.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +""" +Serves the single-page SYSMOD viewer (this folder) and relays its requests to SysML v2 API servers. + + python web/serve.py # http://localhost:8080/ + python web/serve.py --port 9090 + +Only the Python standard library, no packages. + +Why a relay: a web page may only read servers that allow requests from it (CORS), and a page may not call +plain-http servers from https. The relay asks the server on behalf of the page, so every SysML v2 API server works, +also e.g. http://sysml2.intercax.com:9000 or a server without CORS such as Flexo. + +The relay is narrow: + - it listens on localhost only (unless --host says otherwise); + - only GET of the read endpoints of the SysML v2 API (/projects, /projects/{id}, .../branches, .../commits, + .../commits/{id}/elements[/{id}], optionally behind a path prefix such as /api/v1) and only the paging query + page[size], page[after], page[before]; http and https; no redirects followed; JSON only; + - the token (header X-Relay-Authorization) is passed on as Authorization and never stored or logged. +The same rules as relay.php of mbse4u.com/tools/sysmod-viewer/, which in addition has an allowlist of servers. +""" +import argparse +import json +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TIMEOUT = 60 +MAX_BYTES = 64 * 1024 * 1024 +QUERY_KEYS = ("page[size]", "page[after]", "page[before]") +SEGMENT = r"[A-Za-z0-9._~%-]{1,200}" +READ_PATH = re.compile( + r"^(/[A-Za-z0-9._~-]{1,60}){0,3}?/projects(/" + SEGMENT + r"(/branches(/" + SEGMENT + r")?|/commits(/" + SEGMENT + + r"(/elements(/" + SEGMENT + r")?)?)?)?)?$" +) +CONFIG = {"relay": {"url": "relay", "servers": ["*"], "label": "the local relay (serve.py)"}} + + +def check_url(url: str): + """The address to request, or (None, reason). Same rules as relay.php, without the allowlist.""" + if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): + return None, "invalid address" + p = urllib.parse.urlsplit(url) + if p.scheme.lower() not in ("http", "https") or not p.hostname: + return None, "only http and https" + if p.username or p.password or p.fragment: + return None, "invalid address" + path = p.path or "" + if "//" in path: + return None, "invalid path" + for segment in path.split("/"): + d = urllib.parse.unquote(segment) + if d in (".", "..") or any(c in d for c in "/\\\0"): + return None, "invalid path" + if not READ_PATH.match(path): + return None, "not a read endpoint of the SysML v2 API" + query = [] + seen = set() + for pair in filter(None, (p.query or "").split("&")): + k, _, v = pair.partition("=") + k, v = urllib.parse.unquote(k), urllib.parse.unquote(v) + if k not in QUERY_KEYS or k in seen or len(v) > 200 or re.search(r"[\x00-\x1f\x7f]", v): + return None, "query not allowed" + if k == "page[size]" and not re.fullmatch(r"\d{1,5}", v): + return None, "query not allowed" + seen.add(k) + query.append(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="")) + netloc = p.hostname.lower() + (f":{p.port}" if p.port else "") + return urllib.parse.urlunsplit((p.scheme.lower(), netloc, path, "&".join(query), "")), "" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None # a redirect is answered as an HTTP error, never followed + + +OPENER = urllib.request.build_opener(NoRedirect) + + +class Handler(SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=str(HERE), **kwargs) + + def log_message(self, fmt, *args): # no query strings in the log (they may name projects) + sys.stderr.write("%s %s\n" % (self.command, self.path.split("?")[0])) + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + super().end_headers() + + def answer(self, status, body: bytes, headers=None): + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def fail(self, status, message): + self.answer(status, json.dumps({"error": message}).encode(), {"X-Relay-Error": "1"}) + + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/viewer-config.json": + return self.answer(200, json.dumps(CONFIG).encode()) + if path == "/relay": + return self.relay() + if path.endswith(".py"): + return self.send_error(404) + return super().do_GET() + + def do_POST(self): + self.fail(405, "only GET") + + def relay(self): + site = self.headers.get("Sec-Fetch-Site", "") + if site not in ("", "same-origin", "none"): + return self.fail(403, "only for the SYSMOD viewer of this server") + params = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) + target, error = check_url((params.get("url") or [""])[0]) + if not target: + return self.fail(400, error) + headers = {"Accept": "application/json", "User-Agent": "SYSMOD-viewer-relay/1"} + auth = self.headers.get("X-Relay-Authorization") or self.headers.get("Authorization") + if auth and len(auth) < 8192 and "\r" not in auth and "\n" not in auth: + headers["Authorization"] = auth + try: + with OPENER.open(urllib.request.Request(target, headers=headers), timeout=TIMEOUT) as r: + status, body, rh = r.status, r.read(MAX_BYTES + 1), r.headers + except urllib.error.HTTPError as e: + if 300 <= e.code < 400: + return self.fail(502, "the server answered with a redirect, which the relay does not follow") + status, body, rh = e.code, e.read(MAX_BYTES + 1), e.headers + except (urllib.error.URLError, TimeoutError, OSError) as e: + timeout = "timed out" in str(e).lower() + return self.fail(504 if timeout else 502, "the server did not answer in time" if timeout else "the server could not be reached") + if len(body) > MAX_BYTES: + return self.fail(502, "the answer of the server is too large for the relay") + try: + json.loads(body or b"null") + except ValueError: + body = json.dumps({"error": "the server did not answer with JSON", "status": status}).encode() + extra = {} + link = rh.get("Link") + if link and "\r" not in link and "\n" not in link: + extra["Link"] = link # unchanged: the viewer resolves the next page against the server's address + self.answer(status, body, extra) + + +def main(): + ap = argparse.ArgumentParser(description="Serves the SYSMOD viewer and relays its requests to SysML v2 API servers.") + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="127.0.0.1", help="default 127.0.0.1: only this computer can use the relay") + a = ap.parse_args() + server = ThreadingHTTPServer((a.host, a.port), Handler) + print(f"SYSMOD viewer: http://localhost:{a.port}/ (Ctrl+C to stop)") + try: + server.serve_forever() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js new file mode 100644 index 0000000..988c2bf --- /dev/null +++ b/web/sysmod-viewer-api.js @@ -0,0 +1,152 @@ +/* sysmod-viewer-api.js: the requests of the SYSMOD viewer to a SysML v2 REST API server (OMG Systems Modeling API, + e.g. the SysML v2 Pilot Implementation's API services or Open-MBEE Flexo). Pure ES module; runs in the browser and in Node. + + Used by the single-page SYSMOD viewer of github.com/Open-MBEE/sysmod-sysmlv2-api (web/) and by mbse4u.com/tools/sysmod-viewer/. + + The browser talks to the server DIRECTLY: there is no server of the viewer in between. That needs + - CORS: the server must allow requests from the page's origin (Access-Control-Allow-Origin), with a token also the + header Authorization (Access-Control-Allow-Headers); for paging it should expose the header Link. + - HTTPS: a page on https:// may not call an http:// server. Exception: http://localhost and http://127.0.0.1. + + Servers that do not allow it (or have no https) can be reached through a relay on the origin of the page: + createClient({ baseUrl, relay: { url: '/relay', servers: ['https://flexo.systemsmodeling.com'], label: 'the relay of mbse4u.com', contact: 'info@mbse4u.com' } }) + Then every request to such a server goes to ?url=
, the token as header X-Relay-Authorization. + servers: ['*'] sends every server through the relay (web/serve.py, the local relay of the repository). + Relays: web/serve.py (local, any server), mbse4u.com/tools/sysmod-viewer/relay.php (allowlist relay-servers.json). + + const api = createClient({ baseUrl: 'https://sysml.example.org', token: 'Bearer …' }); + await api.projects(); // [{ '@id', name, description, created, defaultBranch }] + await api.commits(projectId); // newest first + await api.elements(projectId, commitId, { onProgress: (n) => … , signal }); // all elements of the commit +*/ + +export class ApiError extends Error { + constructor(message, { status = 0, url = '', hint = '' } = {}) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.url = url; + this.hint = hint; + } +} + +/** Normalizes what a user pastes: no trailing slash, no /projects…, scheme added if missing. */ +export function normalizeBaseUrl(input) { + let s = String(input || '').trim(); + if (!s) return ''; + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = (/^(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(s) ? 'http://' : 'https://') + s; + const u = new URL(s); + if (!/^https?:$/.test(u.protocol)) throw new ApiError('The address must start with https:// (or http:// for a server on this computer).'); + u.hash = ''; u.search = ''; + u.pathname = u.pathname.replace(/\/projects(\/.*)?$/, '').replace(/\/+$/, ''); + return u.href.replace(/\/+$/, ''); +} + +const isLocal = (u) => ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname); + +/** A reason why the browser will not even send the request (mixed content), or '' */ +export function blockedReason(baseUrl, pageProtocol = globalThis.location?.protocol, contact = '') { + const u = new URL(baseUrl); + if (pageProtocol === 'https:' && u.protocol === 'http:' && !isLocal(u)) + return 'This page is loaded over HTTPS, so your browser does not allow it to call a server over plain HTTP. Use the https:// address of the server. A server on your own computer (http://localhost) is the exception. ' + + (contact ? `If the server has no https address, it can be added to the relay of this page: write to ${contact}.` : 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'); + return ''; +} + +/** The next page from a Link header: ; rel="next" */ +export function nextFromLink(header) { + if (!header) return null; + for (const part of header.split(',')) { + const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/i); + if (m) return m[1]; + } + return null; +} + +/** Is this address on a server that the relay serves? relay.servers are origins (https://host[:port]). */ +export function usesRelay(url, relay) { + if (!relay?.url || !Array.isArray(relay.servers)) return false; + if (relay.servers.includes('*')) return true; + try { return relay.servers.map((s) => String(s).replace(/\/+$/, '').toLowerCase()).includes(new URL(url).origin.toLowerCase()); } catch { return false; } +} + +export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 1000 } = {}) { + const base = normalizeBaseUrl(baseUrl); + if (!base) throw new ApiError('Enter the address of a SysML v2 API server.'); + const t = String(token || '').trim(); + const auth = t ? (/^(bearer|basic)\s/i.test(t) ? t : `Bearer ${t}`) : ''; + const viaRelay = usesRelay(base, relay); + const relayLabel = relay?.label || 'the relay'; + const contact = relay?.contact || ''; + + async function get(url, signal) { + const relayed = usesRelay(url, relay); + const headers = { Accept: 'application/json' }; + if (auth) headers[relayed ? 'X-Relay-Authorization' : 'Authorization'] = auth; + const target = relayed ? `${relay.url}?url=${encodeURIComponent(url)}` : url; + if (!relayed) { + const blocked = blockedReason(url, globalThis.location?.protocol, contact); + if (blocked) throw new ApiError('The browser blocks this address.', { url, hint: blocked }); + } + let r; + try { + r = await fetchFn(target, { headers, signal, credentials: 'omit', mode: 'cors' }); + } catch (e) { + if (e?.name === 'AbortError') throw e; + throw new ApiError(relayed ? `${relayLabel[0].toUpperCase()}${relayLabel.slice(1)} could not be reached.` : 'The server could not be reached.', { + url, + hint: relayed ? 'Check your connection and try again.' + : 'Most likely the server does not allow requests from this page (CORS); otherwise the address is wrong or the server is down. ' + + 'The developer console of your browser (F12) shows the exact reason. ' + + (auth ? 'With a token the server must also allow the header Authorization in its CORS settings. ' : '') + + (contact ? `If the server cannot allow it, it can be added to the relay of this page: write to ${contact}.` : 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'), + }); + } + if (relayed && r.headers.get('X-Relay-Error')) { + let msg = ''; + try { msg = (await r.json()).error || ''; } catch { /* not JSON */ } + throw new ApiError(`${relayLabel[0].toUpperCase()}${relayLabel.slice(1)}: ${msg || `HTTP ${r.status}`}.`, { status: r.status, url }); + } + if (r.status === 401 || r.status === 403) throw new ApiError(`The server refused access (HTTP ${r.status}).`, { status: r.status, url, hint: auth ? 'Check the token.' : 'The server needs a token: enter it under "Token".' }); + if (r.status === 404) throw new ApiError('Not found (HTTP 404).', { status: 404, url, hint: 'Is this the base address of the API? It is the address in front of /projects.' }); + if (!r.ok) throw new ApiError(`The server answered with HTTP ${r.status}.`, { status: r.status, url }); + let body; + try { body = await r.json(); } catch { + throw new ApiError(relayed ? 'The relay did not answer with JSON.' : 'The server did not answer with JSON.', { url, hint: relayed ? `Is ${relayLabel} running? (It is a server-side script; a static development server does not run it.)` : 'Is this the address of a SysML v2 API server?' }); + } + return { body, link: r.headers.get('Link') || r.headers.get('link') }; + } + + /** All pages of a list resource. Follows the Link header; without it (not exposed by CORS) page[after]=. */ + async function list(path, { signal, onProgress, size = pageSize } = {}) { + const sep = path.includes('?') ? '&' : '?'; + let url = `${base}${path}${sep}page%5Bsize%5D=${size}`; + const out = [], seen = new Set(); + for (let page = 0; page < 10000; page++) { + const { body, link } = await get(url, signal); + const items = Array.isArray(body) ? body : Array.isArray(body?.elements) ? body.elements : null; + if (!items) throw new ApiError('The server did not answer with a list.', { url, hint: 'Is this the address of a SysML v2 API server?' }); + let fresh = 0; + for (const it of items) { const id = it?.['@id']; if (id && seen.has(id)) continue; if (id) seen.add(id); out.push(it); fresh++; } + onProgress?.(out.length); + const next = nextFromLink(link); + if (next) { url = new URL(next, url).href; if (!fresh) break; continue; } + // no Link header: if the page was full there may be more, ask for the page after the last element + if (items.length < size || !fresh || !items.at(-1)?.['@id']) break; + url = `${base}${path}${sep}page%5Bsize%5D=${size}&page%5Bafter%5D=${encodeURIComponent(items.at(-1)['@id'])}`; + } + return out; + } + + const time = (c) => Date.parse(c.created || c.timestamp || '') || 0; + + return { + base, + viaRelay, + projects: async (opts) => (await list('/projects', opts)).sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''))), + project: async (id, opts) => (await get(`${base}/projects/${encodeURIComponent(id)}`, opts?.signal)).body, + branches: (id, opts) => list(`/projects/${encodeURIComponent(id)}/branches`, opts), + commits: async (id, opts) => (await list(`/projects/${encodeURIComponent(id)}/commits`, opts)).sort((a, b) => time(b) - time(a)), + elements: (id, commit, opts) => list(`/projects/${encodeURIComponent(id)}/commits/${encodeURIComponent(commit)}/elements`, opts), + }; +} diff --git a/web/sysmod-viewer-core.js b/web/sysmod-viewer-core.js new file mode 100644 index 0000000..6b94c70 --- /dev/null +++ b/web/sysmod-viewer-core.js @@ -0,0 +1,544 @@ +/* sysmod-viewer-core.js: reads a SYSMOD project from the elements of a SysML v2 model, as the SysML v2 REST API delivers them. + Pure ES module without dependencies: runs in the browser (page /tools/sysmod-viewer/) and in Node (scripts/test-sysmod-viewer.mjs). + + Port of the reading part of github.com/Open-MBEE/sysmod-sysmlv2-api (sysmod_api_helpers.py) and + github.com/MBSE4U/mbse4u_sysmlv2_helpers (Apache License 2.0, Tim Weilkiens and contributors), adapted to SYSMOD v5 + (SYSMOD::Project with brownfieldContext, systemIdeaContext, specificationContext, functionalContext, logicalContext, + productContext and their *Impl white box variants). Differences to the Python original: + - The whole commit is loaded once (paged), then everything is read locally. No request per element. + - Roles of the project are found by their DIRECT redefinition/subsetting of the library feature (:>> problemStatement), + not by any specialization: specificationContext also specializes systemIdeaContext, the direct relation tells them apart. + - Read-only. No AI, no writing commits. + + const model = createModel(elements); // elements: array of SysML v2 API element objects (with derived properties) + const projects = findProjects(model); // [{ id, name, qualifiedName }] + const view = readProject(model, projects[0].id); // everything the viewer shows, plain data, see readProject() +*/ + +export const SYSMOD = { + project: 'SYSMOD::Project', + soi: 'SYSMOD::SystemContext::systemOfInterest', + actors: 'SYSMOD::SystemContext::actors', + useCases: 'SYSMOD::SystemContext::useCases', +}; + +/** The contexts of a SYSMOD v5 project, in the order of the SYSMOD Atlas. key = atlas id, role = feature of SYSMOD::Project. */ +export const CONTEXTS = [ + { key: 'BFAC', role: 'brownfieldContext', title: 'Brownfield Architecture', space: 'solution' }, + { key: 'SIC', role: 'systemIdeaContext', title: 'System Idea Architecture', space: 'solution' }, + { key: 'SC', role: 'specificationContext', title: 'System Specification', space: 'problem' }, + { key: 'FUC', role: 'functionalContext', title: 'Functional Architecture', space: 'solution' }, + { key: 'LAC', role: 'logicalContext', title: 'Logical Architecture', space: 'solution' }, + { key: 'PAC', role: 'productContext', title: 'Product Architecture', space: 'solution' }, +]; + +const ref = (r) => (r && typeof r === 'object' ? r['@id'] : r) || null; +const refs = (v) => (Array.isArray(v) ? v : v ? [v] : []).map(ref).filter(Boolean); + +/** Element access over an array of elements. Unknown ids (e.g. the standard library, not part of the project) give null. */ +export function createModel(elements) { + const byId = new Map(); + for (const e of elements) if (e && e['@id']) byId.set(e['@id'], e); + let byQName = null, byType = null, annotations = null; + const M = { + size: byId.size, + get: (r) => byId.get(ref(r)) ?? null, + all: (rs) => refs(rs).map((id) => byId.get(id)).filter(Boolean), + /** first element with this qualified name; library elements are preferred over model elements with the same name */ + byQName(qn) { + if (!byQName) { + byQName = new Map(); + for (const e of byId.values()) if (e.qualifiedName && !byQName.has(e.qualifiedName)) byQName.set(e.qualifiedName, e); + } + return byQName.get(qn) ?? null; + }, + ofType(t) { + if (!byType) { + byType = new Map(); + for (const e of byId.values()) { const k = e['@type']; if (!byType.has(k)) byType.set(k, []); byType.get(k).push(e); } + } + return byType.get(t) ?? []; + }, + /** ids of the metadata definitions applied to an element (#user, #system, ...), from the MetadataUsages */ + metadataOf(el) { + if (!annotations) { + annotations = new Map(); + for (const mu of M.ofType('MetadataUsage')) { + const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; + if (!def) continue; + for (const a of refs(mu.annotatedElement)) { if (!annotations.has(a)) annotations.set(a, []); annotations.get(a).push(def); } + } + } + return annotations.get(ref(el)) ?? []; + }, + }; + return M; +} + +/** An element of the SYSMOD library itself (SYSMOD, SYSMOD15288, SYSMOD4AI, SYSMODViews …) or of another library */ +export const isLibrary = (el) => !!el && (el.isLibraryElement === true || /^SYSMOD[A-Za-z0-9_]*::/.test(el.qualifiedName || '')); + +export const nameOf = (el) => (el && (el.name ?? el.declaredName ?? el.shortName ?? el.declaredShortName)) || ''; + +/** The general elements of an element: what it redefines, subsets, is typed by, specializes. */ +function generals(M, el) { + const out = []; + for (const s of M.all(el.ownedSpecialization)) { const g = ref(s.general); if (g) out.push(g); } + // some servers omit ownedSpecialization on usages: typing and redefinition are specializations as well + for (const t of refs(el.type)) out.push(t); + return out; +} + +/** Does el specialize target (transitively, also over typing)? el === target counts. */ +export function specializes(M, el, target) { + const goal = ref(target); + if (!el || !goal) return false; + const seen = new Set(), todo = [ref(el)]; + while (todo.length) { + const id = todo.pop(); + if (id === goal) return true; + if (seen.has(id)) continue; + seen.add(id); + const e = M.get(id); + if (e) todo.push(...generals(M, e)); + } + return false; +} + +/** Does el redefine or subset target directly (:>> target, :> target)? */ +export function directlySpecializes(M, el, target) { + const goal = ref(target); + return M.all(el.ownedSpecialization).some((s) => ref(s.general) === goal); +} + +/** Documentation text of an element; with viaDefinition the documentation of its definition if it has none of its own. */ +export function docOf(M, el, viaDefinition = true) { + if (!el) return ''; + const own = M.all(el.documentation).map((d) => cleanDoc(d.body)).filter(Boolean); + if (own.length) return own.join('\n\n'); + // the text of the definition, but not the generic text of a SYSMOD library definition ("Base element for concerns.") + if (viaDefinition) for (const d of definitionsOf(M, el)) { if (isLibrary(d)) continue; const t = docOf(M, d, false); if (t) return t; } + return ''; +} + +/** The most specific definitions of a usage: a definition that another one of the list specializes is left out. */ +export function definitionsOf(M, el) { + const defs = M.all(el?.definition ?? el?.type); + return defs.filter((d) => !defs.some((o) => o !== d && specializes(M, o, d))); +} + +/** Removes the comment layout that some servers keep in the body (leading asterisks of continued lines). */ +export function cleanDoc(body) { + if (typeof body !== 'string') return ''; + return body.replace(/^\s*\/\*+|\*+\/\s*$/g, '').split('\n').map((l) => l.replace(/^\s*\*\s?/, '').trim()).join('\n').replace(/\n{3,}/g, '\n\n').trim(); +} + +/** + * All features of an element, effective: its own and the inherited ones, a redefined feature replaced by its redefinition. + * Computed here over the generalizations (typing, subclassification, subsetting, redefinition), because not every server + * delivers the derived inheritedFeature; what the server delivers in feature/inheritedFeature is added. + */ +export function featuresOf(M, el, type) { + if (!el) return []; + const all = M.effective ? M.effective(el) : effectiveFeatures(M, el); + return type ? all.filter((f) => (Array.isArray(type) ? type.includes(f['@type']) : f['@type'] === type)) : all; +} +function effectiveFeatures(M, el) { + const cache = (M._eff ||= new Map()); + const hit = cache.get(el['@id']); + if (hit) return hit; + cache.set(el['@id'], []); // guards against cycles + const out = [], seen = new Set(), redefined = new Set(); + const add = (f) => { + if (!f || seen.has(f['@id']) || redefined.has(f['@id'])) return; + seen.add(f['@id']); + out.push(f); + for (const r of M.all(f.ownedSpecialization)) if (r['@type'] === 'Redefinition') { const g = ref(r.redefinedFeature ?? r.general); if (g) redefined.add(g); } + }; + for (const f of M.all(el.ownedFeature)) add(f); + for (const g of generals(M, el)) { const ge = M.get(g); if (ge && ge !== el) for (const f of effectiveFeatures(M, ge)) add(f); } + for (const f of M.all(el.feature)) add(f); + for (const f of M.all(el.inheritedFeature)) add(f); + // the nearest feature of a name wins (several paths of inheritance can bring redefinitions of the same feature) + const names = new Set(); + const result = out.filter((f) => { + if (redefined.has(f['@id'])) return false; + const n = nameOf(f); + if (!n) return true; + if (names.has(n)) return false; + names.add(n); + return true; + }); + cache.set(el['@id'], result); + return result; +} +/** Only the owned features (no inherited ones) */ +export const ownedFeaturesOf = (M, el, type) => M.all(el?.ownedFeature).filter((f) => !type || (Array.isArray(type) ? type.includes(f['@type']) : f['@type'] === type)); + +/** The feature of an element with this name (effective, inherited included) */ +export const featureNamed = (M, el, name, type) => featuresOf(M, el, type).find((f) => nameOf(f) === name) || null; + +/** Text of the value of an attribute (literal, enumeration literal, quantity, feature chain); '' if it has none. */ +export function valueOf(M, feature) { + if (!feature) return ''; + for (const r of M.all(feature.ownedRelationship)) { + if (r['@type'] !== 'FeatureValue') continue; + const t = exprText(M, M.get(r.value), 0); + if (t !== '') return t; + } + return ''; +} + +/** A readable text of an expression. Keeps to the common cases of SYSMOD attribute values. */ +export function exprText(M, e, depth = 0) { + if (!e || depth > 8) return ''; + const t = e['@type']; + if ('value' in e && /^Literal/.test(t)) return t === 'LiteralInfinity' ? '*' : String(e.value); + if (t === 'LiteralInfinity') return '*'; + if (t === 'NullExpression') return ''; + if (t === 'FeatureReferenceExpression') return nameOf(M.get(e.referent)); + if (t === 'FeatureChainExpression') { + const target = M.get(e.targetFeature); + const chain = target && refs(target.chainingFeature).length ? M.all(target.chainingFeature).map(nameOf) : [nameOf(target)]; + const src = argsOf(M, e).map((a) => exprText(M, a, depth + 1)).filter(Boolean)[0]; + return [src, ...chain].filter(Boolean).join('.'); + } + if (t === 'OperatorExpression') { + const args = argsOf(M, e).map((a) => exprText(M, a, depth + 1)); + const op = e.operator; + if (op === '[') return `${args[0] ?? ''} [${args[1] ?? ''}]`; + if (op === ',') return args.filter(Boolean).join(', '); + if (op === '-' && args.length === 1) return `-${args[0]}`; + if (args.length === 2 && op) return `${args[0]} ${op} ${args[1]}`; + return args.filter(Boolean).join(' '); + } + if (t === 'InvocationExpression') return `${nameOf(M.all(e.instantiatedType ?? e.type)[0])}(${argsOf(M, e).map((a) => exprText(M, a, depth + 1)).join(', ')})`; + return ''; +} +/** Arguments of an invocation: the values of its input parameters, in order. */ +function argsOf(M, e) { + const direct = M.all(e.argument); + if (direct.length) return direct; + const out = []; + for (const p of M.all(e.ownedFeature)) { + if (p.direction && p.direction !== 'in') continue; + for (const r of M.all(p.ownedRelationship)) if (r['@type'] === 'FeatureValue') { const v = M.get(r.value); if (v) out.push(v); } + } + return out; +} + +const valueNamed = (M, el, name) => valueOf(M, featureNamed(M, el, name, 'AttributeUsage')); + +/** The SYSMOD projects of the model: elements with #project, otherwise definitions that specialize SYSMOD::Project. */ +export function findProjects(M) { + const lib = M.byQName(SYSMOD.project); + const found = new Map(); + for (const mu of M.ofType('MetadataUsage')) { + const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; + if (!def || !(def.declaredShortName === 'project' || def.qualifiedName === 'SYSMOD::ProjectMetadata')) continue; + for (const a of M.all(mu.annotatedElement)) if (a !== lib) found.set(a['@id'], a); + } + if (!found.size && lib) { + for (const d of M.ofType('OccurrenceDefinition')) if (d !== lib && !d.isLibraryElement && specializes(M, d, lib)) found.set(d['@id'], d); + } + return [...found.values()] + .map((p) => ({ id: p['@id'], name: nameOf(p) || '(unnamed project)', qualifiedName: p.qualifiedName || '' })) + .sort((a, b) => a.name.localeCompare(b.name)); +} + +/** The features of the project that play a role of SYSMOD::Project (e.g. 'problemStatement'). */ +function roleOf(M, project, role, { transitive = false } = {}) { + const lib = M.byQName(`${SYSMOD.project}::${role}`); + if (!lib) return []; + const own = ownedFeaturesOf(M, project); + const direct = own.filter((f) => f !== lib && directlySpecializes(M, f, lib)); + if (direct.length || !transitive) return direct; + return own.filter((f) => f !== lib && specializes(M, f, lib)); +} + +/** Stereotype-like labels from the SYSMOD metadata on an element and the elements it redefines (#user, #system ...). */ +function stereotypesOf(M, el) { + const names = new Set(); + const seen = new Set(), todo = [el['@id']]; + while (todo.length && seen.size < 40) { + const id = todo.pop(); + if (seen.has(id)) continue; + seen.add(id); + for (const d of M.metadataOf(id)) { const n = d.declaredShortName || nameOf(d); if (n) names.add(n); } + const e = M.get(id); + if (e) for (const s of M.all(e.ownedSpecialization)) if (s['@type'] !== 'FeatureTyping') { const g = ref(s.general); if (g) todo.push(g); } + } + return [...names]; +} + +const brief = (M, el) => (el ? { id: el['@id'], name: nameOf(el), type: el['@type'], doc: docOf(M, el) } : null); +const typeNames = (M, el) => definitionsOf(M, el).map(nameOf).filter(Boolean); + +/** System of interest, actors, connections and (white box) internal parts of a context. */ +export function readContext(M, project, def) { + const ctx = roleOf(M, project, def.role)[0]; + if (!ctx) return null; + const impl = roleOf(M, project, `${def.role}Impl`)[0] || null; + const soiLib = M.byQName(SYSMOD.soi), actorsLib = M.byQName(SYSMOD.actors); + const parts = featuresOf(M, ctx, 'PartUsage'); + const soi = parts.find((p) => p !== soiLib && specializes(M, p, soiLib)) || null; + const actors = parts.filter((p) => p !== actorsLib && p !== soi && specializes(M, p, actorsLib)); + // connections between the actors and the system (interfaces, connections), by the parts their ends point to + // a feature stands for the soi or an actor if it is that part or one the part redefines (e.g. the part of the context definition) + const match = (x) => { + if (!x || x === soiLib || x === actorsLib) return null; + if (soi && (x === soi || specializes(M, soi, x))) return soi; + return actors.find((a) => a === x || specializes(M, a, x)) || null; + }; + const partOfEnd = (end) => { + let e = end; + for (let i = 0; e && i < 6; i++) { + const hit = match(e); + if (hit) return hit; + const chain = M.all(e.chainingFeature); + if (chain.length) { e = chain[0]; continue; } + const rs = M.all(e.ownedSpecialization).find((s) => s['@type'] === 'ReferenceSubsetting') || M.all(e.ownedReferenceSubsetting)[0]; + const next = rs ? M.get(rs.referencedFeature ?? rs.general) : null; + if (next) { e = next; continue; } + // a port of the soi (or of a part that redefines it) also stands for the soi + return match(M.get(e.owningType ?? e.owner)); + } + return null; + }; + const links = []; + for (const c of featuresOf(M, ctx, ['InterfaceUsage', 'ConnectionUsage', 'AllocationUsage', 'FlowUsage', 'SuccessionFlowUsage', 'BindingConnectorAsUsage'])) { + if (c['@type'] === 'BindingConnectorAsUsage' || c['@type'] === 'AllocationUsage') continue; + // the owned ends: the inherited ends of the library (actorPort, systemPort) point to the generic actors and soi + const ends = M.all(c.ownedEndFeature).length ? M.all(c.ownedEndFeature) : M.all(c.connectorEnd).length ? M.all(c.connectorEnd) : M.all(c.relatedFeature); + const ps = [...new Set(ends.map(partOfEnd).filter(Boolean))]; + if (ps.length === 2 && ps.includes(soi)) links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: ps.find((p) => p !== soi)['@id'] }); + } + // white box: the system of interest of the Impl context, its parts + let soiImpl = null; + if (impl) soiImpl = featuresOf(M, impl, 'PartUsage').find((p) => p !== soiLib && specializes(M, p, soiLib)) || null; + const inner = featuresOf(M, soiImpl || soi, 'PartUsage').filter((p) => !p.isLibraryElement && !specializes(M, p, actorsLib)); + return { + key: def.key, role: def.role, title: def.title, + context: { ...brief(M, ctx), types: typeNames(M, ctx) }, + impl: impl ? brief(M, impl) : null, + system: soi ? { ...brief(M, soi), types: typeNames(M, soi), stereotypes: stereotypesOf(M, soi) } : null, + systemImpl: soiImpl ? { ...brief(M, soiImpl), types: typeNames(M, soiImpl) } : null, + actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((s) => s !== 'system') })), + links, + parts: inner.map((p) => ({ ...brief(M, p), types: typeNames(M, p), multiplicity: multiplicityOf(M, p) })), + }; +} + +/** "1..*", "0..1", "" from the multiplicity of a feature */ +export function multiplicityOf(M, f) { + const m = M.get(f?.multiplicity); + if (!m) return ''; + const lo = exprText(M, M.get(m.lowerBound)), hi = exprText(M, M.get(m.upperBound)); + if (!lo && !hi) { + const bounds = M.all(m.ownedFeature).map((b) => valueOf(M, b) || exprText(M, b)); + if (bounds.length === 2) return `${bounds[0]}..${bounds[1]}`; + if (bounds.length === 1) return bounds[0]; + return ''; + } + return lo && hi && lo !== hi ? `${lo}..${hi}` : hi || lo; +} + +function readStakeholders(M, project) { + const ownerLib = M.byQName(`${SYSMOD.project}::projectOwner`); + const lib = M.byQName(`${SYSMOD.project}::projectStakeholders`); + // all owned features that are stakeholders, also the project owner (:>> projectOwner, which :> projectStakeholders) + const all = lib ? ownedFeaturesOf(M, project).filter((f) => f !== lib && f !== ownerLib && specializes(M, f, lib)) : []; + return all.sort((a, b) => (ownerLib && specializes(M, b, ownerLib)) - (ownerLib && specializes(M, a, ownerLib))).map((p) => ({ + id: p['@id'], + name: valueNamed(M, p, 'name') || nameOf(p), + element: nameOf(p), + types: typeNames(M, p), + owner: !!ownerLib && specializes(M, p, ownerLib), + doc: docOf(M, p), + contact: valueNamed(M, p, 'contact'), + risk: valueNamed(M, p, 'risk'), + effort: valueNamed(M, p, 'effort'), + categories: valueNamed(M, p, 'categories'), + })); +} + +/** Nested concerns/requirements of a root (the needs under stakeholderNeeds, the requirements under the specification) */ +function nestedOf(M, root, types, depth = 0, seen = new Set()) { + if (!root || depth > 6) return []; + const out = []; + for (const f of featuresOf(M, root, types)) { + if (seen.has(f['@id']) || f.isLibraryElement || !nameOf(f)) continue; + if (M.get(f.owningMembership)?.['@type'] === 'FramedConcernMembership') continue; // frame x: a reference, not a nested need + seen.add(f['@id']); + out.push({ el: f, depth }); + out.push(...nestedOf(M, f, types, depth + 1, seen)); + } + return out; +} + +const subjectStakeholders = (M, el) => featuresOf(M, el) + .filter((f) => f['@type'] === 'PartUsage' && M.all(f.owningMembership ? [f.owningMembership] : []).some((m) => m['@type'] === 'StakeholderMembership')) + .map((f) => { const v = valueOf(M, f); return v && v !== nameOf(f) ? v.split('.').pop() : nameOf(f); }) + .filter(Boolean); + +function readNeeds(M, project) { + const root = roleOf(M, project, 'stakeholderNeeds')[0]; + return nestedOf(M, root, 'ConcernUsage').map(({ el, depth }) => ({ + id: el['@id'], depth, + name: nameOf(el), shortName: el.shortName || el.declaredShortName || '', + types: typeNames(M, el), + doc: docOf(M, el), + stakeholders: subjectStakeholders(M, el).join(', '), + priority: valueNamed(M, el, 'priority'), + })); +} + +function readRequirements(M, project) { + const root = roleOf(M, project, 'systemRequirementSpecification')[0]; + return { + specification: root ? { ...brief(M, root), types: typeNames(M, root) } : null, + requirements: nestedOf(M, root, ['RequirementUsage', 'ConcernUsage']).filter(({ el }) => el['@type'] === 'RequirementUsage').map(({ el, depth }) => ({ + id: el['@id'], depth, + shortName: el.shortName || el.declaredShortName || M.all(el.definition).map((d) => d.shortName || d.declaredShortName).find(Boolean) || '', + name: nameOf(el), + types: typeNames(M, el), + doc: docOf(M, el), + motivation: valueNamed(M, el, 'motivation'), + priority: valueNamed(M, el, 'priority'), + obligation: valueNamed(M, el, 'obligation'), + stability: valueNamed(M, el, 'stability'), + stakeholders: subjectStakeholders(M, el).join(', '), + })), + }; +} + +function readUseCases(M, ctx) { + if (!ctx) return []; + const lib = M.byQName(SYSMOD.useCases); + const el = M.get(ctx.context.id); + return featuresOf(M, el, 'UseCaseUsage').filter((u) => u !== lib && !u.isLibraryElement).map((u) => { + const objective = M.all(u.objectiveRequirement)[0] + || featuresOf(M, u, 'RequirementUsage').find((r) => M.get(r.owningMembership)?.['@type'] === 'ObjectiveMembership'); + const subject = M.get(u.subjectParameter) || featuresOf(M, u).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); + // steps: the actions the use case (or its definition) owns and the actions its subject performs for it + const steps = []; + const ACTIONS = ['PerformActionUsage', 'ActionUsage', 'AcceptActionUsage', 'SendActionUsage']; + for (const s of [u, ...definitionsOf(M, u)]) { + const subj = M.get(s.subjectParameter) || ownedFeaturesOf(M, s).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); + for (const owner of [subj, s].filter(Boolean)) { + for (const a of ownedFeaturesOf(M, owner, ACTIONS)) { + const n = nameOf(a); + if (n && !a.isLibraryElement && !steps.includes(n) && !/^(start|done|subactions|actions)$/.test(n)) steps.push(n); + } + } + } + const actors = M.all(u.actorParameter).map((a) => nameOf(a)).filter(Boolean); + return { + id: u['@id'], + name: nameOf(u), + types: typeNames(M, u), + doc: docOf(M, objective) || docOf(M, u), + subject: subject ? nameOf(subject) : '', + actors: actors.join(', '), + trigger: valueNamed(M, u, 'ucTrigger'), + result: valueNamed(M, u, 'ucResult'), + motivation: valueNamed(M, u, 'ucMotivation'), + precondition: modelDoc(M, featureNamed(M, u, 'precondition')), + postcondition: modelDoc(M, featureNamed(M, u, 'postcondition')), + steps, + }; + }); +} + +/** Documentation of a feature of the model; '' for the inherited feature of the SYSMOD library with its generic text */ +const modelDoc = (M, f) => (f && !isLibrary(f) ? docOf(M, f) : ''); + +function readObjectives(M, project) { + const root = roleOf(M, project, 'systemObjectives')[0]; + return { + doc: docOf(M, root, false), + items: nestedOf(M, root, 'ConcernUsage').map(({ el, depth }) => ({ id: el['@id'], depth, name: nameOf(el), types: typeNames(M, el), doc: docOf(M, el) })), + }; +} + +/** UVL text of a feature tree (PLEML): element with #featureTree and a textual representation */ +function readFeatureTree(M) { + for (const mu of M.ofType('MetadataUsage')) { + const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; + if (!def || def.declaredShortName !== 'featureTree') continue; + for (const a of M.all(mu.annotatedElement)) { + const rep = M.all(a.textualRepresentation)[0] || M.all(a.ownedElement).find((e) => e['@type'] === 'TextualRepresentation'); + if (rep?.body) return { name: nameOf(a), language: rep.language || '', body: cleanDoc(rep.body) }; + } + } + return null; +} + +/** Everything the viewer shows for one SYSMOD project. Plain data: strings, arrays, objects. */ +export function readProject(M, projectId) { + const project = M.get(projectId); + if (!project) throw new Error('The SYSMOD project is not in the loaded model.'); + const ps = roleOf(M, project, 'problemStatement')[0]; + const contexts = CONTEXTS.map((def) => readContext(M, project, def)); + const byKey = Object.fromEntries(CONTEXTS.map((d, i) => [d.key, contexts[i]])); + const owner = roleOf(M, project, 'projectOwner')[0]; + const sic = byKey.SIC; + const sicImpl = M.get(sic?.systemImpl?.id), sicSoi = M.get(sic?.system?.id); + const view = { + id: project['@id'], + name: nameOf(project), + qualifiedName: project.qualifiedName || '', + doc: docOf(M, project, false), + purpose: valueNamed(M, project, 'purpose'), + owner: owner ? valueNamed(M, owner, 'name') || nameOf(owner) : '', + problemStatement: ps ? { id: ps['@id'], name: nameOf(ps), doc: docOf(M, ps, false) } : null, + // the system idea: the white box system of interest of the system idea context (its own text, else its definition's) + systemIdea: sic?.system ? { + name: sic.system.name, + types: (sicImpl ? typeNames(M, sicImpl) : sic.system.types), + doc: docOf(M, sicImpl) || docOf(M, sicSoi), + blackBox: sicImpl ? docOf(M, sicSoi) : '', + } : null, + objectives: readObjectives(M, project), + stakeholders: readStakeholders(M, project), + needs: readNeeds(M, project), + ...readRequirements(M, project), + useCases: readUseCases(M, byKey.SC), + contexts, + featureTree: readFeatureTree(M), + }; + view.atlas = atlasOf(view); + view.checks = checksOf(view); + return view; +} + +/** Which SYSMOD artifacts the project has: the status of the SYSMOD Atlas. */ +export function atlasOf(v) { + const ctx = Object.fromEntries(v.contexts.map((c, i) => [CONTEXTS[i].key, !!c])); + return { + FEATURE: !!v.featureTree, + STAKE: v.stakeholders.length > 0, + PS: !!v.problemStatement?.doc, + NE: v.needs.length > 0, + RE: v.requirements.length > 0, + UC: v.useCases.length > 0, + ...ctx, + }; +} + +/** Simple completeness checks (the "quality checks" of the original viewer, extended to SYSMOD v5). */ +export function checksOf(v) { + const c = (id, ok, title, okText, failText) => ({ id, status: ok ? 'passed' : 'failed', title, text: ok ? okText : failText }); + const owner = v.stakeholders.find((s) => s.owner); + return [ + c('SYSMOD-001', !!v.problemStatement?.doc, 'Problem statement', 'The project has a problem statement with text.', 'The project has no problem statement with text (concern :>> problemStatement with a doc).'), + c('SYSMOD-002', !!owner, 'Project owner', `The project owner is ${owner?.name}.`, 'No stakeholder redefines projectOwner.'), + c('SYSMOD-003', v.stakeholders.length > 1, 'Stakeholders', `${v.stakeholders.length} stakeholders.`, 'Besides the project owner, no stakeholders are modeled (:> projectStakeholders).'), + c('SYSMOD-004', !!v.systemIdea, 'System idea', 'The system idea context has a system of interest.', 'No system idea context with a system of interest (:>> systemIdeaContext).'), + c('SYSMOD-005', v.contexts.some((x) => x && x.key === 'SC'), 'System context', 'The project has a specification context.', 'No specification context (:>> specificationContext).'), + c('SYSMOD-006', v.contexts.filter(Boolean).every((x) => x.actors.length > 0), 'Actors', 'Every context has actors.', `Contexts without actors: ${v.contexts.filter((x) => x && !x.actors.length).map((x) => x.title).join(', ')}.`), + c('SYSMOD-007', v.useCases.length > 0, 'Use cases', `${v.useCases.length} system use cases.`, 'The specification context has no system use cases.'), + c('SYSMOD-008', v.requirements.length > 0, 'Requirements', `${v.requirements.length} requirements.`, 'No requirements under the system requirement specification (:>> systemRequirementSpecification).'), + c('SYSMOD-009', v.requirements.every((r) => r.doc), 'Requirement texts', 'Every requirement has a text.', `Requirements without text: ${v.requirements.filter((r) => !r.doc).map((r) => r.name).join(', ')}.`), + ]; +} diff --git a/web/sysmod-viewer.css b/web/sysmod-viewer.css new file mode 100644 index 0000000..67b6f31 --- /dev/null +++ b/web/sysmod-viewer.css @@ -0,0 +1,123 @@ +/* SYSMOD viewer (single page): styles. The same class names as on mbse4u.com/tools/sysmod-viewer/, without the site's framework. */ +:root { + --sheet: #f6f7f9; --surface: #ffffff; --ink: #1d2330; --muted: #5f6878; --line: #2457c5; --mark: #ffe14d; --on-mark: #1d2330; + --c-methods: #2e7d32; --c-books: #c62828; --c-info: #b26a00; --sec: #2457c5; + --font-ui: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; --font-display: var(--font-ui); + --font-notation: ui-monospace, "Cascadia Code", Consolas, monospace; --font-mono: var(--font-notation); + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { --sheet: #14171c; --surface: #1b1f26; --ink: #e3e7ee; --muted: #9aa3b2; --line: #6e9cff; --sec: #6e9cff; --c-methods: #66bb6a; --c-books: #ff6b6b; --c-info: #f0b45a; } +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--sheet); color: var(--ink); font-family: var(--font-ui); line-height: 1.5; } +main { max-width: 72rem; margin: 0 auto; padding: 2rem clamp(1rem, 4vw, 2.5rem) 4rem; } +a { color: var(--line); } +h1 { font-size: clamp(1.75rem, 3vw, 2.25rem); margin: 0 0 0.25rem; } +code { font-family: var(--font-notation); font-size: 0.9em; } +.lead { max-width: 46rem; margin: 0.5rem 0 0; } +.btn { display: inline-flex; align-items: center; gap: 0.45rem; font: 600 0.9375rem var(--font-ui); padding: 0.55rem 1rem; border: 1.5px solid var(--ink); background: var(--ink); color: var(--sheet); border-radius: 3px; cursor: pointer; text-decoration: none; } +.btn:hover { background: var(--mark); color: var(--on-mark); } +.prose { max-width: 46rem; } .prose li + li { margin-top: 0.4rem; } +.ui { font-family: var(--font-ui); } .text-muted { color: var(--muted); } .font-semibold { font-weight: 600; } .font-normal { font-weight: 400; } +.m-0 { margin: 0; } .mb-2 { margin-bottom: 0.5rem; } .mb-3 { margin-bottom: 0.75rem; } .mb-4 { margin-bottom: 1rem; } .mt-4 { margin-top: 1rem; } .mt-6 { margin-top: 1.5rem; } .mt-10 { margin-top: 2.5rem; } .mt-16 { margin-top: 4rem; } .ml-3 { margin-left: 0.75rem; } +.max-w-\[46rem\] { max-width: 46rem; } .overflow-x-auto { overflow-x: auto; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } +[hidden] { display: none !important; } + +.display { font-family: var(--font-display); font-weight: 700; letter-spacing: -0.01em; line-height: 1.1; } +.display-md { font-size: clamp(1.625rem, 2.6vw, 2.125rem); } +.ui { font-family: var(--font-ui); } +.notation { font-family: var(--font-notation); font-size: 0.8125rem; line-height: 1.7; } +.stereo { font-family: var(--font-ui); font-size: 0.8125rem; font-weight: 500; color: var(--sec, var(--muted)); line-height: 1.3; } +.stereo::before { content: "«" / ""; } +.stereo::after { content: "»" / ""; } +.bk { border: 1.5px solid var(--line); background: var(--surface); } +.bk-usage { border-radius: 10px; overflow: hidden; } +.bk-head { padding: calc(0.7rem + 6px) 1rem 0.8rem; font-family: var(--font-ui); box-shadow: inset 0 6px 0 var(--sec, var(--line)); background: color-mix(in oklab, var(--sec, var(--surface)) 9%, var(--surface)); } +.bk-comp { border-top: 1.5px solid var(--line); padding: 0.65rem 1rem; } +.bk-comp.text { font-size: 1rem; line-height: 1.6; } +.bk-link { display: block; color: inherit; text-decoration: none; height: 100%; } +.bk-link:hover .bk { background: color-mix(in oklab, var(--mark) 22%, var(--surface)); } +.bk-link:hover .bk-title { background: var(--mark); color: var(--on-mark); } +.bk-title { font-family: var(--font-ui); font-stretch: 82%; font-weight: 700; font-size: 1.5rem; line-height: 1.1; letter-spacing: -0.005em; } +.mc-result { border: 1.5px solid var(--line); border-left-width: 6px; border-radius: 10px; padding: 1rem 1.25rem; background: color-mix(in oklab, var(--surface) 70%, transparent); max-width: 52rem; } +.mc-result.mc-ok { border-left-color: var(--c-methods); } +.mc-result.mc-bad { border-left-color: var(--c-books); } +.mc-result.mc-meh { border-left-color: var(--c-info); } +.mc-verdict { margin: 0 0 0.35rem; font-family: var(--font-display); font-weight: 700; font-size: 1.5rem; } +.mc-ok .mc-verdict { color: var(--c-methods); } .mc-bad .mc-verdict { color: var(--c-books); } .mc-meh .mc-verdict { color: var(--c-info); } +.mc-facts { margin: 0.25rem 0; font-family: var(--font-ui); font-size: 0.9375rem; color: var(--muted); } +.mc-src { margin: 0.5rem 0 0; padding: 0.4rem 0.6rem; border: 1px solid var(--line); border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; background: var(--surface); } +.mc-files { border-collapse: collapse; font-family: var(--font-ui); font-size: 0.9375rem; min-width: 34rem; } +.mc-files th, .mc-files td { text-align: left; padding: 0.4rem 1rem 0.4rem 0; border-bottom: 1px solid var(--line); } +.mc-files .num { text-align: right; font-variant-numeric: tabular-nums; } +.mc-result, .mc-diag-body { overflow-wrap: anywhere; } +.mc-src { max-width: 100%; } + +/* SYSMOD viewer (/tools/sysmod-viewer/, script public/tools/sysmod-viewer/sysmod-viewer.js) */ +.sv-tabs { display: flex; flex-wrap: wrap; gap: 0.25rem 1.25rem; border-bottom: 1.5px solid var(--line); margin-bottom: 1.25rem; } +.sv-tabs [role="tab"] { font-weight: 600; font-size: 0.9375rem; color: var(--ink); background: none; border: 0; border-bottom: 3px solid transparent; padding: 0.4rem 0.1rem; margin-bottom: -1.5px; cursor: pointer; } +.sv-tabs [role="tab"]:hover { background: var(--mark); color: var(--on-mark); } +.sv-tabs [role="tab"][aria-selected="true"] { border-bottom-color: var(--sec, var(--line)); } +.sv-form { display: grid; grid-template-columns: max-content minmax(0, 34rem); gap: 0.6rem 1rem; align-items: center; } +@media (max-width: 40rem) { .sv-form { grid-template-columns: minmax(0, 1fr); } .sv-form > span:empty { display: none; } } +.sv-input { width: 100%; box-sizing: border-box; font-family: var(--font-ui); font-size: 0.9375rem; padding: 0.5rem 0.65rem; border: 1.5px solid var(--line); border-radius: 4px; background: var(--surface); color: var(--ink); } +.sv-input:focus-visible, .sv-file-btn:has(+ input:focus-visible) { outline: 3px solid var(--mark); outline-offset: 1px; } +.btn:disabled { opacity: 0.55; cursor: progress; } +.sv-file-btn { cursor: pointer; } +.sv-status[data-kind="ok"] { color: var(--c-methods); font-weight: 600; } +.sv-status[data-kind="bad"] { color: var(--c-books); font-weight: 600; } +.sv-out { scroll-margin-top: 5rem; } +.sv-head { border-top: 1.5px solid var(--line); padding-top: 1.5rem; display: grid; gap: 0.35rem; } +.sv-origin { font-size: 0.875rem; margin: 0.25rem 0 0.5rem; } +.sv-purpose { margin: 0; max-width: 46rem; } +.sv-sec { margin-top: 3rem; scroll-margin-top: 5rem; } +.sv-h { font-size: 1.625rem; margin: 0 0 1rem; } +.sv-h4 { font-weight: 700; font-size: 1.0625rem; margin: 1.5rem 0 0.5rem; } +.sv-empty { margin: 0; font-style: italic; } +.sv-details { margin-top: 1rem; } +.sv-details > summary { cursor: pointer; font-weight: 600; } +.sv-atlas { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.25rem; max-width: 52rem; } +@media (max-width: 40rem) { .sv-atlas { grid-template-columns: minmax(0, 1fr); } } +.sv-space { border: 1.5px solid var(--line); border-radius: 10px; padding: 0.75rem; display: grid; gap: 0.6rem; align-content: start; background: var(--surface); } +.sv-space-h { margin: 0; } +.sv-row { display: flex; flex-wrap: wrap; gap: 0.5rem; } +.sv-cell { flex: 1 1 9rem; display: flex; gap: 0.45rem; align-items: baseline; font-family: var(--font-ui); font-size: 0.9375rem; padding: 0.55rem 0.7rem; border: 1.5px dashed color-mix(in oklab, var(--line) 50%, transparent); border-radius: 6px; color: var(--muted); text-decoration: none; } +.sv-cell.on { border-style: solid; border-color: var(--c-methods); color: var(--ink); font-weight: 600; background: color-mix(in oklab, var(--c-methods) 9%, var(--surface)); } +.sv-cell.on:hover { background: var(--mark); color: var(--on-mark); } +.sv-cell-mark { color: var(--c-methods); font-size: 0.75rem; } +.sv-checks { list-style: none; margin: 0.75rem 0 0; padding: 0; display: grid; gap: 0.4rem; max-width: 52rem; font-family: var(--font-ui); font-size: 0.9375rem; } +.sv-check { display: flex; gap: 0.6rem; align-items: baseline; } +.sv-check-mark { flex: none; width: 1.25rem; text-align: center; font-weight: 700; } +.sv-check.passed .sv-check-mark { color: var(--c-methods); } +.sv-check.failed .sv-check-mark { color: var(--c-info); } +.sv-quote { margin: 0; max-width: 46rem; border-left: 6px solid var(--sec, var(--line)); background: color-mix(in oklab, var(--sec, var(--line)) 8%, transparent); padding: 0.75rem 1rem; border-radius: 0 10px 10px 0; font-size: 1.125rem; line-height: 1.6; } +.sv-quote p { margin: 0; } .sv-quote p + p { margin-top: 0.6rem; } +.sv-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.75rem; max-width: 46rem; } +.sv-list p { margin: 0.15rem 0 0; } +.sv-table { min-width: 44rem; } +.sv-table td { vertical-align: top; } +.sv-table .sv-text { min-width: 16rem; max-width: 28rem; } +.sv-table .sv-text p + p { margin-top: 0.4rem; } +.sv-tag { display: inline-block; font-family: var(--font-ui); font-size: 0.75rem; font-weight: 600; padding: 0 0.4rem; border-radius: 3px; background: var(--mark); color: var(--on-mark); } +.sv-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 22rem), 1fr)); gap: 1.25rem; } +.sv-card-title { font-size: 1.25rem; margin: 0.1rem 0; overflow-wrap: anywhere; } +.sv-dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 0.3rem 0.75rem; margin: 0.75rem 0; font-size: 0.9375rem; } +.sv-dl dt { font-family: var(--font-ui); font-weight: 600; color: var(--muted); } +.sv-dl dd { margin: 0; } +.sv-steps { margin: 0.4rem 0 0; padding-left: 1.5rem; } +.sv-pre { max-height: 28rem; white-space: pre; } +.sv-fig { margin: 0; max-width: 60rem; border: 1.5px solid var(--line); border-radius: 10px; background: var(--surface); padding: 0.5rem; overflow-x: auto; } +.sv-svg { display: block; width: 100%; min-width: 34rem; height: auto; font-family: var(--font-ui); } +.sv-svg text { fill: var(--ink); font-size: 13px; } +.sv-svg .sv-name { font-weight: 650; font-size: 14px; } +.sv-svg .sv-st { fill: var(--muted); font-size: 12px; } +.sv-svg .sv-ifc { fill: var(--muted); font-size: 11.5px; font-family: var(--font-notation); } +.sv-sys > rect { fill: color-mix(in oklab, var(--sec, var(--line)) 8%, var(--surface)); stroke: var(--sec, var(--line)); stroke-width: 2; } +.sv-part rect { fill: var(--surface); stroke: var(--line); stroke-width: 1.25; } +.sv-part text { font-size: 12.5px; font-family: var(--font-notation); } +.sv-actor rect { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; } +.sv-actor circle, .sv-actor path { fill: none; stroke: var(--ink); stroke-width: 1.5; stroke-linecap: round; } +.sv-lines line { stroke: var(--line); stroke-width: 1.5; } +.sv-lines line.sv-nolink { stroke-dasharray: 4 4; opacity: 0.6; } diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js new file mode 100644 index 0000000..eda94a6 --- /dev/null +++ b/web/sysmod-viewer.js @@ -0,0 +1,447 @@ +/* sysmod-viewer.js: the interface of the page /tools/sysmod-viewer/. Shows a SYSMOD project of a SysML v2 model: + the SYSMOD Atlas, problem statement, system idea and objectives, stakeholders, needs, requirements, use cases and the + system context diagrams. The model comes from + - a SysML v2 API server (the browser asks the server directly, see sysmod-viewer-api.js), + - the Delivery Drone example (the SysML v2 engine of the checker reads the SYSMOD files of this site in the browser), + - files of the visitor: .sysml (read by the same engine, together with the SYSMOD library) or .json (elements as the API delivers them). + Nothing is sent anywhere else. All texts from the model are inserted with textContent, never as HTML. + The same file runs in github.com/Open-MBEE/sysmod-sysmlv2-api (web/index.html) and on mbse4u.com/tools/sysmod-viewer/: + without cfg.engine there is no example and no .sysml files (only .json), without cfg.relay no relay. */ + +const root = document.getElementById('sysmod-viewer'); +if (root) start(JSON.parse(root.dataset.config)); + +async function start(cfg) { + const core = await import(cfg.core); + const apiMod = await import(cfg.api); + const $ = (s) => root.querySelector(s); + + // ---------- small DOM helpers ---------- + const h = (tag, attrs = {}, ...kids) => { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v == null || v === false) continue; + if (k === 'class') e.className = v; + else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); + else e.setAttribute(k, v === true ? '' : v); + } + for (const k of kids.flat(Infinity)) if (k != null && k !== false && k !== '') e.append(k.nodeType ? k : document.createTextNode(String(k))); + return e; + }; + const SVGNS = 'http://www.w3.org/2000/svg'; + const s = (tag, attrs = {}, ...kids) => { + const e = document.createElementNS(SVGNS, tag); + for (const [k, v] of Object.entries(attrs)) if (v != null) e.setAttribute(k, v); + for (const k of kids.flat(Infinity)) if (k != null && k !== false) e.append(k.nodeType ? k : document.createTextNode(String(k))); + return e; + }; + /** Doc text as paragraphs: blank lines separate paragraphs, single line breaks are the line breaks of the source. */ + const paras = (text, cls = '') => String(text || '').split(/\n{2,}/).map((p) => p.replace(/\s*\n\s*/g, ' ').trim()).filter(Boolean).map((p) => h('p', { class: cls }, p)); + const nf = new Intl.NumberFormat('en'); + const status = (el, text, kind = '') => { el.textContent = text; el.dataset.kind = kind; }; + + // ---------- state in the address (never the token) ---------- + const params = new URLSearchParams(location.search); + const setParams = (obj) => { + const p = new URLSearchParams(); + for (const [k, v] of Object.entries(obj)) if (v) p.set(k, v); + const q = p.toString(); + history.replaceState(null, '', `${location.pathname}${q ? `?${q}` : ''}${location.hash}`); + }; + + // ---------- source tabs ---------- + const tabs = [...root.querySelectorAll('[data-src-tab]')]; + const panels = [...root.querySelectorAll('[data-src-panel]')]; + const showTab = (name) => { + for (const t of tabs) t.setAttribute('aria-selected', String(t.dataset.srcTab === name)); + for (const p of panels) p.hidden = p.dataset.srcPanel !== name; + }; + tabs.forEach((t) => t.addEventListener('click', () => showTab(t.dataset.srcTab))); + root.querySelector('[data-js-only]')?.removeAttribute('hidden'); + + // ---------- the model ---------- + let model = null, source = null; // source: { kind: 'server'|'example'|'files', label, server?, project?, commit? } + const out = $('[data-out]'); + const pick = $('[data-pick]'), pickSel = $('[data-pick-select]'); + + function useElements(elements, src) { + const t0 = performance.now(); + model = core.createModel(elements); + source = src; + const projects = core.findProjects(model); + out.replaceChildren(); + if (!projects.length) { + pick.hidden = true; + out.append(h('div', { class: 'mc-result mc-bad' }, + h('p', { class: 'mc-verdict' }, 'No SYSMOD project found'), + h('p', { class: 'm-0' }, `The model has ${nf.format(model.size)} elements, but none of them is a SYSMOD project (#project, or a specialization of SYSMOD::Project). ` + + 'The SYSMOD library must be part of the same model.'))); + return; + } + pickSel.replaceChildren(...projects.map((p) => h('option', { value: p.id }, p.qualifiedName && p.qualifiedName !== p.name ? `${p.name} (${p.qualifiedName})` : p.name))); + pick.hidden = projects.length < 2; + const wanted = params.get('sysmod'); + const first = projects.find((p) => p.id === wanted) || projects[0]; + pickSel.value = first.id; + render(first.id, performance.now() - t0); + } + pickSel.addEventListener('change', () => render(pickSel.value)); + + // ---------- 1. SysML v2 API server ---------- + const f = { + url: $('[data-url]'), token: $('[data-token]'), connect: $('[data-connect]'), st: $('[data-status-server]'), + projRow: $('[data-proj-row]'), proj: $('[data-proj]'), projFilter: $('[data-proj-filter]'), + commit: $('[data-commit]'), load: $('[data-load]'), err: $('[data-err-server]'), + }; + let client = null, projectList = [], abort = null; + if (params.get('server')) { f.url.value = params.get('server'); showTab('server'); } + // the servers of the relay as suggestions for the address field + const dl = $('[data-relay-list]'); + if (dl) dl.replaceChildren(...(cfg.relay?.servers || []).map((u) => h('option', { value: u }))); + + const showError = (box, e) => { + if (e?.name === 'AbortError') return; + box.replaceChildren(h('div', { class: 'mc-result mc-bad' }, + h('p', { class: 'mc-verdict' }, e?.message || String(e)), + e?.hint ? h('p', { class: 'm-0' }, e.hint) : null, + e?.url ? h('p', { class: 'mc-facts' }, h('code', {}, e.url)) : null)); + }; + + f.connect.addEventListener('click', async () => { + f.err.replaceChildren(); + f.projRow.hidden = true; + try { + client = apiMod.createClient({ baseUrl: f.url.value, token: f.token.value, relay: cfg.relay }); + f.url.value = client.base; + const via = client.viaRelay ? ` via ${cfg.relay?.label || 'the relay'}` : ''; + status(f.st, `Connecting${via} …`); + projectList = await client.projects(); + if (!projectList.length) { status(f.st, 'The server has no projects.', 'bad'); return; } + status(f.st, `${nf.format(projectList.length)} projects${via}`, 'ok'); + f.proj.replaceChildren(); // a new server: no selection carried over from the previous one + fillProjects(); + f.projRow.hidden = false; + const want = params.get('project'); + if (want && projectList.some((p) => p['@id'] === want)) f.proj.value = want; + await loadCommits(); + } catch (e) { status(f.st, ''); showError(f.err, e); } + }); + f.url.addEventListener('keydown', (e) => { if (e.key === 'Enter') f.connect.click(); }); + + function fillProjects() { + const q = f.projFilter.value.trim().toLowerCase(); + const keep = f.proj.value; + const list = projectList.filter((p) => !q || String(p.name || '').toLowerCase().includes(q) || p['@id'].includes(q)); + f.proj.replaceChildren(...list.map((p) => h('option', { value: p['@id'] }, p.name || p['@id']))); + if (list.some((p) => p['@id'] === keep)) f.proj.value = keep; + } + f.projFilter.addEventListener('input', () => { const before = f.proj.value; fillProjects(); if (f.proj.value !== before) loadCommits(); }); + f.proj.addEventListener('change', () => loadCommits()); + + async function loadCommits() { + f.commit.replaceChildren(h('option', {}, 'Loading commits …')); + f.load.disabled = true; + try { + const pid = f.proj.value; + if (!pid) return; + const [commits, head] = await Promise.all([client.commits(pid), defaultHead(pid)]); + if (pid !== f.proj.value) return; // the visitor chose another project meanwhile + const fmt = (c) => { + const d = Date.parse(c.created || ''); + const when = d ? new Date(d).toLocaleString('en', { dateStyle: 'medium', timeStyle: 'short' }) : c['@id'].slice(0, 8); + const desc = c.description ? ` · ${String(c.description).slice(0, 60)}` : ''; + return `${when}${desc}${c['@id'] === head ? ' (head of the default branch)' : ''}`; + }; + f.commit.replaceChildren(...commits.map((c) => h('option', { value: c['@id'] }, fmt(c)))); + const want = params.get('commit'); + f.commit.value = commits.some((c) => c['@id'] === want) ? want : head && commits.some((c) => c['@id'] === head) ? head : commits[0]?.['@id'] || ''; + f.load.disabled = !commits.length; + if (!commits.length) f.commit.replaceChildren(h('option', {}, 'This project has no commits.')); + } catch (e) { f.commit.replaceChildren(); showError(f.err, e); } + } + async function defaultHead(pid) { + try { + const p = await client.project(pid); + const bid = p?.defaultBranch?.['@id']; + if (!bid) return null; + const b = (await client.branches(pid)).find((x) => x['@id'] === bid); + return b?.head?.['@id'] || null; + } catch { return null; } + } + + f.load.addEventListener('click', async () => { + f.err.replaceChildren(); + abort?.abort(); + abort = new AbortController(); + const pid = f.proj.value, cid = f.commit.value; + const pname = f.proj.selectedOptions[0]?.textContent || pid; + f.load.disabled = true; + try { + status(f.st, 'Loading the model …'); + const elements = await client.elements(pid, cid, { signal: abort.signal, onProgress: (n) => status(f.st, `Loading the model … ${nf.format(n)} elements`) }); + status(f.st, `${nf.format(elements.length)} elements loaded`, 'ok'); + setParams({ server: client.base, project: pid, commit: cid }); + useElements(elements, { kind: 'server', label: `${pname} on ${new URL(client.base).host}`, server: client.base, project: pid, commit: cid }); + } catch (e) { status(f.st, ''); showError(f.err, e); } + finally { f.load.disabled = false; } + }); + + // ---------- 2. + 3. The SysML v2 engine in the browser (example and .sysml files) ---------- + let kernelPromise = null; + async function fetchBytes(url) { + const r = await fetch(url); + if (!r.ok) throw new Error(`${url} could not be loaded (HTTP ${r.status})`); + const raw = new Uint8Array(await r.arrayBuffer()); + if (raw[0] !== 0x1f || raw[1] !== 0x8b) return raw; // the server already decompressed it + if (typeof DecompressionStream === 'undefined') throw new Error('This browser cannot decompress the engine. Use a current Chrome, Edge, Firefox or Safari.'); + return new Uint8Array(await new Response(new Blob([raw]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); + } + const kernel = () => (kernelPromise ||= (async () => { + const e = cfg.engine; + const [k, wasm, bundle, snapshot] = await Promise.all([ + import(e.base + e.kernel), fetchBytes(e.base + e.wasm), fetchBytes(e.base + e.bundle), fetchBytes(e.base + e.snapshot), + ]); + await k.default({ module_or_path: wasm }); + return { k, lib: new k.PreparedLibrary(new TextDecoder().decode(bundle), snapshot) }; + })().catch((err) => { kernelPromise = null; throw err; })); + + /** SysML v2 text files -> elements (SysML v2 API JSON), by the engine. Parse errors stop with a message. */ + async function elementsFromSources(files, st) { + status(st, 'Loading the SysML v2 engine (about 5 MB, once) …'); + const { k, lib } = await kernel(); + status(st, `Reading ${files.length} files …`); + await new Promise((r) => setTimeout(r, 30)); // let the browser paint the status + const json = JSON.stringify(files); + const syntax = JSON.parse(k.checkSyntax(json)).filter((x) => x.stage === 'parse'); + if (syntax.length) { + const e = new Error(`${syntax.length} syntax error${syntax.length > 1 ? 's' : ''}, the model cannot be read.`); + e.hint = syntax.slice(0, 3).map((x) => `${x.unit}, line ${x.line}: ${x.message}`).join(' · '); + throw e; + } + const session = k.Session.fromSourcesWithPreparedLibrary(json, lib); + try { return JSON.parse(session.toFullJson(false, 'passthrough')); } finally { session.free(); } + } + + let manifestPromise = null; + const manifest = () => (manifestPromise ||= fetch(cfg.example.manifest).then((r) => { if (!r.ok) throw new Error('The SYSMOD files could not be loaded.'); return r.json(); })); + const sysmodFiles = async (roles) => { + const m = await manifest(); + const files = m.files.filter((x) => roles.includes(x.role)); + return Promise.all(files.map(async (x) => ({ name: x.name, text: await (await fetch(cfg.example.dir + x.name)).text() }))); + }; + + const ex = { btn: $('[data-example]'), st: $('[data-status-example]'), err: $('[data-err-example]') }; + ex.btn?.addEventListener('click', async () => { + ex.err.replaceChildren(); + ex.btn.disabled = true; + try { + const files = await sysmodFiles(['library', 'example']); + const elements = await elementsFromSources(files, ex.st); + status(ex.st, `${nf.format(elements.length)} elements`, 'ok'); + setParams({ example: 'drone' }); + useElements(elements, { kind: 'example', label: 'SYSMOD Delivery Drone example' }); + } catch (e) { status(ex.st, ''); showError(ex.err, e); } + finally { ex.btn.disabled = false; } + }); + + const fl = { input: $('[data-files]'), st: $('[data-status-files]'), err: $('[data-err-files]') }; + fl.input.addEventListener('change', async () => { + fl.err.replaceChildren(); + const picked = [...fl.input.files]; + if (!picked.length) return; + try { + const jsons = picked.filter((x) => /\.json$/i.test(x.name)), texts = picked.filter((x) => /\.(sysml|kerml)$/i.test(x.name)); + let elements; + if (jsons.length) { + status(fl.st, 'Reading …'); + elements = []; + for (const j of jsons) { + const data = JSON.parse(await j.text()); + const list = Array.isArray(data) ? data : Array.isArray(data?.elements) ? data.elements : null; + if (!list) throw Object.assign(new Error(`${j.name} is not a list of elements.`), { hint: 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.' }); + elements.push(...list); + } + } else if (texts.length) { + if (!cfg.engine) throw Object.assign(new Error('.sysml files need the SysML v2 engine, which this page does not have.'), { hint: 'Open a .json file with the elements of a commit, or use mbse4u.com/tools/sysmod-viewer/, which reads .sysml files.' }); + const own = await Promise.all(texts.map(async (x) => ({ name: x.name, text: await x.text() }))); + // the SYSMOD library is added unless the visitor brings it along + const have = new Set(own.map((x) => x.name)); + const lib = (await sysmodFiles(['library'])).filter((x) => !have.has(x.name)); + elements = await elementsFromSources([...lib, ...own], fl.st); + } else throw new Error('Choose .sysml files or a .json file.'); + status(fl.st, `${nf.format(elements.length)} elements`, 'ok'); + setParams({}); + useElements(elements, { kind: 'files', label: picked.map((x) => x.name).join(', ') }); + } catch (e) { status(fl.st, ''); showError(fl.err, e); } + }); + + // ---------- rendering of a SYSMOD project ---------- + const ATLAS = { + problem: [['FEATURE'], ['STAKE', 'PS'], ['NE', 'RE', 'UC', 'SC']], + solution: [['BFAC'], ['SIC'], ['FUC', 'LAC', 'PAC']], + }; + const LABEL = { + FEATURE: 'Features', STAKE: 'Stakeholders', PS: 'Problem Statement', NE: 'Needs', RE: 'Requirements', UC: 'Use Cases', + SC: 'System Specification', BFAC: 'Brownfield Architecture', SIC: 'System Idea Architecture', FUC: 'Functional Architecture', LAC: 'Logical Architecture', PAC: 'Product Architecture', + }; + const TARGET = { FEATURE: 'sv-features', STAKE: 'sv-stakeholders', PS: 'sv-problem', NE: 'sv-needs', RE: 'sv-requirements', UC: 'sv-usecases' }; + const targetOf = (k) => TARGET[k] || `sv-ctx-${k}`; + + const section = (id, title, ...kids) => h('section', { class: 'sv-sec', id, 'aria-labelledby': `${id}-h` }, h('h3', { id: `${id}-h`, class: 'display sv-h' }, title), ...kids); + const empty = (text) => h('p', { class: 'ui text-muted sv-empty' }, text); + const tag = (text) => (text ? h('span', { class: 'sv-tag' }, text) : null); + const typesLine = (types) => (types?.length ? h('span', { class: 'notation text-muted' }, `: ${types.join(', ')}`) : null); + const table = (cols, rows) => h('div', { class: 'overflow-x-auto' }, h('table', { class: 'mc-files sv-table' }, + h('thead', {}, h('tr', {}, cols.map((c) => h('th', { scope: 'col' }, c)))), + h('tbody', {}, rows))); + + function render(projectId, ms) { + const v = core.readProject(model, projectId); + if (source?.kind === 'server') setParams({ server: source.server, project: source.project, commit: source.commit, sysmod: projectId }); + const atlasCell = (k) => { + const on = v.atlas[k]; + return h(on ? 'a' : 'span', { class: `sv-cell${on ? ' on' : ''}`, href: on ? `#${targetOf(k)}` : null, title: on ? `Go to ${LABEL[k]}` : `${LABEL[k]}: not in the model` }, + h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, on ? '■' : '□'), LABEL[k], + h('span', { class: 'sr-only' }, on ? ' (in the model)' : ' (not in the model)')); + }; + const atlas = h('div', { class: 'sv-atlas' }, + ['problem', 'solution'].map((side) => h('div', { class: `sv-space sv-${side}` }, + h('p', { class: 'stereo sv-space-h' }, side === 'problem' ? 'problem space' : 'solution space'), + ATLAS[side].map((row) => h('div', { class: 'sv-row' }, row.map(atlasCell)))))); + + const checks = h('ul', { class: 'sv-checks' }, v.checks.map((c) => h('li', { class: `sv-check ${c.status}` }, + h('span', { class: 'sv-check-mark', 'aria-hidden': 'true' }, c.status === 'passed' ? '✓' : '!'), + h('span', {}, h('strong', {}, c.title), ' ', h('span', { class: 'sr-only' }, c.status === 'passed' ? '(passed) ' : '(open) '), c.text)))); + + const head = h('header', { class: 'sv-head' }, + h('p', { class: 'stereo m-0' }, 'project'), + h('h2', { class: 'display display-md m-0' }, v.name), + v.qualifiedName ? h('p', { class: 'notation text-muted m-0' }, v.qualifiedName) : null, + h('p', { class: 'ui text-muted sv-origin' }, `Source: ${source?.label || ''} · ${nf.format(model.size)} elements${ms ? ` · read in ${Math.round(ms)} ms` : ''}`), + v.purpose ? h('p', { class: 'sv-purpose' }, h('span', { class: 'ui font-semibold' }, 'Purpose: '), v.purpose) : null, + v.owner ? h('p', { class: 'ui m-0' }, h('span', { class: 'font-semibold' }, 'Project owner: '), v.owner) : null, + v.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Project description'), h('div', { class: 'prose max-w-[46rem]' }, paras(v.doc))) : null); + + const sections = [ + section('sv-atlas', 'SYSMOD Atlas', h('p', { class: 'ui text-muted m-0 mb-3' }, 'Which SYSMOD artifacts the project has. Click one to go there.'), atlas, + h('details', { class: 'sv-details', open: true }, h('summary', { class: 'ui' }, `Completeness: ${v.checks.filter((c) => c.status === 'passed').length} of ${v.checks.length}`), checks)), + section('sv-problem', 'Problem statement', v.problemStatement?.doc ? h('blockquote', { class: 'sv-quote' }, paras(v.problemStatement.doc)) : empty('No problem statement in the model.')), + section('sv-idea', 'System idea', + v.systemIdea ? [h('p', { class: 'ui m-0 mb-2' }, h('strong', {}, v.systemIdea.name), typesLine(v.systemIdea.types)), h('div', { class: 'prose max-w-[46rem]' }, paras(v.systemIdea.doc))] : empty('No system idea context in the model.'), + v.objectives.items.length ? [h('h4', { class: 'ui sv-h4' }, 'System objectives'), v.objectives.doc ? h('div', { class: 'prose max-w-[46rem] text-muted' }, paras(v.objectives.doc)) : null, + h('ul', { class: 'sv-list' }, v.objectives.items.map((o) => h('li', { style: `margin-left:${o.depth * 1.25}rem` }, h('strong', { class: 'ui' }, o.name), typesLine(o.types), paras(o.doc, 'm-0'))))] : null), + section('sv-stakeholders', 'Stakeholders', v.stakeholders.length ? table(['Stakeholder', 'Description', 'Risk', 'Effort', 'Categories', 'Contact'], + v.stakeholders.map((x) => h('tr', {}, + h('td', {}, h('strong', {}, x.name), x.owner ? [' ', tag('project owner')] : null, h('br'), h('span', { class: 'notation text-muted' }, x.element, x.types.length ? ` : ${x.types.join(', ')}` : '')), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.risk), h('td', {}, x.effort), h('td', {}, x.categories), h('td', {}, x.contact)))) : empty('No stakeholders in the model.')), + section('sv-needs', 'Stakeholder needs', v.needs.length ? table(['Need', 'Text', 'Stakeholders', 'Priority'], + v.needs.map((x) => h('tr', {}, + h('td', { style: x.depth ? `padding-left:${x.depth * 1.25}rem` : null }, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.stakeholders), h('td', {}, x.priority)))) : empty('No stakeholder needs in the model.')), + section('sv-requirements', 'System requirements', + v.specification ? h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, v.specification.name, v.specification.types.length ? ` : ${v.specification.types[0]}` : '')) : null, + v.requirements.length ? table(['Requirement', 'Text', 'Obligation', 'Stability', 'Motivation', 'Stakeholders'], + v.requirements.map((x) => h('tr', {}, + h('td', { style: x.depth ? `padding-left:${x.depth * 1.25}rem` : null }, x.shortName ? h('span', { class: 'notation' }, `<${x.shortName}> `) : null, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.obligation), h('td', {}, x.stability), h('td', { class: 'sv-text' }, x.motivation), h('td', {}, x.stakeholders)))) : empty('No system requirements in the model.')), + section('sv-usecases', 'System use cases', v.useCases.length ? h('div', { class: 'sv-cards' }, v.useCases.map((u) => h('article', { class: 'bk bk-usage sv-card' }, + h('div', { class: 'bk-head' }, h('p', { class: 'stereo m-0' }, 'use case'), h('h4', { class: 'bk-title sv-card-title' }, u.name), typesLine(u.types)), + h('div', { class: 'bk-comp' }, paras(u.doc, 'm-0'), + h('dl', { class: 'sv-dl' }, + [['Trigger', u.trigger], ['Result', u.result], ['Precondition', u.precondition], ['Postcondition', u.postcondition], ['Motivation', u.motivation], ['Actors', u.actors], ['Subject', u.subject]] + .filter(([, val]) => val).map(([k, val]) => [h('dt', {}, k), h('dd', {}, val)])), + u.steps.length ? h('details', {}, h('summary', { class: 'ui' }, `${u.steps.length} steps`), h('ol', { class: 'sv-steps notation' }, u.steps.map((st) => h('li', {}, st)))) : null)))) + : empty('No system use cases in the specification context.')), + ...v.contexts.map((c, i) => { + const def = core.CONTEXTS[i]; + return section(`sv-ctx-${def.key}`, def.title, c ? contextView(c) : empty(`No ${def.role} in the model.`)); + }), + v.featureTree ? section('sv-features', 'Feature tree', h('p', { class: 'ui text-muted m-0 mb-2' }, `${v.featureTree.name}${v.featureTree.language ? ` (${v.featureTree.language})` : ''}`), h('pre', { class: 'mc-src sv-pre' }, v.featureTree.body)) : null, + ]; + out.replaceChildren(head, ...sections.filter(Boolean)); + out.querySelector('h2')?.setAttribute('tabindex', '-1'); + out.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' }); + } + + // ---------- context diagram (SVG) ---------- + function contextView(c) { + const facts = h('p', { class: 'ui text-muted m-0 mb-3' }, + h('span', { class: 'notation' }, c.context.name, c.context.types.length ? ` : ${c.context.types[0]}` : ''), + ` · ${c.actors.length} actors · ${c.links.length} interfaces · ${c.parts.length} parts${c.systemImpl ? ' (white box)' : ''}`); + return [facts, h('figure', { class: 'sv-fig' }, diagram(c), h('figcaption', { class: 'sr-only' }, describe(c))), + c.context.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Description'), h('div', { class: 'prose max-w-[46rem]' }, paras(c.context.doc))) : null]; + } + const describe = (c) => `System context ${c.context.name}: system of interest ${c.system?.name || 'missing'}` + + `${c.parts.length ? ` with the parts ${c.parts.map((p) => p.name).join(', ')}` : ''}; actors ${c.actors.map((a) => `${a.name}${a.stereotypes.length ? ` (${a.stereotypes.join(', ')})` : ''}`).join(', ') || 'none'}` + + `${c.links.length ? `; interfaces ${c.links.map((l) => l.name).join(', ')}` : ''}.`; + + const clip = (text, n) => (text.length > n ? `${text.slice(0, n - 1)}…` : text); + function diagram(c) { + const W = 960, ACT_W = 180, ACT_H = 62, GAP = 26, PAD = 20, LANE = 140; + const left = [], right = []; + c.actors.forEach((a, i) => (i % 2 ? right : left).push(a)); + const rows = Math.max(left.length, right.length, 1); + const sysX = PAD + ACT_W + LANE, sysW = W - 2 * sysX; + const partCols = sysW > 300 ? 2 : 1, partW = (sysW - 36 - (partCols - 1) * 14) / partCols, partH = 40; + const partRows = Math.ceil(c.parts.length / partCols); + const sysInner = 64 + (partRows ? partRows * (partH + 12) + 6 : 10); + const actorsH = rows * ACT_H + (rows - 1) * GAP; + const H = Math.max(actorsH, sysInner) + 2 * PAD; + const sysY = PAD + Math.max(0, (H - 2 * PAD - sysInner) / 2), sysH = Math.max(sysInner, Math.min(H - 2 * PAD, sysInner + 40)); + const svg = s('svg', { viewBox: `0 0 ${W} ${H}`, class: 'sv-svg', role: 'img', 'aria-label': `Context diagram of ${c.context.name}` }); + // the system of interest + const sys = s('g', { class: 'sv-sys' }, + s('rect', { x: sysX, y: sysY, width: sysW, height: sysH, rx: 10 }), + s('text', { x: sysX + sysW / 2, y: sysY + 22, class: 'sv-st', 'text-anchor': 'middle' }, `«${(c.system?.stereotypes?.[0]) || 'system'}»`), + s('text', { x: sysX + sysW / 2, y: sysY + 42, class: 'sv-name', 'text-anchor': 'middle' }, s('title', {}, c.system?.name || ''), clip(c.system?.name || '(no system of interest)', 40))); + c.parts.forEach((p, i) => { + const col = i % partCols, row = Math.floor(i / partCols); + const x = sysX + 18 + col * (partW + 14), y = sysY + 60 + row * (partH + 12); + const label = `${p.name}${p.types[0] ? ` : ${p.types[0]}` : ''}${p.multiplicity ? ` [${p.multiplicity}]` : ''}`; + sys.append(s('g', { class: 'sv-part' }, s('title', {}, label), s('rect', { x, y, width: partW, height: partH, rx: 4 }), + s('text', { x: x + partW / 2, y: y + 25, 'text-anchor': 'middle' }, clip(label, Math.floor(partW / 7.2))))); + }); + // actors and their interfaces + const linkOf = new Map(); + for (const l of c.links) { if (!linkOf.has(l.actor)) linkOf.set(l.actor, []); linkOf.get(l.actor).push(l.name); } + const lines = s('g', { class: 'sv-lines' }), acts = s('g', {}); + const place = (list, side) => list.forEach((a, i) => { + const off = (H - 2 * PAD - (list.length * ACT_H + (list.length - 1) * GAP)) / 2; + const x = side === 'left' ? PAD : W - PAD - ACT_W, y = PAD + off + i * (ACT_H + GAP); + const cy = y + ACT_H / 2, ax = side === 'left' ? x + ACT_W : x, sx = side === 'left' ? sysX : sysX + sysW; + const names = linkOf.get(a.id) || []; + lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: Math.min(Math.max(cy, sysY + 14), sysY + sysH - 14), class: names.length ? '' : 'sv-nolink' })); + if (names.length) { + // long names on two lines, broken at a word boundary of the camelCase name (operator|Interface) + const label = names.join(', '); + let parts = [label]; + if (label.length > 18) { + const cuts = [...label.matchAll(/(?<=[a-z0-9])(?=[A-Z])|(?<=[,_ -])/g)].map((m) => m.index).filter((i) => i > 2 && i < label.length - 2); + const cut = cuts.sort((a, b) => Math.abs(a - label.length / 2) - Math.abs(b - label.length / 2))[0]; + parts = cut ? [label.slice(0, cut).trim(), label.slice(cut).trim()] : [label]; + } + lines.append(s('text', { x: (ax + sx) / 2, y: cy - 8 - (parts.length - 1) * 13, 'text-anchor': 'middle', class: 'sv-ifc' }, s('title', {}, label), + parts.map((t, i) => s('tspan', { x: (ax + sx) / 2, dy: i ? 13 : 0 }, clip(t, 19))))); + } + const st = a.stereotypes[0] || 'actor'; + const g = s('g', { class: `sv-actor sv-${st}` }, s('title', {}, `${a.name}${a.types.length ? ` : ${a.types.join(', ')}` : ''}${a.doc ? `\n${a.doc}` : ''}`)); + // every actor is a box, so that the line meets it; a «user» gets a small stick figure in it + const fig = st === 'user' ? 22 : 0, tx = x + fig + (ACT_W - fig) / 2; + g.append(s('rect', { x, y, width: ACT_W, height: ACT_H, rx: st === 'environmentalEffect' ? 28 : 4 })); + if (fig) { + const fx = x + 18, fy = y + 13; + g.append(s('circle', { cx: fx, cy: fy, r: 5 }), s('path', { class: 'sv-fig-line', d: `M${fx} ${fy + 5}v15M${fx - 8} ${fy + 11}h16M${fx} ${fy + 20}l-7 12M${fx} ${fy + 20}l7 12` })); + } + g.append(s('text', { x: tx, y: y + 24, 'text-anchor': 'middle', class: 'sv-st' }, `«${st}»`), + s('text', { x: tx, y: y + 44, 'text-anchor': 'middle', class: 'sv-name' }, clip(a.name, fig ? 18 : 21))); + acts.append(g); + }); + place(left, 'left'); place(right, 'right'); + svg.append(lines, sys, acts); + if (!c.actors.length) svg.append(s('text', { x: PAD, y: PAD + 14, class: 'sv-st' }, 'no actors')); + return svg; + } + + // ---------- start ---------- + if (params.get('example') === 'drone' && ex.btn && cfg.engine) { showTab('example'); ex.btn.click(); } +} From ef07fc3a30a354690d81cdef7d141d8cd876c8c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:59:48 +0100 Subject: [PATCH 2/9] web: ports of interfaces, SYSMOD version, cover view; 256 elements per page Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- web/sysmod-viewer-api.js | 2 +- web/sysmod-viewer-core.js | 48 +++++++++++++++++++++++++++++++-------- web/sysmod-viewer.css | 2 ++ web/sysmod-viewer.js | 32 +++++++++++++++++++------- 4 files changed, 66 insertions(+), 18 deletions(-) diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js index 988c2bf..9230be7 100644 --- a/web/sysmod-viewer-api.js +++ b/web/sysmod-viewer-api.js @@ -70,7 +70,7 @@ export function usesRelay(url, relay) { try { return relay.servers.map((s) => String(s).replace(/\/+$/, '').toLowerCase()).includes(new URL(url).origin.toLowerCase()); } catch { return false; } } -export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 1000 } = {}) { +export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) const base = normalizeBaseUrl(baseUrl); if (!base) throw new ApiError('Enter the address of a SysML v2 API server.'); const t = String(token || '').trim(); diff --git a/web/sysmod-viewer-core.js b/web/sysmod-viewer-core.js index 6b94c70..10a01ea 100644 --- a/web/sysmod-viewer-core.js +++ b/web/sysmod-viewer-core.js @@ -290,18 +290,26 @@ export function readContext(M, project, def) { if (soi && (x === soi || specializes(M, soi, x))) return soi; return actors.find((a) => a === x || specializes(M, a, x)) || null; }; + // the part (soi or actor) an end connects, and the port it connects at (operator.controlPort -> operator, controlPort) const partOfEnd = (end) => { - let e = end; + let e = end, port = null; for (let i = 0; e && i < 6; i++) { const hit = match(e); - if (hit) return hit; + if (hit) return { part: hit, port }; + if (e['@type'] === 'PortUsage' && !port) port = e; const chain = M.all(e.chainingFeature); - if (chain.length) { e = chain[0]; continue; } + if (chain.length) { + const last = chain[chain.length - 1]; + if (last['@type'] === 'PortUsage') port = last; + e = chain[0]; + continue; + } const rs = M.all(e.ownedSpecialization).find((s) => s['@type'] === 'ReferenceSubsetting') || M.all(e.ownedReferenceSubsetting)[0]; const next = rs ? M.get(rs.referencedFeature ?? rs.general) : null; if (next) { e = next; continue; } // a port of the soi (or of a part that redefines it) also stands for the soi - return match(M.get(e.owningType ?? e.owner)); + const owner = match(M.get(e.owningType ?? e.owner)); + return owner ? { part: owner, port: port || (e['@type'] === 'PortUsage' ? e : null) } : null; } return null; }; @@ -310,8 +318,13 @@ export function readContext(M, project, def) { if (c['@type'] === 'BindingConnectorAsUsage' || c['@type'] === 'AllocationUsage') continue; // the owned ends: the inherited ends of the library (actorPort, systemPort) point to the generic actors and soi const ends = M.all(c.ownedEndFeature).length ? M.all(c.ownedEndFeature) : M.all(c.connectorEnd).length ? M.all(c.connectorEnd) : M.all(c.relatedFeature); - const ps = [...new Set(ends.map(partOfEnd).filter(Boolean))]; - if (ps.length === 2 && ps.includes(soi)) links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: ps.find((p) => p !== soi)['@id'] }); + const hits = ends.map(partOfEnd).filter(Boolean); + const ps = [...new Set(hits.map((x) => x.part))]; + if (ps.length === 2 && ps.includes(soi)) { + const actor = ps.find((p) => p !== soi); + const portOf = (part) => nameOf(hits.find((x) => x.part === part)?.port) || ''; + links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: actor['@id'], actorPort: portOf(actor), systemPort: portOf(soi) }); + } } // white box: the system of interest of the Impl context, its parts let soiImpl = null; @@ -321,14 +334,17 @@ export function readContext(M, project, def) { key: def.key, role: def.role, title: def.title, context: { ...brief(M, ctx), types: typeNames(M, ctx) }, impl: impl ? brief(M, impl) : null, - system: soi ? { ...brief(M, soi), types: typeNames(M, soi), stereotypes: stereotypesOf(M, soi) } : null, + system: soi ? { ...brief(M, soi), types: typeNames(M, soi), stereotypes: stereotypesOf(M, soi), ports: portsOf(M, soi) } : null, systemImpl: soiImpl ? { ...brief(M, soiImpl), types: typeNames(M, soiImpl) } : null, - actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((s) => s !== 'system') })), + actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((s) => s !== 'system'), ports: portsOf(M, a) })), links, - parts: inner.map((p) => ({ ...brief(M, p), types: typeNames(M, p), multiplicity: multiplicityOf(M, p) })), + parts: inner.map((p) => ({ ...brief(M, p), types: typeNames(M, p), multiplicity: multiplicityOf(M, p), ports: portsOf(M, p) })), }; } +/** The ports of a part (effective, without the generic ports of the SYSMOD library such as actorPorts, systemPorts) */ +const portsOf = (M, el) => featuresOf(M, el, 'PortUsage').filter((p) => !isLibrary(p) && nameOf(p)).map((p) => ({ id: p['@id'], name: nameOf(p), types: typeNames(M, p) })); + /** "1..*", "0..1", "" from the multiplicity of a feature */ export function multiplicityOf(M, f) { const m = M.get(f?.multiplicity); @@ -474,6 +490,17 @@ function readFeatureTree(M) { return null; } +/** The version of the SYSMOD library in the model: @SYSMOD { version = "5.1.4"; } on the SYSMOD package; '' if not stated */ +export function sysmodVersionOf(M) { + for (const mu of M.ofType('MetadataUsage')) { + const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; + if (!def || nameOf(def) !== 'SYSMOD' || !/^SYSMOD::/.test(def.qualifiedName || 'SYSMOD::')) continue; + const v = valueOf(M, featureNamed(M, mu, 'version')); + if (v) return v; + } + return ''; +} + /** Everything the viewer shows for one SYSMOD project. Plain data: strings, arrays, objects. */ export function readProject(M, projectId) { const project = M.get(projectId); @@ -484,7 +511,10 @@ export function readProject(M, projectId) { const owner = roleOf(M, project, 'projectOwner')[0]; const sic = byKey.SIC; const sicImpl = M.get(sic?.systemImpl?.id), sicSoi = M.get(sic?.system?.id); + const cover = featureNamed(M, project, 'projectCoverView', 'ViewUsage') || featureNamed(M, project, 'projectCover', 'ViewUsage'); const view = { + sysmodVersion: sysmodVersionOf(M), + coverView: cover ? nameOf(cover) : '', id: project['@id'], name: nameOf(project), qualifiedName: project.qualifiedName || '', diff --git a/web/sysmod-viewer.css b/web/sysmod-viewer.css index 67b6f31..85a1d3f 100644 --- a/web/sysmod-viewer.css +++ b/web/sysmod-viewer.css @@ -120,4 +120,6 @@ code { font-family: var(--font-notation); font-size: 0.9em; } .sv-actor rect { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; } .sv-actor circle, .sv-actor path { fill: none; stroke: var(--ink); stroke-width: 1.5; stroke-linecap: round; } .sv-lines line { stroke: var(--line); stroke-width: 1.5; } +.sv-port { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; } +.sv-svg .sv-portname { fill: var(--muted); font-size: 10.5px; font-family: var(--font-notation); } .sv-lines line.sv-nolink { stroke-dasharray: 4 4; opacity: 0.6; } diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js index eda94a6..2964141 100644 --- a/web/sysmod-viewer.js +++ b/web/sysmod-viewer.js @@ -317,6 +317,7 @@ async function start(cfg) { h('p', { class: 'stereo m-0' }, 'project'), h('h2', { class: 'display display-md m-0' }, v.name), v.qualifiedName ? h('p', { class: 'notation text-muted m-0' }, v.qualifiedName) : null, + v.sysmodVersion || v.coverView ? h('p', { class: 'ui text-muted m-0 sv-origin' }, [v.sysmodVersion ? `SYSMOD ${v.sysmodVersion}` : '', v.coverView ? `cover view: ${v.coverView}` : ''].filter(Boolean).join(' · ')) : null, h('p', { class: 'ui text-muted sv-origin' }, `Source: ${source?.label || ''} · ${nf.format(model.size)} elements${ms ? ` · read in ${Math.round(ms)} ms` : ''}`), v.purpose ? h('p', { class: 'sv-purpose' }, h('span', { class: 'ui font-semibold' }, 'Purpose: '), v.purpose) : null, v.owner ? h('p', { class: 'ui m-0' }, h('span', { class: 'font-semibold' }, 'Project owner: '), v.owner) : null, @@ -367,13 +368,13 @@ async function start(cfg) { function contextView(c) { const facts = h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, c.context.name, c.context.types.length ? ` : ${c.context.types[0]}` : ''), - ` · ${c.actors.length} actors · ${c.links.length} interfaces · ${c.parts.length} parts${c.systemImpl ? ' (white box)' : ''}`); + ` · ${c.actors.length} actors · ${c.links.length} interfaces · ${c.system?.ports?.length || 0} system ports · ${c.parts.length} parts${c.systemImpl ? ' (white box)' : ''}`); return [facts, h('figure', { class: 'sv-fig' }, diagram(c), h('figcaption', { class: 'sr-only' }, describe(c))), c.context.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Description'), h('div', { class: 'prose max-w-[46rem]' }, paras(c.context.doc))) : null]; } const describe = (c) => `System context ${c.context.name}: system of interest ${c.system?.name || 'missing'}` + `${c.parts.length ? ` with the parts ${c.parts.map((p) => p.name).join(', ')}` : ''}; actors ${c.actors.map((a) => `${a.name}${a.stereotypes.length ? ` (${a.stereotypes.join(', ')})` : ''}`).join(', ') || 'none'}` - + `${c.links.length ? `; interfaces ${c.links.map((l) => l.name).join(', ')}` : ''}.`; + + `${c.links.length ? `; interfaces ${c.links.map((l) => `${l.name || 'interface'}${l.actorPort || l.systemPort ? ` (${l.actorPort || '?'} to ${l.systemPort || '?'})` : ''}`).join(', ')}` : ''}.`; const clip = (text, n) => (text.length > n ? `${text.slice(0, n - 1)}…` : text); function diagram(c) { @@ -403,15 +404,30 @@ async function start(cfg) { }); // actors and their interfaces const linkOf = new Map(); - for (const l of c.links) { if (!linkOf.has(l.actor)) linkOf.set(l.actor, []); linkOf.get(l.actor).push(l.name); } - const lines = s('g', { class: 'sv-lines' }), acts = s('g', {}); + for (const l of c.links) { if (!linkOf.has(l.actor)) linkOf.set(l.actor, []); linkOf.get(l.actor).push(l); } + const lines = s('g', { class: 'sv-lines' }), acts = s('g', {}), portsG = s('g', {}); const place = (list, side) => list.forEach((a, i) => { const off = (H - 2 * PAD - (list.length * ACT_H + (list.length - 1) * GAP)) / 2; const x = side === 'left' ? PAD : W - PAD - ACT_W, y = PAD + off + i * (ACT_H + GAP); const cy = y + ACT_H / 2, ax = side === 'left' ? x + ACT_W : x, sx = side === 'left' ? sysX : sysX + sysW; - const names = linkOf.get(a.id) || []; - lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: Math.min(Math.max(cy, sysY + 14), sysY + sysH - 14), class: names.length ? '' : 'sv-nolink' })); - if (names.length) { + const ls = linkOf.get(a.id) || []; + const names = ls.map((l) => l.name || 'interface'); + const sy = Math.min(Math.max(cy, sysY + 14), sysY + sysH - 14); + lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: sy, class: ls.length ? '' : 'sv-nolink' })); + if (ls.length) { + // the ports the interface connects: small squares on the borders, their names below the line + const ap = [...new Set(ls.map((l) => l.actorPort).filter(Boolean))].join(', '), sp = [...new Set(ls.map((l) => l.systemPort).filter(Boolean))].join(', '); + if (ap) portsG.append(s('rect', { x: ax - 4, y: cy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, `${a.name}.${ap}`))); + if (sp) portsG.append(s('rect', { x: sx - 4, y: sy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, `${c.system?.name || 'system'}.${sp}`))); + if (ap || sp) { + // two lines, left port above the right one, so that long names fit into the lane between the boxes + const [l, r] = side === 'left' ? [ap || '·', sp || '·'] : [sp || '·', ap || '·']; + const mx = (ax + sx) / 2, my = (cy + sy) / 2 + 15; + lines.append(s('text', { x: mx, y: my, 'text-anchor': 'middle', class: 'sv-portname' }, s('title', {}, `ports: ${l} ↔ ${r}`), + s('tspan', { x: mx, dy: 0 }, `${clip(l, 19)} ↔`), s('tspan', { x: mx, dy: 12 }, clip(r, 19)))); + } + } + if (ls.length) { // long names on two lines, broken at a word boundary of the camelCase name (operator|Interface) const label = names.join(', '); let parts = [label]; @@ -437,7 +453,7 @@ async function start(cfg) { acts.append(g); }); place(left, 'left'); place(right, 'right'); - svg.append(lines, sys, acts); + svg.append(lines, sys, acts, portsG); if (!c.actors.length) svg.append(s('text', { x: PAD, y: PAD + 14, class: 'sv-st' }, 'no actors')); return svg; } From 1e7cfd95e01788d6971276aaa81b19ddb6555da7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:00:23 +0100 Subject: [PATCH 3/9] web/serve.py: honour ALLOWED_SYSML_SERVER_ORIGINS like the Flask server; README Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- README.md | 6 +++--- tests/test_web_serve.py | 11 +++++++++++ web/serve.py | 17 ++++++++++++++++- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f2586a6..5761375 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,9 @@ The SYSMOD Viewer as **one web page**: it reads the model with the SysML v2 API python web/serve.py # then open http://localhost:8080/ ``` -`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to any SysML v2 API server: a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. +`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to any SysML v2 API server (or only to those in `ALLOWED_SYSML_SERVER_ORIGINS`, if set, as for the Flask server): a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. -What it shows: the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram (actors, interfaces, white box parts) of all six contexts, from the brownfield to the product architecture. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened. +What it shows: the project cover (purpose, owner, description, the SYSMOD version from `@SYSMOD { version = … }`, the cover view), the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram of all six contexts, from the brownfield to the product architecture: actors, the system of interest with its white box parts, and the interfaces with the ports they connect. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened. | File | What | |---|---| @@ -61,7 +61,7 @@ What it shows: the SYSMOD Atlas, completeness checks, problem statement, system The same JavaScript runs on [mbse4u.com/tools/sysmod-viewer](https://mbse4u.com/tools/sysmod-viewer/), which in addition opens the Delivery Drone example and `.sysml` files with a SysML v2 engine in the browser, and reaches servers without CORS through a relay with an allowlist. Changes to the viewer belong here; the site copies them. -Read-only. Editing the problem statement, AI suggestions, the creation wizard and the feature binding matrix are in the Flask server (below). Tests of `serve.py`: `python -m unittest tests/test_web_serve.py`. +Read-only. Editing the problem statement, AI suggestions and the creation wizard are in the Flask server (below). Tests of `serve.py`: `python -m pytest tests/test_web_serve.py` (part of `python -m pytest`, no extra packages). The viewer's JavaScript is tested on mbse4u.com with the Delivery Drone model and `tests/test_sysmod.sysml` of this repository. --- diff --git a/tests/test_web_serve.py b/tests/test_web_serve.py index d2e4d66..29492ad 100644 --- a/tests/test_web_serve.py +++ b/tests/test_web_serve.py @@ -68,6 +68,17 @@ def test_allowed(self): self.ok("https://h.org/projects/p/branches/b") self.ok("https://H.org/projects", "https://h.org/projects") + def test_allowed_origins(self): + import os + os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = "http://localhost:9000, https://h.org/" + try: + self.ok("http://localhost:9000/projects") + self.ok("https://h.org/projects") + self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + self.refused("http://localhost:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + finally: + del os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] + def test_refused(self): self.refused("", "invalid address") self.refused("file:///etc/passwd", "only http and https") diff --git a/web/serve.py b/web/serve.py index b02b1cf..64f25a2 100644 --- a/web/serve.py +++ b/web/serve.py @@ -17,10 +17,13 @@ .../commits/{id}/elements[/{id}], optionally behind a path prefix such as /api/v1) and only the paging query page[size], page[after], page[before]; http and https; no redirects followed; JSON only; - the token (header X-Relay-Authorization) is passed on as Authorization and never stored or logged. + - ALLOWED_SYSML_SERVER_ORIGINS (as for the Flask server, comma-separated origins such as http://localhost:9000): + if set, only these servers; if not set, any server (the relay listens on localhost only). The same rules as relay.php of mbse4u.com/tools/sysmod-viewer/, which in addition has an allowlist of servers. """ import argparse import json +import os import re import sys import urllib.error @@ -41,6 +44,14 @@ CONFIG = {"relay": {"url": "relay", "servers": ["*"], "label": "the local relay (serve.py)"}} +def allowed_origins(): + """ALLOWED_SYSML_SERVER_ORIGINS as a set of origins, or None (any server).""" + raw = os.environ.get("ALLOWED_SYSML_SERVER_ORIGINS", "").strip() + if not raw: + return None + return {o.strip().rstrip("/").lower() for o in raw.split(",") if o.strip()} + + def check_url(url: str): """The address to request, or (None, reason). Same rules as relay.php, without the allowlist.""" if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): @@ -70,7 +81,11 @@ def check_url(url: str): return None, "query not allowed" seen.add(k) query.append(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="")) - netloc = p.hostname.lower() + (f":{p.port}" if p.port else "") + host = p.hostname.lower() + netloc = (f"[{host}]" if ":" in host else host) + (f":{p.port}" if p.port else "") + allowed = allowed_origins() + if allowed is not None and f"{p.scheme.lower()}://{netloc}" not in allowed: + return None, "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)" return urllib.parse.urlunsplit((p.scheme.lower(), netloc, path, "&".join(query), "")), "" From 2f73c6bb8e970aeb4002379607700143a3aef5d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:13:54 +0100 Subject: [PATCH 4/9] web: relay only to ALLOWED_SYSML_SERVER_ORIGINS; no end-anchored regexes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code scanning: serve.py relayed to any server when ALLOWED_SYSML_SERVER_ORIGINS was not set (server-side request forgery). Now it always uses the allowlist, with the default of the Flask server (http://localhost:9000 …), and the server part of the outgoing request is taken from the allowlist entry, never from the address the page sent. viewer-config.json lists the allowed servers. The JavaScript no longer uses regular expressions anchored at the end of remote text (/\/+$/, /\*+\/\s*$/, /\s*\n\s*/), which can run in quadratic time on long input; replaced by linear helpers with the same results. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- README.md | 5 ++++- tests/test_web_serve.py | 34 ++++++++++++++++++++++++---------- web/index.html | 4 ++-- web/serve.py | 39 +++++++++++++++++++++++---------------- web/sysmod-viewer-api.js | 11 ++++++++--- web/sysmod-viewer-core.js | 9 ++++++++- web/sysmod-viewer.js | 2 +- 7 files changed, 70 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 5761375..c6ddc8f 100644 --- a/README.md +++ b/README.md @@ -45,9 +45,12 @@ The SYSMOD Viewer as **one web page**: it reads the model with the SysML v2 API ```bash python web/serve.py # then open http://localhost:8080/ + +# other SysML v2 servers: name them, as for the Flask server +ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://sysml2.intercax.com:9000 python web/serve.py ``` -`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to any SysML v2 API server (or only to those in `ALLOWED_SYSML_SERVER_ORIGINS`, if set, as for the Flask server): a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. +`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to the SysML v2 API servers in `ALLOWED_SYSML_SERVER_ORIGINS` (as for the Flask server; default `http://localhost:9000`): a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every allowed server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. What it shows: the project cover (purpose, owner, description, the SYSMOD version from `@SYSMOD { version = … }`, the cover view), the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram of all six contexts, from the brownfield to the product architecture: actors, the system of interest with its white box parts, and the interfaces with the ports they connect. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened. diff --git a/tests/test_web_serve.py b/tests/test_web_serve.py index 29492ad..3fa178a 100644 --- a/tests/test_web_serve.py +++ b/tests/test_web_serve.py @@ -50,7 +50,17 @@ def start(handler): return srv +ALLOWED = "https://h.org,http://sysml2.intercax.com:9000" + + class Rules(unittest.TestCase): + def setUp(self): + import os + os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = ALLOWED + + def tearDown(self): + import os + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) def ok(self, url, expected=None): target, error = serve.check_url(url) self.assertEqual(error, "", url) @@ -70,18 +80,17 @@ def test_allowed(self): def test_allowed_origins(self): import os - os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = "http://localhost:9000, https://h.org/" - try: - self.ok("http://localhost:9000/projects") - self.ok("https://h.org/projects") - self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") - self.refused("http://localhost:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") - finally: - del os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] + self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + self.refused("http://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + self.refused("http://sysml2.intercax.com:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS") + self.ok("http://localhost:9000/projects") # the default, as for the Flask server + self.refused("https://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") def test_refused(self): self.refused("", "invalid address") self.refused("file:///etc/passwd", "only http and https") + self.refused("https://h.org@evil.org/projects", "invalid address") self.refused("https://u:p@h.org/projects", "invalid address") self.refused("https://h.org/projects#x", "invalid address") self.refused("https://h.org/admin", "not a read endpoint of the SysML v2 API") @@ -97,13 +106,17 @@ def test_refused(self): class Relay(unittest.TestCase): @classmethod def setUpClass(cls): + import os cls.up = start(FakeSysml) + os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = f"http://127.0.0.1:{cls.up.server_address[1]}" cls.viewer = start(serve.Handler) cls.U = f"http://127.0.0.1:{cls.up.server_address[1]}" cls.R = f"http://127.0.0.1:{cls.viewer.server_address[1]}" @classmethod def tearDownClass(cls): + import os + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) cls.up.shutdown(); cls.viewer.shutdown() def get(self, path, headers=None): @@ -122,7 +135,7 @@ def test_page_and_config(self): self.assertEqual(status, 200) self.assertIn(b'id="sysmod-viewer"', body) status, _, body = self.get("/viewer-config.json") - self.assertEqual(json.loads(body)["relay"]["servers"], ["*"]) + self.assertEqual(json.loads(body)["relay"]["servers"], [self.U]) self.assertEqual(self.get("/serve.py")[0], 404) def test_relayed_with_token_and_paging(self): @@ -139,7 +152,8 @@ def test_errors(self): self.assertEqual(self.relay(self.U + "/projects/redirect")[0], 502) self.assertIn(b"did not answer with JSON", self.relay(self.U + "/projects/html")[2]) self.assertEqual(self.relay(self.U + "/admin")[0], 400) - self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 502) + self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 400) # not on the list + self.assertEqual(self.relay("https://example.org/projects")[0], 400) self.assertEqual(self.relay(self.U + "/projects", {"Sec-Fetch-Site": "cross-site"})[0], 403) status, headers, _ = self.relay(self.U + "/admin") self.assertEqual(headers["X-Relay-Error"], "1") diff --git a/web/index.html b/web/index.html index ff2d245..01bed56 100644 --- a/web/index.html +++ b/web/index.html @@ -85,7 +85,7 @@

Open a model

Good to know

  • Run it: python web/serve.py, then open http://localhost:8080/. The script needs only Python 3, no packages. Browsers do not run the page from a file:// address.
  • -
  • CORS and http: a page can only read servers that allow requests from it. serve.py also relays the requests (read-only) to any SysML v2 server, so with it every server works, including plain http:// ones.
  • +
  • CORS and http: a page can only read servers that allow requests from it. serve.py also relays the requests (read-only) to the servers in ALLOWED_SYSML_SERVER_ORIGINS (default http://localhost:9000), including plain http:// ones and servers without CORS.
  • Token: optional, passed on as header Authorization; it stays in the page and is never stored. The page address records server, project and commit (not the token).
  • SYSMOD v5: the project is an occurrence def with #project or a specialization of SYSMOD::Project; the SYSMOD library must be in the same project.
  • Read-only. Editing, the AI suggestions and the creation wizard are in the Flask server of this repository (sysmod_api_server.py).
  • @@ -100,7 +100,7 @@

    Good to know

    if (r.ok) { const extra = await r.json(); root.dataset.config = JSON.stringify({ ...JSON.parse(root.dataset.config), ...extra }); - if (extra.relay) document.querySelector('[data-relay-note]').append(' Running with serve.py: every server is reached through its relay.'); + if (extra.relay) document.querySelector('[data-relay-note]').append(` Running with serve.py: these servers are reached through its relay: ${extra.relay.servers.join(', ')} (ALLOWED_SYSML_SERVER_ORIGINS).`); } } catch { /* served without serve.py: no relay */ } await import('./sysmod-viewer.js'); diff --git a/web/serve.py b/web/serve.py index 64f25a2..822f53f 100644 --- a/web/serve.py +++ b/web/serve.py @@ -8,8 +8,10 @@ Only the Python standard library, no packages. Why a relay: a web page may only read servers that allow requests from it (CORS), and a page may not call -plain-http servers from https. The relay asks the server on behalf of the page, so every SysML v2 API server works, -also e.g. http://sysml2.intercax.com:9000 or a server without CORS such as Flexo. +plain-http servers from https. The relay asks the server on behalf of the page, so every allowed SysML v2 API server +works, also e.g. http://sysml2.intercax.com:9000 or a server without CORS such as Flexo: + + ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://sysml2.intercax.com:9000 python web/serve.py The relay is narrow: - it listens on localhost only (unless --host says otherwise); @@ -17,8 +19,8 @@ .../commits/{id}/elements[/{id}], optionally behind a path prefix such as /api/v1) and only the paging query page[size], page[after], page[before]; http and https; no redirects followed; JSON only; - the token (header X-Relay-Authorization) is passed on as Authorization and never stored or logged. - - ALLOWED_SYSML_SERVER_ORIGINS (as for the Flask server, comma-separated origins such as http://localhost:9000): - if set, only these servers; if not set, any server (the relay listens on localhost only). + - only the servers in ALLOWED_SYSML_SERVER_ORIGINS (comma-separated origins, as for the Flask server; default + http://localhost:9000, http://127.0.0.1:9000, http://[::1]:9000); The same rules as relay.php of mbse4u.com/tools/sysmod-viewer/, which in addition has an allowlist of servers. """ import argparse @@ -41,19 +43,22 @@ r"^(/[A-Za-z0-9._~-]{1,60}){0,3}?/projects(/" + SEGMENT + r"(/branches(/" + SEGMENT + r")?|/commits(/" + SEGMENT + r"(/elements(/" + SEGMENT + r")?)?)?)?)?$" ) -CONFIG = {"relay": {"url": "relay", "servers": ["*"], "label": "the local relay (serve.py)"}} +DEFAULT_ORIGINS = "http://localhost:9000,http://127.0.0.1:9000,http://[::1]:9000" # as sysmod_api_server.py def allowed_origins(): - """ALLOWED_SYSML_SERVER_ORIGINS as a set of origins, or None (any server).""" - raw = os.environ.get("ALLOWED_SYSML_SERVER_ORIGINS", "").strip() - if not raw: - return None - return {o.strip().rstrip("/").lower() for o in raw.split(",") if o.strip()} + """The servers the relay may ask: ALLOWED_SYSML_SERVER_ORIGINS, as for the Flask server.""" + raw = os.environ.get("ALLOWED_SYSML_SERVER_ORIGINS", DEFAULT_ORIGINS) + return [o.strip().rstrip("/").lower() for o in raw.split(",") if o.strip()] + + +def viewer_config(): + return {"relay": {"url": "relay", "servers": allowed_origins(), "label": "the local relay (serve.py)", + "contact": "the variable ALLOWED_SYSML_SERVER_ORIGINS of serve.py"}} def check_url(url: str): - """The address to request, or (None, reason). Same rules as relay.php, without the allowlist.""" + """The address to request, or (None, reason). Same rules as relay.php of mbse4u.com.""" if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): return None, "invalid address" p = urllib.parse.urlsplit(url) @@ -82,11 +87,12 @@ def check_url(url: str): seen.add(k) query.append(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="")) host = p.hostname.lower() - netloc = (f"[{host}]" if ":" in host else host) + (f":{p.port}" if p.port else "") - allowed = allowed_origins() - if allowed is not None and f"{p.scheme.lower()}://{netloc}" not in allowed: + origin = f"{p.scheme.lower()}://" + (f"[{host}]" if ":" in host else host) + (f":{p.port}" if p.port else "") + # the server part of the request is taken from the allowlist, never from the address the page sent + base = next((allowed for allowed in allowed_origins() if allowed == origin), None) + if base is None: return None, "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)" - return urllib.parse.urlunsplit((p.scheme.lower(), netloc, path, "&".join(query), "")), "" + return base + path + ("?" + "&".join(query) if query else ""), "" class NoRedirect(urllib.request.HTTPRedirectHandler): @@ -124,7 +130,7 @@ def fail(self, status, message): def do_GET(self): path = urllib.parse.urlsplit(self.path).path if path == "/viewer-config.json": - return self.answer(200, json.dumps(CONFIG).encode()) + return self.answer(200, json.dumps(viewer_config()).encode()) if path == "/relay": return self.relay() if path.endswith(".py"): @@ -176,6 +182,7 @@ def main(): a = ap.parse_args() server = ThreadingHTTPServer((a.host, a.port), Handler) print(f"SYSMOD viewer: http://localhost:{a.port}/ (Ctrl+C to stop)") + print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: server.serve_forever() except KeyboardInterrupt: diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js index 9230be7..0d26f58 100644 --- a/web/sysmod-viewer-api.js +++ b/web/sysmod-viewer-api.js @@ -30,6 +30,9 @@ export class ApiError extends Error { } } +/** Removes trailing slashes, in linear time (no regular expression anchored at the end). */ +const trimSlashes = (s) => { let e = s.length; while (e > 0 && s[e - 1] === '/') e--; return s.slice(0, e); }; + /** Normalizes what a user pastes: no trailing slash, no /projects…, scheme added if missing. */ export function normalizeBaseUrl(input) { let s = String(input || '').trim(); @@ -38,8 +41,10 @@ export function normalizeBaseUrl(input) { const u = new URL(s); if (!/^https?:$/.test(u.protocol)) throw new ApiError('The address must start with https:// (or http:// for a server on this computer).'); u.hash = ''; u.search = ''; - u.pathname = u.pathname.replace(/\/projects(\/.*)?$/, '').replace(/\/+$/, ''); - return u.href.replace(/\/+$/, ''); + const i = u.pathname.indexOf('/projects'); + const p = i >= 0 && (u.pathname.length === i + 9 || u.pathname[i + 9] === '/') ? u.pathname.slice(0, i) : u.pathname; + u.pathname = trimSlashes(p); + return trimSlashes(u.href); } const isLocal = (u) => ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname); @@ -67,7 +72,7 @@ export function nextFromLink(header) { export function usesRelay(url, relay) { if (!relay?.url || !Array.isArray(relay.servers)) return false; if (relay.servers.includes('*')) return true; - try { return relay.servers.map((s) => String(s).replace(/\/+$/, '').toLowerCase()).includes(new URL(url).origin.toLowerCase()); } catch { return false; } + try { return relay.servers.map((s) => trimSlashes(String(s)).toLowerCase()).includes(new URL(url).origin.toLowerCase()); } catch { return false; } } export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) diff --git a/web/sysmod-viewer-core.js b/web/sysmod-viewer-core.js index 10a01ea..6ce8e3f 100644 --- a/web/sysmod-viewer-core.js +++ b/web/sysmod-viewer-core.js @@ -130,7 +130,14 @@ export function definitionsOf(M, el) { /** Removes the comment layout that some servers keep in the body (leading asterisks of continued lines). */ export function cleanDoc(body) { if (typeof body !== 'string') return ''; - return body.replace(/^\s*\/\*+|\*+\/\s*$/g, '').split('\n').map((l) => l.replace(/^\s*\*\s?/, '').trim()).join('\n').replace(/\n{3,}/g, '\n\n').trim(); + // without regular expressions anchored at the end (linear time also for long texts) + let t = body.trim(); + if (t.startsWith('/*')) { let i = 1; while (i < t.length && t[i] === '*') i++; t = t.slice(i); } + if (t.endsWith('*/')) { let e = t.length - 1; while (e > 0 && t[e - 1] === '*') e--; t = t.slice(0, e); } + const lines = t.split('\n').map((l) => { const s = l.trimStart(); return (s.startsWith('*') ? s.slice(1) : s).trim(); }); + const out = []; + for (const l of lines) if (l || (out.length && out[out.length - 1] !== '')) out.push(l); // at most one blank line + return out.join('\n').trim(); } /** diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js index 2964141..974b706 100644 --- a/web/sysmod-viewer.js +++ b/web/sysmod-viewer.js @@ -36,7 +36,7 @@ async function start(cfg) { return e; }; /** Doc text as paragraphs: blank lines separate paragraphs, single line breaks are the line breaks of the source. */ - const paras = (text, cls = '') => String(text || '').split(/\n{2,}/).map((p) => p.replace(/\s*\n\s*/g, ' ').trim()).filter(Boolean).map((p) => h('p', { class: cls }, p)); + const paras = (text, cls = '') => String(text || '').split(/\n{2,}/).map((p) => p.split('\n').map((l) => l.trim()).filter(Boolean).join(' ')).filter(Boolean).map((p) => h('p', { class: cls }, p)); const nf = new Intl.NumberFormat('en'); const status = (el, text, kind = '') => { el.textContent = text; el.dataset.kind = kind; }; From d0e6db0c79e65f4e9457ced396de6745f77f493a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:29:57 +0100 Subject: [PATCH 5/9] web: SonarCloud findings of PR #10 (reliability, security, maintainability) Reliability: no single-line if followed by another statement; sort() no longer inside expressions (toSorted, or a separate statement); the promise of start() is handled (errors are shown on the page). Security: no regular expressions with backtracking on remote text; the path check of serve.py works segment by segment instead of a nested-quantifier regex; no http literal in the start message. Maintainability: every function below cognitive complexity 15 (exprText as a table of expression kinds, readContext split into contextLinks, partOfEnd, stepOf, matchRole; the API client's get() into request, answerError, readJson; the interface's render() into one function per section, the diagram into layout, systemBox, actorBox, drawLink, placeActors; serve.py's check_url and relay into small functions); no nested ternaries or nested template literals; fetchBytes and the engine loader at module level; duplicate CSS selectors merged. Behaviour unchanged: 92 checks of mbse4u.com (Delivery Drone model and tests/test_sysmod.sysml), tests/test_web_serve.py, and the pages in a browser (server with and without CORS, relay, token, JSON and .sysml files). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- web/serve.py | 163 ++++--- web/sysmod-viewer-api.js | 196 ++++++--- web/sysmod-viewer-core.js | 340 +++++++++------ web/sysmod-viewer.css | 4 +- web/sysmod-viewer.js | 863 +++++++++++++++++++++++--------------- 5 files changed, 997 insertions(+), 569 deletions(-) diff --git a/web/serve.py b/web/serve.py index 822f53f..9a27fb2 100644 --- a/web/serve.py +++ b/web/serve.py @@ -38,11 +38,31 @@ TIMEOUT = 60 MAX_BYTES = 64 * 1024 * 1024 QUERY_KEYS = ("page[size]", "page[after]", "page[before]") -SEGMENT = r"[A-Za-z0-9._~%-]{1,200}" -READ_PATH = re.compile( - r"^(/[A-Za-z0-9._~-]{1,60}){0,3}?/projects(/" + SEGMENT + r"(/branches(/" + SEGMENT + r")?|/commits(/" + SEGMENT - + r"(/elements(/" + SEGMENT + r")?)?)?)?)?$" -) +SEGMENT_CHARS = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._~%-") +PREFIX_CHARS = SEGMENT_CHARS - {"%"} +# what may follow /projects: {id}, {id}/branches[/{id}], {id}/commits[/{id}[/elements[/{id}]]] +READ_ENDPOINTS = {(), ("*",), ("*", "branches"), ("*", "branches", "*"), ("*", "commits"), ("*", "commits", "*"), + ("*", "commits", "*", "elements"), ("*", "commits", "*", "elements", "*")} + + +def _is_segment(seg: str, chars=SEGMENT_CHARS, longest=200) -> bool: + return 0 < len(seg) <= longest and set(seg) <= chars + + +def _is_read_path(path: str) -> bool: + """/projects…: a read endpoint of the SysML v2 API, optionally behind up to three prefix segments (e.g. /api/v1).""" + segments = path.split("/")[1:] if path.startswith("/") else [] + if "projects" not in segments: + return False + i = segments.index("projects") + if i > 3 or not all(_is_segment(x, PREFIX_CHARS, 60) for x in segments[:i]): + return False + rest = segments[i + 1:] + shape = tuple("*" if k % 2 == 0 else x for k, x in enumerate(rest)) + ids_ok = all(_is_segment(x) for x in rest[0::2]) + return shape in READ_ENDPOINTS and ids_ok + + DEFAULT_ORIGINS = "http://localhost:9000,http://127.0.0.1:9000,http://[::1]:9000" # as sysmod_api_server.py @@ -57,42 +77,64 @@ def viewer_config(): "contact": "the variable ALLOWED_SYSML_SERVER_ORIGINS of serve.py"}} -def check_url(url: str): - """The address to request, or (None, reason). Same rules as relay.php of mbse4u.com.""" - if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): - return None, "invalid address" - p = urllib.parse.urlsplit(url) +def _check_form(p): + """The parts of the address: scheme, host, no user info or fragment. '' if fine, else the reason.""" if p.scheme.lower() not in ("http", "https") or not p.hostname: - return None, "only http and https" + return "only http and https" if p.username or p.password or p.fragment: - return None, "invalid address" - path = p.path or "" + return "invalid address" + return "" + + +def _check_path(path: str): + """A read endpoint of the SysML v2 API, without traversal. '' if fine, else the reason.""" if "//" in path: - return None, "invalid path" + return "invalid path" for segment in path.split("/"): d = urllib.parse.unquote(segment) if d in (".", "..") or any(c in d for c in "/\\\0"): - return None, "invalid path" - if not READ_PATH.match(path): - return None, "not a read endpoint of the SysML v2 API" - query = [] - seen = set() - for pair in filter(None, (p.query or "").split("&")): + return "invalid path" + if not _is_read_path(path): + return "not a read endpoint of the SysML v2 API" + return "" + + +def _paging_query(query: str): + """The paging parameters, each once, re-encoded; None if anything else is in the query.""" + pairs = {} + for pair in filter(None, (query or "").split("&")): k, _, v = pair.partition("=") k, v = urllib.parse.unquote(k), urllib.parse.unquote(v) - if k not in QUERY_KEYS or k in seen or len(v) > 200 or re.search(r"[\x00-\x1f\x7f]", v): - return None, "query not allowed" - if k == "page[size]" and not re.fullmatch(r"\d{1,5}", v): - return None, "query not allowed" - seen.add(k) - query.append(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="")) + valid = k in QUERY_KEYS and k not in pairs and len(v) <= 200 and not re.search(r"[\x00-\x1f\x7f]", v) + if not valid or (k == "page[size]" and not re.fullmatch(r"\d{1,5}", v)): + return None + pairs[k] = v + return "&".join(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="") for k, v in pairs.items()) + + +def _allowed_base(p): + """The entry of ALLOWED_SYSML_SERVER_ORIGINS for the server of the address, or None.""" host = p.hostname.lower() origin = f"{p.scheme.lower()}://" + (f"[{host}]" if ":" in host else host) + (f":{p.port}" if p.port else "") + return next((allowed for allowed in allowed_origins() if allowed == origin), None) + + +def check_url(url: str): + """The address to request, or (None, reason). Same rules as relay.php of mbse4u.com.""" + if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): + return None, "invalid address" + p = urllib.parse.urlsplit(url) + reason = _check_form(p) or _check_path(p.path or "") + if reason: + return None, reason + query = _paging_query(p.query) + if query is None: + return None, "query not allowed" # the server part of the request is taken from the allowlist, never from the address the page sent - base = next((allowed for allowed in allowed_origins() if allowed == origin), None) + base = _allowed_base(p) if base is None: return None, "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)" - return base + path + ("?" + "&".join(query) if query else ""), "" + return base + (p.path or "") + ("?" + query if query else ""), "" class NoRedirect(urllib.request.HTTPRedirectHandler): @@ -148,31 +190,51 @@ def relay(self): target, error = check_url((params.get("url") or [""])[0]) if not target: return self.fail(400, error) - headers = {"Accept": "application/json", "User-Agent": "SYSMOD-viewer-relay/1"} - auth = self.headers.get("X-Relay-Authorization") or self.headers.get("Authorization") - if auth and len(auth) < 8192 and "\r" not in auth and "\n" not in auth: - headers["Authorization"] = auth - try: - with OPENER.open(urllib.request.Request(target, headers=headers), timeout=TIMEOUT) as r: - status, body, rh = r.status, r.read(MAX_BYTES + 1), r.headers - except urllib.error.HTTPError as e: - if 300 <= e.code < 400: - return self.fail(502, "the server answered with a redirect, which the relay does not follow") - status, body, rh = e.code, e.read(MAX_BYTES + 1), e.headers - except (urllib.error.URLError, TimeoutError, OSError) as e: - timeout = "timed out" in str(e).lower() - return self.fail(504 if timeout else 502, "the server did not answer in time" if timeout else "the server could not be reached") - if len(body) > MAX_BYTES: - return self.fail(502, "the answer of the server is too large for the relay") try: - json.loads(body or b"null") - except ValueError: - body = json.dumps({"error": "the server did not answer with JSON", "status": status}).encode() + status, body, headers = fetch(target, self.headers.get("X-Relay-Authorization") or self.headers.get("Authorization")) + except RelayError as e: + return self.fail(e.status, str(e)) extra = {} - link = rh.get("Link") + link = headers.get("Link") if link and "\r" not in link and "\n" not in link: extra["Link"] = link # unchanged: the viewer resolves the next page against the server's address - self.answer(status, body, extra) + self.answer(status, json_or_error(body, status), extra) + + +class RelayError(Exception): + def __init__(self, status, message): + super().__init__(message) + self.status = status + + +def fetch(target, auth): + """GET of the target, without following redirects. (status, body, headers); RelayError if the relay cannot answer.""" + headers = {"Accept": "application/json", "User-Agent": "SYSMOD-viewer-relay/1"} + if auth and len(auth) < 8192 and "\r" not in auth and "\n" not in auth: + headers["Authorization"] = auth + try: + with OPENER.open(urllib.request.Request(target, headers=headers), timeout=TIMEOUT) as r: + status, body, rh = r.status, r.read(MAX_BYTES + 1), r.headers + except urllib.error.HTTPError as e: + if 300 <= e.code < 400: + raise RelayError(502, "the server answered with a redirect, which the relay does not follow") from None + status, body, rh = e.code, e.read(MAX_BYTES + 1), e.headers + except (urllib.error.URLError, TimeoutError, OSError) as e: + if "timed out" in str(e).lower(): + raise RelayError(504, "the server did not answer in time") from None + raise RelayError(502, "the server could not be reached") from None + if len(body) > MAX_BYTES: + raise RelayError(502, "the answer of the server is too large for the relay") + return status, body, rh + + +def json_or_error(body: bytes, status: int) -> bytes: + """The body if it is JSON, else a JSON error (an HTML error page of the server is not passed on).""" + try: + json.loads(body or b"null") + return body + except ValueError: + return json.dumps({"error": "the server did not answer with JSON", "status": status}).encode() def main(): @@ -181,7 +243,8 @@ def main(): ap.add_argument("--host", default="127.0.0.1", help="default 127.0.0.1: only this computer can use the relay") a = ap.parse_args() server = ThreadingHTTPServer((a.host, a.port), Handler) - print(f"SYSMOD viewer: http://localhost:{a.port}/ (Ctrl+C to stop)") + page = urllib.parse.urlunsplit(("http", f"localhost:{a.port}", "/", "", "")) # local only: the server listens on 127.0.0.1 + print(f"SYSMOD viewer: {page} (Ctrl+C to stop)") print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: server.serve_forever() diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js index 0d26f58..a9f36eb 100644 --- a/web/sysmod-viewer-api.js +++ b/web/sysmod-viewer-api.js @@ -31,127 +31,199 @@ export class ApiError extends Error { } /** Removes trailing slashes, in linear time (no regular expression anchored at the end). */ -const trimSlashes = (s) => { let e = s.length; while (e > 0 && s[e - 1] === '/') e--; return s.slice(0, e); }; +function trimSlashes(s) { + let e = s.length; + while (e > 0 && s[e - 1] === '/') e--; + return s.slice(0, e); +} + +const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]']; +const isLocal = (u) => LOCAL_HOSTS.includes(u.hostname); +const hasScheme = (s) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s); +const startsWithLocalHost = (s) => LOCAL_HOSTS.some((h) => s.toLowerCase().startsWith(h) && [undefined, ':', '/'].includes(s[h.length])); + +/** The base path of the API: the path in front of /projects (a pasted address may contain /projects/…). */ +function basePath(pathname) { + const i = pathname.indexOf('/projects'); + const end = i + '/projects'.length; + const isSegment = i >= 0 && (pathname.length === end || pathname[end] === '/'); + return trimSlashes(isSegment ? pathname.slice(0, i) : pathname); +} /** Normalizes what a user pastes: no trailing slash, no /projects…, scheme added if missing. */ export function normalizeBaseUrl(input) { let s = String(input || '').trim(); if (!s) return ''; - if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = (/^(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(s) ? 'http://' : 'https://') + s; + if (!hasScheme(s)) { + const scheme = startsWithLocalHost(s) ? 'http://' : 'https://'; + s = scheme + s; + } const u = new URL(s); - if (!/^https?:$/.test(u.protocol)) throw new ApiError('The address must start with https:// (or http:// for a server on this computer).'); - u.hash = ''; u.search = ''; - const i = u.pathname.indexOf('/projects'); - const p = i >= 0 && (u.pathname.length === i + 9 || u.pathname[i + 9] === '/') ? u.pathname.slice(0, i) : u.pathname; - u.pathname = trimSlashes(p); + if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new ApiError('The address must start with https:// (or http:// for a server on this computer).'); + u.hash = ''; + u.search = ''; + u.pathname = basePath(u.pathname); return trimSlashes(u.href); } -const isLocal = (u) => ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname); +const LOCAL_RELAY = 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'; +const relayOffer = (contact, problem) => (contact ? 'If the server ' + problem + ', it can be added to the relay of this page: write to ' + contact + '.' : LOCAL_RELAY); /** A reason why the browser will not even send the request (mixed content), or '' */ export function blockedReason(baseUrl, pageProtocol = globalThis.location?.protocol, contact = '') { const u = new URL(baseUrl); - if (pageProtocol === 'https:' && u.protocol === 'http:' && !isLocal(u)) - return 'This page is loaded over HTTPS, so your browser does not allow it to call a server over plain HTTP. Use the https:// address of the server. A server on your own computer (http://localhost) is the exception. ' - + (contact ? `If the server has no https address, it can be added to the relay of this page: write to ${contact}.` : 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'); - return ''; + if (pageProtocol !== 'https:' || u.protocol !== 'http:' || isLocal(u)) return ''; + return 'This page is loaded over HTTPS, so your browser does not allow it to call a server over plain HTTP. Use the https:// address of the server. ' + + 'A server on your own computer (http://localhost) is the exception. ' + relayOffer(contact, 'has no https address'); } -/** The next page from a Link header: ; rel="next" */ +/** The next page from a Link header: ; rel="next" (parsed without regular expressions) */ export function nextFromLink(header) { if (!header) return null; for (const part of header.split(',')) { - const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/i); - if (m) return m[1]; + const open = part.indexOf('<'), close = part.indexOf('>', open + 1); + if (open < 0 || close < 0) continue; + const params = part.slice(close + 1).split(';').map((x) => x.trim().toLowerCase().replaceAll('"', '')); + if (params.includes('rel=next')) return part.slice(open + 1, close).trim(); } return null; } -/** Is this address on a server that the relay serves? relay.servers are origins (https://host[:port]). */ +/** Is this address on a server that the relay serves? relay.servers are origins (https://host[:port]), or '*'. */ export function usesRelay(url, relay) { if (!relay?.url || !Array.isArray(relay.servers)) return false; if (relay.servers.includes('*')) return true; - try { return relay.servers.map((s) => trimSlashes(String(s)).toLowerCase()).includes(new URL(url).origin.toLowerCase()); } catch { return false; } + try { + const origin = new URL(url).origin.toLowerCase(); + return relay.servers.some((s) => trimSlashes(String(s)).toLowerCase() === origin); + } catch { + return false; + } +} + +const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1); +/** The header Authorization from what the user enters: "Bearer …", "Basic …" or the bare token */ +function authorization(token) { + const t = String(token || '').trim(); + if (!t) return ''; + return /^(bearer|basic)\s/i.test(t) ? t : 'Bearer ' + t; +} +/** The list of items in an answer: an array, or { elements: [...] } */ +function itemsOf(body) { + if (Array.isArray(body)) return body; + return Array.isArray(body?.elements) ? body.elements : null; } -export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) +export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { + // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) const base = normalizeBaseUrl(baseUrl); if (!base) throw new ApiError('Enter the address of a SysML v2 API server.'); - const t = String(token || '').trim(); - const auth = t ? (/^(bearer|basic)\s/i.test(t) ? t : `Bearer ${t}`) : ''; + const auth = authorization(token); const viaRelay = usesRelay(base, relay); const relayLabel = relay?.label || 'the relay'; const contact = relay?.contact || ''; - async function get(url, signal) { - const relayed = usesRelay(url, relay); + /** The request as the browser sends it: to the server, or to the relay with the address as parameter */ + function request(url, relayed, signal) { const headers = { Accept: 'application/json' }; if (auth) headers[relayed ? 'X-Relay-Authorization' : 'Authorization'] = auth; - const target = relayed ? `${relay.url}?url=${encodeURIComponent(url)}` : url; - if (!relayed) { - const blocked = blockedReason(url, globalThis.location?.protocol, contact); - if (blocked) throw new ApiError('The browser blocks this address.', { url, hint: blocked }); + const target = relayed ? relay.url + '?url=' + encodeURIComponent(url) : url; + return fetchFn(target, { headers, signal, credentials: 'omit', mode: 'cors' }); + } + + function unreachable(url, relayed) { + if (relayed) return new ApiError(capitalize(relayLabel) + ' could not be reached.', { url, hint: 'Check your connection and try again.' }); + const tokenHint = auth ? 'With a token the server must also allow the header Authorization in its CORS settings. ' : ''; + return new ApiError('The server could not be reached.', { + url, + hint: 'Most likely the server does not allow requests from this page (CORS); otherwise the address is wrong or the server is down. ' + + 'The developer console of your browser (F12) shows the exact reason. ' + tokenHint + relayOffer(contact, 'cannot allow it'), + }); + } + + /** An error for an answer that is not OK, or null */ + async function answerError(r, url, relayed) { + if (relayed && r.headers.get('X-Relay-Error')) { + let msg = ''; + try { msg = (await r.json()).error || ''; } catch { /* not JSON */ } + return new ApiError(capitalize(relayLabel) + ': ' + (msg || 'HTTP ' + r.status) + '.', { status: r.status, url }); + } + if (r.status === 401 || r.status === 403) { + const hint = auth ? 'Check the token.' : 'The server needs a token: enter it under "Token".'; + return new ApiError('The server refused access (HTTP ' + r.status + ').', { status: r.status, url, hint }); } + if (r.status === 404) return new ApiError('Not found (HTTP 404).', { status: 404, url, hint: 'Is this the base address of the API? It is the address in front of /projects.' }); + if (!r.ok) return new ApiError('The server answered with HTTP ' + r.status + '.', { status: r.status, url }); + return null; + } + + async function readJson(r, url, relayed) { + try { + return await r.json(); + } catch { + if (relayed) throw new ApiError('The relay did not answer with JSON.', { url, hint: 'Is ' + relayLabel + ' running? (It is a server-side script; a static development server does not run it.)' }); + throw new ApiError('The server did not answer with JSON.', { url, hint: 'Is this the address of a SysML v2 API server?' }); + } + } + + async function get(url, signal) { + const relayed = usesRelay(url, relay); + const blocked = relayed ? '' : blockedReason(url, globalThis.location?.protocol, contact); + if (blocked) throw new ApiError('The browser blocks this address.', { url, hint: blocked }); let r; try { - r = await fetchFn(target, { headers, signal, credentials: 'omit', mode: 'cors' }); + r = await request(url, relayed, signal); } catch (e) { if (e?.name === 'AbortError') throw e; - throw new ApiError(relayed ? `${relayLabel[0].toUpperCase()}${relayLabel.slice(1)} could not be reached.` : 'The server could not be reached.', { - url, - hint: relayed ? 'Check your connection and try again.' - : 'Most likely the server does not allow requests from this page (CORS); otherwise the address is wrong or the server is down. ' - + 'The developer console of your browser (F12) shows the exact reason. ' - + (auth ? 'With a token the server must also allow the header Authorization in its CORS settings. ' : '') - + (contact ? `If the server cannot allow it, it can be added to the relay of this page: write to ${contact}.` : 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'), - }); - } - if (relayed && r.headers.get('X-Relay-Error')) { - let msg = ''; - try { msg = (await r.json()).error || ''; } catch { /* not JSON */ } - throw new ApiError(`${relayLabel[0].toUpperCase()}${relayLabel.slice(1)}: ${msg || `HTTP ${r.status}`}.`, { status: r.status, url }); - } - if (r.status === 401 || r.status === 403) throw new ApiError(`The server refused access (HTTP ${r.status}).`, { status: r.status, url, hint: auth ? 'Check the token.' : 'The server needs a token: enter it under "Token".' }); - if (r.status === 404) throw new ApiError('Not found (HTTP 404).', { status: 404, url, hint: 'Is this the base address of the API? It is the address in front of /projects.' }); - if (!r.ok) throw new ApiError(`The server answered with HTTP ${r.status}.`, { status: r.status, url }); - let body; - try { body = await r.json(); } catch { - throw new ApiError(relayed ? 'The relay did not answer with JSON.' : 'The server did not answer with JSON.', { url, hint: relayed ? `Is ${relayLabel} running? (It is a server-side script; a static development server does not run it.)` : 'Is this the address of a SysML v2 API server?' }); + throw unreachable(url, relayed); } + const error = await answerError(r, url, relayed); + if (error) throw error; + const body = await readJson(r, url, relayed); return { body, link: r.headers.get('Link') || r.headers.get('link') }; } /** All pages of a list resource. Follows the Link header; without it (not exposed by CORS) page[after]=. */ async function list(path, { signal, onProgress, size = pageSize } = {}) { const sep = path.includes('?') ? '&' : '?'; - let url = `${base}${path}${sep}page%5Bsize%5D=${size}`; + const first = base + path + sep + 'page%5Bsize%5D=' + size; + const pageAfter = (id) => first + '&page%5Bafter%5D=' + encodeURIComponent(id); + let url = first; const out = [], seen = new Set(); - for (let page = 0; page < 10000; page++) { + for (let page = 0; page < 10000 && url; page++) { const { body, link } = await get(url, signal); - const items = Array.isArray(body) ? body : Array.isArray(body?.elements) ? body.elements : null; + const items = itemsOf(body); if (!items) throw new ApiError('The server did not answer with a list.', { url, hint: 'Is this the address of a SysML v2 API server?' }); - let fresh = 0; - for (const it of items) { const id = it?.['@id']; if (id && seen.has(id)) continue; if (id) seen.add(id); out.push(it); fresh++; } + const fresh = items.filter((it) => !seen.has(it?.['@id'])); + for (const it of fresh) { + if (it?.['@id']) seen.add(it['@id']); + } + out.push(...fresh); onProgress?.(out.length); - const next = nextFromLink(link); - if (next) { url = new URL(next, url).href; if (!fresh) break; continue; } - // no Link header: if the page was full there may be more, ask for the page after the last element - if (items.length < size || !fresh || !items.at(-1)?.['@id']) break; - url = `${base}${path}${sep}page%5Bsize%5D=${size}&page%5Bafter%5D=${encodeURIComponent(items.at(-1)['@id'])}`; + url = nextUrl({ link, url, items, fresh: fresh.length, size, pageAfter }); } return out; } + /** The address of the next page, or null: from the Link header, else page[after]= if the page was full */ + function nextUrl({ link, url, items, fresh, size, pageAfter }) { + if (!fresh) return null; + const next = nextFromLink(link); + if (next) return new URL(next, url).href; + const last = items.at(-1)?.['@id']; + return items.length >= size && last ? pageAfter(last) : null; + } + const time = (c) => Date.parse(c.created || c.timestamp || '') || 0; + const byName = (a, b) => String(a.name || '').localeCompare(String(b.name || '')); return { base, viaRelay, - projects: async (opts) => (await list('/projects', opts)).sort((a, b) => String(a.name || '').localeCompare(String(b.name || ''))), - project: async (id, opts) => (await get(`${base}/projects/${encodeURIComponent(id)}`, opts?.signal)).body, - branches: (id, opts) => list(`/projects/${encodeURIComponent(id)}/branches`, opts), - commits: async (id, opts) => (await list(`/projects/${encodeURIComponent(id)}/commits`, opts)).sort((a, b) => time(b) - time(a)), - elements: (id, commit, opts) => list(`/projects/${encodeURIComponent(id)}/commits/${encodeURIComponent(commit)}/elements`, opts), + projects: async (opts) => (await list('/projects', opts)).toSorted(byName), + project: async (id, opts) => (await get(base + '/projects/' + encodeURIComponent(id), opts?.signal)).body, + branches: (id, opts) => list('/projects/' + encodeURIComponent(id) + '/branches', opts), + commits: async (id, opts) => (await list('/projects/' + encodeURIComponent(id) + '/commits', opts)).toSorted((a, b) => time(b) - time(a)), + elements: (id, commit, opts) => list('/projects/' + encodeURIComponent(id) + '/commits/' + encodeURIComponent(commit) + '/elements', opts), }; } diff --git a/web/sysmod-viewer-core.js b/web/sysmod-viewer-core.js index 6ce8e3f..52b16d4 100644 --- a/web/sysmod-viewer-core.js +++ b/web/sysmod-viewer-core.js @@ -33,12 +33,28 @@ export const CONTEXTS = [ ]; const ref = (r) => (r && typeof r === 'object' ? r['@id'] : r) || null; -const refs = (v) => (Array.isArray(v) ? v : v ? [v] : []).map(ref).filter(Boolean); +const asList = (v) => { + if (Array.isArray(v)) return v; + return v ? [v] : []; +}; +const refs = (v) => asList(v).map(ref).filter(Boolean); +/** Adds a value to the list of a key in a Map of lists. */ +const addTo = (map, key, value) => { + const list = map.get(key); + if (list) list.push(value); + else map.set(key, [value]); +}; +/** The definition of a MetadataUsage */ +const metadataDefOf = (M, mu) => M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; +/** Does the type of an element match a type or one of a list of types? */ +const isOfType = (el, type) => (Array.isArray(type) ? type.includes(el['@type']) : el['@type'] === type); /** Element access over an array of elements. Unknown ids (e.g. the standard library, not part of the project) give null. */ export function createModel(elements) { const byId = new Map(); - for (const e of elements) if (e && e['@id']) byId.set(e['@id'], e); + for (const e of elements) { + if (e?.['@id']) byId.set(e['@id'], e); + } let byQName = null, byType = null, annotations = null; const M = { size: byId.size, @@ -48,14 +64,16 @@ export function createModel(elements) { byQName(qn) { if (!byQName) { byQName = new Map(); - for (const e of byId.values()) if (e.qualifiedName && !byQName.has(e.qualifiedName)) byQName.set(e.qualifiedName, e); + for (const e of byId.values()) { + if (e.qualifiedName && !byQName.has(e.qualifiedName)) byQName.set(e.qualifiedName, e); + } } return byQName.get(qn) ?? null; }, ofType(t) { if (!byType) { byType = new Map(); - for (const e of byId.values()) { const k = e['@type']; if (!byType.has(k)) byType.set(k, []); byType.get(k).push(e); } + for (const e of byId.values()) addTo(byType, e['@type'], e); } return byType.get(t) ?? []; }, @@ -64,9 +82,9 @@ export function createModel(elements) { if (!annotations) { annotations = new Map(); for (const mu of M.ofType('MetadataUsage')) { - const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; + const def = metadataDefOf(M, mu); if (!def) continue; - for (const a of refs(mu.annotatedElement)) { if (!annotations.has(a)) annotations.set(a, []); annotations.get(a).push(def); } + for (const a of refs(mu.annotatedElement)) addTo(annotations, a, def); } } return annotations.get(ref(el)) ?? []; @@ -76,14 +94,17 @@ export function createModel(elements) { } /** An element of the SYSMOD library itself (SYSMOD, SYSMOD15288, SYSMOD4AI, SYSMODViews …) or of another library */ -export const isLibrary = (el) => !!el && (el.isLibraryElement === true || /^SYSMOD[A-Za-z0-9_]*::/.test(el.qualifiedName || '')); +export const isLibrary = (el) => !!el && (el.isLibraryElement === true || /^SYSMOD\w*::/.test(el.qualifiedName || '')); export const nameOf = (el) => (el && (el.name ?? el.declaredName ?? el.shortName ?? el.declaredShortName)) || ''; /** The general elements of an element: what it redefines, subsets, is typed by, specializes. */ function generals(M, el) { const out = []; - for (const s of M.all(el.ownedSpecialization)) { const g = ref(s.general); if (g) out.push(g); } + for (const s of M.all(el.ownedSpecialization)) { + const g = ref(s.general); + if (g) out.push(g); + } // some servers omit ownedSpecialization on usages: typing and redefinition are specializations as well for (const t of refs(el.type)) out.push(t); return out; @@ -117,7 +138,11 @@ export function docOf(M, el, viaDefinition = true) { const own = M.all(el.documentation).map((d) => cleanDoc(d.body)).filter(Boolean); if (own.length) return own.join('\n\n'); // the text of the definition, but not the generic text of a SYSMOD library definition ("Base element for concerns.") - if (viaDefinition) for (const d of definitionsOf(M, el)) { if (isLibrary(d)) continue; const t = docOf(M, d, false); if (t) return t; } + if (!viaDefinition) return ''; + for (const d of definitionsOf(M, el)) { + const t = isLibrary(d) ? '' : docOf(M, d, false); + if (t) return t; + } return ''; } @@ -132,11 +157,24 @@ export function cleanDoc(body) { if (typeof body !== 'string') return ''; // without regular expressions anchored at the end (linear time also for long texts) let t = body.trim(); - if (t.startsWith('/*')) { let i = 1; while (i < t.length && t[i] === '*') i++; t = t.slice(i); } - if (t.endsWith('*/')) { let e = t.length - 1; while (e > 0 && t[e - 1] === '*') e--; t = t.slice(0, e); } - const lines = t.split('\n').map((l) => { const s = l.trimStart(); return (s.startsWith('*') ? s.slice(1) : s).trim(); }); + if (t.startsWith('/*')) { + let i = 1; + while (i < t.length && t[i] === '*') i++; + t = t.slice(i); + } + if (t.endsWith('*/')) { + let e = t.length - 1; + while (e > 0 && t[e - 1] === '*') e--; + t = t.slice(0, e); + } + const lines = t.split('\n').map((l) => { + const s = l.trimStart(); + return (s.startsWith('*') ? s.slice(1) : s).trim(); + }); const out = []; - for (const l of lines) if (l || (out.length && out[out.length - 1] !== '')) out.push(l); // at most one blank line + for (const l of lines) { + if (l || (out.length && out.at(-1) !== '')) out.push(l); // at most one blank line + } return out.join('\n').trim(); } @@ -148,7 +186,7 @@ export function cleanDoc(body) { export function featuresOf(M, el, type) { if (!el) return []; const all = M.effective ? M.effective(el) : effectiveFeatures(M, el); - return type ? all.filter((f) => (Array.isArray(type) ? type.includes(f['@type']) : f['@type'] === type)) : all; + return type ? all.filter((f) => isOfType(f, type)) : all; } function effectiveFeatures(M, el) { const cache = (M._eff ||= new Map()); @@ -160,12 +198,15 @@ function effectiveFeatures(M, el) { if (!f || seen.has(f['@id']) || redefined.has(f['@id'])) return; seen.add(f['@id']); out.push(f); - for (const r of M.all(f.ownedSpecialization)) if (r['@type'] === 'Redefinition') { const g = ref(r.redefinedFeature ?? r.general); if (g) redefined.add(g); } + for (const g of redefinedBy(M, f)) redefined.add(g); }; - for (const f of M.all(el.ownedFeature)) add(f); - for (const g of generals(M, el)) { const ge = M.get(g); if (ge && ge !== el) for (const f of effectiveFeatures(M, ge)) add(f); } - for (const f of M.all(el.feature)) add(f); - for (const f of M.all(el.inheritedFeature)) add(f); + M.all(el.ownedFeature).forEach(add); + for (const g of generals(M, el)) { + const ge = M.get(g); + if (ge && ge !== el) effectiveFeatures(M, ge).forEach(add); + } + M.all(el.feature).forEach(add); + M.all(el.inheritedFeature).forEach(add); // the nearest feature of a name wins (several paths of inheritance can bring redefinitions of the same feature) const names = new Set(); const result = out.filter((f) => { @@ -179,8 +220,14 @@ function effectiveFeatures(M, el) { cache.set(el['@id'], result); return result; } +/** The ids of the features a feature redefines */ +const redefinedBy = (M, f) => M.all(f.ownedSpecialization) + .filter((r) => r['@type'] === 'Redefinition') + .map((r) => ref(r.redefinedFeature ?? r.general)) + .filter(Boolean); + /** Only the owned features (no inherited ones) */ -export const ownedFeaturesOf = (M, el, type) => M.all(el?.ownedFeature).filter((f) => !type || (Array.isArray(type) ? type.includes(f['@type']) : f['@type'] === type)); +export const ownedFeaturesOf = (M, el, type) => M.all(el?.ownedFeature).filter((f) => !type || isOfType(f, type)); /** The feature of an element with this name (effective, inherited included) */ export const featureNamed = (M, el, name, type) => featuresOf(M, el, type).find((f) => nameOf(f) === name) || null; @@ -200,38 +247,43 @@ export function valueOf(M, feature) { export function exprText(M, e, depth = 0) { if (!e || depth > 8) return ''; const t = e['@type']; - if ('value' in e && /^Literal/.test(t)) return t === 'LiteralInfinity' ? '*' : String(e.value); if (t === 'LiteralInfinity') return '*'; - if (t === 'NullExpression') return ''; - if (t === 'FeatureReferenceExpression') return nameOf(M.get(e.referent)); - if (t === 'FeatureChainExpression') { + if ('value' in e && t.startsWith('Literal')) return String(e.value); + const text = EXPRESSIONS[t]; + return text ? text(M, e, depth) : ''; +} +const argTexts = (M, e, depth) => argsOf(M, e).map((a) => exprText(M, a, depth + 1)); +/** The texts of the kinds of expressions, by metaclass */ +const EXPRESSIONS = { + NullExpression: () => '', + FeatureReferenceExpression: (M, e) => nameOf(M.get(e.referent)), + FeatureChainExpression: (M, e, depth) => { const target = M.get(e.targetFeature); - const chain = target && refs(target.chainingFeature).length ? M.all(target.chainingFeature).map(nameOf) : [nameOf(target)]; - const src = argsOf(M, e).map((a) => exprText(M, a, depth + 1)).filter(Boolean)[0]; + const chain = refs(target?.chainingFeature).length ? M.all(target.chainingFeature).map(nameOf) : [nameOf(target)]; + const src = argTexts(M, e, depth).find(Boolean); return [src, ...chain].filter(Boolean).join('.'); - } - if (t === 'OperatorExpression') { - const args = argsOf(M, e).map((a) => exprText(M, a, depth + 1)); - const op = e.operator; - if (op === '[') return `${args[0] ?? ''} [${args[1] ?? ''}]`; - if (op === ',') return args.filter(Boolean).join(', '); - if (op === '-' && args.length === 1) return `-${args[0]}`; - if (args.length === 2 && op) return `${args[0]} ${op} ${args[1]}`; - return args.filter(Boolean).join(' '); - } - if (t === 'InvocationExpression') return `${nameOf(M.all(e.instantiatedType ?? e.type)[0])}(${argsOf(M, e).map((a) => exprText(M, a, depth + 1)).join(', ')})`; - return ''; + }, + OperatorExpression: (M, e, depth) => operatorText(e.operator, argTexts(M, e, depth)), + InvocationExpression: (M, e, depth) => { + const type = nameOf(M.all(e.instantiatedType ?? e.type)[0]); + return type + '(' + argTexts(M, e, depth).join(', ') + ')'; + }, +}; +function operatorText(op, args) { + if (op === '[') return (args[0] ?? '') + ' [' + (args[1] ?? '') + ']'; + if (op === ',') return args.filter(Boolean).join(', '); + if (op === '-' && args.length === 1) return '-' + args[0]; + if (args.length === 2 && op) return args[0] + ' ' + op + ' ' + args[1]; + return args.filter(Boolean).join(' '); } /** Arguments of an invocation: the values of its input parameters, in order. */ function argsOf(M, e) { const direct = M.all(e.argument); if (direct.length) return direct; - const out = []; - for (const p of M.all(e.ownedFeature)) { - if (p.direction && p.direction !== 'in') continue; - for (const r of M.all(p.ownedRelationship)) if (r['@type'] === 'FeatureValue') { const v = M.get(r.value); if (v) out.push(v); } - } - return out; + return M.all(e.ownedFeature) + .filter((p) => !p.direction || p.direction === 'in') + .flatMap((p) => M.all(p.ownedRelationship).filter((r) => r['@type'] === 'FeatureValue').map((r) => M.get(r.value))) + .filter(Boolean); } const valueNamed = (M, el, name) => valueOf(M, featureNamed(M, el, name, 'AttributeUsage')); @@ -240,17 +292,19 @@ const valueNamed = (M, el, name) => valueOf(M, featureNamed(M, el, name, 'Attrib export function findProjects(M) { const lib = M.byQName(SYSMOD.project); const found = new Map(); - for (const mu of M.ofType('MetadataUsage')) { - const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; - if (!def || !(def.declaredShortName === 'project' || def.qualifiedName === 'SYSMOD::ProjectMetadata')) continue; - for (const a of M.all(mu.annotatedElement)) if (a !== lib) found.set(a['@id'], a); + const isProjectMetadata = (def) => def?.declaredShortName === 'project' || def?.qualifiedName === 'SYSMOD::ProjectMetadata'; + for (const mu of M.ofType('MetadataUsage').filter((x) => isProjectMetadata(metadataDefOf(M, x)))) { + for (const a of M.all(mu.annotatedElement)) { + if (a !== lib) found.set(a['@id'], a); + } } if (!found.size && lib) { - for (const d of M.ofType('OccurrenceDefinition')) if (d !== lib && !d.isLibraryElement && specializes(M, d, lib)) found.set(d['@id'], d); + const specialized = M.ofType('OccurrenceDefinition').filter((d) => d !== lib && !d.isLibraryElement && specializes(M, d, lib)); + for (const d of specialized) found.set(d['@id'], d); } - return [...found.values()] - .map((p) => ({ id: p['@id'], name: nameOf(p) || '(unnamed project)', qualifiedName: p.qualifiedName || '' })) - .sort((a, b) => a.name.localeCompare(b.name)); + const list = [...found.values()].map((p) => ({ id: p['@id'], name: nameOf(p) || '(unnamed project)', qualifiedName: p.qualifiedName || '' })); + list.sort((a, b) => a.name.localeCompare(b.name)); + return list; } /** The features of the project that play a role of SYSMOD::Project (e.g. 'problemStatement'). */ @@ -271,12 +325,17 @@ function stereotypesOf(M, el) { const id = todo.pop(); if (seen.has(id)) continue; seen.add(id); - for (const d of M.metadataOf(id)) { const n = d.declaredShortName || nameOf(d); if (n) names.add(n); } - const e = M.get(id); - if (e) for (const s of M.all(e.ownedSpecialization)) if (s['@type'] !== 'FeatureTyping') { const g = ref(s.general); if (g) todo.push(g); } + for (const d of M.metadataOf(id)) names.add(d.declaredShortName || nameOf(d)); + todo.push(...redefinedOrSubsetted(M, M.get(id))); } + names.delete(''); return [...names]; } +/** What a feature redefines or subsets (not its types) */ +function redefinedOrSubsetted(M, e) { + if (!e) return []; + return M.all(e.ownedSpecialization).filter((s) => s['@type'] !== 'FeatureTyping').map((s) => ref(s.general)).filter(Boolean); +} const brief = (M, el) => (el ? { id: el['@id'], name: nameOf(el), type: el['@type'], doc: docOf(M, el) } : null); const typeNames = (M, el) => definitionsOf(M, el).map(nameOf).filter(Boolean); @@ -290,52 +349,9 @@ export function readContext(M, project, def) { const parts = featuresOf(M, ctx, 'PartUsage'); const soi = parts.find((p) => p !== soiLib && specializes(M, p, soiLib)) || null; const actors = parts.filter((p) => p !== actorsLib && p !== soi && specializes(M, p, actorsLib)); - // connections between the actors and the system (interfaces, connections), by the parts their ends point to - // a feature stands for the soi or an actor if it is that part or one the part redefines (e.g. the part of the context definition) - const match = (x) => { - if (!x || x === soiLib || x === actorsLib) return null; - if (soi && (x === soi || specializes(M, soi, x))) return soi; - return actors.find((a) => a === x || specializes(M, a, x)) || null; - }; - // the part (soi or actor) an end connects, and the port it connects at (operator.controlPort -> operator, controlPort) - const partOfEnd = (end) => { - let e = end, port = null; - for (let i = 0; e && i < 6; i++) { - const hit = match(e); - if (hit) return { part: hit, port }; - if (e['@type'] === 'PortUsage' && !port) port = e; - const chain = M.all(e.chainingFeature); - if (chain.length) { - const last = chain[chain.length - 1]; - if (last['@type'] === 'PortUsage') port = last; - e = chain[0]; - continue; - } - const rs = M.all(e.ownedSpecialization).find((s) => s['@type'] === 'ReferenceSubsetting') || M.all(e.ownedReferenceSubsetting)[0]; - const next = rs ? M.get(rs.referencedFeature ?? rs.general) : null; - if (next) { e = next; continue; } - // a port of the soi (or of a part that redefines it) also stands for the soi - const owner = match(M.get(e.owningType ?? e.owner)); - return owner ? { part: owner, port: port || (e['@type'] === 'PortUsage' ? e : null) } : null; - } - return null; - }; - const links = []; - for (const c of featuresOf(M, ctx, ['InterfaceUsage', 'ConnectionUsage', 'AllocationUsage', 'FlowUsage', 'SuccessionFlowUsage', 'BindingConnectorAsUsage'])) { - if (c['@type'] === 'BindingConnectorAsUsage' || c['@type'] === 'AllocationUsage') continue; - // the owned ends: the inherited ends of the library (actorPort, systemPort) point to the generic actors and soi - const ends = M.all(c.ownedEndFeature).length ? M.all(c.ownedEndFeature) : M.all(c.connectorEnd).length ? M.all(c.connectorEnd) : M.all(c.relatedFeature); - const hits = ends.map(partOfEnd).filter(Boolean); - const ps = [...new Set(hits.map((x) => x.part))]; - if (ps.length === 2 && ps.includes(soi)) { - const actor = ps.find((p) => p !== soi); - const portOf = (part) => nameOf(hits.find((x) => x.part === part)?.port) || ''; - links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: actor['@id'], actorPort: portOf(actor), systemPort: portOf(soi) }); - } - } + const links = contextLinks(M, ctx, { soi, actors, soiLib, actorsLib }); // white box: the system of interest of the Impl context, its parts - let soiImpl = null; - if (impl) soiImpl = featuresOf(M, impl, 'PartUsage').find((p) => p !== soiLib && specializes(M, p, soiLib)) || null; + const soiImpl = impl ? featuresOf(M, impl, 'PartUsage').find((p) => p !== soiLib && specializes(M, p, soiLib)) || null : null; const inner = featuresOf(M, soiImpl || soi, 'PartUsage').filter((p) => !p.isLibraryElement && !specializes(M, p, actorsLib)); return { key: def.key, role: def.role, title: def.title, @@ -343,12 +359,80 @@ export function readContext(M, project, def) { impl: impl ? brief(M, impl) : null, system: soi ? { ...brief(M, soi), types: typeNames(M, soi), stereotypes: stereotypesOf(M, soi), ports: portsOf(M, soi) } : null, systemImpl: soiImpl ? { ...brief(M, soiImpl), types: typeNames(M, soiImpl) } : null, - actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((s) => s !== 'system'), ports: portsOf(M, a) })), + actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((x) => x !== 'system'), ports: portsOf(M, a) })), links, parts: inner.map((p) => ({ ...brief(M, p), types: typeNames(M, p), multiplicity: multiplicityOf(M, p), ports: portsOf(M, p) })), }; } +const CONNECTIONS = ['InterfaceUsage', 'ConnectionUsage', 'FlowUsage', 'SuccessionFlowUsage']; + +/** The ends of a connection: the owned ones (the inherited ends of the library point to the generic actors and soi) */ +function endsOf(M, c) { + for (const list of [c.ownedEndFeature, c.connectorEnd, c.relatedFeature]) { + const ends = M.all(list); + if (ends.length) return ends; + } + return []; +} + +/** The connections between the actors and the system of interest, with the ports they connect */ +function contextLinks(M, ctx, roles) { + const links = []; + for (const c of featuresOf(M, ctx, CONNECTIONS)) { + const hits = endsOf(M, c).map((end) => partOfEnd(M, end, roles)).filter(Boolean); + const ps = [...new Set(hits.map((x) => x.part))]; + if (ps.length !== 2 || !ps.includes(roles.soi)) continue; + const actor = ps.find((p) => p !== roles.soi); + const portOf = (part) => nameOf(hits.find((x) => x.part === part)?.port) || ''; + links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: actor['@id'], actorPort: portOf(actor), systemPort: portOf(roles.soi) }); + } + return links; +} + +/** The soi or the actor a feature stands for: the part itself or one it redefines (e.g. the part of the context definition) */ +function matchRole(M, x, { soi, actors, soiLib, actorsLib }) { + if (!x || x === soiLib || x === actorsLib) return null; + if (soi && (x === soi || specializes(M, soi, x))) return soi; + return actors.find((a) => a === x || specializes(M, a, x)) || null; +} + +/** The feature an end refers to: by its reference subsetting (end :: operator.controlPort) */ +function referencedBy(M, e) { + const rs = M.all(e.ownedSpecialization).find((x) => x['@type'] === 'ReferenceSubsetting') || M.all(e.ownedReferenceSubsetting)[0]; + return rs ? M.get(rs.referencedFeature ?? rs.general) : null; +} + +/** One step from an end towards the part it connects: through a feature chain or a reference subsetting. + { next, port }: next = the next feature (null at the end of the way), port = a port met on the way */ +function stepOf(M, e) { + const chain = M.all(e.chainingFeature); + if (chain.length) { + const last = chain.at(-1); + return { next: chain[0], port: last['@type'] === 'PortUsage' ? last : null }; + } + return { next: referencedBy(M, e), port: null }; +} + +/** The part (soi or actor) an end connects, and the port it connects at (operator.controlPort -> operator, controlPort) */ +function partOfEnd(M, end, roles) { + let e = end, port = null; + for (let i = 0; e && i < 6; i++) { + const hit = matchRole(M, e, roles); + if (hit) return { part: hit, port }; + if (e['@type'] === 'PortUsage') port ||= e; + const step = stepOf(M, e); + if (step.port) port = step.port; + if (!step.next) { + // a port of the soi (or of a part that redefines it) also stands for the soi + const owner = matchRole(M, M.get(e.owningType ?? e.owner), roles); + return owner ? { part: owner, port } : null; + } + e = step.next; + } + return null; +} + /** The ports of a part (effective, without the generic ports of the SYSMOD library such as actorPorts, systemPorts) */ const portsOf = (M, el) => featuresOf(M, el, 'PortUsage').filter((p) => !isLibrary(p) && nameOf(p)).map((p) => ({ id: p['@id'], name: nameOf(p), types: typeNames(M, p) })); @@ -371,7 +455,10 @@ function readStakeholders(M, project) { const lib = M.byQName(`${SYSMOD.project}::projectStakeholders`); // all owned features that are stakeholders, also the project owner (:>> projectOwner, which :> projectStakeholders) const all = lib ? ownedFeaturesOf(M, project).filter((f) => f !== lib && f !== ownerLib && specializes(M, f, lib)) : []; - return all.sort((a, b) => (ownerLib && specializes(M, b, ownerLib)) - (ownerLib && specializes(M, a, ownerLib))).map((p) => ({ + const isOwner = (f) => (ownerLib && specializes(M, f, ownerLib) ? 1 : 0); + const sorted = [...all]; + sorted.sort((a, b) => isOwner(b) - isOwner(a)); + return sorted.map((p) => ({ id: p['@id'], name: valueNamed(M, p, 'name') || nameOf(p), element: nameOf(p), @@ -393,15 +480,17 @@ function nestedOf(M, root, types, depth = 0, seen = new Set()) { if (seen.has(f['@id']) || f.isLibraryElement || !nameOf(f)) continue; if (M.get(f.owningMembership)?.['@type'] === 'FramedConcernMembership') continue; // frame x: a reference, not a nested need seen.add(f['@id']); - out.push({ el: f, depth }); - out.push(...nestedOf(M, f, types, depth + 1, seen)); + out.push({ el: f, depth }, ...nestedOf(M, f, types, depth + 1, seen)); } return out; } const subjectStakeholders = (M, el) => featuresOf(M, el) - .filter((f) => f['@type'] === 'PartUsage' && M.all(f.owningMembership ? [f.owningMembership] : []).some((m) => m['@type'] === 'StakeholderMembership')) - .map((f) => { const v = valueOf(M, f); return v && v !== nameOf(f) ? v.split('.').pop() : nameOf(f); }) + .filter((f) => f['@type'] === 'PartUsage' && M.get(f.owningMembership)?.['@type'] === 'StakeholderMembership') + .map((f) => { + const v = valueOf(M, f); + return v && v !== nameOf(f) ? v.split('.').pop() : nameOf(f); + }) .filter(Boolean); function readNeeds(M, project) { @@ -443,18 +532,7 @@ function readUseCases(M, ctx) { const objective = M.all(u.objectiveRequirement)[0] || featuresOf(M, u, 'RequirementUsage').find((r) => M.get(r.owningMembership)?.['@type'] === 'ObjectiveMembership'); const subject = M.get(u.subjectParameter) || featuresOf(M, u).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); - // steps: the actions the use case (or its definition) owns and the actions its subject performs for it - const steps = []; - const ACTIONS = ['PerformActionUsage', 'ActionUsage', 'AcceptActionUsage', 'SendActionUsage']; - for (const s of [u, ...definitionsOf(M, u)]) { - const subj = M.get(s.subjectParameter) || ownedFeaturesOf(M, s).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); - for (const owner of [subj, s].filter(Boolean)) { - for (const a of ownedFeaturesOf(M, owner, ACTIONS)) { - const n = nameOf(a); - if (n && !a.isLibraryElement && !steps.includes(n) && !/^(start|done|subactions|actions)$/.test(n)) steps.push(n); - } - } - } + const steps = useCaseSteps(M, u); const actors = M.all(u.actorParameter).map((a) => nameOf(a)).filter(Boolean); return { id: u['@id'], @@ -473,6 +551,23 @@ function readUseCases(M, ctx) { }); } +const ACTIONS = ['PerformActionUsage', 'ActionUsage', 'AcceptActionUsage', 'SendActionUsage']; +const LIBRARY_ACTIONS = new Set(['start', 'done', 'subactions', 'actions']); + +/** The steps of a use case: the actions the use case (or its definition) owns and the actions its subject performs for it */ +function useCaseSteps(M, u) { + const steps = new Set(); + for (const s of [u, ...definitionsOf(M, u)]) { + const subj = M.get(s.subjectParameter) || ownedFeaturesOf(M, s).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); + const actions = [subj, s].filter(Boolean).flatMap((owner) => ownedFeaturesOf(M, owner, ACTIONS)); + for (const a of actions) { + const n = nameOf(a); + if (n && !a.isLibraryElement && !LIBRARY_ACTIONS.has(n)) steps.add(n); + } + } + return [...steps]; +} + /** Documentation of a feature of the model; '' for the inherited feature of the SYSMOD library with its generic text */ const modelDoc = (M, f) => (f && !isLibrary(f) ? docOf(M, f) : ''); @@ -487,8 +582,7 @@ function readObjectives(M, project) { /** UVL text of a feature tree (PLEML): element with #featureTree and a textual representation */ function readFeatureTree(M) { for (const mu of M.ofType('MetadataUsage')) { - const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; - if (!def || def.declaredShortName !== 'featureTree') continue; + if (metadataDefOf(M, mu)?.declaredShortName !== 'featureTree') continue; for (const a of M.all(mu.annotatedElement)) { const rep = M.all(a.textualRepresentation)[0] || M.all(a.ownedElement).find((e) => e['@type'] === 'TextualRepresentation'); if (rep?.body) return { name: nameOf(a), language: rep.language || '', body: cleanDoc(rep.body) }; @@ -500,8 +594,8 @@ function readFeatureTree(M) { /** The version of the SYSMOD library in the model: @SYSMOD { version = "5.1.4"; } on the SYSMOD package; '' if not stated */ export function sysmodVersionOf(M) { for (const mu of M.ofType('MetadataUsage')) { - const def = M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; - if (!def || nameOf(def) !== 'SYSMOD' || !/^SYSMOD::/.test(def.qualifiedName || 'SYSMOD::')) continue; + const def = metadataDefOf(M, mu); + if (nameOf(def) !== 'SYSMOD' || !(def.qualifiedName || 'SYSMOD::').startsWith('SYSMOD::')) continue; const v = valueOf(M, featureNamed(M, mu, 'version')); if (v) return v; } @@ -572,7 +666,7 @@ export function checksOf(v) { c('SYSMOD-002', !!owner, 'Project owner', `The project owner is ${owner?.name}.`, 'No stakeholder redefines projectOwner.'), c('SYSMOD-003', v.stakeholders.length > 1, 'Stakeholders', `${v.stakeholders.length} stakeholders.`, 'Besides the project owner, no stakeholders are modeled (:> projectStakeholders).'), c('SYSMOD-004', !!v.systemIdea, 'System idea', 'The system idea context has a system of interest.', 'No system idea context with a system of interest (:>> systemIdeaContext).'), - c('SYSMOD-005', v.contexts.some((x) => x && x.key === 'SC'), 'System context', 'The project has a specification context.', 'No specification context (:>> specificationContext).'), + c('SYSMOD-005', v.contexts.some((x) => x?.key === 'SC'), 'System context', 'The project has a specification context.', 'No specification context (:>> specificationContext).'), c('SYSMOD-006', v.contexts.filter(Boolean).every((x) => x.actors.length > 0), 'Actors', 'Every context has actors.', `Contexts without actors: ${v.contexts.filter((x) => x && !x.actors.length).map((x) => x.title).join(', ')}.`), c('SYSMOD-007', v.useCases.length > 0, 'Use cases', `${v.useCases.length} system use cases.`, 'The specification context has no system use cases.'), c('SYSMOD-008', v.requirements.length > 0, 'Requirements', `${v.requirements.length} requirements.`, 'No requirements under the system requirement specification (:>> systemRequirementSpecification).'), diff --git a/web/sysmod-viewer.css b/web/sysmod-viewer.css index 85a1d3f..ddcbad5 100644 --- a/web/sysmod-viewer.css +++ b/web/sysmod-viewer.css @@ -27,7 +27,6 @@ code { font-family: var(--font-notation); font-size: 0.9em; } .display { font-family: var(--font-display); font-weight: 700; letter-spacing: -0.01em; line-height: 1.1; } .display-md { font-size: clamp(1.625rem, 2.6vw, 2.125rem); } -.ui { font-family: var(--font-ui); } .notation { font-family: var(--font-notation); font-size: 0.8125rem; line-height: 1.7; } .stereo { font-family: var(--font-ui); font-size: 0.8125rem; font-weight: 500; color: var(--sec, var(--muted)); line-height: 1.3; } .stereo::before { content: "«" / ""; } @@ -48,12 +47,11 @@ code { font-family: var(--font-notation); font-size: 0.9em; } .mc-verdict { margin: 0 0 0.35rem; font-family: var(--font-display); font-weight: 700; font-size: 1.5rem; } .mc-ok .mc-verdict { color: var(--c-methods); } .mc-bad .mc-verdict { color: var(--c-books); } .mc-meh .mc-verdict { color: var(--c-info); } .mc-facts { margin: 0.25rem 0; font-family: var(--font-ui); font-size: 0.9375rem; color: var(--muted); } -.mc-src { margin: 0.5rem 0 0; padding: 0.4rem 0.6rem; border: 1px solid var(--line); border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; background: var(--surface); } +.mc-src { margin: 0.5rem 0 0; padding: 0.4rem 0.6rem; border: 1px solid var(--line); border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; background: var(--surface); max-width: 100%; } .mc-files { border-collapse: collapse; font-family: var(--font-ui); font-size: 0.9375rem; min-width: 34rem; } .mc-files th, .mc-files td { text-align: left; padding: 0.4rem 1rem 0.4rem 0; border-bottom: 1px solid var(--line); } .mc-files .num { text-align: right; font-variant-numeric: tabular-nums; } .mc-result, .mc-diag-body { overflow-wrap: anywhere; } -.mc-src { max-width: 100%; } /* SYSMOD viewer (/tools/sysmod-viewer/, script public/tools/sysmod-viewer/sysmod-viewer.js) */ .sv-tabs { display: flex; flex-wrap: wrap; gap: 0.25rem 1.25rem; border-bottom: 1.5px solid var(--line); margin-bottom: 1.25rem; } diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js index 974b706..2ab3511 100644 --- a/web/sysmod-viewer.js +++ b/web/sysmod-viewer.js @@ -1,52 +1,424 @@ -/* sysmod-viewer.js: the interface of the page /tools/sysmod-viewer/. Shows a SYSMOD project of a SysML v2 model: +/* sysmod-viewer.js: the interface of the SYSMOD viewer. Shows a SYSMOD project of a SysML v2 model: the SYSMOD Atlas, problem statement, system idea and objectives, stakeholders, needs, requirements, use cases and the system context diagrams. The model comes from - - a SysML v2 API server (the browser asks the server directly, see sysmod-viewer-api.js), - - the Delivery Drone example (the SysML v2 engine of the checker reads the SYSMOD files of this site in the browser), - - files of the visitor: .sysml (read by the same engine, together with the SYSMOD library) or .json (elements as the API delivers them). + - a SysML v2 API server (the browser asks the server directly, or through a relay; see sysmod-viewer-api.js), + - the Delivery Drone example (a SysML v2 engine reads the SYSMOD files in the browser; only where cfg.engine is set), + - files of the visitor: .json (elements as the API delivers them) or, with cfg.engine, .sysml. Nothing is sent anywhere else. All texts from the model are inserted with textContent, never as HTML. The same file runs in github.com/Open-MBEE/sysmod-sysmlv2-api (web/index.html) and on mbse4u.com/tools/sysmod-viewer/: without cfg.engine there is no example and no .sysml files (only .json), without cfg.relay no relay. */ -const root = document.getElementById('sysmod-viewer'); -if (root) start(JSON.parse(root.dataset.config)); +// ---------- small DOM and text helpers ---------- -async function start(cfg) { +const SVGNS = 'http://www.w3.org/2000/svg'; +const isContent = (k) => k != null && k !== false && k !== ''; +const toNode = (k) => (k.nodeType ? k : document.createTextNode(String(k))); + +function setAttribute(e, k, v) { + if (v == null || v === false) return; + if (k === 'class') e.className = v; + else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); + else e.setAttribute(k, v === true ? '' : v); +} + +/** An HTML element with attributes and children (strings become text nodes) */ +function h(tag, attrs = {}, ...kids) { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) setAttribute(e, k, v); + e.append(...kids.flat(Infinity).filter(isContent).map(toNode)); + return e; +} + +/** An SVG element with attributes and children */ +function s(tag, attrs = {}, ...kids) { + const e = document.createElementNS(SVGNS, tag); + for (const [k, v] of Object.entries(attrs)) { + if (v != null) e.setAttribute(k, v); + } + e.append(...kids.flat(Infinity).filter(isContent).map(toNode)); + return e; +} + +/** text if the condition holds, else '' (keeps template literals flat) */ +const when = (cond, text) => (cond ? text : ''); +const clip = (text, n) => (text.length > n ? text.slice(0, n - 1) + '…' : text); +const nf = new Intl.NumberFormat('en'); + +/** Doc text as paragraphs: blank lines separate paragraphs, single line breaks are the line breaks of the source. */ +function paras(text, cls = '') { + return String(text || '') + .split(/\n{2,}/) + .map((p) => p.split('\n').map((l) => l.trim()).filter(Boolean).join(' ')) + .filter(Boolean) + .map((p) => h('p', { class: cls }, p)); +} + +function setStatus(el, text, kind = '') { + el.textContent = text; + el.dataset.kind = kind; +} + +function errorBox(e) { + return h('div', { class: 'mc-result mc-bad' }, + h('p', { class: 'mc-verdict' }, e?.message || String(e)), + e?.hint ? h('p', { class: 'm-0' }, e.hint) : null, + e?.url ? h('p', { class: 'mc-facts' }, h('code', {}, e.url)) : null); +} + +const withHint = (message, hint) => Object.assign(new Error(message), { hint }); + +// ---------- the SysML v2 engine in the browser (example and .sysml files; only where cfg.engine is set) ---------- + +async function fetchBytes(url) { + const r = await fetch(url); + if (!r.ok) throw new Error(url + ' could not be loaded (HTTP ' + r.status + ')'); + const raw = new Uint8Array(await r.arrayBuffer()); + if (raw[0] !== 0x1f || raw[1] !== 0x8b) return raw; // the server already decompressed it + if (typeof DecompressionStream === 'undefined') throw new Error('This browser cannot decompress the engine. Use a current Chrome, Edge, Firefox or Safari.'); + return new Uint8Array(await new Response(new Blob([raw]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); +} + +let kernelPromise = null; +function loadKernel(engine) { + kernelPromise ||= (async () => { + const at = (name) => engine.base + name; + const [k, wasm, bundle, snapshot] = await Promise.all([ + import(at(engine.kernel)), fetchBytes(at(engine.wasm)), fetchBytes(at(engine.bundle)), fetchBytes(at(engine.snapshot)), + ]); + await k.default({ module_or_path: wasm }); + return { k, lib: new k.PreparedLibrary(new TextDecoder().decode(bundle), snapshot) }; + })().catch((err) => { + kernelPromise = null; // a failed start can be retried + throw err; + }); + return kernelPromise; +} + +/** SysML v2 text files -> elements (SysML v2 API JSON), by the engine. Parse errors stop with a message. */ +async function elementsFromSources(engine, files, statusEl) { + setStatus(statusEl, 'Loading the SysML v2 engine (about 5 MB, once) …'); + const { k, lib } = await loadKernel(engine); + setStatus(statusEl, 'Reading ' + files.length + ' files …'); + await new Promise((r) => setTimeout(r, 30)); // let the browser paint the status + const json = JSON.stringify(files); + const syntax = JSON.parse(k.checkSyntax(json)).filter((x) => x.stage === 'parse'); + if (syntax.length) { + const errors = syntax.length + ' syntax error' + when(syntax.length > 1, 's'); + throw withHint(errors + ', the model cannot be read.', syntax.slice(0, 3).map((x) => x.unit + ', line ' + x.line + ': ' + x.message).join(' · ')); + } + const session = k.Session.fromSourcesWithPreparedLibrary(json, lib); + try { + return JSON.parse(session.toFullJson(false, 'passthrough')); + } finally { + session.free(); + } +} + +/** The elements of .json files (arrays of elements, or { elements: [...] }) */ +async function elementsFromJsonFiles(files) { + const elements = []; + for (const file of files) { + const data = JSON.parse(await file.text()); + const list = Array.isArray(data) ? data : data?.elements; + if (!Array.isArray(list)) throw withHint(file.name + ' is not a list of elements.', 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.'); + elements.push(...list); + } + return elements; +} + +// ---------- rendering of a SYSMOD project ---------- + +const ATLAS = { + problem: [['FEATURE'], ['STAKE', 'PS'], ['NE', 'RE', 'UC', 'SC']], + solution: [['BFAC'], ['SIC'], ['FUC', 'LAC', 'PAC']], +}; +const LABEL = { + FEATURE: 'Features', STAKE: 'Stakeholders', PS: 'Problem Statement', NE: 'Needs', RE: 'Requirements', UC: 'Use Cases', + SC: 'System Specification', BFAC: 'Brownfield Architecture', SIC: 'System Idea Architecture', FUC: 'Functional Architecture', LAC: 'Logical Architecture', PAC: 'Product Architecture', +}; +const TARGET = { FEATURE: 'sv-features', STAKE: 'sv-stakeholders', PS: 'sv-problem', NE: 'sv-needs', RE: 'sv-requirements', UC: 'sv-usecases' }; +const targetOf = (k) => TARGET[k] || 'sv-ctx-' + k; + +const section = (id, title, ...kids) => h('section', { class: 'sv-sec', id, 'aria-labelledby': id + '-h' }, h('h3', { id: id + '-h', class: 'display sv-h' }, title), ...kids); +const empty = (text) => h('p', { class: 'ui text-muted sv-empty' }, text); +const tag = (text) => (text ? h('span', { class: 'sv-tag' }, text) : null); +const typesText = (types) => when(types?.length, ' : ' + (types || []).join(', ')); +const typesLine = (types) => (types?.length ? h('span', { class: 'notation text-muted' }, ': ' + types.join(', ')) : null); +const indent = (depth, prop) => (depth ? prop + ':' + depth * 1.25 + 'rem' : null); +const table = (cols, rows) => h('div', { class: 'overflow-x-auto' }, h('table', { class: 'mc-files sv-table' }, + h('thead', {}, h('tr', {}, cols.map((c) => h('th', { scope: 'col' }, c)))), + h('tbody', {}, rows))); + +function atlasCell(v, k) { + const on = v.atlas[k]; + if (!on) { + return h('span', { class: 'sv-cell', title: LABEL[k] + ': not in the model' }, + h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, '□'), LABEL[k], h('span', { class: 'sr-only' }, ' (not in the model)')); + } + return h('a', { class: 'sv-cell on', href: '#' + targetOf(k), title: 'Go to ' + LABEL[k] }, + h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, '■'), LABEL[k], h('span', { class: 'sr-only' }, ' (in the model)')); +} + +function atlasSection(v) { + const atlas = h('div', { class: 'sv-atlas' }, + ['problem', 'solution'].map((side) => h('div', { class: 'sv-space sv-' + side }, + h('p', { class: 'stereo sv-space-h' }, side + ' space'), + ATLAS[side].map((row) => h('div', { class: 'sv-row' }, row.map((k) => atlasCell(v, k))))))); + const passed = (c) => c.status === 'passed'; + const checks = h('ul', { class: 'sv-checks' }, v.checks.map((c) => h('li', { class: 'sv-check ' + c.status }, + h('span', { class: 'sv-check-mark', 'aria-hidden': 'true' }, passed(c) ? '✓' : '!'), + h('span', {}, h('strong', {}, c.title), ' ', h('span', { class: 'sr-only' }, passed(c) ? '(passed) ' : '(open) '), c.text)))); + return section('sv-atlas', 'SYSMOD Atlas', h('p', { class: 'ui text-muted m-0 mb-3' }, 'Which SYSMOD artifacts the project has. Click one to go there.'), atlas, + h('details', { class: 'sv-details', open: true }, h('summary', { class: 'ui' }, 'Completeness: ' + v.checks.filter(passed).length + ' of ' + v.checks.length), checks)); +} + +function projectHead(v, sourceLabel, size, ms) { + const facts = [when(v.sysmodVersion, 'SYSMOD ' + v.sysmodVersion), when(v.coverView, 'cover view: ' + v.coverView)].filter(Boolean).join(' · '); + const origin = 'Source: ' + sourceLabel + ' · ' + nf.format(size) + ' elements' + when(ms, ' · read in ' + Math.round(ms) + ' ms'); + return h('header', { class: 'sv-head' }, + h('p', { class: 'stereo m-0' }, 'project'), + h('h2', { class: 'display display-md m-0' }, v.name), + v.qualifiedName ? h('p', { class: 'notation text-muted m-0' }, v.qualifiedName) : null, + facts ? h('p', { class: 'ui text-muted m-0 sv-origin' }, facts) : null, + h('p', { class: 'ui text-muted sv-origin' }, origin), + v.purpose ? h('p', { class: 'sv-purpose' }, h('span', { class: 'ui font-semibold' }, 'Purpose: '), v.purpose) : null, + v.owner ? h('p', { class: 'ui m-0' }, h('span', { class: 'font-semibold' }, 'Project owner: '), v.owner) : null, + v.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Project description'), h('div', { class: 'prose max-w-[46rem]' }, paras(v.doc))) : null); +} + +function problemSection(v) { + const ps = v.problemStatement?.doc; + return section('sv-problem', 'Problem statement', ps ? h('blockquote', { class: 'sv-quote' }, paras(ps)) : empty('No problem statement in the model.')); +} + +function ideaSection(v) { + const idea = v.systemIdea + ? [h('p', { class: 'ui m-0 mb-2' }, h('strong', {}, v.systemIdea.name), typesLine(v.systemIdea.types)), h('div', { class: 'prose max-w-[46rem]' }, paras(v.systemIdea.doc))] + : empty('No system idea context in the model.'); + const items = v.objectives.items; + const objectives = items.length ? [ + h('h4', { class: 'ui sv-h4' }, 'System objectives'), + v.objectives.doc ? h('div', { class: 'prose max-w-[46rem] text-muted' }, paras(v.objectives.doc)) : null, + h('ul', { class: 'sv-list' }, items.map((o) => h('li', { style: indent(o.depth, 'margin-left') }, h('strong', { class: 'ui' }, o.name), typesLine(o.types), paras(o.doc, 'm-0')))), + ] : null; + return section('sv-idea', 'System idea', idea, objectives); +} + +function stakeholderSection(v) { + if (!v.stakeholders.length) return section('sv-stakeholders', 'Stakeholders', empty('No stakeholders in the model.')); + const row = (x) => h('tr', {}, + h('td', {}, h('strong', {}, x.name), x.owner ? [' ', tag('project owner')] : null, h('br'), h('span', { class: 'notation text-muted' }, x.element + typesText(x.types))), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.risk), h('td', {}, x.effort), h('td', {}, x.categories), h('td', {}, x.contact)); + return section('sv-stakeholders', 'Stakeholders', table(['Stakeholder', 'Description', 'Risk', 'Effort', 'Categories', 'Contact'], v.stakeholders.map(row))); +} + +function needsSection(v) { + if (!v.needs.length) return section('sv-needs', 'Stakeholder needs', empty('No stakeholder needs in the model.')); + const row = (x) => h('tr', {}, + h('td', { style: indent(x.depth, 'padding-left') }, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.stakeholders), h('td', {}, x.priority)); + return section('sv-needs', 'Stakeholder needs', table(['Need', 'Text', 'Stakeholders', 'Priority'], v.needs.map(row))); +} + +function requirementsSection(v) { + const spec = v.specification; + const specLine = spec ? h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, spec.name + when(spec.types.length, ' : ' + spec.types[0]))) : null; + if (!v.requirements.length) return section('sv-requirements', 'System requirements', specLine, empty('No system requirements in the model.')); + const row = (x) => h('tr', {}, + h('td', { style: indent(x.depth, 'padding-left') }, x.shortName ? h('span', { class: 'notation' }, '<' + x.shortName + '> ') : null, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.obligation), h('td', {}, x.stability), h('td', { class: 'sv-text' }, x.motivation), h('td', {}, x.stakeholders)); + return section('sv-requirements', 'System requirements', specLine, + table(['Requirement', 'Text', 'Obligation', 'Stability', 'Motivation', 'Stakeholders'], v.requirements.map(row))); +} + +function useCaseCard(u) { + const facts = [['Trigger', u.trigger], ['Result', u.result], ['Precondition', u.precondition], ['Postcondition', u.postcondition], ['Motivation', u.motivation], ['Actors', u.actors], ['Subject', u.subject]] + .filter(([, val]) => val); + const steps = u.steps.length + ? h('details', {}, h('summary', { class: 'ui' }, u.steps.length + ' steps'), h('ol', { class: 'sv-steps notation' }, u.steps.map((st) => h('li', {}, st)))) + : null; + return h('article', { class: 'bk bk-usage sv-card' }, + h('div', { class: 'bk-head' }, h('p', { class: 'stereo m-0' }, 'use case'), h('h4', { class: 'bk-title sv-card-title' }, u.name), typesLine(u.types)), + h('div', { class: 'bk-comp' }, paras(u.doc, 'm-0'), h('dl', { class: 'sv-dl' }, facts.map(([k, val]) => [h('dt', {}, k), h('dd', {}, val)])), steps)); +} + +function useCaseSection(v) { + const content = v.useCases.length ? h('div', { class: 'sv-cards' }, v.useCases.map(useCaseCard)) : empty('No system use cases in the specification context.'); + return section('sv-usecases', 'System use cases', content); +} + +function featureSection(v) { + const ft = v.featureTree; + if (!ft) return null; + return section('sv-features', 'Feature tree', h('p', { class: 'ui text-muted m-0 mb-2' }, ft.name + when(ft.language, ' (' + ft.language + ')')), h('pre', { class: 'mc-src sv-pre' }, ft.body)); +} + +// ---------- context diagram (SVG) ---------- + +function contextView(c) { + const counts = ' · ' + c.actors.length + ' actors · ' + c.links.length + ' interfaces · ' + (c.system?.ports?.length || 0) + ' system ports · ' + + c.parts.length + ' parts' + when(c.systemImpl, ' (white box)'); + const facts = h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, c.context.name + when(c.context.types.length, ' : ' + c.context.types[0])), counts); + return [facts, h('figure', { class: 'sv-fig' }, diagram(c), h('figcaption', { class: 'sr-only' }, describe(c))), + c.context.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Description'), h('div', { class: 'prose max-w-[46rem]' }, paras(c.context.doc))) : null]; +} + +/** The diagram in words, for screen readers */ +function describe(c) { + const actor = (a) => a.name + when(a.stereotypes.length, ' (' + a.stereotypes.join(', ') + ')'); + const ports = (l) => when(l.actorPort || l.systemPort, ' (' + (l.actorPort || '?') + ' to ' + (l.systemPort || '?') + ')'); + const link = (l) => (l.name || 'interface') + ports(l); + return 'System context ' + c.context.name + ': system of interest ' + (c.system?.name || 'missing') + + when(c.parts.length, ' with the parts ' + c.parts.map((p) => p.name).join(', ')) + + '; actors ' + (c.actors.map(actor).join(', ') || 'none') + + when(c.links.length, '; interfaces ' + c.links.map(link).join(', ')) + '.'; +} + +const D = { W: 960, ACT_W: 180, ACT_H: 62, GAP: 26, PAD: 20, LANE: 140, PART_H: 40 }; + +/** Positions of the diagram: the system box in the middle, its parts in one or two columns */ +function layout(c) { + const rows = Math.max(Math.ceil(c.actors.length / 2), 1); + const sysX = D.PAD + D.ACT_W + D.LANE, sysW = D.W - 2 * sysX; + const partCols = sysW > 300 ? 2 : 1; + const partW = (sysW - 36 - (partCols - 1) * 14) / partCols; + const partRows = Math.ceil(c.parts.length / partCols); + const sysInner = 64 + (partRows ? partRows * (D.PART_H + 12) + 6 : 10); + const H = Math.max(rows * D.ACT_H + (rows - 1) * D.GAP, sysInner) + 2 * D.PAD; + const sysY = D.PAD + Math.max(0, (H - 2 * D.PAD - sysInner) / 2); + const sysH = Math.max(sysInner, Math.min(H - 2 * D.PAD, sysInner + 40)); + return { H, sysX, sysW, sysY, sysH, partCols, partW }; +} + +function systemBox(c, L) { + const name = c.system?.name || ''; + const sys = s('g', { class: 'sv-sys' }, + s('rect', { x: L.sysX, y: L.sysY, width: L.sysW, height: L.sysH, rx: 10 }), + s('text', { x: L.sysX + L.sysW / 2, y: L.sysY + 22, class: 'sv-st', 'text-anchor': 'middle' }, '«' + (c.system?.stereotypes?.[0] || 'system') + '»'), + s('text', { x: L.sysX + L.sysW / 2, y: L.sysY + 42, class: 'sv-name', 'text-anchor': 'middle' }, s('title', {}, name), clip(name || '(no system of interest)', 40))); + c.parts.forEach((p, i) => { + const x = L.sysX + 18 + (i % L.partCols) * (L.partW + 14), y = L.sysY + 60 + Math.floor(i / L.partCols) * (D.PART_H + 12); + const label = p.name + when(p.types[0], ' : ' + p.types[0]) + when(p.multiplicity, ' [' + p.multiplicity + ']'); + sys.append(s('g', { class: 'sv-part' }, s('title', {}, label), s('rect', { x, y, width: L.partW, height: D.PART_H, rx: 4 }), + s('text', { x: x + L.partW / 2, y: y + 25, 'text-anchor': 'middle' }, clip(label, Math.floor(L.partW / 7.2))))); + }); + return sys; +} + +/** Long interface names on two lines, broken at a word boundary of the camelCase name (operator|Interface) */ +function splitLabel(label) { + if (label.length <= 18) return [label]; + const cuts = [...label.matchAll(/(?<=[a-z0-9])(?=[A-Z])|(?<=[,_ -])/g)].map((m) => m.index).filter((i) => i > 2 && i < label.length - 2); + if (!cuts.length) return [label]; + const middle = label.length / 2; + const cut = cuts.reduce((best, i) => (Math.abs(i - middle) < Math.abs(best - middle) ? i : best)); + return [label.slice(0, cut).trim(), label.slice(cut).trim()]; +} + +const unique = (list) => [...new Set(list.filter(Boolean))].join(', '); + +/** The interface label above the line, the ports below it, and the port squares on the borders */ +function drawLink(g, links, a, ends) { + const { ax, cy, sx, sy, side, systemName } = ends; + const mx = (ax + sx) / 2; + const label = links.map((l) => l.name || 'interface').join(', '); + const parts = splitLabel(label); + g.lines.append(s('text', { x: mx, y: cy - 8 - (parts.length - 1) * 13, 'text-anchor': 'middle', class: 'sv-ifc' }, s('title', {}, label), + parts.map((t, i) => s('tspan', { x: mx, dy: i ? 13 : 0 }, clip(t, 19))))); + const ap = unique(links.map((l) => l.actorPort)), sp = unique(links.map((l) => l.systemPort)); + if (ap) g.ports.append(s('rect', { x: ax - 4, y: cy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, a.name + '.' + ap))); + if (sp) g.ports.append(s('rect', { x: sx - 4, y: sy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, systemName + '.' + sp))); + if (!ap && !sp) return; + // two lines, left port above the right one, so that long names fit into the lane between the boxes + const [l, r] = side === 'left' ? [ap || '·', sp || '·'] : [sp || '·', ap || '·']; + const my = (cy + sy) / 2 + 15; + g.lines.append(s('text', { x: mx, y: my, 'text-anchor': 'middle', class: 'sv-portname' }, s('title', {}, 'ports: ' + l + ' ↔ ' + r), + s('tspan', { x: mx, dy: 0 }, clip(l, 19) + ' ↔'), s('tspan', { x: mx, dy: 12 }, clip(r, 19)))); +} + +/** An actor box; a «user» gets a small stick figure in it */ +function actorBox(a, x, y) { + const st = a.stereotypes[0] || 'actor'; + const title = a.name + typesText(a.types) + when(a.doc, '\n' + a.doc); + const g = s('g', { class: 'sv-actor sv-' + st }, s('title', {}, title)); + const fig = st === 'user' ? 22 : 0, tx = x + fig + (D.ACT_W - fig) / 2; + g.append(s('rect', { x, y, width: D.ACT_W, height: D.ACT_H, rx: st === 'environmentalEffect' ? 28 : 4 })); + if (fig) { + const fx = x + 18, fy = y + 13; + const figure = 'M' + fx + ' ' + (fy + 5) + 'v15M' + (fx - 8) + ' ' + (fy + 11) + 'h16M' + fx + ' ' + (fy + 20) + 'l-7 12M' + fx + ' ' + (fy + 20) + 'l7 12'; + g.append(s('circle', { cx: fx, cy: fy, r: 5 }), s('path', { class: 'sv-fig-line', d: figure })); + } + g.append(s('text', { x: tx, y: y + 24, 'text-anchor': 'middle', class: 'sv-st' }, '«' + st + '»'), + s('text', { x: tx, y: y + 44, 'text-anchor': 'middle', class: 'sv-name' }, clip(a.name, fig ? 18 : 21))); + return g; +} + +/** The actors of one side, with the lines to the system box */ +function placeActors(g, c, L, list, side) { + const linksOf = (a) => c.links.filter((l) => l.actor === a.id); + const off = (L.H - 2 * D.PAD - (list.length * D.ACT_H + (list.length - 1) * D.GAP)) / 2; + const left = side === 'left'; + list.forEach((a, i) => { + const x = left ? D.PAD : D.W - D.PAD - D.ACT_W, y = D.PAD + off + i * (D.ACT_H + D.GAP); + const cy = y + D.ACT_H / 2, ax = left ? x + D.ACT_W : x, sx = left ? L.sysX : L.sysX + L.sysW; + const sy = Math.min(Math.max(cy, L.sysY + 14), L.sysY + L.sysH - 14); + const links = linksOf(a); + g.lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: sy, class: links.length ? '' : 'sv-nolink' })); + if (links.length) drawLink(g, links, a, { ax, cy, sx, sy, side, systemName: c.system?.name || 'system' }); + g.actors.append(actorBox(a, x, y)); + }); +} + +function diagram(c) { + const L = layout(c); + const svg = s('svg', { viewBox: '0 0 ' + D.W + ' ' + L.H, class: 'sv-svg', role: 'img', 'aria-label': 'Context diagram of ' + c.context.name }); + const g = { lines: s('g', { class: 'sv-lines' }), actors: s('g', {}), ports: s('g', {}) }; + placeActors(g, c, L, c.actors.filter((_, i) => i % 2 === 0), 'left'); + placeActors(g, c, L, c.actors.filter((_, i) => i % 2 === 1), 'right'); + svg.append(g.lines, systemBox(c, L), g.actors, g.ports); + if (!c.actors.length) svg.append(s('text', { x: D.PAD, y: D.PAD + 14, class: 'sv-st' }, 'no actors')); + return svg; +} + +/** All sections of a project */ +function projectSections(v, contexts) { + return [ + atlasSection(v), problemSection(v), ideaSection(v), stakeholderSection(v), needsSection(v), requirementsSection(v), useCaseSection(v), + ...v.contexts.map((c, i) => section('sv-ctx-' + contexts[i].key, contexts[i].title, c ? contextView(c) : empty('No ' + contexts[i].role + ' in the model.'))), + featureSection(v), + ].filter(Boolean); +} + +// ---------- the page ---------- + +/** The commit to preselect: the one in the address, else the head of the default branch, else the newest */ +function preselectedCommit(commits, wanted, head) { + const has = (id) => id && commits.some((c) => c['@id'] === id); + if (has(wanted)) return wanted; + if (has(head)) return head; + return commits[0]?.['@id'] || ''; +} + +function commitLabel(c, head) { + const d = Date.parse(c.created || ''); + const date = d ? new Date(d).toLocaleString('en', { dateStyle: 'medium', timeStyle: 'short' }) : c['@id'].slice(0, 8); + return date + when(c.description, ' · ' + String(c.description).slice(0, 60)) + when(c['@id'] === head, ' (head of the default branch)'); +} + +async function start(root, cfg) { const core = await import(cfg.core); const apiMod = await import(cfg.api); - const $ = (s) => root.querySelector(s); - - // ---------- small DOM helpers ---------- - const h = (tag, attrs = {}, ...kids) => { - const e = document.createElement(tag); - for (const [k, v] of Object.entries(attrs || {})) { - if (v == null || v === false) continue; - if (k === 'class') e.className = v; - else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); - else e.setAttribute(k, v === true ? '' : v); - } - for (const k of kids.flat(Infinity)) if (k != null && k !== false && k !== '') e.append(k.nodeType ? k : document.createTextNode(String(k))); - return e; - }; - const SVGNS = 'http://www.w3.org/2000/svg'; - const s = (tag, attrs = {}, ...kids) => { - const e = document.createElementNS(SVGNS, tag); - for (const [k, v] of Object.entries(attrs)) if (v != null) e.setAttribute(k, v); - for (const k of kids.flat(Infinity)) if (k != null && k !== false) e.append(k.nodeType ? k : document.createTextNode(String(k))); - return e; - }; - /** Doc text as paragraphs: blank lines separate paragraphs, single line breaks are the line breaks of the source. */ - const paras = (text, cls = '') => String(text || '').split(/\n{2,}/).map((p) => p.split('\n').map((l) => l.trim()).filter(Boolean).join(' ')).filter(Boolean).map((p) => h('p', { class: cls }, p)); - const nf = new Intl.NumberFormat('en'); - const status = (el, text, kind = '') => { el.textContent = text; el.dataset.kind = kind; }; + const $ = (sel) => root.querySelector(sel); // ---------- state in the address (never the token) ---------- const params = new URLSearchParams(location.search); const setParams = (obj) => { const p = new URLSearchParams(); - for (const [k, v] of Object.entries(obj)) if (v) p.set(k, v); + for (const [k, v] of Object.entries(obj)) { + if (v) p.set(k, v); + } const q = p.toString(); - history.replaceState(null, '', `${location.pathname}${q ? `?${q}` : ''}${location.hash}`); + history.replaceState(null, '', location.pathname + when(q, '?' + q) + location.hash); }; // ---------- source tabs ---------- @@ -64,6 +436,14 @@ async function start(cfg) { const out = $('[data-out]'); const pick = $('[data-pick]'), pickSel = $('[data-pick-select]'); + function render(projectId, ms) { + const v = core.readProject(model, projectId); + if (source?.kind === 'server') setParams({ server: source.server, project: source.project, commit: source.commit, sysmod: projectId }); + out.replaceChildren(projectHead(v, source?.label || '', model.size, ms), ...projectSections(v, core.CONTEXTS)); + out.querySelector('h2')?.setAttribute('tabindex', '-1'); + out.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' }); + } + function useElements(elements, src) { const t0 = performance.now(); model = core.createModel(elements); @@ -74,14 +454,14 @@ async function start(cfg) { pick.hidden = true; out.append(h('div', { class: 'mc-result mc-bad' }, h('p', { class: 'mc-verdict' }, 'No SYSMOD project found'), - h('p', { class: 'm-0' }, `The model has ${nf.format(model.size)} elements, but none of them is a SYSMOD project (#project, or a specialization of SYSMOD::Project). ` + h('p', { class: 'm-0' }, 'The model has ' + nf.format(model.size) + ' elements, but none of them is a SYSMOD project (#project, or a specialization of SYSMOD::Project). ' + 'The SYSMOD library must be part of the same model.'))); return; } - pickSel.replaceChildren(...projects.map((p) => h('option', { value: p.id }, p.qualifiedName && p.qualifiedName !== p.name ? `${p.name} (${p.qualifiedName})` : p.name))); + const label = (p) => (p.qualifiedName && p.qualifiedName !== p.name ? p.name + ' (' + p.qualifiedName + ')' : p.name); + pickSel.replaceChildren(...projects.map((p) => h('option', { value: p.id }, label(p)))); pick.hidden = projects.length < 2; - const wanted = params.get('sysmod'); - const first = projects.find((p) => p.id === wanted) || projects[0]; + const first = projects.find((p) => p.id === params.get('sysmod')) || projects[0]; pickSel.value = first.id; render(first.id, performance.now() - t0); } @@ -94,39 +474,46 @@ async function start(cfg) { commit: $('[data-commit]'), load: $('[data-load]'), err: $('[data-err-server]'), }; let client = null, projectList = [], abort = null; - if (params.get('server')) { f.url.value = params.get('server'); showTab('server'); } + if (params.get('server')) { + f.url.value = params.get('server'); + showTab('server'); + } // the servers of the relay as suggestions for the address field - const dl = $('[data-relay-list]'); - if (dl) dl.replaceChildren(...(cfg.relay?.servers || []).map((u) => h('option', { value: u }))); + $('[data-relay-list]')?.replaceChildren(...(cfg.relay?.servers || []).filter((u) => u !== '*').map((u) => h('option', { value: u }))); const showError = (box, e) => { - if (e?.name === 'AbortError') return; - box.replaceChildren(h('div', { class: 'mc-result mc-bad' }, - h('p', { class: 'mc-verdict' }, e?.message || String(e)), - e?.hint ? h('p', { class: 'm-0' }, e.hint) : null, - e?.url ? h('p', { class: 'mc-facts' }, h('code', {}, e.url)) : null)); + if (e?.name !== 'AbortError') box.replaceChildren(errorBox(e)); }; - f.connect.addEventListener('click', async () => { + async function connect() { f.err.replaceChildren(); f.projRow.hidden = true; try { client = apiMod.createClient({ baseUrl: f.url.value, token: f.token.value, relay: cfg.relay }); f.url.value = client.base; - const via = client.viaRelay ? ` via ${cfg.relay?.label || 'the relay'}` : ''; - status(f.st, `Connecting${via} …`); + const via = when(client.viaRelay, ' via ' + (cfg.relay?.label || 'the relay')); + setStatus(f.st, 'Connecting' + via + ' …'); projectList = await client.projects(); - if (!projectList.length) { status(f.st, 'The server has no projects.', 'bad'); return; } - status(f.st, `${nf.format(projectList.length)} projects${via}`, 'ok'); + if (!projectList.length) { + setStatus(f.st, 'The server has no projects.', 'bad'); + return; + } + setStatus(f.st, nf.format(projectList.length) + ' projects' + via, 'ok'); f.proj.replaceChildren(); // a new server: no selection carried over from the previous one fillProjects(); f.projRow.hidden = false; const want = params.get('project'); if (want && projectList.some((p) => p['@id'] === want)) f.proj.value = want; await loadCommits(); - } catch (e) { status(f.st, ''); showError(f.err, e); } + } catch (e) { + setStatus(f.st, ''); + showError(f.err, e); + } + } + f.connect.addEventListener('click', connect); + f.url.addEventListener('keydown', (e) => { + if (e.key === 'Enter') f.connect.click(); }); - f.url.addEventListener('keydown', (e) => { if (e.key === 'Enter') f.connect.click(); }); function fillProjects() { const q = f.projFilter.value.trim().toLowerCase(); @@ -135,30 +522,13 @@ async function start(cfg) { f.proj.replaceChildren(...list.map((p) => h('option', { value: p['@id'] }, p.name || p['@id']))); if (list.some((p) => p['@id'] === keep)) f.proj.value = keep; } - f.projFilter.addEventListener('input', () => { const before = f.proj.value; fillProjects(); if (f.proj.value !== before) loadCommits(); }); + f.projFilter.addEventListener('input', () => { + const before = f.proj.value; + fillProjects(); + if (f.proj.value !== before) loadCommits(); + }); f.proj.addEventListener('change', () => loadCommits()); - async function loadCommits() { - f.commit.replaceChildren(h('option', {}, 'Loading commits …')); - f.load.disabled = true; - try { - const pid = f.proj.value; - if (!pid) return; - const [commits, head] = await Promise.all([client.commits(pid), defaultHead(pid)]); - if (pid !== f.proj.value) return; // the visitor chose another project meanwhile - const fmt = (c) => { - const d = Date.parse(c.created || ''); - const when = d ? new Date(d).toLocaleString('en', { dateStyle: 'medium', timeStyle: 'short' }) : c['@id'].slice(0, 8); - const desc = c.description ? ` · ${String(c.description).slice(0, 60)}` : ''; - return `${when}${desc}${c['@id'] === head ? ' (head of the default branch)' : ''}`; - }; - f.commit.replaceChildren(...commits.map((c) => h('option', { value: c['@id'] }, fmt(c)))); - const want = params.get('commit'); - f.commit.value = commits.some((c) => c['@id'] === want) ? want : head && commits.some((c) => c['@id'] === head) ? head : commits[0]?.['@id'] || ''; - f.load.disabled = !commits.length; - if (!commits.length) f.commit.replaceChildren(h('option', {}, 'This project has no commits.')); - } catch (e) { f.commit.replaceChildren(); showError(f.err, e); } - } async function defaultHead(pid) { try { const p = await client.project(pid); @@ -166,10 +536,33 @@ async function start(cfg) { if (!bid) return null; const b = (await client.branches(pid)).find((x) => x['@id'] === bid); return b?.head?.['@id'] || null; - } catch { return null; } + } catch { + return null; + } + } + + async function loadCommits() { + f.commit.replaceChildren(h('option', {}, 'Loading commits …')); + f.load.disabled = true; + const pid = f.proj.value; + if (!pid) return; + try { + const [commits, head] = await Promise.all([client.commits(pid), defaultHead(pid)]); + if (pid !== f.proj.value) return; // the visitor chose another project meanwhile + if (!commits.length) { + f.commit.replaceChildren(h('option', {}, 'This project has no commits.')); + return; + } + f.commit.replaceChildren(...commits.map((c) => h('option', { value: c['@id'] }, commitLabel(c, head)))); + f.commit.value = preselectedCommit(commits, params.get('commit'), head); + f.load.disabled = false; + } catch (e) { + f.commit.replaceChildren(); + showError(f.err, e); + } } - f.load.addEventListener('click', async () => { + async function loadModel() { f.err.replaceChildren(); abort?.abort(); abort = new AbortController(); @@ -177,53 +570,30 @@ async function start(cfg) { const pname = f.proj.selectedOptions[0]?.textContent || pid; f.load.disabled = true; try { - status(f.st, 'Loading the model …'); - const elements = await client.elements(pid, cid, { signal: abort.signal, onProgress: (n) => status(f.st, `Loading the model … ${nf.format(n)} elements`) }); - status(f.st, `${nf.format(elements.length)} elements loaded`, 'ok'); + setStatus(f.st, 'Loading the model …'); + const onProgress = (n) => setStatus(f.st, 'Loading the model … ' + nf.format(n) + ' elements'); + const elements = await client.elements(pid, cid, { signal: abort.signal, onProgress }); + setStatus(f.st, nf.format(elements.length) + ' elements loaded', 'ok'); setParams({ server: client.base, project: pid, commit: cid }); - useElements(elements, { kind: 'server', label: `${pname} on ${new URL(client.base).host}`, server: client.base, project: pid, commit: cid }); - } catch (e) { status(f.st, ''); showError(f.err, e); } - finally { f.load.disabled = false; } - }); - - // ---------- 2. + 3. The SysML v2 engine in the browser (example and .sysml files) ---------- - let kernelPromise = null; - async function fetchBytes(url) { - const r = await fetch(url); - if (!r.ok) throw new Error(`${url} could not be loaded (HTTP ${r.status})`); - const raw = new Uint8Array(await r.arrayBuffer()); - if (raw[0] !== 0x1f || raw[1] !== 0x8b) return raw; // the server already decompressed it - if (typeof DecompressionStream === 'undefined') throw new Error('This browser cannot decompress the engine. Use a current Chrome, Edge, Firefox or Safari.'); - return new Uint8Array(await new Response(new Blob([raw]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); - } - const kernel = () => (kernelPromise ||= (async () => { - const e = cfg.engine; - const [k, wasm, bundle, snapshot] = await Promise.all([ - import(e.base + e.kernel), fetchBytes(e.base + e.wasm), fetchBytes(e.base + e.bundle), fetchBytes(e.base + e.snapshot), - ]); - await k.default({ module_or_path: wasm }); - return { k, lib: new k.PreparedLibrary(new TextDecoder().decode(bundle), snapshot) }; - })().catch((err) => { kernelPromise = null; throw err; })); - - /** SysML v2 text files -> elements (SysML v2 API JSON), by the engine. Parse errors stop with a message. */ - async function elementsFromSources(files, st) { - status(st, 'Loading the SysML v2 engine (about 5 MB, once) …'); - const { k, lib } = await kernel(); - status(st, `Reading ${files.length} files …`); - await new Promise((r) => setTimeout(r, 30)); // let the browser paint the status - const json = JSON.stringify(files); - const syntax = JSON.parse(k.checkSyntax(json)).filter((x) => x.stage === 'parse'); - if (syntax.length) { - const e = new Error(`${syntax.length} syntax error${syntax.length > 1 ? 's' : ''}, the model cannot be read.`); - e.hint = syntax.slice(0, 3).map((x) => `${x.unit}, line ${x.line}: ${x.message}`).join(' · '); - throw e; + useElements(elements, { kind: 'server', label: pname + ' on ' + new URL(client.base).host, server: client.base, project: pid, commit: cid }); + } catch (e) { + setStatus(f.st, ''); + showError(f.err, e); + } finally { + f.load.disabled = false; } - const session = k.Session.fromSourcesWithPreparedLibrary(json, lib); - try { return JSON.parse(session.toFullJson(false, 'passthrough')); } finally { session.free(); } } + f.load.addEventListener('click', loadModel); + // ---------- 2. + 3. The example and files ---------- let manifestPromise = null; - const manifest = () => (manifestPromise ||= fetch(cfg.example.manifest).then((r) => { if (!r.ok) throw new Error('The SYSMOD files could not be loaded.'); return r.json(); })); + const manifest = () => { + manifestPromise ||= fetch(cfg.example.manifest).then((r) => { + if (!r.ok) throw new Error('The SYSMOD files could not be loaded.'); + return r.json(); + }); + return manifestPromise; + }; const sysmodFiles = async (roles) => { const m = await manifest(); const files = m.files.filter((x) => roles.includes(x.role)); @@ -231,233 +601,64 @@ async function start(cfg) { }; const ex = { btn: $('[data-example]'), st: $('[data-status-example]'), err: $('[data-err-example]') }; - ex.btn?.addEventListener('click', async () => { + async function openExample() { ex.err.replaceChildren(); ex.btn.disabled = true; try { - const files = await sysmodFiles(['library', 'example']); - const elements = await elementsFromSources(files, ex.st); - status(ex.st, `${nf.format(elements.length)} elements`, 'ok'); + const elements = await elementsFromSources(cfg.engine, await sysmodFiles(['library', 'example']), ex.st); + setStatus(ex.st, nf.format(elements.length) + ' elements', 'ok'); setParams({ example: 'drone' }); useElements(elements, { kind: 'example', label: 'SYSMOD Delivery Drone example' }); - } catch (e) { status(ex.st, ''); showError(ex.err, e); } - finally { ex.btn.disabled = false; } - }); + } catch (e) { + setStatus(ex.st, ''); + showError(ex.err, e); + } finally { + ex.btn.disabled = false; + } + } + ex.btn?.addEventListener('click', openExample); + + /** .sysml files, read together with the SYSMOD library (unless the visitor brings it along) */ + async function elementsFromSysmlFiles(files, statusEl) { + if (!cfg.engine) throw withHint('.sysml files need the SysML v2 engine, which this page does not have.', 'Open a .json file with the elements of a commit, or use mbse4u.com/tools/sysmod-viewer/, which reads .sysml files.'); + const own = await Promise.all(files.map(async (x) => ({ name: x.name, text: await x.text() }))); + const have = new Set(own.map((x) => x.name)); + const lib = (await sysmodFiles(['library'])).filter((x) => !have.has(x.name)); + return elementsFromSources(cfg.engine, [...lib, ...own], statusEl); + } const fl = { input: $('[data-files]'), st: $('[data-status-files]'), err: $('[data-err-files]') }; - fl.input.addEventListener('change', async () => { + async function openFiles() { fl.err.replaceChildren(); const picked = [...fl.input.files]; if (!picked.length) return; + const ofKind = (...ext) => picked.filter((x) => ext.some((e) => x.name.toLowerCase().endsWith(e))); + const jsons = ofKind('.json'), texts = ofKind('.sysml', '.kerml'); try { - const jsons = picked.filter((x) => /\.json$/i.test(x.name)), texts = picked.filter((x) => /\.(sysml|kerml)$/i.test(x.name)); - let elements; - if (jsons.length) { - status(fl.st, 'Reading …'); - elements = []; - for (const j of jsons) { - const data = JSON.parse(await j.text()); - const list = Array.isArray(data) ? data : Array.isArray(data?.elements) ? data.elements : null; - if (!list) throw Object.assign(new Error(`${j.name} is not a list of elements.`), { hint: 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.' }); - elements.push(...list); - } - } else if (texts.length) { - if (!cfg.engine) throw Object.assign(new Error('.sysml files need the SysML v2 engine, which this page does not have.'), { hint: 'Open a .json file with the elements of a commit, or use mbse4u.com/tools/sysmod-viewer/, which reads .sysml files.' }); - const own = await Promise.all(texts.map(async (x) => ({ name: x.name, text: await x.text() }))); - // the SYSMOD library is added unless the visitor brings it along - const have = new Set(own.map((x) => x.name)); - const lib = (await sysmodFiles(['library'])).filter((x) => !have.has(x.name)); - elements = await elementsFromSources([...lib, ...own], fl.st); - } else throw new Error('Choose .sysml files or a .json file.'); - status(fl.st, `${nf.format(elements.length)} elements`, 'ok'); + if (!jsons.length && !texts.length) throw new Error('Choose .sysml files or a .json file.'); + setStatus(fl.st, 'Reading …'); + const elements = jsons.length ? await elementsFromJsonFiles(jsons) : await elementsFromSysmlFiles(texts, fl.st); + setStatus(fl.st, nf.format(elements.length) + ' elements', 'ok'); setParams({}); useElements(elements, { kind: 'files', label: picked.map((x) => x.name).join(', ') }); - } catch (e) { status(fl.st, ''); showError(fl.err, e); } - }); - - // ---------- rendering of a SYSMOD project ---------- - const ATLAS = { - problem: [['FEATURE'], ['STAKE', 'PS'], ['NE', 'RE', 'UC', 'SC']], - solution: [['BFAC'], ['SIC'], ['FUC', 'LAC', 'PAC']], - }; - const LABEL = { - FEATURE: 'Features', STAKE: 'Stakeholders', PS: 'Problem Statement', NE: 'Needs', RE: 'Requirements', UC: 'Use Cases', - SC: 'System Specification', BFAC: 'Brownfield Architecture', SIC: 'System Idea Architecture', FUC: 'Functional Architecture', LAC: 'Logical Architecture', PAC: 'Product Architecture', - }; - const TARGET = { FEATURE: 'sv-features', STAKE: 'sv-stakeholders', PS: 'sv-problem', NE: 'sv-needs', RE: 'sv-requirements', UC: 'sv-usecases' }; - const targetOf = (k) => TARGET[k] || `sv-ctx-${k}`; - - const section = (id, title, ...kids) => h('section', { class: 'sv-sec', id, 'aria-labelledby': `${id}-h` }, h('h3', { id: `${id}-h`, class: 'display sv-h' }, title), ...kids); - const empty = (text) => h('p', { class: 'ui text-muted sv-empty' }, text); - const tag = (text) => (text ? h('span', { class: 'sv-tag' }, text) : null); - const typesLine = (types) => (types?.length ? h('span', { class: 'notation text-muted' }, `: ${types.join(', ')}`) : null); - const table = (cols, rows) => h('div', { class: 'overflow-x-auto' }, h('table', { class: 'mc-files sv-table' }, - h('thead', {}, h('tr', {}, cols.map((c) => h('th', { scope: 'col' }, c)))), - h('tbody', {}, rows))); - - function render(projectId, ms) { - const v = core.readProject(model, projectId); - if (source?.kind === 'server') setParams({ server: source.server, project: source.project, commit: source.commit, sysmod: projectId }); - const atlasCell = (k) => { - const on = v.atlas[k]; - return h(on ? 'a' : 'span', { class: `sv-cell${on ? ' on' : ''}`, href: on ? `#${targetOf(k)}` : null, title: on ? `Go to ${LABEL[k]}` : `${LABEL[k]}: not in the model` }, - h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, on ? '■' : '□'), LABEL[k], - h('span', { class: 'sr-only' }, on ? ' (in the model)' : ' (not in the model)')); - }; - const atlas = h('div', { class: 'sv-atlas' }, - ['problem', 'solution'].map((side) => h('div', { class: `sv-space sv-${side}` }, - h('p', { class: 'stereo sv-space-h' }, side === 'problem' ? 'problem space' : 'solution space'), - ATLAS[side].map((row) => h('div', { class: 'sv-row' }, row.map(atlasCell)))))); - - const checks = h('ul', { class: 'sv-checks' }, v.checks.map((c) => h('li', { class: `sv-check ${c.status}` }, - h('span', { class: 'sv-check-mark', 'aria-hidden': 'true' }, c.status === 'passed' ? '✓' : '!'), - h('span', {}, h('strong', {}, c.title), ' ', h('span', { class: 'sr-only' }, c.status === 'passed' ? '(passed) ' : '(open) '), c.text)))); - - const head = h('header', { class: 'sv-head' }, - h('p', { class: 'stereo m-0' }, 'project'), - h('h2', { class: 'display display-md m-0' }, v.name), - v.qualifiedName ? h('p', { class: 'notation text-muted m-0' }, v.qualifiedName) : null, - v.sysmodVersion || v.coverView ? h('p', { class: 'ui text-muted m-0 sv-origin' }, [v.sysmodVersion ? `SYSMOD ${v.sysmodVersion}` : '', v.coverView ? `cover view: ${v.coverView}` : ''].filter(Boolean).join(' · ')) : null, - h('p', { class: 'ui text-muted sv-origin' }, `Source: ${source?.label || ''} · ${nf.format(model.size)} elements${ms ? ` · read in ${Math.round(ms)} ms` : ''}`), - v.purpose ? h('p', { class: 'sv-purpose' }, h('span', { class: 'ui font-semibold' }, 'Purpose: '), v.purpose) : null, - v.owner ? h('p', { class: 'ui m-0' }, h('span', { class: 'font-semibold' }, 'Project owner: '), v.owner) : null, - v.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Project description'), h('div', { class: 'prose max-w-[46rem]' }, paras(v.doc))) : null); - - const sections = [ - section('sv-atlas', 'SYSMOD Atlas', h('p', { class: 'ui text-muted m-0 mb-3' }, 'Which SYSMOD artifacts the project has. Click one to go there.'), atlas, - h('details', { class: 'sv-details', open: true }, h('summary', { class: 'ui' }, `Completeness: ${v.checks.filter((c) => c.status === 'passed').length} of ${v.checks.length}`), checks)), - section('sv-problem', 'Problem statement', v.problemStatement?.doc ? h('blockquote', { class: 'sv-quote' }, paras(v.problemStatement.doc)) : empty('No problem statement in the model.')), - section('sv-idea', 'System idea', - v.systemIdea ? [h('p', { class: 'ui m-0 mb-2' }, h('strong', {}, v.systemIdea.name), typesLine(v.systemIdea.types)), h('div', { class: 'prose max-w-[46rem]' }, paras(v.systemIdea.doc))] : empty('No system idea context in the model.'), - v.objectives.items.length ? [h('h4', { class: 'ui sv-h4' }, 'System objectives'), v.objectives.doc ? h('div', { class: 'prose max-w-[46rem] text-muted' }, paras(v.objectives.doc)) : null, - h('ul', { class: 'sv-list' }, v.objectives.items.map((o) => h('li', { style: `margin-left:${o.depth * 1.25}rem` }, h('strong', { class: 'ui' }, o.name), typesLine(o.types), paras(o.doc, 'm-0'))))] : null), - section('sv-stakeholders', 'Stakeholders', v.stakeholders.length ? table(['Stakeholder', 'Description', 'Risk', 'Effort', 'Categories', 'Contact'], - v.stakeholders.map((x) => h('tr', {}, - h('td', {}, h('strong', {}, x.name), x.owner ? [' ', tag('project owner')] : null, h('br'), h('span', { class: 'notation text-muted' }, x.element, x.types.length ? ` : ${x.types.join(', ')}` : '')), - h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.risk), h('td', {}, x.effort), h('td', {}, x.categories), h('td', {}, x.contact)))) : empty('No stakeholders in the model.')), - section('sv-needs', 'Stakeholder needs', v.needs.length ? table(['Need', 'Text', 'Stakeholders', 'Priority'], - v.needs.map((x) => h('tr', {}, - h('td', { style: x.depth ? `padding-left:${x.depth * 1.25}rem` : null }, h('strong', {}, x.name), h('br'), typesLine(x.types)), - h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.stakeholders), h('td', {}, x.priority)))) : empty('No stakeholder needs in the model.')), - section('sv-requirements', 'System requirements', - v.specification ? h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, v.specification.name, v.specification.types.length ? ` : ${v.specification.types[0]}` : '')) : null, - v.requirements.length ? table(['Requirement', 'Text', 'Obligation', 'Stability', 'Motivation', 'Stakeholders'], - v.requirements.map((x) => h('tr', {}, - h('td', { style: x.depth ? `padding-left:${x.depth * 1.25}rem` : null }, x.shortName ? h('span', { class: 'notation' }, `<${x.shortName}> `) : null, h('strong', {}, x.name), h('br'), typesLine(x.types)), - h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.obligation), h('td', {}, x.stability), h('td', { class: 'sv-text' }, x.motivation), h('td', {}, x.stakeholders)))) : empty('No system requirements in the model.')), - section('sv-usecases', 'System use cases', v.useCases.length ? h('div', { class: 'sv-cards' }, v.useCases.map((u) => h('article', { class: 'bk bk-usage sv-card' }, - h('div', { class: 'bk-head' }, h('p', { class: 'stereo m-0' }, 'use case'), h('h4', { class: 'bk-title sv-card-title' }, u.name), typesLine(u.types)), - h('div', { class: 'bk-comp' }, paras(u.doc, 'm-0'), - h('dl', { class: 'sv-dl' }, - [['Trigger', u.trigger], ['Result', u.result], ['Precondition', u.precondition], ['Postcondition', u.postcondition], ['Motivation', u.motivation], ['Actors', u.actors], ['Subject', u.subject]] - .filter(([, val]) => val).map(([k, val]) => [h('dt', {}, k), h('dd', {}, val)])), - u.steps.length ? h('details', {}, h('summary', { class: 'ui' }, `${u.steps.length} steps`), h('ol', { class: 'sv-steps notation' }, u.steps.map((st) => h('li', {}, st)))) : null)))) - : empty('No system use cases in the specification context.')), - ...v.contexts.map((c, i) => { - const def = core.CONTEXTS[i]; - return section(`sv-ctx-${def.key}`, def.title, c ? contextView(c) : empty(`No ${def.role} in the model.`)); - }), - v.featureTree ? section('sv-features', 'Feature tree', h('p', { class: 'ui text-muted m-0 mb-2' }, `${v.featureTree.name}${v.featureTree.language ? ` (${v.featureTree.language})` : ''}`), h('pre', { class: 'mc-src sv-pre' }, v.featureTree.body)) : null, - ]; - out.replaceChildren(head, ...sections.filter(Boolean)); - out.querySelector('h2')?.setAttribute('tabindex', '-1'); - out.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' }); + } catch (e) { + setStatus(fl.st, ''); + showError(fl.err, e); + } } + fl.input.addEventListener('change', openFiles); - // ---------- context diagram (SVG) ---------- - function contextView(c) { - const facts = h('p', { class: 'ui text-muted m-0 mb-3' }, - h('span', { class: 'notation' }, c.context.name, c.context.types.length ? ` : ${c.context.types[0]}` : ''), - ` · ${c.actors.length} actors · ${c.links.length} interfaces · ${c.system?.ports?.length || 0} system ports · ${c.parts.length} parts${c.systemImpl ? ' (white box)' : ''}`); - return [facts, h('figure', { class: 'sv-fig' }, diagram(c), h('figcaption', { class: 'sr-only' }, describe(c))), - c.context.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Description'), h('div', { class: 'prose max-w-[46rem]' }, paras(c.context.doc))) : null]; - } - const describe = (c) => `System context ${c.context.name}: system of interest ${c.system?.name || 'missing'}` - + `${c.parts.length ? ` with the parts ${c.parts.map((p) => p.name).join(', ')}` : ''}; actors ${c.actors.map((a) => `${a.name}${a.stereotypes.length ? ` (${a.stereotypes.join(', ')})` : ''}`).join(', ') || 'none'}` - + `${c.links.length ? `; interfaces ${c.links.map((l) => `${l.name || 'interface'}${l.actorPort || l.systemPort ? ` (${l.actorPort || '?'} to ${l.systemPort || '?'})` : ''}`).join(', ')}` : ''}.`; - - const clip = (text, n) => (text.length > n ? `${text.slice(0, n - 1)}…` : text); - function diagram(c) { - const W = 960, ACT_W = 180, ACT_H = 62, GAP = 26, PAD = 20, LANE = 140; - const left = [], right = []; - c.actors.forEach((a, i) => (i % 2 ? right : left).push(a)); - const rows = Math.max(left.length, right.length, 1); - const sysX = PAD + ACT_W + LANE, sysW = W - 2 * sysX; - const partCols = sysW > 300 ? 2 : 1, partW = (sysW - 36 - (partCols - 1) * 14) / partCols, partH = 40; - const partRows = Math.ceil(c.parts.length / partCols); - const sysInner = 64 + (partRows ? partRows * (partH + 12) + 6 : 10); - const actorsH = rows * ACT_H + (rows - 1) * GAP; - const H = Math.max(actorsH, sysInner) + 2 * PAD; - const sysY = PAD + Math.max(0, (H - 2 * PAD - sysInner) / 2), sysH = Math.max(sysInner, Math.min(H - 2 * PAD, sysInner + 40)); - const svg = s('svg', { viewBox: `0 0 ${W} ${H}`, class: 'sv-svg', role: 'img', 'aria-label': `Context diagram of ${c.context.name}` }); - // the system of interest - const sys = s('g', { class: 'sv-sys' }, - s('rect', { x: sysX, y: sysY, width: sysW, height: sysH, rx: 10 }), - s('text', { x: sysX + sysW / 2, y: sysY + 22, class: 'sv-st', 'text-anchor': 'middle' }, `«${(c.system?.stereotypes?.[0]) || 'system'}»`), - s('text', { x: sysX + sysW / 2, y: sysY + 42, class: 'sv-name', 'text-anchor': 'middle' }, s('title', {}, c.system?.name || ''), clip(c.system?.name || '(no system of interest)', 40))); - c.parts.forEach((p, i) => { - const col = i % partCols, row = Math.floor(i / partCols); - const x = sysX + 18 + col * (partW + 14), y = sysY + 60 + row * (partH + 12); - const label = `${p.name}${p.types[0] ? ` : ${p.types[0]}` : ''}${p.multiplicity ? ` [${p.multiplicity}]` : ''}`; - sys.append(s('g', { class: 'sv-part' }, s('title', {}, label), s('rect', { x, y, width: partW, height: partH, rx: 4 }), - s('text', { x: x + partW / 2, y: y + 25, 'text-anchor': 'middle' }, clip(label, Math.floor(partW / 7.2))))); - }); - // actors and their interfaces - const linkOf = new Map(); - for (const l of c.links) { if (!linkOf.has(l.actor)) linkOf.set(l.actor, []); linkOf.get(l.actor).push(l); } - const lines = s('g', { class: 'sv-lines' }), acts = s('g', {}), portsG = s('g', {}); - const place = (list, side) => list.forEach((a, i) => { - const off = (H - 2 * PAD - (list.length * ACT_H + (list.length - 1) * GAP)) / 2; - const x = side === 'left' ? PAD : W - PAD - ACT_W, y = PAD + off + i * (ACT_H + GAP); - const cy = y + ACT_H / 2, ax = side === 'left' ? x + ACT_W : x, sx = side === 'left' ? sysX : sysX + sysW; - const ls = linkOf.get(a.id) || []; - const names = ls.map((l) => l.name || 'interface'); - const sy = Math.min(Math.max(cy, sysY + 14), sysY + sysH - 14); - lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: sy, class: ls.length ? '' : 'sv-nolink' })); - if (ls.length) { - // the ports the interface connects: small squares on the borders, their names below the line - const ap = [...new Set(ls.map((l) => l.actorPort).filter(Boolean))].join(', '), sp = [...new Set(ls.map((l) => l.systemPort).filter(Boolean))].join(', '); - if (ap) portsG.append(s('rect', { x: ax - 4, y: cy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, `${a.name}.${ap}`))); - if (sp) portsG.append(s('rect', { x: sx - 4, y: sy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, `${c.system?.name || 'system'}.${sp}`))); - if (ap || sp) { - // two lines, left port above the right one, so that long names fit into the lane between the boxes - const [l, r] = side === 'left' ? [ap || '·', sp || '·'] : [sp || '·', ap || '·']; - const mx = (ax + sx) / 2, my = (cy + sy) / 2 + 15; - lines.append(s('text', { x: mx, y: my, 'text-anchor': 'middle', class: 'sv-portname' }, s('title', {}, `ports: ${l} ↔ ${r}`), - s('tspan', { x: mx, dy: 0 }, `${clip(l, 19)} ↔`), s('tspan', { x: mx, dy: 12 }, clip(r, 19)))); - } - } - if (ls.length) { - // long names on two lines, broken at a word boundary of the camelCase name (operator|Interface) - const label = names.join(', '); - let parts = [label]; - if (label.length > 18) { - const cuts = [...label.matchAll(/(?<=[a-z0-9])(?=[A-Z])|(?<=[,_ -])/g)].map((m) => m.index).filter((i) => i > 2 && i < label.length - 2); - const cut = cuts.sort((a, b) => Math.abs(a - label.length / 2) - Math.abs(b - label.length / 2))[0]; - parts = cut ? [label.slice(0, cut).trim(), label.slice(cut).trim()] : [label]; - } - lines.append(s('text', { x: (ax + sx) / 2, y: cy - 8 - (parts.length - 1) * 13, 'text-anchor': 'middle', class: 'sv-ifc' }, s('title', {}, label), - parts.map((t, i) => s('tspan', { x: (ax + sx) / 2, dy: i ? 13 : 0 }, clip(t, 19))))); - } - const st = a.stereotypes[0] || 'actor'; - const g = s('g', { class: `sv-actor sv-${st}` }, s('title', {}, `${a.name}${a.types.length ? ` : ${a.types.join(', ')}` : ''}${a.doc ? `\n${a.doc}` : ''}`)); - // every actor is a box, so that the line meets it; a «user» gets a small stick figure in it - const fig = st === 'user' ? 22 : 0, tx = x + fig + (ACT_W - fig) / 2; - g.append(s('rect', { x, y, width: ACT_W, height: ACT_H, rx: st === 'environmentalEffect' ? 28 : 4 })); - if (fig) { - const fx = x + 18, fy = y + 13; - g.append(s('circle', { cx: fx, cy: fy, r: 5 }), s('path', { class: 'sv-fig-line', d: `M${fx} ${fy + 5}v15M${fx - 8} ${fy + 11}h16M${fx} ${fy + 20}l-7 12M${fx} ${fy + 20}l7 12` })); - } - g.append(s('text', { x: tx, y: y + 24, 'text-anchor': 'middle', class: 'sv-st' }, `«${st}»`), - s('text', { x: tx, y: y + 44, 'text-anchor': 'middle', class: 'sv-name' }, clip(a.name, fig ? 18 : 21))); - acts.append(g); - }); - place(left, 'left'); place(right, 'right'); - svg.append(lines, sys, acts, portsG); - if (!c.actors.length) svg.append(s('text', { x: PAD, y: PAD + 14, class: 'sv-st' }, 'no actors')); - return svg; + // ---------- start ---------- + if (params.get('example') === 'drone' && ex.btn && cfg.engine) { + showTab('example'); + await openExample(); } +} - // ---------- start ---------- - if (params.get('example') === 'drone' && ex.btn && cfg.engine) { showTab('example'); ex.btn.click(); } +const viewerRoot = document.getElementById('sysmod-viewer'); +if (viewerRoot) { + start(viewerRoot, JSON.parse(viewerRoot.dataset.config)).catch((e) => { + viewerRoot.querySelector('[data-out]')?.replaceChildren(errorBox(e)); + console.error(e); + }); } From c371c24402865b2947437f7811850cbd13e5ad12 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 22:31:16 +0100 Subject: [PATCH 6/9] web: remaining SonarCloud and CodeQL findings of PR #10 - promises of event handlers are voided; nextUrl at module scope - no await in loops: pages are read recursively, JSON files with Promise.all - reduce() with an initial value; instead of role=status - serve.py: except OSError (URLError and TimeoutError are OSErrors); no clear-text URL in the start message - test server: Link header from its own address, not from the Host header Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- tests/test_web_serve.py | 2 +- web/index.html | 4 ++-- web/serve.py | 5 ++--- web/sysmod-viewer-api.js | 48 +++++++++++++++++++++------------------- web/sysmod-viewer.js | 27 +++++++++++----------- 5 files changed, 43 insertions(+), 43 deletions(-) diff --git a/tests/test_web_serve.py b/tests/test_web_serve.py index 3fa178a..af0ee51 100644 --- a/tests/test_web_serve.py +++ b/tests/test_web_serve.py @@ -33,7 +33,7 @@ def do_GET(self): if u.path == "/projects": return self.send(200, [{"@id": "p-1", "name": "P", "auth": self.headers.get("Authorization", ""), "query": u.query}]) if u.path == "/projects/p-1/commits/c/elements": - return self.send(200, [{"@id": "e-1"}], {"Link": f"; rel=\"next\""}) + return self.send(200, [{"@id": "e-1"}], {"Link": f"; rel=\"next\""}) if u.path == "/projects/redirect": self.send_response(302); self.send_header("Location", "https://example.org/"); self.end_headers(); return if u.path == "/projects/html": diff --git a/web/index.html b/web/index.html index 01bed56..e369ff0 100644 --- a/web/index.html +++ b/web/index.html @@ -43,7 +43,7 @@

    Open a model

    - +

    diff --git a/web/serve.py b/web/serve.py index 9a27fb2..75787fc 100644 --- a/web/serve.py +++ b/web/serve.py @@ -219,7 +219,7 @@ def fetch(target, auth): if 300 <= e.code < 400: raise RelayError(502, "the server answered with a redirect, which the relay does not follow") from None status, body, rh = e.code, e.read(MAX_BYTES + 1), e.headers - except (urllib.error.URLError, TimeoutError, OSError) as e: + except OSError as e: # URLError and TimeoutError are OSErrors if "timed out" in str(e).lower(): raise RelayError(504, "the server did not answer in time") from None raise RelayError(502, "the server could not be reached") from None @@ -243,8 +243,7 @@ def main(): ap.add_argument("--host", default="127.0.0.1", help="default 127.0.0.1: only this computer can use the relay") a = ap.parse_args() server = ThreadingHTTPServer((a.host, a.port), Handler) - page = urllib.parse.urlunsplit(("http", f"localhost:{a.port}", "/", "", "")) # local only: the server listens on 127.0.0.1 - print(f"SYSMOD viewer: {page} (Ctrl+C to stop)") + print(f"SYSMOD viewer on port {a.port} of {a.host}: open localhost:{a.port} in the browser (Ctrl+C to stop)") print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: server.serve_forever() diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js index a9f36eb..59479d9 100644 --- a/web/sysmod-viewer-api.js +++ b/web/sysmod-viewer-api.js @@ -114,6 +114,15 @@ function itemsOf(body) { return Array.isArray(body?.elements) ? body.elements : null; } +/** The address of the next page, or null: from the Link header, else page[after]= if the page was full */ +function nextUrl({ link, url, items, fresh, size, first }) { + if (!fresh) return null; + const next = nextFromLink(link); + if (next) return new URL(next, url).href; + const last = items.at(-1)?.['@id']; + return items.length >= size && last ? first + '&page%5Bafter%5D=' + encodeURIComponent(last) : null; +} + export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) const base = normalizeBaseUrl(baseUrl); @@ -187,31 +196,24 @@ export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn async function list(path, { signal, onProgress, size = pageSize } = {}) { const sep = path.includes('?') ? '&' : '?'; const first = base + path + sep + 'page%5Bsize%5D=' + size; - const pageAfter = (id) => first + '&page%5Bafter%5D=' + encodeURIComponent(id); - let url = first; - const out = [], seen = new Set(); - for (let page = 0; page < 10000 && url; page++) { - const { body, link } = await get(url, signal); - const items = itemsOf(body); - if (!items) throw new ApiError('The server did not answer with a list.', { url, hint: 'Is this the address of a SysML v2 API server?' }); - const fresh = items.filter((it) => !seen.has(it?.['@id'])); - for (const it of fresh) { - if (it?.['@id']) seen.add(it['@id']); - } - out.push(...fresh); - onProgress?.(out.length); - url = nextUrl({ link, url, items, fresh: fresh.length, size, pageAfter }); - } - return out; + const paging = { first, size, signal, onProgress, out: [], seen: new Set() }; + await readPages(first, paging, 0); + return paging.out; } - /** The address of the next page, or null: from the Link header, else page[after]= if the page was full */ - function nextUrl({ link, url, items, fresh, size, pageAfter }) { - if (!fresh) return null; - const next = nextFromLink(link); - if (next) return new URL(next, url).href; - const last = items.at(-1)?.['@id']; - return items.length >= size && last ? pageAfter(last) : null; + /** Reads the page at url and, one after the other, the pages after it (at most 10000) */ + async function readPages(url, paging, page) { + if (!url || page >= 10000) return; + const { body, link } = await get(url, paging.signal); + const items = itemsOf(body); + if (!items) throw new ApiError('The server did not answer with a list.', { url, hint: 'Is this the address of a SysML v2 API server?' }); + const fresh = items.filter((it) => !paging.seen.has(it?.['@id'])); + for (const it of fresh) { + if (it?.['@id']) paging.seen.add(it['@id']); + } + paging.out.push(...fresh); + paging.onProgress?.(paging.out.length); + await readPages(nextUrl({ link, url, items, fresh: fresh.length, size: paging.size, first: paging.first }), paging, page + 1); } const time = (c) => Date.parse(c.created || c.timestamp || '') || 0; diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js index 2ab3511..37e8970 100644 --- a/web/sysmod-viewer.js +++ b/web/sysmod-viewer.js @@ -116,14 +116,13 @@ async function elementsFromSources(engine, files, statusEl) { /** The elements of .json files (arrays of elements, or { elements: [...] }) */ async function elementsFromJsonFiles(files) { - const elements = []; - for (const file of files) { - const data = JSON.parse(await file.text()); + const texts = await Promise.all([...files].map((file) => file.text())); + return texts.flatMap((text, i) => { + const data = JSON.parse(text); const list = Array.isArray(data) ? data : data?.elements; - if (!Array.isArray(list)) throw withHint(file.name + ' is not a list of elements.', 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.'); - elements.push(...list); - } - return elements; + if (!Array.isArray(list)) throw withHint(files[i].name + ' is not a list of elements.', 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.'); + return list; + }); } // ---------- rendering of a SYSMOD project ---------- @@ -311,7 +310,7 @@ function splitLabel(label) { const cuts = [...label.matchAll(/(?<=[a-z0-9])(?=[A-Z])|(?<=[,_ -])/g)].map((m) => m.index).filter((i) => i > 2 && i < label.length - 2); if (!cuts.length) return [label]; const middle = label.length / 2; - const cut = cuts.reduce((best, i) => (Math.abs(i - middle) < Math.abs(best - middle) ? i : best)); + const cut = cuts.reduce((best, i) => (Math.abs(i - middle) < Math.abs(best - middle) ? i : best), cuts[0]); return [label.slice(0, cut).trim(), label.slice(cut).trim()]; } @@ -510,7 +509,7 @@ async function start(root, cfg) { showError(f.err, e); } } - f.connect.addEventListener('click', connect); + f.connect.addEventListener('click', () => void connect()); f.url.addEventListener('keydown', (e) => { if (e.key === 'Enter') f.connect.click(); }); @@ -525,9 +524,9 @@ async function start(root, cfg) { f.projFilter.addEventListener('input', () => { const before = f.proj.value; fillProjects(); - if (f.proj.value !== before) loadCommits(); + if (f.proj.value !== before) void loadCommits(); }); - f.proj.addEventListener('change', () => loadCommits()); + f.proj.addEventListener('change', () => void loadCommits()); async function defaultHead(pid) { try { @@ -583,7 +582,7 @@ async function start(root, cfg) { f.load.disabled = false; } } - f.load.addEventListener('click', loadModel); + f.load.addEventListener('click', () => void loadModel()); // ---------- 2. + 3. The example and files ---------- let manifestPromise = null; @@ -616,7 +615,7 @@ async function start(root, cfg) { ex.btn.disabled = false; } } - ex.btn?.addEventListener('click', openExample); + ex.btn?.addEventListener('click', () => void openExample()); /** .sysml files, read together with the SYSMOD library (unless the visitor brings it along) */ async function elementsFromSysmlFiles(files, statusEl) { @@ -646,7 +645,7 @@ async function start(root, cfg) { showError(fl.err, e); } } - fl.input.addEventListener('change', openFiles); + fl.input.addEventListener('change', () => void openFiles()); // ---------- start ---------- if (params.get('example') === 'drone' && ex.btn && cfg.engine) { From 2f4834c714fb89d095f9b23477f7a0e6ff011fb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:59:40 +0100 Subject: [PATCH 7/9] web/serve.py: mark the plain-HTTP local server as reviewed for SonarCloud (S5332) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- web/serve.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/serve.py b/web/serve.py index 75787fc..45ff9f8 100644 --- a/web/serve.py +++ b/web/serve.py @@ -246,7 +246,7 @@ def main(): print(f"SYSMOD viewer on port {a.port} of {a.host}: open localhost:{a.port} in the browser (Ctrl+C to stop)") print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: - server.serve_forever() + server.serve_forever() # NOSONAR: plain HTTP on purpose, local development server (127.0.0.1 by default) except KeyboardInterrupt: pass From 1c7595fa2165766b06ec8df3ed96ba1e53310957 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:03:21 +0100 Subject: [PATCH 8/9] web/serve.py: correct syntax of the SonarCloud suppression comment (NOSONAR(python:S5332)) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- web/serve.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/serve.py b/web/serve.py index 45ff9f8..a43ed5a 100644 --- a/web/serve.py +++ b/web/serve.py @@ -246,7 +246,8 @@ def main(): print(f"SYSMOD viewer on port {a.port} of {a.host}: open localhost:{a.port} in the browser (Ctrl+C to stop)") print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: - server.serve_forever() # NOSONAR: plain HTTP on purpose, local development server (127.0.0.1 by default) + # Plain HTTP on purpose: a local development server (127.0.0.1 by default). + server.serve_forever() # NOSONAR(python:S5332) except KeyboardInterrupt: pass From 23aaebb23b8e159d7c1db37504295b84229bc8cc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:06:26 +0100 Subject: [PATCH 9/9] web/serve.py: plain NOSONAR marker for the local HTTP server Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H3jemrqbQnRXB9jiZkhv1r --- web/serve.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/serve.py b/web/serve.py index a43ed5a..ea7f89f 100644 --- a/web/serve.py +++ b/web/serve.py @@ -247,7 +247,7 @@ def main(): print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) try: # Plain HTTP on purpose: a local development server (127.0.0.1 by default). - server.serve_forever() # NOSONAR(python:S5332) + server.serve_forever() # NOSONAR except KeyboardInterrupt: pass