Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(web): expand artifact preview and download support

xiaoyao424ae4a8ae08d9
diff --git a/jiuwenswarm/channels/desktop/desktop_app.py b/jiuwenswarm/channels/desktop/desktop_app.py
index 25df6f8c15..95f6a276fe 100644
--- a/jiuwenswarm/channels/desktop/desktop_app.py
+++ b/jiuwenswarm/channels/desktop/desktop_app.py
@@ -12,6 +12,7 @@ import signal
import socket
import subprocess
import sys
+import tempfile
import threading
import time
from pathlib import Path
@@ -394,8 +395,8 @@ class _WindowApi:
def install_update(self, installer_path: str) -> bool:
return self._runtime.install_update(installer_path)
- def download_file(self, url: str, filename: str) -> bool:
- """通过 webview 下载文件,解决 exe 中无法使用 <a> 标签下载的问题。"""
+ def download_file(self, url: str, filename: str) -> DesktopSaveResult:
+ """通过 webview 下载文件,解决桌面端无法使用 <a> 标签下载的问题。"""
# 如果是相对路径,拼接完整的 URL(使用前端 web server 端口)
if url.startswith("/"):
full_url = f"http://{self._runtime.frontend_host}:{self._runtime.frontend_port}{url}"
@@ -497,41 +498,48 @@ class DesktopRuntime:
threading.Thread(target=_delayed_destroy, daemon=True).start()
return True
- def download_file(self, url: str, filename: str) -> bool:
- """下载文件到用户下载目录(异步执行,避免阻塞 UI)。"""
- def _download() -> None:
- try:
- import urllib.request
-
- # 获取下载目录
- download_dir = Path.home() / "Downloads"
- if not download_dir.exists():
- download_dir.mkdir(parents=True, exist_ok=True)
-
- safe_name = Path(filename).name
- if not safe_name:
- raise ValueError("empty_filename")
-
- # 处理文件名冲突
- target_path = download_dir / safe_name
- if target_path.exists():
- base, ext = Path(safe_name).stem, Path(safe_name).suffix
- counter = 1
- while target_path.exists():
- target_path = download_dir / f"{base} ({counter}){ext}"
- counter += 1
-
- # 下载文件
- urllib.request.urlretrieve(url, target_path)
- logger.info("[desktop] file downloaded to: %s", target_path)
-
- # 下载完成后提醒用户并打开文件
- self._show_download_complete(str(target_path))
- except Exception as exc: # noqa: BLE001
- logger.error("[desktop] download failed: %s", exc)
+ def download_file(self, url: str, filename: str) -> DesktopSaveResult:
+ """选择保存位置并在实际写入完成后返回结果。"""
+ try:
+ target_path = self._select_save_path(filename, ())
+ except (OSError, RuntimeError, ValueError) as exc:
+ logger.error("[desktop] failed to select download path: %s", exc)
+ return _desktop_save_result(False)
- threading.Thread(target=_download, daemon=True).start()
- return True
+ if target_path is None:
+ logger.info("[desktop] file download cancelled by user")
+ return _desktop_save_result(False, cancelled=True)
+
+ temp_path: Path | None = None
+ try:
+ import urllib.request
+
+ temp_fd, temp_name = tempfile.mkstemp(
+ dir=target_path.parent,
+ prefix=f".{target_path.name}.",
+ suffix=".part",
+ )
+ os.close(temp_fd)
+ temp_path = Path(temp_name)
+ urllib.request.urlretrieve(url, temp_path)
+ os.replace(temp_path, target_path)
+ temp_path = None
+ logger.info("[desktop] file downloaded to: %s", target_path)
+ except Exception as exc: # noqa: BLE001
+ logger.error("[desktop] download failed: %s", exc)
+ if temp_path is not None:
+ try:
+ temp_path.unlink(missing_ok=True)
+ except OSError as cleanup_exc:
+ logger.warning(
+ "[desktop] failed to remove partial download %s: %s",
+ temp_path,
+ cleanup_exc,
+ )
+ return _desktop_save_result(False)
+
+ self._show_download_complete(str(target_path))
+ return _desktop_save_result(True)
@staticmethod
def _sanitize_filename(filename: str) -> str:
diff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.py
index a57b7b7716..ad709db0fa 100644
--- a/jiuwenswarm/channels/web/app_web.py
+++ b/jiuwenswarm/channels/web/app_web.py
@@ -139,6 +139,39 @@ def _generate_agent_data(project_root: Path) -> None:
)
+def _parse_single_byte_range(
+ range_header: str,
+ file_size: int,
+) -> tuple[int, int] | None:
+ """Parse one HTTP byte range, returning inclusive start and end offsets."""
+ if file_size == 0 or not range_header.startswith("bytes=") or "," in range_header:
+ return None
+
+ range_value = range_header[6:]
+ if "-" not in range_value:
+ return None
+
+ start_text, end_text = range_value.split("-", 1)
+ if not start_text:
+ if not end_text.isascii() or not end_text.isdecimal():
+ return None
+ suffix_length = int(end_text)
+ if suffix_length <= 0:
+ return None
+ return max(0, file_size - suffix_length), file_size - 1
+
+ if not start_text.isascii() or not start_text.isdecimal():
+ return None
+ if end_text and (not end_text.isascii() or not end_text.isdecimal()):
+ return None
+
+ start = int(start_text)
+ end = int(end_text) if end_text else file_size - 1
+ if start >= file_size or end < start:
+ return None
+ return start, min(end, file_size - 1)
+
+
class _SpaStaticHandler(SimpleHTTPRequestHandler):
"""Static file handler with SPA fallback to index.html."""
@@ -934,24 +967,50 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):
if not mime_type:
mime_type = "application/octet-stream"
- self.send_response(200)
+ range_header = self.headers.get("Range")
+ byte_range = None
+ if range_header:
+ byte_range = _parse_single_byte_range(range_header, file_size)
+ if byte_range is None:
+ self.send_response(416)
+ self.send_header("Content-Range", f"bytes */{file_size}")
+ self.end_headers()
+ return
+
+ start, end = byte_range or (0, max(0, file_size - 1))
+ content_length = 0 if file_size == 0 else end - start + 1
+ self.send_response(206 if byte_range is not None else 200)
self.send_header("Content-Type", mime_type)
- self.send_header("Content-Length", str(file_size))
+ self.send_header("Content-Length", str(content_length))
+ self.send_header("Accept-Ranges", "bytes")
encoded_name = quote(file_name, safe="")
+ disposition = (
+ "inline"
+ if query.get("inline", "").lower() in {"1", "true"}
+ else "attachment"
+ )
self.send_header(
"Content-Disposition",
- f"attachment; filename*=UTF-8''{encoded_name}",
+ f"{disposition}; filename*=UTF-8''{encoded_name}",
)
self.send_header("Cache-Control", "no-store")
+ if byte_range is not None:
+ self.send_header(
+ "Content-Range",
+ f"bytes {start}-{end}/{file_size}",
+ )
self.end_headers()
if self.command != "HEAD":
with open(file_path, "rb") as f:
- while True:
- chunk = f.read(65536)
+ f.seek(start)
+ remaining = content_length
+ while remaining > 0:
+ chunk = f.read(min(65536, remaining))
if not chunk:
break
self.wfile.write(chunk)
+ remaining -= len(chunk)
except Exception as exc:
self.log_error("file download error: %s", exc)
try:
diff --git a/jiuwenswarm/channels/web/frontend/.prettierrc.cjs b/jiuwenswarm/channels/web/frontend/.prettierrc.cjs
index 438d7fe1b4..9d543c8612 100644
--- a/jiuwenswarm/channels/web/frontend/.prettierrc.cjs
+++ b/jiuwenswarm/channels/web/frontend/.prettierrc.cjs
@@ -5,7 +5,7 @@ module.exports = {
semi: true,
singleQuote: true,
jsxSingleQuote: false,
- trailingComma: 'es5',
+ trailingComma: 'all',
bracketSpacing: true,
arrowParens: 'avoid',
proseWrap: 'preserve',
diff --git a/jiuwenswarm/channels/web/frontend/package-lock.json b/jiuwenswarm/channels/web/frontend/package-lock.json
index 7b3c93edd9..be82ab63be 100644
--- a/jiuwenswarm/channels/web/frontend/package-lock.json
+++ b/jiuwenswarm/channels/web/frontend/package-lock.json
@@ -10,11 +10,30 @@
"dependencies": {
"@a2ui/react": "0.8.0",
"@a2ui/web_core": "0.8.0",
+ "@codemirror/lang-cpp": "6.0.3",
+ "@codemirror/lang-css": "6.3.1",
+ "@codemirror/lang-go": "6.0.1",
+ "@codemirror/lang-java": "6.0.2",
+ "@codemirror/lang-javascript": "6.2.5",
+ "@codemirror/lang-php": "6.0.2",
+ "@codemirror/lang-python": "6.2.1",
+ "@codemirror/lang-rust": "6.0.2",
+ "@codemirror/lang-sql": "6.10.0",
+ "@codemirror/lang-vue": "0.1.3",
+ "@codemirror/lang-xml": "6.1.0",
+ "@codemirror/lang-yaml": "6.1.3",
+ "@codemirror/language": "6.12.4",
+ "@codemirror/legacy-modes": "6.5.3",
+ "@codemirror/state": "6.7.1",
+ "@codemirror/view": "6.43.7",
"@tailwindcss/typography": "^0.5.19",
"clsx": "^2.1.0",
+ "docx-preview": "0.3.7",
+ "exceljs": "4.4.0",
"html-to-image": "1.11.13",
"i18next": "^25.8.18",
"i18next-browser-languagedetector": "^8.2.1",
+ "jszip": "3.10.1",
"lucide-react": "1.16.0",
"mermaid": "11.15.0",
"qrcode.react": "^4.2.0",
@@ -23,6 +42,8 @@
"react-i18next": "^16.5.8",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
+ "saxes": "5.0.1",
+ "ssf": "0.11.2",
"zustand": "^4.5.0"
},
"devDependencies": {
@@ -38,6 +59,7 @@
"eslint-plugin-react-refresh": "^0.4.0",
"postcss": "^8.4.0",
"prettier": "^3.3.3",
+ "rollup": "4.57.1",
"tailwindcss": "^3.4.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
@@ -98,13 +120,13 @@
}
},
"node_modules/@babel/code-frame": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
- "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-validator-identifier": "^7.28.5",
+ "@babel/helper-validator-identifier": "^7.29.7",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
@@ -113,9 +135,9 @@
}
},
"node_modules/@babel/compat-data": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",
- "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -123,21 +145,21 @@
}
},
"node_modules/@babel/core": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
- "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-compilation-targets": "^7.28.6",
- "@babel/helper-module-transforms": "^7.28.6",
- "@babel/helpers": "^7.28.6",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/traverse": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/remapping": "^2.3.5",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
@@ -164,14 +186,14 @@
}
},
"node_modules/@babel/generator": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.0.tgz",
- "integrity": "sha512-vSH118/wwM/pLR38g/Sgk05sNtro6TlTJKuiMXDaZqPUfjTFcudpCOt00IhOfj+1BFAX+UFAlzCU+6WXr3GLFQ==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz",
+ "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/parser": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/gen-mapping": "^0.3.12",
"@jridgewell/trace-mapping": "^0.3.28",
"jsesc": "^3.0.2"
@@ -181,14 +203,14 @@
}
},
"node_modules/@babel/helper-compilation-targets": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
- "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/compat-data": "^7.28.6",
- "@babel/helper-validator-option": "^7.27.1",
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
@@ -208,9 +230,9 @@
}
},
"node_modules/@babel/helper-globals": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
- "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -218,29 +240,29 @@
}
},
"node_modules/@babel/helper-module-imports": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",
- "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/traverse": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-transforms": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",
- "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-module-imports": "^7.28.6",
- "@babel/helper-validator-identifier": "^7.28.5",
- "@babel/traverse": "^7.28.6"
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -250,9 +272,9 @@
}
},
"node_modules/@babel/helper-plugin-utils": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz",
- "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+ "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -260,9 +282,9 @@
}
},
"node_modules/@babel/helper-string-parser": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
- "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -270,9 +292,9 @@
}
},
"node_modules/@babel/helper-validator-identifier": {
- "version": "7.28.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
- "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -280,9 +302,9 @@
}
},
"node_modules/@babel/helper-validator-option": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
- "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -290,27 +312,27 @@
}
},
"node_modules/@babel/helpers": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.6.tgz",
- "integrity": "sha512-xOBvwq86HHdB7WUDTfKfT/Vuxh7gElQ+Sfti2Cy6yIWNW05P8iUslOVcZ4/sKbE+/jQaukQAdz/gf3724kYdqw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz",
- "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
+ "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.0"
+ "@babel/types": "^7.29.7"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -320,13 +342,13 @@
}
},
"node_modules/@babel/plugin-transform-react-jsx-self": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz",
- "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
+ "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-plugin-utils": "^7.27.1"
+ "@babel/helper-plugin-utils": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -336,13 +358,13 @@
}
},
"node_modules/@babel/plugin-transform-react-jsx-source": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz",
- "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
+ "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-plugin-utils": "^7.27.1"
+ "@babel/helper-plugin-utils": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -352,42 +374,42 @@
}
},
"node_modules/@babel/runtime": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz",
- "integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
- "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.28.6",
- "@babel/parser": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",
- "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz",
+ "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-globals": "^7.28.0",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0",
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7",
"debug": "^4.3.1"
},
"engines": {
@@ -395,14 +417,14 @@
}
},
"node_modules/@babel/types": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
- "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
+ "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-string-parser": "^7.27.1",
- "@babel/helper-validator-identifier": "^7.28.5"
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -420,6 +442,244 @@
"integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==",
"license": "Apache-2.0"
},
+ "node_modules/@codemirror/autocomplete": {
+ "version": "6.20.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
+ "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-cpp": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz",
+ "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/cpp": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-css": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
+ "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.2",
+ "@lezer/css": "^1.1.7"
+ }
+ },
+ "node_modules/@codemirror/lang-go": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-go/-/lang-go-6.0.1.tgz",
+ "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.6.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/go": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-html": {
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
+ "integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/lang-css": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.0.0",
+ "@codemirror/language": "^6.4.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/css": "^1.1.0",
+ "@lezer/html": "^1.3.12"
+ }
+ },
+ "node_modules/@codemirror/lang-java": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz",
+ "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/java": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-javascript": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
+ "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.6.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/javascript": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-php": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-php/-/lang-php-6.0.2.tgz",
+ "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/php": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-python": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz",
+ "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.3.2",
+ "@codemirror/language": "^6.8.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.1",
+ "@lezer/python": "^1.1.4"
+ }
+ },
+ "node_modules/@codemirror/lang-rust": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz",
+ "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/rust": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-sql": {
+ "version": "6.10.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz",
+ "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-vue": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz",
+ "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/lang-html": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.1.2",
+ "@codemirror/language": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.1"
+ }
+ },
+ "node_modules/@codemirror/lang-xml": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz",
+ "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.4.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/xml": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-yaml": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz",
+ "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.2.0",
+ "@lezer/lr": "^1.0.0",
+ "@lezer/yaml": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/language": {
+ "version": "6.12.4",
+ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
+ "integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.23.0",
+ "@lezer/common": "^1.5.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0",
+ "style-mod": "^4.0.0"
+ }
+ },
+ "node_modules/@codemirror/legacy-modes": {
+ "version": "6.5.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/legacy-modes/-/legacy-modes-6.5.3.tgz",
+ "integrity": "sha512-xCsmIzH78MyWkib9jlPaaun57XNkfbMIhagfaZVd0iLTqlpw3jXaIcbZm72MTmmn64eTZpBVNjbyYh+QXnxRsg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0"
+ }
+ },
+ "node_modules/@codemirror/lint": {
+ "version": "6.9.7",
+ "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
+ "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.42.0",
+ "crelt": "^1.0.5"
+ }
+ },
+ "node_modules/@codemirror/state": {
+ "version": "6.7.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.1.tgz",
+ "integrity": "sha512-9QzNDgE4EYDnAHfrTlR2lwiPciiOymLtwKK+8yHQzCc7GXhAP9xdEbEJFy2IWB1j9UGUl9BsgMmTo/ImA02T7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@marijn/find-cluster-break": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/view": {
+ "version": "6.43.7",
+ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.7.tgz",
+ "integrity": "sha512-FZsExxkoxnAN+d9TgqXLg5g4A1oQwzX9WlkOT5i2PKkcW7xx3Bmu0vs90g6fo9Mpdsb/l96dnAraQ8932aO4/g==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.7.0",
+ "crelt": "^1.0.6",
+ "style-mod": "^4.1.0",
+ "w3c-keyname": "^2.2.4"
+ }
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -812,9 +1072,9 @@
}
},
"node_modules/@eslint-community/eslint-utils": {
- "version": "4.9.1",
- "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
- "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",
+ "version": "4.10.1",
+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
+ "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -865,9 +1125,9 @@
}
},
"node_modules/@eslint/eslintrc/node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
+ "version": "1.1.17",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.17.tgz",
+ "integrity": "sha512-w+aeW/mkgM4PyRMOJCgi3fOrTm5Q8QY1OSfn2TO2iuDj3ezIHqejmuxbjfPrqUkgqRew1iqkyAn0tr0ZwHD9+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -876,9 +1136,9 @@
}
},
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -898,6 +1158,47 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
+ "node_modules/@fast-csv/format": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz",
+ "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^14.0.1",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.isboolean": "^3.0.3",
+ "lodash.isequal": "^4.5.0",
+ "lodash.isfunction": "^3.0.9",
+ "lodash.isnil": "^4.0.0"
+ }
+ },
+ "node_modules/@fast-csv/format/node_modules/@types/node": {
+ "version": "14.18.63",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz",
+ "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==",
+ "license": "MIT"
+ },
+ "node_modules/@fast-csv/parse": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz",
+ "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^14.0.1",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.groupby": "^4.6.0",
+ "lodash.isfunction": "^3.0.9",
+ "lodash.isnil": "^4.0.0",
+ "lodash.isundefined": "^3.0.1",
+ "lodash.uniq": "^4.5.0"
+ }
+ },
+ "node_modules/@fast-csv/parse/node_modules/@types/node": {
+ "version": "14.18.63",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz",
+ "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==",
+ "license": "MIT"
+ },
"node_modules/@humanwhocodes/config-array": {
"version": "0.13.0",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
@@ -915,9 +1216,9 @@
}
},
"node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
+ "version": "1.1.17",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.17.tgz",
+ "integrity": "sha512-w+aeW/mkgM4PyRMOJCgi3fOrTm5Q8QY1OSfn2TO2iuDj3ezIHqejmuxbjfPrqUkgqRew1iqkyAn0tr0ZwHD9+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -926,9 +1227,9 @@
}
},
"node_modules/@humanwhocodes/config-array/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -967,9 +1268,9 @@
"license": "MIT"
},
"node_modules/@iconify/utils": {
- "version": "3.1.3",
- "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.3.tgz",
- "integrity": "sha512-LPKOXPn/zV+zis1oOfGWogaXVpqUybF3ZS6SCZIsz8vg0ivVp9+fVqyYB7xq0aiST/VhUQYGO1qo6uoYSiEJqw==",
+ "version": "3.1.4",
+ "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.4.tgz",
+ "integrity": "sha512-b1S7B1k9ohZ+iNTi2ATxbRYG9fTrJmUT0rc46bvVnNxqNRGW7dyo/vRREwyniI5IRN2RSJHDcm+s3BjWrSAjHw==",
"license": "MIT",
"dependencies": {
"@antfu/install-pkg": "^1.1.0",
@@ -1023,13 +1324,164 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@lezer/common": {
+ "version": "1.5.2",
+ "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
+ "integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
+ "license": "MIT"
+ },
+ "node_modules/@lezer/cpp": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@lezer/cpp/-/cpp-1.1.6.tgz",
+ "integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/css": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.4.tgz",
+ "integrity": "sha512-N+tn9tej2hPvyKgHEApMOQfHczDJCwxrRFS3SPn9QjYN+uwHvEDnCgKRrb3mxDYxRS8sKMM8fhC3+lc04Abz5Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/go": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@lezer/go/-/go-1.0.1.tgz",
+ "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/highlight": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
+ "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/html": {
+ "version": "1.3.13",
+ "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
+ "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/java": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.3.tgz",
+ "integrity": "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/javascript": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
+ "integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.1.3",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/lr": {
+ "version": "1.4.10",
+ "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
+ "integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/php": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@lezer/php/-/php-1.0.5.tgz",
+ "integrity": "sha512-W7asp9DhM6q0W6DYNwIkLSKOvxlXRrif+UXBMxzsJUuqmhE7oVU+gS3THO4S/Puh7Xzgm858UNaFi6dxTP8dJA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.1.0"
+ }
+ },
+ "node_modules/@lezer/python": {
+ "version": "1.1.19",
+ "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz",
+ "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/rust": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@lezer/rust/-/rust-1.0.2.tgz",
+ "integrity": "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/xml": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/@lezer/xml/-/xml-1.0.6.tgz",
+ "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/yaml": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@lezer/yaml/-/yaml-1.0.4.tgz",
+ "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.4.0"
+ }
+ },
+ "node_modules/@marijn/find-cluster-break": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",
+ "integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",
+ "license": "MIT"
+ },
"node_modules/@mermaid-js/parser": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.1.tgz",
- "integrity": "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==",
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.2.0.tgz",
+ "integrity": "sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==",
"license": "MIT",
"dependencies": {
- "@chevrotain/types": "~11.1.1"
+ "@chevrotain/types": "~11.1.2"
}
},
"node_modules/@nodelib/fs.scandir": {
@@ -1686,28 +2138,15 @@
}
},
"node_modules/@tailwindcss/typography": {
- "version": "0.5.19",
- "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.19.tgz",
- "integrity": "sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==",
+ "version": "0.5.20",
+ "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.20.tgz",
+ "integrity": "sha512-hwbzQuNUfcPvbegQFatVPl/MY/tcM9KLl963hQ5laJKPh81TEZ1+dNG9PirGvcaDBkp+BCshExAyKVPW91dozw==",
"license": "MIT",
"dependencies": {
"postcss-selector-parser": "6.0.10"
},
"peerDependencies": {
- "tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1"
- }
- },
- "node_modules/@tailwindcss/typography/node_modules/postcss-selector-parser": {
- "version": "6.0.10",
- "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",
- "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",
- "license": "MIT",
- "dependencies": {
- "cssesc": "^3.0.0",
- "util-deprecate": "^1.0.2"
- },
- "engines": {
- "node": ">=4"
+ "tailwindcss": ">=3.0.0 || >=4.0.0 || insiders"
}
},
"node_modules/@types/babel__core": {
@@ -1936,9 +2375,9 @@
"license": "MIT"
},
"node_modules/@types/d3-random": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
- "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.4.tgz",
+ "integrity": "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
@@ -2009,18 +2448,18 @@
}
},
"node_modules/@types/debug": {
- "version": "4.1.12",
- "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
- "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
+ "version": "4.1.13",
+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",
"license": "MIT",
"dependencies": {
"@types/ms": "*"
}
},
"node_modules/@types/estree": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"license": "MIT"
},
"node_modules/@types/estree-jsx": {
@@ -2039,9 +2478,9 @@
"license": "MIT"
},
"node_modules/@types/hast": {
- "version": "3.0.4",
- "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
- "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz",
+ "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",
"license": "MIT",
"dependencies": {
"@types/unist": "*"
@@ -2070,13 +2509,13 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "25.2.3",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.3.tgz",
- "integrity": "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==",
+ "version": "25.9.5",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.5.tgz",
+ "integrity": "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "undici-types": "~7.16.0"
+ "undici-types": ">=7.24.0 <7.24.7"
}
},
"node_modules/@types/prop-types": {
@@ -2086,9 +2525,9 @@
"license": "MIT"
},
"node_modules/@types/react": {
- "version": "18.3.27",
- "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
- "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
+ "version": "18.3.31",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
+ "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -2324,9 +2763,9 @@
}
},
"node_modules/@ungap/structured-clone": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
- "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.3.tgz",
+ "integrity": "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg==",
"license": "ISC"
},
"node_modules/@upsetjs/venn.js": {
@@ -2361,9 +2800,9 @@
}
},
"node_modules/acorn": {
- "version": "8.17.0",
- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
- "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
+ "version": "8.18.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT",
"bin": {
@@ -2384,9 +2823,9 @@
}
},
"node_modules/ajv": {
- "version": "6.12.6",
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
- "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "version": "6.15.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
+ "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2445,6 +2884,75 @@
"node": ">= 8"
}
},
+ "node_modules/archiver": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz",
+ "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==",
+ "license": "MIT",
+ "dependencies": {
+ "archiver-utils": "^2.1.0",
+ "async": "^3.2.4",
+ "buffer-crc32": "^0.2.1",
+ "readable-stream": "^3.6.0",
+ "readdir-glob": "^1.1.2",
+ "tar-stream": "^2.2.0",
+ "zip-stream": "^4.1.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/archiver-utils": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz",
+ "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==",
+ "license": "MIT",
+ "dependencies": {
+ "glob": "^7.1.4",
+ "graceful-fs": "^4.2.0",
+ "lazystream": "^1.0.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.difference": "^4.5.0",
+ "lodash.flatten": "^4.4.0",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.union": "^4.6.0",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/archiver-utils/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/archiver-utils/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
+ "node_modules/archiver-utils/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/arg": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
@@ -2467,10 +2975,16 @@
"node": ">=8"
}
},
+ "node_modules/async": {
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
+ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
+ "license": "MIT"
+ },
"node_modules/autoprefixer": {
- "version": "10.4.24",
- "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.24.tgz",
- "integrity": "sha512-uHZg7N9ULTVbutaIsDRoUkoS8/h3bdsmVJYZ5l3wv8Cp/6UIIoRDm90hZ+BwxUj/hGBEzLxdHNSKuFpn8WOyZw==",
+ "version": "10.5.4",
+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.4.tgz",
+ "integrity": "sha512-MaU0U/za7N3r6brxD4YB/l4NSrFzLPlANv6wEuQVaIPlD3L4W9rFcQPbL/EilY9BHhHvhfcz3gInDLrEtWT4EA==",
"dev": true,
"funding": [
{
@@ -2488,8 +3002,8 @@
],
"license": "MIT",
"dependencies": {
- "browserslist": "^4.28.1",
- "caniuse-lite": "^1.0.30001766",
+ "browserslist": "^4.28.6",
+ "caniuse-lite": "^1.0.30001806",
"fraction.js": "^5.3.4",
"picocolors": "^1.1.1",
"postcss-value-parser": "^4.2.0"
@@ -2518,17 +3032,61 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
- "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
- "version": "2.9.19",
- "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.19.tgz",
- "integrity": "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==",
+ "version": "2.11.7",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.7.tgz",
+ "integrity": "sha512-APw5YuIQAg6L9w4sHDI6j26DGFJI6RpYOhnkMPdC9lWbkKvsyPHzDsve1yd73lk21yz7Y09Kci8B2Pp9FonzWA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
- "baseline-browser-mapping": "dist/cli.js"
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/big-integer": {
+ "version": "1.6.52",
+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
+ "license": "Unlicense",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/binary": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz",
+ "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffers": "~0.1.1",
+ "chainsaw": "~0.1.0"
+ },
+ "engines": {
+ "node": "*"
}
},
"node_modules/binary-extensions": {
@@ -2543,11 +3101,27 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "node_modules/bluebird": {
+ "version": "3.4.7",
+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz",
+ "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==",
+ "license": "MIT"
+ },
"node_modules/brace-expansion": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
- "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
- "dev": true,
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.3.tgz",
+ "integrity": "sha512-DRdx5neNsG/QXbniLFWi2YmC/68oeOOmKz6zOjVk6ZS1ZLXgLIKqVEc6hWsmkjBbgii0SwaBTcJ5XKj5gzY/4A==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -2566,9 +3140,9 @@
}
},
"node_modules/browserslist": {
- "version": "4.28.1",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",
- "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",
+ "version": "4.28.7",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz",
+ "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==",
"dev": true,
"funding": [
{
@@ -2586,11 +3160,11 @@
],
"license": "MIT",
"dependencies": {
- "baseline-browser-mapping": "^2.9.0",
- "caniuse-lite": "^1.0.30001759",
- "electron-to-chromium": "^1.5.263",
- "node-releases": "^2.0.27",
- "update-browserslist-db": "^1.2.0"
+ "baseline-browser-mapping": "^2.10.44",
+ "caniuse-lite": "^1.0.30001806",
+ "electron-to-chromium": "^1.5.393",
+ "node-releases": "^2.0.51",
+ "update-browserslist-db": "^1.2.3"
},
"bin": {
"browserslist": "cli.js"
@@ -2599,6 +3173,56 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "node_modules/buffer-crc32": {
+ "version": "0.2.13",
+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/buffer-indexof-polyfill": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz",
+ "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/buffers": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz",
+ "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==",
+ "engines": {
+ "node": ">=0.2.0"
+ }
+ },
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -2632,9 +3256,9 @@
}
},
"node_modules/caniuse-lite": {
- "version": "1.0.30001767",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001767.tgz",
- "integrity": "sha512-34+zUAMhSH+r+9eKmYG+k2Rpt8XttfE4yXAjoZvkAPs15xcYQhyBYdalJ65BzivAvGRMViEjy6oKr/S91loekQ==",
+ "version": "1.0.30001806",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz",
+ "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==",
"dev": true,
"funding": [
{
@@ -2662,6 +3286,18 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/chainsaw": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz",
+ "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==",
+ "license": "MIT/X11",
+ "dependencies": {
+ "traverse": ">=0.3.0 <0.4"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -2795,19 +3431,33 @@
}
},
"node_modules/commander": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
- "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
"license": "MIT",
"engines": {
- "node": ">= 6"
+ "node": ">= 10"
+ }
+ },
+ "node_modules/compress-commons": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz",
+ "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-crc32": "^0.2.13",
+ "crc32-stream": "^4.0.2",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
- "dev": true,
"license": "MIT"
},
"node_modules/convert-source-map": {
@@ -2817,6 +3467,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/core-util-is": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
+ "license": "MIT"
+ },
"node_modules/cose-base": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",
@@ -2853,6 +3509,37 @@
}
}
},
+ "node_modules/crc-32": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
+ "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
+ "license": "Apache-2.0",
+ "bin": {
+ "crc32": "bin/crc32.njs"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
+ "node_modules/crc32-stream": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz",
+ "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==",
+ "license": "MIT",
+ "dependencies": {
+ "crc-32": "^1.2.0",
+ "readable-stream": "^3.4.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/crelt": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
+ "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
+ "license": "MIT"
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -3104,15 +3791,6 @@
"node": ">=12"
}
},
- "node_modules/d3-dsv/node_modules/commander": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
- "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
- "license": "MIT",
- "engines": {
- "node": ">= 10"
- }
- },
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@@ -3506,10 +4184,19 @@
"node": ">=6.0.0"
}
},
+ "node_modules/docx-preview": {
+ "version": "0.3.7",
+ "resolved": "https://registry.npmjs.org/docx-preview/-/docx-preview-0.3.7.tgz",
+ "integrity": "sha512-Lav69CTA/IYZPJTsKH7oYeoZjyg96N0wEJMNslGJnZJ+dMUZK85Lt5ASC79yUlD48ecWjuv+rkcmFt6EVPV0Xg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "jszip": ">=3.0.0"
+ }
+ },
"node_modules/dompurify": {
- "version": "3.4.8",
- "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.8.tgz",
- "integrity": "sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==",
+ "version": "3.4.12",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.12.tgz",
+ "integrity": "sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
@@ -3526,13 +4213,61 @@
"tslib": "^2.0.3"
}
},
+ "node_modules/duplexer2": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",
+ "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "readable-stream": "^2.0.2"
+ }
+ },
+ "node_modules/duplexer2/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/duplexer2/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
+ "node_modules/duplexer2/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/electron-to-chromium": {
- "version": "1.5.283",
- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.283.tgz",
- "integrity": "sha512-3vifjt1HgrGW/h76UEeny+adYApveS9dH2h3p57JYzBSXJIKUJAvtmIytDKjcSCt9xHfrNCFJ7gts6vkhuq++w==",
+ "version": "1.5.398",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.398.tgz",
+ "integrity": "sha512-AsvhAxopJGh6museTDMIjn6JpDYOfgu4RLlygomt87MUwBUqTfd/1EiPtx10/LZE8xpTvkP2E9Gafq7lkLtodQ==",
"dev": true,
"license": "ISC"
},
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
@@ -3555,14 +4290,24 @@
"is-arrayish": "^0.2.1"
}
},
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/es-toolkit": {
- "version": "1.47.0",
- "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.47.0.tgz",
- "integrity": "sha512-n1GuoD0WEQZMBk5tttoZSqwgyLx01oqa5XsBmCHwPyNe1S9jPBEmtR2pSgp2kJuWE3ciFZ6yRHmY4pM4C3OOkw==",
+ "version": "1.50.0",
+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.50.0.tgz",
+ "integrity": "sha512-OyZKhUVvEep9ITEiwHn8GKnMRQIVqoSIX7WnRbkWgJkllCujilqP2rD0u979tkl8wqyc8ICwlc1UBVv/Sl1G6w==",
"license": "MIT",
"workspaces": [
"docs",
- "benchmarks"
+ "benchmarks",
+ "tests/types"
]
},
"node_modules/esbuild": {
@@ -3738,9 +4483,9 @@
}
},
"node_modules/eslint/node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
+ "version": "1.1.17",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.17.tgz",
+ "integrity": "sha512-w+aeW/mkgM4PyRMOJCgi3fOrTm5Q8QY1OSfn2TO2iuDj3ezIHqejmuxbjfPrqUkgqRew1iqkyAn0tr0ZwHD9+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3749,9 +4494,9 @@
}
},
"node_modules/eslint/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -3842,12 +4587,45 @@
"node": ">=0.10.0"
}
},
+ "node_modules/exceljs": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz",
+ "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==",
+ "license": "MIT",
+ "dependencies": {
+ "archiver": "^5.0.0",
+ "dayjs": "^1.8.34",
+ "fast-csv": "^4.3.1",
+ "jszip": "^3.10.1",
+ "readable-stream": "^3.6.0",
+ "saxes": "^5.0.1",
+ "tmp": "^0.2.0",
+ "unzipper": "^0.10.11",
+ "uuid": "^8.3.0"
+ },
+ "engines": {
+ "node": ">=8.3.0"
+ }
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
+ "node_modules/fast-csv": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz",
+ "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==",
+ "license": "MIT",
+ "dependencies": {
+ "@fast-csv/format": "4.3.5",
+ "@fast-csv/parse": "4.3.6"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3964,12 +4742,21 @@
}
},
"node_modules/flatted": {
- "version": "3.3.3",
- "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz",
- "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.3.tgz",
+ "integrity": "sha512-/zipXxyO6rGvuNGDiULY9MvEGSkb2gaG4GGH4ygMi0ZZzyMHdUZBmntJmx5x1G2VuPytCwGN4xsJP6cw+sK+vQ==",
"dev": true,
"license": "ISC"
},
+ "node_modules/frac": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
+ "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
"node_modules/fraction.js": {
"version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -3984,11 +4771,16 @@
"url": "https://github.com/sponsors/rawify"
}
},
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "license": "MIT"
+ },
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
- "dev": true,
"license": "ISC"
},
"node_modules/fsevents": {
@@ -4005,6 +4797,35 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/fstream": {
+ "version": "1.0.12",
+ "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz",
+ "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==",
+ "deprecated": "This package is no longer supported.",
+ "license": "ISC",
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "inherits": "~2.0.0",
+ "mkdirp": ">=0.5 0",
+ "rimraf": "2"
+ },
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/fstream/node_modules/rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "deprecated": "Rimraf versions prior to v4 are no longer supported",
+ "license": "ISC",
+ "dependencies": {
+ "glob": "^7.1.3"
+ },
+ "bin": {
+ "rimraf": "bin.js"
+ }
+ },
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@@ -4028,8 +4849,7 @@
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
- "deprecated": "Glob versions prior to v9 are no longer supported",
- "dev": true,
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
@@ -4059,10 +4879,9 @@
}
},
"node_modules/glob/node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
- "dev": true,
+ "version": "1.1.17",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.17.tgz",
+ "integrity": "sha512-w+aeW/mkgM4PyRMOJCgi3fOrTm5Q8QY1OSfn2TO2iuDj3ezIHqejmuxbjfPrqUkgqRew1iqkyAn0tr0ZwHD9+w==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
@@ -4070,10 +4889,9 @@
}
},
"node_modules/glob/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
- "dev": true,
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
@@ -4119,6 +4937,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "license": "ISC"
+ },
"node_modules/graphemer": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
@@ -4143,9 +4967,9 @@
}
},
"node_modules/hasown": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
- "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
@@ -4195,9 +5019,9 @@
}
},
"node_modules/html-parse-stringify": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
- "integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.1.0.tgz",
+ "integrity": "sha512-E0oAXcELOtsXe+BmpJ2EZyedbldPpriV5vICzEuo6xjC/D1lDukOI7KrpfQGF2Qc4wWEy0nk3bFORS2K5ZAhFQ==",
"license": "MIT",
"dependencies": {
"void-elements": "3.1.0"
@@ -4220,29 +5044,29 @@
}
},
"node_modules/i18next": {
- "version": "25.8.18",
- "resolved": "https://registry.npmjs.org/i18next/-/i18next-25.8.18.tgz",
- "integrity": "sha512-lzY5X83BiL5AP77+9DydbrqkQHFN9hUzWGjqjLpPcp5ZOzuu1aSoKaU3xbBLSjWx9dAzW431y+d+aogxOZaKRA==",
+ "version": "25.10.10",
+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-25.10.10.tgz",
+ "integrity": "sha512-cqUW2Z3EkRx7NqSyywjkgCLK7KLCL6IFVFcONG7nVYIJ3ekZ1/N5jUsihHV6Bq37NfhgtczxJcxduELtjTwkuQ==",
"funding": [
{
"type": "individual",
- "url": "https://locize.com"
+ "url": "https://www.locize.com/i18next"
},
{
"type": "individual",
- "url": "https://locize.com/i18next.html"
+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
},
{
"type": "individual",
- "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
+ "url": "https://www.locize.com"
}
],
"license": "MIT",
"dependencies": {
- "@babel/runtime": "^7.28.6"
+ "@babel/runtime": "^7.29.2"
},
"peerDependencies": {
- "typescript": "^5"
+ "typescript": "^5 || ^6"
},
"peerDependenciesMeta": {
"typescript": {
@@ -4271,6 +5095,26 @@
"node": ">=0.10.0"
}
},
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -4281,6 +5125,12 @@
"node": ">= 4"
}
},
+ "node_modules/immediate": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
+ "license": "MIT"
+ },
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -4323,7 +5173,6 @@
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
- "dev": true,
"license": "ISC",
"dependencies": {
"once": "^1.3.0",
@@ -4334,7 +5183,6 @@
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/inline-style-parser": {
@@ -4396,12 +5244,12 @@
}
},
"node_modules/is-core-module": {
- "version": "2.16.1",
- "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
- "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
+ "version": "2.16.2",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz",
+ "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==",
"license": "MIT",
"dependencies": {
- "hasown": "^2.0.2"
+ "hasown": "^2.0.3"
},
"engines": {
"node": ">= 0.4"
@@ -4482,6 +5330,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
+ "license": "MIT"
+ },
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -4505,10 +5359,20 @@
"license": "MIT"
},
"node_modules/js-yaml": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
- "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
+ "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
"dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -4571,6 +5435,48 @@
"node": ">=6"
}
},
+ "node_modules/jszip": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
+ "license": "(MIT OR GPL-3.0-or-later)",
+ "dependencies": {
+ "lie": "~3.3.0",
+ "pako": "~1.0.2",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/jszip/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/jszip/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
+ "node_modules/jszip/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/katex": {
"version": "0.16.47",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.47.tgz",
@@ -4617,6 +5523,48 @@
"integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",
"license": "MIT"
},
+ "node_modules/lazystream": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
+ "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
+ "license": "MIT",
+ "dependencies": {
+ "readable-stream": "^2.0.5"
+ },
+ "engines": {
+ "node": ">= 0.6.3"
+ }
+ },
+ "node_modules/lazystream/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/lazystream/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
+ "node_modules/lazystream/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
@@ -4631,6 +5579,15 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/lie": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
"node_modules/lilconfig": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
@@ -4650,14 +5607,30 @@
"license": "MIT"
},
"node_modules/linkify-it": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz",
- "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==",
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz",
+ "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/markdown-it"
+ }
+ ],
"license": "MIT",
"dependencies": {
"uc.micro": "^2.0.0"
}
},
+ "node_modules/listenercount": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz",
+ "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==",
+ "license": "ISC"
+ },
"node_modules/locate-path": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@@ -4680,6 +5653,73 @@
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
"license": "MIT"
},
+ "node_modules/lodash.defaults": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
+ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.difference": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz",
+ "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.escaperegexp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
+ "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.flatten": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
+ "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.groupby": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz",
+ "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isboolean": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isfunction": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz",
+ "integrity": "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isnil": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz",
+ "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isplainobject": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isundefined": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz",
+ "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==",
+ "license": "MIT"
+ },
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -4687,6 +5727,18 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/lodash.union": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",
+ "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.uniq": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz",
+ "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==",
+ "license": "MIT"
+ },
"node_modules/longest-streak": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
@@ -4739,14 +5791,24 @@
}
},
"node_modules/markdown-it": {
- "version": "14.1.1",
- "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz",
- "integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==",
+ "version": "14.3.0",
+ "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.0.tgz",
+ "integrity": "sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/markdown-it"
+ }
+ ],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1",
- "entities": "^4.4.0",
- "linkify-it": "^5.0.0",
+ "entities": "^4.5.0",
+ "linkify-it": "^5.0.2",
"mdurl": "^2.0.0",
"punycode.js": "^2.3.1",
"uc.micro": "^2.1.0"
@@ -5060,9 +6122,9 @@
}
},
"node_modules/mdurl": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz",
- "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==",
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz",
+ "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==",
"license": "MIT"
},
"node_modules/merge2": {
@@ -5103,6 +6165,19 @@
"uuid": "^11.1.0 || ^12 || ^13 || ^14.0.0"
}
},
+ "node_modules/mermaid/node_modules/uuid": {
+ "version": "14.0.1",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.1.tgz",
+ "integrity": "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist-node/bin/uuid"
+ }
+ },
"node_modules/micromark": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
@@ -5695,6 +6770,27 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "license": "MIT",
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -5713,9 +6809,9 @@
}
},
"node_modules/nanoid": {
- "version": "3.3.11",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
- "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "version": "3.3.16",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
+ "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"funding": [
{
"type": "github",
@@ -5749,11 +6845,14 @@
}
},
"node_modules/node-releases": {
- "version": "2.0.27",
- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
- "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",
+ "version": "2.0.51",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz",
+ "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
},
"node_modules/normalize-path": {
"version": "3.0.0",
@@ -5786,7 +6885,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "dev": true,
"license": "ISC",
"dependencies": {
"wrappy": "1"
@@ -5843,11 +6941,17 @@
}
},
"node_modules/package-manager-detector": {
- "version": "1.6.0",
- "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz",
- "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==",
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.8.0.tgz",
+ "integrity": "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==",
"license": "MIT"
},
+ "node_modules/pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -5925,7 +7029,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -5964,9 +7067,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -6010,9 +7113,9 @@
}
},
"node_modules/postcss": {
- "version": "8.5.6",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
- "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
+ "version": "8.5.25",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
+ "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"funding": [
{
"type": "opencollective",
@@ -6029,7 +7132,7 @@
],
"license": "MIT",
"dependencies": {
- "nanoid": "^3.3.11",
+ "nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -6146,10 +7249,23 @@
"postcss": "^8.2.14"
}
},
+ "node_modules/postcss-nested/node_modules/postcss-selector-parser": {
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz",
+ "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==",
+ "license": "MIT",
+ "dependencies": {
+ "cssesc": "^3.0.0",
+ "util-deprecate": "^1.0.2"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/postcss-selector-parser": {
- "version": "6.1.2",
- "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
- "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
+ "version": "6.0.10",
+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",
+ "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
@@ -6176,9 +7292,9 @@
}
},
"node_modules/prettier": {
- "version": "3.8.5",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.5.tgz",
- "integrity": "sha512-zxcTTCedNGJM4R8sj/Cq/F0W/c4iE0afWBcBwMTRtw4WHYP9TWkYjdiH3npPRUYsXQCPR0hTU9yjovOu+E6EQA==",
+ "version": "3.9.6",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz",
+ "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==",
"dev": true,
"license": "MIT",
"bin": {
@@ -6191,10 +7307,16 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/process-nextick-args": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
+ "license": "MIT"
+ },
"node_modules/property-information": {
- "version": "7.1.0",
- "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
- "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",
+ "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
"license": "MIT",
"funding": {
"type": "github",
@@ -6275,19 +7397,19 @@
}
},
"node_modules/react-i18next": {
- "version": "16.5.8",
- "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-16.5.8.tgz",
- "integrity": "sha512-2ABeHHlakxVY+LSirD+OiERxFL6+zip0PaHo979bgwzeHg27Sqc82xxXWIrSFmfWX0ZkrvXMHwhsi/NGUf5VQg==",
+ "version": "16.6.6",
+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-16.6.6.tgz",
+ "integrity": "sha512-ZgL2HUoW34UKUkOV7uSQFE1CDnRPD+tCR3ywSuWH7u2iapnz86U8Bi3Vrs620qNDzCf1F47NxglCEkchCTDOHw==",
"license": "MIT",
"dependencies": {
- "@babel/runtime": "^7.28.4",
+ "@babel/runtime": "^7.29.2",
"html-parse-stringify": "^3.0.1",
"use-sync-external-store": "^1.6.0"
},
"peerDependencies": {
- "i18next": ">= 25.6.2",
+ "i18next": ">= 25.10.9",
"react": ">= 16.8.0",
- "typescript": "^5"
+ "typescript": "^5 || ^6"
},
"peerDependenciesMeta": {
"react-dom": {
@@ -6347,6 +7469,41 @@
"pify": "^2.3.0"
}
},
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/readdir-glob": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz",
+ "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "minimatch": "^5.1.0"
+ }
+ },
+ "node_modules/readdir-glob/node_modules/minimatch": {
+ "version": "5.1.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
+ "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -6426,11 +7583,12 @@
}
},
"node_modules/resolve": {
- "version": "1.22.11",
- "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
- "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",
+ "version": "1.22.12",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz",
+ "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==",
"license": "MIT",
"dependencies": {
+ "es-errors": "^1.3.0",
"is-core-module": "^2.16.1",
"path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0"
@@ -6533,6 +7691,13 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/rollup/node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/roughjs": {
"version": "4.6.6",
"resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",
@@ -6574,12 +7739,44 @@
"integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
"license": "BSD-3-Clause"
},
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
+ "node_modules/saxes": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz",
+ "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==",
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
@@ -6590,9 +7787,9 @@
}
},
"node_modules/semver": {
- "version": "7.7.3",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
- "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
@@ -6602,6 +7799,12 @@
"node": ">=10"
}
},
+ "node_modules/setimmediate": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
+ "license": "MIT"
+ },
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -6665,6 +7868,27 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/ssf": {
+ "version": "0.11.2",
+ "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
+ "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "frac": "~1.1.2"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
"node_modules/stringify-entities": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
@@ -6705,6 +7929,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/style-mod": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
+ "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
+ "license": "MIT"
+ },
"node_modules/style-to-js": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
@@ -6751,6 +7981,15 @@
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/sucrase/node_modules/commander": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
+ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -6820,6 +8059,35 @@
"node": ">=14.0.0"
}
},
+ "node_modules/tailwindcss/node_modules/postcss-selector-parser": {
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz",
+ "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==",
+ "license": "MIT",
+ "dependencies": {
+ "cssesc": "^3.0.0",
+ "util-deprecate": "^1.0.2"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@@ -6858,13 +8126,13 @@
}
},
"node_modules/tinyglobby": {
- "version": "0.2.15",
- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
- "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
"license": "MIT",
"dependencies": {
"fdir": "^6.5.0",
- "picomatch": "^4.0.3"
+ "picomatch": "^4.0.4"
},
"engines": {
"node": ">=12.0.0"
@@ -6891,9 +8159,9 @@
}
},
"node_modules/tinyglobby/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"license": "MIT",
"engines": {
"node": ">=12"
@@ -6902,6 +8170,15 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/tmp": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
+ "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -6914,6 +8191,15 @@
"node": ">=8.0"
}
},
+ "node_modules/traverse": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz",
+ "integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==",
+ "license": "MIT/X11",
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/trim-lines": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
@@ -6948,9 +8234,9 @@
}
},
"node_modules/ts-dedent": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",
- "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.3.0.tgz",
+ "integrity": "sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==",
"license": "MIT",
"engines": {
"node": ">=6.10"
@@ -7016,9 +8302,9 @@
"license": "MIT"
},
"node_modules/undici-types": {
- "version": "7.16.0",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
- "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
+ "version": "7.24.6",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
"dev": true,
"license": "MIT"
},
@@ -7109,6 +8395,54 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/unzipper": {
+ "version": "0.10.14",
+ "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz",
+ "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==",
+ "license": "MIT",
+ "dependencies": {
+ "big-integer": "^1.6.17",
+ "binary": "~0.3.0",
+ "bluebird": "~3.4.1",
+ "buffer-indexof-polyfill": "~1.0.0",
+ "duplexer2": "~0.1.4",
+ "fstream": "^1.0.12",
+ "graceful-fs": "^4.2.2",
+ "listenercount": "~1.0.1",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "~1.0.4"
+ }
+ },
+ "node_modules/unzipper/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/unzipper/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
+ "node_modules/unzipper/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
"node_modules/update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -7166,16 +8500,13 @@
"license": "MIT"
},
"node_modules/uuid": {
- "version": "14.0.0",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.0.tgz",
- "integrity": "sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==",
- "funding": [
- "https://github.com/sponsors/broofa",
- "https://github.com/sponsors/ctavan"
- ],
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
"license": "MIT",
"bin": {
- "uuid": "dist-node/bin/uuid"
+ "uuid": "dist/bin/uuid"
}
},
"node_modules/vfile": {
@@ -7290,6 +8621,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/w3c-keyname": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
+ "license": "MIT"
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -7320,9 +8657,14 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "dev": true,
"license": "ISC"
},
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "license": "MIT"
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
@@ -7343,6 +8685,41 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/zip-stream": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz",
+ "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==",
+ "license": "MIT",
+ "dependencies": {
+ "archiver-utils": "^3.0.4",
+ "compress-commons": "^4.1.2",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/zip-stream/node_modules/archiver-utils": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz",
+ "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==",
+ "license": "MIT",
+ "dependencies": {
+ "glob": "^7.2.3",
+ "graceful-fs": "^4.2.0",
+ "lazystream": "^1.0.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.difference": "^4.5.0",
+ "lodash.flatten": "^4.4.0",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.union": "^4.6.0",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index cb87918764..bae68a8df4 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -10,6 +10,8 @@
"build": "tsc && vite build",
"test:code-turn-diff-binding": "tsc src/features/code-mode/codeTurnDiffBinding.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/code-turn-diff-binding --skipLibCheck --noEmitOnError && node --test tests/codeTurnDiffBinding.test.mjs",
"test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs",
+ "test:spreadsheet-preview": "esbuild src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts src/components/ArtifactsPanel/spreadsheetPreviewModel.ts src/components/ArtifactsPanel/filePreviewModel.ts src/components/ArtifactsPanel/chartGeometry.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/spreadsheet-preview && node --test tests/spreadsheetPreview.test.mjs",
+ "test:presentation-preview": "esbuild src/components/ArtifactsPanel/pptxPresentationParser.ts src/components/ArtifactsPanel/pptxPreviewModel.ts src/components/ArtifactsPanel/ooxmlArchiveLimits.ts src/components/ArtifactsPanel/filePreviewModel.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/presentation-preview && node --test tests/presentationPreview.test.mjs",
"test:tool-result-lifecycle": "tsc src/stores/toolResultLifecycle.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/tool-result-lifecycle --skipLibCheck --noEmitOnError && node --test tests/toolResultLifecycle.test.mjs",
"test:team-panel-state": "tsc src/features/teamPanelStateNormalize.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/team-panel-state --skipLibCheck --noEmitOnError && node --test tests/teamPanelState.test.mjs",
"test:create-conversation-session": "tsc src/multi-session/state/createConversationSession.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/create-conversation-session --skipLibCheck --noEmitOnError && node --test tests/createConversationSession.test.mjs",
@@ -20,17 +22,39 @@
"test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs",
"test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs",
"test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs",
+ "test:history-pagination": "tsc src/features/historyPagination.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/history-pagination --skipLibCheck --noEmitOnError && node --test tests/historyPagination.test.mjs",
+ "test:artifact-collection": "esbuild src/components/ArtifactsPanel/artifactCollection.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/artifact-collection/artifactCollection.mjs && node --test tests/artifactCollection.test.mjs",
+ "test:desktop-save": "esbuild src/utils/desktopSave.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/desktop-save/desktopSave.mjs && node --test tests/desktopSave.test.mjs",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@a2ui/react": "0.8.0",
"@a2ui/web_core": "0.8.0",
+ "@codemirror/lang-cpp": "6.0.3",
+ "@codemirror/lang-css": "6.3.1",
+ "@codemirror/lang-go": "6.0.1",
+ "@codemirror/lang-java": "6.0.2",
+ "@codemirror/lang-javascript": "6.2.5",
+ "@codemirror/lang-php": "6.0.2",
+ "@codemirror/lang-python": "6.2.1",
+ "@codemirror/lang-rust": "6.0.2",
+ "@codemirror/lang-sql": "6.10.0",
+ "@codemirror/lang-vue": "0.1.3",
+ "@codemirror/lang-xml": "6.1.0",
+ "@codemirror/lang-yaml": "6.1.3",
+ "@codemirror/language": "6.12.4",
+ "@codemirror/legacy-modes": "6.5.3",
+ "@codemirror/state": "6.7.1",
+ "@codemirror/view": "6.43.7",
"@tailwindcss/typography": "^0.5.19",
"clsx": "^2.1.0",
+ "docx-preview": "0.3.7",
+ "exceljs": "4.4.0",
"html-to-image": "1.11.13",
"i18next": "^25.8.18",
"i18next-browser-languagedetector": "^8.2.1",
+ "jszip": "3.10.1",
"lucide-react": "1.16.0",
"mermaid": "11.15.0",
"qrcode.react": "^4.2.0",
@@ -39,6 +63,8 @@
"react-i18next": "^16.5.8",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
+ "saxes": "5.0.1",
+ "ssf": "0.11.2",
"zustand": "^4.5.0"
},
"devDependencies": {
@@ -54,6 +80,7 @@
"eslint-plugin-react-refresh": "^0.4.0",
"postcss": "^8.4.0",
"prettier": "^3.3.3",
+ "rollup": "4.57.1",
"tailwindcss": "^3.4.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 988295d59f..86d610be67 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -34,6 +34,7 @@ import {
type HistoryHarnessReplayItem,
type FetchHistoryPageResult,
} from './features/historyRestore';
+import { prefetchHistoryPages } from './features/historyPagination';
import {
normalizeToolCallPayload,
normalizeToolResultPayload,
@@ -339,6 +340,9 @@ function AppContent() {
const hasChangesRef = useRef(false);
const [historyLoadingMore, setHistoryLoadingMore] = useState(false);
const [historyPrepending, setHistoryPrepending] = useState(false);
+ const [historyRetrySessions, setHistoryRetrySessions] = useState<ReadonlySet<string>>(
+ () => new Set()
+ );
/** 仅用于强制重跑「首屏 history」effect:从会话列表恢复时若 sessionId 未变,也要重新拉 history 并恢复 historyPagerMeta */
const [historyBootstrapKey, setHistoryBootstrapKey] = useState(0);
const sessionIdRef = useRef(sessionId);
@@ -363,6 +367,20 @@ function AppContent() {
const historyRestoreFromPanelHintRef = useRef(false);
const { loadProjects, setSelectedProject } = useWorkspaceStore();
+ const setHistoryRetryAvailable = useCallback((sid: string, available: boolean) => {
+ setHistoryRetrySessions((current) => {
+ if (current.has(sid) === available) {
+ return current;
+ }
+ const next = new Set(current);
+ if (available) {
+ next.add(sid);
+ } else {
+ next.delete(sid);
+ }
+ return next;
+ });
+ }, []);
useEffect(() => {
sessionIdRef.current = sessionId;
@@ -375,10 +393,12 @@ function AppContent() {
teamAreaActiveTab,
teamAreaActiveDetailTab,
teamAreaSelectedMemberId,
+ teamAreaSelectedArtifactId,
setTeamAreaExpanded,
setTeamAreaActiveTab,
setTeamAreaActiveDetailTab,
setTeamAreaSelectedMemberId,
+ setTeamAreaSelectedArtifactId,
} = useTeamPanelState();
useEffect(() => {
@@ -529,6 +549,7 @@ function AppContent() {
const prevToken = historyBackgroundPrefetchTokensRef.current.get(targetSid) ?? 0;
historyBackgroundPrefetchTokensRef.current.set(targetSid, prevToken + 1);
historyLoadingSessionsRef.current.delete(targetSid);
+ setHistoryRetryAvailable(targetSid, false);
if (targetSid === sessionIdRef.current) {
setHistoryPrepending(false);
setHistoryLoadingMore(false);
@@ -558,7 +579,7 @@ function AppContent() {
])) {
cancelSession(targetSid);
}
- }, [setLoadingHistory]);
+ }, [setHistoryRetryAvailable, setLoadingHistory]);
useEffect(() => () => disposeInFlightHistoryHandles(), [disposeInFlightHistoryHandles]);
const todos = useTodoStore((s) => s.runtimes[sessionId]?.todos ?? []);
@@ -773,43 +794,48 @@ function AppContent() {
}, [applyHistoryPageResult, setHistoryPagerMeta]);
const startBackgroundHistoryPrefetch = useCallback((sid: string, initialLoadedPages: number, initialTotalPages: number) => {
- if (initialLoadedPages >= initialTotalPages) return;
+ if (initialLoadedPages >= initialTotalPages || historyLoadingSessionsRef.current.has(sid)) {
+ return;
+ }
const token = (historyBackgroundPrefetchTokensRef.current.get(sid) ?? 0) + 1;
historyBackgroundPrefetchTokensRef.current.set(sid, token);
+ historyLoadingSessionsRef.current.add(sid);
+ setHistoryRetryAvailable(sid, false);
+ if (sessionIdRef.current === sid) {
+ setHistoryPrepending(true);
+ }
void (async () => {
- let loadedPages = initialLoadedPages;
- let totalPages = initialTotalPages;
- while (
- token === historyBackgroundPrefetchTokensRef.current.get(sid) &&
- loadedPages < totalPages
- ) {
- if (historyLoadingSessionsRef.current.has(sid)) {
- return;
- }
- const nextPage = loadedPages + 1;
- historyLoadingSessionsRef.current.add(sid);
- if (sessionIdRef.current === sid) {
- setHistoryPrepending(true);
+ try {
+ const outcome = await prefetchHistoryPages({
+ initialLoadedPages,
+ initialTotalPages,
+ isCurrent: () => token === historyBackgroundPrefetchTokensRef.current.get(sid),
+ fetchPage: (pageIdx, totalPages) =>
+ fetchHistoryPageResult(sid, pageIdx, totalPages),
+ applyPage: (page) => {
+ applyLoadedHistoryPage(sid, page);
+ },
+ waitForNextPaint,
+ });
+ if (
+ outcome === 'failed' &&
+ token === historyBackgroundPrefetchTokensRef.current.get(sid)
+ ) {
+ setHistoryRetryAvailable(sid, true);
}
- const page = await fetchHistoryPageResult(sid, nextPage, totalPages);
+ } finally {
historyLoadingSessionsRef.current.delete(sid);
if (sessionIdRef.current === sid) {
setHistoryPrepending(false);
}
- if (
- page == null ||
- token !== historyBackgroundPrefetchTokensRef.current.get(sid)
- ) {
- return;
- }
- applyLoadedHistoryPage(sid, page);
- loadedPages = nextPage;
- totalPages = page.totalPages;
- await waitForNextPaint();
}
})();
- }, [applyLoadedHistoryPage, fetchHistoryPageResult]);
+ }, [
+ applyLoadedHistoryPage,
+ fetchHistoryPageResult,
+ setHistoryRetryAvailable,
+ ]);
const upsertSessionMetadata = useCallback((session: Session, options: { setCurrent?: boolean } = {}) => {
const sessionStore = useSessionStore.getState();
@@ -1787,23 +1813,40 @@ function AppContent() {
const nextPage = historyPagerMeta.loadedPages + 1;
const fallbackTotal = historyPagerMeta.totalPages;
const prevToken = historyBackgroundPrefetchTokensRef.current.get(sid) ?? 0;
- historyBackgroundPrefetchTokensRef.current.set(sid, prevToken + 1);
+ const token = prevToken + 1;
+ historyBackgroundPrefetchTokensRef.current.set(sid, token);
historyLoadingSessionsRef.current.add(sid);
+ setHistoryRetryAvailable(sid, false);
setHistoryLoadingMore(true);
setLoadingHistory(sid, true);
- const page = await fetchHistoryPageResult(sid, nextPage, fallbackTotal);
- if (page) {
- applyLoadedHistoryPage(sid, page);
- startBackgroundHistoryPrefetch(sid, page.pageIdx, page.totalPages);
+ let page: LoadedHistoryPage | null = null;
+ try {
+ page = await fetchHistoryPageResult(sid, nextPage, fallbackTotal);
+ if (
+ page &&
+ token === historyBackgroundPrefetchTokensRef.current.get(sid)
+ ) {
+ applyLoadedHistoryPage(sid, page);
+ }
+ } finally {
+ historyLoadingSessionsRef.current.delete(sid);
+ setHistoryLoadingMore(false);
+ setLoadingHistory(sid, false);
}
- historyLoadingSessionsRef.current.delete(sid);
- setHistoryLoadingMore(false);
- setLoadingHistory(sid, false);
+ if (token !== historyBackgroundPrefetchTokensRef.current.get(sid)) {
+ return;
+ }
+ if (!page) {
+ setHistoryRetryAvailable(sid, true);
+ return;
+ }
+ startBackgroundHistoryPrefetch(sid, page.pageIdx, page.totalPages);
}, [
applyLoadedHistoryPage,
fetchHistoryPageResult,
historyPagerMeta,
sessionId,
+ setHistoryRetryAvailable,
setLoadingHistory,
startBackgroundHistoryPrefetch,
]);
@@ -1815,6 +1858,7 @@ function AppContent() {
totalPages: historyPagerMeta.totalPages,
loadingMore: historyLoadingMore,
prepending: historyPrepending,
+ retryAvailable: historyRetrySessions.has(sessionId),
onLoadMore: handleLoadMoreHistory,
};
}, [
@@ -1822,6 +1866,8 @@ function AppContent() {
historyLoadingMore,
historyPagerMeta,
historyPrepending,
+ historyRetrySessions,
+ sessionId,
]);
const handleRestoreSession = useCallback(
@@ -2231,11 +2277,13 @@ function AppContent() {
teamAreaActiveDetailTab={teamAreaActiveDetailTab}
teamAreaSelectedMemberId={teamAreaSelectedMemberId}
codeReviewTarget={codeReviewTarget}
+ teamAreaSelectedArtifactId={teamAreaSelectedArtifactId}
setTeamAreaExpanded={setTeamAreaExpanded}
setTeamAreaActiveTab={setTeamAreaActiveTab}
setTeamAreaActiveDetailTab={setTeamAreaActiveDetailTab}
setTeamAreaSelectedMemberId={setTeamAreaSelectedMemberId}
setCodeReviewTarget={setCodeReviewTarget}
+ setTeamAreaSelectedArtifactId={setTeamAreaSelectedArtifactId}
/>
)}
</div>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/CodePreview.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/CodePreview.tsx
new file mode 100644
index 0000000000..413b1bba2a
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/CodePreview.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
+import { EditorState } from '@codemirror/state';
+import { EditorView, lineNumbers } from '@codemirror/view';
+import { LoaderCircle } from 'lucide-react';
+import { loadCodeLanguage } from './codeLanguages';
+
+const lightPreviewTheme = EditorView.theme(
+ {
+ '&': {
+ height: '100%',
+ backgroundColor: 'transparent',
+ fontSize: '12px',
+ },
+ '.cm-scroller': {
+ overflow: 'auto',
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',
+ },
+ '.cm-content': {
+ padding: '0',
+ },
+ '.cm-gutters': {
+ backgroundColor: 'transparent',
+ border: 'none',
+ },
+ '.cm-lineNumbers .cm-gutterElement': {
+ minWidth: '32px',
+ padding: '0 10px 0 4px',
+ },
+ '.cm-focused': {
+ outline: 'none',
+ },
+ },
+ { dark: false },
+);
+
+type LoadState = 'loading' | 'ready' | 'error';
+
+export function CodePreview({ content, name, mimeType }: { content: string; name: string; mimeType?: string }) {
+ const { t } = useTranslation();
+ const hostRef = useRef<HTMLDivElement>(null);
+ const [loadState, setLoadState] = useState<LoadState>('loading');
+
+ useEffect(() => {
+ let disposed = false;
+ let view: EditorView | null = null;
+ setLoadState('loading');
+
+ void loadCodeLanguage(name, mimeType)
+ .then(language => {
+ if (disposed || !hostRef.current) return;
+ view = new EditorView({
+ parent: hostRef.current,
+ state: EditorState.create({
+ doc: content,
+ extensions: [
+ EditorState.readOnly.of(true),
+ EditorView.editable.of(false),
+ EditorView.contentAttributes.of({
+ 'aria-label': name,
+ tabindex: '0',
+ }),
+ lineNumbers(),
+ syntaxHighlighting(defaultHighlightStyle),
+ language,
+ lightPreviewTheme,
+ ],
+ }),
+ });
+ setLoadState('ready');
+ })
+ .catch(() => {
+ if (!disposed) setLoadState('error');
+ });
+
+ return () => {
+ disposed = true;
+ view?.destroy();
+ };
+ }, [content, mimeType, name]);
+
+ return (
+ <div className="relative h-full min-h-0 w-full overflow-hidden" data-testid="artifact-code-preview">
+ <div ref={hostRef} className="h-full min-h-0 w-full" />
+ {loadState === 'loading' && (
+ <div className="absolute inset-0 flex items-center justify-center gap-2 text-sm text-text-muted">
+ <LoaderCircle className="animate-spin" size={16} />
+ {t('common.loading')}
+ </div>
+ )}
+ {loadState === 'error' && <div className="absolute inset-0 flex items-center justify-center text-sm text-text-muted">{t('artifacts.previewFailed')}</div>}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/DocxPreview.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/DocxPreview.tsx
new file mode 100644
index 0000000000..7eddbf730c
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/DocxPreview.tsx
@@ -0,0 +1,101 @@
+import { useEffect, useRef, useState } from 'react';
+import { LoaderCircle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+type DocxPreviewState = 'loading' | 'ready' | 'error';
+
+export function DocxPreview({ url, title }: { url: string; title: string }) {
+ const { t } = useTranslation();
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const styleRef = useRef<HTMLDivElement>(null);
+ const [state, setState] = useState<DocxPreviewState>('loading');
+
+ useEffect(() => {
+ const body = bodyRef.current;
+ const styleHost = styleRef.current;
+ if (!body || !styleHost) return;
+
+ const abortController = new AbortController();
+ let cancelled = false;
+ body.replaceChildren();
+ styleHost.replaceChildren();
+ setState('loading');
+
+ const handleLinkClick = (event: MouseEvent) => {
+ if (!(event.target instanceof Element)) return;
+ const anchor = event.target.closest('a[href]');
+ if (!anchor) return;
+ event.preventDefault();
+ const href = anchor.getAttribute('href');
+ if (!href) return;
+
+ if (href.startsWith('#')) {
+ const target = body.querySelector(`[id="${CSS.escape(href.slice(1))}"]`);
+ target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ return;
+ }
+ if (/^(https?:|mailto:|tel:)/i.test(href)) {
+ window.open(href, '_blank', 'noopener,noreferrer');
+ }
+ };
+ body.addEventListener('click', handleLinkClick);
+
+ void fetch(url, { cache: 'no-store', signal: abortController.signal })
+ .then(async response => {
+ const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
+ if (!response.ok || contentType.includes('text/html')) {
+ throw new Error(`DOCX request failed with HTTP ${response.status}`);
+ }
+ return response.arrayBuffer();
+ })
+ .then(async content => {
+ if (cancelled) return;
+ const { renderAsync } = await import('docx-preview');
+ if (cancelled) return;
+ await renderAsync(content, body, styleHost, {
+ className: 'docx-artifact-page',
+ inWrapper: true,
+ breakPages: true,
+ ignoreHeight: false,
+ ignoreWidth: false,
+ renderHeaders: true,
+ renderFooters: true,
+ renderFootnotes: true,
+ renderEndnotes: true,
+ useBase64URL: true,
+ });
+ if (!cancelled) setState('ready');
+ })
+ .catch(error => {
+ if (abortController.signal.aborted || cancelled) return;
+ console.error('Failed to render DOCX preview', error);
+ setState('error');
+ });
+
+ return () => {
+ cancelled = true;
+ abortController.abort();
+ body.removeEventListener('click', handleLinkClick);
+ body.replaceChildren();
+ styleHost.replaceChildren();
+ };
+ }, [url]);
+
+ return (
+ <div className="relative flex h-full min-h-0 w-full flex-col" aria-label={title} data-testid="artifact-docx-preview">
+ <div ref={styleRef} className="shrink-0" />
+ <div ref={bodyRef} className="min-h-0 flex-1 overflow-auto bg-secondary" />
+ {state === 'loading' && (
+ <div className="absolute inset-0 flex items-center justify-center gap-2 bg-secondary text-sm text-text-muted">
+ <LoaderCircle className="animate-spin" size={16} />
+ {t('common.loading')}
+ </div>
+ )}
+ {state === 'error' && (
+ <div className="absolute inset-0 flex items-center justify-center bg-secondary p-6 text-sm text-danger" role="alert">
+ {t('artifacts.docxPreviewFailed')}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/FilePreview.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/FilePreview.tsx
new file mode 100644
index 0000000000..023e271d3f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/FilePreview.tsx
@@ -0,0 +1,149 @@
+import { useEffect, useState } from 'react';
+import { AlertCircle, LoaderCircle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { MarkdownRenderer } from '../MarkdownRenderer';
+import { CodePreview } from './CodePreview';
+import { DocxPreview } from './DocxPreview';
+import { PresentationPreview } from './PresentationPreview';
+import { SpreadsheetPreview } from './SpreadsheetPreview';
+import { artifactBinaryPreviewUrl, artifactTextPreviewUrl, previewKind, type PreviewKind } from './filePreviewModel';
+
+export type PreviewArtifact = {
+ id: string;
+ name: string;
+ mimeType?: string;
+ downloadUrl?: string;
+ path?: string;
+ size?: number;
+};
+
+type TextKind = Extract<PreviewKind, 'markdown' | 'text' | 'code' | 'json' | 'jsonl'>;
+
+function Notice({ children }: { children: string }) {
+ return (
+ <div className="flex min-h-[240px] items-center justify-center text-sm text-text-muted" data-testid="artifact-preview-notice">
+ <div className="flex items-center gap-2 rounded-md border border-border bg-secondary px-3 py-2">
+ <AlertCircle size={15} />
+ {children}
+ </div>
+ </div>
+ );
+}
+
+function TextPreview({ artifact, kind }: { artifact: PreviewArtifact; kind: TextKind }) {
+ const { t } = useTranslation();
+ const [state, setState] = useState<{ content: string; error: boolean; loading: boolean }>({ content: '', error: false, loading: true });
+ useEffect(() => {
+ const url = artifactTextPreviewUrl(artifact, window.location.origin);
+ if (!url) {
+ setState({ content: '', error: true, loading: false });
+ return;
+ }
+ let cancelled = false;
+ setState({ content: '', error: false, loading: true });
+ void fetch(url, { cache: 'no-store' })
+ .then(async response => {
+ const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
+ if (!response.ok || contentType.includes('text/html')) throw new Error('read_failed');
+ return response.text();
+ })
+ .then(content => {
+ if (!cancelled) setState({ content, error: false, loading: false });
+ })
+ .catch(() => {
+ if (!cancelled) setState({ content: '', error: true, loading: false });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [artifact.downloadUrl, artifact.path]);
+ if (state.loading)
+ return (
+ <div className="flex min-h-[240px] items-center justify-center gap-2 text-sm text-text-muted">
+ <LoaderCircle className="animate-spin" size={16} />
+ {t('common.loading')}
+ </div>
+ );
+ if (state.error) return <Notice>{t('artifacts.previewFailed')}</Notice>;
+ if (kind === 'markdown')
+ return <MarkdownRenderer content={state.content} className="chat-text chat-markdown h-full max-w-none overflow-auto" testId="artifact-markdown-preview" />;
+ if (kind === 'code') return <CodePreview content={state.content} name={artifact.name} mimeType={artifact.mimeType} />;
+ if (kind === 'json' || kind === 'jsonl') {
+ try {
+ const value =
+ kind === 'json'
+ ? JSON.parse(state.content)
+ : state.content
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .map(line => JSON.parse(line));
+ return (
+ <pre className="m-0 h-full w-full max-w-full overflow-auto bg-transparent text-xs text-text" data-testid="artifact-json-preview">
+ {JSON.stringify(value, null, 2)}
+ </pre>
+ );
+ } catch {
+ return <Notice>{t('artifacts.invalidJson')}</Notice>;
+ }
+ }
+ return (
+ <pre className="m-0 h-full w-full max-w-full overflow-auto bg-transparent text-xs text-text" data-testid="artifact-text-preview">
+ {state.content}
+ </pre>
+ );
+}
+
+export function FilePreview({
+ artifact,
+ onPresentationStructureInvalidChange,
+}: {
+ artifact: PreviewArtifact;
+ onPresentationStructureInvalidChange?: (artifactId: string, invalid: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const kind = previewKind(artifact);
+ const url = artifactBinaryPreviewUrl(artifact, window.location.origin);
+ if (!url) return <Notice>{t('artifacts.previewMissingPath')}</Notice>;
+ if (kind === 'unsupported') return <Notice>{t('artifacts.previewUnsupported')}</Notice>;
+
+ switch (kind) {
+ case 'markdown':
+ case 'text':
+ case 'code':
+ case 'json':
+ case 'jsonl':
+ return <TextPreview artifact={artifact} kind={kind} />;
+ case 'html':
+ return (
+ <iframe
+ title={artifact.name}
+ src={url}
+ sandbox=""
+ className="block h-full min-h-full w-full border-0 bg-transparent"
+ data-testid="artifact-html-preview"
+ />
+ );
+ case 'image':
+ return (
+ <div className="flex h-full min-h-0 w-full items-center justify-center overflow-hidden">
+ <img src={url} alt={artifact.name} className="h-full w-full object-contain" data-testid="artifact-image-preview" />
+ </div>
+ );
+ case 'pdf':
+ return <iframe title={artifact.name} src={url} className="block h-full min-h-full w-full border-0 bg-transparent" data-testid="artifact-pdf-preview" />;
+ case 'docx':
+ return <DocxPreview url={url} title={artifact.name} />;
+ case 'spreadsheet':
+ return <SpreadsheetPreview url={url} title={artifact.name} size={artifact.size} />;
+ case 'presentation':
+ return (
+ <PresentationPreview
+ artifactId={artifact.id}
+ url={url}
+ title={artifact.name}
+ size={artifact.size}
+ onStructureInvalidChange={onPresentationStructureInvalidChange}
+ />
+ );
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/PresentationPreview.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/PresentationPreview.tsx
new file mode 100644
index 0000000000..e0c81cf980
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/PresentationPreview.tsx
@@ -0,0 +1,928 @@
+import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from 'react';
+import { AlertCircle, ChevronLeft, ChevronRight, LoaderCircle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { categoryCenter, categoryPoint, clusteredCategoryBand, ensureNonZeroAxisSpan, linearPosition, spanFromBaseline } from './chartGeometry';
+import {
+ MAX_PRESENTATION_PREVIEW_BYTES,
+ presentationLineHeight,
+ type PresentationChart,
+ type PresentationData,
+ type PresentationFill,
+ type PresentationImage,
+ type PresentationNode,
+ type PresentationParagraph,
+ type PresentationShape,
+ type PresentationSlide,
+ type PresentationSpacing,
+ type PresentationTable,
+ type PresentationText,
+ type PresentationWorkerResponse,
+} from './pptxPreviewModel';
+
+type PreviewState = 'loading' | 'ready' | 'error' | 'resource-limit' | 'too-large';
+
+function PreviewMessage({ children, danger = false }: { children: string; danger?: boolean }) {
+ return (
+ <div
+ className={clsx('flex h-full min-h-[240px] items-center justify-center gap-2 p-6 text-sm', danger ? 'text-danger' : 'text-text-muted')}
+ role={danger ? 'alert' : undefined}
+ >
+ <AlertCircle size={16} />
+ <span>{children}</span>
+ </div>
+ );
+}
+
+export function PresentationPreview({
+ artifactId,
+ url,
+ title,
+ size,
+ onStructureInvalidChange,
+}: {
+ artifactId: string;
+ url: string;
+ title: string;
+ size?: number;
+ onStructureInvalidChange?: (artifactId: string, invalid: boolean) => void;
+}) {
+ const { t } = useTranslation();
+ const [state, setState] = useState<PreviewState>(size !== undefined && size > MAX_PRESENTATION_PREVIEW_BYTES ? 'too-large' : 'loading');
+ const [presentation, setPresentation] = useState<PresentationData | null>(null);
+
+ useEffect(() => {
+ onStructureInvalidChange?.(artifactId, false);
+ if (size !== undefined && size > MAX_PRESENTATION_PREVIEW_BYTES) {
+ setState('too-large');
+ setPresentation(null);
+ return;
+ }
+ const controller = new AbortController();
+ const worker = new Worker(new URL('./pptxPreview.worker.ts', import.meta.url), { type: 'module' });
+ let cancelled = false;
+ setState('loading');
+ setPresentation(null);
+ worker.onmessage = (event: MessageEvent<PresentationWorkerResponse>) => {
+ if (cancelled) return;
+ if (event.data.type === 'ready') {
+ setPresentation(event.data.presentation);
+ setState('ready');
+ onStructureInvalidChange?.(
+ artifactId,
+ event.data.presentation.slides.some(slide => slide.status === 'invalid'),
+ );
+ } else {
+ console.error('Failed to parse presentation preview', event.data.message);
+ setState(event.data.code === 'resource-limit' ? 'resource-limit' : 'error');
+ }
+ worker.terminate();
+ };
+ worker.onerror = event => {
+ if (!cancelled) {
+ console.error('Presentation preview worker failed', event.message);
+ setState('error');
+ }
+ worker.terminate();
+ };
+ void fetch(url, { cache: 'no-store', signal: controller.signal })
+ .then(async response => {
+ const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
+ const contentLength = Number(response.headers.get('content-length'));
+ if (!response.ok || contentType.includes('text/html') || contentType.includes('application/json'))
+ throw new Error(`PPTX request failed with HTTP ${response.status}`);
+ if (Number.isFinite(contentLength) && contentLength > MAX_PRESENTATION_PREVIEW_BYTES) throw new Error('presentation_too_large');
+ return readLimitedResponse(response);
+ })
+ .then(buffer => {
+ if (!cancelled) worker.postMessage({ type: 'parse', buffer }, [buffer]);
+ })
+ .catch(error => {
+ if (cancelled || controller.signal.aborted) return;
+ setState(error instanceof Error && error.message === 'presentation_too_large' ? 'too-large' : 'error');
+ worker.terminate();
+ });
+ return () => {
+ cancelled = true;
+ controller.abort();
+ worker.terminate();
+ };
+ }, [artifactId, onStructureInvalidChange, size, url]);
+
+ if (state === 'loading') {
+ return (
+ <div
+ className="flex h-full min-h-[240px] items-center justify-center gap-2 text-sm text-text-muted"
+ aria-label={title}
+ data-testid="artifact-presentation-preview"
+ >
+ <LoaderCircle className="animate-spin" size={16} />
+ {t('common.loading')}
+ </div>
+ );
+ }
+ if (state === 'too-large')
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-presentation-preview">
+ <PreviewMessage danger>{t('artifacts.presentationTooLarge', { size: '50 MiB' })}</PreviewMessage>
+ </div>
+ );
+ if (state === 'resource-limit')
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-presentation-preview">
+ <PreviewMessage danger>{t('artifacts.presentationResourceLimitExceeded')}</PreviewMessage>
+ </div>
+ );
+ if (state === 'error' || !presentation)
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-presentation-preview">
+ <PreviewMessage danger>{t('artifacts.presentationPreviewFailed')}</PreviewMessage>
+ </div>
+ );
+ return <PresentationViewer presentation={presentation} title={title} />;
+}
+
+async function readLimitedResponse(response: Response): Promise<ArrayBuffer> {
+ if (!response.body) throw new Error('presentation_response_body_missing');
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > MAX_PRESENTATION_PREVIEW_BYTES) {
+ await reader.cancel();
+ throw new Error('presentation_too_large');
+ }
+ chunks.push(value);
+ }
+ const result = new Uint8Array(size);
+ let offset = 0;
+ chunks.forEach(chunk => {
+ result.set(chunk, offset);
+ offset += chunk.byteLength;
+ });
+ return result.buffer;
+}
+
+function PresentationViewer({ presentation, title }: { presentation: PresentationData; title: string }) {
+ const { t } = useTranslation();
+ const [slideIndex, setSlideIndex] = useState(0);
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const thumbnailListRef = useRef<HTMLDivElement>(null);
+ const thumbnailListId = useId();
+ const [thumbnailScrollState, setThumbnailScrollState] = useState({ isOverflowing: false, canScrollBack: false, canScrollForward: false });
+ const [viewport, setViewport] = useState({ width: 0, height: 0 });
+ const activeSlide = presentation.slides[slideIndex] ?? presentation.slides[0];
+ useEffect(() => {
+ const element = canvasRef.current;
+ if (!element) return;
+ const update = () => setViewport({ width: element.clientWidth, height: element.clientHeight });
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+ useEffect(() => {
+ thumbnailListRef.current?.querySelector<HTMLElement>('[aria-current="page"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ }, [slideIndex]);
+ const updateThumbnailScrollState = useCallback(() => {
+ const element = thumbnailListRef.current;
+ if (!element) return;
+ const isOverflowing = element.scrollWidth > element.clientWidth;
+ const next = {
+ isOverflowing,
+ canScrollBack: isOverflowing && element.scrollLeft > 0,
+ canScrollForward: isOverflowing && element.scrollLeft < element.scrollWidth - element.clientWidth,
+ };
+ setThumbnailScrollState(current =>
+ current.isOverflowing === next.isOverflowing &&
+ current.canScrollBack === next.canScrollBack &&
+ current.canScrollForward === next.canScrollForward
+ ? current
+ : next,
+ );
+ }, []);
+ useLayoutEffect(() => {
+ const element = thumbnailListRef.current;
+ if (!element) return;
+ updateThumbnailScrollState();
+ const observer = new ResizeObserver(updateThumbnailScrollState);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [presentation.slides.length, updateThumbnailScrollState]);
+ const scrollThumbnailList = useCallback((direction: -1 | 1) => {
+ const element = thumbnailListRef.current;
+ if (!element) return;
+ element.scrollBy({ left: direction * element.clientWidth, behavior: 'smooth' });
+ }, []);
+ const fit = Math.min(Math.max(0.05, (viewport.width - 48) / presentation.width), Math.max(0.05, (viewport.height - 48) / presentation.height));
+ const scale = fit;
+ const goTo = (next: number) => setSlideIndex(Math.min(Math.max(next, 0), presentation.slides.length - 1));
+ return (
+ <div
+ className="flex h-full min-h-0 w-full flex-col overflow-hidden border border-border bg-card"
+ aria-label={title}
+ data-testid="artifact-presentation-preview"
+ >
+ <section className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <div ref={canvasRef} className="min-h-0 flex-1 overflow-auto bg-bg-muted p-6">
+ <div
+ className="flex min-h-full min-w-full items-center justify-center"
+ style={{ width: Math.max(viewport.width - 48, presentation.width * scale), height: Math.max(viewport.height - 48, presentation.height * scale) }}
+ >
+ <SlideCanvas presentation={presentation} slide={activeSlide} scale={scale} />
+ </div>
+ </div>
+ </section>
+ <nav className="shrink-0 border-t border-border bg-panel" aria-label={t('artifacts.presentationSlides')}>
+ <div className="relative">
+ <div
+ ref={thumbnailListRef}
+ id={thumbnailListId}
+ className="flex min-w-0 gap-2 overflow-x-auto overflow-y-hidden p-2 [overscroll-behavior-inline:contain]"
+ onScroll={updateThumbnailScrollState}
+ >
+ {presentation.slides.map((slide, index) => (
+ <button
+ key={slide.id}
+ type="button"
+ className={clsx(
+ 'flex w-fit shrink-0 flex-col items-center gap-1 rounded border p-1 transition-colors',
+ index === slideIndex ? 'border-accent bg-accent-subtle' : 'border-transparent hover:border-border hover:bg-secondary',
+ )}
+ onClick={() => goTo(index)}
+ aria-current={index === slideIndex ? 'page' : undefined}
+ aria-label={t('artifacts.presentationGoToSlide', { index: index + 1 })}
+ >
+ <SlideThumbnail presentation={presentation} slide={slide} active={Math.abs(index - slideIndex) <= 1} />
+ <span className="text-[11px] leading-none tabular-nums text-text-muted" aria-hidden="true">
+ {index + 1}
+ </span>
+ </button>
+ ))}
+ </div>
+ {thumbnailScrollState.isOverflowing && (
+ <>
+ <button
+ type="button"
+ className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full border border-border bg-card p-1 text-text-muted shadow-sm transition-colors hover:bg-secondary hover:text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40"
+ onClick={() => scrollThumbnailList(-1)}
+ disabled={!thumbnailScrollState.canScrollBack}
+ aria-controls={thumbnailListId}
+ aria-label={t('artifacts.presentationScrollThumbnailsPrevious')}
+ >
+ <ChevronLeft size={16} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full border border-border bg-card p-1 text-text-muted shadow-sm transition-colors hover:bg-secondary hover:text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40"
+ onClick={() => scrollThumbnailList(1)}
+ disabled={!thumbnailScrollState.canScrollForward}
+ aria-controls={thumbnailListId}
+ aria-label={t('artifacts.presentationScrollThumbnailsNext')}
+ >
+ <ChevronRight size={16} aria-hidden="true" />
+ </button>
+ </>
+ )}
+ </div>
+ </nav>
+ </div>
+ );
+}
+
+function SlideThumbnail({ presentation, slide, active }: { presentation: PresentationData; slide: PresentationSlide; active: boolean }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [visible, setVisible] = useState(active);
+ useEffect(() => {
+ if (active) {
+ setVisible(true);
+ return;
+ }
+ setVisible(false);
+ const element = ref.current;
+ if (!element || !('IntersectionObserver' in window)) return;
+ const observer = new IntersectionObserver(entries => setVisible(entries.some(entry => entry.isIntersecting)), { rootMargin: '0px 160px' });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [active]);
+ const scale = Math.min(134 / presentation.width, 82 / presentation.height);
+ return (
+ <div
+ ref={ref}
+ className="relative flex shrink-0 items-center justify-center overflow-hidden bg-white"
+ style={{ width: presentation.width * scale, height: presentation.height * scale }}
+ aria-hidden="true"
+ >
+ {visible || active ? <SlideCanvas presentation={presentation} slide={slide} scale={scale} /> : null}
+ </div>
+ );
+}
+
+function SlideCanvas({ presentation, slide, scale }: { presentation: PresentationData; slide: PresentationSlide; scale: number }) {
+ const background = fillStyle(slide.background);
+ return (
+ <div className="shrink-0" style={{ width: presentation.width * scale, height: presentation.height * scale }}>
+ <div
+ className="relative bg-white shadow-sm"
+ style={{ width: presentation.width, height: presentation.height, ...background, transform: `scale(${scale})`, transformOrigin: 'top left' }}
+ >
+ {slide.status !== 'invalid' && slide.nodes.map(node => <SlideNode key={node.id} node={node} />)}
+ </div>
+ </div>
+ );
+}
+
+function SlideNode({ node }: { node: PresentationNode }) {
+ if (node.type === 'shape') return <ShapeNode shape={node} />;
+ if (node.type === 'image') return <ImageNode image={node} />;
+ if (node.type === 'table') return <TableNode table={node} />;
+ if (node.type === 'chart') return <ChartNode chart={node} />;
+ return <UnsupportedNode node={node} />;
+}
+
+function nodeStyle(node: PresentationNode): CSSProperties {
+ const transforms = [`rotate(${node.rotation ?? 0}deg)`];
+ if (node.flipH) transforms.push('scaleX(-1)');
+ if (node.flipV) transforms.push('scaleY(-1)');
+ return {
+ position: 'absolute',
+ left: node.x,
+ top: node.y,
+ width: node.width,
+ height: node.height,
+ transform: transforms.join(' '),
+ transformOrigin: 'center center',
+ };
+}
+
+function ShapeNode({ shape }: { shape: PresentationShape }) {
+ return (
+ <div style={nodeStyle(shape)}>
+ <ShapeVector shape={shape} />
+ {shape.text && <TextBox text={shape.text} />}
+ </div>
+ );
+}
+
+function ShapeVector({ shape }: { shape: PresentationShape }) {
+ const gradientId = useId().replace(/:/g, '');
+ const width = Math.max(0.001, shape.width);
+ const height = Math.max(0.001, shape.height);
+ const fill = shape.fill.kind === 'gradient' ? `url(#${gradientId})` : shape.fill.kind === 'solid' ? shape.fill.color : 'transparent';
+ const opacity = shape.fill.kind === 'solid' ? 1 - (shape.fill.transparency ?? 0) : 1;
+ const stroke = shape.stroke?.color ?? 'none';
+ const dash = shape.stroke?.dash;
+ const common = { fill, fillOpacity: opacity, stroke, strokeWidth: shape.stroke?.width ?? 0, strokeDasharray: dash };
+ return (
+ <svg className="absolute inset-0 h-full w-full overflow-visible" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
+ {shape.fill.kind === 'gradient' && (
+ <defs>
+ <linearGradient id={gradientId} gradientTransform={`rotate(${shape.fill.angle})`}>
+ <>
+ {shape.fill.stops.map(stop => (
+ <stop key={stop.offset} offset={`${stop.offset * 100}%`} stopColor={stop.color} stopOpacity={1 - (stop.transparency ?? 0)} />
+ ))}
+ </>
+ </linearGradient>
+ </defs>
+ )}
+ <ShapePath shape={shape} common={common} />
+ </svg>
+ );
+}
+
+function ShapePath({ shape, common }: { shape: PresentationShape; common: Record<string, string | number | undefined> }) {
+ const { geometry } = shape;
+ const width = Math.max(0.001, shape.width);
+ const height = Math.max(0.001, shape.height);
+ const points = (values: Array<[number, number]>) => values.map(([x, y]) => `${x * width},${y * height}`).join(' ');
+ if (geometry === 'ellipse') return <ellipse cx={width / 2} cy={height / 2} rx={width / 2} ry={height / 2} {...common} />;
+ if (geometry === 'roundRect') {
+ const adjustment = Math.min(50_000, Math.max(0, shape.adjustments?.adj ?? 16_667));
+ const radius = (Math.min(width, height) * adjustment) / 100_000;
+ return <rect x="0" y="0" width={width} height={height} rx={radius} ry={radius} {...common} />;
+ }
+ if (geometry === 'triangle')
+ return (
+ <polygon
+ points={points([
+ [0.5, 0],
+ [1, 1],
+ [0, 1],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'rtTriangle')
+ return (
+ <polygon
+ points={points([
+ [0, 0],
+ [1, 1],
+ [0, 1],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'diamond')
+ return (
+ <polygon
+ points={points([
+ [0.5, 0],
+ [1, 0.5],
+ [0.5, 1],
+ [0, 0.5],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'parallelogram')
+ return (
+ <polygon
+ points={points([
+ [0.2, 0],
+ [1, 0],
+ [0.8, 1],
+ [0, 1],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'trapezoid')
+ return (
+ <polygon
+ points={points([
+ [0.2, 0],
+ [0.8, 0],
+ [1, 1],
+ [0, 1],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'hexagon')
+ return (
+ <polygon
+ points={points([
+ [0.25, 0],
+ [0.75, 0],
+ [1, 0.5],
+ [0.75, 1],
+ [0.25, 1],
+ [0, 0.5],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'pentagon')
+ return (
+ <polygon
+ points={points([
+ [0.5, 0],
+ [1, 0.38],
+ [0.81, 1],
+ [0.19, 1],
+ [0, 0.38],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'chevron')
+ return (
+ <polygon
+ points={points([
+ [0, 0],
+ [0.58, 0],
+ [1, 0.5],
+ [0.58, 1],
+ [0, 1],
+ [0.42, 0.5],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'plus')
+ return (
+ <polygon
+ points={points([
+ [0.35, 0],
+ [0.65, 0],
+ [0.65, 0.35],
+ [1, 0.35],
+ [1, 0.65],
+ [0.65, 0.65],
+ [0.65, 1],
+ [0.35, 1],
+ [0.35, 0.65],
+ [0, 0.65],
+ [0, 0.35],
+ [0.35, 0.35],
+ ])}
+ {...common}
+ />
+ );
+ if (geometry === 'minus') return <rect x="0" y={height * 0.35} width={width} height={height * 0.3} {...common} />;
+ if (geometry === 'lineVertical') return <line x1={width / 2} y1="0" x2={width / 2} y2={height} {...common} />;
+ if (geometry === 'line' || geometry.includes('Connector')) return <line x1="0" y1={height / 2} x2={width} y2={height / 2} {...common} />;
+ return <rect x="0" y="0" width={width} height={height} {...common} />;
+}
+
+function TextBox({ text }: { text: PresentationText }) {
+ const frameRef = useRef<HTMLDivElement>(null);
+ const contentRef = useRef<HTMLDivElement>(null);
+ useLayoutEffect(() => {
+ const frame = frameRef.current;
+ const content = contentRef.current;
+ if (!frame || !content) return;
+ const fit = () => {
+ frame.style.setProperty('--ppt-text-scale', '1');
+ if (text.autoFit !== 'shrink') {
+ frame.dataset.autofitScale = '1';
+ return;
+ }
+ const computed = getComputedStyle(frame);
+ const availableWidth = frame.clientWidth - Number.parseFloat(computed.paddingLeft) - Number.parseFloat(computed.paddingRight);
+ const availableHeight = frame.clientHeight - Number.parseFloat(computed.paddingTop) - Number.parseFloat(computed.paddingBottom);
+ const fits = (scale: number) => {
+ frame.style.setProperty('--ppt-text-scale', String(scale));
+ return content.scrollWidth <= availableWidth + 0.5 && content.scrollHeight <= availableHeight + 0.5;
+ };
+ if (fits(1)) {
+ frame.dataset.autofitScale = '1';
+ return;
+ }
+ let lower = 0.01;
+ let upper = 1;
+ for (let iteration = 0; iteration < 12; iteration += 1) {
+ const candidate = (lower + upper) / 2;
+ if (fits(candidate)) lower = candidate;
+ else upper = candidate;
+ }
+ frame.style.setProperty('--ppt-text-scale', String(lower));
+ frame.dataset.autofitScale = String(lower);
+ };
+ fit();
+ let cancelled = false;
+ void document.fonts?.ready.then(() => {
+ if (!cancelled) fit();
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [text]);
+ const style: CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ flexDirection: 'column',
+ justifyContent: text.anchor === 'middle' ? 'center' : text.anchor === 'bottom' ? 'flex-end' : 'flex-start',
+ boxSizing: 'border-box',
+ padding: `${text.margin.top}px ${text.margin.right}px ${text.margin.bottom}px ${text.margin.left}px`,
+ overflow: text.autoFit === 'resize' ? 'visible' : 'hidden',
+ color: text.color ?? '#000000',
+ fontFamily: fontStack(text.fontFamily, text.eastAsianFontFamily, text.complexScriptFontFamily),
+ fontSize: scaledFontSize(text.fontSize),
+ fontSynthesis: 'none',
+ writingMode: text.vertical ? (text.verticalReverse ? 'vertical-lr' : 'vertical-rl') : undefined,
+ };
+ return (
+ <div ref={frameRef} style={style}>
+ <div ref={contentRef} style={{ width: '100%', flexShrink: 0 }}>
+ {text.paragraphs.map((paragraph, index) => (
+ <TextParagraph key={index} paragraph={paragraph} defaults={text} />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function TextParagraph({ paragraph, defaults }: { paragraph: PresentationParagraph; defaults: PresentationText }) {
+ const largestFontSize = Math.max(defaults.fontSize ?? 0, ...paragraph.runs.map(run => run.fontSize ?? 0)) || undefined;
+ const hangingIndent = paragraph.bullet && (paragraph.indent ?? 0) < 0 ? -(paragraph.indent ?? 0) : undefined;
+ const style: CSSProperties = {
+ margin: 0,
+ paddingLeft: paragraph.marginLeft,
+ textIndent: paragraph.indent,
+ textAlign: paragraph.align,
+ marginTop: paragraphSpacing(paragraph.spaceBefore),
+ marginBottom: paragraphSpacing(paragraph.spaceAfter),
+ lineHeight: presentationLineHeight(paragraph.lineSpacing),
+ fontSize: scaledFontSize(largestFontSize),
+ whiteSpace: 'pre-wrap',
+ lineBreak: 'strict',
+ overflowWrap: 'normal',
+ wordBreak: 'normal',
+ };
+ const content = paragraph.runs.map((run, index) => <TextRun key={index} run={run} defaults={defaults} />);
+ if (!paragraph.bullet) return <p style={style}>{content}</p>;
+ return (
+ <p style={style}>
+ <span style={{ display: 'inline-block', textIndent: 0, width: hangingIndent, marginRight: hangingIndent === undefined ? '0.4em' : undefined }}>
+ {paragraph.bullet.kind === 'number' ? '1.' : paragraph.bullet.value}
+ </span>
+ {content}
+ </p>
+ );
+}
+
+function TextRun({ run, defaults }: { run: PresentationParagraph['runs'][number]; defaults: PresentationText }) {
+ const fontSize = run.fontSize ?? defaults.fontSize;
+ const style: CSSProperties = {
+ color: run.color ?? defaults.color,
+ fontFamily: fontStack(
+ run.fontFamily ?? defaults.fontFamily,
+ run.eastAsianFontFamily ?? defaults.eastAsianFontFamily,
+ run.complexScriptFontFamily ?? defaults.complexScriptFontFamily,
+ ),
+ fontSize: scaledFontSize(fontSize),
+ letterSpacing: run.characterSpacing,
+ fontKerning: run.kerningThreshold !== undefined && fontSize !== undefined && fontSize < run.kerningThreshold ? 'none' : 'normal',
+ fontSynthesis: 'none',
+ fontWeight: run.bold ? 700 : undefined,
+ fontStyle: run.italic ? 'italic' : undefined,
+ textDecoration: run.underline ? 'underline' : undefined,
+ verticalAlign: run.baseline ? `${run.baseline / 1_000}%` : undefined,
+ whiteSpace: 'pre-wrap',
+ };
+ return <span style={style}>{run.text}</span>;
+}
+
+function paragraphSpacing(spacing: PresentationSpacing | undefined): string | number | undefined {
+ if (!spacing) return undefined;
+ return spacing.kind === 'absolute' ? spacing.value : `${spacing.value}em`;
+}
+
+function scaledFontSize(value: number | undefined): string | undefined {
+ return value === undefined ? undefined : `calc(${value}px * var(--ppt-text-scale, 1))`;
+}
+
+function fontStack(...fonts: Array<string | undefined>): string {
+ const declared = [...new Set(fonts.map(font => font?.trim()).filter((font): font is string => Boolean(font)))];
+ return [...declared.map(font => `"${font.replace(/"/g, '')}"`), 'sans-serif'].join(', ');
+}
+
+function ImageNode({ image }: { image: PresentationImage }) {
+ const [source, setSource] = useState<string>();
+ useEffect(() => {
+ const objectUrl = URL.createObjectURL(image.image);
+ setSource(objectUrl);
+ return () => URL.revokeObjectURL(objectUrl);
+ }, [image.image]);
+ const crop = image.crop;
+ const visibleWidth = Math.max(0.001, 1 - (crop?.left ?? 0) - (crop?.right ?? 0));
+ const visibleHeight = Math.max(0.001, 1 - (crop?.top ?? 0) - (crop?.bottom ?? 0));
+ return (
+ <div style={{ ...nodeStyle(image), overflow: 'hidden' }}>
+ {source && (
+ <img
+ src={source}
+ alt={image.alt}
+ draggable={false}
+ className="absolute max-w-none"
+ style={{
+ width: `${100 / visibleWidth}%`,
+ height: `${100 / visibleHeight}%`,
+ left: `${(-(crop?.left ?? 0) / visibleWidth) * 100}%`,
+ top: `${(-(crop?.top ?? 0) / visibleHeight) * 100}%`,
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function TableNode({ table }: { table: PresentationTable }) {
+ const maximumCells = Math.max(1, ...table.rows.map(row => row.cells.length));
+ const columns = table.columns.length > 0 ? table.columns : Array.from({ length: maximumCells }, () => table.width / maximumCells);
+ return (
+ <div
+ style={{
+ ...nodeStyle(table),
+ display: 'grid',
+ gridTemplateColumns: columns.map(width => `${width}px`).join(' '),
+ gridTemplateRows: table.rows.map(row => `${row.height}px`).join(' '),
+ overflow: 'hidden',
+ }}
+ >
+ {table.rows.flatMap((row, rowIndex) =>
+ row.cells.map((cell, cellIndex) => {
+ if (cell.merged) return null;
+ return (
+ <div
+ key={`${rowIndex}:${cellIndex}`}
+ style={{
+ position: 'relative',
+ boxSizing: 'border-box',
+ minWidth: 0,
+ minHeight: 0,
+ gridColumn: `span ${cell.colSpan ?? 1}`,
+ gridRow: `span ${cell.rowSpan ?? 1}`,
+ border: cell.stroke ? `${cell.stroke.width}px solid ${cell.stroke.color}` : '1px solid #B7B7B7',
+ ...fillStyle(cell.fill),
+ overflow: 'hidden',
+ }}
+ >
+ {cell.text && <TextBox text={cell.text} />}
+ </div>
+ );
+ }),
+ )}
+ </div>
+ );
+}
+
+function ChartNode({ chart }: { chart: PresentationChart }) {
+ const allValues = chart.series.flatMap(series => series.values);
+ if (allValues.length === 0) return <UnsupportedNode node={{ ...chart, type: 'unsupported', feature: 'chart without data' }} />;
+ const width = 800;
+ const height = 480;
+ const plot = { left: chart.chartType === 'bar' ? 145 : 78, top: chart.title ? 80 : 38, right: 716, bottom: 410 };
+ const maximum = Math.max(0, ...allValues);
+ const minimum = Math.min(0, ...allValues);
+ const { maximum: axisMaximum } = ensureNonZeroAxisSpan(minimum, maximum, 1);
+ const span = axisMaximum - minimum;
+ const categoryCount = Math.max(1, ...chart.series.map(series => Math.max(series.categories.length, series.values.length)));
+ const categories =
+ chart.series.find(series => series.categories.length > 0)?.categories ?? Array.from({ length: categoryCount }, (_, index) => String(index + 1));
+ const colors = ['#4472C4', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5', '#70AD47'];
+ const xAtCategory = (index: number) =>
+ chart.chartType === 'line' ? categoryPoint(index, categoryCount, plot.left, plot.right) : categoryCenter(index, categoryCount, plot.left, plot.right);
+ const yAtCategory = (index: number) => categoryCenter(index, categoryCount, plot.top, plot.bottom);
+ const xAtValue = (value: number) => linearPosition(value, minimum, axisMaximum, plot.left, plot.right);
+ const yAtValue = (value: number) => linearPosition(value, minimum, axisMaximum, plot.bottom, plot.top);
+ const zeroX = xAtValue(0);
+ const zeroY = yAtValue(0);
+ const chartLabel = chart.title || chart.name || 'Chart';
+ const legendSeries = chart.series.map((series, seriesIndex) => ({
+ series,
+ seriesIndex,
+ label: series.name || `Series ${seriesIndex + 1}`,
+ }));
+ return (
+ <figure className="absolute m-0 overflow-hidden bg-white text-black" style={nodeStyle(chart)}>
+ <svg className="h-full w-full" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" role="img" aria-label={chartLabel}>
+ <rect width={width} height={height} fill="#FFFFFF" />
+ {chart.title && (
+ <text x={width / 2} y="38" textAnchor="middle" fontSize="25" fontWeight="600">
+ {chart.title}
+ </text>
+ )}
+ {[0, 1, 2, 3, 4].map(index => {
+ const value = minimum + (span * index) / 4;
+ if (chart.chartType === 'bar') {
+ const x = xAtValue(value);
+ return (
+ <g key={index}>
+ <line x1={x} x2={x} y1={plot.top} y2={plot.bottom} stroke="#D9D9D9" />
+ <text x={x} y={plot.bottom + 22} textAnchor="middle" fontSize="12">
+ {Number(value.toFixed(2))}
+ </text>
+ </g>
+ );
+ }
+ const y = yAtValue(value);
+ return (
+ <g key={index}>
+ <line x1={plot.left} x2={plot.right} y1={y} y2={y} stroke="#D9D9D9" />
+ <text x={plot.left - 9} y={y + 4} textAnchor="end" fontSize="12">
+ {Number(value.toFixed(2))}
+ </text>
+ </g>
+ );
+ })}
+ {chart.chartType !== 'pie' &&
+ (chart.chartType === 'bar' ? (
+ <>
+ <line x1={zeroX} x2={zeroX} y1={plot.top} y2={plot.bottom} stroke="#777" />
+ <line x1={plot.left} x2={plot.right} y1={plot.bottom} y2={plot.bottom} stroke="#777" />
+ {categories.map((category, index) => (
+ <text key={`${category}:${index}`} x={plot.left - 10} y={yAtCategory(index) + 4} textAnchor="end" fontSize="12">
+ {category}
+ </text>
+ ))}
+ </>
+ ) : (
+ <>
+ <line x1={plot.left} x2={plot.left} y1={plot.top} y2={plot.bottom} stroke="#777" />
+ <line x1={plot.left} x2={plot.right} y1={zeroY} y2={zeroY} stroke="#777" />
+ {categories.map((category, index) => (
+ <text key={`${category}:${index}`} x={xAtCategory(index)} y={plot.bottom + 22} textAnchor="middle" fontSize="12">
+ {category}
+ </text>
+ ))}
+ </>
+ ))}
+ <ChartMarks chart={chart} colors={colors} plot={plot} categoryCount={categoryCount} xAtCategory={xAtCategory} xAtValue={xAtValue} yAtValue={yAtValue} />
+ {legendSeries.map(({ series, seriesIndex, label }, legendIndex) => (
+ <g key={`${seriesIndex}:${label}`}>
+ <rect x="735" y={plot.top + legendIndex * 22} width="11" height="11" fill={series.color ?? colors[seriesIndex % colors.length]} />
+ <text x="752" y={plot.top + legendIndex * 22 + 10} fontSize="12">
+ {label}
+ </text>
+ </g>
+ ))}
+ </svg>
+ </figure>
+ );
+}
+
+function ChartMarks({
+ chart,
+ colors,
+ plot,
+ categoryCount,
+ xAtCategory,
+ xAtValue,
+ yAtValue,
+}: {
+ chart: PresentationChart;
+ colors: string[];
+ plot: { left: number; top: number; right: number; bottom: number };
+ categoryCount: number;
+ xAtCategory: (index: number) => number;
+ xAtValue: (value: number) => number;
+ yAtValue: (value: number) => number;
+}) {
+ if (chart.chartType === 'pie') {
+ const series = chart.series[0];
+ const total = series.values.reduce((sum, value) => sum + Math.max(value, 0), 0) || 1;
+ const centerX = (plot.left + plot.right) / 2;
+ const centerY = (plot.top + plot.bottom) / 2;
+ const radius = Math.min(plot.right - plot.left, plot.bottom - plot.top) * 0.34;
+ let angle = -Math.PI / 2;
+ return (
+ <>
+ {series.values.map((value, index) => {
+ const end = angle + (Math.max(value, 0) / total) * Math.PI * 2;
+ const path = sectorPath(centerX, centerY, radius, angle, end);
+ angle = end;
+ return <path key={index} d={path} fill={colors[index % colors.length]} stroke="#FFFFFF" />;
+ })}
+ </>
+ );
+ }
+ if (chart.chartType === 'column' || chart.chartType === 'bar') {
+ return (
+ <>
+ {chart.series.flatMap((series, seriesIndex) =>
+ series.values.map((value, index) => {
+ const color = series.color ?? colors[seriesIndex % colors.length];
+ if (chart.chartType === 'bar') {
+ const band = clusteredCategoryBand(index, categoryCount, seriesIndex, chart.series.length, plot.top, plot.bottom);
+ const valueSpan = spanFromBaseline(xAtValue(value), xAtValue(0));
+ return <rect key={`${seriesIndex}:${index}`} x={valueSpan.start} y={band.start} width={valueSpan.size} height={band.size} fill={color} />;
+ }
+ const band = clusteredCategoryBand(index, categoryCount, seriesIndex, chart.series.length, plot.left, plot.right);
+ const valueSpan = spanFromBaseline(yAtValue(value), yAtValue(0));
+ return <rect key={`${seriesIndex}:${index}`} x={band.start} y={valueSpan.start} width={band.size} height={valueSpan.size} fill={color} />;
+ }),
+ )}
+ </>
+ );
+ }
+ return (
+ <>
+ {chart.series.map((series, index) => (
+ <polyline
+ key={`${index}:${series.name ?? ''}`}
+ points={series.values.map((value, point) => `${xAtCategory(point)},${yAtValue(value)}`).join(' ')}
+ fill="none"
+ stroke={series.color ?? colors[index % colors.length]}
+ strokeWidth="4"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ ))}
+ </>
+ );
+}
+
+function UnsupportedNode({ node: _node }: { node: Extract<PresentationNode, { type: 'unsupported' }> }) {
+ return null;
+}
+
+function fillStyle(fill: PresentationFill): CSSProperties {
+ if (fill.kind === 'solid') return { backgroundColor: `${fill.color}${alphaHex(1 - (fill.transparency ?? 0))}` };
+ if (fill.kind === 'gradient')
+ return {
+ backgroundImage: `linear-gradient(${fill.angle}deg, ${fill.stops.map(stop => `${stop.color}${alphaHex(1 - (stop.transparency ?? 0))} ${stop.offset * 100}%`).join(', ')})`,
+ };
+ return {};
+}
+
+function alphaHex(value: number): string {
+ return Math.round(Math.min(1, Math.max(0, value)) * 255)
+ .toString(16)
+ .padStart(2, '0');
+}
+
+function sectorPath(centerX: number, centerY: number, radius: number, start: number, end: number): string {
+ const startX = centerX + radius * Math.cos(start);
+ const startY = centerY + radius * Math.sin(start);
+ const endX = centerX + radius * Math.cos(end);
+ const endY = centerY + radius * Math.sin(end);
+ return `M ${centerX} ${centerY} L ${startX} ${startY} A ${radius} ${radius} 0 ${end - start > Math.PI ? 1 : 0} 1 ${endX} ${endY} Z`;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/SpreadsheetPreview.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/SpreadsheetPreview.tsx
new file mode 100644
index 0000000000..ec33124618
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/SpreadsheetPreview.tsx
@@ -0,0 +1,733 @@
+import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type UIEvent as ReactUIEvent } from 'react';
+import { AlertCircle, ChevronDown, LoaderCircle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { categoryCenter, categoryPoint, clusteredCategoryBand, ensureNonZeroAxisSpan, linearPosition, spanFromBaseline } from './chartGeometry';
+import {
+ MAX_SPREADSHEET_PREVIEW_BYTES,
+ axisIndexAtOffset,
+ buildAxisMetrics,
+ columnLabel,
+ type SpreadsheetCellData,
+ type SpreadsheetCellStyle,
+ type SpreadsheetChart,
+ type SpreadsheetDrawingAnchor,
+ type SpreadsheetMergeRange,
+ type SpreadsheetSheetData,
+ type SpreadsheetWorkerResponse,
+ type SpreadsheetWorkbookData,
+} from './spreadsheetPreviewModel';
+
+type PreviewStatus = 'loading' | 'ready' | 'error' | 'resource-limit' | 'too-large';
+type Viewport = { width: number; height: number; scrollLeft: number; scrollTop: number };
+
+const ROW_HEADER_WIDTH = 48;
+const COLUMN_HEADER_HEIGHT = 28;
+const AXIS_OVERSCAN = 2;
+
+function PreviewMessage({ children, danger = false }: { children: string; danger?: boolean }) {
+ return (
+ <div
+ className={clsx('flex h-full min-h-[240px] items-center justify-center gap-2 p-6 text-sm', danger ? 'text-danger' : 'text-text-muted')}
+ role={danger ? 'alert' : undefined}
+ >
+ <AlertCircle size={16} />
+ <span>{children}</span>
+ </div>
+ );
+}
+
+export function SpreadsheetPreview({ url, title, size }: { url: string; title: string; size?: number }) {
+ const { t } = useTranslation();
+ const [status, setStatus] = useState<PreviewStatus>(size !== undefined && size > MAX_SPREADSHEET_PREVIEW_BYTES ? 'too-large' : 'loading');
+ const [workbook, setWorkbook] = useState<SpreadsheetWorkbookData | null>(null);
+
+ useEffect(() => {
+ if (size !== undefined && size > MAX_SPREADSHEET_PREVIEW_BYTES) {
+ setStatus('too-large');
+ setWorkbook(null);
+ return;
+ }
+
+ const abortController = new AbortController();
+ const worker = new Worker(new URL('./spreadsheetPreview.worker.ts', import.meta.url), { type: 'module' });
+ let cancelled = false;
+ setStatus('loading');
+ setWorkbook(null);
+
+ worker.onmessage = (event: MessageEvent<SpreadsheetWorkerResponse>) => {
+ if (cancelled) return;
+ if (event.data.type === 'ready') {
+ setWorkbook(event.data.workbook);
+ setStatus('ready');
+ } else {
+ console.error('Failed to parse XLSX preview', event.data.message);
+ setStatus(event.data.code === 'resource-limit' ? 'resource-limit' : 'error');
+ }
+ worker.terminate();
+ };
+ worker.onerror = event => {
+ if (cancelled) return;
+ console.error('XLSX preview worker failed', event.message);
+ setStatus('error');
+ worker.terminate();
+ };
+
+ void fetch(url, { cache: 'no-store', signal: abortController.signal })
+ .then(async response => {
+ const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
+ const contentLength = Number(response.headers.get('content-length'));
+ if (!response.ok || contentType.includes('text/html') || contentType.includes('application/json')) {
+ throw new Error(`XLSX request failed with HTTP ${response.status}`);
+ }
+ if (Number.isFinite(contentLength) && contentLength > MAX_SPREADSHEET_PREVIEW_BYTES) throw new Error('spreadsheet_too_large');
+ return readLimitedResponse(response);
+ })
+ .then(buffer => {
+ if (!cancelled) worker.postMessage({ type: 'parse', buffer }, [buffer]);
+ })
+ .catch(error => {
+ if (cancelled || abortController.signal.aborted) return;
+ setStatus(error instanceof Error && error.message === 'spreadsheet_too_large' ? 'too-large' : 'error');
+ worker.terminate();
+ });
+
+ return () => {
+ cancelled = true;
+ abortController.abort();
+ worker.terminate();
+ };
+ }, [size, url]);
+
+ if (status === 'loading') {
+ return (
+ <div
+ className="flex h-full min-h-[240px] items-center justify-center gap-2 text-sm text-text-muted"
+ aria-label={title}
+ data-testid="artifact-spreadsheet-preview"
+ >
+ <LoaderCircle className="animate-spin" size={16} />
+ {t('common.loading')}
+ </div>
+ );
+ }
+ if (status === 'too-large') {
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-spreadsheet-preview">
+ <PreviewMessage danger>{t('artifacts.spreadsheetTooLarge', { size: '50 MiB' })}</PreviewMessage>
+ </div>
+ );
+ }
+ if (status === 'resource-limit') {
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-spreadsheet-preview">
+ <PreviewMessage danger>{t('artifacts.spreadsheetResourceLimitExceeded')}</PreviewMessage>
+ </div>
+ );
+ }
+ if (status === 'error' || !workbook) {
+ return (
+ <div className="h-full" aria-label={title} data-testid="artifact-spreadsheet-preview">
+ <PreviewMessage danger>{t('artifacts.spreadsheetPreviewFailed')}</PreviewMessage>
+ </div>
+ );
+ }
+ return <WorkbookViewer workbook={workbook} title={title} />;
+}
+
+async function readLimitedResponse(response: Response): Promise<ArrayBuffer> {
+ if (!response.body) throw new Error('spreadsheet_response_body_missing');
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let byteLength = 0;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ byteLength += value.byteLength;
+ if (byteLength > MAX_SPREADSHEET_PREVIEW_BYTES) {
+ await reader.cancel();
+ throw new Error('spreadsheet_too_large');
+ }
+ chunks.push(value);
+ }
+
+ const buffer = new Uint8Array(byteLength);
+ let offset = 0;
+ chunks.forEach(chunk => {
+ buffer.set(chunk, offset);
+ offset += chunk.byteLength;
+ });
+ return buffer.buffer;
+}
+
+function WorkbookViewer({ workbook, title }: { workbook: SpreadsheetWorkbookData; title: string }) {
+ const { t } = useTranslation();
+ const tabPanelId = useId();
+ const visibleSheets = useMemo(() => workbook.sheets.filter(sheet => sheet.state === 'visible'), [workbook.sheets]);
+ const requestedActiveSheet = workbook.sheets[workbook.activeSheetIndex];
+ const initialSheet = visibleSheets.find(sheet => sheet.id === requestedActiveSheet?.id) ?? visibleSheets[0];
+ const [activeSheetId, setActiveSheetId] = useState(initialSheet?.id ?? 0);
+ const tabRefs = useRef(new Map<number, HTMLButtonElement>());
+ const activeSheet = visibleSheets.find(sheet => sheet.id === activeSheetId) ?? visibleSheets[0];
+
+ const activateSheet = (sheetId: number, focus = false) => {
+ setActiveSheetId(sheetId);
+ if (focus) requestAnimationFrame(() => tabRefs.current.get(sheetId)?.focus());
+ };
+
+ const handleTabKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>, index: number) => {
+ let targetIndex: number | null = null;
+ if (event.key === 'ArrowRight') targetIndex = (index + 1) % visibleSheets.length;
+ else if (event.key === 'ArrowLeft') targetIndex = (index - 1 + visibleSheets.length) % visibleSheets.length;
+ else if (event.key === 'Home') targetIndex = 0;
+ else if (event.key === 'End') targetIndex = visibleSheets.length - 1;
+ if (targetIndex === null) return;
+ event.preventDefault();
+ activateSheet(visibleSheets[targetIndex].id, true);
+ };
+
+ return (
+ <div
+ className="flex h-full min-h-0 w-full flex-col overflow-hidden border border-border bg-card"
+ aria-label={title}
+ data-testid="artifact-spreadsheet-preview"
+ >
+ <div
+ className="flex h-10 shrink-0 items-end gap-1 overflow-x-auto border-b border-border bg-panel px-2 pt-1"
+ role="tablist"
+ aria-label={t('artifacts.spreadsheetSheetTabsLabel')}
+ >
+ {visibleSheets.map((sheet, index) => {
+ const selected = sheet.id === activeSheet?.id;
+ return (
+ <button
+ key={sheet.id}
+ ref={element => {
+ if (element) tabRefs.current.set(sheet.id, element);
+ else tabRefs.current.delete(sheet.id);
+ }}
+ type="button"
+ role="tab"
+ aria-selected={selected}
+ aria-controls={tabPanelId}
+ tabIndex={selected ? 0 : -1}
+ title={sheet.name}
+ className={clsx(
+ 'relative h-8 max-w-48 shrink-0 truncate rounded-t-md px-3 text-xs transition-colors',
+ selected ? 'bg-card font-medium text-text' : 'text-text-muted hover:bg-secondary hover:text-text',
+ )}
+ onClick={() => activateSheet(sheet.id)}
+ onKeyDown={event => handleTabKeyDown(event, index)}
+ >
+ {sheet.name}
+ {selected && <span className="absolute inset-x-2 bottom-0 h-0.5 rounded-full bg-accent" />}
+ </button>
+ );
+ })}
+ </div>
+ {activeSheet ? (
+ <div id={tabPanelId} role="tabpanel" className="min-h-0 flex-1">
+ <WorksheetGrid key={activeSheet.id} sheet={activeSheet} styles={workbook.styles} />
+ </div>
+ ) : (
+ <PreviewMessage>{t('artifacts.spreadsheetEmptyWorkbook')}</PreviewMessage>
+ )}
+ </div>
+ );
+}
+
+function WorksheetGrid({ sheet, styles }: { sheet: SpreadsheetSheetData; styles: SpreadsheetCellStyle[] }) {
+ const { t } = useTranslation();
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const scrollFrameRef = useRef<number | null>(null);
+ const [viewport, setViewport] = useState<Viewport>({ width: 0, height: 0, scrollLeft: 0, scrollTop: 0 });
+ const rowMetrics = useMemo(() => buildAxisMetrics(sheet.rowCount, sheet.defaultRowHeight, sheet.rowSizes), [sheet]);
+ const columnMetrics = useMemo(() => buildAxisMetrics(sheet.columnCount, sheet.defaultColumnWidth, sheet.columnSizes), [sheet]);
+ const cellMap = useMemo(() => {
+ const map = new Map<string, SpreadsheetCellData>();
+ sheet.rows.forEach(row => row.cells.forEach(cell => map.set(cellKey(cell.row, cell.column), cell)));
+ return map;
+ }, [sheet.rows]);
+ const rowStyleMap = useMemo(() => new Map(sheet.rowStyleIds.map(item => [item.index, item.styleId])), [sheet.rowStyleIds]);
+ const columnStyleMap = useMemo(() => new Map(sheet.columnStyleIds.map(item => [item.index, item.styleId])), [sheet.columnStyleIds]);
+ const commentMap = useMemo(() => new Map(sheet.comments.map(item => [cellKey(item.row, item.column), item.comment])), [sheet.comments]);
+
+ useEffect(() => {
+ const element = scrollRef.current;
+ if (!element) return;
+ const updateSize = () => {
+ setViewport(current => ({
+ ...current,
+ width: element.clientWidth,
+ height: element.clientHeight,
+ scrollLeft: element.scrollLeft,
+ scrollTop: element.scrollTop,
+ }));
+ };
+ updateSize();
+ const observer = new ResizeObserver(updateSize);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (scrollFrameRef.current !== null) cancelAnimationFrame(scrollFrameRef.current);
+ },
+ [],
+ );
+
+ const handleScroll = (event: ReactUIEvent<HTMLDivElement>) => {
+ const element = event.currentTarget;
+ if (scrollFrameRef.current !== null) return;
+ scrollFrameRef.current = requestAnimationFrame(() => {
+ scrollFrameRef.current = null;
+ setViewport(current => ({
+ ...current,
+ scrollLeft: element.scrollLeft,
+ scrollTop: element.scrollTop,
+ }));
+ });
+ };
+
+ if (sheet.rowCount === 0 || sheet.columnCount === 0) return <PreviewMessage>{t('artifacts.spreadsheetEmptySheet')}</PreviewMessage>;
+
+ const firstRow = Math.max(1, axisIndexAtOffset(rowMetrics.offsets, Math.max(0, viewport.scrollTop - COLUMN_HEADER_HEIGHT)) - AXIS_OVERSCAN);
+ const lastRow = Math.min(
+ sheet.rowCount,
+ axisIndexAtOffset(rowMetrics.offsets, Math.max(0, viewport.scrollTop - COLUMN_HEADER_HEIGHT + viewport.height)) + AXIS_OVERSCAN,
+ );
+ const firstColumn = Math.max(1, axisIndexAtOffset(columnMetrics.offsets, Math.max(0, viewport.scrollLeft - ROW_HEADER_WIDTH)) - AXIS_OVERSCAN);
+ const lastColumn = Math.min(
+ sheet.columnCount,
+ axisIndexAtOffset(columnMetrics.offsets, Math.max(0, viewport.scrollLeft - ROW_HEADER_WIDTH + viewport.width)) + AXIS_OVERSCAN,
+ );
+
+ const visibleMerges = sheet.merges.filter(
+ merge => merge.bottom >= firstRow && merge.top <= lastRow && merge.right >= firstColumn && merge.left <= lastColumn,
+ );
+ const mergedCells = new Set<string>();
+ visibleMerges.forEach(merge => {
+ for (let row = Math.max(merge.top, firstRow); row <= Math.min(merge.bottom, lastRow); row += 1) {
+ for (let column = Math.max(merge.left, firstColumn); column <= Math.min(merge.right, lastColumn); column += 1) {
+ mergedCells.add(cellKey(row, column));
+ }
+ }
+ });
+
+ const cells: React.ReactNode[] = visibleMerges.map(merge =>
+ renderCell(sheet, styles, cellMap, commentMap, rowStyleMap, columnStyleMap, rowMetrics.offsets, columnMetrics.offsets, merge.top, merge.left, merge),
+ );
+ for (let row = firstRow; row <= lastRow; row += 1) {
+ if (rowMetrics.offsets[row] === rowMetrics.offsets[row - 1]) continue;
+ for (let column = firstColumn; column <= lastColumn; column += 1) {
+ if (columnMetrics.offsets[column] === columnMetrics.offsets[column - 1] || mergedCells.has(cellKey(row, column))) continue;
+ cells.push(renderCell(sheet, styles, cellMap, commentMap, rowStyleMap, columnStyleMap, rowMetrics.offsets, columnMetrics.offsets, row, column));
+ }
+ }
+
+ const columnHeaders: React.ReactNode[] = [];
+ for (let column = firstColumn; column <= lastColumn; column += 1) {
+ const width = columnMetrics.offsets[column] - columnMetrics.offsets[column - 1];
+ if (width <= 0) continue;
+ columnHeaders.push(
+ <div
+ key={column}
+ role="columnheader"
+ aria-colindex={column}
+ className="absolute flex h-full items-center justify-center overflow-hidden border-r border-border bg-panel text-[11px] font-medium text-text-muted"
+ style={{ left: ROW_HEADER_WIDTH + columnMetrics.offsets[column - 1] - viewport.scrollLeft, width }}
+ >
+ {columnLabel(column)}
+ </div>,
+ );
+ }
+
+ const rowHeaders: React.ReactNode[] = [];
+ for (let row = firstRow; row <= lastRow; row += 1) {
+ const height = rowMetrics.offsets[row] - rowMetrics.offsets[row - 1];
+ if (height <= 0) continue;
+ rowHeaders.push(
+ <div
+ key={row}
+ role="rowheader"
+ aria-rowindex={row}
+ className="absolute flex w-full items-center justify-center overflow-hidden border-b border-border bg-panel text-[11px] tabular-nums text-text-muted"
+ style={{ top: COLUMN_HEADER_HEIGHT + rowMetrics.offsets[row - 1] - viewport.scrollTop, height }}
+ >
+ {row}
+ </div>,
+ );
+ }
+
+ return (
+ <div className="relative isolate h-full min-h-0 w-full overflow-hidden bg-card">
+ <div
+ ref={scrollRef}
+ className="relative z-0 h-full w-full overflow-auto"
+ role="grid"
+ aria-label={t('artifacts.spreadsheetTableLabel', { sheet: sheet.name })}
+ aria-rowcount={sheet.rowCount}
+ aria-colcount={sheet.columnCount}
+ onScroll={handleScroll}
+ >
+ <div
+ className="relative"
+ style={{
+ width: ROW_HEADER_WIDTH + columnMetrics.totalSize,
+ height: COLUMN_HEADER_HEIGHT + rowMetrics.totalSize,
+ }}
+ >
+ {cells}
+ {sheet.images.map(image => (
+ <img
+ key={image.id}
+ src={image.source}
+ alt={image.alt}
+ className="absolute z-10 object-contain"
+ style={drawingStyle(image.anchor, rowMetrics.offsets, columnMetrics.offsets)}
+ />
+ ))}
+ {sheet.charts.map(chart => (
+ <WorkbookChart key={chart.id} chart={chart} style={drawingStyle(chart.anchor, rowMetrics.offsets, columnMetrics.offsets)} />
+ ))}
+ </div>
+ </div>
+ <div className="pointer-events-none absolute inset-x-0 top-0 z-30 h-7 overflow-hidden border-b border-border bg-panel">{columnHeaders}</div>
+ <div className="pointer-events-none absolute inset-y-0 left-0 z-30 w-12 overflow-hidden border-r border-border bg-panel">{rowHeaders}</div>
+ <div className="pointer-events-none absolute left-0 top-0 z-40 h-7 w-12 border-b border-r border-border bg-panel" />
+ </div>
+ );
+}
+
+function renderCell(
+ sheet: SpreadsheetSheetData,
+ styles: SpreadsheetCellStyle[],
+ cellMap: Map<string, SpreadsheetCellData>,
+ commentMap: Map<string, { author?: string; text: string }>,
+ rowStyleMap: Map<number, number>,
+ columnStyleMap: Map<number, number>,
+ rowOffsets: Float64Array,
+ columnOffsets: Float64Array,
+ row: number,
+ column: number,
+ merge?: SpreadsheetMergeRange,
+): React.ReactNode {
+ const cell = cellMap.get(cellKey(row, column));
+ const comment = commentMap.get(cellKey(row, column));
+ const bottom = merge?.bottom ?? row;
+ const right = merge?.right ?? column;
+ const width = columnOffsets[right] - columnOffsets[column - 1];
+ const height = rowOffsets[bottom] - rowOffsets[row - 1];
+ if (width <= 0 || height <= 0) return null;
+
+ const inheritedStyle = {
+ ...(styles[columnStyleMap.get(column) ?? 0] ?? {}),
+ ...(styles[rowStyleMap.get(row) ?? 0] ?? {}),
+ };
+ const documentStyle = cell ? (styles[cell.styleId] ?? {}) : inheritedStyle;
+ const style: CSSProperties = {
+ left: ROW_HEADER_WIDTH + columnOffsets[column - 1],
+ top: COLUMN_HEADER_HEIGHT + rowOffsets[row - 1],
+ width,
+ height,
+ justifyContent: cell?.alignRight ? 'flex-end' : 'flex-start',
+ alignItems: 'flex-end',
+ ...documentStyle,
+ };
+ const content = cell?.hyperlink ? (
+ <a
+ href={cell.hyperlink}
+ target="_blank"
+ rel="noreferrer"
+ className={clsx('min-w-0 text-text-link underline', documentStyle.whiteSpace === 'normal' ? 'break-words' : 'truncate')}
+ >
+ {cell.text}
+ </a>
+ ) : (
+ <span className={clsx('min-w-0', documentStyle.whiteSpace === 'normal' ? 'break-words' : 'truncate')}>{cell?.text ?? ''}</span>
+ );
+
+ return (
+ <div
+ key={`${row}:${column}:${bottom}:${right}`}
+ role="gridcell"
+ aria-rowindex={row}
+ aria-colindex={column}
+ aria-rowspan={merge ? merge.bottom - merge.top + 1 : undefined}
+ aria-colspan={merge ? merge.right - merge.left + 1 : undefined}
+ title={
+ [cell?.formula ? `${cell.text}\n=${cell.formula}` : undefined, comment ? `${comment.author ? `${comment.author}: ` : ''}${comment.text}` : undefined]
+ .filter((value): value is string => Boolean(value))
+ .join('\n') ||
+ cell?.text ||
+ undefined
+ }
+ className={clsx(
+ 'absolute flex min-w-0 overflow-hidden px-2 text-xs text-text',
+ sheet.showGridLines ? 'border-b border-r border-border' : 'border-b border-r border-transparent',
+ )}
+ style={style}
+ >
+ {content}
+ {comment && (
+ <span aria-label={comment.text} className="absolute right-0 top-0 h-0 w-0 border-b-[7px] border-l-[7px] border-b-transparent border-l-red-500" />
+ )}
+ {sheet.autoFilter && row === sheet.autoFilter.top && column >= sheet.autoFilter.left && column <= sheet.autoFilter.right && (
+ <ChevronDown aria-hidden="true" size={12} className="ml-1 shrink-0 opacity-70" />
+ )}
+ </div>
+ );
+}
+
+function cellKey(row: number, column: number): string {
+ return `${row}:${column}`;
+}
+
+function drawingStyle(anchor: SpreadsheetDrawingAnchor, rowOffsets: Float64Array, columnOffsets: Float64Array): CSSProperties {
+ const left = ROW_HEADER_WIDTH + (columnOffsets[anchor.fromColumn - 1] ?? 0) + anchor.fromColumnOffset;
+ const top = COLUMN_HEADER_HEIGHT + (rowOffsets[anchor.fromRow - 1] ?? 0) + anchor.fromRowOffset;
+ const width =
+ anchor.width ??
+ Math.max(
+ 0,
+ (columnOffsets[anchor.toColumn ?? anchor.fromColumn] ?? 0) -
+ (columnOffsets[anchor.fromColumn - 1] ?? 0) +
+ (anchor.toColumnOffset ?? 0) -
+ anchor.fromColumnOffset,
+ );
+ const height =
+ anchor.height ??
+ Math.max(0, (rowOffsets[anchor.toRow ?? anchor.fromRow] ?? 0) - (rowOffsets[anchor.fromRow - 1] ?? 0) + (anchor.toRowOffset ?? 0) - anchor.fromRowOffset);
+ return { left, top, width, height };
+}
+
+function WorkbookChart({ chart, style }: { chart: SpreadsheetChart; style: CSSProperties }) {
+ const width = Math.max(240, Number(style.width) || 240);
+ const height = Math.max(160, Number(style.height) || 160);
+ const series = chart.series.filter(item => item.values.length > 0);
+ const legendSeries = series.map((item, seriesIndex) => ({
+ item,
+ seriesIndex,
+ label: item.name || `Series ${seriesIndex + 1}`,
+ }));
+ const values = series.flatMap(item => item.values);
+ if (values.length === 0) return null;
+
+ const viewWidth = 800;
+ const viewHeight = 400;
+ const chartLabel = chart.title || 'Chart';
+ const legendWidth = chart.legendPosition === 'right' && legendSeries.length > 0 ? 150 : 0;
+ const bottomLegendReserve = chart.type === 'bar' && chart.valueAxisTitle && chart.legendPosition === 'bottom' && legendSeries.length > 0 ? 34 : 0;
+ const plot = {
+ left: chart.type === 'bar' ? 145 : 76,
+ top: 72,
+ right: viewWidth - 42 - legendWidth,
+ bottom: viewHeight - 62 - bottomLegendReserve,
+ };
+ const minValue = Math.min(0, ...values);
+ const maxValue = Math.max(0, ...values);
+ const span = Math.max(1, maxValue - minValue);
+ const tickStep = niceTickStep(span / 5);
+ const { minimum: axisMin, maximum: axisMax } = ensureNonZeroAxisSpan(
+ Math.floor(minValue / tickStep) * tickStep,
+ Math.ceil(maxValue / tickStep) * tickStep,
+ tickStep,
+ );
+ const categoryCount = Math.max(1, ...series.map(item => Math.max(item.categories.length, item.values.length)));
+ const categories = series.find(item => item.categories.length > 0)?.categories ?? Array.from({ length: categoryCount }, (_, index) => String(index + 1));
+ const xAtCategory = (index: number) =>
+ chart.type === 'line' || chart.type === 'scatter'
+ ? categoryPoint(index, categoryCount, plot.left, plot.right)
+ : categoryCenter(index, categoryCount, plot.left, plot.right);
+ const yAtCategory = (index: number) => categoryCenter(index, categoryCount, plot.top, plot.bottom);
+ const xAtValue = (value: number) => linearPosition(value, axisMin, axisMax, plot.left, plot.right);
+ const yAtValue = (value: number) => linearPosition(value, axisMin, axisMax, plot.bottom, plot.top);
+ const zeroX = xAtValue(0);
+ const zeroY = yAtValue(0);
+ const colors = ['#2F80C3', '#D44343', '#72A842', '#8064A2', '#F79646', '#4BACC6'];
+ const ticks: number[] = [];
+ for (let value = axisMin; value <= axisMax + tickStep / 100; value += tickStep) ticks.push(Number(value.toFixed(10)));
+
+ return (
+ <figure
+ className="absolute z-20 m-0 overflow-hidden border border-[#a0a0a0] bg-white text-black shadow-sm"
+ style={{ ...style, minWidth: width, minHeight: height }}
+ >
+ <svg className="block h-full w-full" viewBox={`0 0 ${viewWidth} ${viewHeight}`} preserveAspectRatio="none" role="img" aria-label={chartLabel}>
+ <rect width={viewWidth} height={viewHeight} fill="#FFFFFF" />
+ {chart.title && (
+ <text x={viewWidth / 2} y={42} textAnchor="middle" fontSize="27" fontWeight="700" fill="#111111">
+ {chart.title}
+ </text>
+ )}
+ {chart.type !== 'pie' &&
+ ticks.map(value => {
+ if (chart.type === 'bar') {
+ const x = xAtValue(value);
+ return (
+ <g key={value}>
+ <line x1={x} x2={x} y1={plot.top} y2={plot.bottom} stroke="#8a8a8a" strokeWidth="1" />
+ <text x={x} y={plot.bottom + 22} textAnchor="middle" fontSize="13" fill="#111111">
+ {value}
+ </text>
+ </g>
+ );
+ }
+ const y = yAtValue(value);
+ return (
+ <g key={value}>
+ <line x1={plot.left} x2={plot.right} y1={y} y2={y} stroke="#8a8a8a" strokeWidth="1" />
+ <text x={plot.left - 10} y={y + 5} textAnchor="end" fontSize="13" fill="#111111">
+ {value}
+ </text>
+ </g>
+ );
+ })}
+ {chart.type !== 'pie' &&
+ (chart.type === 'bar' ? (
+ <>
+ <line x1={zeroX} x2={zeroX} y1={plot.top} y2={plot.bottom} stroke="#666666" />
+ <line x1={plot.left} x2={plot.right} y1={plot.bottom} y2={plot.bottom} stroke="#666666" />
+ {categories.map((category, index) => (
+ <text key={`${category}:${index}`} x={plot.left - 10} y={yAtCategory(index) + 5} textAnchor="end" fontSize="12" fill="#111111">
+ {category}
+ </text>
+ ))}
+ </>
+ ) : (
+ <>
+ <line x1={plot.left} x2={plot.left} y1={plot.top} y2={plot.bottom} stroke="#666666" />
+ <line x1={plot.left} x2={plot.right} y1={zeroY} y2={zeroY} stroke="#666666" />
+ {categories.map((category, index) => (
+ <text key={`${category}:${index}`} x={xAtCategory(index)} y={plot.bottom + 25} textAnchor="middle" fontSize="12" fill="#111111">
+ {category}
+ </text>
+ ))}
+ </>
+ ))}
+ {chart.valueAxisTitle &&
+ (chart.type === 'bar' ? (
+ <text x={(plot.left + plot.right) / 2} y={viewHeight - 8 - bottomLegendReserve} textAnchor="middle" fontSize="14" fontWeight="700" fill="#111111">
+ {chart.valueAxisTitle}
+ </text>
+ ) : (
+ <text transform={`translate(22 ${(plot.top + plot.bottom) / 2}) rotate(-90)`} textAnchor="middle" fontSize="14" fontWeight="700" fill="#111111">
+ {chart.valueAxisTitle}
+ </text>
+ ))}
+ <ChartMarks
+ chart={chart}
+ series={series}
+ colors={colors}
+ plot={plot}
+ categoryCount={categoryCount}
+ xAtCategory={xAtCategory}
+ xAtValue={xAtValue}
+ yAtValue={yAtValue}
+ />
+ {chart.legendPosition !== 'none' &&
+ legendSeries.map(({ item, seriesIndex, label }, legendIndex) => {
+ const x = chart.legendPosition === 'right' ? plot.right + 28 : plot.left + legendIndex * 115;
+ const y = chart.legendPosition === 'bottom' ? viewHeight - 15 : chart.legendPosition === 'top' ? 57 : plot.top + 24 + legendIndex * 25;
+ return (
+ <g key={`${seriesIndex}:${label}:legend`}>
+ <line x1={x} x2={x + 27} y1={y} y2={y} stroke={item.color ?? colors[seriesIndex % colors.length]} strokeWidth="6" strokeLinecap="round" />
+ <text x={x + 34} y={y + 5} fontSize="13" fill="#111111">
+ {label}
+ </text>
+ </g>
+ );
+ })}
+ </svg>
+ </figure>
+ );
+}
+
+function ChartMarks({
+ chart,
+ series,
+ colors,
+ plot,
+ categoryCount,
+ xAtCategory,
+ xAtValue,
+ yAtValue,
+}: {
+ chart: SpreadsheetChart;
+ series: SpreadsheetChart['series'];
+ colors: string[];
+ plot: { left: number; top: number; right: number; bottom: number };
+ categoryCount: number;
+ xAtCategory: (index: number) => number;
+ xAtValue: (value: number) => number;
+ yAtValue: (value: number) => number;
+}) {
+ if (chart.type === 'pie') {
+ const item = series[0];
+ const total = item.values.reduce((sum, value) => sum + Math.max(0, value), 0);
+ let angle = -Math.PI / 2;
+ const centerX = (plot.left + plot.right) / 2;
+ const centerY = (plot.top + plot.bottom) / 2;
+ const radius = Math.min(plot.right - plot.left, plot.bottom - plot.top) * 0.36;
+ return (
+ <>
+ {item.values.map((value, index) => {
+ const next = angle + (Math.max(0, value) / Math.max(total, 1)) * Math.PI * 2;
+ const path = sectorPath(centerX, centerY, radius, angle, next);
+ angle = next;
+ return <path key={index} d={path} fill={colors[index % colors.length]} stroke="#FFFFFF" />;
+ })}
+ </>
+ );
+ }
+ if (chart.type === 'column' || chart.type === 'bar') {
+ return (
+ <>
+ {series.flatMap((item, seriesIndex) =>
+ item.values.map((value, index) => {
+ const color = item.color ?? colors[seriesIndex % colors.length];
+ if (chart.type === 'bar') {
+ const band = clusteredCategoryBand(index, categoryCount, seriesIndex, series.length, plot.top, plot.bottom);
+ const valueSpan = spanFromBaseline(xAtValue(value), xAtValue(0));
+ return <rect key={`${seriesIndex}:${index}`} x={valueSpan.start} y={band.start} width={valueSpan.size} height={band.size} fill={color} />;
+ }
+ const band = clusteredCategoryBand(index, categoryCount, seriesIndex, series.length, plot.left, plot.right);
+ const valueSpan = spanFromBaseline(yAtValue(value), yAtValue(0));
+ return <rect key={`${seriesIndex}:${index}`} x={band.start} y={valueSpan.start} width={band.size} height={valueSpan.size} fill={color} />;
+ }),
+ )}
+ </>
+ );
+ }
+ return (
+ <>
+ {series.map((item, seriesIndex) => {
+ const color = item.color ?? colors[seriesIndex % colors.length];
+ const points = item.values.map((value, index) => `${xAtCategory(index)},${yAtValue(value)}`).join(' ');
+ return (
+ <g key={`${item.name ?? seriesIndex}:marks`}>
+ <polyline points={points} fill="none" stroke={color} strokeWidth="5" strokeLinecap="round" strokeLinejoin="round" />
+ {chart.type === 'scatter' &&
+ item.values.map((value, index) => <circle key={index} cx={xAtCategory(index)} cy={yAtValue(value)} r="4" fill={color} />)}
+ </g>
+ );
+ })}
+ </>
+ );
+}
+
+function niceTickStep(value: number): number {
+ const power = 10 ** Math.floor(Math.log10(Math.max(value, 1)));
+ const normalized = value / power;
+ return (normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10) * power;
+}
+
+function sectorPath(centerX: number, centerY: number, radius: number, start: number, end: number): string {
+ const startX = centerX + radius * Math.cos(start);
+ const startY = centerY + radius * Math.sin(start);
+ const endX = centerX + radius * Math.cos(end);
+ const endY = centerY + radius * Math.sin(end);
+ return `M ${centerX} ${centerY} L ${startX} ${startY} A ${radius} ${radius} 0 ${end - start > Math.PI ? 1 : 0} 1 ${endX} ${endY} Z`;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/artifactCollection.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/artifactCollection.ts
new file mode 100644
index 0000000000..329e379685
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/artifactCollection.ts
@@ -0,0 +1,119 @@
+import type { FileDownloadItem, Message } from '../../types';
+import { extractTokenFromDownloadUrl, getFileIdentityKey, resolveFilePath } from '../../utils/fileDownloadDedup';
+
+export interface ArtifactItem {
+ id: string;
+ name: string;
+ size?: number;
+ mimeType?: string;
+ downloadUrl?: string;
+ downloadToken?: string;
+ path?: string;
+ source: 'message';
+ sourceMember?: string;
+ timestamp?: number;
+}
+
+export function fileArtifactId(file: FileDownloadItem): string {
+ return `file:${getFileIdentityKey(file)}`;
+}
+
+function normalizeDownloadUrl(downloadUrl?: string, downloadToken?: string): string | undefined {
+ const normalizedUrl = downloadUrl?.trim();
+ if (normalizedUrl) return normalizedUrl;
+ const normalizedToken = downloadToken?.trim();
+ if (normalizedToken) return `/file-api/download?token=${encodeURIComponent(normalizedToken)}`;
+ return undefined;
+}
+
+function preferArtifact(existing: ArtifactItem, candidate: ArtifactItem): ArtifactItem {
+ const existingTs = existing.timestamp || 0;
+ const candidateTs = candidate.timestamp || 0;
+ const existingHasUrl = Boolean(existing.downloadUrl || existing.downloadToken);
+ const candidateHasUrl = Boolean(candidate.downloadUrl || candidate.downloadToken);
+
+ let primary: ArtifactItem;
+ let secondary: ArtifactItem;
+ if (candidateTs > existingTs) {
+ primary = candidate;
+ secondary = existing;
+ } else if (candidateTs < existingTs) {
+ primary = existing;
+ secondary = candidate;
+ } else if (candidateHasUrl && !existingHasUrl) {
+ primary = candidate;
+ secondary = existing;
+ } else {
+ primary = existing;
+ secondary = candidate;
+ }
+
+ if (!primary.downloadUrl && secondary.downloadUrl) {
+ primary = {
+ ...primary,
+ downloadUrl: secondary.downloadUrl,
+ downloadToken: primary.downloadToken || secondary.downloadToken,
+ size: primary.size ?? secondary.size,
+ mimeType: primary.mimeType || secondary.mimeType,
+ };
+ }
+ if (!primary.path && secondary.path) {
+ primary = { ...primary, path: secondary.path };
+ }
+ return primary;
+}
+
+function messageTime(message: Message): number {
+ const parsed = Date.parse(message.timestamp);
+ return Number.isFinite(parsed) ? parsed : 0;
+}
+
+function hasArtifactResource(file: FileDownloadItem): boolean {
+ return Boolean(file.download_url?.trim() || file.download_token?.trim() || file.path?.trim());
+}
+
+function fileItemToArtifact(file: FileDownloadItem, message: Message): ArtifactItem {
+ const name = file.name.trim();
+ const downloadToken = file.download_token?.trim() || extractTokenFromDownloadUrl(file.download_url);
+ return {
+ id: fileArtifactId(file),
+ name,
+ size: file.size,
+ mimeType: file.mime_type,
+ downloadUrl: normalizeDownloadUrl(file.download_url, downloadToken),
+ downloadToken,
+ path: resolveFilePath({
+ path: file.path,
+ download_token: downloadToken,
+ download_url: file.download_url,
+ }),
+ source: 'message',
+ timestamp: messageTime(message),
+ };
+}
+
+export function buildArtifacts(messages: Message[]): ArtifactItem[] {
+ const artifacts: ArtifactItem[] = [];
+
+ messages.forEach(message => {
+ message.fileItems?.forEach(file => {
+ if (!file.name?.trim() || !hasArtifactResource(file)) return;
+ artifacts.push(fileItemToArtifact(file, message));
+ });
+ });
+
+ const deduped = new Map<string, ArtifactItem>();
+ artifacts.forEach(artifact => {
+ const key = getFileIdentityKey({
+ name: artifact.name,
+ size: artifact.size,
+ path: artifact.path,
+ download_url: artifact.downloadUrl,
+ download_token: artifact.downloadToken,
+ });
+ const existing = deduped.get(key);
+ deduped.set(key, existing ? preferArtifact(existing, artifact) : artifact);
+ });
+
+ return Array.from(deduped.values()).sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/chartGeometry.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/chartGeometry.ts
new file mode 100644
index 0000000000..0e76ecc71b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/chartGeometry.ts
@@ -0,0 +1,79 @@
+export type AxisSpan = {
+ start: number;
+ size: number;
+};
+
+export type CategoryBand = {
+ start: number;
+ size: number;
+};
+
+export type AxisDomain = {
+ minimum: number;
+ maximum: number;
+};
+
+export function ensureNonZeroAxisSpan(minimum: number, maximum: number, step: number): AxisDomain {
+ if (![minimum, maximum, step].every(Number.isFinite)) throw new TypeError('Chart axis values must be finite');
+ if (maximum < minimum) throw new RangeError('Chart axis maximum must not be less than its minimum');
+ if (step <= 0) throw new RangeError('Chart axis step must be positive');
+ return {
+ minimum,
+ maximum: maximum === minimum ? maximum + step : maximum,
+ };
+}
+
+export function linearPosition(value: number, domainStart: number, domainEnd: number, rangeStart: number, rangeEnd: number): number {
+ if (![value, domainStart, domainEnd, rangeStart, rangeEnd].every(Number.isFinite)) throw new TypeError('Chart coordinates must be finite');
+ if (domainStart === domainEnd) throw new RangeError('Chart domain must have a non-zero span');
+ return rangeStart + ((value - domainStart) / (domainEnd - domainStart)) * (rangeEnd - rangeStart);
+}
+
+export function spanFromBaseline(valuePosition: number, baselinePosition: number): AxisSpan {
+ if (!Number.isFinite(valuePosition) || !Number.isFinite(baselinePosition)) throw new TypeError('Chart coordinates must be finite');
+ return {
+ start: Math.min(valuePosition, baselinePosition),
+ size: Math.abs(valuePosition - baselinePosition),
+ };
+}
+
+export function categoryCenter(index: number, categoryCount: number, rangeStart: number, rangeEnd: number): number {
+ validateCategoryIndex(index, categoryCount);
+ if (!Number.isFinite(rangeStart) || !Number.isFinite(rangeEnd)) throw new TypeError('Chart coordinates must be finite');
+ return rangeStart + ((index + 0.5) / categoryCount) * (rangeEnd - rangeStart);
+}
+
+export function categoryPoint(index: number, categoryCount: number, rangeStart: number, rangeEnd: number): number {
+ validateCategoryIndex(index, categoryCount);
+ if (!Number.isFinite(rangeStart) || !Number.isFinite(rangeEnd)) throw new TypeError('Chart coordinates must be finite');
+ if (categoryCount === 1) return (rangeStart + rangeEnd) / 2;
+ return rangeStart + (index / (categoryCount - 1)) * (rangeEnd - rangeStart);
+}
+
+export function clusteredCategoryBand(
+ categoryIndex: number,
+ categoryCount: number,
+ seriesIndex: number,
+ seriesCount: number,
+ rangeStart: number,
+ rangeEnd: number,
+ occupiedRatio = 0.72,
+): CategoryBand {
+ validateCategoryIndex(categoryIndex, categoryCount);
+ validateCategoryIndex(seriesIndex, seriesCount);
+ if (!Number.isFinite(rangeStart) || !Number.isFinite(rangeEnd)) throw new TypeError('Chart coordinates must be finite');
+ if (!Number.isFinite(occupiedRatio) || occupiedRatio <= 0 || occupiedRatio > 1) throw new RangeError('Occupied ratio must be in the interval (0, 1]');
+
+ const categorySize = (rangeEnd - rangeStart) / categoryCount;
+ const clusterSize = categorySize * occupiedRatio;
+ const bandSize = clusterSize / seriesCount;
+ return {
+ start: rangeStart + categoryIndex * categorySize + (categorySize - clusterSize) / 2 + seriesIndex * bandSize,
+ size: bandSize,
+ };
+}
+
+function validateCategoryIndex(index: number, count: number): void {
+ if (!Number.isInteger(count) || count < 1) throw new RangeError('Category count must be a positive integer');
+ if (!Number.isInteger(index) || index < 0 || index >= count) throw new RangeError(`Category index ${index} is outside the axis`);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguageExtensions.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguageExtensions.ts
new file mode 100644
index 0000000000..e2c73b35e4
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguageExtensions.ts
@@ -0,0 +1,47 @@
+export const CODE_LANGUAGE_EXTENSIONS = [
+ 'bash',
+ 'c',
+ 'cc',
+ 'cjs',
+ 'cpp',
+ 'cs',
+ 'css',
+ 'go',
+ 'h',
+ 'hpp',
+ 'java',
+ 'js',
+ 'jsx',
+ 'kt',
+ 'kts',
+ 'lua',
+ 'mjs',
+ 'php',
+ 'pl',
+ 'py',
+ 'rb',
+ 'rs',
+ 'sh',
+ 'sql',
+ 'swift',
+ 'toml',
+ 'ts',
+ 'tsx',
+ 'vue',
+ 'xml',
+ 'yaml',
+ 'yml',
+] as const;
+
+export type CodeLanguageExtension = (typeof CODE_LANGUAGE_EXTENSIONS)[number];
+
+const CODE_LANGUAGE_EXTENSION_SET: ReadonlySet<string> = new Set(CODE_LANGUAGE_EXTENSIONS);
+
+export function fileExtension(name: string): string {
+ const value = name.split('.').pop()?.trim().toLowerCase() ?? '';
+ return value === name.toLowerCase() ? '' : value;
+}
+
+export function isCodeLanguageExtension(value: string): value is CodeLanguageExtension {
+ return CODE_LANGUAGE_EXTENSION_SET.has(value);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguages.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguages.ts
new file mode 100644
index 0000000000..dda971b009
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/codeLanguages.ts
@@ -0,0 +1,54 @@
+import type { Extension } from '@codemirror/state';
+import { StreamLanguage } from '@codemirror/language';
+import { fileExtension, isCodeLanguageExtension, type CodeLanguageExtension } from './codeLanguageExtensions';
+
+type LanguageLoader = () => Promise<Extension>;
+
+const javascript = async (typescript = false, jsx = false): Promise<Extension> => (await import('@codemirror/lang-javascript')).javascript({ typescript, jsx });
+
+const cpp = async (): Promise<Extension> => (await import('@codemirror/lang-cpp')).cpp();
+
+const LANGUAGE_LOADERS = {
+ bash: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/shell')).shell),
+ c: cpp,
+ cc: cpp,
+ cjs: () => javascript(),
+ cpp,
+ cs: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/clike')).csharp),
+ css: async () => (await import('@codemirror/lang-css')).css(),
+ go: async () => (await import('@codemirror/lang-go')).go(),
+ h: cpp,
+ hpp: cpp,
+ java: async () => (await import('@codemirror/lang-java')).java(),
+ js: () => javascript(),
+ jsx: () => javascript(false, true),
+ kt: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/clike')).kotlin),
+ kts: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/clike')).kotlin),
+ lua: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/lua')).lua),
+ mjs: () => javascript(),
+ php: async () => (await import('@codemirror/lang-php')).php(),
+ pl: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/perl')).perl),
+ py: async () => (await import('@codemirror/lang-python')).python(),
+ rb: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/ruby')).ruby),
+ rs: async () => (await import('@codemirror/lang-rust')).rust(),
+ sh: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/shell')).shell),
+ sql: async () => (await import('@codemirror/lang-sql')).sql(),
+ swift: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/swift')).swift),
+ toml: async () => StreamLanguage.define((await import('@codemirror/legacy-modes/mode/toml')).toml),
+ ts: () => javascript(true),
+ tsx: () => javascript(true, true),
+ vue: async () => (await import('@codemirror/lang-vue')).vue(),
+ xml: async () => (await import('@codemirror/lang-xml')).xml(),
+ yaml: async () => (await import('@codemirror/lang-yaml')).yaml(),
+ yml: async () => (await import('@codemirror/lang-yaml')).yaml(),
+} satisfies Record<CodeLanguageExtension, LanguageLoader>;
+
+export async function loadCodeLanguage(name: string, mimeType?: string): Promise<Extension> {
+ const extension = fileExtension(name);
+ if (isCodeLanguageExtension(extension)) return LANGUAGE_LOADERS[extension]();
+
+ const mime = (mimeType ?? '').toLowerCase();
+ if (mime === 'application/typescript') return LANGUAGE_LOADERS.ts();
+ if (mime === 'application/javascript' || mime === 'text/javascript') return LANGUAGE_LOADERS.js();
+ throw new Error(`unsupported_code_language:${extension || mime || 'unknown'}`);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/filePreviewModel.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/filePreviewModel.ts
new file mode 100644
index 0000000000..d2b1702368
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/filePreviewModel.ts
@@ -0,0 +1,69 @@
+import { fileExtension, isCodeLanguageExtension } from './codeLanguageExtensions';
+
+type PreviewFile = {
+ name: string;
+ mimeType?: string;
+};
+
+type PreviewResource = {
+ downloadUrl?: string;
+ path?: string;
+};
+
+type TextKind = 'markdown' | 'text' | 'code' | 'json' | 'jsonl';
+export type PreviewKind = TextKind | 'html' | 'image' | 'pdf' | 'docx' | 'spreadsheet' | 'presentation' | 'unsupported';
+
+const TEXT_EXTENSIONS = new Set(['conf', 'csv', 'ini', 'log', 'text', 'txt']);
+const IMAGE_EXTENSIONS = new Set(['avif', 'bmp', 'gif', 'ico', 'jfif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
+
+function inlineDownloadUrl(downloadUrl: string, origin: string): string {
+ const url = new URL(downloadUrl, origin);
+ url.searchParams.set('inline', '1');
+ return url.pathname + url.search;
+}
+
+export function artifactDownloadUrl(resource: PreviewResource): string | null {
+ if (resource.downloadUrl) return resource.downloadUrl;
+ return resource.path ? `/file-api/raw-file?path=${encodeURIComponent(resource.path)}` : null;
+}
+
+export function artifactBinaryPreviewUrl(resource: PreviewResource, origin: string): string | null {
+ if (resource.downloadUrl) return inlineDownloadUrl(resource.downloadUrl, origin);
+ return resource.path ? `/file-api/raw-file?path=${encodeURIComponent(resource.path)}` : null;
+}
+
+export function artifactTextPreviewUrl(resource: PreviewResource, origin: string): string | null {
+ if (resource.downloadUrl) return inlineDownloadUrl(resource.downloadUrl, origin);
+ return resource.path ? `/file-api/file-content?path=${encodeURIComponent(resource.path)}&encoding=auto` : null;
+}
+
+export function previewKind(file: PreviewFile): PreviewKind {
+ const mime = (file.mimeType ?? '').toLowerCase();
+ const ext = fileExtension(file.name);
+ if (mime === 'text/markdown' || ['md', 'markdown'].includes(ext)) return 'markdown';
+ if (mime === 'application/json' || mime === 'text/json' || ext === 'json') return 'json';
+ if (mime === 'application/x-ndjson' || mime === 'application/jsonl' || ext === 'jsonl') return 'jsonl';
+ if (mime === 'text/html' || mime === 'application/xhtml+xml' || ext === 'html' || ext === 'htm') return 'html';
+ if (mime === 'application/javascript' || mime === 'text/javascript' || mime === 'application/typescript' || isCodeLanguageExtension(ext)) return 'code';
+ if (mime.startsWith('image/') || IMAGE_EXTENSIONS.has(ext)) return 'image';
+ if (mime === 'application/pdf' || ext === 'pdf') return 'pdf';
+ if (mime === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || ext === 'docx') return 'docx';
+ if (
+ mime === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
+ mime === 'application/vnd.ms-powerpoint.presentation.macroenabled.12' ||
+ ext === 'pptx' ||
+ ext === 'pptm'
+ ) {
+ return 'presentation';
+ }
+ if (
+ mime === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
+ mime === 'application/vnd.ms-excel.sheet.macroenabled.12' ||
+ ext === 'xlsx' ||
+ ext === 'xlsm'
+ ) {
+ return 'spreadsheet';
+ }
+ if (mime.startsWith('text/') || TEXT_EXTENSIONS.has(ext)) return 'text';
+ return 'unsupported';
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/index.tsx
index a6a9ee70de..5d2189c55d 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/index.tsx
@@ -1,341 +1,93 @@
-import { useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react';
-import { Download, FileText, Info, LoaderCircle } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react';
+import { AlertCircle, Download, FileText, Info, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { useChatStore, useSessionStore } from '../../stores';
-import type { FileDownloadItem, Message } from '../../types';
-import type { TeamMemberExecutionEvent, TeamTask } from '../../stores/sessionStore';
-import {
- extractTokenFromDownloadUrl,
- getFileIdentityKey,
- resolveFilePath,
-} from '../../utils/fileDownloadDedup';
-import { MarkdownRenderer } from '../MarkdownRenderer';
-import { getMemberDisplayName } from '../teamArea/shared';
+import { useChatStore } from '../../stores';
+import { executeDesktopSave, type DesktopSaveApiResult } from '../../utils/desktopSave';
+import { FilePreview } from './FilePreview';
+import { buildArtifacts, type ArtifactItem } from './artifactCollection';
+import { artifactDownloadUrl } from './filePreviewModel';
-type ArtifactSource = 'message' | 'team_execution' | 'team_task';
+type ListResizeDrag = { pointerId: number; startX: number; startWidth: number };
-export interface ArtifactItem {
- id: string;
- name: string;
- size?: number;
- mimeType?: string;
- downloadUrl?: string;
- downloadToken?: string;
- path?: string;
- source: ArtifactSource;
- sourceMember?: string;
- timestamp?: number;
-}
+const MIN_LIST_WIDTH = 240;
+const MAX_LIST_WIDTH = 520;
-type PreviewState =
- | { status: 'idle'; content: string; error?: string }
- | { status: 'loading'; content: string; error?: string }
- | { status: 'ready'; content: string; error?: string }
- | { status: 'error'; content: string; error: string };
+export { fileArtifactId } from './artifactCollection';
type DownloadCapableWindow = Window & {
pywebview?: {
api?: {
- download_file?: (url: string, filename: string) => Promise<boolean> | boolean;
+ download_file?: (url: string, filename: string) => DesktopSaveApiResult;
};
};
};
-const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']);
-
-function formatFileSize(bytes?: number): string {
- if (bytes == null || !Number.isFinite(bytes)) return '-';
- if (bytes === 0) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB'];
- const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
- const value = bytes / Math.pow(1024, index);
- return `${value.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
-}
-
-function getFileExtension(name: string): string {
- const ext = name.split('.').pop()?.trim().toLowerCase() || '';
- return ext === name.toLowerCase() ? '' : ext;
-}
-
-function getFileTypeLabel(item: ArtifactItem): string {
- const ext = getFileExtension(item.name);
- if (ext) return ext.toUpperCase();
- if (item.mimeType) return item.mimeType;
- return 'FILE';
-}
-
-function isMarkdownArtifact(item: ArtifactItem): boolean {
- return MARKDOWN_EXTENSIONS.has(getFileExtension(item.name));
-}
-
-function normalizeDownloadUrl(downloadUrl?: string, downloadToken?: string): string | undefined {
- if (downloadUrl) return downloadUrl;
- if (downloadToken) return `/file-api/download?token=${encodeURIComponent(downloadToken)}`;
- return undefined;
-}
-
-function preferArtifact(existing: ArtifactItem, candidate: ArtifactItem): ArtifactItem {
- const existingTs = existing.timestamp || 0;
- const candidateTs = candidate.timestamp || 0;
- const existingHasUrl = Boolean(existing.downloadUrl || existing.downloadToken);
- const candidateHasUrl = Boolean(candidate.downloadUrl || candidate.downloadToken);
-
- let primary: ArtifactItem;
- let secondary: ArtifactItem;
- if (candidateTs > existingTs) {
- primary = candidate;
- secondary = existing;
- } else if (candidateTs < existingTs) {
- primary = existing;
- secondary = candidate;
- } else if (candidateHasUrl && !existingHasUrl) {
- primary = candidate;
- secondary = existing;
- } else {
- primary = existing;
- secondary = candidate;
- }
-
- // 保留可下载信息:避免较新的 team_task 路径条目盖掉已有 downloadUrl
- if (!primary.downloadUrl && secondary.downloadUrl) {
- primary = {
- ...primary,
- downloadUrl: secondary.downloadUrl,
- downloadToken: primary.downloadToken || secondary.downloadToken,
- size: primary.size ?? secondary.size,
- mimeType: primary.mimeType || secondary.mimeType,
- };
- }
- if (!primary.path && secondary.path) {
- primary = { ...primary, path: secondary.path };
- }
- if (!primary.sourceMember && secondary.sourceMember) {
- primary = { ...primary, sourceMember: secondary.sourceMember };
- }
- return primary;
-}
-
-function messageTime(message: Message): number {
- const parsed = Date.parse(message.timestamp);
- return Number.isFinite(parsed) ? parsed : 0;
-}
-
-function fileItemToArtifact(file: FileDownloadItem, message: Message, index: number): ArtifactItem {
- const downloadToken = file.download_token || extractTokenFromDownloadUrl(file.download_url);
- return {
- id: `message:${message.id}:${file.name}:${index}`,
- name: file.name || `artifact-${index + 1}`,
- size: file.size,
- mimeType: file.mime_type,
- downloadUrl: normalizeDownloadUrl(file.download_url, downloadToken),
- downloadToken,
- path: resolveFilePath({
- path: file.path,
- download_token: downloadToken,
- download_url: file.download_url,
- }),
- source: 'message',
- timestamp: messageTime(message),
- };
-}
-
-function executionFileToArtifact(
- file: NonNullable<TeamMemberExecutionEvent['files']>[number],
- event: TeamMemberExecutionEvent,
- index: number
-): ArtifactItem {
- const downloadToken = extractTokenFromDownloadUrl(file.download_url);
- return {
- id: `team-execution:${event.id}:${file.name}:${index}`,
- name: file.name || `artifact-${index + 1}`,
- size: file.size,
- mimeType: file.mime_type,
- downloadUrl: normalizeDownloadUrl(file.download_url, downloadToken),
- downloadToken,
- path: resolveFilePath({
- path: file.path,
- download_token: downloadToken,
- download_url: file.download_url,
- }),
- source: 'team_execution',
- sourceMember: event.member_id,
- timestamp: event.timestamp,
- };
-}
-
-function taskFileToArtifact(task: TeamTask, filePath: string, index: number): ArtifactItem {
- const normalizedPath = filePath.trim();
- const name = normalizedPath.split(/[\\/]/).pop() || normalizedPath || `artifact-${index + 1}`;
- return {
- id: `team-task:${task.task_id}:${normalizedPath}:${index}`,
- name,
- path: normalizedPath || undefined,
- source: 'team_task',
- sourceMember: task.assignee,
- timestamp: task.timestamp,
- };
-}
-
-function buildArtifacts(
- messages: Message[],
- executionEvents: TeamMemberExecutionEvent[],
- teamTasks: TeamTask[]
-): ArtifactItem[] {
- const artifacts: ArtifactItem[] = [];
-
- messages.forEach((message) => {
- message.fileItems?.forEach((file, index) => {
- artifacts.push(fileItemToArtifact(file, message, index));
- });
- });
-
- executionEvents.forEach((event) => {
- event.files?.forEach((file, index) => {
- artifacts.push(executionFileToArtifact(file, event, index));
- });
- });
-
- teamTasks.forEach((task) => {
- task.files?.forEach((filePath, index) => {
- artifacts.push(taskFileToArtifact(task, filePath, index));
- });
- });
-
- const deduped = new Map<string, ArtifactItem>();
- artifacts.forEach((artifact) => {
- const key = getFileIdentityKey({
- name: artifact.name,
- size: artifact.size,
- path: artifact.path,
- download_url: artifact.downloadUrl,
- download_token: artifact.downloadToken,
- });
- const existing = deduped.get(key);
- deduped.set(key, existing ? preferArtifact(existing, artifact) : artifact);
- });
-
- return Array.from(deduped.values()).sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
-}
-
-function isHtmlFallback(contentType: string, text: string): boolean {
- const normalizedType = contentType.toLowerCase();
- const start = text.slice(0, 500).trim().toLowerCase();
- return (
- normalizedType.includes('text/html') ||
- start.startsWith('<!doctype html') ||
- start.startsWith('<html') ||
- (start.includes('<div id="root"') && start.includes('/src/'))
- );
-}
-
-async function fetchMarkdownPreview(item: ArtifactItem): Promise<string> {
- const urls: string[] = [];
- if (item.path) {
- urls.push(`/file-api/file-content?path=${encodeURIComponent(item.path)}&encoding=auto`);
- }
- if (item.downloadUrl) {
- urls.push(item.downloadUrl);
- }
- if (urls.length === 0) {
- throw new Error('missing_readable_path');
- }
-
- let lastError: unknown = null;
- for (const url of urls) {
- try {
- const response = await fetch(url, { cache: 'no-store' });
- const text = await response.text();
- if (!response.ok) {
- lastError = new Error(`HTTP ${response.status}`);
- continue;
- }
- if (isHtmlFallback(response.headers.get('content-type') || '', text)) {
- lastError = new Error('html_fallback');
- continue;
- }
- return text;
- } catch (error) {
- lastError = error;
- }
- }
- throw lastError instanceof Error ? lastError : new Error('preview_failed');
-}
-
export function useSessionArtifacts(): ArtifactItem[] {
- const activeSessionId = useChatStore((s) => s.activeSessionId);
- const messages = useChatStore((s) => s.runtimes[activeSessionId ?? '']?.messages ?? []);
- const executionEvents = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.teamMemberExecutionEvents ?? []);
- const teamTasks = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.teamTasks ?? []);
+ const activeSessionId = useChatStore(s => s.activeSessionId);
+ const messages = useChatStore(s => s.runtimes[activeSessionId ?? '']?.messages ?? []);
- return useMemo(
- () => buildArtifacts(messages, executionEvents, teamTasks),
- [executionEvents, messages, teamTasks]
- );
+ return useMemo(() => buildArtifacts(messages), [messages]);
}
export function useSessionArtifactsCount(): number {
return useSessionArtifacts().length;
}
-export function ArtifactsPanel({ className }: { className?: string }) {
+export function ArtifactsPanel({
+ className,
+ selectedArtifactId,
+ onSelectArtifact,
+}: {
+ className?: string;
+ selectedArtifactId?: string;
+ onSelectArtifact?: (artifactId: string) => void;
+}) {
const { t } = useTranslation();
const artifacts = useSessionArtifacts();
const [selectedId, setSelectedId] = useState<string>('');
- const [previewState, setPreviewState] = useState<PreviewState>({ status: 'idle', content: '' });
- const [listWidth, setListWidth] = useState(320);
- const selectedArtifact = artifacts.find((artifact) => artifact.id === selectedId) || artifacts[0] || null;
- const dragStateRef = useRef<{ startX: number; startWidth: number } | null>(null);
+ const [isListOpen, setIsListOpen] = useState(false);
+ const [listWidth, setListWidth] = useState(MIN_LIST_WIDTH);
+ const [invalidPresentationIds, setInvalidPresentationIds] = useState<Set<string>>(() => new Set());
+ const listResizeDragRef = useRef<ListResizeDrag | null>(null);
+ const selectedArtifact = artifacts.find(artifact => artifact.id === selectedId) || artifacts[0] || null;
+ const selectedPresentationIsInvalid = selectedArtifact ? invalidPresentationIds.has(selectedArtifact.id) : false;
useEffect(() => {
+ if (selectedArtifactId && artifacts.some(artifact => artifact.id === selectedArtifactId) && selectedArtifactId !== selectedId) {
+ setSelectedId(selectedArtifactId);
+ return;
+ }
if (!selectedArtifact) {
setSelectedId('');
- setPreviewState({ status: 'idle', content: '' });
return;
}
if (selectedArtifact.id !== selectedId) {
setSelectedId(selectedArtifact.id);
}
- }, [selectedArtifact, selectedId]);
-
- useEffect(() => {
- if (!selectedArtifact) return;
- if (!isMarkdownArtifact(selectedArtifact)) {
- setPreviewState({ status: 'idle', content: '' });
- return;
- }
-
- let cancelled = false;
- setPreviewState({ status: 'loading', content: '' });
- void fetchMarkdownPreview(selectedArtifact)
- .then((content) => {
- if (!cancelled) {
- setPreviewState({ status: 'ready', content });
- }
- })
- .catch((error) => {
- if (!cancelled) {
- const key = error instanceof Error && error.message === 'missing_readable_path'
- ? 'artifacts.previewMissingPath'
- : 'artifacts.previewFailed';
- setPreviewState({ status: 'error', content: '', error: t(key) });
- }
- });
-
- return () => {
- cancelled = true;
- };
- }, [selectedArtifact, t]);
+ }, [artifacts, selectedArtifact, selectedArtifactId, selectedId]);
+
+ const handlePresentationStructureInvalidChange = useCallback((artifactId: string, invalid: boolean) => {
+ setInvalidPresentationIds(current => {
+ if (current.has(artifactId) === invalid) return current;
+ const next = new Set(current);
+ if (invalid) next.add(artifactId);
+ else next.delete(artifactId);
+ return next;
+ });
+ }, []);
const handleDownload = async (artifact: ArtifactItem) => {
- const downloadUrl = artifact.downloadUrl || (artifact.path ? `/file-api/file-content?path=${encodeURIComponent(artifact.path)}` : '');
+ const downloadUrl = artifactDownloadUrl(artifact);
if (!downloadUrl) return;
const pywebviewApi = (window as DownloadCapableWindow).pywebview?.api;
if (pywebviewApi?.download_file) {
- const success = await pywebviewApi.download_file(downloadUrl, artifact.name || 'download');
- if (!success) {
- console.error('Download failed via pywebview API');
+ const outcome = await executeDesktopSave(() =>
+ pywebviewApi.download_file!(downloadUrl, artifact.name || 'download')
+ );
+ if (outcome === 'failed') {
+ window.alert(t('artifacts.downloadFailed', { name: artifact.name }));
}
return;
}
@@ -348,140 +100,129 @@ export function ArtifactsPanel({ className }: { className?: string }) {
document.body.removeChild(link);
};
- const handleDividerMouseDown = (event: ReactMouseEvent<HTMLDivElement>) => {
+ const handleListResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) return;
event.preventDefault();
- dragStateRef.current = { startX: event.clientX, startWidth: listWidth };
-
- const handleMouseMove = (moveEvent: MouseEvent) => {
- const state = dragStateRef.current;
- if (!state) return;
- setListWidth(Math.min(520, Math.max(240, state.startWidth + moveEvent.clientX - state.startX)));
- };
- const handleMouseUp = () => {
- dragStateRef.current = null;
- document.removeEventListener('mousemove', handleMouseMove);
- document.removeEventListener('mouseup', handleMouseUp);
+ event.currentTarget.setPointerCapture(event.pointerId);
+ listResizeDragRef.current = {
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startWidth: listWidth,
};
+ };
- document.addEventListener('mousemove', handleMouseMove);
- document.addEventListener('mouseup', handleMouseUp);
+ const handleListResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const drag = listResizeDragRef.current;
+ if (!drag || drag.pointerId !== event.pointerId) return;
+ const nextWidth = drag.startWidth + event.clientX - drag.startX;
+ setListWidth(Math.min(MAX_LIST_WIDTH, Math.max(MIN_LIST_WIDTH, nextWidth)));
};
- return (
- <section className={clsx('flex min-h-0 min-w-0 flex-1 overflow-hidden bg-card', className)}>
- <aside
- className="flex shrink-0 flex-col overflow-hidden border-border bg-card"
- style={{ width: listWidth }}
- >
- <div className="shrink-0 px-4 py-3">
- <div className="text-sm font-semibold text-text">{t('artifacts.title')}</div>
- <div className="mt-1 text-xs text-text-muted">
- {t('artifacts.count', { count: artifacts.length })}
- </div>
- </div>
+ const finishListResize = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (listResizeDragRef.current?.pointerId !== event.pointerId) return;
+ listResizeDragRef.current = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ };
- <div className="min-h-0 flex-1 overflow-y-auto p-3">
- {artifacts.length === 0 ? (
- <div className="flex h-full items-center justify-center px-5 text-center text-sm text-text-muted">
- {t('artifacts.empty')}
- </div>
- ) : (
- <div className="space-y-2">
- {artifacts.map((artifact) => {
- const selected = selectedArtifact?.id === artifact.id;
- return (
- <button
- key={artifact.id}
- type="button"
- className={clsx(
- 'w-full rounded-md border px-3 py-2.5 text-left ',
- selected
- ? 'border-accent bg-accent-subtle'
- : 'border-border bg-card hover:border-border-hover hover:bg-secondary'
- )}
- onClick={() => setSelectedId(artifact.id)}
- >
- <div className="flex min-w-0 items-center gap-2">
- <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-secondary text-text-muted">
- <FileText size={15} />
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-text">{artifact.name}</span>
- <span className="mt-1 flex min-w-0 items-center gap-2 text-xs text-text-muted">
- <span className="shrink-0 rounded bg-secondary px-1.5 py-0.5 font-mono text-[10px]">
- {getFileTypeLabel(artifact)}
- </span>
- <span className="shrink-0">{formatFileSize(artifact.size)}</span>
- {artifact.sourceMember && (
- <span className="truncate">{getMemberDisplayName(artifact.sourceMember)}</span>
- )}
- </span>
- </span>
- </div>
- </button>
- );
- })}
+ return (
+ <section className={clsx('flex min-h-0 min-w-0 flex-1 overflow-hidden bg-transparent', className)}>
+ {isListOpen && (
+ <>
+ <aside className="flex shrink-0 flex-col overflow-hidden bg-card" style={{ width: listWidth }} data-testid="artifact-list">
+ <div className="flex h-12 shrink-0 items-center px-6">
+ <div className="text-sm font-semibold text-text">{t('artifacts.title')}</div>
</div>
- )}
- </div>
- </aside>
- <div
- className="resize-divider"
- onMouseDown={handleDividerMouseDown}
- />
-
- <div className="flex min-w-0 flex-1 flex-col overflow-hidden bg-card">
- {selectedArtifact ? (
- <>
- <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-3">
- <div className="min-w-0">
- <div className="truncate text-sm font-semibold text-text">{selectedArtifact.name}</div>
- <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-text-muted">
- <span>{getFileTypeLabel(selectedArtifact)}</span>
- <span>|</span>
- <span>{formatFileSize(selectedArtifact.size)}</span>
- {selectedArtifact.sourceMember && (
- <>
- <span>|</span>
- <span className="truncate">{getMemberDisplayName(selectedArtifact.sourceMember)}</span>
- </>
- )}
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-4">
+ {artifacts.length === 0 ? (
+ <div className="flex h-full items-center justify-center px-5 text-center text-sm text-text-muted">{t('artifacts.empty')}</div>
+ ) : (
+ <div className="space-y-2">
+ {artifacts.map(artifact => {
+ const selected = selectedArtifact?.id === artifact.id;
+ return (
+ <button
+ key={artifact.id}
+ type="button"
+ className={clsx(
+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-lg px-3 text-left text-sm',
+ selected ? 'bg-secondary text-text' : 'text-text hover:bg-secondary',
+ )}
+ onClick={() => {
+ setSelectedId(artifact.id);
+ onSelectArtifact?.(artifact.id);
+ }}
+ >
+ <FileText size={16} className="shrink-0 text-text-muted" />
+ <span className="truncate">{artifact.name}</span>
+ </button>
+ );
+ })}
</div>
- </div>
- <button
- type="button"
- className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-text-muted hover:bg-secondary hover:text-text disabled:cursor-not-allowed disabled:opacity-40"
- title={t('artifacts.download')}
- aria-label={t('artifacts.download')}
- disabled={!selectedArtifact.downloadUrl && !selectedArtifact.path}
- onClick={() => {
- void handleDownload(selectedArtifact);
- }}
- >
- <Download size={16} />
- </button>
+ )}
</div>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
- {!isMarkdownArtifact(selectedArtifact) ? (
- <PreviewNotice title={t('artifacts.previewUnsupported')} />
- ) : previewState.status === 'loading' ? (
- <div className="flex h-full items-center justify-center gap-2 text-sm text-text-muted">
- <LoaderCircle size={16} className="animate-spin" />
- {t('common.loading')}
+ </aside>
+
+ <div
+ className="resize-divider touch-none select-none"
+ data-testid="artifact-list-resize-divider"
+ onPointerDown={handleListResizePointerDown}
+ onPointerMove={handleListResizePointerMove}
+ onPointerUp={finishListResize}
+ onPointerCancel={finishListResize}
+ onLostPointerCapture={() => {
+ listResizeDragRef.current = null;
+ }}
+ />
+ </>
+ )}
+
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden bg-transparent">
+ <div className="flex h-12 shrink-0 items-center gap-3 border-b border-border px-3">
+ <button
+ type="button"
+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-text-muted hover:bg-secondary hover:text-text"
+ title={t(isListOpen ? 'artifacts.collapseList' : 'artifacts.expandList')}
+ aria-label={t(isListOpen ? 'artifacts.collapseList' : 'artifacts.expandList')}
+ aria-expanded={isListOpen}
+ onClick={() => setIsListOpen(open => !open)}
+ >
+ {isListOpen ? <PanelLeftClose size={18} /> : <PanelLeftOpen size={18} />}
+ </button>
+ <div className="h-5 w-px bg-border" />
+ {selectedArtifact && (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <div className="min-w-0 truncate text-sm font-medium text-text">{selectedArtifact.name}</div>
+ {selectedPresentationIsInvalid && (
+ <div className="flex min-w-0 items-center gap-1 text-xs text-danger" role="status" title={t('artifacts.presentationStructureInvalid')}>
+ <AlertCircle size={14} className="shrink-0" />
+ <span className="truncate">{t('artifacts.presentationStructureInvalid')}</span>
</div>
- ) : previewState.status === 'error' ? (
- <PreviewNotice title={previewState.error} />
- ) : (
- <MarkdownRenderer
- content={previewState.content}
- className="chat-text chat-markdown max-w-none"
- testId="artifact-markdown-preview"
- />
)}
</div>
- </>
+ )}
+ {selectedArtifact && (
+ <button
+ type="button"
+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-text-muted hover:bg-secondary hover:text-text disabled:cursor-not-allowed disabled:opacity-40"
+ title={t('artifacts.download')}
+ aria-label={t('artifacts.download')}
+ disabled={!selectedArtifact.downloadUrl && !selectedArtifact.path}
+ onClick={() => {
+ void handleDownload(selectedArtifact);
+ }}
+ >
+ <Download size={16} />
+ </button>
+ )}
+ </div>
+
+ {selectedArtifact ? (
+ <div className="min-h-0 flex-1 overflow-hidden bg-transparent p-3" data-testid="artifact-preview-surface">
+ <FilePreview artifact={selectedArtifact} onPresentationStructureInvalidChange={handlePresentationStructureInvalidChange} />
+ </div>
) : (
<PreviewNotice title={t('artifacts.selectArtifact')} fill />
)}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/ooxmlArchiveLimits.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/ooxmlArchiveLimits.ts
new file mode 100644
index 0000000000..31965ed19b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/ooxmlArchiveLimits.ts
@@ -0,0 +1,187 @@
+const MEBIBYTE = 1024 * 1024;
+const END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50;
+const ZIP64_END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06064b50;
+const ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE = 0x07064b50;
+const CENTRAL_DIRECTORY_ENTRY_SIGNATURE = 0x02014b50;
+const ZIP64_EXTRA_FIELD_ID = 0x0001;
+const MAX_ZIP_COMMENT_BYTES = 65_535;
+
+export type OoxmlArchiveLimits = {
+ maxCompressedBytes: number;
+ maxEntries: number;
+ maxEntryUncompressedBytes: number;
+ maxTotalUncompressedBytes: number;
+};
+
+export type OoxmlArchiveLimitKind = 'compressed-size' | 'entry-count' | 'entry-size' | 'uncompressed-size';
+
+export const PRESENTATION_ARCHIVE_LIMITS: OoxmlArchiveLimits = {
+ maxCompressedBytes: 50 * MEBIBYTE,
+ maxEntries: 5_000,
+ maxEntryUncompressedBytes: 64 * MEBIBYTE,
+ maxTotalUncompressedBytes: 200 * MEBIBYTE,
+};
+
+export const SPREADSHEET_ARCHIVE_LIMITS: OoxmlArchiveLimits = {
+ maxCompressedBytes: 50 * MEBIBYTE,
+ maxEntries: 5_000,
+ maxEntryUncompressedBytes: 64 * MEBIBYTE,
+ maxTotalUncompressedBytes: 128 * MEBIBYTE,
+};
+
+export class OoxmlArchiveLimitError extends Error {
+ constructor(readonly limit: OoxmlArchiveLimitKind) {
+ super(`The OOXML archive exceeds the ${limit} preview limit`);
+ this.name = 'OoxmlArchiveLimitError';
+ }
+}
+
+export function isOoxmlArchiveLimitError(error: unknown): error is OoxmlArchiveLimitError {
+ return error instanceof OoxmlArchiveLimitError;
+}
+
+export function inspectOoxmlArchive(buffer: ArrayBuffer | ArrayBufferView, limits: OoxmlArchiveLimits): void {
+ if (buffer.byteLength > limits.maxCompressedBytes) throw new OoxmlArchiveLimitError('compressed-size');
+
+ const view = buffer instanceof ArrayBuffer ? new DataView(buffer) : new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ const directory = readCentralDirectory(view);
+ if (directory.entryCount > BigInt(limits.maxEntries)) throw new OoxmlArchiveLimitError('entry-count');
+
+ const directoryOffset = safeOffset(directory.offset, view.byteLength);
+ const directorySize = safeOffset(directory.size, view.byteLength);
+ const directoryEnd = directoryOffset + directorySize;
+ if (directoryEnd > view.byteLength) throw new Error('The OOXML archive has an invalid central directory');
+
+ let entryOffset = directoryOffset;
+ let totalUncompressedBytes = 0n;
+ for (let index = 0; index < Number(directory.entryCount); index += 1) {
+ assertAvailable(view, entryOffset, 46);
+ if (view.getUint32(entryOffset, true) !== CENTRAL_DIRECTORY_ENTRY_SIGNATURE) {
+ throw new Error('The OOXML archive has an invalid central directory entry');
+ }
+
+ const fileNameLength = view.getUint16(entryOffset + 28, true);
+ const extraFieldLength = view.getUint16(entryOffset + 30, true);
+ const commentLength = view.getUint16(entryOffset + 32, true);
+ const extraFieldOffset = entryOffset + 46 + fileNameLength;
+ const nextEntryOffset = extraFieldOffset + extraFieldLength + commentLength;
+ if (nextEntryOffset > directoryEnd) throw new Error('The OOXML archive has a truncated central directory entry');
+
+ const uncompressedSize = readEntryUncompressedSize(view, entryOffset, extraFieldOffset, extraFieldLength);
+ if (uncompressedSize > BigInt(limits.maxEntryUncompressedBytes)) throw new OoxmlArchiveLimitError('entry-size');
+ totalUncompressedBytes += uncompressedSize;
+ if (totalUncompressedBytes > BigInt(limits.maxTotalUncompressedBytes)) {
+ throw new OoxmlArchiveLimitError('uncompressed-size');
+ }
+ entryOffset = nextEntryOffset;
+ }
+ if (entryOffset !== directoryEnd) throw new Error('The OOXML archive central directory size does not match its entries');
+}
+
+type CentralDirectory = {
+ entryCount: bigint;
+ offset: bigint;
+ size: bigint;
+};
+
+function readCentralDirectory(view: DataView): CentralDirectory {
+ const endOffset = findEndOfCentralDirectory(view);
+ const diskNumber = view.getUint16(endOffset + 4, true);
+ const directoryDiskNumber = view.getUint16(endOffset + 6, true);
+ const diskEntryCount = view.getUint16(endOffset + 8, true);
+ const entryCount = view.getUint16(endOffset + 10, true);
+ const directorySize = view.getUint32(endOffset + 12, true);
+ const directoryOffset = view.getUint32(endOffset + 16, true);
+ const usesZip64 =
+ diskNumber === 0xffff ||
+ directoryDiskNumber === 0xffff ||
+ diskEntryCount === 0xffff ||
+ entryCount === 0xffff ||
+ directorySize === 0xffffffff ||
+ directoryOffset === 0xffffffff;
+
+ if (usesZip64) return readZip64CentralDirectory(view, endOffset);
+ if (diskNumber !== 0 || directoryDiskNumber !== 0 || diskEntryCount !== entryCount) {
+ throw new Error('Multi-disk OOXML archives are not supported');
+ }
+ return {
+ entryCount: BigInt(entryCount),
+ offset: BigInt(directoryOffset),
+ size: BigInt(directorySize),
+ };
+}
+
+function findEndOfCentralDirectory(view: DataView): number {
+ const minimumOffset = Math.max(0, view.byteLength - 22 - MAX_ZIP_COMMENT_BYTES);
+ for (let offset = view.byteLength - 22; offset >= minimumOffset; offset -= 1) {
+ if (view.getUint32(offset, true) !== END_OF_CENTRAL_DIRECTORY_SIGNATURE) continue;
+ const commentLength = view.getUint16(offset + 20, true);
+ if (offset + 22 + commentLength === view.byteLength) return offset;
+ }
+ throw new Error('The OOXML archive has no valid end-of-central-directory record');
+}
+
+function readZip64CentralDirectory(view: DataView, endOffset: number): CentralDirectory {
+ const locatorOffset = endOffset - 20;
+ assertAvailable(view, locatorOffset, 20);
+ if (view.getUint32(locatorOffset, true) !== ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE) {
+ throw new Error('The OOXML archive has no valid ZIP64 locator');
+ }
+ const zip64DiskNumber = view.getUint32(locatorOffset + 4, true);
+ const zip64EndOffset = safeOffset(view.getBigUint64(locatorOffset + 8, true), view.byteLength);
+ const diskCount = view.getUint32(locatorOffset + 16, true);
+ assertAvailable(view, zip64EndOffset, 56);
+ if (view.getUint32(zip64EndOffset, true) !== ZIP64_END_OF_CENTRAL_DIRECTORY_SIGNATURE) {
+ throw new Error('The OOXML archive has no valid ZIP64 end-of-central-directory record');
+ }
+
+ const recordSize = view.getBigUint64(zip64EndOffset + 4, true);
+ if (recordSize < 44n || BigInt(zip64EndOffset) + 12n + recordSize > BigInt(locatorOffset)) {
+ throw new Error('The OOXML archive has an invalid ZIP64 end-of-central-directory record');
+ }
+ const diskNumber = view.getUint32(zip64EndOffset + 16, true);
+ const directoryDiskNumber = view.getUint32(zip64EndOffset + 20, true);
+ const diskEntryCount = view.getBigUint64(zip64EndOffset + 24, true);
+ const entryCount = view.getBigUint64(zip64EndOffset + 32, true);
+ if (zip64DiskNumber !== 0 || diskCount !== 1 || diskNumber !== 0 || directoryDiskNumber !== 0 || diskEntryCount !== entryCount) {
+ throw new Error('Multi-disk OOXML archives are not supported');
+ }
+ return {
+ entryCount,
+ size: view.getBigUint64(zip64EndOffset + 40, true),
+ offset: view.getBigUint64(zip64EndOffset + 48, true),
+ };
+}
+
+function readEntryUncompressedSize(view: DataView, entryOffset: number, extraFieldOffset: number, extraFieldLength: number): bigint {
+ const uncompressed32 = view.getUint32(entryOffset + 24, true);
+ if (uncompressed32 !== 0xffffffff) return BigInt(uncompressed32);
+ return readZip64UncompressedSize(view, extraFieldOffset, extraFieldLength);
+}
+
+function readZip64UncompressedSize(view: DataView, extraFieldOffset: number, extraFieldLength: number): bigint {
+ const extraFieldEnd = extraFieldOffset + extraFieldLength;
+ let offset = extraFieldOffset;
+ while (offset + 4 <= extraFieldEnd) {
+ const fieldId = view.getUint16(offset, true);
+ const fieldSize = view.getUint16(offset + 2, true);
+ const fieldDataOffset = offset + 4;
+ const nextFieldOffset = fieldDataOffset + fieldSize;
+ if (nextFieldOffset > extraFieldEnd) throw new Error('The OOXML archive has a truncated extra field');
+ if (fieldId === ZIP64_EXTRA_FIELD_ID) {
+ if (fieldDataOffset + 8 > nextFieldOffset) throw new Error('The OOXML archive has an incomplete ZIP64 size field');
+ return view.getBigUint64(fieldDataOffset, true);
+ }
+ offset = nextFieldOffset;
+ }
+ throw new Error('The OOXML archive is missing ZIP64 entry sizes');
+}
+
+function safeOffset(value: bigint, byteLength: number): number {
+ if (value > BigInt(byteLength)) throw new Error('The OOXML archive contains an invalid offset');
+ return Number(value);
+}
+
+function assertAvailable(view: DataView, offset: number, length: number): void {
+ if (offset < 0 || length < 0 || offset + length > view.byteLength) throw new Error('The OOXML archive is truncated');
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPresentationParser.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPresentationParser.ts
new file mode 100644
index 0000000000..dbf615dadb
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPresentationParser.ts
@@ -0,0 +1,1118 @@
+import JSZip from 'jszip';
+import { SaxesParser } from 'saxes';
+import { OoxmlArchiveLimitError, PRESENTATION_ARCHIVE_LIMITS, inspectOoxmlArchive, isOoxmlArchiveLimitError } from './ooxmlArchiveLimits';
+import {
+ MAX_PRESENTATION_UNCOMPRESSED_BYTES,
+ type PresentationBounds,
+ type PresentationChart,
+ type PresentationColor,
+ type PresentationData,
+ type PresentationFill,
+ type PresentationImage,
+ type PresentationNode,
+ type PresentationParagraph,
+ type PresentationRun,
+ type PresentationShape,
+ type PresentationSlide,
+ type PresentationSpacing,
+ type PresentationStroke,
+ type PresentationTable,
+ type PresentationText,
+} from './pptxPreviewModel';
+
+type XmlNode = { name: string; attrs: Record<string, string>; children: XmlNode[]; text: string };
+type Relationship = { id: string; target: string; type: string; external: boolean };
+type ThemeFont = {
+ latin?: string;
+ eastAsian?: string;
+ complexScript?: string;
+ supplemental: Map<string, string>;
+};
+type Theme = { colors: Map<string, string>; majorFont: ThemeFont; minorFont: ThemeFont };
+type Part = { path: string; xml: XmlNode; rels: Map<string, Relationship> };
+type SlidePart = { part: Part };
+type Transform = { scaleX: number; scaleY: number; offsetX: number; offsetY: number };
+type Template = { background: PresentationFill; nodes: PresentationNode[]; placeholders: Map<string, PresentationShape> };
+type TableStyle = { wholeTbl?: PresentationFill; band1H?: PresentationFill; firstRow?: PresentationFill };
+
+const EMUS_PER_PIXEL = 9_525;
+const CSS_PIXELS_PER_POINT = 96 / 72;
+const EMPTY_FILL: PresentationFill = { kind: 'none' };
+const WHITE_FILL: PresentationFill = { kind: 'solid', color: '#FFFFFF' };
+const ROOT_TRANSFORM: Transform = { scaleX: 1, scaleY: 1, offsetX: 0, offsetY: 0 };
+const SUPPORTED_GEOMETRIES = new Set([
+ 'rect',
+ 'roundRect',
+ 'ellipse',
+ 'triangle',
+ 'rtTriangle',
+ 'diamond',
+ 'parallelogram',
+ 'trapezoid',
+ 'hexagon',
+ 'pentagon',
+ 'chevron',
+ 'plus',
+ 'minus',
+ 'line',
+ 'lineVertical',
+]);
+const MEDIUM_STYLE_2_ACCENT_1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}';
+
+export async function parsePresentation(buffer: ArrayBuffer): Promise<PresentationData> {
+ inspectOoxmlArchive(buffer, PRESENTATION_ARCHIVE_LIMITS);
+ const archive = await JSZip.loadAsync(buffer, { checkCRC32: true, createFolders: false });
+ const entries = Object.values(archive.files).filter(entry => !entry.dir);
+ if (entries.length === 0) throw new Error('The presentation archive is empty');
+
+ const files = new Map<string, JSZip.JSZipObject>();
+ for (const entry of entries) {
+ if (entry.name.includes('..') || entry.name.startsWith('/')) throw new Error('The presentation contains an unsafe archive path');
+ files.set(entry.name, entry);
+ }
+ const presentationFile = files.get('ppt/presentation.xml');
+ if (!presentationFile) throw new Error('This is not a PPTX or PPTM presentation');
+
+ let unpackedBytes = 0;
+ const textCache = new Map<string, string>();
+ const xmlCache = new Map<string, XmlNode>();
+ const blobCache = new Map<string, Blob>();
+ const readText = async (path: string): Promise<string | undefined> => {
+ if (textCache.has(path)) return textCache.get(path);
+ const entry = files.get(path);
+ if (!entry) return undefined;
+ const text = await entry.async('string');
+ unpackedBytes += new TextEncoder().encode(text).byteLength;
+ ensureUncompressedLimit(unpackedBytes);
+ textCache.set(path, text);
+ return text;
+ };
+ const readXml = async (path: string): Promise<XmlNode | undefined> => {
+ if (xmlCache.has(path)) return xmlCache.get(path);
+ const text = await readText(path);
+ if (text === undefined) return undefined;
+ const xml = parseXml(text);
+ xmlCache.set(path, xml);
+ return xml;
+ };
+ const readBlob = async (path: string): Promise<Blob | undefined> => {
+ if (blobCache.has(path)) return blobCache.get(path);
+ const entry = files.get(path);
+ if (!entry) return undefined;
+ const bytes = await entry.async('uint8array');
+ unpackedBytes += bytes.byteLength;
+ ensureUncompressedLimit(unpackedBytes);
+ const blob = new Blob([new Uint8Array(bytes)], { type: mediaMimeType(path) });
+ blobCache.set(path, blob);
+ return blob;
+ };
+
+ const presentationXml = await readXml('ppt/presentation.xml');
+ const presentationRels = await readRelationships('ppt/_rels/presentation.xml.rels', readXml);
+ if (!presentationXml) throw new Error('The presentation XML cannot be read');
+ const { width, height } = readSlideSize(presentationXml);
+ const themeCache = new Map<string, Theme>();
+ const partCache = new Map<string, Part>();
+ const templateCache = new Map<string, Template>();
+
+ const getPart = async (path: string): Promise<Part | undefined> => {
+ if (partCache.has(path)) return partCache.get(path);
+ const xml = await readXml(path);
+ if (!xml) return undefined;
+ const part: Part = { path, xml, rels: await readRelationships(relsPath(path), readXml) };
+ partCache.set(path, part);
+ return part;
+ };
+ const getSlidePart = async (path: string): Promise<SlidePart | undefined> => {
+ const text = await readText(path);
+ if (text === undefined) return undefined;
+ return {
+ part: { path, xml: parseXml(text), rels: await readRelationships(relsPath(path), readXml) },
+ };
+ };
+ const getTheme = async (master: Part | undefined): Promise<Theme> => {
+ if (!master) return emptyTheme();
+ const themeRelationship = findRelationship(master.rels, 'theme');
+ if (!themeRelationship || themeRelationship.external) return emptyTheme();
+ const path = resolveTarget(master.path, themeRelationship.target);
+ if (themeCache.has(path)) return themeCache.get(path)!;
+ const xml = await readXml(path);
+ const theme = xml ? parseTheme(xml) : emptyTheme();
+ themeCache.set(path, theme);
+ return theme;
+ };
+ const getTemplate = async (part: Part, theme: Theme): Promise<Template> => {
+ const cached = templateCache.get(part.path);
+ if (cached) return cached;
+ const template = await parseTemplate(part, theme, readBlob, readXml);
+ templateCache.set(part.path, template);
+ return template;
+ };
+
+ const slideIdList = direct<XmlNode | undefined>(child(presentationXml, 'sldIdLst'));
+ const slideReferences = direct<XmlNode[]>(child(slideIdList, 'sldId', true));
+ const slides: PresentationSlide[] = [];
+ for (let index = 0; index < slideReferences.length; index += 1) {
+ const relationId = attr(slideReferences[index], 'r:id');
+ const relationship = relationId ? presentationRels.get(relationId) : undefined;
+ if (!relationship || relationship.external || !relationship.type.includes('slide')) {
+ slides.push(invalidSlide(index));
+ continue;
+ }
+ try {
+ const slidePart = await getSlidePart(resolveTarget('ppt/presentation.xml', relationship.target));
+ if (!slidePart) {
+ slides.push(invalidSlide(index));
+ continue;
+ }
+ const layoutRelationship = findRelationship(slidePart.part.rels, 'slideLayout');
+ const layoutPart =
+ layoutRelationship && !layoutRelationship.external ? await getPart(resolveTarget(slidePart.part.path, layoutRelationship.target)) : undefined;
+ const masterRelationship = layoutPart ? findRelationship(layoutPart.rels, 'slideMaster') : undefined;
+ const masterPart =
+ masterRelationship && !masterRelationship.external ? await getPart(resolveTarget(layoutPart!.path, masterRelationship.target)) : undefined;
+ const theme = await getTheme(masterPart);
+ const masterTemplate = masterPart ? await getTemplate(masterPart, theme) : emptyTemplate();
+ const layoutTemplate = layoutPart ? await getTemplate(layoutPart, theme) : emptyTemplate();
+ slides.push(await parseSlide(slidePart.part, index, theme, masterTemplate, layoutTemplate, readBlob, readXml));
+ } catch (error) {
+ if (isOoxmlArchiveLimitError(error)) throw error;
+ slides.push(invalidSlide(index));
+ }
+ }
+ if (slides.length === 0) throw new Error('The presentation contains no readable slides');
+ return { width, height, slides };
+}
+
+function ensureUncompressedLimit(size: number): void {
+ if (size > MAX_PRESENTATION_UNCOMPRESSED_BYTES) throw new OoxmlArchiveLimitError('uncompressed-size');
+}
+
+function invalidSlide(index: number): PresentationSlide {
+ return {
+ id: `slide-${index + 1}`,
+ name: `Slide ${index + 1}`,
+ background: WHITE_FILL,
+ nodes: [],
+ status: 'invalid',
+ };
+}
+
+function parseXml(input: string): XmlNode {
+ const root: XmlNode = { name: '__root__', attrs: {}, children: [], text: '' };
+ const stack = [root];
+ const parser = new SaxesParser<{ xmlns: false }>({ xmlns: false });
+ parser.on('opentag', tag => {
+ const attrs: Record<string, string> = {};
+ Object.entries(tag.attributes).forEach(([name, value]) => {
+ attrs[name] = String(value);
+ });
+ const node: XmlNode = { name: tag.name, attrs, children: [], text: '' };
+ stack[stack.length - 1].children.push(node);
+ stack.push(node);
+ });
+ parser.on('text', text => {
+ stack[stack.length - 1].text += text;
+ });
+ parser.on('cdata', text => {
+ stack[stack.length - 1].text += text;
+ });
+ parser.on('closetag', () => {
+ if (stack.length > 1) stack.pop();
+ });
+ parser.on('error', error => {
+ throw new Error(`Invalid presentation XML: ${error.message}`);
+ });
+ parser.write(input).close();
+ if (root.children.length !== 1) throw new Error('Invalid presentation XML document');
+ return root.children[0];
+}
+
+function localName(name: string): string {
+ return name.includes(':') ? name.slice(name.lastIndexOf(':') + 1) : name;
+}
+
+function attr(node: XmlNode | undefined, name: string): string | undefined {
+ if (!node) return undefined;
+ return node.attrs[name] ?? node.attrs[localName(name)] ?? Object.entries(node.attrs).find(([key]) => localName(key) === localName(name))?.[1];
+}
+
+function child(node: XmlNode | undefined, name: string, all = false): XmlNode | XmlNode[] | undefined {
+ const matches = node?.children.filter(item => localName(item.name) === name) ?? [];
+ return all ? matches : matches[0];
+}
+
+function descendants(node: XmlNode | undefined, name: string): XmlNode[] {
+ if (!node) return [];
+ const result: XmlNode[] = [];
+ const visit = (current: XmlNode) => {
+ current.children.forEach(item => {
+ if (localName(item.name) === name) result.push(item);
+ visit(item);
+ });
+ };
+ visit(node);
+ return result;
+}
+
+function direct<T>(value: XmlNode | XmlNode[] | undefined): T {
+ return value as T;
+}
+
+function relsPath(path: string): string {
+ const slash = path.lastIndexOf('/');
+ const directory = slash >= 0 ? path.slice(0, slash) : '';
+ const file = slash >= 0 ? path.slice(slash + 1) : path;
+ return `${directory}/_rels/${file}.rels`;
+}
+
+async function readRelationships(path: string, readXml: (path: string) => Promise<XmlNode | undefined>): Promise<Map<string, Relationship>> {
+ const xml = await readXml(path);
+ const relationships = new Map<string, Relationship>();
+ direct<XmlNode[]>(child(xml, 'Relationship', true)).forEach(item => {
+ const id = attr(item, 'Id');
+ const target = attr(item, 'Target');
+ const type = attr(item, 'Type');
+ if (!id || !target || !type) return;
+ relationships.set(id, { id, target, type, external: attr(item, 'TargetMode') === 'External' });
+ });
+ return relationships;
+}
+
+function resolveTarget(sourcePath: string, target: string): string {
+ const base = sourcePath.slice(0, sourcePath.lastIndexOf('/') + 1);
+ const parts = `${base}${target}`.split('/');
+ const normalized: string[] = [];
+ for (const part of parts) {
+ if (!part || part === '.') continue;
+ if (part === '..') {
+ if (normalized.length === 0) throw new Error('The presentation relationship points outside its package');
+ normalized.pop();
+ } else {
+ normalized.push(part);
+ }
+ }
+ return normalized.join('/');
+}
+
+function findRelationship(rels: Map<string, Relationship>, type: string): Relationship | undefined {
+ return [...rels.values()].find(item => item.type.toLowerCase().includes(`/relationships/${type.toLowerCase()}`));
+}
+
+function readSlideSize(xml: XmlNode): { width: number; height: number } {
+ const size = direct<XmlNode | undefined>(child(xml, 'sldSz'));
+ return {
+ width: emu(attrNumber(size, 'cx') ?? 9_144_000),
+ height: emu(attrNumber(size, 'cy') ?? 6_858_000),
+ };
+}
+
+function emptyTheme(): Theme {
+ return {
+ colors: new Map(),
+ majorFont: { supplemental: new Map() },
+ minorFont: { supplemental: new Map() },
+ };
+}
+
+function parseTheme(xml: XmlNode): Theme {
+ const theme = emptyTheme();
+ const scheme = descendants(xml, 'clrScheme')[0];
+ scheme?.children.forEach(item => {
+ const color = resolveColor(item, theme);
+ if (color) theme.colors.set(localName(item.name), color);
+ });
+ const major = descendants(xml, 'majorFont')[0];
+ const minor = descendants(xml, 'minorFont')[0];
+ theme.majorFont = parseThemeFont(major);
+ theme.minorFont = parseThemeFont(minor);
+ return theme;
+}
+
+function parseThemeFont(node: XmlNode | undefined): ThemeFont {
+ const supplemental = new Map<string, string>();
+ direct<XmlNode[]>(child(node, 'font', true)).forEach(font => {
+ const script = attr(font, 'script');
+ const typeface = attr(font, 'typeface');
+ if (script && typeface) supplemental.set(script, typeface);
+ });
+ return {
+ latin: nonEmpty(attr(direct<XmlNode | undefined>(child(node, 'latin')), 'typeface')),
+ eastAsian: nonEmpty(attr(direct<XmlNode | undefined>(child(node, 'ea')), 'typeface')),
+ complexScript: nonEmpty(attr(direct<XmlNode | undefined>(child(node, 'cs')), 'typeface')),
+ supplemental,
+ };
+}
+
+function emptyTemplate(): Template {
+ return { background: EMPTY_FILL, nodes: [], placeholders: new Map() };
+}
+
+async function parseTemplate(
+ part: Part,
+ theme: Theme,
+ readBlob: (path: string) => Promise<Blob | undefined>,
+ readXml: (path: string) => Promise<XmlNode | undefined>,
+): Promise<Template> {
+ const tree = descendants(part.xml, 'spTree')[0];
+ if (!tree) return emptyTemplate();
+ const nodes = await parseNodes(tree.children, part, theme, ROOT_TRANSFORM, readBlob, readXml);
+ const placeholders = new Map<string, PresentationShape>();
+ nodes.forEach(node => {
+ if (node.type === 'shape' && node.placeholderKey) placeholders.set(node.placeholderKey, node);
+ });
+ return { background: parseBackground(part.xml, theme), nodes, placeholders };
+}
+
+async function parseSlide(
+ part: Part,
+ index: number,
+ theme: Theme,
+ master: Template,
+ layout: Template,
+ readBlob: (path: string) => Promise<Blob | undefined>,
+ readXml: (path: string) => Promise<XmlNode | undefined>,
+): Promise<PresentationSlide> {
+ const tree = descendants(part.xml, 'spTree')[0];
+ const rawNodes = tree ? await parseNodes(tree.children, part, theme, ROOT_TRANSFORM, readBlob, readXml) : [];
+ const nodes = rawNodes.map(node =>
+ inheritPlaceholder(node, layout.placeholders.get(node.placeholderKey ?? '') ?? master.placeholders.get(node.placeholderKey ?? '')),
+ );
+ const templateNodes = [...master.nodes, ...layout.nodes].filter(node => !node.placeholderKey);
+ const allNodes = [...templateNodes, ...nodes];
+ const hasUnsupportedNodes = allNodes.some(node => node.type === 'unsupported');
+ return {
+ id: `slide-${index + 1}`,
+ name: attr(descendants(part.xml, 'cSld')[0], 'name') || `Slide ${index + 1}`,
+ background: firstFill(parseBackground(part.xml, theme), layout.background, master.background, WHITE_FILL),
+ nodes: allNodes.filter(node => node.type !== 'unsupported'),
+ status: hasUnsupportedNodes ? 'incomplete' : undefined,
+ };
+}
+
+function inheritPlaceholder(node: PresentationNode, template: PresentationShape | undefined): PresentationNode {
+ if (!template || node.type !== 'shape') return node;
+ const hasBounds = node.width > 0 && node.height > 0;
+ return {
+ ...node,
+ x: hasBounds ? node.x : template.x,
+ y: hasBounds ? node.y : template.y,
+ width: hasBounds ? node.width : template.width,
+ height: hasBounds ? node.height : template.height,
+ fill: node.fill.kind === 'none' ? template.fill : node.fill,
+ stroke: node.stroke ?? template.stroke,
+ text: node.text ? { ...template.text, ...node.text, margin: node.text.margin } : template.text,
+ };
+}
+
+function firstFill(...fills: PresentationFill[]): PresentationFill {
+ return fills.find(fill => fill.kind !== 'none') ?? WHITE_FILL;
+}
+
+async function parseNodes(
+ children: XmlNode[],
+ part: Part,
+ theme: Theme,
+ transform: Transform,
+ readBlob: (path: string) => Promise<Blob | undefined>,
+ readXml: (path: string) => Promise<XmlNode | undefined>,
+ nodePath = 'root',
+): Promise<PresentationNode[]> {
+ const nodes: PresentationNode[] = [];
+ for (let index = 0; index < children.length; index += 1) {
+ const node = children[index];
+ const sourcePath = `${nodePath}.${index}`;
+ const type = localName(node.name);
+ if (type === 'nvGrpSpPr' || type === 'grpSpPr') continue;
+ if (type === 'sp') {
+ const shape = parseShape(node, theme, transform);
+ nodes.push(withSourceId(isSupportedGeometry(shape.geometry) ? shape : unsupported(node, transform, `shape: ${shape.geometry}`), part.path, sourcePath));
+ } else if (type === 'pic') {
+ const image = await parseImage(node, part, transform, readBlob);
+ nodes.push(withSourceId(image ?? unsupported(node, transform, 'image'), part.path, sourcePath));
+ } else if (type === 'graphicFrame') {
+ nodes.push(
+ withSourceId((await parseGraphicFrame(node, part, theme, transform, readXml)) ?? unsupported(node, transform, 'graphic object'), part.path, sourcePath),
+ );
+ } else if (type === 'grpSp') {
+ const groupTransform = composeTransform(node, transform);
+ nodes.push(...(await parseNodes(node.children, part, theme, groupTransform, readBlob, readXml, sourcePath)));
+ } else if (type === 'cxnSp') {
+ const connector = parseShape(node, theme, transform);
+ nodes.push(
+ withSourceId(
+ isSupportedGeometry(connector.geometry) ? connector : unsupported(node, transform, `connector: ${connector.geometry}`),
+ part.path,
+ sourcePath,
+ ),
+ );
+ } else if (['contentPart', 'graphic'].includes(type)) {
+ nodes.push(withSourceId(unsupported(node, transform, 'graphic object'), part.path, sourcePath));
+ }
+ }
+ return nodes;
+}
+
+function isSupportedGeometry(geometry: string): boolean {
+ return SUPPORTED_GEOMETRIES.has(geometry) || geometry.includes('Connector');
+}
+
+function withSourceId<T extends PresentationNode>(node: T, path: string, nodePath: string): T {
+ return { ...node, id: `${path}#${nodePath}:${node.id}` };
+}
+
+function parseShape(node: XmlNode, theme: Theme, transform: Transform): PresentationShape {
+ const properties = direct<XmlNode | undefined>(child(node, 'spPr'));
+ const textBody = direct<XmlNode | undefined>(child(node, 'txBody'));
+ const rawBounds = readBounds(properties, transform);
+ const nameNode = descendants(node, 'cNvPr')[0];
+ const placeholder = descendants(node, 'ph')[0];
+ const presetGeometry = direct<XmlNode | undefined>(child(properties, 'prstGeom'));
+ const parsedGeometry = attr(presetGeometry, 'prst') ?? (child(properties, 'custGeom') ? 'custom' : 'rect');
+ const stroke = parseStroke(properties, theme);
+ const geometry = isLinearGeometry(parsedGeometry) && rawBounds.width === 0 && rawBounds.height > 0 ? 'lineVertical' : parsedGeometry;
+ const bounds = normalizeLineBounds(rawBounds, geometry, stroke);
+ return {
+ type: 'shape',
+ id: nodeId(nameNode, `shape-${bounds.x}-${bounds.y}-${bounds.width}-${bounds.height}`),
+ name: attr(nameNode, 'name') ?? 'Shape',
+ placeholderKey: placeholderKey(placeholder),
+ geometry,
+ adjustments: parseGeometryAdjustments(presetGeometry),
+ fill: parseFill(properties, theme),
+ stroke,
+ text: textBody ? parseText(textBody, theme) : undefined,
+ ...bounds,
+ };
+}
+
+function parseGeometryAdjustments(geometry: XmlNode | undefined): Record<string, number> | undefined {
+ const values: Record<string, number> = {};
+ const adjustmentList = direct<XmlNode | undefined>(child(geometry, 'avLst'));
+ direct<XmlNode[]>(child(adjustmentList, 'gd', true)).forEach(guide => {
+ const name = attr(guide, 'name');
+ const formula = attr(guide, 'fmla')?.trim();
+ const match = formula?.match(/^val\s+(-?\d+(?:\.\d+)?)$/);
+ if (name && match) values[name] = Number(match[1]);
+ });
+ return Object.keys(values).length > 0 ? values : undefined;
+}
+
+function isLinearGeometry(geometry: string): boolean {
+ return geometry === 'line' || geometry.includes('Connector');
+}
+
+function normalizeLineBounds(bounds: PresentationBounds, geometry: string, stroke: PresentationStroke | undefined): PresentationBounds {
+ if (!isLinearGeometry(geometry) && geometry !== 'lineVertical') return bounds;
+ const thickness = Math.max(1, stroke?.width ?? 1);
+ const width = bounds.width || thickness;
+ const height = bounds.height || thickness;
+ return {
+ ...bounds,
+ x: bounds.width === 0 ? bounds.x - thickness / 2 : bounds.x,
+ y: bounds.height === 0 ? bounds.y - thickness / 2 : bounds.y,
+ width,
+ height,
+ };
+}
+
+async function parseImage(
+ node: XmlNode,
+ part: Part,
+ transform: Transform,
+ readBlob: (path: string) => Promise<Blob | undefined>,
+): Promise<PresentationImage | undefined> {
+ const properties = direct<XmlNode | undefined>(child(node, 'spPr'));
+ const blip = descendants(node, 'blip')[0];
+ const relationship = part.rels.get(attr(blip, 'r:embed') ?? '');
+ if (!relationship || relationship.external) return undefined;
+ const image = await readBlob(resolveTarget(part.path, relationship.target));
+ if (!image) return undefined;
+ const nameNode = descendants(node, 'cNvPr')[0];
+ const crop = descendants(node, 'srcRect')[0];
+ const bounds = readBounds(properties, transform);
+ return {
+ type: 'image',
+ id: nodeId(nameNode, `image-${bounds.x}-${bounds.y}-${bounds.width}-${bounds.height}`),
+ name: attr(nameNode, 'name') ?? 'Image',
+ alt: attr(nameNode, 'descr') ?? attr(nameNode, 'name') ?? 'Image',
+ image,
+ crop: crop
+ ? {
+ left: (attrNumber(crop, 'l') ?? 0) / 100_000,
+ right: (attrNumber(crop, 'r') ?? 0) / 100_000,
+ top: (attrNumber(crop, 't') ?? 0) / 100_000,
+ bottom: (attrNumber(crop, 'b') ?? 0) / 100_000,
+ }
+ : undefined,
+ ...bounds,
+ };
+}
+
+async function parseGraphicFrame(
+ node: XmlNode,
+ part: Part,
+ theme: Theme,
+ transform: Transform,
+ readXml: (path: string) => Promise<XmlNode | undefined>,
+): Promise<PresentationTable | PresentationChart | undefined> {
+ const graphicData = descendants(node, 'graphicData')[0];
+ if (!graphicData) return undefined;
+ const bounds = readBounds(node, transform);
+ const nameNode = descendants(node, 'cNvPr')[0];
+ const name = attr(nameNode, 'name') ?? 'Graphic';
+ const table = descendants(graphicData, 'tbl')[0];
+ if (table) return parseTable(table, { id: nodeId(nameNode, `table-${bounds.x}-${bounds.y}-${bounds.width}-${bounds.height}`), name, ...bounds }, theme);
+ const chart = descendants(graphicData, 'chart')[0];
+ const relationship = part.rels.get(attr(chart, 'r:id') ?? '');
+ if (!chart || !relationship || relationship.external) return undefined;
+ const chartXml = await readXml(resolveTarget(part.path, relationship.target));
+ return chartXml
+ ? parseChart(chartXml, { id: nodeId(nameNode, `chart-${bounds.x}-${bounds.y}-${bounds.width}-${bounds.height}`), name, ...bounds }, theme)
+ : undefined;
+}
+
+function parseTable(table: XmlNode, base: Omit<PresentationTable, 'type' | 'columns' | 'rows'>, theme: Theme): PresentationTable {
+ const properties = direct<XmlNode | undefined>(child(table, 'tblPr'));
+ const styleId = textContent(direct<XmlNode | undefined>(child(properties, 'tableStyleId'))).trim();
+ const style = builtInTableStyle(styleId, theme);
+ const hasFirstRow = attr(properties, 'firstRow') === '1' || attr(properties, 'firstRow') === 'true';
+ const hasRowBands = attr(properties, 'bandRow') === '1' || attr(properties, 'bandRow') === 'true';
+ const grid = direct<XmlNode[]>(child(direct<XmlNode | undefined>(child(table, 'tblGrid')), 'gridCol', true));
+ const rows = direct<XmlNode[]>(child(table, 'tr', true)).map((row, rowIndex) => ({
+ height: emu(attrNumber(row, 'h') ?? 0),
+ cells: direct<XmlNode[]>(child(row, 'tc', true)).map(cell => {
+ const cellProperties = direct<XmlNode | undefined>(child(cell, 'tcPr'));
+ return {
+ text: parseTableText(cell, theme),
+ fill: hasCellFill(cellProperties) ? parseFill(cellProperties, theme) : resolveTableStyleFill(style, rowIndex, hasFirstRow, hasRowBands),
+ stroke: parseStroke(cellProperties, theme),
+ colSpan: attrNumber(cellProperties, 'gridSpan') ?? 1,
+ rowSpan: attrNumber(cellProperties, 'rowSpan') ?? 1,
+ merged: attr(cellProperties, 'hMerge') === '1' || attr(cellProperties, 'vMerge') === '1',
+ };
+ }),
+ }));
+ return { type: 'table', ...base, columns: grid.map(item => emu(attrNumber(item, 'w') ?? 0)), rows };
+}
+
+function hasCellFill(properties: XmlNode | undefined): boolean {
+ return Boolean(child(properties, 'solidFill') || child(properties, 'gradFill') || child(properties, 'noFill'));
+}
+
+function resolveTableStyleFill(style: TableStyle | undefined, rowIndex: number, hasFirstRow: boolean, hasRowBands: boolean): PresentationFill {
+ if (!style) return EMPTY_FILL;
+ if (hasFirstRow && rowIndex === 0 && style.firstRow) return style.firstRow;
+ const dataRowIndex = rowIndex - (hasFirstRow ? 1 : 0);
+ if (hasRowBands && dataRowIndex >= 0 && dataRowIndex % 2 === 0 && style.band1H) return style.band1H;
+ return style.wholeTbl ?? EMPTY_FILL;
+}
+
+function builtInTableStyle(styleId: string, theme: Theme): TableStyle | undefined {
+ if (styleId !== MEDIUM_STYLE_2_ACCENT_1) return undefined;
+ const accent = theme.colors.get('accent1');
+ if (!accent) return undefined;
+ return {
+ wholeTbl: solidTint(accent, 0.2),
+ band1H: solidTint(accent, 0.4),
+ firstRow: { kind: 'solid', color: accent },
+ };
+}
+
+function solidTint(color: string, retainedFraction: number): PresentationFill {
+ const rgb = parseHex(color);
+ if (!rgb) return EMPTY_FILL;
+ const retained = Math.min(1, Math.max(0, retainedFraction));
+ const tinted = rgb.map(channel => {
+ const linear = srgbChannelToLinear(channel / 255);
+ return Math.round(linearChannelToSrgb(linear * retained + (1 - retained)) * 255);
+ });
+ return { kind: 'solid', color: `#${tinted.map(item => item.toString(16).padStart(2, '0')).join('')}`.toUpperCase() };
+}
+
+function srgbChannelToLinear(channel: number): number {
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+}
+
+function linearChannelToSrgb(channel: number): number {
+ return channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
+}
+
+function parseTableText(cell: XmlNode, theme: Theme): PresentationText | undefined {
+ const textBody = direct<XmlNode | undefined>(child(cell, 'txBody'));
+ return textBody ? parseText(textBody, theme) : undefined;
+}
+
+function parseChart(xml: XmlNode, base: Omit<PresentationChart, 'type' | 'chartType' | 'title' | 'series'>, theme: Theme): PresentationChart | undefined {
+ const plot = descendants(xml, 'plotArea')[0];
+ if (!plot) return undefined;
+ const typeNode = ['barChart', 'lineChart', 'pieChart'].map(kind => [kind, direct<XmlNode | undefined>(child(plot, kind))] as const).find(([, item]) => item);
+ if (!typeNode || !typeNode[1]) return undefined;
+ const [kind, node] = typeNode;
+ const chartType: PresentationChart['chartType'] =
+ kind === 'barChart'
+ ? attr(direct<XmlNode | undefined>(child(node, 'barDir')), 'val') === 'bar'
+ ? 'bar'
+ : 'column'
+ : kind === 'lineChart'
+ ? 'line'
+ : 'pie';
+ const series = direct<XmlNode[]>(child(node, 'ser', true)).map((seriesNode, index) => parseChartSeries(seriesNode, theme, index));
+ if (series.length === 0) return undefined;
+ const title = descendants(xml, 'title')[0];
+ return { type: 'chart', ...base, chartType, title: title ? textContent(title).trim() || undefined : undefined, series };
+}
+
+function parseChartSeries(node: XmlNode, theme: Theme, index: number): PresentationChart['series'][number] {
+ const name = textContent(descendants(node, 'tx')[0]).trim() || undefined;
+ const categories = descendants(descendants(node, 'cat')[0], 'pt').map(point => textContent(point).trim());
+ const values = descendants(descendants(node, 'val')[0], 'pt')
+ .map(point => Number(textContent(point)))
+ .filter(Number.isFinite);
+ const color = resolveColor(descendants(node, 'solidFill')[0], theme) ?? theme.colors.get(`accent${(index % 6) + 1}`);
+ return { name, categories, values, color };
+}
+
+function unsupported(node: XmlNode, transform: Transform, feature: string): PresentationNode {
+ const properties = direct<XmlNode | undefined>(child(node, 'spPr'));
+ const nameNode = descendants(node, 'cNvPr')[0];
+ return {
+ type: 'unsupported',
+ id: nodeId(nameNode, `unsupported-${feature}-${attr(nameNode, 'name') ?? 'object'}`),
+ name: attr(nameNode, 'name') ?? feature,
+ feature,
+ ...readBounds(properties ?? node, transform),
+ };
+}
+
+function placeholderKey(node: XmlNode | undefined): string | undefined {
+ if (!node) return undefined;
+ const type = attr(node, 'type') ?? 'body';
+ const index = attr(node, 'idx') ?? '0';
+ return `${type}:${index}`;
+}
+
+function nodeId(node: XmlNode | undefined, fallback: string): string {
+ return attr(node, 'id') ?? fallback;
+}
+
+function composeTransform(node: XmlNode, parent: Transform): Transform {
+ const properties = direct<XmlNode | undefined>(child(node, 'grpSpPr'));
+ const xfrm = direct<XmlNode | undefined>(child(properties, 'xfrm'));
+ const off = direct<XmlNode | undefined>(child(xfrm, 'off'));
+ const ext = direct<XmlNode | undefined>(child(xfrm, 'ext'));
+ const childOff = direct<XmlNode | undefined>(child(xfrm, 'chOff'));
+ const childExt = direct<XmlNode | undefined>(child(xfrm, 'chExt'));
+ const x = attrNumber(off, 'x') ?? 0;
+ const y = attrNumber(off, 'y') ?? 0;
+ const width = attrNumber(ext, 'cx') ?? 0;
+ const height = attrNumber(ext, 'cy') ?? 0;
+ const childX = attrNumber(childOff, 'x') ?? 0;
+ const childY = attrNumber(childOff, 'y') ?? 0;
+ const childWidth = (attrNumber(childExt, 'cx') ?? width) || 1;
+ const childHeight = (attrNumber(childExt, 'cy') ?? height) || 1;
+ const scaleX = parent.scaleX * (width / childWidth || 1);
+ const scaleY = parent.scaleY * (height / childHeight || 1);
+ return {
+ scaleX,
+ scaleY,
+ offsetX: parent.offsetX + parent.scaleX * (x - childX * (width / childWidth || 1)),
+ offsetY: parent.offsetY + parent.scaleY * (y - childY * (height / childHeight || 1)),
+ };
+}
+
+function readBounds(properties: XmlNode | undefined, transform: Transform): PresentationBounds {
+ const xfrm = direct<XmlNode | undefined>(child(properties, 'xfrm'));
+ const off = direct<XmlNode | undefined>(child(xfrm, 'off'));
+ const ext = direct<XmlNode | undefined>(child(xfrm, 'ext'));
+ const x = attrNumber(off, 'x') ?? 0;
+ const y = attrNumber(off, 'y') ?? 0;
+ const width = attrNumber(ext, 'cx') ?? 0;
+ const height = attrNumber(ext, 'cy') ?? 0;
+ return {
+ x: emu(transform.offsetX + x * transform.scaleX),
+ y: emu(transform.offsetY + y * transform.scaleY),
+ width: emu(width * transform.scaleX),
+ height: emu(height * transform.scaleY),
+ rotation: (attrNumber(xfrm, 'rot') ?? 0) / 60_000,
+ flipH: attr(xfrm, 'flipH') === '1' || attr(xfrm, 'flipH') === 'true',
+ flipV: attr(xfrm, 'flipV') === '1' || attr(xfrm, 'flipV') === 'true',
+ };
+}
+
+function parseBackground(xml: XmlNode, theme: Theme): PresentationFill {
+ const background = descendants(xml, 'bg')[0];
+ const properties = direct<XmlNode | undefined>(child(background, 'bgPr'));
+ return parseFill(properties ?? background, theme);
+}
+
+function parseFill(node: XmlNode | undefined, theme: Theme): PresentationFill {
+ if (!node) return EMPTY_FILL;
+ const solid = direct<XmlNode | undefined>(child(node, 'solidFill'));
+ if (solid) {
+ const color = resolveColor(solid, theme);
+ return color ? { kind: 'solid', color, transparency: resolveTransparency(solid) } : EMPTY_FILL;
+ }
+ const gradient = direct<XmlNode | undefined>(child(node, 'gradFill'));
+ if (gradient) {
+ const stops = descendants(gradient, 'gs').map(stop => {
+ const color = resolveColor(stop, theme) ?? '#000000';
+ return { offset: (attrNumber(stop, 'pos') ?? 0) / 100_000, color, transparency: resolveTransparency(stop) };
+ });
+ if (stops.length > 0) {
+ const linear = direct<XmlNode | undefined>(child(gradient, 'lin'));
+ return { kind: 'gradient', angle: (attrNumber(linear, 'ang') ?? 0) / 60_000, stops };
+ }
+ }
+ return EMPTY_FILL;
+}
+
+function parseStroke(node: XmlNode | undefined, theme: Theme): PresentationStroke | undefined {
+ const line = direct<XmlNode | undefined>(child(node, 'ln'));
+ if (!line || child(line, 'noFill')) return undefined;
+ const color = resolveColor(line, theme);
+ if (!color) return undefined;
+ const dash = attr(direct<XmlNode | undefined>(child(line, 'prstDash')), 'val');
+ return {
+ color,
+ width: Math.max(0.5, emu(attrNumber(line, 'w') ?? 12_700)),
+ dash: dash === 'dash' ? '6 4' : dash === 'dot' ? '1 3' : dash === 'lgDash' ? '10 5' : undefined,
+ };
+}
+
+function resolveColor(node: XmlNode | undefined, theme: Theme): PresentationColor | undefined {
+ if (!node) return undefined;
+ const colorNode = findColorNode(node);
+ if (!colorNode) return undefined;
+ let color: string | undefined;
+ switch (localName(colorNode.name)) {
+ case 'srgbClr':
+ color = attr(colorNode, 'val');
+ break;
+ case 'schemeClr':
+ color = theme.colors.get(attr(colorNode, 'val') ?? '');
+ break;
+ case 'sysClr':
+ color = attr(colorNode, 'lastClr') ?? attr(colorNode, 'val');
+ break;
+ case 'prstClr':
+ color = presetColor(attr(colorNode, 'val'));
+ break;
+ }
+ if (!color) return undefined;
+ const initialRgb = parseHex(color);
+ if (!initialRgb) return undefined;
+ let rgb: [number, number, number] = initialRgb;
+ colorNode.children.forEach(modifier => {
+ const value = (attrNumber(modifier, 'val') ?? 0) / 100_000;
+ if (localName(modifier.name) === 'tint') rgb = rgb.map(item => item + (255 - item) * value) as [number, number, number];
+ if (localName(modifier.name) === 'shade') rgb = rgb.map(item => item * value) as [number, number, number];
+ if (localName(modifier.name) === 'lumMod') rgb = rgb.map(item => item * value) as [number, number, number];
+ if (localName(modifier.name) === 'lumOff') rgb = rgb.map(item => item + 255 * value) as [number, number, number];
+ });
+ return `#${rgb
+ .map(item =>
+ Math.round(Math.min(255, Math.max(0, item)))
+ .toString(16)
+ .padStart(2, '0'),
+ )
+ .join('')}`.toUpperCase();
+}
+
+function resolveTransparency(node: XmlNode): number | undefined {
+ const color = findColorNode(node);
+ const alpha = color?.children.find(item => localName(item.name) === 'alpha');
+ return alpha ? 1 - (attrNumber(alpha, 'val') ?? 100_000) / 100_000 : undefined;
+}
+
+function findColorNode(node: XmlNode): XmlNode | undefined {
+ const isColor = (item: XmlNode) => ['srgbClr', 'schemeClr', 'sysClr', 'prstClr'].includes(localName(item.name));
+ return node.children.find(isColor) ?? direct<XmlNode | undefined>(child(node, 'solidFill'))?.children.find(isColor);
+}
+
+function parseText(node: XmlNode, theme: Theme): PresentationText {
+ const bodyProperties = direct<XmlNode | undefined>(child(node, 'bodyPr'));
+ const listStyle = direct<XmlNode | undefined>(child(node, 'lstStyle'));
+ const defaultParagraph = direct<XmlNode | undefined>(child(listStyle, 'defPPr')) ?? direct<XmlNode | undefined>(child(listStyle, 'lvl1pPr'));
+ const defaultRun = direct<XmlNode | undefined>(child(defaultParagraph, 'defRPr'));
+ const normalAutofit = direct<XmlNode | undefined>(child(bodyProperties, 'normAutofit'));
+ const shapeAutofit = direct<XmlNode | undefined>(child(bodyProperties, 'spAutoFit'));
+ const noAutofit = direct<XmlNode | undefined>(child(bodyProperties, 'noAutofit'));
+ const fontScale = parsePercentage(attr(normalAutofit, 'fontScale')) ?? 1;
+ const lineSpacingReduction = parsePercentage(attr(normalAutofit, 'lnSpcReduction')) ?? 0;
+ const paragraphs = direct<XmlNode[]>(child(node, 'p', true)).map(paragraph => parseParagraph(paragraph, listStyle, theme, fontScale, lineSpacingReduction));
+ const vertical = attr(bodyProperties, 'vert');
+ const anchor = attr(bodyProperties, 'anchor');
+ const fonts = parseFontFamilies([defaultRun], theme, '');
+ return {
+ paragraphs,
+ margin: {
+ left: emu(attrNumber(bodyProperties, 'lIns') ?? 91_440),
+ right: emu(attrNumber(bodyProperties, 'rIns') ?? 91_440),
+ top: emu(attrNumber(bodyProperties, 'tIns') ?? 45_720),
+ bottom: emu(attrNumber(bodyProperties, 'bIns') ?? 45_720),
+ },
+ vertical: vertical === 'vert' || vertical === 'vert270' || vertical === 'eaVert',
+ verticalReverse: vertical === 'vert270',
+ anchor: anchor === 'ctr' || anchor === 'b' ? (anchor === 'ctr' ? 'middle' : 'bottom') : 'top',
+ autoFit: normalAutofit ? 'shrink' : shapeAutofit ? 'resize' : noAutofit ? 'none' : undefined,
+ ...fonts,
+ fontSize: parseFontSize([defaultRun], fontScale),
+ color: resolveColor(defaultRun, theme),
+ };
+}
+
+function parseParagraph(node: XmlNode, listStyle: XmlNode | undefined, theme: Theme, fontScale: number, lineSpacingReduction: number): PresentationParagraph {
+ const properties = direct<XmlNode | undefined>(child(node, 'pPr'));
+ const level = attrNumber(properties, 'lvl') ?? 0;
+ const listProperties =
+ direct<XmlNode | undefined>(child(listStyle, `lvl${Math.min(9, Math.max(1, level + 1))}pPr`)) ?? direct<XmlNode | undefined>(child(listStyle, 'defPPr'));
+ const paragraphDefaultRun = direct<XmlNode | undefined>(child(properties, 'defRPr'));
+ const listDefaultRun = direct<XmlNode | undefined>(child(listProperties, 'defRPr'));
+ const runs: PresentationRun[] = [];
+ node.children.forEach(item => {
+ const kind = localName(item.name);
+ if (kind === 'br') {
+ runs.push({
+ text: '\n',
+ ...parseRunStyle([direct<XmlNode | undefined>(child(item, 'rPr')), paragraphDefaultRun, listDefaultRun], theme, '\n', fontScale),
+ });
+ return;
+ }
+ if (kind !== 'r' && kind !== 'fld') return;
+ const runProperties = direct<XmlNode | undefined>(child(item, 'rPr'));
+ const text = textContent(direct<XmlNode | undefined>(child(item, 't')));
+ runs.push({
+ text,
+ ...parseRunStyle([runProperties, paragraphDefaultRun, listDefaultRun], theme, text, fontScale),
+ });
+ });
+ const alignment = firstAttribute([properties, listProperties], 'algn');
+ const marginLeft = firstNumber([properties, listProperties], 'marL');
+ const indent = firstNumber([properties, listProperties], 'indent');
+ return {
+ runs,
+ align: alignment === 'ctr' ? 'center' : alignment === 'r' ? 'right' : alignment === 'just' ? 'justify' : 'left',
+ level,
+ bullet: parseBullet(properties, listProperties),
+ marginLeft: marginLeft === undefined ? undefined : emu(marginLeft),
+ indent: indent === undefined ? undefined : emu(indent),
+ spaceBefore: parseSpacing(firstChild([properties, listProperties], 'spcBef')),
+ spaceAfter: parseSpacing(firstChild([properties, listProperties], 'spcAft')),
+ lineSpacing: parseSpacing(firstChild([properties, listProperties], 'lnSpc'), lineSpacingReduction),
+ };
+}
+
+function parseBullet(primary: XmlNode | undefined, fallback: XmlNode | undefined): PresentationParagraph['bullet'] {
+ for (const properties of [primary, fallback]) {
+ if (!properties) continue;
+ if (child(properties, 'buNone')) return undefined;
+ const character = direct<XmlNode | undefined>(child(properties, 'buChar'));
+ if (character) return { kind: 'character', value: attr(character, 'char') ?? '•' };
+ if (child(properties, 'buAutoNum')) return { kind: 'number' };
+ }
+ return undefined;
+}
+
+function parseRunStyle(nodes: Array<XmlNode | undefined>, theme: Theme, text: string, fontScale: number): Omit<PresentationRun, 'text'> {
+ const fonts = parseFontFamilies(nodes, theme, text);
+ const spacing = firstNumber(nodes, 'spc');
+ const kerning = firstNumber(nodes, 'kern');
+ return {
+ ...fonts,
+ fontSize: parseFontSize(nodes, fontScale),
+ characterSpacing: spacing === undefined ? undefined : pointHundredths(spacing),
+ kerningThreshold: kerning === undefined ? undefined : pointHundredths(kerning),
+ color: firstResolvedColor(nodes, theme),
+ bold: firstBooleanAttribute(nodes, 'b'),
+ italic: firstBooleanAttribute(nodes, 'i'),
+ underline: firstUnderline(nodes),
+ baseline: firstNumber(nodes, 'baseline'),
+ hyperlink: firstChildAttribute(nodes, 'hlinkClick', 'r:id'),
+ };
+}
+
+function firstResolvedColor(nodes: Array<XmlNode | undefined>, theme: Theme): PresentationColor | undefined {
+ for (const node of nodes) {
+ const color = resolveColor(node, theme);
+ if (color !== undefined) return color;
+ }
+ return undefined;
+}
+
+function firstBooleanAttribute(nodes: Array<XmlNode | undefined>, name: string): boolean | undefined {
+ const value = firstAttribute(nodes, name);
+ return value === undefined ? undefined : value === '1' || value === 'true';
+}
+
+function firstUnderline(nodes: Array<XmlNode | undefined>): boolean | undefined {
+ const value = firstAttribute(nodes, 'u');
+ return value === undefined ? undefined : value !== 'none';
+}
+
+function parseSpacing(node: XmlNode | undefined, reduction = 0): PresentationSpacing | undefined {
+ if (!node) return undefined;
+ const points = direct<XmlNode | undefined>(child(node, 'spcPts'));
+ if (points) return { kind: 'absolute', value: pointHundredths(attrNumber(points, 'val') ?? 0) };
+ const percentage = direct<XmlNode | undefined>(child(node, 'spcPct'));
+ return percentage ? { kind: 'relative', value: ((attrNumber(percentage, 'val') ?? 0) / 100_000) * Math.max(0, 1 - reduction) } : undefined;
+}
+
+function parseFontSize(nodes: Array<XmlNode | undefined>, fontScale: number): number | undefined {
+ const value = firstNumber(nodes, 'sz');
+ return value === undefined ? undefined : pointHundredths(value) * fontScale;
+}
+
+function parseFontFamilies(
+ nodes: Array<XmlNode | undefined>,
+ theme: Theme,
+ text: string,
+): Pick<PresentationRun, 'fontFamily' | 'eastAsianFontFamily' | 'complexScriptFontFamily'> {
+ const language = firstAttribute(nodes, 'lang') ?? firstAttribute(nodes, 'altLang');
+ return {
+ fontFamily: resolveTypeface(firstChildAttribute(nodes, 'latin', 'typeface'), 'latin', theme, language, text),
+ eastAsianFontFamily: resolveTypeface(firstChildAttribute(nodes, 'ea', 'typeface'), 'eastAsian', theme, language, text),
+ complexScriptFontFamily: resolveTypeface(firstChildAttribute(nodes, 'cs', 'typeface'), 'complexScript', theme, language, text),
+ };
+}
+
+function resolveTypeface(
+ value: string | undefined,
+ script: 'latin' | 'eastAsian' | 'complexScript',
+ theme: Theme,
+ language: string | undefined,
+ text: string,
+): string | undefined {
+ const typeface = nonEmpty(value);
+ const token = typeface?.match(/^\+(mj|mn)-(lt|ea|cs)$/);
+ if (token) {
+ const font = token[1] === 'mj' ? theme.majorFont : theme.minorFont;
+ const tokenScript = token[2] === 'lt' ? 'latin' : token[2] === 'ea' ? 'eastAsian' : 'complexScript';
+ return themeTypeface(font, tokenScript, language, text);
+ }
+ return typeface ?? themeTypeface(theme.minorFont, script, language, text);
+}
+
+function themeTypeface(font: ThemeFont, script: 'latin' | 'eastAsian' | 'complexScript', language: string | undefined, text: string): string | undefined {
+ if (script === 'latin') return font.latin;
+ if (script === 'complexScript') return font.complexScript;
+ if (font.eastAsian) return font.eastAsian;
+ const supplementalScript = eastAsianThemeScript(language, text);
+ return supplementalScript ? font.supplemental.get(supplementalScript) : undefined;
+}
+
+function eastAsianThemeScript(language: string | undefined, text: string): string | undefined {
+ const normalized = language?.toLowerCase();
+ if (normalized?.startsWith('ja')) return 'Jpan';
+ if (normalized?.startsWith('ko')) return 'Hang';
+ if (normalized && /^zh-(tw|hk|mo)\b/.test(normalized)) return 'Hant';
+ if (normalized?.startsWith('zh')) return 'Hans';
+ if (/[\u3040-\u30ff]/u.test(text)) return 'Jpan';
+ if (/[\uac00-\ud7af]/u.test(text)) return 'Hang';
+ if (/[\u3100-\u312f\u31a0-\u31bf]/u.test(text)) return 'Hant';
+ if (/[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u.test(text)) return 'Hans';
+ return undefined;
+}
+
+function firstAttribute(nodes: Array<XmlNode | undefined>, name: string): string | undefined {
+ for (const node of nodes) {
+ const value = attr(node, name);
+ if (value !== undefined) return value;
+ }
+ return undefined;
+}
+
+function firstNumber(nodes: Array<XmlNode | undefined>, name: string): number | undefined {
+ for (const node of nodes) {
+ const value = attrNumber(node, name);
+ if (value !== undefined) return value;
+ }
+ return undefined;
+}
+
+function firstChild(nodes: Array<XmlNode | undefined>, name: string): XmlNode | undefined {
+ for (const node of nodes) {
+ const value = direct<XmlNode | undefined>(child(node, name));
+ if (value) return value;
+ }
+ return undefined;
+}
+
+function firstChildAttribute(nodes: Array<XmlNode | undefined>, childName: string, attributeName: string): string | undefined {
+ for (const node of nodes) {
+ const value = attr(direct<XmlNode | undefined>(child(node, childName)), attributeName);
+ if (value !== undefined) return value;
+ }
+ return undefined;
+}
+
+function parsePercentage(value: string | undefined): number | undefined {
+ if (!value) return undefined;
+ const normalized = value.trim();
+ const number = Number(normalized.endsWith('%') ? normalized.slice(0, -1) : normalized);
+ if (!Number.isFinite(number)) return undefined;
+ return normalized.endsWith('%') ? number / 100 : number / 100_000;
+}
+
+function pointHundredths(value: number): number {
+ return (value / 100) * CSS_PIXELS_PER_POINT;
+}
+
+function nonEmpty(value: string | undefined): string | undefined {
+ const normalized = value?.trim();
+ return normalized ? normalized : undefined;
+}
+
+function attrNumber(node: XmlNode | undefined, name: string): number | undefined {
+ const value = attr(node, name);
+ if (value === undefined || value === '') return undefined;
+ const number = Number(value);
+ return Number.isFinite(number) ? number : undefined;
+}
+
+function emu(value: number): number {
+ return value / EMUS_PER_PIXEL;
+}
+
+function textContent(node: XmlNode | undefined): string {
+ if (!node) return '';
+ return node.text + node.children.map(textContent).join('');
+}
+
+function parseHex(value: string): [number, number, number] | undefined {
+ const normalized = value.replace('#', '');
+ if (!/^[0-9a-f]{6}$/i.test(normalized)) return undefined;
+ return [Number.parseInt(normalized.slice(0, 2), 16), Number.parseInt(normalized.slice(2, 4), 16), Number.parseInt(normalized.slice(4, 6), 16)];
+}
+
+function presetColor(value: string | undefined): string | undefined {
+ const colors: Record<string, string> = {
+ black: '000000',
+ white: 'FFFFFF',
+ red: 'FF0000',
+ green: '008000',
+ blue: '0000FF',
+ yellow: 'FFFF00',
+ gray: '808080',
+ grey: '808080',
+ dkGray: '404040',
+ ltGray: 'C0C0C0',
+ orange: 'FFA500',
+ purple: '800080',
+ brown: 'A52A2A',
+ transparent: '000000',
+ };
+ return value ? colors[value] : undefined;
+}
+
+function mediaMimeType(path: string): string {
+ const extension = path.slice(path.lastIndexOf('.') + 1).toLowerCase();
+ return (
+ (
+ { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', bmp: 'image/bmp', webp: 'image/webp', svg: 'image/svg+xml' } as Record<
+ string,
+ string
+ >
+ )[extension] ?? 'application/octet-stream'
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreview.worker.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreview.worker.ts
new file mode 100644
index 0000000000..910365621b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreview.worker.ts
@@ -0,0 +1,21 @@
+import { parsePresentation } from './pptxPresentationParser';
+import { isOoxmlArchiveLimitError } from './ooxmlArchiveLimits';
+import type { PresentationWorkerRequest, PresentationWorkerResponse } from './pptxPreviewModel';
+
+const workerScope = self as unknown as {
+ onmessage: ((event: MessageEvent<PresentationWorkerRequest>) => void) | null;
+ postMessage: (message: PresentationWorkerResponse) => void;
+};
+
+workerScope.onmessage = event => {
+ if (event.data.type !== 'parse') return;
+ void parsePresentation(event.data.buffer)
+ .then(presentation => workerScope.postMessage({ type: 'ready', presentation }))
+ .catch(error =>
+ workerScope.postMessage({
+ type: 'error',
+ code: isOoxmlArchiveLimitError(error) ? 'resource-limit' : 'parse-error',
+ message: error instanceof Error ? error.message : 'Unable to parse the presentation',
+ }),
+ );
+};
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreviewModel.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreviewModel.ts
new file mode 100644
index 0000000000..c7e779b52a
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/pptxPreviewModel.ts
@@ -0,0 +1,137 @@
+import { PRESENTATION_ARCHIVE_LIMITS } from './ooxmlArchiveLimits';
+
+export const MAX_PRESENTATION_PREVIEW_BYTES = PRESENTATION_ARCHIVE_LIMITS.maxCompressedBytes;
+export const MAX_PRESENTATION_UNCOMPRESSED_BYTES = PRESENTATION_ARCHIVE_LIMITS.maxTotalUncompressedBytes;
+
+export type PresentationColor = string;
+
+export type PresentationFill =
+ | { kind: 'solid'; color: PresentationColor; transparency?: number }
+ | { kind: 'gradient'; angle: number; stops: Array<{ offset: number; color: PresentationColor; transparency?: number }> }
+ | { kind: 'none' };
+
+export type PresentationStroke = {
+ color: PresentationColor;
+ width: number;
+ dash?: string;
+};
+
+export type PresentationSpacing = { kind: 'absolute'; value: number } | { kind: 'relative'; value: number };
+
+export function presentationLineHeight(spacing: PresentationSpacing | undefined): string | number {
+ if (!spacing) return 'normal';
+ return spacing.kind === 'absolute' ? `${spacing.value}px` : spacing.value;
+}
+
+export type PresentationRun = {
+ text: string;
+ fontSize?: number;
+ fontFamily?: string;
+ eastAsianFontFamily?: string;
+ complexScriptFontFamily?: string;
+ characterSpacing?: number;
+ kerningThreshold?: number;
+ color?: PresentationColor;
+ bold?: boolean;
+ italic?: boolean;
+ underline?: boolean;
+ baseline?: number;
+ hyperlink?: string;
+};
+
+export type PresentationParagraph = {
+ runs: PresentationRun[];
+ align?: 'left' | 'center' | 'right' | 'justify';
+ level: number;
+ bullet?: { kind: 'character'; value: string } | { kind: 'number' };
+ marginLeft?: number;
+ indent?: number;
+ spaceBefore?: PresentationSpacing;
+ spaceAfter?: PresentationSpacing;
+ lineSpacing?: PresentationSpacing;
+};
+
+export type PresentationText = {
+ paragraphs: PresentationParagraph[];
+ margin: { left: number; right: number; top: number; bottom: number };
+ vertical?: boolean;
+ verticalReverse?: boolean;
+ anchor?: 'top' | 'middle' | 'bottom';
+ autoFit?: 'shrink' | 'resize' | 'none';
+ fontFamily?: string;
+ eastAsianFontFamily?: string;
+ complexScriptFontFamily?: string;
+ fontSize?: number;
+ color?: PresentationColor;
+};
+
+export type PresentationBounds = { x: number; y: number; width: number; height: number; rotation?: number; flipH?: boolean; flipV?: boolean };
+
+type PresentationNodeBase = PresentationBounds & {
+ id: string;
+ name: string;
+ placeholderKey?: string;
+};
+
+export type PresentationShape = PresentationNodeBase & {
+ type: 'shape';
+ geometry: string;
+ adjustments?: Record<string, number>;
+ fill: PresentationFill;
+ stroke?: PresentationStroke;
+ text?: PresentationText;
+};
+
+export type PresentationImage = PresentationNodeBase & {
+ type: 'image';
+ image: Blob;
+ alt: string;
+ crop?: { left: number; right: number; top: number; bottom: number };
+};
+
+export type PresentationTableCell = {
+ text?: PresentationText;
+ fill: PresentationFill;
+ stroke?: PresentationStroke;
+ colSpan?: number;
+ rowSpan?: number;
+ merged?: boolean;
+};
+
+export type PresentationTable = PresentationNodeBase & {
+ type: 'table';
+ columns: number[];
+ rows: Array<{ height: number; cells: PresentationTableCell[] }>;
+};
+
+export type PresentationChart = PresentationNodeBase & {
+ type: 'chart';
+ chartType: 'bar' | 'column' | 'line' | 'pie';
+ title?: string;
+ series: Array<{ name?: string; categories: string[]; values: number[]; color?: PresentationColor }>;
+};
+
+export type PresentationUnsupported = PresentationNodeBase & {
+ type: 'unsupported';
+ feature: string;
+};
+
+export type PresentationNode = PresentationShape | PresentationImage | PresentationTable | PresentationChart | PresentationUnsupported;
+
+export type PresentationSlide = {
+ id: string;
+ name: string;
+ background: PresentationFill;
+ nodes: PresentationNode[];
+ status?: 'incomplete' | 'invalid';
+};
+
+export type PresentationData = {
+ width: number;
+ height: number;
+ slides: PresentationSlide[];
+};
+
+export type PresentationWorkerRequest = { type: 'parse'; buffer: ArrayBuffer };
+export type PresentationWorkerResponse =
+ { type: 'ready'; presentation: PresentationData } | { type: 'error'; code: 'parse-error' | 'resource-limit'; message: string };
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreview.worker.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreview.worker.ts
new file mode 100644
index 0000000000..a8df6d8387
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreview.worker.ts
@@ -0,0 +1,23 @@
+import { parseSpreadsheetWorkbook } from './spreadsheetWorkbookParser';
+import { isOoxmlArchiveLimitError } from './ooxmlArchiveLimits';
+import type { SpreadsheetWorkerRequest, SpreadsheetWorkerResponse } from './spreadsheetPreviewModel';
+
+const workerScope = self as unknown as {
+ onmessage: ((event: MessageEvent<SpreadsheetWorkerRequest>) => void) | null;
+ postMessage: (message: SpreadsheetWorkerResponse) => void;
+};
+
+workerScope.onmessage = event => {
+ if (event.data.type !== 'parse') return;
+ void parseSpreadsheetWorkbook(event.data.buffer)
+ .then(workbook => {
+ workerScope.postMessage({ type: 'ready', workbook });
+ })
+ .catch(error => {
+ workerScope.postMessage({
+ type: 'error',
+ code: isOoxmlArchiveLimitError(error) ? 'resource-limit' : 'parse-error',
+ message: error instanceof Error ? error.message : 'Unable to parse the workbook',
+ });
+ });
+};
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreviewModel.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreviewModel.ts
new file mode 100644
index 0000000000..6053ad3ca2
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetPreviewModel.ts
@@ -0,0 +1,191 @@
+import { SPREADSHEET_ARCHIVE_LIMITS } from './ooxmlArchiveLimits';
+
+export const MAX_SPREADSHEET_PREVIEW_BYTES = SPREADSHEET_ARCHIVE_LIMITS.maxCompressedBytes;
+
+export type SpreadsheetCssValue = string | number;
+export type SpreadsheetCellStyle = Record<string, SpreadsheetCssValue>;
+
+export type SpreadsheetCellData = {
+ row: number;
+ column: number;
+ text: string;
+ formula?: string;
+ hyperlink?: string;
+ alignRight: boolean;
+ styleId: number;
+};
+
+export type SpreadsheetRowData = {
+ index: number;
+ styleId: number;
+ cells: SpreadsheetCellData[];
+};
+
+export type SpreadsheetAxisSize = {
+ index: number;
+ size: number;
+};
+
+export type SpreadsheetMergeRange = {
+ top: number;
+ left: number;
+ bottom: number;
+ right: number;
+};
+
+export type SpreadsheetCellComment = {
+ author?: string;
+ text: string;
+};
+
+export type SpreadsheetAutoFilter = SpreadsheetMergeRange;
+
+export type SpreadsheetDrawingAnchor = {
+ fromColumn: number;
+ fromRow: number;
+ fromColumnOffset: number;
+ fromRowOffset: number;
+ toColumn?: number;
+ toRow?: number;
+ toColumnOffset?: number;
+ toRowOffset?: number;
+ width?: number;
+ height?: number;
+};
+
+export type SpreadsheetChartSeries = {
+ name?: string;
+ categories: string[];
+ values: number[];
+ color?: string;
+};
+
+export type SpreadsheetChart = {
+ id: string;
+ anchor: SpreadsheetDrawingAnchor;
+ type: 'line' | 'column' | 'bar' | 'pie' | 'scatter';
+ title?: string;
+ categoryAxisTitle?: string;
+ valueAxisTitle?: string;
+ legendPosition?: 'bottom' | 'left' | 'right' | 'top' | 'none';
+ series: SpreadsheetChartSeries[];
+};
+
+export type SpreadsheetImage = {
+ id: string;
+ anchor: SpreadsheetDrawingAnchor;
+ alt: string;
+ source: string;
+};
+
+export type SpreadsheetSheetData = {
+ id: number;
+ name: string;
+ state: 'visible' | 'hidden' | 'veryHidden';
+ rowCount: number;
+ columnCount: number;
+ defaultRowHeight: number;
+ defaultColumnWidth: number;
+ rowSizes: SpreadsheetAxisSize[];
+ columnSizes: SpreadsheetAxisSize[];
+ rowStyleIds: Array<{ index: number; styleId: number }>;
+ columnStyleIds: Array<{ index: number; styleId: number }>;
+ rows: SpreadsheetRowData[];
+ merges: SpreadsheetMergeRange[];
+ showGridLines: boolean;
+ autoFilter?: SpreadsheetAutoFilter;
+ comments: Array<{ row: number; column: number; comment: SpreadsheetCellComment }>;
+ charts: SpreadsheetChart[];
+ images: SpreadsheetImage[];
+};
+
+export type SpreadsheetWorkbookData = {
+ activeSheetIndex: number;
+ sheets: SpreadsheetSheetData[];
+ styles: SpreadsheetCellStyle[];
+};
+
+export type SpreadsheetWorkerRequest = {
+ type: 'parse';
+ buffer: ArrayBuffer;
+};
+
+export type SpreadsheetWorkerResponse =
+ { type: 'ready'; workbook: SpreadsheetWorkbookData } | { type: 'error'; code: 'parse-error' | 'resource-limit'; message: string };
+
+export type SpreadsheetAxisMetrics = {
+ offsets: Float64Array;
+ totalSize: number;
+};
+
+export function columnLabel(column: number): string {
+ if (!Number.isInteger(column) || column < 1) throw new RangeError('Column index must be a positive integer');
+ let value = column;
+ let label = '';
+ while (value > 0) {
+ const remainder = (value - 1) % 26;
+ label = String.fromCharCode(65 + remainder) + label;
+ value = Math.floor((value - 1) / 26);
+ }
+ return label;
+}
+
+export function buildAxisMetrics(count: number, defaultSize: number, overrides: SpreadsheetAxisSize[]): SpreadsheetAxisMetrics {
+ if (!Number.isInteger(count) || count < 0) throw new RangeError('Axis count must be a non-negative integer');
+ if (!Number.isFinite(defaultSize) || defaultSize < 0) throw new RangeError('Default axis size must be non-negative');
+
+ const overrideSizes = new Map<number, number>();
+ overrides.forEach(({ index, size }) => {
+ if (!Number.isInteger(index) || index < 1 || index > count) throw new RangeError(`Axis override index ${index} is outside the axis`);
+ if (!Number.isFinite(size) || size < 0) throw new RangeError(`Axis override size for ${index} must be non-negative`);
+ overrideSizes.set(index, size);
+ });
+
+ const offsets = new Float64Array(count + 1);
+ for (let index = 1; index <= count; index += 1) {
+ offsets[index] = offsets[index - 1] + (overrideSizes.get(index) ?? defaultSize);
+ }
+ return { offsets, totalSize: offsets[count] ?? 0 };
+}
+
+export function axisIndexAtOffset(offsets: Float64Array, offset: number): number {
+ const count = offsets.length - 1;
+ if (count <= 0) return 0;
+ if (offset <= 0) {
+ let first = 1;
+ while (first < count && offsets[first] <= 0) first += 1;
+ return first;
+ }
+ if (offset >= offsets[count]) return count;
+
+ let low = 1;
+ let high = count;
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2);
+ if (offsets[middle] <= offset) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+}
+
+export function parseCellRange(range: string): SpreadsheetMergeRange {
+ const match = /^\$?([A-Z]+)\$?(\d+):\$?([A-Z]+)\$?(\d+)$/i.exec(range.trim());
+ if (!match) throw new Error(`Invalid spreadsheet range: ${range}`);
+ const [, leftLabel, topText, rightLabel, bottomText] = match;
+ const left = columnNumber(leftLabel);
+ const right = columnNumber(rightLabel);
+ const top = Number(topText);
+ const bottom = Number(bottomText);
+ if (top < 1 || bottom < top || right < left) throw new Error(`Invalid spreadsheet range: ${range}`);
+ return { top, left, bottom, right };
+}
+
+function columnNumber(label: string): number {
+ let value = 0;
+ for (const character of label.toUpperCase()) {
+ const code = character.charCodeAt(0);
+ if (code < 65 || code > 90) throw new Error(`Invalid spreadsheet column: ${label}`);
+ value = value * 26 + code - 64;
+ }
+ return value;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts
new file mode 100644
index 0000000000..40afe9308e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/ArtifactsPanel/spreadsheetWorkbookParser.ts
@@ -0,0 +1,1112 @@
+import ExcelJS, { type Border, type Cell, type Color, type Fill, type Font, type Style, type Workbook, type Worksheet } from 'exceljs';
+import JSZip from 'jszip';
+import { SaxesParser, type SaxesTagNS } from 'saxes';
+import SSF from 'ssf';
+import { SPREADSHEET_ARCHIVE_LIMITS, inspectOoxmlArchive } from './ooxmlArchiveLimits';
+import {
+ parseCellRange,
+ type SpreadsheetCellData,
+ type SpreadsheetCellStyle,
+ type SpreadsheetChart,
+ type SpreadsheetChartSeries,
+ type SpreadsheetDrawingAnchor,
+ type SpreadsheetImage,
+ type SpreadsheetSheetData,
+ type SpreadsheetWorkbookData,
+} from './spreadsheetPreviewModel';
+
+type ExtendedColor = Partial<Color> & {
+ indexed?: number;
+ tint?: number;
+};
+
+type RuntimeCellModel = {
+ address: string;
+};
+
+type RuntimeRowModel = {
+ number: number;
+ height?: number;
+ hidden?: boolean;
+ style?: Partial<Style>;
+ cells: RuntimeCellModel[];
+};
+
+type RuntimeColumnModel = {
+ min: number;
+ max: number;
+ width?: number;
+ hidden?: boolean;
+ style?: Partial<Style>;
+};
+
+type RuntimeWorksheetModel = {
+ rows?: RuntimeRowModel[];
+ cols?: RuntimeColumnModel[];
+ merges?: string[];
+};
+
+type RuntimeConditionalFormattingRule = {
+ type: 'cellIs' | 'containsText' | 'notContainsText' | 'beginsWith' | 'endsWith' | 'colorScale' | 'dataBar' | string;
+ operator?: string;
+ formulae?: string[];
+ text?: string;
+ style?: Partial<Style>;
+ color?: ExtendedColor;
+ colorScale?: { cfvo: Array<{ type: string; value?: number }>; color: ExtendedColor[] };
+};
+
+type RuntimeConditionalFormatting = {
+ ref: string;
+ rules: RuntimeConditionalFormattingRule[];
+};
+
+type RuntimeWorksheetView = {
+ showGridLines?: boolean;
+};
+
+type SheetArtifacts = {
+ comments: SpreadsheetSheetData['comments'];
+ charts: SpreadsheetChart[];
+ images: SpreadsheetImage[];
+};
+
+type WorkbookThemes = {
+ theme1?: string;
+};
+
+const DEFAULT_THEME_COLORS = ['FFFFFF', '000000', 'EEECE1', '1F497D', '4F81BD', 'C0504D', '9BBB59', '8064A2', '4BACC6', 'F79646', '0000FF', '800080'];
+
+const INDEXED_COLORS = [
+ '000000',
+ 'FFFFFF',
+ 'FF0000',
+ '00FF00',
+ '0000FF',
+ 'FFFF00',
+ 'FF00FF',
+ '00FFFF',
+ '000000',
+ 'FFFFFF',
+ 'FF0000',
+ '00FF00',
+ '0000FF',
+ 'FFFF00',
+ 'FF00FF',
+ '00FFFF',
+ '800000',
+ '008000',
+ '000080',
+ '808000',
+ '800080',
+ '008080',
+ 'C0C0C0',
+ '808080',
+ '9999FF',
+ '993366',
+ 'FFFFCC',
+ 'CCFFFF',
+ '660066',
+ 'FF8080',
+ '0066CC',
+ 'CCCCFF',
+ '000080',
+ 'FF00FF',
+ 'FFFF00',
+ '00FFFF',
+ '800080',
+ '800000',
+ '008080',
+ '0000FF',
+ '00CCFF',
+ 'CCFFFF',
+ 'CCFFCC',
+ 'FFFF99',
+ '99CCFF',
+ 'FF99CC',
+ 'CC99FF',
+ 'FFCC99',
+ '3366FF',
+ '33CCCC',
+ '99CC00',
+ 'FFCC00',
+ 'FF9900',
+ 'FF6600',
+ '666699',
+ '969696',
+ '003366',
+ '339966',
+ '003300',
+ '333300',
+ '993300',
+ '993366',
+ '333399',
+ '333333',
+];
+
+const THEME_COLOR_NAMES = ['lt1', 'dk1', 'lt2', 'dk2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink'];
+const DRAWING_ARCHIVE_ENTRY = /^xl\/drawings\/(?:_rels\/)?drawing\d+\.xml(?:\.rels)?$/i;
+const DRAWING_RELATIONSHIP = /\/relationships\/drawing$/;
+const COMMENTS_RELATIONSHIP = /\/relationships\/comments$/;
+const CHART_RELATIONSHIP = /\/relationships\/chart$/;
+const IMAGE_RELATIONSHIP = /\/relationships\/image$/;
+
+type Relationship = { id: string; target: string; type: string };
+type SheetArchiveReference = { name: string; path: string };
+type RelationshipCollection = Relationship[] & { get: (id: string) => Relationship | undefined };
+
+class StyleRegistry {
+ readonly styles: SpreadsheetCellStyle[] = [{}];
+ private readonly indexes = new Map<string, number>([['{}', 0]]);
+
+ add(style: SpreadsheetCellStyle): number {
+ const key = JSON.stringify(style);
+ const existing = this.indexes.get(key);
+ if (existing !== undefined) return existing;
+ const index = this.styles.length;
+ this.styles.push(style);
+ this.indexes.set(key, index);
+ return index;
+ }
+}
+
+export async function parseSpreadsheetWorkbook(buffer: ArrayBuffer): Promise<SpreadsheetWorkbookData> {
+ inspectOoxmlArchive(buffer, SPREADSHEET_ARCHIVE_LIMITS);
+ const archive = await JSZip.loadAsync(buffer);
+ const workbook = new ExcelJS.Workbook();
+ await workbook.xlsx.load(await prepareWorkbookBuffer(archive, buffer), { ignoreNodes: ['drawing'] });
+ if (workbook.worksheets.length === 0) throw new Error('The workbook contains no worksheets');
+
+ const palette = parseThemePalette(workbook);
+ const registry = new StyleRegistry();
+ const artifacts = await parseWorkbookArtifacts(archive, workbook);
+ const sheets = workbook.worksheets.map(worksheet => buildSheetData(workbook, worksheet, palette, registry, artifacts.get(worksheet.name)));
+ if (!sheets.some(sheet => sheet.state === 'visible')) throw new Error('The workbook contains no visible worksheets');
+ const requestedActiveIndex = workbook.views?.[0]?.activeTab ?? 0;
+
+ return {
+ activeSheetIndex: Math.min(Math.max(requestedActiveIndex, 0), sheets.length - 1),
+ sheets,
+ styles: registry.styles,
+ };
+}
+
+async function prepareWorkbookBuffer(archive: JSZip, buffer: ArrayBuffer): Promise<ArrayBuffer> {
+ const drawingEntries = Object.keys(archive.files).filter(name => DRAWING_ARCHIVE_ENTRY.test(name));
+ if (drawingEntries.length === 0) return buffer;
+
+ // JSZip's clone shares file records. Re-open the source so removing records
+ // for ExcelJS cannot remove the drawing payload we render ourselves.
+ const parserArchive = await JSZip.loadAsync(buffer);
+ drawingEntries.forEach(name => parserArchive.remove(name));
+ return parserArchive.generateAsync({ type: 'arraybuffer' });
+}
+
+function buildSheetData(
+ workbook: Workbook,
+ worksheet: Worksheet,
+ palette: string[],
+ registry: StyleRegistry,
+ artifacts?: SheetArtifacts,
+): SpreadsheetSheetData {
+ const model = worksheet.model as unknown as RuntimeWorksheetModel;
+ const rows = model.rows ?? [];
+ const columns = model.cols ?? [];
+ const merges = (model.merges ?? []).map(parseCellRange);
+ let rowCount = 0;
+ let columnCount = 0;
+
+ rows.forEach(row => {
+ rowCount = Math.max(rowCount, row.number);
+ row.cells.forEach(cell => {
+ const location = decodeCellAddress(cell.address);
+ columnCount = Math.max(columnCount, location.column);
+ });
+ });
+ merges.forEach(range => {
+ rowCount = Math.max(rowCount, range.bottom);
+ columnCount = Math.max(columnCount, range.right);
+ });
+ [...(artifacts?.charts ?? []), ...(artifacts?.images ?? [])].forEach(({ anchor }) => {
+ rowCount = Math.max(
+ rowCount,
+ anchor.toRow ?? anchor.fromRow + Math.ceil((anchor.height ?? 0) / pointsToPixels(worksheet.properties.defaultRowHeight ?? 15)),
+ );
+ columnCount = Math.max(
+ columnCount,
+ anchor.toColumn ?? anchor.fromColumn + Math.ceil((anchor.width ?? 0) / columnWidthToPixels(worksheet.properties.defaultColWidth ?? 8.43)),
+ );
+ });
+
+ const rowSizes: SpreadsheetSheetData['rowSizes'] = [];
+ const rowStyleIds: SpreadsheetSheetData['rowStyleIds'] = [];
+ const rowData: SpreadsheetSheetData['rows'] = [];
+
+ rows.forEach(rowModel => {
+ if (rowModel.hidden || rowModel.height !== undefined) {
+ rowSizes.push({
+ index: rowModel.number,
+ size: rowModel.hidden ? 0 : pointsToPixels(rowModel.height ?? worksheet.properties.defaultRowHeight ?? 15),
+ });
+ }
+ const rowStyleId = registry.add(styleToCss(rowModel.style ?? {}, palette));
+ if (rowStyleId !== 0) rowStyleIds.push({ index: rowModel.number, styleId: rowStyleId });
+
+ const cells: SpreadsheetCellData[] = [];
+ rowModel.cells.forEach(cellModel => {
+ const location = decodeCellAddress(cellModel.address);
+ const cell = worksheet.findCell(location.row, location.column);
+ if (!cell || cell.type === ExcelJS.ValueType.Merge) return;
+ const cellData = buildCellData(workbook, cell, palette, registry);
+ if (cellData.text || cellData.formula || cellData.hyperlink || cellData.styleId !== 0) cells.push(cellData);
+ });
+ if (cells.length > 0) rowData.push({ index: rowModel.number, styleId: rowStyleId, cells });
+ });
+
+ const columnSizes: SpreadsheetSheetData['columnSizes'] = [];
+ const columnStyleIds: SpreadsheetSheetData['columnStyleIds'] = [];
+ columns.forEach(columnModel => {
+ const styleId = registry.add(styleToCss(columnModel.style ?? {}, palette));
+ for (let index = columnModel.min; index <= columnModel.max; index += 1) {
+ columnCount = Math.max(columnCount, index);
+ if (columnModel.hidden || columnModel.width !== undefined) {
+ columnSizes.push({
+ index,
+ size: columnModel.hidden ? 0 : columnWidthToPixels(columnModel.width ?? worksheet.properties.defaultColWidth ?? 8.43),
+ });
+ }
+ if (styleId !== 0) columnStyleIds.push({ index, styleId });
+ }
+ });
+
+ applyConditionalFormats(worksheet, rowData, palette, registry);
+
+ const defaultView = worksheet.views?.[0] as RuntimeWorksheetView | undefined;
+ const showGridLines = defaultView?.showGridLines ?? worksheet.properties.showGridLines ?? true;
+
+ return {
+ id: worksheet.id,
+ name: worksheet.name,
+ state: worksheet.state,
+ rowCount,
+ columnCount,
+ defaultRowHeight: pointsToPixels(worksheet.properties.defaultRowHeight ?? 15),
+ defaultColumnWidth: columnWidthToPixels(worksheet.properties.defaultColWidth ?? 8.43),
+ rowSizes,
+ columnSizes,
+ rowStyleIds,
+ columnStyleIds,
+ rows: rowData,
+ merges,
+ showGridLines,
+ autoFilter: parseAutoFilter(worksheet.autoFilter),
+ comments: artifacts?.comments ?? [],
+ charts: artifacts?.charts ?? [],
+ images: artifacts?.images ?? [],
+ };
+}
+
+function applyConditionalFormats(worksheet: Worksheet, rows: SpreadsheetSheetData['rows'], palette: string[], registry: StyleRegistry): void {
+ const formats = (worksheet as Worksheet & { conditionalFormattings?: RuntimeConditionalFormatting[] }).conditionalFormattings ?? [];
+ if (formats.length === 0) return;
+ const cells = new Map(rows.flatMap(row => row.cells.map(cell => [cellKey(cell.row, cell.column), cell])));
+
+ formats.forEach(format => {
+ const ranges = format.ref.split(/\s+/).filter(Boolean).map(parseCellRange);
+ format.rules.forEach(rule => {
+ const rangeCells = ranges.flatMap(range => cellsInRange(range, cells, worksheet));
+ if (rule.type === 'colorScale') {
+ applyColorScale(rule, rangeCells, palette, registry);
+ return;
+ }
+ if (rule.type === 'dataBar') {
+ applyDataBar(rule, rangeCells, palette, registry);
+ return;
+ }
+ rangeCells.forEach(({ data, value }) => {
+ if (!matchesConditionalRule(rule, data.text, value, worksheet)) return;
+ const overlay = styleToCss(rule.style ?? {}, palette);
+ if (Object.keys(overlay).length > 0) data.styleId = registry.add({ ...(registry.styles[data.styleId] ?? {}), ...overlay });
+ });
+ });
+ });
+}
+
+function cellsInRange(
+ range: ReturnType<typeof parseCellRange>,
+ cells: Map<string, SpreadsheetCellData>,
+ worksheet: Worksheet,
+): Array<{ data: SpreadsheetCellData; value: number }> {
+ const result: Array<{ data: SpreadsheetCellData; value: number }> = [];
+ for (let row = range.top; row <= range.bottom; row += 1) {
+ for (let column = range.left; column <= range.right; column += 1) {
+ const data = cells.get(cellKey(row, column));
+ const raw = chartCellValue(worksheet.getCell(row, column).value);
+ const value = typeof raw === 'number' ? raw : Number(raw);
+ if (data && Number.isFinite(value)) result.push({ data, value });
+ else if (data && !Number.isFinite(value)) result.push({ data, value: Number.NaN });
+ }
+ }
+ return result;
+}
+
+function matchesConditionalRule(rule: RuntimeConditionalFormattingRule, text: string, value: number, worksheet: Worksheet): boolean {
+ const formula = rule.formulae?.[0];
+ const criterion = formula === undefined ? undefined : resolveConditionalFormula(formula, worksheet);
+ if (rule.type === 'cellIs' && criterion !== undefined && Number.isFinite(value)) {
+ const second = rule.formulae?.[1] === undefined ? undefined : resolveConditionalFormula(rule.formulae[1], worksheet);
+ if (rule.operator === 'between') return second !== undefined && value >= Number(criterion) && value <= Number(second);
+ if (rule.operator === 'notBetween') return second !== undefined && (value < Number(criterion) || value > Number(second));
+ if (rule.operator === 'equal') return value === Number(criterion);
+ if (rule.operator === 'notEqual') return value !== Number(criterion);
+ if (rule.operator === 'greaterThan') return value > Number(criterion);
+ if (rule.operator === 'greaterThanOrEqual') return value >= Number(criterion);
+ if (rule.operator === 'lessThan') return value < Number(criterion);
+ if (rule.operator === 'lessThanOrEqual') return value <= Number(criterion);
+ }
+ const needle = String(rule.text ?? criterion ?? '');
+ if (rule.type === 'containsText') return needle.length > 0 && text.includes(needle);
+ if (rule.type === 'notContainsText') return needle.length > 0 && !text.includes(needle);
+ if (rule.type === 'beginsWith') return needle.length > 0 && text.startsWith(needle);
+ if (rule.type === 'endsWith') return needle.length > 0 && text.endsWith(needle);
+ return false;
+}
+
+function resolveConditionalFormula(formula: string, worksheet: Worksheet): string | number | undefined {
+ const normalized = formula.trim().replace(/^=/, '');
+ if (/^-?(?:\d+\.?\d*|\.\d+)$/.test(normalized)) return Number(normalized);
+ const reference = /^\$?([A-Z]+)\$?(\d+)$/i.exec(normalized);
+ if (reference) return chartCellValue(worksheet.getCell(`${reference[1]}${reference[2]}`).value);
+ return /^"(?:[^"]|"")*"$/.test(normalized) ? normalized.slice(1, -1).replace(/""/g, '"') : undefined;
+}
+
+function applyColorScale(
+ rule: RuntimeConditionalFormattingRule,
+ cells: Array<{ data: SpreadsheetCellData; value: number }>,
+ palette: string[],
+ registry: StyleRegistry,
+): void {
+ const finite = cells.filter(item => Number.isFinite(item.value));
+ const colors = rule.colorScale?.color.map(color => resolveColor(color, palette)).filter((color): color is string => Boolean(color)) ?? [];
+ if (finite.length === 0 || colors.length < 2) return;
+ const min = Math.min(...finite.map(item => item.value));
+ const max = Math.max(...finite.map(item => item.value));
+ finite.forEach(({ data, value }) => {
+ const ratio = max === min ? 0.5 : (value - min) / (max - min);
+ const color = interpolateColor(colors, ratio);
+ data.styleId = registry.add({ ...(registry.styles[data.styleId] ?? {}), backgroundColor: color });
+ });
+}
+
+function applyDataBar(
+ rule: RuntimeConditionalFormattingRule,
+ cells: Array<{ data: SpreadsheetCellData; value: number }>,
+ palette: string[],
+ registry: StyleRegistry,
+): void {
+ const finite = cells.filter(item => Number.isFinite(item.value));
+ if (finite.length === 0) return;
+ const color = resolveColor(rule.color, palette) ?? '#638EC6';
+ const min = Math.min(0, ...finite.map(item => item.value));
+ const max = Math.max(...finite.map(item => item.value));
+ const span = Math.max(1, max - min);
+ finite.forEach(({ data, value }) => {
+ const percentage = Math.max(0, Math.min(100, ((value - min) / span) * 100));
+ data.styleId = registry.add({
+ ...(registry.styles[data.styleId] ?? {}),
+ backgroundImage: `linear-gradient(to right, ${color} 0 ${percentage}%, transparent ${percentage}% 100%)`,
+ });
+ });
+}
+
+function interpolateColor(colors: string[], ratio: number): string {
+ const position = Math.max(0, Math.min(1, ratio)) * (colors.length - 1);
+ const lower = Math.floor(position);
+ const upper = Math.min(colors.length - 1, lower + 1);
+ const fraction = position - lower;
+ const start = hexToRgb(colors[lower].replace('#', ''));
+ const end = hexToRgb(colors[upper].replace('#', ''));
+ return `rgb(${start.map((value, index) => Math.round(value + (end[index] - value) * fraction)).join(', ')})`;
+}
+
+function buildCellData(workbook: Workbook, cell: Cell, palette: string[], registry: StyleRegistry): SpreadsheetCellData {
+ const value = cell.value;
+ let formula: string | undefined;
+ let hyperlink: string | undefined;
+ let displayValue: unknown = value;
+
+ if (isFormulaValue(value)) {
+ formula = 'formula' in value ? value.formula : cell.formula;
+ displayValue = value.result === undefined ? `=${formula}` : value.result;
+ } else if (isHyperlinkValue(value)) {
+ displayValue = value.text;
+ hyperlink = safeHyperlink(value.hyperlink);
+ } else if (isRichTextValue(value)) {
+ displayValue = value.richText.map(part => part.text).join('');
+ } else if (isCellError(value)) {
+ displayValue = value.error;
+ }
+
+ return {
+ row: Number(cell.row),
+ column: Number(cell.col),
+ text: formatCellValue(displayValue, cell.numFmt, workbook.properties.date1904),
+ formula,
+ hyperlink,
+ alignRight: typeof displayValue === 'number' || displayValue instanceof Date,
+ styleId: registry.add(styleToCss(cell.style, palette)),
+ };
+}
+
+function formatCellValue(value: unknown, numberFormat: string | undefined, date1904: boolean): string {
+ if (value === null || value === undefined) return '';
+ if (value instanceof Date) return SSF.format(numberFormat || 'm/d/yy', value, { date1904 });
+ if (typeof value === 'number') return SSF.format(numberFormat || 'General', value, { date1904 });
+ if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';
+ return String(value);
+}
+
+function styleToCss(style: Partial<Style>, palette: string[]): SpreadsheetCellStyle {
+ const css: SpreadsheetCellStyle = {};
+ applyFont(css, style.font, palette);
+ applyFill(css, style.fill, palette);
+ applyAlignment(css, style.alignment);
+ applyBorders(css, style.border, palette);
+ return css;
+}
+
+function applyFont(css: SpreadsheetCellStyle, font: Partial<Font> | undefined, palette: string[]): void {
+ if (!font) return;
+ if (font.name) css.fontFamily = font.name;
+ if (font.size) {
+ css.fontSize = `${pointsToPixels(font.size)}px`;
+ // Tailwind's text-size utility also sets a fixed 16px line-height. That
+ // line-height is smaller than many workbook title fonts and clips their
+ // descenders inside the row's exact Excel height.
+ css.lineHeight = 'normal';
+ }
+ if (font.bold) css.fontWeight = 700;
+ if (font.italic) css.fontStyle = 'italic';
+ if (font.color) {
+ const color = resolveColor(font.color, palette);
+ if (color) css.color = color;
+ }
+
+ const decorations: string[] = [];
+ if (font.underline && font.underline !== 'none') decorations.push('underline');
+ if (font.strike) decorations.push('line-through');
+ if (decorations.length > 0) css.textDecorationLine = decorations.join(' ');
+ if (font.underline === 'double' || font.underline === 'doubleAccounting') css.textDecorationStyle = 'double';
+ if (font.vertAlign === 'superscript') css.verticalAlign = 'super';
+ if (font.vertAlign === 'subscript') css.verticalAlign = 'sub';
+}
+
+function applyFill(css: SpreadsheetCellStyle, fill: Fill | undefined, palette: string[]): void {
+ if (!fill) return;
+ if (fill.type === 'pattern') {
+ if (fill.pattern === 'none') return;
+ const foreground = resolveColor(fill.fgColor, palette);
+ const background = resolveColor(fill.bgColor, palette);
+ if (fill.pattern === 'solid') {
+ if (foreground) css.backgroundColor = foreground;
+ return;
+ }
+ if (background) css.backgroundColor = background;
+ if (foreground) css.backgroundImage = `repeating-linear-gradient(45deg, ${foreground} 0 1px, transparent 1px 4px)`;
+ return;
+ }
+
+ if (fill.type === 'gradient') {
+ const stops = fill.stops
+ .map(stop => {
+ const color = resolveColor(stop.color, palette);
+ return color ? `${color} ${Math.round(stop.position * 10000) / 100}%` : null;
+ })
+ .filter((stop): stop is string => Boolean(stop));
+ if (stops.length === 0) return;
+ if (fill.gradient === 'angle') {
+ css.backgroundImage = `linear-gradient(${normalizeDegrees(fill.degree + 90)}deg, ${stops.join(', ')})`;
+ } else {
+ css.backgroundImage = `radial-gradient(circle at ${fill.center.left * 100}% ${fill.center.top * 100}%, ${stops.join(', ')})`;
+ }
+ }
+}
+
+function applyAlignment(css: SpreadsheetCellStyle, alignment: Partial<Style['alignment']> | undefined): void {
+ if (!alignment) return;
+ if (alignment.horizontal) {
+ css.justifyContent =
+ alignment.horizontal === 'center' || alignment.horizontal === 'centerContinuous'
+ ? 'center'
+ : alignment.horizontal === 'right'
+ ? 'flex-end'
+ : alignment.horizontal === 'distributed'
+ ? 'space-between'
+ : 'flex-start';
+ if (alignment.horizontal === 'justify') css.textAlign = 'justify';
+ }
+ if (alignment.vertical) {
+ css.alignItems = alignment.vertical === 'top' ? 'flex-start' : alignment.vertical === 'middle' ? 'center' : 'flex-end';
+ }
+ if (alignment.wrapText) {
+ css.whiteSpace = 'normal';
+ css.overflowWrap = 'anywhere';
+ }
+ if (alignment.indent) css.paddingLeft = `${8 + alignment.indent * 9}px`;
+ if (alignment.readingOrder === 'rtl') css.direction = 'rtl';
+}
+
+function applyBorders(css: SpreadsheetCellStyle, borders: Partial<Style['border']> | undefined, palette: string[]): void {
+ if (!borders) return;
+ applyBorder(css, 'Top', borders.top, palette);
+ applyBorder(css, 'Right', borders.right, palette);
+ applyBorder(css, 'Bottom', borders.bottom, palette);
+ applyBorder(css, 'Left', borders.left, palette);
+}
+
+function applyBorder(css: SpreadsheetCellStyle, side: 'Top' | 'Right' | 'Bottom' | 'Left', border: Partial<Border> | undefined, palette: string[]): void {
+ if (!border?.style) return;
+ const borderStyle =
+ border.style === 'dotted' || border.style === 'hair' ? 'dotted' : border.style.includes('dash') ? 'dashed' : border.style === 'double' ? 'double' : 'solid';
+ const borderWidth =
+ border.style === 'hair' || border.style === 'thin' || border.style === 'dotted' || border.style === 'dashed' ? 1 : border.style === 'thick' ? 3 : 2;
+ const color = resolveColor(border.color, palette) ?? '#000000';
+ css[`border${side}`] = `${borderWidth}px ${borderStyle} ${color}`;
+}
+
+function resolveColor(color: ExtendedColor | undefined, palette: string[]): string | undefined {
+ if (!color) return undefined;
+ let hex: string | undefined;
+ let alpha = 'FF';
+
+ if (color.argb && /^[0-9a-f]{8}$/i.test(color.argb)) {
+ alpha = color.argb.slice(0, 2);
+ hex = color.argb.slice(2);
+ } else if (color.argb && /^[0-9a-f]{6}$/i.test(color.argb)) {
+ hex = color.argb;
+ } else if (color.theme !== undefined) {
+ hex = palette[color.theme];
+ } else if (color.indexed !== undefined) {
+ hex = INDEXED_COLORS[color.indexed];
+ }
+ if (!hex) return undefined;
+ const tinted = applyTint(hex, color.tint ?? 0);
+ // SpreadsheetML stores RGB colours as 00RRGGBB as well as FFRRGGBB. Cell
+ // formatting has no alpha channel, so the leading byte is not transparency.
+ const opacity = alpha === '00' ? 1 : Number.parseInt(alpha, 16) / 255;
+ if (opacity >= 1) return `#${tinted}`;
+ const [red, green, blue] = hexToRgb(tinted);
+ return `rgba(${red}, ${green}, ${blue}, ${Math.round(opacity * 1000) / 1000})`;
+}
+
+async function parseWorkbookArtifacts(archive: JSZip, workbook?: Workbook): Promise<Map<string, SheetArtifacts>> {
+ const sheets = await resolveWorkbookSheets(archive);
+ const result = new Map<string, SheetArtifacts>();
+ await Promise.all(
+ sheets.map(async sheet => {
+ const xml = await readArchiveText(archive, sheet.path);
+ if (!xml) return;
+ const relationships = await readRelationships(archive, sheet.path);
+ const reference = parseSheetReferences(xml);
+ const referencedComments = relationships.get(reference.commentsRelationshipId ?? '');
+ const referencedDrawing = relationships.get(reference.drawingRelationshipId ?? '');
+ const commentsRelationship =
+ referencedComments && COMMENTS_RELATIONSHIP.test(referencedComments.type)
+ ? referencedComments
+ : relationships.find(value => COMMENTS_RELATIONSHIP.test(value.type));
+ const drawingRelationship =
+ referencedDrawing && DRAWING_RELATIONSHIP.test(referencedDrawing.type)
+ ? referencedDrawing
+ : relationships.find(value => DRAWING_RELATIONSHIP.test(value.type));
+ const comments = commentsRelationship ? await parseComments(archive, commentsRelationship.target) : [];
+ const drawing = drawingRelationship ? await parseDrawing(archive, drawingRelationship.target, workbook) : { charts: [], images: [] };
+ result.set(sheet.name, { comments, ...drawing });
+ }),
+ );
+ return result;
+}
+
+async function resolveWorkbookSheets(archive: JSZip): Promise<SheetArchiveReference[]> {
+ const workbookXml = await readArchiveText(archive, 'xl/workbook.xml');
+ if (!workbookXml) return [];
+ const relationships = await readRelationships(archive, 'xl/workbook.xml');
+ const sheets: Array<{ name: string; relationshipId: string }> = [];
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ if (tag.local !== 'sheet') return;
+ const name = xmlAttribute(tag, 'name');
+ const relationshipId = xmlAttribute(tag, 'id');
+ if (name && relationshipId) sheets.push({ name, relationshipId });
+ });
+ parser.write(workbookXml).close();
+ return sheets.flatMap(sheet => {
+ const relationship = relationships.get(sheet.relationshipId);
+ return relationship ? [{ name: sheet.name, path: relationship.target }] : [];
+ });
+}
+
+async function readRelationships(archive: JSZip, originPath: string): Promise<RelationshipCollection> {
+ const path = relationshipPath(originPath);
+ const xml = await readArchiveText(archive, path);
+ const values: Relationship[] = [];
+ if (xml) {
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ if (tag.local !== 'Relationship') return;
+ const id = xmlAttribute(tag, 'Id');
+ const target = xmlAttribute(tag, 'Target');
+ const type = xmlAttribute(tag, 'Type');
+ if (id && target && type) values.push({ id, target: resolveArchivePath(originPath, target), type });
+ });
+ parser.write(xml).close();
+ }
+ const indexed = values as RelationshipCollection;
+ const byId = new Map(values.map(value => [value.id, value]));
+ indexed.get = id => byId.get(id);
+ return indexed;
+}
+
+function parseSheetReferences(xml: string): { drawingRelationshipId?: string; commentsRelationshipId?: string } {
+ const result: { drawingRelationshipId?: string; commentsRelationshipId?: string } = {};
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ if (tag.local === 'drawing') result.drawingRelationshipId = xmlAttribute(tag, 'id');
+ if (tag.local === 'legacyDrawing') result.commentsRelationshipId = xmlAttribute(tag, 'id');
+ });
+ parser.write(xml).close();
+ return result;
+}
+
+async function parseComments(archive: JSZip, path: string): Promise<SpreadsheetSheetData['comments']> {
+ const xml = await readArchiveText(archive, path);
+ if (!xml) return [];
+ const authors: string[] = [];
+ const comments: SpreadsheetSheetData['comments'] = [];
+ let stack: string[] = [];
+ let activeAuthor = -1;
+ let activeReference: { row: number; column: number } | undefined;
+ let text = '';
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ stack.push(tag.local);
+ if (tag.local === 'comment') {
+ const reference = xmlAttribute(tag, 'ref');
+ const authorId = Number(xmlAttribute(tag, 'authorId'));
+ if (reference) activeReference = decodeCellAddress(reference);
+ activeAuthor = Number.isInteger(authorId) ? authorId : -1;
+ text = '';
+ }
+ });
+ parser.on('text', value => {
+ if (stack.at(-1) === 'author') authors.push(value);
+ if (activeReference && stack.at(-1) === 't') text += value;
+ });
+ parser.on('closetag', tag => {
+ if (tag.local === 'comment' && activeReference) {
+ comments.push({ ...activeReference, comment: { author: authors[activeAuthor], text } });
+ activeReference = undefined;
+ activeAuthor = -1;
+ }
+ stack.pop();
+ });
+ parser.write(xml).close();
+ return comments;
+}
+
+async function parseDrawing(archive: JSZip, path: string, workbook?: Workbook): Promise<Pick<SheetArtifacts, 'charts' | 'images'>> {
+ const xml = await readArchiveText(archive, path);
+ if (!xml) return { charts: [], images: [] };
+ const relationships = await readRelationships(archive, path);
+ const anchors = parseDrawingAnchors(xml);
+ const charts: SpreadsheetChart[] = [];
+ const images: SpreadsheetImage[] = [];
+ await Promise.all(
+ anchors.map(async (anchor, index) => {
+ if (anchor.chartRelationshipId) {
+ const relationship = relationships.get(anchor.chartRelationshipId);
+ if (relationship && CHART_RELATIONSHIP.test(relationship.type)) {
+ const chart = await parseChart(archive, relationship.target, workbook);
+ if (chart) charts.push({ ...chart, id: `${path}:chart:${index}`, anchor: anchor.anchor });
+ }
+ }
+ if (anchor.imageRelationshipId) {
+ const relationship = relationships.get(anchor.imageRelationshipId);
+ if (relationship && IMAGE_RELATIONSHIP.test(relationship.type)) {
+ const source = await archive.file(relationship.target)?.async('base64');
+ if (source)
+ images.push({
+ id: `${path}:image:${index}`,
+ anchor: anchor.anchor,
+ alt: anchor.name ?? '',
+ source: `data:${mediaType(relationship.target)};base64,${source}`,
+ });
+ }
+ }
+ }),
+ );
+ return { charts, images };
+}
+
+type DrawingAnchorReference = {
+ anchor: SpreadsheetDrawingAnchor;
+ chartRelationshipId?: string;
+ imageRelationshipId?: string;
+ name?: string;
+};
+
+function parseDrawingAnchors(xml: string): DrawingAnchorReference[] {
+ const anchors: DrawingAnchorReference[] = [];
+ const stack: string[] = [];
+ let active: DrawingAnchorReference | undefined;
+ let marker: 'from' | 'to' | undefined;
+ let text = '';
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ stack.push(tag.local);
+ if (tag.local === 'oneCellAnchor' || tag.local === 'twoCellAnchor' || tag.local === 'absoluteAnchor') {
+ active = { anchor: { fromColumn: 1, fromRow: 1, fromColumnOffset: 0, fromRowOffset: 0 } };
+ }
+ if (!active) return;
+ if (tag.local === 'from' || tag.local === 'to') marker = tag.local;
+ if (tag.local === 'ext' && stack.at(-2)?.endsWith('Anchor')) {
+ active.anchor.width = emuToPixels(Number(xmlAttribute(tag, 'cx')));
+ active.anchor.height = emuToPixels(Number(xmlAttribute(tag, 'cy')));
+ }
+ if (tag.local === 'chart') active.chartRelationshipId = xmlAttribute(tag, 'id');
+ if (tag.local === 'blip') active.imageRelationshipId = xmlAttribute(tag, 'embed');
+ if (tag.local === 'cNvPr') active.name = xmlAttribute(tag, 'descr') ?? xmlAttribute(tag, 'name');
+ if (tag.local === 'col' || tag.local === 'row' || tag.local === 'colOff' || tag.local === 'rowOff') text = '';
+ });
+ parser.on('text', value => {
+ if (active && marker && ['col', 'row', 'colOff', 'rowOff'].includes(stack.at(-1) ?? '')) text += value;
+ });
+ parser.on('closetag', tag => {
+ if (active && marker && ['col', 'row', 'colOff', 'rowOff'].includes(tag.local)) {
+ const value = Number(text);
+ if (Number.isFinite(value)) setAnchorMarker(active.anchor, marker, tag.local, value);
+ }
+ if (tag.local === 'from' || tag.local === 'to') marker = undefined;
+ if ((tag.local === 'oneCellAnchor' || tag.local === 'twoCellAnchor' || tag.local === 'absoluteAnchor') && active) {
+ anchors.push(active);
+ active = undefined;
+ }
+ stack.pop();
+ });
+ parser.write(xml).close();
+ return anchors;
+}
+
+function setAnchorMarker(anchor: SpreadsheetDrawingAnchor, marker: 'from' | 'to', kind: string, value: number): void {
+ if (marker === 'from') {
+ if (kind === 'col') anchor.fromColumn = value + 1;
+ if (kind === 'row') anchor.fromRow = value + 1;
+ if (kind === 'colOff') anchor.fromColumnOffset = emuToPixels(value);
+ if (kind === 'rowOff') anchor.fromRowOffset = emuToPixels(value);
+ return;
+ }
+ if (kind === 'col') anchor.toColumn = value + 1;
+ if (kind === 'row') anchor.toRow = value + 1;
+ if (kind === 'colOff') anchor.toColumnOffset = emuToPixels(value);
+ if (kind === 'rowOff') anchor.toRowOffset = emuToPixels(value);
+}
+
+type ParsedChartSeries = SpreadsheetChartSeries & {
+ nameReference?: string;
+ categoryReference?: string;
+ valueReference?: string;
+};
+
+async function parseChart(archive: JSZip, path: string, workbook?: Workbook): Promise<Omit<SpreadsheetChart, 'id' | 'anchor'> | undefined> {
+ const xml = await readArchiveText(archive, path);
+ if (!xml) return undefined;
+ const stack: string[] = [];
+ const series: ParsedChartSeries[] = [];
+ let activeSeries: ParsedChartSeries | undefined;
+ let chartType: SpreadsheetChart['type'] = 'line';
+ let title = '';
+ let categoryAxisTitle = '';
+ let valueAxisTitle = '';
+ let legendPosition: SpreadsheetChart['legendPosition'] = 'right';
+ let pointIndex = 0;
+ let text = '';
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ stack.push(tag.local);
+ if (tag.local === 'lineChart') chartType = 'line';
+ if (tag.local === 'scatterChart') chartType = 'scatter';
+ if (tag.local === 'pieChart' || tag.local === 'doughnutChart') chartType = 'pie';
+ if (tag.local === 'barChart') chartType = xmlAttribute(tag, 'barDir') === 'bar' ? 'bar' : 'column';
+ if (tag.local === 'barDir') chartType = xmlAttribute(tag, 'val') === 'bar' ? 'bar' : 'column';
+ if (tag.local === 'ser') {
+ activeSeries = { categories: [], values: [] };
+ series.push(activeSeries);
+ }
+ if (tag.local === 'pt') pointIndex = Number(xmlAttribute(tag, 'idx')) || 0;
+ if (tag.local === 'legendPos') {
+ const value = xmlAttribute(tag, 'val');
+ legendPosition = value === 'b' ? 'bottom' : value === 't' ? 'top' : value === 'l' ? 'left' : value === 'r' ? 'right' : 'none';
+ }
+ if (tag.local === 'srgbClr' && activeSeries && stack.includes('spPr')) {
+ const value = xmlAttribute(tag, 'val');
+ if (value && /^[0-9a-f]{6}$/i.test(value)) activeSeries.color = `#${applyTint(value, 0)}`;
+ }
+ if (tag.local === 't' || tag.local === 'v' || tag.local === 'f') text = '';
+ });
+ parser.on('text', value => {
+ if (stack.at(-1) === 't' || stack.at(-1) === 'v' || stack.at(-1) === 'f') text += value;
+ });
+ parser.on('closetag', tag => {
+ if (!activeSeries && tag.local !== 't' && tag.local !== 'v') {
+ stack.pop();
+ return;
+ }
+ if (tag.local === 't' || tag.local === 'v') {
+ const value = text.trim();
+ if (value) {
+ if (stack.includes('title')) {
+ if (stack.includes('catAx')) categoryAxisTitle += value;
+ else if (stack.includes('valAx')) valueAxisTitle += value;
+ else title += value;
+ } else if (activeSeries && stack.includes('tx')) {
+ activeSeries.name = value;
+ } else if (activeSeries && (stack.includes('cat') || stack.includes('xVal'))) {
+ activeSeries.categories[pointIndex] = value;
+ } else if (activeSeries && (stack.includes('val') || stack.includes('yVal'))) {
+ const numeric = Number(value);
+ if (Number.isFinite(numeric)) activeSeries.values[pointIndex] = numeric;
+ }
+ }
+ }
+ if (tag.local === 'f' && activeSeries) {
+ const reference = text.trim();
+ if (reference) {
+ if (stack.includes('tx')) activeSeries.nameReference = reference;
+ else if (stack.includes('cat') || stack.includes('xVal')) activeSeries.categoryReference = reference;
+ else if (stack.includes('val') || stack.includes('yVal')) activeSeries.valueReference = reference;
+ }
+ }
+ if (tag.local === 'ser') activeSeries = undefined;
+ stack.pop();
+ });
+ parser.write(xml).close();
+ if (workbook) {
+ series.forEach(item => hydrateChartSeries(item, workbook));
+ }
+ return {
+ type: chartType,
+ title: title || undefined,
+ categoryAxisTitle: categoryAxisTitle || undefined,
+ valueAxisTitle: valueAxisTitle || undefined,
+ legendPosition,
+ series: series.map(({ nameReference: _nameReference, categoryReference: _categoryReference, valueReference: _valueReference, ...item }) => item),
+ };
+}
+
+function hydrateChartSeries(series: ParsedChartSeries, workbook: Workbook): void {
+ if (!series.name && series.nameReference) series.name = resolveChartRange(series.nameReference, workbook).map(String).join('');
+ if (series.categories.length === 0 && series.categoryReference) series.categories = resolveChartRange(series.categoryReference, workbook).map(String);
+ if (series.values.length === 0 && series.valueReference) {
+ series.values = resolveChartRange(series.valueReference, workbook)
+ .map(value => Number(value))
+ .filter(value => Number.isFinite(value));
+ }
+}
+
+function resolveChartRange(reference: string, workbook: Workbook): Array<string | number> {
+ const match = /^(?:'((?:[^']|'')+)'|([^'!]+))!\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?$/i.exec(reference.trim());
+ if (!match) return [];
+ const sheetName = (match[1] ?? match[2]).replace(/''/g, "'");
+ const worksheet = workbook.getWorksheet(sheetName);
+ if (!worksheet) return [];
+ const start = decodeCellAddress(`${match[3]}${match[4]}`);
+ const end = decodeCellAddress(`${match[5] ?? match[3]}${match[6] ?? match[4]}`);
+ const values: Array<string | number> = [];
+ for (let row = start.row; row <= end.row; row += 1) {
+ for (let column = start.column; column <= end.column; column += 1) {
+ const cell = worksheet.getCell(row, column);
+ const value = chartCellValue(cell.value);
+ if (typeof value === 'number' || typeof value === 'string') values.push(value);
+ }
+ }
+ return values;
+}
+
+function chartCellValue(value: Cell['value']): string | number | undefined {
+ if (typeof value === 'number' || typeof value === 'string') return value;
+ if (value instanceof Date) return value.toLocaleDateString();
+ if (isFormulaValue(value)) return chartCellValue(value.result as Cell['value']);
+ if (isHyperlinkValue(value)) return value.text;
+ if (isRichTextValue(value)) return value.richText.map(part => part.text).join('');
+ return undefined;
+}
+
+function parseAutoFilter(autoFilter: unknown): SpreadsheetSheetData['autoFilter'] {
+ const reference =
+ typeof autoFilter === 'string'
+ ? autoFilter
+ : autoFilter && typeof autoFilter === 'object' && 'ref' in autoFilter && typeof autoFilter.ref === 'string'
+ ? autoFilter.ref
+ : undefined;
+ return reference ? parseCellRange(reference) : undefined;
+}
+
+async function readArchiveText(archive: JSZip, path: string): Promise<string | undefined> {
+ const entry = archive.file(path);
+ return entry ? entry.async('text') : undefined;
+}
+
+function relationshipPath(originPath: string): string {
+ const parts = originPath.split('/');
+ const file = parts.pop();
+ return [...parts, '_rels', `${file}.rels`].join('/');
+}
+
+function resolveArchivePath(originPath: string, target: string): string {
+ if (target.startsWith('/')) return target.slice(1);
+ const parts = originPath.split('/').slice(0, -1);
+ target.split('/').forEach(part => {
+ if (!part || part === '.') return;
+ if (part === '..') parts.pop();
+ else parts.push(part);
+ });
+ return parts.join('/');
+}
+
+function emuToPixels(value: number): number {
+ return Number.isFinite(value) ? Math.max(0, Math.round((value / 9525) * 100) / 100) : 0;
+}
+
+function mediaType(path: string): string {
+ const extension = path.split('.').pop()?.toLowerCase();
+ if (extension === 'jpg' || extension === 'jpeg') return 'image/jpeg';
+ if (extension === 'gif') return 'image/gif';
+ if (extension === 'svg') return 'image/svg+xml';
+ if (extension === 'bmp') return 'image/bmp';
+ if (extension === 'tif' || extension === 'tiff') return 'image/tiff';
+ return 'image/png';
+}
+
+function parseThemePalette(workbook: Workbook): string[] {
+ const themes = workbook.model.themes as unknown as WorkbookThemes;
+ const xml = themes?.theme1;
+ if (!xml) return [...DEFAULT_THEME_COLORS];
+
+ const palette = [...DEFAULT_THEME_COLORS];
+ let activeThemeIndex = -1;
+ const parser = new SaxesParser<{ xmlns: true }>({ xmlns: true });
+ parser.on('opentag', tag => {
+ const themeIndex = THEME_COLOR_NAMES.indexOf(tag.local);
+ if (themeIndex >= 0) {
+ activeThemeIndex = themeIndex;
+ return;
+ }
+ if (activeThemeIndex < 0 || (tag.local !== 'srgbClr' && tag.local !== 'sysClr')) return;
+ const color = tag.local === 'sysClr' ? xmlAttribute(tag, 'lastClr') : xmlAttribute(tag, 'val');
+ if (color && /^[0-9a-f]{6}$/i.test(color)) palette[activeThemeIndex] = color.toUpperCase();
+ });
+ parser.on('closetag', tag => {
+ if (THEME_COLOR_NAMES[activeThemeIndex] === tag.local) activeThemeIndex = -1;
+ });
+ parser.write(xml).close();
+ return palette;
+}
+
+function xmlAttribute(tag: SaxesTagNS, name: string): string | undefined {
+ const attribute = Object.values(tag.attributes).find(value => value.local === name);
+ return attribute?.value;
+}
+
+function applyTint(hex: string, tint: number): string {
+ const normalizedTint = Math.max(-1, Math.min(1, tint));
+ if (normalizedTint === 0) return hex.toUpperCase();
+ const [red, green, blue] = hexToRgb(hex).map(value => value / 255) as [number, number, number];
+ const maximum = Math.max(red, green, blue);
+ const minimum = Math.min(red, green, blue);
+ let hue = 0;
+ let saturation = 0;
+ let lightness = (maximum + minimum) / 2;
+
+ if (maximum !== minimum) {
+ const delta = maximum - minimum;
+ saturation = lightness > 0.5 ? delta / (2 - maximum - minimum) : delta / (maximum + minimum);
+ if (maximum === red) hue = (green - blue) / delta + (green < blue ? 6 : 0);
+ else if (maximum === green) hue = (blue - red) / delta + 2;
+ else hue = (red - green) / delta + 4;
+ hue /= 6;
+ }
+ lightness = normalizedTint < 0 ? lightness * (1 + normalizedTint) : lightness * (1 - normalizedTint) + normalizedTint;
+
+ const channels =
+ saturation === 0
+ ? [lightness, lightness, lightness]
+ : [hueToRgb(lightness, saturation, hue + 1 / 3), hueToRgb(lightness, saturation, hue), hueToRgb(lightness, saturation, hue - 1 / 3)];
+ return channels
+ .map(channel =>
+ Math.round(channel * 255)
+ .toString(16)
+ .padStart(2, '0'),
+ )
+ .join('')
+ .toUpperCase();
+}
+
+function hueToRgb(lightness: number, saturation: number, hue: number): number {
+ let normalizedHue = hue;
+ if (normalizedHue < 0) normalizedHue += 1;
+ if (normalizedHue > 1) normalizedHue -= 1;
+ const upper = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
+ const lower = 2 * lightness - upper;
+ if (normalizedHue < 1 / 6) return lower + (upper - lower) * 6 * normalizedHue;
+ if (normalizedHue < 1 / 2) return upper;
+ if (normalizedHue < 2 / 3) return lower + (upper - lower) * (2 / 3 - normalizedHue) * 6;
+ return lower;
+}
+
+function hexToRgb(hex: string): [number, number, number] {
+ return [Number.parseInt(hex.slice(0, 2), 16), Number.parseInt(hex.slice(2, 4), 16), Number.parseInt(hex.slice(4, 6), 16)];
+}
+
+function decodeCellAddress(address: string): { row: number; column: number } {
+ const match = /^\$?([A-Z]+)\$?(\d+)$/i.exec(address);
+ if (!match) throw new Error(`Invalid spreadsheet cell address: ${address}`);
+ let column = 0;
+ for (const character of match[1].toUpperCase()) column = column * 26 + character.charCodeAt(0) - 64;
+ return { row: Number(match[2]), column };
+}
+
+function cellKey(row: number, column: number): string {
+ return `${row}:${column}`;
+}
+
+function columnWidthToPixels(width: number): number {
+ if (width <= 0) return 0;
+ return Math.max(1, Math.floor(((256 * width + Math.floor(128 / 7)) / 256) * 7));
+}
+
+function pointsToPixels(points: number): number {
+ return Math.max(0, Math.round((points * 96 * 100) / 72) / 100);
+}
+
+function safeHyperlink(hyperlink: string): string | undefined {
+ return /^(https?:|mailto:|tel:)/i.test(hyperlink) ? hyperlink : undefined;
+}
+
+function isFormulaValue(value: unknown): value is { formula: string; result?: unknown } | { sharedFormula: string; result?: unknown } {
+ return Boolean(value && typeof value === 'object' && ('formula' in value || 'sharedFormula' in value));
+}
+
+function isHyperlinkValue(value: unknown): value is { text: string; hyperlink: string } {
+ return Boolean(value && typeof value === 'object' && 'text' in value && 'hyperlink' in value);
+}
+
+function isRichTextValue(value: unknown): value is { richText: Array<{ text: string }> } {
+ return Boolean(value && typeof value === 'object' && 'richText' in value);
+}
+
+function isCellError(value: unknown): value is { error: string } {
+ return Boolean(value && typeof value === 'object' && 'error' in value);
+}
+
+function normalizeDegrees(degrees: number): number {
+ return ((degrees % 360) + 360) % 360;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/HistoryPagerBar.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/HistoryPagerBar.tsx
deleted file mode 100644
index c4eb9b2ab0..0000000000
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/HistoryPagerBar.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { useTranslation } from 'react-i18next';
-import { useState, useEffect } from 'react';
-
-export interface HistoryPagerBarProps {
- loadedPages: number;
- totalPages: number;
- loadingMore: boolean;
- onLoadMore: () => void;
-}
-
-export function HistoryPagerBar({
- loadedPages,
- totalPages,
- loadingMore,
- onLoadMore,
-}: HistoryPagerBarProps) {
- const { t } = useTranslation();
- const hasMore = loadedPages < totalPages;
- const [showLoadedMessage, setShowLoadedMessage] = useState(false);
-
- // 监听 loadingMore 状态变化,当从 true 变为 false 时,显示加载完成消息
- useEffect(() => {
- if (!loadingMore && loadedPages > 0) {
- setShowLoadedMessage(true);
- // 3秒后关闭消息
- const timer = setTimeout(() => {
- setShowLoadedMessage(false);
- }, 3000);
- return () => clearTimeout(timer);
- }
- }, [loadingMore, loadedPages]);
-
- // 当开始加载新内容时,隐藏已加载消息
- useEffect(() => {
- if (loadingMore) {
- setShowLoadedMessage(false);
- }
- }, [loadingMore]);
-
- const handleClick = () => {
- if (hasMore && !loadingMore) {
- void onLoadMore();
- }
- };
-
- return (
- <div
- className="history-pager-bar mb-3 rounded-lg border border-white/10 bg-secondary/50 px-3 py-2.5 flex flex-col items-center justify-center gap-2 text-sm cursor-pointer"
- onClick={handleClick}
- title={t('chat.historyPager.clickOrScrollToLoadMore')}
- >
- {/* 加载完成消息 */}
- {showLoadedMessage && (
- <span className="text-text-muted tabular-nums animate-fade-in">
- {t('chat.historyPager.loadedOfTotal', { loaded: loadedPages, total: totalPages })}
- </span>
- )}
-
- {/* 加载状态或提示文本 */}
- {loadingMore ? (
- <div className="flex justify-center items-center py-2">
- <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-text-muted" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
- <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
- </svg>
- </div>
- ) : (
- hasMore ? (
- <span className="text-xs text-text-muted">
- {t('chat.historyPager.clickOrScrollToLoadMore')}
- </span>
- ) : (
- <span className="text-xs text-text-muted">{t('chat.historyPager.allLoaded')}</span>
- )
- )}
- </div>
- );
-}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
index fbe44ab255..f70884917d 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
@@ -37,6 +37,9 @@ import { MarkdownRenderer } from '../../components/MarkdownRenderer';
import { isTeamP2PMessageToUser, parseTeamEventMessage } from './teamEventUtils';
import { TeamMemberAvatar } from '../TeamMemberAvatar';
import { ProactiveRecommendationCard } from './ProactiveRecommendationCard';
+import { fileArtifactId } from '../ArtifactsPanel';
+import { openArtifactPanel } from '../../features/teamPanelState';
+import { executeDesktopSave, type DesktopSaveApiResult } from '../../utils/desktopSave';
export const MarkdownMessageBody = memo(function MarkdownMessageBody({
content,
@@ -104,7 +107,11 @@ function TeamLeaderPlainTextMessage({
showAvatar={showAvatar}
>
{fileItems && fileItems.length > 0 && (
- <FileDownloadList files={fileItems} className="w-full md:w-1/2" />
+ <FileDownloadList
+ files={fileItems}
+ className="w-full md:w-1/2"
+ onPreview={(index) => openArtifactPanel(fileArtifactId(fileItems[index]))}
+ />
)}
<div className="team-member-message__plain">
<A2UIMessageContent
@@ -622,7 +629,10 @@ export const MessageItem = memo(function MessageItem({
<MediaRenderer items={visibleMediaItems} align="start" />
)}
{visibleFileItems && (
- <FileDownloadList files={visibleFileItems} />
+ <FileDownloadList
+ files={visibleFileItems}
+ onPreview={(index) => openArtifactPanel(fileArtifactId(visibleFileItems[index]))}
+ />
)}
</>
)}
@@ -765,9 +775,11 @@ function getFileTypeConfig(mimeType: string | undefined, name: string) {
function FileDownloadList({
files,
className,
+ onPreview,
}: {
files: FileDownloadItem[];
className?: string;
+ onPreview?: (index: number) => void;
}) {
const { t } = useTranslation();
const [expiredSet, setExpiredSet] = useState<Set<number>>(new Set());
@@ -793,13 +805,15 @@ function FileDownloadList({
const handleDownload = async (file: FileDownloadItem, index: number) => {
if (expiredSet.has(index)) return;
- // 检查是否在 PyWebView 环境中(exe 模式)
- const pywebviewApi = (window as Window & { pywebview?: { api?: { download_file?: (url: string, filename: string) => Promise<boolean> | boolean } } }).pywebview?.api;
+ // 检查是否在 PyWebView 桌面环境中
+ const pywebviewApi = (window as Window & { pywebview?: { api?: { download_file?: (url: string, filename: string) => DesktopSaveApiResult } } }).pywebview?.api;
if (pywebviewApi?.download_file) {
- // exe 模式:通过 webview API 下载
- const success = await pywebviewApi.download_file(file.download_url, file.name || 'download');
- if (!success) {
- console.error('Download failed via pywebview API');
+ // 桌面端:通过 webview API 下载
+ const outcome = await executeDesktopSave(() =>
+ pywebviewApi.download_file!(file.download_url, file.name || 'download')
+ );
+ if (outcome === 'failed') {
+ window.alert(t('artifacts.downloadFailed', { name: file.name }));
}
return;
}
@@ -825,38 +839,63 @@ function FileDownloadList({
'flex items-center gap-3 rounded-lg border px-3 py-2.5 ',
expired
? 'border-border/50 bg-card/50 cursor-not-allowed opacity-60'
- : 'border-border bg-card hover:shadow-md hover:border-border-hover cursor-pointer group'
+ : clsx(
+ 'border-border bg-card',
+ onPreview && 'cursor-pointer group hover:border-border-hover hover:shadow-md'
+ )
)}
- onClick={() => handleDownload(file, index)}
+ onClick={() => {
+ if (!expired) onPreview?.(index);
+ }}
>
- <div className={`flex-shrink-0 w-10 h-10 rounded-lg ${typeConfig.bg} flex items-center justify-center`}>
- {typeof typeConfig.icon === 'string' ? (
- <span className="text-white text-base leading-none select-none">{typeConfig.icon}</span>
- ) : (
- typeConfig.icon
- )}
- </div>
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-text leading-snug truncate">{file.name}</div>
- <div className="flex items-center gap-1.5 mt-0.5">
- <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-text-muted bg-secondary leading-none">
- {ext || typeConfig.label}
- </span>
- <span className="text-xs text-text-muted">{formatFileSize(file.size)}</span>
- {expired && (
- <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-danger bg-danger/10 leading-none">
- {t('chatUi.fileExpired')}
- </span>
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 items-center gap-3 text-left"
+ disabled={expired || !onPreview}
+ onClick={(event) => {
+ event.stopPropagation();
+ onPreview?.(index);
+ }}
+ title={onPreview ? t('artifacts.openPreview', { name: file.name }) : undefined}
+ aria-label={onPreview ? t('artifacts.openPreview', { name: file.name }) : undefined}
+ >
+ <div className={`flex-shrink-0 w-10 h-10 rounded-lg ${typeConfig.bg} flex items-center justify-center`}>
+ {typeof typeConfig.icon === 'string' ? (
+ <span className="text-white text-base leading-none select-none">{typeConfig.icon}</span>
+ ) : (
+ typeConfig.icon
)}
</div>
- </div>
- <div
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-text leading-snug truncate">{file.name}</div>
+ <div className="flex items-center gap-1.5 mt-0.5">
+ <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-text-muted bg-secondary leading-none">
+ {ext || typeConfig.label}
+ </span>
+ <span className="text-xs text-text-muted">{formatFileSize(file.size)}</span>
+ {expired && (
+ <span className="inline-flex items-center px-1 py-px rounded text-[10px] font-mono font-medium text-danger bg-danger/10 leading-none">
+ {t('chatUi.fileExpired')}
+ </span>
+ )}
+ </div>
+ </div>
+ </button>
+ <button
+ type="button"
className={clsx(
'flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center ',
expired
? 'text-text-muted/40'
- : 'text-text-muted group-hover:text-accent group-hover:bg-accent-subtle'
+ : 'text-text-muted hover:text-accent hover:bg-accent-subtle'
)}
+ disabled={expired}
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleDownload(file, index);
+ }}
+ title={t('artifacts.download')}
+ aria-label={t('artifacts.download')}
>
{expired ? (
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
@@ -867,7 +906,7 @@ function FileDownloadList({
<path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
</svg>
)}
- </div>
+ </button>
</div>
);
})}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
index e8ef75138c..66fa5bbc34 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
@@ -27,7 +27,6 @@ import { SubtaskProgress } from './SubtaskProgress';
import { InlineQuestionCard } from './InlineQuestionCard';
import { InteractionSlot } from '../InteractionSlot';
import { GoalBar } from '../GoalBar';
-import { HistoryPagerBar } from './HistoryPagerBar';
import { HarnessProgressBar } from './HarnessProgressBar';
import { AgentTeamActivityCard } from './TeamEventGroupDisplay';
import { isTeamActivityMessage, parseTeamEventMessage } from './teamEventUtils';
@@ -38,12 +37,17 @@ import './ChatPanel.css';
import { CodeChangesCard } from '../../features/code-mode/CodeChangesCard';
import { useCodeTurnDiffHistory } from '../../features/code-mode/useCodeTurnDiffHistory';
import type { CodeReviewTarget } from '../../features/code-mode/types';
+import {
+ canLoadOlderHistory,
+ shouldShowHistoryRetry,
+} from '../../features/historyPagination';
export interface ChatHistoryPagerProps {
loadedPages: number;
totalPages: number;
loadingMore: boolean;
prepending?: boolean;
+ retryAvailable?: boolean;
onLoadMore: () => void | Promise<void>;
}
@@ -707,21 +711,24 @@ export function ChatPanel({
const historyTotalPages = historyPager?.totalPages ?? 0;
const historyLoadingMore = historyPager?.loadingMore ?? false;
const historyPrepending = historyPager?.prepending ?? false;
+ const historyRetryAvailable = historyPager?.retryAvailable ?? false;
const historyOnLoadMore = historyPager?.onLoadMore;
const hasHistoryPager = Boolean(historyPager);
- const canLoadOlderHistory = Boolean(
- historyOnLoadMore &&
- historyLoadedPages < historyTotalPages &&
- !historyLoadingMore &&
- !historyPrepending
+ const historyLoadMoreState = {
+ loadedPages: historyLoadedPages,
+ totalPages: historyTotalPages,
+ loadingMore: historyLoadingMore,
+ prepending: historyPrepending,
+ };
+ const canRequestOlderHistory = Boolean(
+ historyOnLoadMore && canLoadOlderHistory(historyLoadMoreState)
);
- const showHistoryPager = Boolean(
- !isHistoryRestoring &&
- historyPager && (
- historyLoadingMore ||
- historyLoadedPages < historyTotalPages ||
- !hasTimelineContent
- )
+ const showHistoryRetry = Boolean(
+ historyOnLoadMore &&
+ shouldShowHistoryRetry({
+ ...historyLoadMoreState,
+ retryAvailable: historyRetryAvailable,
+ })
);
const chatContentClassName = hasConversation
? `chat-content${mode === 'team' ? ' chat-content--team' : ''}`
@@ -812,10 +819,10 @@ export function ChatPanel({
rememberSessionScrollTop(currentSessionId, el);
// 当滚动到顶部且有更多历史消息时,加载更多
- if (el.scrollTop <= LOAD_OLDER_THRESHOLD_PX && canLoadOlderHistory && historyOnLoadMore) {
+ if (el.scrollTop <= LOAD_OLDER_THRESHOLD_PX && canRequestOlderHistory && historyOnLoadMore) {
void historyOnLoadMore();
}
- }, [activeSessionId, canLoadOlderHistory, historyOnLoadMore, rememberSessionScrollTop]);
+ }, [activeSessionId, canRequestOlderHistory, historyOnLoadMore, rememberSessionScrollTop]);
useEffect(() => {
const el = scrollContainerRef.current;
@@ -847,14 +854,14 @@ export function ChatPanel({
if (e.deltaY < 0) {
stickToBottomUntilStableRef.current = false;
}
- if (e.deltaY < 0 && canLoadOlderHistory && historyOnLoadMore) {
+ if (e.deltaY < 0 && canRequestOlderHistory && historyOnLoadMore) {
// 检查是否已经在顶部(没有滚动条时 scrollTop 始终为 0)
const el = scrollContainerRef.current;
if (el && el.scrollTop <= LOAD_OLDER_THRESHOLD_PX) {
void historyOnLoadMore();
}
}
- }, [canLoadOlderHistory, historyOnLoadMore]);
+ }, [canRequestOlderHistory, historyOnLoadMore]);
// 监听浏览器 tab 可见性变化:隐藏时记录位置,恢复可见时抑制自动滚底
useEffect(() => {
@@ -1071,13 +1078,16 @@ export function ChatPanel({
<div className={chatContentClassName}>
{hasConversation ? (
<>
- {showHistoryPager && historyPager && (
- <HistoryPagerBar
- loadedPages={historyPager.loadedPages}
- totalPages={historyPager.totalPages}
- loadingMore={historyPager.loadingMore}
- onLoadMore={historyPager.onLoadMore}
- />
+ {showHistoryRetry && historyOnLoadMore && (
+ <div className="flex justify-center pb-3">
+ <button
+ type="button"
+ className="btn !px-3 !py-1.5 text-xs"
+ onClick={() => void historyOnLoadMore()}
+ >
+ {t('chat.historyLoadMore')}
+ </button>
+ </div>
)}
{hasTimelineContent ? (
<>
@@ -1096,13 +1106,13 @@ export function ChatPanel({
summary={contextCompressionSummary}
/>
</>
- ) : (
- <div className="flex items-center justify-center h-32">
- <div className="text-text-muted text-sm">
- {t('connection.loadingConfig')}
+ ) : isHistoryRestoring ? (
+ <div className="flex h-32 items-center justify-center" role="status" aria-live="polite">
+ <div className="text-sm text-text-muted">
+ {t('chat.historyLoading')}
</div>
</div>
- )}
+ ) : null}
</>
) : (
<div className="chat-welcome">
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx
index 4dca04088d..478eae4216 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx
@@ -51,11 +51,13 @@ interface ToolPanelProps {
teamAreaActiveDetailTab: TeamDetailTab;
teamAreaSelectedMemberId?: string;
codeReviewTarget?: CodeReviewTarget | null;
+ teamAreaSelectedArtifactId?: string;
setTeamAreaExpanded: (expanded: boolean) => void;
setTeamAreaActiveTab: (tab: TabType) => void;
setTeamAreaActiveDetailTab: (detailTab: TeamDetailTab) => void;
setTeamAreaSelectedMemberId: (memberId: string) => void;
setCodeReviewTarget?: (target: CodeReviewTarget | null) => void;
+ setTeamAreaSelectedArtifactId: (artifactId: string) => void;
}
function isEmptyValue(value: unknown): boolean {
@@ -96,6 +98,8 @@ function ExpandedSingleAgentArea({
onTabChange,
onCollapse,
reviewPanel,
+ selectedArtifactId,
+ onArtifactSelect,
}: {
activeTab: TabType;
tasks: TeamTask[];
@@ -105,6 +109,8 @@ function ExpandedSingleAgentArea({
onTabChange: (tab: TabType) => void;
onCollapse: () => void;
reviewPanel?: ReactNode;
+ selectedArtifactId?: string;
+ onArtifactSelect: (artifactId: string) => void;
}) {
const { t } = useTranslation();
const artifactsCount = useSessionArtifactsCount();
@@ -164,7 +170,7 @@ function ExpandedSingleAgentArea({
<div className="flex min-h-0 flex-1 overflow-hidden">
{resolvedTab === 'artifacts' ? (
<div className="flex min-w-0 flex-1 overflow-hidden">
- <ArtifactsPanel />
+ <ArtifactsPanel selectedArtifactId={selectedArtifactId} onSelectArtifact={onArtifactSelect} />
</div>
) : resolvedTab === 'review' && reviewPanel ? (
<div className="flex min-w-0 flex-1 overflow-hidden">{reviewPanel}</div>
@@ -192,11 +198,13 @@ export function ToolPanel({
teamAreaActiveDetailTab,
teamAreaSelectedMemberId,
codeReviewTarget = null,
+ teamAreaSelectedArtifactId,
setTeamAreaExpanded,
setTeamAreaActiveTab,
setTeamAreaActiveDetailTab,
setTeamAreaSelectedMemberId,
setCodeReviewTarget,
+ setTeamAreaSelectedArtifactId,
}: ToolPanelProps) {
const { t } = useTranslation();
const { isConnected, memoryUsage, setMemoryUsage } = useSessionStore();
@@ -440,6 +448,8 @@ export function ToolPanel({
onTabChange={setTeamAreaActiveTab}
onCollapse={() => setTeamAreaExpanded(false)}
reviewPanel={codeReviewPanel}
+ selectedArtifactId={teamAreaSelectedArtifactId}
+ onArtifactSelect={setTeamAreaSelectedArtifactId}
/>
</div>
</div>
@@ -460,9 +470,11 @@ export function ToolPanel({
activeTab={teamAreaActiveTab}
activeDetailTab={teamAreaActiveDetailTab}
selectedMemberId={teamAreaSelectedMemberId}
+ selectedArtifactId={teamAreaSelectedArtifactId}
onTabChange={setTeamAreaActiveTab}
onDetailTabChange={setTeamAreaActiveDetailTab}
onMemberSelect={setTeamAreaSelectedMemberId}
+ onArtifactSelect={setTeamAreaSelectedArtifactId}
onCollapse={() => {
setTeamAreaExpanded(false);
setTeamAreaSelectedMemberId('');
diff --git a/jiuwenswarm/channels/web/frontend/src/components/teamArea/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/teamArea/index.tsx
index cf4f550988..510e579d1c 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/teamArea/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/teamArea/index.tsx
@@ -103,9 +103,11 @@ function ExpandedTeamArea({
activeTab,
activeDetailTab,
selectedMemberId: externalSelectedMemberId,
+ selectedArtifactId,
onTabChange,
onDetailTabChange,
onMemberSelect,
+ onArtifactSelect,
onCollapse,
reviewPanel,
}: {
@@ -114,9 +116,11 @@ function ExpandedTeamArea({
activeTab: TabType;
activeDetailTab: TeamDetailTab;
selectedMemberId?: string;
+ selectedArtifactId?: string;
onTabChange: (tab: TabType) => void;
onDetailTabChange: (tab: TeamDetailTab) => void;
onMemberSelect?: (memberId: string) => void;
+ onArtifactSelect?: (artifactId: string) => void;
onCollapse?: () => void;
reviewPanel?: ReactNode;
}) {
@@ -202,7 +206,7 @@ function ExpandedTeamArea({
/>
) : resolvedTab === 'artifacts' ? (
<div className="flex min-w-0 flex-1 overflow-hidden">
- <ArtifactsPanel />
+ <ArtifactsPanel selectedArtifactId={selectedArtifactId} onSelectArtifact={onArtifactSelect} />
</div>
) : resolvedTab === 'review' && reviewPanel ? (
<div className="flex min-w-0 flex-1 overflow-hidden">{reviewPanel}</div>
@@ -234,9 +238,11 @@ export function TeamArea(props: TeamAreaProps) {
activeTab={props.activeTab}
activeDetailTab={props.activeDetailTab}
selectedMemberId={props.selectedMemberId}
+ selectedArtifactId={props.selectedArtifactId}
onTabChange={props.onTabChange}
onDetailTabChange={props.onDetailTabChange}
onMemberSelect={props.onMemberSelect}
+ onArtifactSelect={props.onArtifactSelect}
onCollapse={props.onCollapse}
reviewPanel={reviewPanel}
/>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/teamArea/shared.tsx b/jiuwenswarm/channels/web/frontend/src/components/teamArea/shared.tsx
index 4cb1f7ae24..1860da3026 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/teamArea/shared.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/teamArea/shared.tsx
@@ -84,9 +84,11 @@ export type TeamAreaProps = BaseTeamAreaProps & (
activeTab: TabType;
activeDetailTab: TeamDetailTab;
selectedMemberId?: string;
+ selectedArtifactId?: string;
onTabChange: (tab: TabType) => void;
onDetailTabChange: (tab: TeamDetailTab) => void;
onMemberSelect?: (memberId: string) => void;
+ onArtifactSelect?: (artifactId: string) => void;
onCollapse?: () => void;
}
);
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyPagination.ts b/jiuwenswarm/channels/web/frontend/src/features/historyPagination.ts
new file mode 100644
index 0000000000..6e43f4d65b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/historyPagination.ts
@@ -0,0 +1,65 @@
+export interface HistoryPageDescriptor {
+ pageIdx: number;
+ totalPages: number;
+}
+
+export type HistoryPrefetchOutcome = 'completed' | 'failed' | 'cancelled';
+
+interface PrefetchHistoryPagesOptions<Page extends HistoryPageDescriptor> {
+ initialLoadedPages: number;
+ initialTotalPages: number;
+ isCurrent: () => boolean;
+ fetchPage: (pageIdx: number, totalPages: number) => Promise<Page | null>;
+ applyPage: (page: Page) => void;
+ waitForNextPaint: () => Promise<void>;
+}
+
+export async function prefetchHistoryPages<Page extends HistoryPageDescriptor>({
+ initialLoadedPages,
+ initialTotalPages,
+ isCurrent,
+ fetchPage,
+ applyPage,
+ waitForNextPaint,
+}: PrefetchHistoryPagesOptions<Page>): Promise<HistoryPrefetchOutcome> {
+ let loadedPages = initialLoadedPages;
+ let totalPages = initialTotalPages;
+
+ while (loadedPages < totalPages) {
+ if (!isCurrent()) {
+ return 'cancelled';
+ }
+
+ const nextPage = loadedPages + 1;
+ const page = await fetchPage(nextPage, totalPages);
+
+ if (!isCurrent()) {
+ return 'cancelled';
+ }
+ if (!page || page.pageIdx !== nextPage) {
+ return 'failed';
+ }
+
+ applyPage(page);
+ loadedPages = page.pageIdx;
+ totalPages = page.totalPages;
+ await waitForNextPaint();
+ }
+
+ return 'completed';
+}
+
+interface HistoryLoadMoreState {
+ loadedPages: number;
+ totalPages: number;
+ loadingMore: boolean;
+ prepending: boolean;
+}
+
+export function canLoadOlderHistory({ loadedPages, totalPages, loadingMore, prepending }: HistoryLoadMoreState): boolean {
+ return loadedPages < totalPages && !loadingMore && !prepending;
+}
+
+export function shouldShowHistoryRetry(state: HistoryLoadMoreState & { retryAvailable: boolean }): boolean {
+ return state.retryAvailable && canLoadOlderHistory(state);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/teamPanelState.ts b/jiuwenswarm/channels/web/frontend/src/features/teamPanelState.ts
index 3a4c8afb15..659529e0cd 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/teamPanelState.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/teamPanelState.ts
@@ -17,10 +17,12 @@ interface UseTeamPanelStateResult {
teamAreaActiveTab: TabType;
teamAreaActiveDetailTab: TeamDetailTab;
teamAreaSelectedMemberId?: string;
+ teamAreaSelectedArtifactId?: string;
setTeamAreaExpanded: (expanded: boolean) => void;
setTeamAreaActiveTab: (tab: TabType) => void;
setTeamAreaActiveDetailTab: (tab: TeamDetailTab) => void;
setTeamAreaSelectedMemberId: (memberId: string) => void;
+ setTeamAreaSelectedArtifactId: (artifactId: string) => void;
}
function loadTeamPanelState(): TeamPanelState {
@@ -61,6 +63,17 @@ export function openTeamPanel(
notifyTeamPanelState(nextState);
}
+export function openArtifactPanel(selectedArtifactId: string): void {
+ const nextState: TeamPanelState = {
+ ...loadTeamPanelState(),
+ expanded: true,
+ activeTab: 'artifacts',
+ selectedArtifactId,
+ };
+ saveTeamPanelState(nextState);
+ notifyTeamPanelState(nextState);
+}
+
export function useTeamPanelState(): UseTeamPanelStateResult {
const [state, setState] = useState<TeamPanelState>(loadTeamPanelState);
@@ -89,6 +102,10 @@ export function useTeamPanelState(): UseTeamPanelStateResult {
updateState({ selectedMemberId });
}, [updateState]);
+ const setTeamAreaSelectedArtifactId = useCallback((selectedArtifactId: string) => {
+ updateState({ selectedArtifactId });
+ }, [updateState]);
+
useEffect(() => {
function handleTeamPanelStateChange(event: Event) {
setState((event as CustomEvent<TeamPanelState>).detail);
@@ -105,9 +122,11 @@ export function useTeamPanelState(): UseTeamPanelStateResult {
teamAreaActiveTab: state.activeTab,
teamAreaActiveDetailTab: state.activeDetailTab,
teamAreaSelectedMemberId: state.selectedMemberId,
+ teamAreaSelectedArtifactId: state.selectedArtifactId,
setTeamAreaExpanded,
setTeamAreaActiveTab,
setTeamAreaActiveDetailTab,
setTeamAreaSelectedMemberId,
+ setTeamAreaSelectedArtifactId,
};
}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/teamPanelStateNormalize.ts b/jiuwenswarm/channels/web/frontend/src/features/teamPanelStateNormalize.ts
index 39a24cb5d7..f616d3c75e 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/teamPanelStateNormalize.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/teamPanelStateNormalize.ts
@@ -6,6 +6,7 @@ export interface TeamPanelState {
activeTab: TeamPanelActiveTab;
activeDetailTab: TeamPanelDetailTab;
selectedMemberId?: string;
+ selectedArtifactId?: string;
}
export const DEFAULT_TEAM_PANEL_STATE: TeamPanelState = {
@@ -42,12 +43,17 @@ export function normalizeTeamPanelState(value: unknown): TeamPanelState {
typeof raw.selectedMemberId === 'string' && raw.selectedMemberId.trim()
? raw.selectedMemberId
: undefined;
+ const selectedArtifactId =
+ typeof raw.selectedArtifactId === 'string' && raw.selectedArtifactId.trim()
+ ? raw.selectedArtifactId
+ : undefined;
return {
expanded: typeof raw.expanded === 'boolean' ? raw.expanded : DEFAULT_TEAM_PANEL_STATE.expanded,
activeTab,
activeDetailTab,
...(selectedMemberId ? { selectedMemberId } : {}),
+ ...(selectedArtifactId ? { selectedArtifactId } : {}),
};
}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index 1713df090a..2a6bc5852c 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -951,7 +951,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const clearPendingContextCompressionStart = useCallback((sessionId: string) => {
const pending = pendingContextCompressionStartRef.current.get(sessionId);
if (pending) {
- clearTimeout(pending.timer);
+ window.clearTimeout(pending.timer);
pendingContextCompressionStartRef.current.delete(sessionId);
}
}, []);
@@ -965,13 +965,13 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const key = getTeamMemberContextCompressionKey(sessionId, memberId);
const pending = pendingTeamMemberContextCompressionStartRef.current.get(key);
if (!pending) return;
- clearTimeout(pending.timer);
+ window.clearTimeout(pending.timer);
pendingTeamMemberContextCompressionStartRef.current.delete(key);
}, [getTeamMemberContextCompressionKey]);
const clearAllPendingTeamMemberContextCompressionStarts = useCallback(() => {
for (const pending of pendingTeamMemberContextCompressionStartRef.current.values()) {
- clearTimeout(pending.timer);
+ window.clearTimeout(pending.timer);
}
pendingTeamMemberContextCompressionStartRef.current.clear();
}, []);
@@ -1028,7 +1028,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const pending: PendingContextCompressionStart = {
runtimeState,
shown: false,
- timer: setTimeout(() => {
+ timer: window.setTimeout(() => {
const current = pendingContextCompressionStartRef.current.get(sessionId);
if (current !== pending) return;
pending.shown = true;
@@ -1108,7 +1108,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
const pending: PendingContextCompressionStart = {
runtimeState,
shown: false,
- timer: setTimeout(() => {
+ timer: window.setTimeout(() => {
if (pendingTeamMemberContextCompressionStartRef.current.get(key) !== pending) return;
pending.shown = true;
setTeamMemberContextCompressionStatus(sessionId, memberId, {
@@ -1157,7 +1157,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
useEffect(() => {
return () => {
pendingContextCompressionStartRef.current.forEach((pending) => {
- clearTimeout(pending.timer);
+ window.clearTimeout(pending.timer);
});
pendingContextCompressionStartRef.current.clear();
clearAllPendingTeamMemberContextCompressionStarts();
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index e675280fdb..73ee377793 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -187,10 +187,38 @@
"count": "{{count}} item(s)",
"empty": "No artifacts",
"download": "Download",
+ "downloadFailed": "Could not download “{{name}}”. Check your connection and save location, then try again.",
+ "expandList": "Show artifact list",
+ "collapseList": "Hide artifact list",
+ "openPreview": "Open preview for {{name}}",
"selectArtifact": "Select an artifact to preview",
- "previewUnsupported": "Preview is only supported for Markdown files",
- "previewMissingPath": "No readable local path is available for this artifact",
- "previewFailed": "Failed to load Markdown preview"
+ "previewUnsupported": "This file type cannot be previewed yet. Download it to view it.",
+ "previewMissingPath": "No downloadable resource is available for this artifact preview",
+ "previewFailed": "Failed to load the file preview",
+ "docxPreviewFailed": "Failed to load the Word document preview",
+ "presentationPreviewFailed": "Failed to load the PowerPoint presentation preview",
+ "presentationResourceLimitExceeded": "The PowerPoint presentation content exceeds the browser preview limit. Download the file to view it.",
+ "presentationTooLarge": "PowerPoint presentations larger than {{size}} cannot be previewed in the browser. Download the file to view it.",
+ "presentationSlides": "Slides",
+ "presentationPage": "Slide {{current}} of {{total}}",
+ "presentationSlideIncomplete": "Slide {{page}} is only partially previewed",
+ "presentationStructureInvalid": "This presentation contains structurally invalid slides. Try downloading it to view.",
+ "presentationGoToSlide": "Go to slide {{index}}",
+ "presentationScrollThumbnailsPrevious": "Scroll slide thumbnails left",
+ "presentationScrollThumbnailsNext": "Scroll slide thumbnails right",
+ "presentationPreviousSlide": "Previous slide",
+ "presentationNextSlide": "Next slide",
+ "presentationZoomOut": "Zoom out",
+ "presentationZoomIn": "Zoom in",
+ "presentationZoomLevel": "{{percent}}% actual slide size",
+ "spreadsheetPreviewFailed": "Failed to load the Excel workbook preview",
+ "spreadsheetResourceLimitExceeded": "The Excel workbook content exceeds the browser preview limit. Download the file to view it.",
+ "spreadsheetTooLarge": "Excel workbooks larger than {{size}} cannot be previewed in the browser. Download the file to view it.",
+ "spreadsheetEmptyWorkbook": "This workbook contains no visible worksheets",
+ "spreadsheetEmptySheet": "This worksheet is empty",
+ "spreadsheetSheetTabsLabel": "Worksheets",
+ "spreadsheetTableLabel": "{{sheet}} worksheet preview",
+ "invalidJson": "The JSON or JSONL content is invalid"
},
"teams": {
"title": "Team Management",
@@ -296,12 +324,8 @@
"teamPauseHint": "After pausing a team, send the next message to continue",
"teamBroadcastTarget": "@all",
"contextCompressionCompleted": "Completed context compression {{count}} time(s) this turn",
- "historyPager": {
- "loadedOfTotal": "Loaded {{loaded}} / {{total}} pages",
- "loadingMore": "Loading...",
- "clickOrScrollToLoadMore": "Click or scroll up to load more",
- "allLoaded": "All history loaded"
- },
+ "historyLoading": "Loading conversation history…",
+ "historyLoadMore": "Load more history",
"config": {
"mode": {
"cluster": "Cluster",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 9656445ed2..0cdc034858 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -187,10 +187,38 @@
"count": "{{count}} 个产物",
"empty": "暂无产物",
"download": "下载",
+ "downloadFailed": "“{{name}}”下载失败,请检查网络和保存位置后重试。",
+ "expandList": "展开产物列表",
+ "collapseList": "收起产物列表",
+ "openPreview": "打开 {{name}} 的预览",
"selectArtifact": "请选择一个产物预览",
- "previewUnsupported": "仅支持 Markdown 文件预览",
- "previewMissingPath": "当前产物没有可读取的本地路径",
- "previewFailed": "Markdown 预览加载失败"
+ "previewUnsupported": "此文件类型暂不支持预览,请下载后查看",
+ "previewMissingPath": "当前产物没有可用于预览的下载资源",
+ "previewFailed": "文件预览加载失败",
+ "docxPreviewFailed": "Word 文档预览加载失败",
+ "presentationPreviewFailed": "PowerPoint 演示文稿预览加载失败",
+ "presentationResourceLimitExceeded": "PowerPoint 演示文稿内容规模超过浏览器预览上限,请下载后查看",
+ "presentationTooLarge": "超过 {{size}} 的 PowerPoint 演示文稿无法在浏览器中预览,请下载后查看",
+ "presentationSlides": "幻灯片",
+ "presentationPage": "第 {{current}} / {{total}} 页",
+ "presentationSlideIncomplete": "第 {{page}} 页部分内容无法预览",
+ "presentationStructureInvalid": "该演示文稿包含结构无效的页面,可尝试下载后查看",
+ "presentationGoToSlide": "跳转到第 {{index}} 页",
+ "presentationScrollThumbnailsPrevious": "向左滚动幻灯片缩略图",
+ "presentationScrollThumbnailsNext": "向右滚动幻灯片缩略图",
+ "presentationPreviousSlide": "上一页",
+ "presentationNextSlide": "下一页",
+ "presentationZoomOut": "缩小",
+ "presentationZoomIn": "放大",
+ "presentationZoomLevel": "幻灯片实际尺寸的 {{percent}}%",
+ "spreadsheetPreviewFailed": "Excel 工作簿预览加载失败",
+ "spreadsheetResourceLimitExceeded": "Excel 工作簿内容规模超过浏览器预览上限,请下载后查看",
+ "spreadsheetTooLarge": "超过 {{size}} 的 Excel 工作簿无法在浏览器中预览,请下载后查看",
+ "spreadsheetEmptyWorkbook": "此工作簿不包含可见工作表",
+ "spreadsheetEmptySheet": "此工作表为空",
+ "spreadsheetSheetTabsLabel": "工作表",
+ "spreadsheetTableLabel": "{{sheet}} 工作表预览",
+ "invalidJson": "JSON 或 JSONL 内容无效"
},
"teams": {
"title": "团队管理",
@@ -297,12 +325,8 @@
"teamPauseHint": "团队暂停后,直接发送下一条消息即可继续",
"teamBroadcastTarget": "@所有人",
"contextCompressionCompleted": "本轮完成上下文压缩 {{count}} 次",
- "historyPager": {
- "loadedOfTotal": "历史已加载 {{loaded}} / {{total}} 页",
- "loadingMore": "加载中…",
- "clickOrScrollToLoadMore": "点击或向上滚动加载更多",
- "allLoaded": "历史已全部加载"
- },
+ "historyLoading": "历史数据加载中…",
+ "historyLoadMore": "加载更多历史消息",
"config": {
"mode": {
"cluster": "集群模式",
diff --git a/jiuwenswarm/channels/web/frontend/src/index.css b/jiuwenswarm/channels/web/frontend/src/index.css
index d072550b41..b4787e5759 100644
--- a/jiuwenswarm/channels/web/frontend/src/index.css
+++ b/jiuwenswarm/channels/web/frontend/src/index.css
@@ -1342,7 +1342,7 @@ select {
.tool-tree {
margin: 0;
padding: 0;
- --tool-muted: color-mix(in srgb, var(--color-text-secondary) 72%, var(--color-surface-elevated));
+ --tool-muted: rgba(var(--color-text-secondary-rgb), 0.72);
--tool-muted-strong: var(--color-text-secondary);
}
@@ -1442,7 +1442,7 @@ select {
margin: 0;
padding: 0 2px 0 42px;
font-size: var(--font-size-2xs, 11px);
- color: color-mix(in srgb, var(--color-text-secondary) 72%, var(--color-surface-elevated));
+ color: rgba(var(--color-text-secondary-rgb), 0.72);
}
/* team:与 920px 居中栅格的内容列(36 + 12 = 48px)对齐。 */
@@ -1502,7 +1502,7 @@ select {
.completed-work-row--nested .completed-work-chip--streak {
font-size: var(--font-size-2xs, 11px);
- color: color-mix(in srgb, var(--color-text-secondary) 72%, transparent);
+ color: rgba(var(--color-text-secondary-rgb), 0.72);
}
.completed-work-chip {
@@ -1514,7 +1514,7 @@ select {
padding: 2px 4px 2px 0;
border: 0;
background: transparent;
- color: color-mix(in srgb, var(--color-text-secondary) 88%, transparent);
+ color: rgba(var(--color-text-secondary-rgb), 0.88);
font-size: var(--font-size-sm, 13px);
line-height: 1.4;
cursor: pointer;
@@ -1531,7 +1531,7 @@ select {
width: 16px;
height: 16px;
flex-shrink: 0;
- color: color-mix(in srgb, var(--color-success, #16a34a) 80%, var(--color-text-secondary));
+ color: var(--color-feedback-success);
}
.completed-work-chip__icon svg {
@@ -1576,7 +1576,7 @@ select {
}
.reasoning-panel {
- --tool-muted: color-mix(in srgb, var(--color-text-secondary) 78%, transparent);
+ --tool-muted: rgba(var(--color-text-secondary-rgb), 0.78);
display: flex;
flex-direction: column;
}
@@ -1609,8 +1609,8 @@ select {
padding: 6px 10px;
max-height: 220px;
overflow-y: auto;
- border-left: 2px solid color-mix(in srgb, var(--color-text-secondary) 22%, transparent);
- color: color-mix(in srgb, var(--color-text-secondary) 82%, transparent);
+ border-left: 2px solid rgba(var(--color-text-secondary-rgb), 0.22);
+ color: rgba(var(--color-text-secondary-rgb), 0.82);
font-size: var(--font-size-2xs, 11px);
line-height: 1.55;
white-space: pre-wrap;
@@ -1797,8 +1797,8 @@ select {
width: 100%;
margin: 2px 0 4px;
padding: 10px 12px;
- background: color-mix(in srgb, var(--color-surface-elevated) 60%, transparent);
- border: 1px solid color-mix(in srgb, var(--color-border-default) 70%, transparent);
+ background: rgba(var(--color-surface-card-rgb), 0.6);
+ border: 1px solid rgba(var(--color-border-default-rgb), 0.7);
border-radius: 8px;
opacity: 0;
transform: translateY(-4px);
diff --git a/jiuwenswarm/channels/web/frontend/src/utils/desktopSave.ts b/jiuwenswarm/channels/web/frontend/src/utils/desktopSave.ts
index 718aff9441..dfafd689fb 100644
--- a/jiuwenswarm/channels/web/frontend/src/utils/desktopSave.ts
+++ b/jiuwenswarm/channels/web/frontend/src/utils/desktopSave.ts
@@ -5,6 +5,8 @@ export type DesktopSaveResult = {
export type DesktopSaveApiResult = Promise<boolean | DesktopSaveResult> | boolean | DesktopSaveResult;
+export type DesktopSaveOutcome = 'saved' | 'cancelled' | 'failed';
+
export function isDesktopSaveCancelled(result: boolean | DesktopSaveResult): boolean {
return typeof result === 'object' && result.cancelled === true;
}
@@ -12,3 +14,14 @@ export function isDesktopSaveCancelled(result: boolean | DesktopSaveResult): boo
export function isDesktopSaveOk(result: boolean | DesktopSaveResult): boolean {
return typeof result === 'boolean' ? result : result.ok;
}
+
+export async function executeDesktopSave(save: () => DesktopSaveApiResult): Promise<DesktopSaveOutcome> {
+ try {
+ const result = await save();
+ if (isDesktopSaveCancelled(result)) return 'cancelled';
+ return isDesktopSaveOk(result) ? 'saved' : 'failed';
+ } catch (error) {
+ console.error('Desktop save API failed:', error);
+ return 'failed';
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
index 76f507b0f1..80a7bad29c 100644
--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts
@@ -10,12 +10,17 @@ interface ImportMeta {
readonly env: ImportMetaEnv;
}
+type DesktopSaveResult = {
+ ok: boolean;
+ cancelled?: boolean;
+};
+
interface Window {
pywebview?: {
api?: {
- download_file?: (url: string, filename: string) => Promise<boolean> | boolean;
+ download_file?: (url: string, filename: string) => Promise<DesktopSaveResult> | DesktopSaveResult;
install_update?: (path: string) => Promise<boolean> | boolean;
- save_data_url?: (dataUrl: string, filename: string) => Promise<{ ok: boolean; cancelled?: boolean }> | { ok: boolean; cancelled?: boolean };
+ save_data_url?: (dataUrl: string, filename: string) => Promise<DesktopSaveResult> | DesktopSaveResult;
select_project_directory?: () => Promise<string | null> | string | null;
};
};
diff --git a/jiuwenswarm/channels/web/frontend/tests/artifactCollection.test.mjs b/jiuwenswarm/channels/web/frontend/tests/artifactCollection.test.mjs
new file mode 100644
index 0000000000..3533c72446
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/artifactCollection.test.mjs
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { buildArtifacts, fileArtifactId } from '../node_modules/.cache/artifact-collection/artifactCollection.mjs';
+
+function file(overrides = {}) {
+ return {
+ name: 'report.txt',
+ size: 10,
+ mime_type: 'text/plain',
+ download_url: '/file-api/download?token=report',
+ download_token: 'report',
+ ...overrides,
+ };
+}
+
+function message(role, id, timestamp, fileItems) {
+ return {
+ id,
+ role,
+ content: '',
+ timestamp,
+ fileItems,
+ };
+}
+
+test('collects files from every message role', () => {
+ const artifacts = buildArtifacts([
+ message('user', 'user-message', '2026-07-30T08:00:00.000Z', [file({ name: 'input.txt' })]),
+ message('system', 'team-message', '2026-07-30T09:00:00.000Z', [file({ name: 'team-draft.txt' })]),
+ message('tool', 'tool-message', '2026-07-30T10:00:00.000Z', [file({ name: 'tool-output.txt' })]),
+ message('assistant', 'assistant-message', '2026-07-30T11:00:00.000Z', [file({ name: 'final.txt' })]),
+ ]);
+
+ assert.deepEqual(
+ artifacts.map(artifact => artifact.name),
+ ['final.txt', 'tool-output.txt', 'team-draft.txt', 'input.txt'],
+ );
+ assert.ok(artifacts.every(artifact => artifact.source === 'message'));
+});
+
+test('rejects file entries without a display name or readable resource', () => {
+ const artifacts = buildArtifacts([
+ message('assistant', 'assistant-message', '2026-07-30T11:00:00.000Z', [
+ file({ name: ' ' }),
+ file({ name: 'missing-resource.txt', download_url: '', download_token: '' }),
+ file({ name: 'signed-url.txt', download_url: '/file-api/download?token=url', download_token: '' }),
+ file({ name: 'token-only.txt', download_url: '', download_token: 'token-only' }),
+ file({ name: 'path-only.txt', download_url: '', download_token: '', path: 'agent/workspace/path-only.txt' }),
+ ]),
+ ]);
+
+ assert.deepEqual(artifacts.map(artifact => artifact.name).sort(), ['path-only.txt', 'signed-url.txt', 'token-only.txt']);
+ assert.equal(artifacts.find(artifact => artifact.name === 'token-only.txt')?.downloadUrl, '/file-api/download?token=token-only');
+});
+
+test('sorts assistant artifacts newest first and keeps card selection ids stable', () => {
+ const olderFile = file({ name: ' older.txt ', download_token: 'older', download_url: '' });
+ const artifacts = buildArtifacts([
+ message('assistant', 'older', '2026-07-30T08:00:00.000Z', [olderFile]),
+ message('assistant', 'newer', '2026-07-30T12:00:00.000Z', [file({ name: 'newer.txt', download_token: 'newer', download_url: '' })]),
+ ]);
+
+ assert.deepEqual(
+ artifacts.map(artifact => artifact.name),
+ ['newer.txt', 'older.txt'],
+ );
+ assert.equal(artifacts[1].id, fileArtifactId(olderFile));
+});
+
+test('duplicate file cards select the retained artifact with the same stable id', () => {
+ const olderFile = file({
+ path: '/workspace/report.txt',
+ download_url: '/file-api/download?token=older',
+ download_token: 'older',
+ });
+ const newerFile = file({
+ path: '/workspace/report.txt',
+ download_url: '/file-api/download?token=newer',
+ download_token: 'newer',
+ });
+
+ const artifacts = buildArtifacts([
+ message('assistant', 'older-message', '2026-07-30T08:00:00.000Z', [olderFile]),
+ message('assistant', 'newer-message', '2026-07-30T12:00:00.000Z', [newerFile]),
+ ]);
+
+ assert.equal(artifacts.length, 1);
+ assert.equal(fileArtifactId(olderFile), fileArtifactId(newerFile));
+ assert.equal(artifacts[0].id, fileArtifactId(olderFile));
+ assert.equal(artifacts[0].downloadUrl, newerFile.download_url);
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/desktopSave.test.mjs b/jiuwenswarm/channels/web/frontend/tests/desktopSave.test.mjs
new file mode 100644
index 0000000000..42e75152a5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/desktopSave.test.mjs
@@ -0,0 +1,23 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { executeDesktopSave } from '../node_modules/.cache/desktop-save/desktopSave.mjs';
+
+test('executeDesktopSave distinguishes saved, cancelled, and failed results', async () => {
+ assert.equal(await executeDesktopSave(() => true), 'saved');
+ assert.equal(await executeDesktopSave(() => ({ ok: true, cancelled: false })), 'saved');
+ assert.equal(await executeDesktopSave(() => ({ ok: false, cancelled: true })), 'cancelled');
+ assert.equal(await executeDesktopSave(() => ({ ok: false, cancelled: false })), 'failed');
+});
+
+test('executeDesktopSave converts rejected desktop API calls into failed results', async () => {
+ const originalConsoleError = console.error;
+ const errors = [];
+ console.error = (...args) => errors.push(args);
+ try {
+ assert.equal(await executeDesktopSave(() => Promise.reject(new Error('bridge unavailable'))), 'failed');
+ } finally {
+ console.error = originalConsoleError;
+ }
+ assert.equal(errors.length, 1);
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/historyPagination.test.mjs b/jiuwenswarm/channels/web/frontend/tests/historyPagination.test.mjs
new file mode 100644
index 0000000000..1ec68de05b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/historyPagination.test.mjs
@@ -0,0 +1,122 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { canLoadOlderHistory, prefetchHistoryPages, shouldShowHistoryRetry } from '../node_modules/.cache/history-pagination/features/historyPagination.js';
+
+test('offers retry while older history remains after a failed request', () => {
+ const state = {
+ loadedPages: 1,
+ totalPages: 3,
+ loadingMore: false,
+ prepending: false,
+ retryAvailable: true,
+ };
+
+ assert.equal(canLoadOlderHistory(state), true);
+ assert.equal(shouldShowHistoryRetry(state), true);
+});
+
+test('marks background prefetch as failed when page two does not return', async () => {
+ const requestedPages = [];
+ const appliedPages = [];
+
+ const outcome = await prefetchHistoryPages({
+ initialLoadedPages: 1,
+ initialTotalPages: 3,
+ isCurrent: () => true,
+ fetchPage: async pageIdx => {
+ requestedPages.push(pageIdx);
+ return null;
+ },
+ applyPage: page => {
+ appliedPages.push(page.pageIdx);
+ },
+ waitForNextPaint: async () => {},
+ });
+
+ assert.equal(outcome, 'failed');
+ assert.deepEqual(requestedPages, [2]);
+ assert.deepEqual(appliedPages, []);
+});
+
+test('offers retry when any later page fails before history is complete', async () => {
+ const requestedPages = [];
+ const appliedPages = [];
+
+ const outcome = await prefetchHistoryPages({
+ initialLoadedPages: 1,
+ initialTotalPages: 4,
+ isCurrent: () => true,
+ fetchPage: async pageIdx => {
+ requestedPages.push(pageIdx);
+ return pageIdx === 3
+ ? null
+ : {
+ pageIdx,
+ totalPages: 4,
+ };
+ },
+ applyPage: page => {
+ appliedPages.push(page.pageIdx);
+ },
+ waitForNextPaint: async () => {},
+ });
+
+ assert.equal(outcome, 'failed');
+ assert.deepEqual(requestedPages, [2, 3]);
+ assert.deepEqual(appliedPages, [2]);
+ assert.equal(
+ shouldShowHistoryRetry({
+ loadedPages: 2,
+ totalPages: 4,
+ loadingMore: false,
+ prepending: false,
+ retryAvailable: true,
+ }),
+ true,
+ );
+});
+
+test('continues automatic prefetch after a successful retry', async () => {
+ const appliedPages = [];
+
+ const outcome = await prefetchHistoryPages({
+ initialLoadedPages: 2,
+ initialTotalPages: 3,
+ isCurrent: () => true,
+ fetchPage: async pageIdx => ({
+ pageIdx,
+ totalPages: 3,
+ }),
+ applyPage: page => {
+ appliedPages.push(page.pageIdx);
+ },
+ waitForNextPaint: async () => {},
+ });
+
+ assert.equal(outcome, 'completed');
+ assert.deepEqual(appliedPages, [3]);
+});
+
+test('does not expose retry while a request is active or history is complete', () => {
+ assert.equal(
+ shouldShowHistoryRetry({
+ loadedPages: 1,
+ totalPages: 3,
+ loadingMore: true,
+ prepending: false,
+ retryAvailable: true,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldShowHistoryRetry({
+ loadedPages: 3,
+ totalPages: 3,
+ loadingMore: false,
+ prepending: false,
+ retryAvailable: true,
+ }),
+ false,
+ );
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/presentationPreview.test.mjs b/jiuwenswarm/channels/web/frontend/tests/presentationPreview.test.mjs
new file mode 100644
index 0000000000..e3883452eb
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/presentationPreview.test.mjs
@@ -0,0 +1,311 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import JSZip from 'jszip';
+import en from '../src/i18n/locales/en.json' with { type: 'json' };
+import zh from '../src/i18n/locales/zh.json' with { type: 'json' };
+import { previewKind } from '../node_modules/.cache/presentation-preview/filePreviewModel.js';
+import {
+ OoxmlArchiveLimitError,
+ PRESENTATION_ARCHIVE_LIMITS,
+ SPREADSHEET_ARCHIVE_LIMITS,
+ inspectOoxmlArchive,
+} from '../node_modules/.cache/presentation-preview/ooxmlArchiveLimits.js';
+import { parsePresentation } from '../node_modules/.cache/presentation-preview/pptxPresentationParser.js';
+import { presentationLineHeight } from '../node_modules/.cache/presentation-preview/pptxPreviewModel.js';
+
+function assertClose(actual, expected) {
+ assert.ok(Math.abs(actual - expected) < 1e-9, `expected ${actual} to be close to ${expected}`);
+}
+
+function presentationArchive(slides, additionalFiles = {}) {
+ const archive = new JSZip();
+ const slideIds = slides.map((_, index) => `<p:sldId id="${256 + index}" r:id="rId${index + 1}"/>`).join('');
+ const relationships = slides
+ .map(
+ (_, index) =>
+ `<Relationship Id="rId${index + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide${index + 1}.xml"/>`,
+ )
+ .join('');
+
+ archive.file(
+ 'ppt/presentation.xml',
+ `<p:presentation xmlns:p="p" xmlns:r="r"><p:sldSz cx="9144000" cy="6858000"/><p:sldIdLst>${slideIds}</p:sldIdLst></p:presentation>`,
+ );
+ archive.file('ppt/_rels/presentation.xml.rels', `<Relationships xmlns="r">${relationships}</Relationships>`);
+ slides.forEach((slide, index) => archive.file(`ppt/slides/slide${index + 1}.xml`, slide));
+ Object.entries(additionalFiles).forEach(([path, contents]) => archive.file(path, contents));
+ return archive;
+}
+
+test('recognizes read-only OOXML presentation formats', () => {
+ assert.equal(previewKind({ name: 'proposal.pptx' }), 'presentation');
+ assert.equal(previewKind({ name: 'board-deck.pptm' }), 'presentation');
+ assert.equal(previewKind({ name: 'legacy.ppt' }), 'unsupported');
+ assert.equal(previewKind({ name: 'deck.bin', mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }), 'presentation');
+});
+
+test('uses font metrics when DrawingML omits explicit line spacing', () => {
+ assert.equal(presentationLineHeight(undefined), 'normal');
+ assert.equal(presentationLineHeight({ kind: 'relative', value: 1.2 }), 1.2);
+ assert.equal(presentationLineHeight({ kind: 'absolute', value: 24 }), '24px');
+});
+
+test('keeps presentation preview messages complete in Chinese and English', () => {
+ const keys = [
+ 'presentationPreviewFailed',
+ 'presentationResourceLimitExceeded',
+ 'presentationTooLarge',
+ 'presentationSlides',
+ 'presentationPage',
+ 'presentationSlideIncomplete',
+ 'presentationStructureInvalid',
+ 'presentationGoToSlide',
+ 'presentationPreviousSlide',
+ 'presentationNextSlide',
+ 'presentationZoomOut',
+ 'presentationZoomIn',
+ 'presentationZoomLevel',
+ ];
+ for (const locale of [en, zh]) keys.forEach(key => assert.equal(typeof locale.artifacts[key], 'string', `${key} is missing`));
+ assert.match(en.artifacts.presentationTooLarge, /\{\{size\}\}/);
+ assert.match(zh.artifacts.presentationPage, /\{\{current\}\}/);
+ assert.match(zh.artifacts.presentationPage, /\{\{total\}\}/);
+});
+
+test('enforces presentation and spreadsheet archive limits before decompression', () => {
+ assert.equal(PRESENTATION_ARCHIVE_LIMITS.maxCompressedBytes, 50 * 1024 * 1024);
+ assert.equal(PRESENTATION_ARCHIVE_LIMITS.maxEntries, 5_000);
+ assert.equal(PRESENTATION_ARCHIVE_LIMITS.maxEntryUncompressedBytes, 64 * 1024 * 1024);
+ assert.equal(PRESENTATION_ARCHIVE_LIMITS.maxTotalUncompressedBytes, 200 * 1024 * 1024);
+ assert.equal(SPREADSHEET_ARCHIVE_LIMITS.maxTotalUncompressedBytes, 128 * 1024 * 1024);
+
+ assert.throws(
+ () => inspectOoxmlArchive(new ArrayBuffer(11), { ...PRESENTATION_ARCHIVE_LIMITS, maxCompressedBytes: 10 }),
+ error => error instanceof OoxmlArchiveLimitError && error.limit === 'compressed-size',
+ );
+ assert.throws(
+ () => inspectOoxmlArchive(declaredArchive([64 * 1024 * 1024 + 1]), PRESENTATION_ARCHIVE_LIMITS),
+ error => error instanceof OoxmlArchiveLimitError && error.limit === 'entry-size',
+ );
+ assert.doesNotThrow(() => inspectOoxmlArchive(declaredArchive([64, 64].map(size => size * 1024 * 1024)), SPREADSHEET_ARCHIVE_LIMITS));
+ assert.throws(
+ () => inspectOoxmlArchive(declaredArchive([50, 50, 50].map(size => size * 1024 * 1024)), SPREADSHEET_ARCHIVE_LIMITS),
+ error => error instanceof OoxmlArchiveLimitError && error.limit === 'uncompressed-size',
+ );
+ assert.doesNotThrow(() => inspectOoxmlArchive(declaredArchive([50, 50, 50, 50].map(size => size * 1024 * 1024)), PRESENTATION_ARCHIVE_LIMITS));
+ assert.throws(
+ () => inspectOoxmlArchive(declaredArchive([51, 50, 50, 50].map(size => size * 1024 * 1024)), PRESENTATION_ARCHIVE_LIMITS),
+ error => error instanceof OoxmlArchiveLimitError && error.limit === 'uncompressed-size',
+ );
+ assert.throws(
+ () => inspectOoxmlArchive(declaredArchive([], 5_001), PRESENTATION_ARCHIVE_LIMITS),
+ error => error instanceof OoxmlArchiveLimitError && error.limit === 'entry-count',
+ );
+
+ const zip64Archive = declaredZip64Archive(32 * 1024 * 1024);
+ const wrappedArchive = new Uint8Array(zip64Archive.byteLength + 8);
+ wrappedArchive.set(new Uint8Array(zip64Archive), 4);
+ assert.doesNotThrow(() => inspectOoxmlArchive(wrappedArchive.subarray(4, -4), PRESENTATION_ARCHIVE_LIMITS));
+});
+
+function declaredArchive(uncompressedSizes, claimedEntryCount = uncompressedSizes.length) {
+ const entryLength = 47;
+ const directorySize = entryLength * uncompressedSizes.length;
+ const buffer = new ArrayBuffer(directorySize + 22);
+ const view = new DataView(buffer);
+ uncompressedSizes.forEach((uncompressedSize, index) => {
+ const offset = index * entryLength;
+ view.setUint32(offset, 0x02014b50, true);
+ view.setUint32(offset + 24, uncompressedSize, true);
+ view.setUint16(offset + 28, 1, true);
+ new Uint8Array(buffer, offset + 46, 1)[0] = 65 + (index % 26);
+ });
+ view.setUint32(directorySize, 0x06054b50, true);
+ view.setUint16(directorySize + 8, claimedEntryCount, true);
+ view.setUint16(directorySize + 10, claimedEntryCount, true);
+ view.setUint32(directorySize + 12, directorySize, true);
+ return buffer;
+}
+
+function declaredZip64Archive(uncompressedSize) {
+ const directorySize = 67;
+ const zip64EndOffset = directorySize;
+ const locatorOffset = zip64EndOffset + 56;
+ const endOffset = locatorOffset + 20;
+ const buffer = new ArrayBuffer(endOffset + 22);
+ const view = new DataView(buffer);
+
+ view.setUint32(0, 0x02014b50, true);
+ view.setUint32(20, 0xffffffff, true);
+ view.setUint32(24, 0xffffffff, true);
+ view.setUint16(28, 1, true);
+ view.setUint16(30, 20, true);
+ new Uint8Array(buffer, 46, 1)[0] = 65;
+ view.setUint16(47, 0x0001, true);
+ view.setUint16(49, 16, true);
+ view.setBigUint64(51, BigInt(uncompressedSize), true);
+ view.setBigUint64(59, 0n, true);
+
+ view.setUint32(zip64EndOffset, 0x06064b50, true);
+ view.setBigUint64(zip64EndOffset + 4, 44n, true);
+ view.setBigUint64(zip64EndOffset + 24, 1n, true);
+ view.setBigUint64(zip64EndOffset + 32, 1n, true);
+ view.setBigUint64(zip64EndOffset + 40, BigInt(directorySize), true);
+
+ view.setUint32(locatorOffset, 0x07064b50, true);
+ view.setBigUint64(locatorOffset + 8, BigInt(zip64EndOffset), true);
+ view.setUint32(locatorOffset + 16, 1, true);
+
+ view.setUint32(endOffset, 0x06054b50, true);
+ view.setUint16(endOffset + 8, 0xffff, true);
+ view.setUint16(endOffset + 10, 0xffff, true);
+ view.setUint32(endOffset + 12, 0xffffffff, true);
+ view.setUint32(endOffset + 16, 0xffffffff, true);
+ return buffer;
+}
+
+test('parses an OOXML slide into a stable browser presentation model', async () => {
+ const archive = presentationArchive([
+ `<?xml version="1.0" encoding="UTF-8"?>
+ <p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Overview"><p:bg><p:bgPr><a:solidFill><a:srgbClr val="123456"/></a:solidFill></p:bgPr></p:bg><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Title"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
+ <p:spPr><a:xfrm><a:off x="914400" y="457200"/><a:ext cx="7315200" cy="914400"/></a:xfrm><a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 30000"/></a:avLst></a:prstGeom><a:solidFill><a:srgbClr val="123456"/></a:solidFill></p:spPr>
+ <p:txBody><a:bodyPr><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:pPr algn="ctr" marL="342900" indent="-285750"><a:lnSpc><a:spcPct val="120000"/></a:lnSpc><a:spcBef><a:spcPts val="600"/></a:spcBef><a:defRPr sz="2400" spc="125" kern="1200" b="1"><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></a:defRPr></a:pPr><a:r><a:t>Quarterly review &amp; design &lt; 1%</a:t></a:r></a:p></p:txBody>
+ </p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ ]);
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ assert.equal(presentation.width, 960);
+ assert.equal(presentation.height, 720);
+ assert.equal(presentation.slides.length, 1);
+ assert.equal(presentation.slides[0].name, 'Overview');
+ assert.deepEqual(presentation.slides[0].background, { kind: 'solid', color: '#123456', transparency: undefined });
+ assert.equal(presentation.slides[0].nodes.length, 1);
+ const shape = presentation.slides[0].nodes[0];
+ assert.equal(shape.type, 'shape');
+ assert.equal(shape.geometry, 'roundRect');
+ assert.deepEqual(shape.adjustments, { adj: 30000 });
+ assert.equal(shape.fill.color, '#123456');
+ assert.equal(shape.text.autoFit, 'shrink');
+ assert.equal(shape.text.paragraphs[0].runs[0].text, 'Quarterly review & design < 1%');
+ assert.equal(shape.text.paragraphs[0].runs[0].fontSize, 32);
+ assertClose(shape.text.paragraphs[0].runs[0].characterSpacing, 5 / 3);
+ assert.equal(shape.text.paragraphs[0].runs[0].kerningThreshold, 16);
+ assert.equal(shape.text.paragraphs[0].runs[0].color, '#ABCDEF');
+ assert.equal(shape.text.paragraphs[0].marginLeft, 36);
+ assert.equal(shape.text.paragraphs[0].indent, -30);
+ assert.deepEqual(shape.text.paragraphs[0].spaceBefore, { kind: 'absolute', value: 8 });
+ assert.deepEqual(shape.text.paragraphs[0].lineSpacing, { kind: 'relative', value: 1.2 });
+});
+
+test('applies stored normal-autofit font and line-spacing scales', async () => {
+ const archive = presentationArchive([
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Autofit"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
+ <p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="9144000" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr>
+ <p:txBody><a:bodyPr><a:normAutofit fontScale="75000" lnSpcReduction="20000"/></a:bodyPr><a:lstStyle/><a:p>
+ <a:pPr><a:lnSpc><a:spcPct val="120000"/></a:lnSpc><a:defRPr sz="2400"/></a:pPr><a:r><a:t>Scaled text</a:t></a:r>
+ </a:p></p:txBody>
+ </p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ ]);
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ const text = presentation.slides[0].nodes[0].text;
+ assert.equal(text.autoFit, 'shrink');
+ assert.equal(text.paragraphs[0].runs[0].fontSize, 24);
+ assertClose(text.paragraphs[0].lineSpacing.value, 0.96);
+});
+
+test('parses table cell text and built-in row banding from standard OOXML', async () => {
+ const archive = presentationArchive(
+ [
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Weather"><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="2" name="Daily forecast"/><p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>
+ <p:xfrm><a:off x="0" y="0"/><a:ext cx="9144000" cy="914400"/></p:xfrm>
+ <a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table"><a:tbl>
+ <a:tblPr firstRow="1" bandRow="1"><a:tableStyleId>{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}</a:tableStyleId></a:tblPr><a:tblGrid><a:gridCol w="9144000"/></a:tblGrid><a:tr h="914400"><a:tc>
+ <a:txBody><a:bodyPr lIns="45720" rIns="45720" tIns="22860" bIns="22860"><a:spAutoFit/></a:bodyPr><a:lstStyle/>
+ <a:p><a:pPr><a:defRPr sz="1400" lang="zh-CN" b="1"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:defRPr></a:pPr><a:r><a:t>日期</a:t></a:r></a:p>
+ </a:txBody><a:tcPr><a:solidFill><a:srgbClr val="2196F3"/></a:solidFill></a:tcPr>
+ </a:tc></a:tr><a:tr h="914400"><a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>7月23日</a:t></a:r></a:p></a:txBody><a:tcPr/></a:tc></a:tr><a:tr h="914400"><a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>7月24日</a:t></a:r></a:p></a:txBody><a:tcPr/></a:tc></a:tr></a:tbl></a:graphicData></a:graphic>
+ </p:graphicFrame>
+ </p:spTree></p:cSld></p:sld>`,
+ ],
+ {
+ 'ppt/slides/_rels/slide1.xml.rels':
+ '<Relationships xmlns="r"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/></Relationships>',
+ 'ppt/slideLayouts/slideLayout1.xml': '<p:sldLayout xmlns:p="p"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/></p:spTree></p:cSld></p:sldLayout>',
+ 'ppt/slideLayouts/_rels/slideLayout1.xml.rels':
+ '<Relationships xmlns="r"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/></Relationships>',
+ 'ppt/slideMasters/slideMaster1.xml': '<p:sldMaster xmlns:p="p"><p:cSld><p:spTree><p:nvGrpSpPr/><p:grpSpPr/></p:spTree></p:cSld></p:sldMaster>',
+ 'ppt/slideMasters/_rels/slideMaster1.xml.rels':
+ '<Relationships xmlns="r"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/></Relationships>',
+ 'ppt/theme/theme1.xml':
+ '<a:theme xmlns:a="a"><a:themeElements><a:clrScheme name="Test"><a:accent1><a:srgbClr val="4F81BD"/></a:accent1></a:clrScheme><a:fontScheme name="Test"><a:majorFont><a:latin typeface="Aptos Display"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Aptos"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Hans" typeface="宋体"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>',
+ },
+ );
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ const table = presentation.slides[0].nodes[0];
+ assert.equal(table.type, 'table');
+ const text = table.rows[0].cells[0].text;
+ assert.equal(text.paragraphs[0].runs[0].text, '日期');
+ assertClose(text.paragraphs[0].runs[0].fontSize, 56 / 3);
+ assert.equal(text.paragraphs[0].runs[0].fontFamily, 'Aptos');
+ assert.equal(text.paragraphs[0].runs[0].eastAsianFontFamily, '宋体');
+ assert.equal(text.paragraphs[0].runs[0].color, '#FFFFFF');
+ assert.equal(text.autoFit, 'resize');
+ assert.deepEqual(text.margin, { left: 4.8, right: 4.8, top: 2.4, bottom: 2.4 });
+ assert.equal(table.rows[1].cells[0].fill.color, '#D0D8E8');
+ assert.equal(table.rows[2].cells[0].fill.color, '#E9EDF4');
+});
+
+test('renders valid slides and rejects invalid slide XML without repairing it', async () => {
+ const archive = presentationArchive([
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Valid"><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Visible"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="123456"/></a:solidFill></p:spPr></p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Invalid"><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Must not render"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>Research & Development</a:t></a:r></a:p></p:txBody></p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ ]);
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ assert.equal(presentation.slides.length, 2);
+ assert.equal(presentation.slides[0].status, undefined);
+ assert.equal(presentation.slides[0].nodes.length, 1);
+ assert.equal(presentation.slides[0].nodes[0].name, 'Visible');
+ assert.equal(presentation.slides[1].status, 'invalid');
+ assert.equal(presentation.slides[1].nodes.length, 0);
+});
+
+test('leaves an unreadable slide blank instead of rendering a partial slide', async () => {
+ const archive = presentationArchive([
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Unreadable"><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Visible"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr></p:sp>
+ <p:sp><p:nvSpPr><p:cNvPr id="3" name="Broken"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>1 < 2</a:t></a:r></a:p></p:txBody></p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ ]);
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ assert.equal(presentation.slides.length, 1);
+ assert.equal(presentation.slides[0].status, 'invalid');
+ assert.equal(presentation.slides[0].nodes.length, 0);
+});
+
+test('keeps unsupported objects out of the slide canvas and reports the page in the header', async () => {
+ const archive = presentationArchive([
+ `<p:sld xmlns:p="p" xmlns:a="a"><p:cSld name="Mixed"><p:spTree>
+ <p:nvGrpSpPr/><p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="Visible"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:prstGeom prst="rect"/></p:spPr></p:sp>
+ <p:sp><p:nvSpPr><p:cNvPr id="3" name="Unsupported"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm><a:custGeom/></p:spPr></p:sp>
+ </p:spTree></p:cSld></p:sld>`,
+ ]);
+ const presentation = await parsePresentation(await archive.generateAsync({ type: 'arraybuffer' }));
+ assert.equal(presentation.slides[0].status, 'incomplete');
+ assert.equal(presentation.slides[0].nodes.length, 1);
+ assert.equal(presentation.slides[0].nodes[0].name, 'Visible');
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/spreadsheetPreview.test.mjs b/jiuwenswarm/channels/web/frontend/tests/spreadsheetPreview.test.mjs
new file mode 100644
index 0000000000..b3fde91072
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/spreadsheetPreview.test.mjs
@@ -0,0 +1,239 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ExcelJS from 'exceljs';
+
+import {
+ artifactBinaryPreviewUrl,
+ artifactDownloadUrl,
+ artifactTextPreviewUrl,
+ previewKind,
+} from '../node_modules/.cache/spreadsheet-preview/filePreviewModel.js';
+import {
+ MAX_SPREADSHEET_PREVIEW_BYTES,
+ axisIndexAtOffset,
+ buildAxisMetrics,
+ columnLabel,
+ parseCellRange,
+} from '../node_modules/.cache/spreadsheet-preview/spreadsheetPreviewModel.js';
+import {
+ categoryCenter,
+ categoryPoint,
+ clusteredCategoryBand,
+ ensureNonZeroAxisSpan,
+ linearPosition,
+ spanFromBaseline,
+} from '../node_modules/.cache/spreadsheet-preview/chartGeometry.js';
+import { parseSpreadsheetWorkbook } from '../node_modules/.cache/spreadsheet-preview/spreadsheetWorkbookParser.js';
+
+test('recognizes OOXML workbooks but leaves legacy XLS files unsupported', () => {
+ assert.equal(previewKind({ name: 'report.xlsx' }), 'spreadsheet');
+ assert.equal(previewKind({ name: 'REPORT.XLSX', mimeType: 'application/octet-stream' }), 'spreadsheet');
+ assert.equal(previewKind({ name: 'automation.xlsm' }), 'spreadsheet');
+ assert.equal(previewKind({ name: 'automation.bin', mimeType: 'application/vnd.ms-excel.sheet.macroEnabled.12' }), 'spreadsheet');
+ assert.equal(
+ previewKind({
+ name: 'report.bin',
+ mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ }),
+ 'spreadsheet',
+ );
+ assert.equal(previewKind({ name: 'legacy.xls' }), 'unsupported');
+ assert.equal(previewKind({ name: 'data.csv' }), 'text');
+});
+
+test('uses signed download URLs without decoding them into local file paths', () => {
+ const signedResource = {
+ downloadUrl: '/file-api/download?token=signed-token',
+ path: '/tmp/report.xlsx',
+ };
+ assert.equal(artifactDownloadUrl(signedResource), '/file-api/download?token=signed-token');
+ assert.equal(artifactBinaryPreviewUrl(signedResource, 'https://example.test'), '/file-api/download?token=signed-token&inline=1');
+ assert.equal(artifactTextPreviewUrl(signedResource, 'https://example.test'), '/file-api/download?token=signed-token&inline=1');
+
+ const taskResource = { path: 'agent/workspace/report.xlsx' };
+ assert.equal(artifactDownloadUrl(taskResource), '/file-api/raw-file?path=agent%2Fworkspace%2Freport.xlsx');
+ assert.equal(artifactBinaryPreviewUrl(taskResource, 'https://example.test'), '/file-api/raw-file?path=agent%2Fworkspace%2Freport.xlsx');
+ assert.equal(artifactTextPreviewUrl(taskResource, 'https://example.test'), '/file-api/file-content?path=agent%2Fworkspace%2Freport.xlsx&encoding=auto');
+});
+
+test('builds exact virtual-axis offsets including hidden rows', () => {
+ const metrics = buildAxisMetrics(4, 20, [
+ { index: 2, size: 36 },
+ { index: 3, size: 0 },
+ ]);
+ assert.deepEqual(Array.from(metrics.offsets), [0, 20, 56, 56, 76]);
+ assert.equal(metrics.totalSize, 76);
+ assert.equal(axisIndexAtOffset(metrics.offsets, 0), 1);
+ assert.equal(axisIndexAtOffset(metrics.offsets, 20), 2);
+ assert.equal(axisIndexAtOffset(metrics.offsets, 55), 2);
+ assert.equal(axisIndexAtOffset(metrics.offsets, 56), 4);
+});
+
+test('converts spreadsheet coordinates without truncating the Excel range', () => {
+ assert.equal(columnLabel(1), 'A');
+ assert.equal(columnLabel(26), 'Z');
+ assert.equal(columnLabel(27), 'AA');
+ assert.equal(columnLabel(16384), 'XFD');
+ assert.deepEqual(parseCellRange('$B$2:$XFD$1048576'), {
+ top: 2,
+ left: 2,
+ bottom: 1048576,
+ right: 16384,
+ });
+ assert.equal(MAX_SPREADSHEET_PREVIEW_BYTES, 50 * 1024 * 1024);
+});
+
+test('maps signed chart values from the zero baseline on either axis', () => {
+ const horizontalBaseline = linearPosition(0, -40, 100, 0, 140);
+ assert.deepEqual(spanFromBaseline(linearPosition(100, -40, 100, 0, 140), horizontalBaseline), { start: 40, size: 100 });
+ assert.deepEqual(spanFromBaseline(linearPosition(10, -40, 100, 0, 140), horizontalBaseline), { start: 40, size: 10 });
+ assert.deepEqual(spanFromBaseline(linearPosition(-40, -40, 100, 0, 140), horizontalBaseline), { start: 0, size: 40 });
+
+ const verticalBaseline = linearPosition(0, -40, 100, 280, 0);
+ const positiveColumn = spanFromBaseline(linearPosition(100, -40, 100, 280, 0), verticalBaseline);
+ const negativeColumn = spanFromBaseline(linearPosition(-40, -40, 100, 280, 0), verticalBaseline);
+ assert.deepEqual(positiveColumn, { start: 0, size: 200 });
+ assert.deepEqual(negativeColumn, { start: 200, size: 80 });
+});
+
+test('centres categories and allocates non-overlapping clustered bands', () => {
+ assert.equal(categoryCenter(1, 4, 0, 400), 150);
+ assert.equal(categoryPoint(0, 4, 0, 400), 0);
+ assert.equal(categoryPoint(3, 4, 0, 400), 400);
+ assert.equal(categoryPoint(0, 1, 0, 400), 200);
+ assert.deepEqual(clusteredCategoryBand(1, 4, 0, 2, 0, 400), { start: 114, size: 36 });
+ assert.deepEqual(clusteredCategoryBand(1, 4, 1, 2, 0, 400), { start: 150, size: 36 });
+});
+
+test('keeps zero as the upper boundary for an all-negative chart', () => {
+ assert.deepEqual(ensureNonZeroAxisSpan(-40, 0, 10), { minimum: -40, maximum: 0 });
+ assert.deepEqual(ensureNonZeroAxisSpan(0, 0, 10), { minimum: 0, maximum: 10 });
+});
+
+test('parses workbook sheets, formatting, merges and cached formula results', async () => {
+ const source = new ExcelJS.Workbook();
+ source.views = [{ activeTab: 1 }];
+ const summary = source.addWorksheet('汇总');
+ const details = source.addWorksheet('Details');
+
+ summary.getCell('A1').value = 'Revenue';
+ summary.getCell('A1').font = { bold: true, size: 21, color: { argb: 'FFFFFFFF' } };
+ summary.getCell('A1').fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF1F4E78' } };
+ summary.getCell('B2').value = 0.125;
+ summary.getCell('B2').numFmt = '0.00%';
+ summary.getCell('C3').value = new Date('2024-01-01T00:00:00.000Z');
+ summary.getCell('C3').numFmt = 'yyyy-mm-dd';
+ summary.getCell('D4').value = { formula: 'SUM(1,2)', result: 3 };
+ summary.mergeCells('A5:B6');
+ summary.getCell('A5').value = 'Merged';
+ summary.getCell('A1').note = 'Source-controlled note';
+ summary.autoFilter = 'A1:B2';
+ summary.getRow(2).height = 30;
+ summary.getColumn(2).width = 18;
+ details.getCell('A1').value = 'Second sheet';
+ details.getCell('A2').value = 'Theme colors';
+ details.getCell('A2').font = { color: { theme: 1 } };
+ details.getCell('A2').fill = { type: 'pattern', pattern: 'solid', fgColor: { theme: 0 } };
+
+ const buffer = await source.xlsx.writeBuffer();
+ const parsed = await parseSpreadsheetWorkbook(buffer);
+
+ assert.deepEqual(
+ parsed.sheets.map(sheet => sheet.name),
+ ['汇总', 'Details'],
+ );
+ assert.equal(parsed.activeSheetIndex, 1);
+ assert.deepEqual(parsed.sheets[0].merges, [{ top: 5, left: 1, bottom: 6, right: 2 }]);
+ assert.equal(parsed.sheets[0].rowCount, 6);
+ assert.equal(parsed.sheets[0].columnCount, 4);
+ assert.deepEqual(parsed.sheets[0].autoFilter, { top: 1, left: 1, bottom: 2, right: 2 });
+ assert.deepEqual(parsed.sheets[0].comments, [{ row: 1, column: 1, comment: { author: 'Author', text: 'Source-controlled note' } }]);
+ assert.ok(parsed.sheets[0].rowSizes.some(item => item.index === 2 && item.size === 40));
+ assert.ok(parsed.sheets[0].columnSizes.some(item => item.index === 2 && item.size > 100));
+
+ const cells = new Map(parsed.sheets[0].rows.flatMap(row => row.cells.map(cell => [`${cell.row}:${cell.column}`, cell])));
+ assert.equal(cells.get('2:2').text, '12.50%');
+ assert.equal(cells.get('3:3').text, '2024-01-01');
+ assert.equal(cells.get('4:4').text, '3');
+ assert.equal(cells.get('4:4').formula, 'SUM(1,2)');
+ assert.equal(cells.get('4:4').alignRight, true);
+
+ const titleStyle = parsed.styles[cells.get('1:1').styleId];
+ assert.equal(titleStyle.fontWeight, 700);
+ assert.equal(titleStyle.lineHeight, 'normal');
+ assert.equal(titleStyle.color, '#FFFFFF');
+ assert.equal(titleStyle.backgroundColor, '#1F4E78');
+ const themeCell = parsed.sheets[1].rows.flatMap(row => row.cells).find(cell => cell.row === 2 && cell.column === 1);
+ const themeStyle = parsed.styles[themeCell.styleId];
+ assert.equal(themeStyle.color, '#000000');
+ assert.equal(themeStyle.backgroundColor, '#FFFFFF');
+});
+
+test('keeps a formula visible when the workbook has no cached result', async () => {
+ const source = new ExcelJS.Workbook();
+ const sheet = source.addWorksheet('Formula');
+ sheet.getCell('A1').value = { formula: 'NOW()' };
+ const parsed = await parseSpreadsheetWorkbook(await source.xlsx.writeBuffer());
+ assert.equal(parsed.sheets[0].rows[0].cells[0].text, '=NOW()');
+});
+
+test('applies common conditional-formatting rules without recalculating formulas', async () => {
+ const source = new ExcelJS.Workbook();
+ const sheet = source.addWorksheet('Conditional formatting');
+ sheet.getCell('A1').value = 4;
+ sheet.getCell('A2').value = 9;
+ sheet.addConditionalFormatting({
+ ref: 'A1:A2',
+ rules: [
+ {
+ type: 'cellIs',
+ operator: 'greaterThan',
+ formulae: ['5'],
+ style: { fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: '00F4CCCC' } } },
+ },
+ ],
+ });
+ const parsed = await parseSpreadsheetWorkbook(await source.xlsx.writeBuffer());
+ const highCell = parsed.sheets[0].rows.flatMap(row => row.cells).find(cell => cell.row === 2 && cell.column === 1);
+ assert.equal(parsed.styles[highCell.styleId].backgroundColor, '#F4CCCC');
+});
+
+test('preserves opaque OOXML colours and embedded images', async () => {
+ const source = new ExcelJS.Workbook();
+ const sheet = source.addWorksheet('Assets');
+ sheet.getCell('A1').value = 'Brand';
+ sheet.getCell('A1').fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '0000AEEF' } };
+ const imageId = source.addImage({
+ base64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScL6YQAAAABJRU5ErkJggg==',
+ extension: 'png',
+ });
+ sheet.addImage(imageId, 'B2:C4');
+
+ const parsed = await parseSpreadsheetWorkbook(await source.xlsx.writeBuffer());
+ assert.equal(parsed.styles[parsed.sheets[0].rows[0].cells[0].styleId].backgroundColor, '#00AEEF');
+ assert.equal(parsed.sheets[0].images.length, 1);
+ assert.match(parsed.sheets[0].images[0].source, /^data:image\/png;base64,/);
+ assert.equal(parsed.sheets[0].images[0].anchor.fromColumn, 2);
+ assert.equal(parsed.sheets[0].images[0].anchor.fromRow, 2);
+});
+
+test('keeps spreadsheet preview messages complete in Chinese and English', async () => {
+ const localeNames = ['zh', 'en'];
+ const keys = [
+ 'spreadsheetPreviewFailed',
+ 'spreadsheetResourceLimitExceeded',
+ 'spreadsheetTooLarge',
+ 'spreadsheetEmptyWorkbook',
+ 'spreadsheetEmptySheet',
+ 'spreadsheetSheetTabsLabel',
+ 'spreadsheetTableLabel',
+ ];
+
+ for (const localeName of localeNames) {
+ const locale = JSON.parse(await readFile(new URL(`../src/i18n/locales/${localeName}.json`, import.meta.url), 'utf8'));
+ keys.forEach(key => assert.equal(typeof locale.artifacts[key], 'string', `${localeName} is missing artifacts.${key}`));
+ assert.match(locale.artifacts.spreadsheetTooLarge, /\{\{size\}\}/);
+ assert.match(locale.artifacts.spreadsheetTableLabel, /\{\{sheet\}\}/);
+ }
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/teamPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/teamPanelState.test.mjs
index 739737abfc..dde1ecafb0 100644
--- a/jiuwenswarm/channels/web/frontend/tests/teamPanelState.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/teamPanelState.test.mjs
@@ -24,12 +24,14 @@ test('normalizeTeamPanelState keeps valid values', () => {
activeTab: 'planning',
activeDetailTab: 'group',
selectedMemberId: 'agent-1',
+ selectedArtifactId: 'artifact-1',
}),
{
expanded: true,
activeTab: 'planning',
activeDetailTab: 'group',
selectedMemberId: 'agent-1',
+ selectedArtifactId: 'artifact-1',
},
);
});
@@ -41,6 +43,7 @@ test('normalizeTeamPanelState falls back for invalid enum fields', () => {
activeTab: 'unknown-tab',
activeDetailTab: 123,
selectedMemberId: '',
+ selectedArtifactId: ' ',
}),
{
expanded: false,
diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.ts
index 2db97275d5..64dc3dece0 100644
--- a/jiuwenswarm/channels/web/frontend/vite.config.ts
+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts
@@ -4,6 +4,8 @@ import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
import { spawnSync } from 'child_process'
import { createHash } from 'node:crypto'
+import { createHmac, timingSafeEqual } from 'node:crypto'
+import type { ServerResponse } from 'http'
import path from 'path'
import fs from 'fs'
@@ -216,7 +218,20 @@ function decodeFileContent(raw: Buffer, requestedEncoding: string): { content: s
throw new Error('Unable to decode file with any known encoding')
}
-const RAW_FILE_CONTENT_TYPES: Record<string, string> = {
+const DOWNLOAD_CONTENT_TYPES: Record<string, string> = {
+ '.md': 'text/markdown; charset=utf-8',
+ '.markdown': 'text/markdown; charset=utf-8',
+ '.txt': 'text/plain; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.jsonl': 'application/x-ndjson; charset=utf-8',
+ '.csv': 'text/csv; charset=utf-8',
+ '.html': 'text/html; charset=utf-8',
+ '.htm': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.ts': 'text/plain; charset=utf-8',
+ '.tsx': 'text/plain; charset=utf-8',
+ '.py': 'text/plain; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
@@ -225,10 +240,69 @@ const RAW_FILE_CONTENT_TYPES: Record<string, string> = {
'.svg': 'image/svg+xml',
'.bmp': 'image/bmp',
'.avif': 'image/avif',
+ '.pdf': 'application/pdf',
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
-function rawFileContentType(filePath: string): string {
- return RAW_FILE_CONTENT_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream'
+function downloadContentType(filePath: string): string {
+ return DOWNLOAD_CONTENT_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream'
+}
+
+function handleFileStreamError(res: ServerResponse, error: NodeJS.ErrnoException): void {
+ if (res.headersSent) {
+ res.destroy(error)
+ return
+ }
+
+ res.statusCode = error.code === 'EACCES' || error.code === 'EPERM' ? 403 : 500
+ res.removeHeader('content-length')
+ res.removeHeader('content-disposition')
+ res.removeHeader('accept-ranges')
+ res.removeHeader('content-range')
+ res.setHeader('content-type', 'application/json; charset=utf-8')
+ res.end(JSON.stringify({
+ error: res.statusCode === 403 ? 'file_access_denied' : 'file_read_failed',
+ }))
+}
+
+function resolveFileDownloadSecret(): string | null {
+ const envSecret = process.env.JIUWENSWARM_FILE_DOWNLOAD_SECRET
+ if (envSecret && envSecret.length >= 32) return envSecret
+
+ const workspace = process.env.JIUWENSWARM_WORKSPACE || path.join(process.env.HOME || process.env.USERPROFILE || '', '.jiuwenswarm')
+ const secretPath = path.join(workspace, 'config', '.file_download_secret')
+ try {
+ const secret = fs.readFileSync(secretPath, 'utf8').trim()
+ return secret.length >= 32 ? secret : null
+ } catch {
+ return null
+ }
+}
+
+function validateFileDownloadToken(token: string): { path: string } | null {
+ const parts = token.split('.')
+ if (parts.length !== 2) return null
+ const [payloadBase64, signature] = parts
+
+ const secret = resolveFileDownloadSecret()
+ if (!secret) return null
+ const expected = createHmac('sha256', secret).update(payloadBase64).digest('hex')
+ const actual = Buffer.from(signature, 'hex')
+ const expectedBuffer = Buffer.from(expected, 'hex')
+ if (actual.length !== expectedBuffer.length || !timingSafeEqual(actual, expectedBuffer)) return null
+
+ try {
+ const payload = JSON.parse(Buffer.from(payloadBase64, 'base64url').toString('utf8')) as Record<string, unknown>
+ if (
+ typeof payload.path !== 'string' ||
+ !payload.path ||
+ typeof payload.sid !== 'string'
+ ) return null
+ return { path: payload.path }
+ } catch {
+ return null
+ }
}
/** WS proxy 中常见的、可安全忽略的 socket 错误码(跨平台) */
@@ -650,6 +724,95 @@ function devFileContentApi(): Plugin {
}
})
+ server.middlewares.use('/file-api/download', (req, res) => {
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ res.statusCode = 405
+ res.setHeader('content-type', 'application/json; charset=utf-8')
+ res.end(JSON.stringify({ error: 'method_not_allowed' }))
+ return
+ }
+
+ const url = new URL(req.url || '/file-api/download', 'http://localhost')
+ const token = url.searchParams.get('token') || ''
+ const payload = validateFileDownloadToken(token)
+ if (!payload) {
+ res.statusCode = 403
+ res.setHeader('content-type', 'application/json; charset=utf-8')
+ res.end(JSON.stringify({ error: 'invalid_or_expired_token' }))
+ return
+ }
+
+ let stat: fs.Stats
+ try {
+ stat = fs.statSync(payload.path)
+ } catch {
+ res.statusCode = 404
+ res.setHeader('content-type', 'application/json; charset=utf-8')
+ res.end(JSON.stringify({ error: 'file_not_found' }))
+ return
+ }
+ if (!stat.isFile()) {
+ res.statusCode = 404
+ res.setHeader('content-type', 'application/json; charset=utf-8')
+ res.end(JSON.stringify({ error: 'file_not_found' }))
+ return
+ }
+
+ const fileSize = stat.size
+ let start = 0
+ let end = Math.max(0, fileSize - 1)
+ let partial = false
+ const range = req.headers.range
+ if (range) {
+ if (!range.startsWith('bytes=') || range.includes(',') || fileSize === 0) {
+ res.statusCode = 416
+ res.setHeader('content-range', `bytes */${fileSize}`)
+ res.end()
+ return
+ }
+ const [startText, endText] = range.slice(6).split('-', 2)
+ try {
+ if (startText) {
+ start = Number(startText)
+ end = endText ? Number(endText) : end
+ } else {
+ const suffixLength = Number(endText)
+ if (!Number.isInteger(suffixLength) || suffixLength <= 0) throw new Error('invalid_suffix')
+ start = Math.max(0, fileSize - suffixLength)
+ }
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= fileSize || end < start) throw new Error('invalid_range')
+ end = Math.min(end, fileSize - 1)
+ partial = true
+ } catch {
+ res.statusCode = 416
+ res.setHeader('content-range', `bytes */${fileSize}`)
+ res.end()
+ return
+ }
+ }
+
+ const contentLength = fileSize === 0 ? 0 : end - start + 1
+ const inline = ['1', 'true'].includes((url.searchParams.get('inline') || '').toLowerCase())
+ const fileName = path.basename(payload.path)
+ res.statusCode = partial ? 206 : 200
+ res.setHeader('content-type', downloadContentType(payload.path))
+ res.setHeader('content-length', String(contentLength))
+ res.setHeader('accept-ranges', 'bytes')
+ res.setHeader('content-disposition', `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(fileName)}`)
+ res.setHeader('cache-control', 'no-store')
+ if (partial) res.setHeader('content-range', `bytes ${start}-${end}/${fileSize}`)
+ if (req.method === 'HEAD') {
+ res.end()
+ return
+ }
+ const fileStream = fs.createReadStream(payload.path, fileSize === 0 ? undefined : { start, end })
+ fileStream.once('error', (error) => {
+ server.config.logger.error(`[file-api] Failed to read ${payload.path}: ${(error as Error).message}`)
+ handleFileStreamError(res, error)
+ })
+ fileStream.pipe(res)
+ })
+
server.middlewares.use('/file-api/raw-file', (req, res) => {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.statusCode = 405
@@ -683,13 +846,18 @@ function devFileContentApi(): Plugin {
}
res.statusCode = 200
- res.setHeader('content-type', rawFileContentType(fullPath))
+ res.setHeader('content-type', downloadContentType(fullPath))
res.setHeader('cache-control', 'no-store')
if (req.method === 'HEAD') {
res.end()
return
}
- fs.createReadStream(fullPath).pipe(res)
+ const fileStream = fs.createReadStream(fullPath)
+ fileStream.once('error', (error) => {
+ server.config.logger.error(`[file-api] Failed to read ${fullPath}: ${(error as Error).message}`)
+ handleFileStreamError(res, error)
+ })
+ fileStream.pipe(res)
} catch (error) {
res.statusCode = 500
res.setHeader('content-type', 'application/json; charset=utf-8')
@@ -843,6 +1011,9 @@ const webTarget = `http://127.0.0.1:${webPort}`
export default defineConfig({
plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), devFileContentApi(), react(), svgr()],
+ optimizeDeps: {
+ include: ['exceljs', 'jszip', 'saxes', 'ssf'],
+ },
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.py
index 66fa4632b6..cf410314bd 100644
--- a/jiuwenswarm/server/runtime/session/session_history.py
+++ b/jiuwenswarm/server/runtime/session/session_history.py
@@ -337,10 +337,16 @@ def _is_team_relevant(item: dict[str, Any]) -> bool:
if not isinstance(et, str):
return False
if et in _TEAM_RELEVANT_EVENT_TYPES:
+ if et == "chat.file":
+ role = item.get("role")
+ return isinstance(role, str) and role.strip().lower() in {
+ "assistant",
+ "teammate",
+ }
if et in ("chat.tool_call", "chat.tracer_agent"):
mode = item.get("mode")
return isinstance(mode, str) and mode.strip().lower() == "team"
- if et in ("chat.final", "chat.tool_result", "chat.file"):
+ if et in ("chat.final", "chat.tool_result"):
role = item.get("role")
return isinstance(role, str) and role.strip().lower() == "teammate"
return True
diff --git a/tests/unit_tests/test_desktop_file_download.py b/tests/unit_tests/test_desktop_file_download.py
new file mode 100644
index 0000000000..ea7d1da9be
--- /dev/null
+++ b/tests/unit_tests/test_desktop_file_download.py
@@ -0,0 +1,123 @@
+from pathlib import Path
+import urllib.request
+
+from jiuwenswarm.channels.desktop import desktop_app
+
+
+def _runtime() -> desktop_app.DesktopRuntime:
+ return desktop_app.DesktopRuntime(
+ frontend_host="127.0.0.1",
+ ports={
+ "app": 19001,
+ "web": 19000,
+ "frontend": 5173,
+ "tui": 19002,
+ "third_party": 19003,
+ },
+ )
+
+
+def test_download_file_prompts_for_destination_before_downloading(
+ monkeypatch, tmp_path
+):
+ runtime = _runtime()
+ target_path = tmp_path / "report.pdf"
+ selected = []
+ downloaded = []
+ completed = []
+
+ def select_save_path(filename: str, file_types: tuple[str, ...]) -> Path:
+ selected.append((filename, file_types))
+ return target_path
+
+ def urlretrieve(url: str, path: Path) -> None:
+ downloaded.append((url, path))
+ path.write_bytes(b"pdf-content")
+
+ monkeypatch.setattr(runtime, "_select_save_path", select_save_path)
+ monkeypatch.setattr(runtime, "_show_download_complete", completed.append)
+ monkeypatch.setattr(urllib.request, "urlretrieve", urlretrieve)
+
+ result = runtime.download_file("https://example.test/report.pdf", "report.pdf")
+
+ assert result == {"ok": True, "cancelled": False}
+ assert selected == [("report.pdf", ())]
+ assert downloaded[0][0] == "https://example.test/report.pdf"
+ assert downloaded[0][1].parent == target_path.parent
+ assert downloaded[0][1].suffix == ".part"
+ assert target_path.read_bytes() == b"pdf-content"
+ assert list(tmp_path.glob(".*.part")) == []
+ assert completed == [str(target_path)]
+
+
+def test_download_file_stops_when_destination_selection_is_cancelled(monkeypatch):
+ runtime = _runtime()
+ download_started = False
+
+ monkeypatch.setattr(runtime, "_select_save_path", lambda filename, file_types: None)
+
+ def unexpected_download(url: str, path: Path) -> None:
+ nonlocal download_started
+ download_started = True
+
+ monkeypatch.setattr(urllib.request, "urlretrieve", unexpected_download)
+
+ result = runtime.download_file("https://example.test/report.pdf", "report.pdf")
+
+ assert result == {"ok": False, "cancelled": True}
+ assert download_started is False
+
+
+def test_download_file_rejects_invalid_suggested_filename(monkeypatch):
+ runtime = _runtime()
+
+ def reject_filename(filename: str, file_types: tuple[str, ...]) -> Path:
+ raise ValueError("empty_filename")
+
+ monkeypatch.setattr(runtime, "_select_save_path", reject_filename)
+
+ result = runtime.download_file("https://example.test/report.pdf", "")
+
+ assert result == {"ok": False, "cancelled": False}
+
+
+def test_download_file_reports_transfer_failure_and_preserves_existing_file(
+ monkeypatch, tmp_path
+):
+ runtime = _runtime()
+ target_path = tmp_path / "report.pdf"
+ target_path.write_bytes(b"existing-content")
+ completed = []
+
+ monkeypatch.setattr(
+ runtime, "_select_save_path", lambda filename, file_types: target_path
+ )
+ monkeypatch.setattr(runtime, "_show_download_complete", completed.append)
+
+ def fail_download(url: str, path: Path) -> None:
+ path.write_bytes(b"partial-content")
+ raise OSError("network disconnected")
+
+ monkeypatch.setattr(urllib.request, "urlretrieve", fail_download)
+
+ result = runtime.download_file("https://example.test/report.pdf", "report.pdf")
+
+ assert result == {"ok": False, "cancelled": False}
+ assert target_path.read_bytes() == b"existing-content"
+ assert list(tmp_path.glob(".*.part")) == []
+ assert completed == []
+
+
+def test_download_file_reports_destination_write_failure(monkeypatch, tmp_path):
+ runtime = _runtime()
+ missing_parent = tmp_path / "missing"
+ target_path = missing_parent / "report.pdf"
+
+ monkeypatch.setattr(
+ runtime, "_select_save_path", lambda filename, file_types: target_path
+ )
+
+ result = runtime.download_file("https://example.test/report.pdf", "report.pdf")
+
+ assert result == {"ok": False, "cancelled": False}
+ assert target_path.exists() is False
diff --git a/tests/unit_tests/test_session_history_empty_filter.py b/tests/unit_tests/test_session_history_empty_filter.py
index 7c06651732..27f1bee9e3 100644
--- a/tests/unit_tests/test_session_history_empty_filter.py
+++ b/tests/unit_tests/test_session_history_empty_filter.py
@@ -68,6 +68,21 @@ def test_append_history_skips_empty_chat_final_and_heartbeat(tmp_path, monkeypat
assert session_history.load_history_records("heartbeat_abc") == []
+def test_assistant_file_event_is_restored_for_team_history() -> None:
+ assert session_history._is_team_relevant(
+ {
+ "event_type": "chat.file",
+ "role": "assistant",
+ "files": [
+ {
+ "name": "report.xlsx",
+ "download_url": "/file-api/download?token=signed",
+ }
+ ],
+ }
+ )
+
+
def test_has_persistable_assistant_payload_tool_result_with_tool_call_id():
assert session_history._has_persistable_assistant_payload(
content_text="",
diff --git a/tests/unit_tests/test_web_file_download.py b/tests/unit_tests/test_web_file_download.py
new file mode 100644
index 0000000000..95a95a9b3b
--- /dev/null
+++ b/tests/unit_tests/test_web_file_download.py
@@ -0,0 +1,212 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import io
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.tools import web_file_download
+from jiuwenswarm.agents.harness.common.tools.web_file_download import (
+ WebFileDownloadManager,
+)
+from jiuwenswarm.channels.web.app_web import _SpaStaticHandler
+
+
+class _DownloadHandlerStub:
+ def __init__(
+ self,
+ *,
+ command: str = "HEAD",
+ headers: dict[str, str] | None = None,
+ ) -> None:
+ self.command = command
+ self.headers = headers or {}
+ self.wfile = io.BytesIO()
+ self.status: int | None = None
+ self.response_headers: dict[str, str] = {}
+ self.headers_ended = False
+
+ def send_response(self, status: int) -> None:
+ self.status = status
+
+ def send_header(self, name: str, value: str) -> None:
+ self.response_headers[name] = value
+
+ def end_headers(self) -> None:
+ self.headers_ended = True
+
+ def _write_json(self, status: int, payload: dict) -> None:
+ raise AssertionError(f"unexpected JSON response: {status} {payload}")
+
+ def log_error(self, message: str, *args: object) -> None:
+ raise AssertionError(message % args)
+
+
+def _serve_file(
+ monkeypatch: pytest.MonkeyPatch,
+ file_path: Path,
+ query: dict[str, str],
+ *,
+ command: str = "HEAD",
+ headers: dict[str, str] | None = None,
+) -> _DownloadHandlerStub:
+ monkeypatch.setattr(
+ web_file_download,
+ "validate_file_download_token",
+ lambda _token: {"path": str(file_path)},
+ )
+ handler = _DownloadHandlerStub(command=command, headers=headers)
+ _SpaStaticHandler._handle_file_download(handler, query)
+ return handler
+
+
+def _signed_token(secret: str, payload: object) -> str:
+ encoded = base64.urlsafe_b64encode(
+ json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ ).decode("ascii")
+ signature = hmac.new(
+ secret.encode("utf-8"), encoded.encode("ascii"), hashlib.sha256
+ ).hexdigest()
+ return f"{encoded}.{signature}"
+
+
+def test_valid_token_is_accepted() -> None:
+ manager = WebFileDownloadManager(secret="s" * 32)
+ token = manager.generate_token("/tmp/report.xlsx", "session-1", expires_in=60)
+
+ payload = manager.validate_token(token)
+ assert payload is not None
+ assert payload["path"] == "/tmp/report.xlsx"
+ assert payload["exp"] == pytest.approx(int(time.time()) + 60, abs=1)
+ assert payload["sid"] == "session-1"
+
+
+def test_expiration_is_not_required_for_download() -> None:
+ secret = "s" * 32
+ manager = WebFileDownloadManager(secret=secret)
+ token = _signed_token(
+ secret,
+ {"path": "/tmp/report.xlsx", "sid": "session-1"},
+ )
+
+ assert manager.validate_token(token) == {
+ "path": "/tmp/report.xlsx",
+ "sid": "session-1",
+ }
+
+
+def test_tampered_token_is_rejected() -> None:
+ manager = WebFileDownloadManager(secret="s" * 32)
+ token = manager.generate_token("/tmp/report.xlsx", expires_in=60)
+ encoded, signature = token.split(".")
+
+ assert manager.validate_token(f"{encoded}x.{signature}") is None
+
+
[email protected]("inline_value", ["1", "true", "TRUE"])
+def test_download_handler_uses_inline_disposition_for_preview(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+ inline_value: str,
+) -> None:
+ file_path = tmp_path / "preview sample.pdf"
+ file_path.write_bytes(b"%PDF-1.7")
+ handler = _serve_file(
+ monkeypatch,
+ file_path,
+ {"token": "signed-token", "inline": inline_value},
+ )
+
+ assert handler.status == 200
+ assert handler.headers_ended is True
+ assert handler.response_headers["Content-Type"] == "application/pdf"
+ assert handler.response_headers["Accept-Ranges"] == "bytes"
+ assert handler.response_headers["Content-Disposition"] == (
+ "inline; filename*=UTF-8''preview%20sample.pdf"
+ )
+
+
+ "query", [{"token": "signed-token"}, {"token": "signed-token", "inline": "0"}]
+)
+def test_download_handler_keeps_attachment_disposition_for_download(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+ query: dict[str, str],
+) -> None:
+ file_path = tmp_path / "report.pdf"
+ file_path.write_bytes(b"%PDF-1.7")
+ handler = _serve_file(monkeypatch, file_path, query)
+
+ assert handler.status == 200
+ assert handler.response_headers["Content-Disposition"] == (
+ "attachment; filename*=UTF-8''report.pdf"
+ )
+
+
+ ("range_header", "expected_body", "expected_content_range"),
+ [
+ ("bytes=2-5", b"2345", "bytes 2-5/10"),
+ ("bytes=7-", b"789", "bytes 7-9/10"),
+ ("bytes=-3", b"789", "bytes 7-9/10"),
+ ("bytes=7-20", b"789", "bytes 7-9/10"),
+ ],
+)
+def test_download_handler_serves_single_byte_range(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+ range_header: str,
+ expected_body: bytes,
+ expected_content_range: str,
+) -> None:
+ file_path = tmp_path / "media.bin"
+ file_path.write_bytes(b"0123456789")
+ handler = _serve_file(
+ monkeypatch,
+ file_path,
+ {"token": "signed-token", "inline": "1"},
+ command="GET",
+ headers={"Range": range_header},
+ )
+
+ assert handler.status == 206
+ assert handler.response_headers["Content-Length"] == str(len(expected_body))
+ assert handler.response_headers["Accept-Ranges"] == "bytes"
+ assert handler.response_headers["Content-Range"] == expected_content_range
+ assert handler.wfile.getvalue() == expected_body
+
+
+ "range_header",
+ [
+ "items=0-1",
+ "bytes=10-12",
+ "bytes=3-2",
+ "bytes=-0",
+ "bytes=0-1,3-4",
+ ],
+)
+def test_download_handler_rejects_invalid_byte_range(
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+ range_header: str,
+) -> None:
+ file_path = tmp_path / "media.bin"
+ file_path.write_bytes(b"0123456789")
+ handler = _serve_file(
+ monkeypatch,
+ file_path,
+ {"token": "signed-token", "inline": "1"},
+ command="GET",
+ headers={"Range": range_header},
+ )
+
+ assert handler.status == 416
+ assert handler.response_headers["Content-Range"] == "bytes */10"
+ assert handler.wfile.getvalue() == b""