From 6470853d1db0f2d8c735370652fd8131d50d0047 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:28:27 -0400 Subject: [PATCH 01/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- marketplace.json | 50 ++++++++++++++++++++++ pnpm-lock.yaml | 106 ++++++++++++++++++++++++++++++----------------- 2 files changed, 118 insertions(+), 38 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..9d3172d1 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "help-center-builder", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/help-center-builder", + "displayName": "Help Center Builder", + "displayName_i18n": { + "en": "Help Center Builder", + "zh-CN": "帮助中心制作" + }, + "description": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "description_i18n": { + "en": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "zh-CN": "把一个放 Markdown / HTML 文档的文件夹生成静态帮助中心:带分类卡片的首页、分类页,文章页有面包屑、侧边导航、目录、相关文章和上一篇 / 下一篇,还有离线可用的即时全文搜索(支持中文)。增量构建只重写受改动影响的页面,并列出原因;同时报告坏链和失效锚点。输出文件夹可直接上传到任意静态托管。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "help center", + "knowledge base", + "documentation", + "static site", + "markdown", + "faq", + "search", + "support", + "帮助中心", + "知识库", + "文档站", + "常见问题" + ], + "examplePrompts": [ + "Build a help center from the docs folder", + "I edited a few articles; update the help center", + "Check the help docs for broken links" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "用 docs 文件夹生成帮助中心", + "我改了几篇文章,更新一下帮助中心", + "检查帮助文档里有没有坏链" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..cbe8f569 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -37,7 +37,7 @@ importers: version: 6.0.2 vitest: specifier: 4.1.4 - version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) zod: specifier: 4.6.5 version: 4.6.5 @@ -89,6 +89,46 @@ importers: ui-plugins/gridcraft: {} + ui-plugins/help-center-builder: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + marked: + specifier: 18.3.0 + version: 18.3.0 + minisearch: + specifier: 7.2.0 + version: 7.2.0 + yaml: + specifier: 2.9.1 + version: 2.9.1 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) + ui-plugins/jupyter-notebook: dependencies: '@modelcontextprotocol/sdk': @@ -2475,10 +2515,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2750,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -2880,6 +2913,11 @@ packages: engines: {node: '>= 20'} hasBin: true + marked@18.3.0: + resolution: {integrity: sha512-ed8zmPXlBb3UfGXN5iHMQyMhFpdqLgoV5umUXx/Q1R+FW3q8VpqpyoKUwlENL9appo2UMvNLURDVaT3AMOryGA==} + engines: {node: '>= 20'} + hasBin: true + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2906,6 +2944,9 @@ packages: resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} engines: {node: '>=18'} + minisearch@7.2.0: + resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==} + mlly@1.8.2: resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} @@ -3068,10 +3109,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3697,8 +3734,8 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - yaml@2.9.0: - resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true @@ -4285,11 +4322,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5151,14 +5188,14 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.1 - '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0))': + '@vitest/mocker@4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1))': dependencies: '@vitest/spy': 4.1.4 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: msw: 2.13.3(@types/node@25.5.0)(typescript@6.0.2) - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) '@vitest/pretty-format@4.1.4': dependencies: @@ -5809,13 +5846,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5904,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6079,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6186,6 +6215,8 @@ snapshots: marked@18.0.14: {} + marked@18.3.0: {} + math-intrinsics@1.1.0: {} mdn-data@2.27.1: {} @@ -6224,6 +6255,8 @@ snapshots: dependencies: mime-db: 1.54.0 + minisearch@7.2.0: {} + mlly@1.8.2: dependencies: acorn: 8.16.0 @@ -6406,8 +6439,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6785,8 +6816,8 @@ snapshots: tinyglobby@0.2.16: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyglobby@0.2.17: dependencies: @@ -6902,7 +6933,7 @@ snapshots: vary@1.1.2: {} - vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0): + vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -6915,12 +6946,12 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 tsx: 4.21.0 - yaml: 2.9.0 + yaml: 2.9.1 - vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)): + vitest@4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)): dependencies: '@vitest/expect': 4.1.4 - '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + '@vitest/mocker': 4.1.4(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1)) '@vitest/pretty-format': 4.1.4 '@vitest/runner': 4.1.4 '@vitest/snapshot': 4.1.4 @@ -6937,7 +6968,7 @@ snapshots: tinyexec: 1.3.1 tinyglobby: 0.2.17 tinyrainbow: 3.1.1 - vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + vite: 8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@opentelemetry/api': 1.9.1 @@ -7018,8 +7049,7 @@ snapshots: y18n@5.0.8: optional: true - yaml@2.9.0: - optional: true + yaml@2.9.1: {} yargs-parser@21.1.1: optional: true From aae19ee2313e7bea105c6824a0749e621c0a57f9 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:29:01 -0400 Subject: [PATCH 02/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- external_plugins/help-center-builder/LICENSE | 21 +++++++ .../help-center-builder/README.md | 59 +++++++++++++++++++ .../help-center-builder/README_CN.md | 59 +++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 external_plugins/help-center-builder/LICENSE create mode 100644 external_plugins/help-center-builder/README.md create mode 100644 external_plugins/help-center-builder/README_CN.md diff --git a/external_plugins/help-center-builder/LICENSE b/external_plugins/help-center-builder/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/help-center-builder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/help-center-builder/README.md b/external_plugins/help-center-builder/README.md new file mode 100644 index 00000000..cb14036e --- /dev/null +++ b/external_plugins/help-center-builder/README.md @@ -0,0 +1,59 @@ +# Help Center Builder + +Turn a folder of **Markdown / HTML** docs into a **static help center** with category navigation, breadcrumbs, related articles and instant **full-text search** that works offline. When you edit docs, an **incremental build** rewrites only the pages the change affects and tells you why. + +## What it does + +- **Reads your docs**: + - Sub-folders become categories; files at the top level go to “General”. + - Front matter: `title`, `description`, `order`, `tags`, `related`, `updated`, `category`, `draft`. Without a title, a leading `#` / `##` / setext heading is used. + - An `index.md` in a folder becomes that category's intro; a top-level `index.md` becomes the home page's. + - HTML files (for example CMS exports) are supported: title, meta description and tags are read; navigation, scripts and inline handlers are removed. +- **Optional `help-center.json`** in the docs folder: `title`, `description`, `accent` colour, `logo`, `footer`, `baseUrl`, `lang`, and category names, descriptions and order. +- **Generates** `help-center/`: + - Home page with a search hero and category cards; category pages with article lists. + - Article pages: breadcrumbs, sidebar (the category's articles plus all categories), “On this page” table of contents, related articles (your `related` first, then shared tags and similar titles), and previous / next. + - Search page and 404 page; `sitemap.xml` and canonical links when `baseUrl` is set. + - Responsive, light and dark themes. English or Chinese interface, detected automatically. + - Images and other files are copied, and `.md` links are rewritten to `.html`. +- **Search**: built with [MiniSearch](https://github.com/lucaong/minisearch) at build time and shipped as a script. + - Works on any static host and straight from disk (`file://`), with no server or external service. + - Prefix and fuzzy matching; titles, tags and headings weigh more; Chinese / Japanese / Korean are split into characters and pairs. + - Live dropdown with keyboard navigation (`/` focuses the box), plus a results page. +- **Incremental builds**: + - Each page records what it depends on: its content, its category's article list, the categories, its related articles, previous / next, site settings and the template. + - Only pages whose dependencies changed are rewritten, each listed with the reason (for example “related articles changed”). Deleted articles are removed, and changed images re-copied. + - Use **Full rebuild** to rewrite everything. +- **Checks**: broken links to articles or files, missing `#anchors`, links outside the docs folder, two files producing the same page, missing or duplicate titles, empty articles, unknown `related`, drafts. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Build a help center from the docs folder" +- "I edited a few articles; update the help center" +- "Check the help docs for broken links" + +Or use the panel: choose the docs folder, then **Build help center**; later, **Build changes**. Browse the site map and preview any page, and see which pages were rewritten and why. Open `help-center/index.html` in a browser, or upload the folder to a static host (Cloudflare Pages, Netlify, GitHub Pages, S3…). + +## Tools + +| Tool | Purpose | +|---|---| +| `hc_scan` | Categories, articles and problems in a docs folder (writes nothing) | +| `hc_build` | Build or update the site (incremental; `full` to rewrite everything) | + +## Scope (v0.1) + +- Hosting is up to you: the output is a plain static folder. Deploying it (for example to Cloudflare Pages) is a separate step. +- No feedback buttons, analytics, comments or login-protected articles (they need a backend). +- One language per site. Code blocks aren't syntax-highlighted. MDX, Liquid and other templating aren't run. + +## Privacy, network and files + +- Runs locally with no network access and no API keys. The generated site loads nothing from other servers. +- Reads the docs folder. Writes the output folder and `.help-center/builds.json`, and deletes only pages it wrote earlier. + +## License + +MIT. Uses [marked](https://github.com/markedjs/marked) (MIT), [MiniSearch](https://github.com/lucaong/minisearch) (MIT; also shipped in each generated site) and [yaml](https://github.com/eemeli/yaml) (ISC). diff --git a/external_plugins/help-center-builder/README_CN.md b/external_plugins/help-center-builder/README_CN.md new file mode 100644 index 00000000..3a359f2a --- /dev/null +++ b/external_plugins/help-center-builder/README_CN.md @@ -0,0 +1,59 @@ +# 帮助中心制作 + +把一个放 **Markdown / HTML** 文档的文件夹生成 **静态帮助中心**:分类导航、面包屑、相关文章,以及离线可用的即时 **全文搜索**。改了文档后,**增量构建** 只重写受影响的页面,并告诉你原因。 + +## 功能 + +- **读取文档**: + - 子文件夹就是分类;放在根目录的文件归入“常规”。 + - 支持 front matter:`title`、`description`、`order`、`tags`、`related`、`updated`、`category`、`draft`。没写标题时,用开头的 `#` / `##` / setext 标题。 + - 文件夹里的 `index.md` 作为该分类的介绍;根目录的 `index.md` 作为首页介绍。 + - 支持 HTML 文件(例如从 CMS 导出的):读取标题、meta 描述和标签,去掉导航、脚本和内联事件。 +- **可选的 `help-center.json`**(放在文档目录里):`title`、`description`、主题色 `accent`、`logo`、`footer`、`baseUrl`、`lang`,以及分类名称、说明和顺序。 +- **生成** `help-center/`: + - 首页:搜索大框加分类卡片;分类页:文章列表。 + - 文章页:面包屑、侧边栏(本分类文章加全部分类)、“本页内容”目录、相关文章(先用你写的 `related`,再按共同标签和相近标题补足)、上一篇 / 下一篇。 + - 搜索页和 404 页;设置了 `baseUrl` 时生成 `sitemap.xml` 和 canonical 链接。 + - 响应式布局,支持浅色 / 深色主题;界面中英文自动识别。 + - 图片等文件原样复制,`.md` 链接改写成 `.html`。 +- **搜索**:构建时用 [MiniSearch](https://github.com/lucaong/minisearch) 生成索引,以脚本形式随站点发布。 + - 任何静态托管都能用,直接双击打开(`file://`)也能用,不需要服务器或外部服务。 + - 支持前缀和模糊匹配;标题、标签、小标题权重更高;中日韩文字按单字和双字切分。 + - 输入时实时下拉,可用键盘选择(按 `/` 聚焦搜索框);另有搜索结果页。 +- **增量构建**: + - 每个页面记录它依赖的内容:正文、同分类文章列表、分类列表、相关文章、上一篇 / 下一篇、站点设置、模板。 + - 只重写依赖有变化的页面,并逐页列出原因(例如“相关文章变了”)。删掉的文章会被移除,改过的图片会重新复制。 + - 点“全量重建”可重写全部页面。 +- **检查**:指向文章或文件的坏链、失效的 `#锚点`、指向文档目录外的链接、两个文件生成同一个页面、缺失或重复的标题、空文章、无效的 `related`、草稿。 + +## 使用 + +在 ZCode Desktop 里对 Agent 说: + +- “用 docs 文件夹生成帮助中心” +- “我改了几篇文章,更新一下帮助中心” +- “检查帮助文档里有没有坏链” + +也可以用面板:选择文档目录 → **生成帮助中心**;以后改了文档点 **增量构建**。面板里能浏览站点结构、预览任意页面,并查看哪些页面被重写及原因。用浏览器打开 `help-center/index.html`,或把整个文件夹上传到静态托管(Cloudflare Pages、Netlify、GitHub Pages、S3 等)。 + +## 工具 + +| 工具 | 用途 | +|---|---| +| `hc_scan` | 查看文档目录的分类、文章和问题(不写文件) | +| `hc_build` | 生成或更新站点(默认增量,`full` 为全量重建) | + +## 范围(v0.1) + +- 托管由你决定:输出是普通的静态文件夹,部署(例如到 Cloudflare Pages)是另外一步。 +- 不含“是否有帮助”反馈、统计、评论、需要登录的文章(这些需要后端)。 +- 一个站点一种语言;代码块不做语法高亮;不执行 MDX、Liquid 等模板语法。 + +## 隐私、网络与文件 + +- 在本地运行,不联网,不需要 API Key。生成的站点不从其他服务器加载任何东西。 +- 读取文档目录;写入输出目录和 `.help-center/builds.json`;只删除自己以前生成的页面。 + +## 许可 + +MIT。使用 [marked](https://github.com/markedjs/marked)(MIT)、[MiniSearch](https://github.com/lucaong/minisearch)(MIT,也随每个生成的站点发布)和 [yaml](https://github.com/eemeli/yaml)(ISC)。 From 1132f15fe9e74abe43f925c6caefd880cdc0ee87 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:29:39 -0400 Subject: [PATCH 03/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- ui-plugins/help-center-builder/package.json | 35 +++++++++++++++++++ ui-plugins/help-center-builder/tsconfig.json | 14 ++++++++ .../help-center-builder/vitest.config.ts | 2 ++ 3 files changed, 51 insertions(+) create mode 100644 ui-plugins/help-center-builder/package.json create mode 100644 ui-plugins/help-center-builder/tsconfig.json create mode 100644 ui-plugins/help-center-builder/vitest.config.ts diff --git a/ui-plugins/help-center-builder/package.json b/ui-plugins/help-center-builder/package.json new file mode 100644 index 00000000..a15da9a6 --- /dev/null +++ b/ui-plugins/help-center-builder/package.json @@ -0,0 +1,35 @@ +{ + "name": "@penova/plugin-help-center-builder", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Help Center Builder" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5", + "marked": "18.3.0", + "minisearch": "7.2.0", + "yaml": "2.9.1" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/help-center-builder/tsconfig.json b/ui-plugins/help-center-builder/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/help-center-builder/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/help-center-builder/vitest.config.ts b/ui-plugins/help-center-builder/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/help-center-builder/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } }); From aa8676d2a273fbf548d38be520058ef814db282e Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:11 -0400 Subject: [PATCH 04/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../.zcode-plugin/plugin.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 external_plugins/help-center-builder/.zcode-plugin/plugin.json diff --git a/external_plugins/help-center-builder/.zcode-plugin/plugin.json b/external_plugins/help-center-builder/.zcode-plugin/plugin.json new file mode 100644 index 00000000..26223185 --- /dev/null +++ b/external_plugins/help-center-builder/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "help-center-builder", + "version": "0.1.0", + "description": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "description_i18n": { + "en": "Turn a folder of Markdown / HTML docs into a static help center: home page with category cards, category pages, articles with breadcrumbs, sidebar, table of contents, related articles and previous / next, and instant full-text search that works offline (Chinese too). Incremental builds rewrite only the pages a change affects and list them with the reason. Broken links and anchors are reported. The output folder can be uploaded to any static host.", + "zh-CN": "把一个放 Markdown / HTML 文档的文件夹生成静态帮助中心:带分类卡片的首页、分类页,文章页有面包屑、侧边导航、目录、相关文章和上一篇 / 下一篇,还有离线可用的即时全文搜索(支持中文)。增量构建只重写受改动影响的页面,并列出原因;同时报告坏链和失效锚点。输出文件夹可直接上传到任意静态托管。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "help center", + "knowledge base", + "documentation", + "static site", + "markdown", + "faq", + "search", + "support", + "帮助中心", + "知识库", + "文档站", + "常见问题" + ], + "skills": "skills", + "mcpServers": { + "help-center-builder": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "帮助中心制作", + "en-US": "Help Center Builder" + }, + "icon": "life-buoy", + "server": "help-center-builder", + "resourceUri": "ui://help-center-builder/panel.html", + "availability": "session" + } + ] + } +} From 2bc9479309c6fb2dffd5b739af2981e7fd812391 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:48 -0400 Subject: [PATCH 05/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../help-center-builder/scripts/build.mjs | 81 +++++++++ .../help-center-builder/scripts/e2e.mts | 117 +++++++++++++ .../help-center-builder/scripts/harness.mjs | 162 ++++++++++++++++++ .../help-center-builder/scripts/licenses.mjs | 43 +++++ 4 files changed, 403 insertions(+) create mode 100644 ui-plugins/help-center-builder/scripts/build.mjs create mode 100644 ui-plugins/help-center-builder/scripts/e2e.mts create mode 100644 ui-plugins/help-center-builder/scripts/harness.mjs create mode 100644 ui-plugins/help-center-builder/scripts/licenses.mjs diff --git a/ui-plugins/help-center-builder/scripts/build.mjs b/ui-plugins/help-center-builder/scripts/build.mjs new file mode 100644 index 00000000..5ea87cfb --- /dev/null +++ b/ui-plugins/help-center-builder/scripts/build.mjs @@ -0,0 +1,81 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +// 站点运行时(CSS、搜索脚本、分词)和 minisearch 浏览器版(MIT),复制到每个生成的站点。 +await cp(join(root, "src/runtime"), join(dist, "runtime"), { recursive: true }); +{ + const umd = join(root, "node_modules/minisearch/dist/umd/index.js"); + await writeFile(join(dist, "runtime/assets/minisearch.js"), `/*! MiniSearch 7.2.0 | MIT License | https://github.com/lucaong/minisearch */\n${await readFile(umd, "utf8")}`); +} + +await writeNotices([ui.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/help-center-builder/scripts/e2e.mts b/ui-plugins/help-center-builder/scripts/e2e.mts new file mode 100644 index 00000000..b6580cd1 --- /dev/null +++ b/ui-plugins/help-center-builder/scripts/e2e.mts @@ -0,0 +1,117 @@ +// 浏览器端到端测试: +// 1) 真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板:选文档目录 → 生成 → 站点结构/预览;改一篇文档 → 增量构建,列出重写的页面和原因; +// 2) 在 Chrome 里打开生成的站点(HTTP):首页搜索下拉、键盘选择跳转、文章页面包屑/目录/相关文章/上一篇下一篇、搜索结果页; +// 3) 中文站点用 file:// 直接打开,离线中文搜索可用。需要 Chrome。 +import assert from "node:assert/strict"; +import { cpSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { mkdtemp } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { extname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "help-center-builder-shots"); +mkdirSync(shots, { recursive: true }); +const S = process.env.HELP_SAMPLES ?? "/workspace/zcode-new-plugins/samples/help"; +const workspace = await mkdtemp(join(tmpdir(), "hcb-e2e-")); +cpSync(join(S, "harbor"), join(workspace, "docs"), { recursive: true }); +cpSync(join(S, "zh"), join(workspace, "zh-docs"), { recursive: true }); +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +let web: ReturnType | undefined; +try { + step("panel: build the Harbor help center"); + const { outer, frame, context } = await harness.open("?locale=zh-CN", { width: 1440, height: 1000 }); + await frame.locator("select.docs option[value='docs']").waitFor({ state: "attached", timeout: 20_000 }); + await frame.locator("select.docs").selectOption("docs"); + await frame.locator("button.build").click(); + await frame.locator(".sum", { hasText: "15 篇文章、5 个分类、共 23 个页面" }).waitFor({ timeout: 60_000 }); + await frame.locator(".iss .info", { hasText: "onclick" }).waitFor(); + assert.equal(await frame.locator(".iss .error, .iss .warn").count(), 0); + await frame.frameLocator("iframe.pv").locator(".hero h1", { hasText: "How can we help?" }).waitFor(); + await frame.locator(".tree a", { hasText: "Refunds" }).click(); + await frame.frameLocator("iframe.pv").locator(".crumbs", { hasText: "Billing & payments" }).waitFor(); + await frame.locator(".tree a", { hasText: "Create a Harbor Bikes account" }).click(); + await frame.frameLocator("iframe.pv").locator("article img[src^='data:image/png']").waitFor(); + await outer.screenshot({ path: join(shots, "01-panel-built.png") }); + + step("panel: edit one article → incremental build lists what changed and why"); + const f = join(workspace, "docs/billing/refunds.md"); + writeFileSync(f, readFileSync(f, "utf8").replace("title: Refunds", "title: Refunds and chargebacks")); + await frame.locator("button.build").click(); + await frame.locator(".sum", { hasText: "重写 7 个页面,16 个未变" }).waitFor({ timeout: 60_000 }); + await frame.locator(".rb li[data-out='rentals/change-or-cancel.html'] .why", { hasText: "相关文章变了" }).waitFor(); + await frame.locator(".rb li[data-out='billing/deposits.html'] .why", { hasText: "上一篇/下一篇变了" }).waitFor(); + await frame.locator(".rb li[data-out='billing/refunds.html'] .why", { hasText: "内容改了" }).waitFor(); + await frame.locator(".tree a", { hasText: "Refunds and chargebacks" }).click(); + await frame.frameLocator("iframe.pv").locator("article h1", { hasText: "Refunds and chargebacks" }).waitFor(); + await outer.screenshot({ path: join(shots, "02-panel-incremental.png") }); + await harness.agent(outer, "hc_build", { docs: "zh-docs", out: "zh-site" }); + await frame.locator(".sum", { hasText: "5 篇文章" }).waitFor({ timeout: 30_000 }); + + step("site over HTTP: search dropdown, keyboard, article layout"); + const site = join(workspace, "help-center"); + const types: Record = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".png": "image/png", ".xml": "application/xml" }; + web = createServer((req, res) => { + let p = join(site, decodeURIComponent(new URL(req.url!, "http://x").pathname)); + if (existsSync(p) && statSync(p).isDirectory()) p = join(p, "index.html"); + if (!p.startsWith(site) || !existsSync(p)) { res.writeHead(404, { "Content-Type": "text/html" }); return res.end(readFileSync(join(site, "404.html"))); } + res.writeHead(200, { "Content-Type": types[extname(p)] ?? "application/octet-stream", "X-Content-Type-Options": "nosniff" }); + res.end(readFileSync(p)); + }); + const port = await new Promise((ok) => web!.listen(0, "127.0.0.1", () => ok((web!.address() as { port: number }).port))); + const page = await context.newPage(); + const errors: string[] = []; + page.on("pageerror", (e) => errors.push(String(e))); + page.on("console", (m) => { if (m.type() === "error" && !/404/.test(m.text())) errors.push(m.text()); }); + page.on("response", (r) => { if (r.status() >= 400 && !/favicon\.ico$/.test(r.url())) errors.push(`${r.status()} ${r.url()}`); }); + await page.setViewportSize({ width: 1280, height: 860 }); + await page.goto(`http://127.0.0.1:${port}/`); + await page.locator(".hero input").fill("refund"); + await page.locator(".hero .results .hit").first().waitFor(); + assert.match(await page.locator(".hero .results .hit .hit-t").first().innerText(), /Refunds and chargebacks/); + await page.locator(".hero input").fill("deposit card"); + await page.locator(".hero .results .hit-t", { hasText: "Deposits and card holds" }).waitFor(); + await page.screenshot({ path: join(shots, "03-site-search.png") }); + await page.locator(".hero input").press("ArrowDown"); + await page.locator(".hero input").press("Enter"); + await page.waitForURL(/billing\/deposits\.html$/); + await page.locator(".crumbs", { hasText: "Billing & payments" }).waitFor(); + await page.goto(`http://127.0.0.1:${port}/getting-started/create-account.html`); + await page.locator(".toc a", { hasText: "Sign up on the web" }).click(); + await page.waitForURL(/#sign-up-on-the-web$/); + assert.equal(await page.locator(".side a.on").innerText(), "Create a Harbor Bikes account"); + await page.locator(".pn a.next", { hasText: "Take your first ride" }).waitFor(); + assert.ok(await page.locator("article img").evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth === 360)); + await page.evaluate(() => window.scrollTo(0, 0)); + await page.screenshot({ path: join(shots, "04-site-article.png") }); + await page.locator(".top input").fill("full station"); + await page.locator(".top input").press("Enter"); + await page.waitForURL(/search\.html\?q=full/); + await page.locator("#search-page .hit-t", { hasText: "Ending a rental when a station is full" }).waitFor(); + assert.match(await page.locator("#search-count").innerText(), /results for “full station”/); + await page.goto(`http://127.0.0.1:${port}/billing/index.html`); + assert.equal(await page.locator(".list li").count(), 3); + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(`http://127.0.0.1:${port}/bikes/battery.html`); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= 391), "no horizontal scroll on mobile"); + assert.deepEqual(errors, []); + + step("Chinese site from file:// (offline search)"); + const zh = await context.newPage(); + await zh.setViewportSize({ width: 1280, height: 860 }); + await zh.goto(pathToFileURL(join(workspace, "zh-site/index.html")).href); + await zh.locator(".hero h1", { hasText: "有什么可以帮你?" }).waitFor(); + await zh.locator(".hero input").fill("退款"); + await zh.locator(".hero .results .hit-t", { hasText: "会员如何退款" }).waitFor(); + assert.equal(await zh.locator(".hero .results .hit-t mark").first().innerText(), "退款"); + await zh.screenshot({ path: join(shots, "05-zh-file-search.png") }); + await zh.locator(".hero .results .hit").first().click(); + await zh.locator(".related a", { hasText: "我的数据安全吗" }).waitFor(); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + web?.close(); + await harness.close(); +} diff --git a/ui-plugins/help-center-builder/scripts/harness.mjs b/ui-plugins/help-center-builder/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/help-center-builder/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/help-center-builder/scripts/licenses.mjs b/ui-plugins/help-center-builder/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/help-center-builder/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} From b70cd1eb8066567e14c7dddc5bb0431c39043789 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:31:24 -0400 Subject: [PATCH 06/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- ui-plugins/help-center-builder/src/docs.ts | 142 +++++++++++ ui-plugins/help-center-builder/src/main.ts | 14 ++ ui-plugins/help-center-builder/src/server.ts | 249 +++++++++++++++++++ ui-plugins/help-center-builder/src/site.ts | 179 +++++++++++++ 4 files changed, 584 insertions(+) create mode 100644 ui-plugins/help-center-builder/src/docs.ts create mode 100644 ui-plugins/help-center-builder/src/main.ts create mode 100644 ui-plugins/help-center-builder/src/server.ts create mode 100644 ui-plugins/help-center-builder/src/site.ts diff --git a/ui-plugins/help-center-builder/src/docs.ts b/ui-plugins/help-center-builder/src/docs.ts new file mode 100644 index 00000000..4cb49159 --- /dev/null +++ b/ui-plugins/help-center-builder/src/docs.ts @@ -0,0 +1,142 @@ +import { createHash } from "node:crypto"; +import { Marked, Renderer } from "marked"; +import { parse as parseYaml } from "yaml"; + +export interface Heading { level: number; id: string; text: string } +export interface Link { href: string; target: string | null; anchor: string; kind: "doc" | "asset" | "external" | "anchor" } +export interface Doc { + src: string; out: string; hash: string; title: string; titleFromFile: boolean; description: string; excerpt: string; + folder: string; categoryName?: string; order: number; tags: string[]; related: string[]; updated?: string; draft: boolean; + html: string; text: string; headings: Heading[]; ids: string[]; links: Link[]; stripped: string[]; isIntro: boolean; +} + +export const sha = (b: string | Uint8Array) => createHash("sha256").update(b).digest("hex").slice(0, 16); +const DOC_EXT = /\.(md|markdown|html?)$/i; +export const isDocPath = (p: string) => DOC_EXT.test(p); +export const outPath = (src: string) => src.replace(DOC_EXT, ".html"); + +/** 标题锚点:保留中日韩文字和字母数字,其余变成连字符。 */ +export function slugify(s: string): string { + return s.normalize("NFKC").toLowerCase().replace(/<[^>]+>/g, "").replace(/&[a-z#0-9]+;/gi, "").replace(/[^\p{L}\p{N}\s_-]+/gu, "").trim().replace(/[\s_]+/g, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "") || "section"; +} +const ENT: Record = { amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", apos: "'", nbsp: " " }; +export const decode = (s: string) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e: string) => (e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : +e.slice(1)) : ENT[e.toLowerCase()] ?? m)); +export const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!); +export const plain = (html: string) => decode(html.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, " ").replace(//gi, (m) => ` ${m} `).replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim(); + +/** 帮助中心内容不该带脚本:移除 script/iframe/object、内联事件和 javascript: 链接(清理作者内容,不是安全沙箱)。 */ +export function sanitize(html: string): { html: string; stripped: string[] } { + const stripped: string[] = []; + let out = html.replace(/<(script|iframe|object|embed)\b[\s\S]*?(<\/\1\s*>|$)/gi, (_, t: string) => { stripped.push(`<${t.toLowerCase()}>`); return ""; }); + out = out.replace(/<(script|iframe|object|embed)\b[^>]*\/?>/gi, (_, t: string) => { stripped.push(`<${t.toLowerCase()}>`); return ""; }); + out = out.replace(/\s(on[a-z]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, (_, a: string) => { stripped.push(`${a.toLowerCase()}=`); return ""; }); + out = out.replace(/\b(href|src)\s*=\s*(["'])\s*javascript:[^"']*\2/gi, (_, a: string) => { stripped.push("javascript:"); return `${a}="#"`; }); + return { html: out, stripped: [...new Set(stripped)] }; +} + +function frontMatter(raw: string): { data: Record; body: string } { + const m = raw.match(/^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?/); + if (!m) return { data: {}, body: raw.replace(/^\uFEFF/, "") }; + let data: Record = {}; + try { const y = parseYaml(m[1]); if (y && typeof y === "object") data = y as Record; } catch (e) { data = { __error: (e as Error).message }; } + return { data, body: raw.slice(m[0].length) }; +} +const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : typeof v === "string" ? v.split(/[,,]/) : []).map((s) => s.trim()).filter(Boolean); + +function renderMarkdown(md: string) { + const used = new Map(); + const headings: Heading[] = []; + const marked = new Marked({ gfm: true }); + marked.use({ + renderer: { + heading({ tokens, depth }) { + const inner = this.parser.parseInline(tokens); + const text = plain(inner); + let id = slugify(text); + const n = used.get(id) ?? 0; + used.set(id, n + 1); + if (n) id = `${id}-${n}`; + headings.push({ level: depth, id, text }); + return `${inner}\n`; + }, + table(token) { return `
${Renderer.prototype.table.call(this, token)}
`; }, + }, + }); + return { html: marked.parse(md, { async: false }) as string, headings }; +} + +function fromHtml(raw: string) { + const title = decode(raw.match(/]*>([\s\S]*?)<\/h1>/i)?.[1]?.replace(/<[^>]+>/g, "").trim() ?? raw.match(/([\s\S]*?)<\/title>/i)?.[1]?.trim() ?? ""); + const meta = (n: string) => decode(raw.match(new RegExp(`<meta\\s+name=["']${n}["']\\s+content=["']([^"']*)["']`, "i"))?.[1] ?? ""); + let body = raw.match(/<(main|article)\b[^>]*>([\s\S]*?)<\/\1>/i)?.[2] ?? raw.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i)?.[1] ?? raw; + body = body.replace(/<(nav|header|footer|style)\b[\s\S]*?<\/\1>/gi, "").replace(/<h1\b[^>]*>[\s\S]*?<\/h1>/i, ""); + const used = new Map<string, number>(); + const headings: Heading[] = []; + body = body.replace(/<h([2-6])\b([^>]*)>([\s\S]*?)<\/h\1>/gi, (_, lv: string, attrs: string, inner: string) => { + const text = plain(inner); + let id = attrs.match(/\bid=["']([^"']+)["']/)?.[1] ?? slugify(text); + const n = used.get(id) ?? 0; used.set(id, n + 1); if (n) id = `${id}-${n}`; + headings.push({ level: +lv, id, text }); + return `<h${lv} id="${esc(id)}">${inner}</h${lv}>`; + }); + return { title, description: meta("description"), tags: list(meta("tags") || meta("keywords")), html: body.trim(), headings }; +} + +/** 解析一篇文档(Markdown 或 HTML)。links 里的 target 是相对文档根目录的路径。 */ +export function parseDoc(src: string, raw: string): Doc { + const isHtml = /\.html?$/i.test(src); + const base = src.split("/").pop()!.replace(DOC_EXT, ""); + let title = "", description = "", tags: string[] = [], data: Record<string, unknown> = {}, html: string, headings: Heading[]; + if (isHtml) { + const r = fromHtml(raw); + ({ title, description, tags, html, headings } = r); + } else { + const fm = frontMatter(raw); + data = fm.data; + let body = fm.body; + // 没写 title 时,用开头第一个块的一/二级标题(# / ## / setext 都算)作标题,并从正文里去掉。 + if (!data.title) { + const first = new Marked({ gfm: true }).lexer(body).find((t) => t.type !== "space"); + if (first?.type === "heading" && first.depth <= 2) { title = plain(new Marked().parseInline(first.text, { async: false }) as string); body = body.slice(body.indexOf(first.raw) + first.raw.length); } + } + ({ html, headings } = renderMarkdown(body)); + } + title = String(data.title ?? title).trim(); + const titleFromFile = !title; + if (!title) title = base.replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase()); + const s = sanitize(html); + html = s.html; + const text = plain(html); + const ids = [...new Set([...html.matchAll(/\s(?:id|name)\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]))]; + const dir = src.includes("/") ? src.slice(0, src.lastIndexOf("/") + 1) : ""; + const links: Link[] = []; + for (const m of html.matchAll(/\s(href|src)\s*=\s*["']([^"']*)["']/gi)) { + const href = decode(m[2]); + if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("//")) { links.push({ href, target: null, anchor: "", kind: "external" }); continue; } + if (href.startsWith("#")) { links.push({ href, target: src, anchor: decodeURIComponent(href.slice(1)), kind: "anchor" }); continue; } + const [pathPart, anchor = ""] = href.split("#"); + const clean = decodeURIComponent(pathPart.split("?")[0]); + const target = normalize(clean.startsWith("/") ? clean.slice(1) : dir + clean); + links.push({ href, target, anchor: decodeURIComponent(anchor), kind: isDocPath(target ?? "") ? "doc" : "asset" }); + } + const folder = src.includes("/") ? src.split("/")[0] : ""; + const firstPara = plain(html.match(/<p\b[^>]*>([\s\S]*?)<\/p>/i)?.[1] ?? "") || text; + description = String(data.description ?? description).trim(); + return { + src, out: outPath(src), hash: sha(raw), title, titleFromFile, description, + excerpt: (description || firstPara).slice(0, 180) + ((description || firstPara).length > 180 ? "…" : ""), + folder, categoryName: data.category ? String(data.category) : undefined, order: Number.isFinite(Number(data.order)) ? Number(data.order) : 1000, + tags: tags.length ? tags : list(data.tags), related: list(data.related), updated: data.updated ? (data.updated instanceof Date ? data.updated.toISOString().slice(0, 10) : String(data.updated)) : undefined, + draft: data.draft === true, html, text: text.slice(0, 30_000), headings, ids, links, stripped: s.stripped, isIntro: /(^|\/)index\.(md|markdown|html?)$/i.test(src), + }; +} + +/** 规范化相对路径(处理 ./ 和 ../);越出根目录返回 null。 */ +export function normalize(p: string): string | null { + const out: string[] = []; + for (const part of p.split("/")) { + if (!part || part === ".") continue; + if (part === "..") { if (!out.length) return null; out.pop(); } else out.push(part); + } + return out.join("/"); +} diff --git a/ui-plugins/help-center-builder/src/main.ts b/ui-plugins/help-center-builder/src/main.ts new file mode 100644 index 00000000..50111e63 --- /dev/null +++ b/ui-plugins/help-center-builder/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[help-center-builder] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/help-center-builder/src/server.ts b/ui-plugins/help-center-builder/src/server.ts new file mode 100644 index 00000000..9d232064 --- /dev/null +++ b/ui-plugins/help-center-builder/src/server.ts @@ -0,0 +1,249 @@ +import { readFile, rm } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import MiniSearch from "minisearch"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { type Doc, isDocPath, parseDoc, sha } from "./docs.ts"; +import { type Model, REASONS, type SiteConf, TEMPLATE_VERSION, buildModel, detectLang, plan, searchDocs } from "./site.ts"; + +export const NAME = "help-center-builder"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const STORE = ".help-center/builds.json"; +const CONFIG = "help-center.json"; +const FIELDS = ["title", "headings", "tags", "text"]; +const RUNTIME_ASSETS = ["style.css", "search.js", "tokenize.js", "minisearch.js"]; + +export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void } +export interface Issue { level: "error" | "warn" | "info"; src: string; message: string } +interface Manifest { docs: string; out: string; builtAt: string; pages: Record<string, Record<string, string>>; files: Record<string, string>; site: SiteConf; summary: Summary } +export interface Rebuilt { out: string; kind: string; reasons: string[]; src?: string } +export interface Summary { pages: number; articles: number; categories: { name: string; out: string; count: number }[]; rebuilt: Rebuilt[]; unchanged: number; removed: string[]; copied: string[]; issues: Issue[]; ms: number; full: boolean; first: boolean; searchRebuilt: boolean; lang: string; bytes: number } + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const assets = join(options.assetRoot, "runtime/assets"); + // 与站点浏览器端完全相同的分词源码(同一个文件),保证索引和查询切词一致。 + const hcTokenize = new Function(`${readFileSync(join(assets, "tokenize.js"), "utf8")}\nreturn hcTokenize;`)() as (s: string) => string[]; + const { server, tool } = createKitServer({ name: NAME, version: VERSION, panelUri: PANEL_URI, surface: "editor", panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), log: options.log }); + const load = async (): Promise<Record<string, Manifest>> => ((await ws.exists(STORE)) ? JSON.parse(await ws.readText(STORE)).builds ?? {} : {}); + const save = async (all: Record<string, Manifest>) => ws.write(STORE, JSON.stringify({ version: 1, builds: all }, null, 1) + "\n"); + const norm = (p: string, what: string) => { const r = p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "") || "."; ws.resolve(r); if (r.startsWith("..") || r.startsWith("/")) throw new KitError("bad_path", `${what} must be inside the workspace.`); return r; }; + + async function read(docsDir: string, overrides: Partial<SiteConf>, skip: string[] = []) { + if (!(await ws.exists(docsDir))) throw new KitError("not_found", `Folder ${docsDir}/ not found.`); + // 输出目录(以及以前建过的站点)可能就在文档目录里面(例如文档在工作区根目录),不能再当成文档扫进来。 + const files = (await ws.list({ dir: docsDir, limit: 5000 })).filter((f) => !skip.some((o) => f.path === o || f.path.startsWith(`${o}/`))); + const relOf = (p: string) => (docsDir === "." ? p : p.slice(docsDir.length + 1)); + const docs: Doc[] = []; + const assetsIn: { path: string; rel: string }[] = []; + let conf: Partial<SiteConf> & { categories?: SiteConf["categories"] } = {}; + const issues: Issue[] = []; + for (const f of files) { + const r = relOf(f.path); + if (r === CONFIG) { try { conf = JSON.parse(await ws.readText(f.path)); } catch (e) { issues.push({ level: "error", src: r, message: `Invalid JSON: ${(e as Error).message}` }); } continue; } + if (isDocPath(r)) { if (f.size > 5 * 1024 * 1024) { issues.push({ level: "warn", src: r, message: "Skipped: larger than 5 MB." }); continue; } docs.push(parseDoc(r, await ws.readText(f.path))); } + else assetsIn.push({ path: f.path, rel: r }); + } + if (!docs.length) throw new KitError("no_docs", `No Markdown or HTML files in ${docsDir}/.`); + const site: SiteConf = { + title: overrides.title ?? conf.title ?? "Help Center", + description: overrides.description ?? conf.description ?? "", + accent: overrides.accent ?? conf.accent ?? "#2563eb", + baseUrl: overrides.baseUrl ?? conf.baseUrl, + footer: conf.footer, + logo: conf.logo, + lang: (overrides.lang ?? conf.lang ?? detectLang(docs)) === "zh-CN" ? "zh-CN" : "en", + categories: Array.isArray(conf.categories) ? conf.categories : [], + }; + if (!/^#[0-9a-f]{6}$/i.test(site.accent)) { issues.push({ level: "warn", src: CONFIG, message: `accent “${site.accent}” isn't #rrggbb; using #2563eb.` }); site.accent = "#2563eb"; } + if (site.baseUrl && !/^https?:\/\/[^\s]+$/.test(site.baseUrl)) { issues.push({ level: "warn", src: CONFIG, message: `baseUrl “${site.baseUrl}” isn't an http(s) URL; ignored.` }); site.baseUrl = undefined; } + const model = buildModel(docs, site); + issues.push(...check(model, docs, new Set(assetsIn.map((a) => a.rel)))); + return { model, assetsIn, issues, docs }; + } + + function check(m: Model, all: Doc[], assetSet: Set<string>): Issue[] { + const out: Issue[] = []; + const docBy = new Map(all.map((d) => [d.src, d])); + // 文档间链接按“去掉扩展名的路径”匹配:a.md、a.html 都指向同一篇(输出都是 a.html)。 + const stem = (p: string) => p.replace(/\.(md|markdown|html?)$/i, ""); + const byStem = new Map(all.map((d) => [stem(d.src), d])); + const findDoc = (p: string) => byStem.get(stem(p)); + const byOut = new Map<string, string>(); + for (const d of all) { + if (byOut.has(d.out)) out.push({ level: "error", src: d.src, message: `Same output page as ${byOut.get(d.out)} (${d.out}); rename one.` }); + byOut.set(d.out, d.src); + if (d.draft) { out.push({ level: "info", src: d.src, message: "Draft: not published." }); continue; } + if (d.titleFromFile) out.push({ level: "warn", src: d.src, message: `No title; using “${d.title}” from the file name. Add a # heading or title: in front matter.` }); + if (!d.isIntro && d.text.length < 20) out.push({ level: "warn", src: d.src, message: "Almost empty article." }); + if (d.stripped.length) out.push({ level: "info", src: d.src, message: `Removed ${d.stripped.join(", ")} (help articles don't run scripts).` }); + for (const l of d.links) { + if (l.kind === "external") continue; + if (l.target === null) { out.push({ level: "error", src: d.src, message: `Link ${l.href} points outside the docs folder.` }); continue; } + if (l.kind === "asset") { if (!assetSet.has(l.target)) out.push({ level: "error", src: d.src, message: `Broken link: ${l.href} (file not found).` }); continue; } + const t = docBy.get(l.target) ?? findDoc(l.target); + if (!t) { out.push({ level: "error", src: d.src, message: `Broken link: ${l.href} (no such article).` }); continue; } + if (t.draft) out.push({ level: "warn", src: d.src, message: `Links to draft ${t.src}.` }); + if (l.anchor && !t.ids.includes(l.anchor)) out.push({ level: "warn", src: d.src, message: `Missing anchor: ${l.href} (no #${l.anchor} in ${t.src}).` }); + } + for (const r of d.related) if (!m.docs.some((x) => x.src === r || x.out === r || x.src.replace(/\.\w+$/, "") === r.replace(/\.\w+$/, ""))) out.push({ level: "warn", src: d.src, message: `related: “${r}” isn't a published article.` }); + } + const titles = new Map<string, string>(); + for (const d of m.docs) { const k = d.title.toLowerCase(); if (titles.has(k)) out.push({ level: "warn", src: d.src, message: `Same title as ${titles.get(k)}: “${d.title}”.` }); else titles.set(k, d.src); } + for (const c of m.site.categories) if (!m.categories.some((x) => x.key === (c.key ?? c.folder) || x.name === c.name)) out.push({ level: "info", src: CONFIG, message: `Category “${c.name ?? c.folder}” has no articles.` }); + return out; + } + + async function build(docsDir: string, outDir: string, overrides: Partial<SiteConf>, full: boolean) { + const t0 = Date.now(); + const { model, assetsIn, issues } = await read(docsDir, overrides, [outDir, ...Object.keys(await load())]); + if (issues.some((i) => i.level === "error" && /Same output page/.test(i.message))) throw new KitError("conflict", issues.filter((i) => /Same output page/.test(i.message)).map((i) => `${i.src}: ${i.message}`).join("\n")); + const all = await load(); + const prev = all[outDir]; + const first = !prev; + const files: Record<string, string> = {}; + const pagesParts: Record<string, Record<string, string>> = {}; + const rebuilt: Rebuilt[] = []; + const copied: string[] = []; + let unchanged = 0, bytes = 0; + const write = async (p: string, data: string | Uint8Array) => { await ws.write(`${outDir}/${p}`, data); bytes += typeof data === "string" ? Buffer.byteLength(data) : data.length; }; + const exists = (p: string) => ws.exists(`${outDir}/${p}`); + for (const p of plan(model)) { + pagesParts[p.out] = p.parts; + const old = prev?.pages[p.out]; + let reasons: string[] = []; + if (full) reasons = ["full"]; + else if (!old) reasons = ["new"]; + else { + reasons = Object.keys(p.parts).filter((k) => old[k] !== p.parts[k]); + if (!reasons.length && !(await exists(p.out))) reasons = ["missing"]; + } + files[p.out] = sha(JSON.stringify(p.parts)); + if (!reasons.length) { unchanged++; continue; } + await write(p.out, p.render()); + rebuilt.push({ out: p.out, kind: p.kind, reasons, ...(p.src ? { src: p.src } : {}) }); + } + for (const a of RUNTIME_ASSETS) { + const data = await readFile(join(assets, a)); + const h = sha(data); + files[`assets/${a}`] = h; + if (full || prev?.files[`assets/${a}`] !== h || !(await exists(`assets/${a}`))) { await write(`assets/${a}`, data); copied.push(`assets/${a}`); } + } + for (const a of assetsIn) { + const data = await ws.read(a.path); + const h = sha(data); + files[a.rel] = h; + if (full || prev?.files[a.rel] !== h || !(await exists(a.rel))) { await write(a.rel, data); copied.push(a.rel); } + } + const sd = searchDocs(model); + const ms = new MiniSearch({ fields: FIELDS, storeFields: [], tokenize: hcTokenize, processTerm: (t: string) => t }); + ms.addAll(sd.map(({ show: _s, ...d }) => d)); + const searchH = sha(JSON.stringify(sd) + TEMPLATE_VERSION); + files["search-index.js"] = searchH; + const searchRebuilt = full || prev?.files["search-index.js"] !== searchH || !(await exists("search-index.js")); + if (searchRebuilt) await write("search-index.js", `window.HC_SEARCH=${JSON.stringify({ fields: FIELDS, index: ms.toJSON(), docs: Object.fromEntries(sd.map((d) => [d.id, d.show])) }).replace(/</g, "\\u003c")};\n`); + if (model.site.baseUrl) { + const base = model.site.baseUrl.replace(/\/+$/, ""); + const urls = plan(model).filter((p) => p.kind !== "404" && p.kind !== "search").map((p) => ` <url><loc>${base}/${p.out.split("/").map(encodeURIComponent).join("/").replace(/&/g, "&")}</loc>${p.src && model.bySrc.get(p.src)?.updated ? `<lastmod>${model.bySrc.get(p.src)!.updated}</lastmod>` : ""}</url>`); + const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join("\n")}\n</urlset>\n`; + const h = sha(xml); + files["sitemap.xml"] = h; + if (full || prev?.files["sitemap.xml"] !== h || !(await exists("sitemap.xml"))) { await write("sitemap.xml", xml); copied.push("sitemap.xml"); } + } + const removed: string[] = []; + for (const old of Object.keys(prev?.files ?? {})) if (!(old in files)) { await rm(ws.resolve(`${outDir}/${old}`), { force: true }); removed.push(old); } + const summary: Summary = { pages: Object.keys(pagesParts).length, articles: model.docs.length, categories: model.categories.map((c) => ({ name: c.name, out: c.out, count: c.docs.length })), rebuilt, unchanged, removed, copied, issues, ms: Date.now() - t0, full, first, searchRebuilt, lang: model.site.lang, bytes }; + all[outDir] = { docs: docsDir, out: outDir, builtAt: new Date().toISOString(), pages: pagesParts, files, site: model.site, summary }; + await save(all); + return { summary, model }; + } + + const describe = (docs: string, out: string, s: Summary) => { + const errs = s.issues.filter((i) => i.level === "error"), warns = s.issues.filter((i) => i.level === "warn"); + return [ + `${s.first ? "Built" : s.full ? "Fully rebuilt" : "Updated"} ${out}/ from ${docs}/: ${s.articles} articles in ${s.categories.length} categories, ${s.pages} pages (${s.ms} ms).`, + s.first || s.full ? `Wrote all ${s.rebuilt.length} pages${s.copied.length ? ` and ${s.copied.length} assets` : ""}.` : `Rebuilt ${s.rebuilt.length} page(s), ${s.unchanged} unchanged${s.removed.length ? `, removed ${s.removed.length}` : ""}${s.copied.length ? `, copied ${s.copied.length} asset(s)` : ""}; search index ${s.searchRebuilt ? "rebuilt" : "unchanged"}.`, + ...(!s.first && !s.full ? s.rebuilt.slice(0, 40).map((r) => ` ↻ ${r.out} — ${r.reasons.map((k) => REASONS[k]?.en ?? k).join(", ")}`) : []), + ...s.removed.map((r) => ` ✕ ${r}`), + errs.length || warns.length ? `Problems: ${errs.length} error(s), ${warns.length} warning(s):` : "No broken links or other problems.", + ...[...errs, ...warns].slice(0, 30).map((i) => ` ${i.level === "error" ? "✗" : "!"} ${i.src}: ${i.message}`), + `Open ${out}/index.html in a browser, or upload the ${out}/ folder to any static host (Cloudflare Pages, Netlify, GitHub Pages, S3).`, + ].join("\n"); + }; + const siteArgs = { + title: z.string().max(80).optional().describe(`Site title (else ${CONFIG} → "Help Center")`), + description: z.string().max(200).optional(), + accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("Brand colour"), + baseUrl: z.string().url().optional().describe("Public URL, for canonical links, sitemap.xml and 404.html"), + lang: z.enum(["en", "zh-CN"]).optional().describe("Site UI language (auto-detected)"), + }; + + tool("hc_scan", { + description: `Look at a docs folder (Markdown / HTML, optional ${CONFIG}) without writing anything: categories, articles, language, and problems such as broken links, missing anchors, missing titles and duplicate titles.`, + input: { docs: z.string().describe("Docs folder"), ...siteArgs }, readOnly: true, + }, async (i) => { + const docs = norm(i.docs, "docs"); + const { model, issues, assetsIn } = await read(docs, i, Object.keys(await load())); + const cats = model.categories.map((c) => ({ name: c.name, out: c.out, articles: c.docs.map((d) => ({ src: d.src, title: d.title, tags: d.tags })) })); + return { + text: [`${docs}/: ${model.docs.length} articles in ${cats.length} categories (${model.site.lang}), ${assetsIn.length} other files.`, ...cats.map((c) => ` ${c.name}: ${c.articles.map((a) => a.title).join(" · ")}`), issues.length ? `Problems:\n${issues.map((x) => ` ${x.level === "error" ? "✗" : x.level === "warn" ? "!" : "·"} ${x.src}: ${x.message}`).join("\n")}` : "No problems found."].join("\n"), + structured: { kind: "scan", docs, site: model.site, categories: cats, issues }, + }; + }); + + tool("hc_build", { + description: "Build (or update) a static help center from a docs folder: home page with category cards, category pages, article pages with breadcrumbs, sidebar, table of contents, related articles and previous/next, full-text search (works offline, Chinese too), 404 and sitemap. Incremental: only pages whose content or dependencies changed are rewritten, and they are listed with the reason.", + input: { docs: z.string().describe("Docs folder with .md / .html files (sub-folders = categories)"), out: z.string().optional().describe("Output folder (default help-center)"), full: z.boolean().optional().describe("Rewrite every page"), ...siteArgs }, + openPanel: true, timeoutMs: 180_000, + }, async (i) => { + const docs = norm(i.docs, "docs"); + const out = norm(i.out ?? "help-center", "out"); + if (out === "." || out === docs || docs.startsWith(`${out}/`)) throw new KitError("bad_out", "Choose an output folder that is separate from the docs folder."); + const known = await load(); + if (!known[out] && (await ws.exists(`${out}/index.html`))) throw new KitError("exists", `${out}/ already has a site that this plugin didn't build; choose another out.`); + const { summary } = await build(docs, out, { title: i.title, description: i.description, accent: i.accent, baseUrl: i.baseUrl, lang: i.lang }, !!i.full); + return { text: describe(docs, out, summary), structured: { kind: "build", docs, out, summary } }; + }); + + tool("hc_preview", { + description: "Static preview of a built page for the panel (styles inlined, scripts removed).", + input: { out: z.string(), page: z.string().optional() }, readOnly: true, visibility: ["app"], + }, async (i) => { + const out = norm(i.out, "out"); + const page = (i.page ?? "index.html").replace(/^\/+/, ""); + if (!page.endsWith(".html") || page.includes("..")) throw new KitError("bad_page", "Choose an .html page of the site."); + let html = await ws.readText(`${out}/${page}`); + const css = await ws.readText(`${out}/assets/style.css`).catch(() => ""); + const dir = page.includes("/") ? page.slice(0, page.lastIndexOf("/") + 1) : ""; + html = html.replace(/<link rel="stylesheet"[^>]*>/, `<style>${css}</style>`).replace(/<script\b[\s\S]*?<\/script>/gi, ""); + const imgs = [...html.matchAll(/<img\b[^>]*\ssrc="([^"]+)"/g)].map((m) => m[1]).filter((s) => !/^(data:|https?:)/.test(s)); + for (const src of new Set(imgs)) { + const parts = (dir + decodeURIComponent(src)).split("/"), stack: string[] = []; + for (const p of parts) { if (p === "..") stack.pop(); else if (p && p !== ".") stack.push(p); } + const b = await ws.read(`${out}/${stack.join("/")}`, 2 * 1024 * 1024).catch(() => null); + if (b) html = html.split(`src="${src}"`).join(`src="data:${/\.svg$/i.test(src) ? "image/svg+xml" : /\.png$/i.test(src) ? "image/png" : /\.gif$/i.test(src) ? "image/gif" : /\.webp$/i.test(src) ? "image/webp" : "image/jpeg"};base64,${b.toString("base64")}"`); + } + return { text: `${out}/${page}`, structured: { kind: "preview", page, html } }; + }); + + tool("hc_state", { + description: "Panel state: previous builds and candidate docs folders.", input: {}, readOnly: true, visibility: ["app"], + }, async () => { + const all = await load(); + const md = await ws.list({ exts: [".md", ".markdown", ".html", ".htm"], limit: 3000 }); + const builtOut = Object.keys(all); + const folders = new Map<string, number>(); + for (const f of md) { + if (builtOut.some((o) => f.path.startsWith(`${o}/`))) continue; + const top = f.path.includes("/") ? f.path.split("/")[0] : "."; + folders.set(top, (folders.get(top) ?? 0) + 1); + } + const builds = Object.values(all).sort((a, b) => b.builtAt.localeCompare(a.builtAt)).map((b) => ({ docs: b.docs, out: b.out, builtAt: b.builtAt, summary: b.summary, title: b.site.title })); + return { text: builds.length ? `Last build: ${builds[0].out}/` : "No builds yet.", structured: { kind: "state", builds, folders: [...folders.entries()].filter(([, n]) => n > 0).map(([path, count]) => ({ path, count })) } }; + }); + + return server; +} diff --git a/ui-plugins/help-center-builder/src/site.ts b/ui-plugins/help-center-builder/src/site.ts new file mode 100644 index 00000000..5fac839d --- /dev/null +++ b/ui-plugins/help-center-builder/src/site.ts @@ -0,0 +1,179 @@ +import { type Doc, esc, sha } from "./docs.ts"; + +export const TEMPLATE_VERSION = "1"; +export interface CategoryConf { folder?: string; key?: string; name?: string; description?: string } +export interface SiteConf { title: string; description: string; accent: string; baseUrl?: string; footer?: string; lang: "en" | "zh-CN"; logo?: string; categories: CategoryConf[] } +export interface Category { key: string; name: string; description: string; out: string; docs: Doc[]; intro?: Doc } +export interface Model { site: SiteConf; categories: Category[]; docs: Doc[]; bySrc: Map<string, Doc>; catOf: Map<string, Category>; related: Map<string, Doc[]>; prev: Map<string, Doc | undefined>; next: Map<string, Doc | undefined>; home?: Doc } + +const STR = { + en: { home: "Home", search: "Search help articles…", searchTitle: "Search", onPage: "On this page", related: "Related articles", prev: "Previous", next: "Next", updated: "Updated %s", articles: "%n articles", article: "1 article", all: "All results", none: "No results for “%s”", count: "%n results for “%s”", categories: "Categories", viewAll: "View all %n →", notFound: "Page not found", notFoundText: "The page you were looking for doesn't exist. Try searching:", inCat: "In this category", general: "General", heroQ: "How can we help?" }, + "zh-CN": { home: "首页", search: "搜索帮助文章…", searchTitle: "搜索", onPage: "本页内容", related: "相关文章", prev: "上一篇", next: "下一篇", updated: "更新于 %s", articles: "%n 篇文章", article: "1 篇文章", all: "全部结果", none: "没有找到“%s”的结果", count: "“%s”共 %n 条结果", categories: "分类", viewAll: "查看全部 %n 篇 →", notFound: "页面不存在", notFoundText: "你要找的页面不存在,试试搜索:", inCat: "本分类文章", general: "常规", heroQ: "有什么可以帮你?" }, +}; +export const strings = (lang: SiteConf["lang"]) => STR[lang]; +const pretty = (folder: string) => (/[\p{Script=Han}]/u.test(folder) ? folder : folder.replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase())); +const catKey = (s: string) => s.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "") || "general"; + +export function detectLang(docs: Doc[]): SiteConf["lang"] { + const sample = docs.map((d) => d.title + d.text.slice(0, 400)).join(" "); + const han = (sample.match(/\p{Script=Han}/gu) ?? []).length; + return han > sample.length * 0.15 ? "zh-CN" : "en"; +} + +/** 分类、排序、相关文章、上一篇/下一篇。 */ +export function buildModel(all: Doc[], site: SiteConf): Model { + const docs = all.filter((d) => !d.draft && !d.isIntro); + const intros = all.filter((d) => d.isIntro && !d.draft); + const S = strings(site.lang); + const cats = new Map<string, Category>(); + const confFor = (key: string) => site.categories.find((c) => (c.key ?? c.folder) === key || (c.name && catKey(c.name) === key)); + const get = (key: string, name?: string) => { + let c = cats.get(key); + if (!c) { + const conf = confFor(key); + c = { key, name: conf?.name ?? name ?? (key === "general" ? S.general : pretty(key)), description: conf?.description ?? "", out: `${key}/index.html`, docs: [] }; + cats.set(key, c); + } + return c; + }; + const catOf = new Map<string, Category>(); + for (const d of docs) { + let key = d.folder || "general"; + if (d.categoryName) { const conf = site.categories.find((c) => c.name === d.categoryName); key = conf ? (conf.key ?? conf.folder ?? catKey(d.categoryName)) : catKey(d.categoryName); } + const c = get(key, d.categoryName); + c.docs.push(d); + catOf.set(d.src, c); + } + for (const i of intros) { const key = i.folder || ""; if (key && cats.has(key)) { const c = cats.get(key)!; c.intro = i; if (!c.description) c.description = i.description; } } + const home = intros.find((i) => !i.folder); + const confOrder = (c: Category) => { const i = site.categories.findIndex((x) => x === confFor(c.key)); return i < 0 ? 1e6 : i; }; + const categories = [...cats.values()].sort((a, b) => confOrder(a) - confOrder(b) || a.name.localeCompare(b.name, site.lang)); + for (const c of categories) c.docs.sort((a, b) => a.order - b.order || a.title.localeCompare(b.title, site.lang)); + const ordered = categories.flatMap((c) => c.docs); + const bySrc = new Map(all.map((d) => [d.src, d])); + const prev = new Map<string, Doc | undefined>(), next = new Map<string, Doc | undefined>(); + for (const c of categories) c.docs.forEach((d, i) => { prev.set(d.src, c.docs[i - 1]); next.set(d.src, c.docs[i + 1]); }); + // 相关文章:先用 front matter 里的 related,再按共同标签(×3)、同分类(×1)、标题与小标题词重合度补足到 5 篇。 + const words = new Map(ordered.map((d) => [d.src, new Set(`${d.title} ${d.headings.map((h) => h.text).join(" ")}`.toLowerCase().match(/[\p{L}\p{N}]{3,}|\p{Script=Han}{2}/gu) ?? [])])); + const related = new Map<string, Doc[]>(); + for (const d of ordered) { + const picked: Doc[] = []; + for (const r of d.related) { const t = bySrc.get(r) ?? bySrc.get(r.replace(/\.html$/, ".md")) ?? ordered.find((x) => x.out === r || x.src.replace(/\.\w+$/, "") === r.replace(/\.\w+$/, "")); if (t && t !== d && !t.draft && !t.isIntro && !picked.includes(t)) picked.push(t); } + const wd = words.get(d.src)!; + const scored = ordered.filter((o) => o !== d && !picked.includes(o)).map((o) => { + const shared = o.tags.filter((t) => d.tags.map((x) => x.toLowerCase()).includes(t.toLowerCase())).length; + const wo = words.get(o.src)!; + const overlap = [...wd].filter((w) => wo.has(w)).length; + return { o, s: shared * 3 + (catOf.get(o.src) === catOf.get(d.src) ? 1 : 0) + overlap * 0.5 }; + }).filter((x) => x.s >= 2).sort((a, b) => b.s - a.s || a.o.title.localeCompare(b.o.title)); + for (const x of scored) { if (picked.length >= 5) break; picked.push(x.o); } + related.set(d.src, picked.slice(0, 5)); + } + return { site, categories, docs: ordered, bySrc, catOf, related, prev, next, home }; +} + +// ---------- 模板 ---------- +const rootOf = (out: string) => "../".repeat(out.split("/").length - 1); +const rel = (from: string, to: string) => rootOf(from) + to.split("/").map(encodeURIComponent).join("/"); +function layout(m: Model, out: string, title: string, body: string, opts: { hero?: boolean; desc?: string } = {}) { + const S = strings(m.site.lang), R = rootOf(out); + const ui = JSON.stringify({ all: S.all, none: S.none, count: S.count }); + const search = (cls = "") => `<form class="search${cls}" action="${R}search.html" role="search"><input type="search" name="q" placeholder="${esc(S.search)}" aria-label="${esc(S.searchTitle)}" autocomplete="off"><div class="results" hidden></div></form>`; + const brand = `<a class="brand" href="${R}index.html">${m.site.logo ? `<img src="${R}${esc(m.site.logo)}" alt="">` : `<span class="dot"></span>`}${esc(m.site.title)}</a>`; + return `<!doctype html> +<html lang="${m.site.lang}" data-root="${R}" data-strings="${esc(ui)}"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width,initial-scale=1"> +<title>${esc(title === m.site.title ? title : `${title} · ${m.site.title}`)} +${opts.desc ? `\n` : ""}${m.site.baseUrl ? `\n` : ""} + + + +
${brand}${opts.hero ? "" : search()}
+${body} +
${esc(m.site.footer ?? m.site.title)}
+ + + + + + +`.replace("__HERO_SEARCH__", search()); +} +/** 正文里的相对链接:.md → .html(输出目录与源目录结构一致,其余相对路径不变)。 */ +function fixLinks(html: string) { + return html.replace(/(\shref\s*=\s*["'])([^"']*)(["'])/gi, (all, a: string, href: string, b: string) => (/^[a-z][a-z0-9+.-]*:|^\/\/|^#/i.test(href) ? all : a + href.replace(/\.(md|markdown|htm)(?=$|[#?])/i, ".html") + b)); +} +const cnt = (S: ReturnType, n: number) => (n === 1 ? S.article : S.articles.replace("%n", String(n))); + +function sidebar(m: Model, out: string, cur?: Category, curDoc?: Doc) { + const S = strings(m.site.lang); + const docs = cur ? `

${esc(cur.name)}

` : ""; + return ``; +} + +export function renderArticle(m: Model, d: Doc) { + const S = strings(m.site.lang), c = m.catOf.get(d.src)!, out = d.out; + const crumbs = `
${esc(S.home)}›${esc(c.name)}›${esc(d.title)}
`; + const toc = d.headings.filter((h) => h.level === 2 || h.level === 3); + const rl = m.related.get(d.src) ?? []; + const p = m.prev.get(d.src), n = m.next.get(d.src); + const body = `
${sidebar(m, out, c, d)}
${crumbs}

${esc(d.title)}

${d.updated ? `
${esc(S.updated.replace("%s", d.updated))}
` : ""}${d.description ? `

${esc(d.description)}

` : ""} +${fixLinks(d.html)} +
${rl.length ? `` : ""}${p || n ? `` : ""}
${toc.length >= 2 ? `` : ""}
`; + return layout(m, out, d.title, body, { desc: d.excerpt }); +} +export function renderCategory(m: Model, c: Category) { + const S = strings(m.site.lang), out = c.out; + const body = `
${sidebar(m, out, c)}
${esc(S.home)}›${esc(c.name)}

${esc(c.name)} ${esc(cnt(S, c.docs.length))}

${c.description ? `

${esc(c.description)}

` : ""}${c.intro ? `
${fixLinks(c.intro.html)}
` : ""}
`; + return layout(m, out, c.name, body, { desc: c.description }); +} +export function renderHome(m: Model) { + const S = strings(m.site.lang), out = "index.html"; + const cards = m.categories.map((c) => `

${esc(c.name)} ${esc(cnt(S, c.docs.length))}

${c.description ? `

${esc(c.description)}

` : ""}${c.docs.length > 5 ? `${esc(S.viewAll.replace("%n", String(c.docs.length)))}` : ""}
`).join(""); + const body = `

${esc(m.home?.title && !m.home.titleFromFile ? m.home.title : S.heroQ)}

${esc(m.site.description)}

__HERO_SEARCH__
${m.home ? `
${fixLinks(m.home.html)}
` : ""}
${cards}
`; + return layout(m, out, m.site.title, body, { hero: true, desc: m.site.description }); +} +export function renderSearch(m: Model) { + const S = strings(m.site.lang), out = "search.html"; + return layout(m, out, S.searchTitle, `
${sidebar(m, out)}

${esc(S.searchTitle)}

`); +} +export function render404(m: Model) { + const S = strings(m.site.lang), out = "404.html"; + // 静态托管(Cloudflare Pages、Netlify 等)会在任意路径返回 404.html,相对路径会失效:有 baseUrl 用它,否则用站点根 "/"。 + const html = layout(m, out, S.notFound, `

${esc(S.notFound)}

${esc(S.notFoundText)}

${esc(S.home)}

`); + const base = m.site.baseUrl ? m.site.baseUrl.replace(/\/+$/, "") + "/" : "/"; + return html.replace(/(href|src)="(?!https?:|#|data:)([^"]+)"/g, (_, a: string, u: string) => `${a}="${base}${u}"`).replace('data-root=""', `data-root="${base}"`); +} + +/** 搜索文档(minisearch 输入)与展示数据。 */ +export function searchDocs(m: Model) { + return m.docs.map((d, i) => ({ id: i, title: d.title, headings: d.headings.map((h) => h.text).join(" · "), tags: d.tags.join(" "), text: `${d.description} ${d.text}`, show: { t: d.title, c: m.catOf.get(d.src)!.name, u: d.out.split("/").map(encodeURIComponent).join("/"), d: d.excerpt } })); +} + +// ---------- 依赖指纹(增量构建) ---------- +export type Parts = Record; +export interface PagePlan { out: string; kind: "article" | "category" | "home" | "search" | "404"; parts: Parts; render: () => string; src?: string } +export function plan(m: Model): PagePlan[] { + const siteH = sha(JSON.stringify({ ...m.site, categories: undefined })); + const catsH = sha(JSON.stringify(m.categories.map((c) => [c.key, c.name, c.out]))); + const navH = (c: Category) => sha(JSON.stringify(c.docs.map((d) => [d.title, d.out]))); + const pages: PagePlan[] = []; + for (const d of m.docs) { + const c = m.catOf.get(d.src)!; + const p = m.prev.get(d.src), n = m.next.get(d.src); + pages.push({ out: d.out, kind: "article", src: d.src, render: () => renderArticle(m, d), parts: { content: d.hash, nav: navH(c), category: sha(JSON.stringify([c.name, c.out])), cats: catsH, related: sha(JSON.stringify((m.related.get(d.src) ?? []).map((r) => [r.title, r.out]))), prevnext: sha(JSON.stringify([p?.title, p?.out, n?.title, n?.out])), site: siteH, tpl: TEMPLATE_VERSION } }); + } + for (const c of m.categories) pages.push({ out: c.out, kind: "category", render: () => renderCategory(m, c), parts: { list: sha(JSON.stringify(c.docs.map((d) => [d.title, d.out, d.excerpt]))), intro: c.intro?.hash ?? "", category: sha(JSON.stringify([c.name, c.description])), cats: catsH, site: siteH, tpl: TEMPLATE_VERSION } }); + pages.push({ out: "index.html", kind: "home", render: () => renderHome(m), parts: { list: sha(JSON.stringify(m.categories.map((c) => [c.name, c.description, c.docs.length, c.docs.slice(0, 5).map((d) => [d.title, d.out])]))), intro: m.home?.hash ?? "", cats: catsH, site: siteH, tpl: TEMPLATE_VERSION } }); + pages.push({ out: "search.html", kind: "search", render: () => renderSearch(m), parts: { cats: catsH, site: siteH, tpl: TEMPLATE_VERSION } }); + pages.push({ out: "404.html", kind: "404", render: () => render404(m), parts: { site: siteH, tpl: TEMPLATE_VERSION } }); + return pages; +} +export const REASONS: Record = { + new: { en: "new page", zh: "新页面" }, missing: { en: "output file was missing", zh: "输出文件缺失" }, full: { en: "full rebuild", zh: "全量重建" }, + content: { en: "content changed", zh: "内容改了" }, nav: { en: "category's article list changed", zh: "同分类文章列表变了" }, category: { en: "category renamed or moved", zh: "所属分类改了" }, + cats: { en: "category list changed", zh: "分类列表变了" }, related: { en: "related articles changed", zh: "相关文章变了" }, prevnext: { en: "previous/next article changed", zh: "上一篇/下一篇变了" }, + site: { en: "site settings changed", zh: "站点设置改了" }, tpl: { en: "template updated", zh: "模板更新" }, list: { en: "article list changed", zh: "文章列表变了" }, intro: { en: "intro text changed", zh: "介绍文字改了" }, +}; From d8eb6396b7e0bac7e6f1c34f61797c98b79613d9 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:31:57 -0400 Subject: [PATCH 07/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../help-center-builder/test/tools.test.ts | 177 ++++++++++++++++++ .../test/workspace-links.test.ts | 43 +++++ 2 files changed, 220 insertions(+) create mode 100644 ui-plugins/help-center-builder/test/tools.test.ts create mode 100644 ui-plugins/help-center-builder/test/workspace-links.test.ts diff --git a/ui-plugins/help-center-builder/test/tools.test.ts b/ui-plugins/help-center-builder/test/tools.test.ts new file mode 100644 index 00000000..4f25ac6b --- /dev/null +++ b/ui-plugins/help-center-builder/test/tools.test.ts @@ -0,0 +1,177 @@ +import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import MiniSearch from "minisearch"; +import { beforeAll, describe, expect, it } from "vitest"; +import { parseDoc, slugify } from "../src/docs.ts"; +import { createServer } from "../src/server.ts"; + +// 样例:虚构的 Harbor Bikes 帮助中心(英文,14 篇 Markdown + 1 篇 CMS 导出的 HTML,5 个分类)、虚构中文帮助中心(小站记账)、真实的 ripgrep 文档(GUIDE/FAQ/README)。 +const S = process.env.HELP_SAMPLES ?? "/workspace/zcode-new-plugins/samples/help"; +const DIST = join(import.meta.dirname, "../dist"); +const tokenize = new Function(`${readFileSync(join(DIST, "runtime/assets/tokenize.js"), "utf8")}\nreturn hcTokenize;`)() as (s: string) => string[]; +let ws: string; +let call: (name: string, args: Record) => Promise; +const out = (p: string) => readFileSync(join(ws, "help-center", p), "utf8"); +const search = (dir: string, q: string) => { + const js = readFileSync(join(ws, dir, "search-index.js"), "utf8"); + const data = JSON.parse(js.slice("window.HC_SEARCH=".length, -2)); + const ms = MiniSearch.loadJSON(JSON.stringify(data.index), { fields: data.fields, storeFields: [], tokenize, processTerm: (t: string) => t }); + return ms.search(q, { boost: { title: 4, tags: 3, headings: 2 }, prefix: (t: string) => t.length > 2, combineWith: "AND" }).map((r) => data.docs[r.id].t); +}; +beforeAll(async () => { + ws = mkdtempSync(join(tmpdir(), "hcb-")); + cpSync(join(S, "harbor"), join(ws, "docs"), { recursive: true }); + cpSync(join(S, "zh"), join(ws, "zh"), { recursive: true }); + cpSync(join(S, "ripgrep"), join(ws, "rg"), { recursive: true }); + const server = createServer({ workspaceRoot: ws, assetRoot: DIST }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + call = async (name, args) => (await client.callTool({ name, arguments: args })) as any; +}); + +describe("parsing", () => { + it("reads front matter, headings, links and cleans HTML exports", () => { + const d = parseDoc("getting-started/create-account.md", readFileSync(join(S, "harbor/getting-started/create-account.md"), "utf8")); + expect(d).toMatchObject({ title: "Create a Harbor Bikes account", folder: "getting-started", order: 1, tags: ["account", "signup", "app"], updated: "2026-10-02" }); + expect(d.headings.map((h) => h.id)).toEqual(["what-you-need", "sign-up-in-the-app", "sign-up-on-the-web"]); + expect(d.links.filter((l) => l.kind !== "external").map((l) => `${l.kind}:${l.target}`)).toEqual(["asset:images/signup.png", "doc:billing/company-accounts.md", "doc:getting-started/first-ride.md"]); + const h = parseDoc("account/contact-support.html", readFileSync(join(S, "harbor/account/contact-support.html"), "utf8")); + expect(h).toMatchObject({ title: "Contact support", description: "Reach a person by chat, email or phone.", tags: ["support", "contact", "phone"] }); + expect(h.html).not.toMatch(/onclick|alert(1)x"); + expect(x.title).toBe("Setup"); + expect(x.headings.map((h) => h.id)).toEqual(["setup", "常见-问题"]); + expect(x.html).not.toMatch(/script|javascript:/); + expect(parseDoc("r.md", "ripgrep (rg)\n------------\nbody text").title).toBe("ripgrep (rg)"); + expect(slugify("What's new in v2.0?")).toBe("whats-new-in-v20"); + }); + it("tokenizes Latin words and CJK bigrams the same way as the browser", () => { + expect(tokenize("Refund e-bike 会员退款")).toEqual(["refund", "e-bike", "e", "bike", "会", "会员", "员", "员退", "退", "退款", "款"]); + }); +}); + +describe("build", () => { + it("builds the whole help center", async () => { + const r = await call("hc_build", { docs: "docs" }); + expect(r.isError).toBeFalsy(); + const s = r.structuredContent.summary; + expect(s).toMatchObject({ articles: 15, pages: 23, first: true, lang: "en" }); + expect(s.categories.map((c: { name: string; count: number }) => `${c.name}:${c.count}`)).toEqual(["Getting started:3", "Rentals & bookings:4", "Billing & payments:3", "Bikes & safety:3", "Your account:2"]); + expect(s.issues.filter((i: { level: string }) => i.level !== "info")).toEqual([]); + const home = out("index.html"); + expect(home).toMatch(/Harbor Bikes Help Center<\/title>/); + expect(home).toContain('href="billing/index.html">Billing & payments</a>'); + const a = out("billing/refunds.html"); + expect(a).toMatch(/<div class="crumbs"><a href="..\/index.html">Home<\/a><span>›<\/span><a href="..\/billing\/index.html">Billing & payments<\/a><span>›<\/span>Refunds<\/div>/); + expect(a).toContain('<a href="../billing/refunds.html" class="on" aria-current="page">Refunds</a>'); + expect(a).toMatch(/class="prev" href="..\/billing\/deposits.html"/); + expect(a).toMatch(/class="next" href="..\/billing\/company-accounts.html"/); + expect(a).toContain('<link rel="canonical" href="https://help.harborbikes.example/billing/refunds.html">'); + const related = out("rentals/change-or-cancel.html").match(/<section class="related">([\s\S]*?)<\/section>/)![1]; + expect(related.match(/href="([^"]+)"/)![1]).toBe("../billing/refunds.html"); // front matter related 排第一 + expect(out("getting-started/create-account.html")).toContain('href="../billing/company-accounts.html"'); + expect(out("getting-started/create-account.html")).toContain('src="../images/signup.png"'); + expect(existsSync(join(ws, "help-center/images/signup.png"))).toBe(true); + expect(out("billing/deposits.html")).toContain('href="../account/contact-support.html"'); + expect(out("account/contact-support.html")).not.toMatch(/onclick|trackingPixel/); + expect(out("bikes/battery.html")).toMatch(/<div class="table-wrap"><table>/); + expect(out("getting-started/create-account.html")).toMatch(/<aside class="toc">.*href="#what-you-need"/s); + expect(out("sitemap.xml").match(/<url>/g)!.length).toBe(21); + expect(out("404.html")).toContain('href="https://help.harborbikes.example/assets/style.css"'); + expect(search("help-center", "refund")[0]).toBe("Refunds"); + expect(search("help-center", "battery range")[0]).toBe("Charging an e-bike battery"); + expect(search("help-center", "dock full")).toContain("Ending a rental when a station is full"); + expect(search("help-center", "chat")).toContain("Contact support"); + }); + it("rebuilds only what a change affects, and says why", async () => { + const again = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + expect(again).toMatchObject({ rebuilt: [], unchanged: 23, searchRebuilt: false, copied: [] }); + const f = join(ws, "docs/billing/refunds.md"); + const orig = readFileSync(f, "utf8"); + writeFileSync(f, orig.replace("3–5 working days**.", "3–5 working days** (Revolut: instant).")); + let s = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + expect(s.rebuilt).toEqual([{ out: "billing/refunds.html", kind: "article", reasons: ["content"], src: "billing/refunds.md" }]); + expect(s.searchRebuilt).toBe(true); + expect(search("help-center", "revolut")).toEqual(["Refunds"]); + writeFileSync(f, readFileSync(f, "utf8").replace("title: Refunds", "title: Refunds and chargebacks")); + s = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + const by = Object.fromEntries(s.rebuilt.map((r: { out: string; reasons: string[] }) => [r.out, r.reasons])); + expect(by["billing/refunds.html"]).toContain("content"); + expect(by["billing/deposits.html"]).toEqual(expect.arrayContaining(["nav", "prevnext"])); + expect(by["billing/company-accounts.html"]).toEqual(expect.arrayContaining(["nav", "prevnext"])); + expect(by["rentals/change-or-cancel.html"]).toEqual(["related"]); + expect(by["billing/index.html"]).toEqual(["list"]); + expect(by["index.html"]).toEqual(["list"]); + expect(by["bikes/battery.html"]).toEqual(["related"]); // 共同标签 charge → 相关文章里有 Refunds + expect(Object.keys(by).sort()).toEqual(["bikes/battery.html", "billing/company-accounts.html", "billing/deposits.html", "billing/index.html", "billing/refunds.html", "index.html", "rentals/change-or-cancel.html"]); + expect(s.unchanged).toBe(23 - s.rebuilt.length); + writeFileSync(join(ws, "docs/billing/vat-invoices.md"), "---\ntitle: VAT invoices\norder: 4\ntags: [invoice, business]\n---\nDownload a VAT invoice for any ride from **Rides → Receipt**.\n"); + s = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + expect(s.rebuilt.find((r: { out: string }) => r.out === "billing/vat-invoices.html").reasons).toEqual(["new"]); + expect(s.pages).toBe(24); + rmSync(join(ws, "docs/billing/vat-invoices.md")); + s = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + expect(s.removed).toEqual(["billing/vat-invoices.html"]); + expect(existsSync(join(ws, "help-center/billing/vat-invoices.html"))).toBe(false); + rmSync(join(ws, "help-center/bikes/battery.html")); + s = (await call("hc_build", { docs: "docs" })).structuredContent.summary; + expect(s.rebuilt).toEqual([{ out: "bikes/battery.html", kind: "article", reasons: ["missing"], src: "bikes/battery.md" }]); + s = (await call("hc_build", { docs: "docs", accent: "#9333ea" })).structuredContent.summary; + expect(s.rebuilt.length).toBe(23); + expect(s.rebuilt.every((r: { reasons: string[] }) => r.reasons.includes("site"))).toBe(true); + const full = (await call("hc_build", { docs: "docs", accent: "#9333ea", full: true })).structuredContent.summary; + expect(full.rebuilt.length).toBe(23); + writeFileSync(f, orig); + }); + it("reports broken links, anchors, conflicts and drafts", async () => { + cpSync(join(S, "harbor"), join(ws, "bad"), { recursive: true }); + writeFileSync(join(ws, "bad/bikes/battery.md"), readFileSync(join(ws, "bad/bikes/battery.md"), "utf8") + "\nSee [locks](lock-wont-open.md#missing) and [old page](../old/page.md) and ![x](../images/nope.png).\n"); + writeFileSync(join(ws, "bad/bikes/draft.md"), "---\ntitle: Upcoming cargo bikes\ndraft: true\n---\nSoon.\n"); + const r = await call("hc_scan", { docs: "bad" }); + const msgs = r.structuredContent.issues.map((i: { level: string; src: string; message: string }) => `${i.level} ${i.src}: ${i.message}`); + expect(msgs).toEqual(expect.arrayContaining([ + "warn bikes/battery.md: Missing anchor: lock-wont-open.md#missing (no #missing in bikes/lock-wont-open.md).", + "error bikes/battery.md: Broken link: ../old/page.md (no such article).", + "error bikes/battery.md: Broken link: ../images/nope.png (file not found).", + "info bikes/draft.md: Draft: not published.", + ])); + writeFileSync(join(ws, "bad/bikes/battery.html"), "<h1>Dup</h1><p>x</p>"); + const c = await call("hc_build", { docs: "bad", out: "bad-site" }); + expect(c.content[0].text).toMatch(/\[conflict\].*battery/s); + // 输出目录可以放在文档目录里:再次构建时不会把生成的页面当成文档。 + expect((await call("hc_build", { docs: "bad", out: "bad" })).content[0].text).toMatch(/\[bad_out\]/); + rmSync(join(ws, "bad/bikes/battery.html")); + await call("hc_build", { docs: "bad", out: "bad/_site" }); + const second = (await call("hc_build", { docs: "bad", out: "bad/_site" })).structuredContent.summary; + expect(second).toMatchObject({ articles: 15, rebuilt: [] }); + }); + it("Chinese help center: UI language, Unicode paths and CJK search", async () => { + const s = (await call("hc_build", { docs: "zh", out: "zh-site" })).structuredContent.summary; + expect(s).toMatchObject({ articles: 5, lang: "zh-CN" }); + expect(s.categories.map((c: { name: string }) => c.name).sort()).toEqual(["入门", "常见问题"].sort()); + const page = readFileSync(join(ws, "zh-site/常见问题/会员退款.html"), "utf8"); + expect(page).toContain('<html lang="zh-CN"'); + expect(page).toContain(">首页</a>"); + expect(page).toMatch(/相关文章.*%E6%95%B0%E6%8D%AE%E5%AE%89%E5%85%A8\.html/s); + expect(search("zh-site", "退款")[0]).toBe("会员如何退款"); + expect(search("zh-site", "验证码")).toEqual(expect.arrayContaining(["忘记密码怎么办", "注册账号"])); + expect(search("zh-site", "excel")).toEqual(["导入银行账单"]); + }); + it("real ripgrep docs: titles from ## / setext headings, HTML anchors, real broken links", async () => { + const r = await call("hc_build", { docs: "rg", out: "rg-site", title: "ripgrep docs" }); + const s = r.structuredContent.summary; + expect(s.articles).toBe(3); + const scan = await call("hc_scan", { docs: "rg" }); + expect(scan.structuredContent.categories[0].articles.map((a: { title: string }) => a.title).sort()).toEqual(["FAQ", "User Guide", "ripgrep (rg)"]); + expect(s.issues.filter((i: { level: string }) => i.level === "error").map((i: { message: string }) => i.message)).toEqual(["Broken link: CHANGELOG.md (no such article).", "Broken link: CHANGELOG.md (no such article)."]); + expect(s.issues.some((i: { message: string }) => /Missing anchor/.test(i.message))).toBe(false); + expect(search("rg-site", "gitignore")).toContain("User Guide"); + expect(search("rg-site", "pcre2 slower")).toContain("FAQ"); + }); +}); diff --git a/ui-plugins/help-center-builder/test/workspace-links.test.ts b/ui-plugins/help-center-builder/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/help-center-builder/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); From 8d0762b31b08707275d466be62c72c366adfaa49 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:37 -0400 Subject: [PATCH 08/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- ui-plugins/help-center-builder/ui/env.d.ts | 4 + ui-plugins/help-center-builder/ui/kit.css | 34 +++++ ui-plugins/help-center-builder/ui/kit.ts | 133 ++++++++++++++++++++ ui-plugins/help-center-builder/ui/main.ts | 85 +++++++++++++ ui-plugins/help-center-builder/ui/panel.css | 19 +++ 5 files changed, 275 insertions(+) create mode 100644 ui-plugins/help-center-builder/ui/env.d.ts create mode 100644 ui-plugins/help-center-builder/ui/kit.css create mode 100644 ui-plugins/help-center-builder/ui/kit.ts create mode 100644 ui-plugins/help-center-builder/ui/main.ts create mode 100644 ui-plugins/help-center-builder/ui/panel.css diff --git a/ui-plugins/help-center-builder/ui/env.d.ts b/ui-plugins/help-center-builder/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/help-center-builder/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/help-center-builder/ui/kit.css b/ui-plugins/help-center-builder/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/help-center-builder/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/help-center-builder/ui/kit.ts b/ui-plugins/help-center-builder/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/help-center-builder/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise<void> | undefined; +let created!: () => void; +const appCreated = new Promise<void>((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record<string, unknown> | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record<string, unknown> | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise<void> { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record<string, unknown> | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call<T = Record<string, unknown>>(name: string, args: Record<string, unknown> = {}, timeout = 300_000): Promise<T> { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record<string, unknown> | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise<Uint8Array> { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h<K extends keyof HTMLElementTagNameMap>( + tag: K, + props: Record<string, unknown> = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/help-center-builder/ui/main.ts b/ui-plugins/help-center-builder/ui/main.ts new file mode 100644 index 00000000..fdac1fd1 --- /dev/null +++ b/ui-plugins/help-center-builder/ui/main.ts @@ -0,0 +1,85 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface Issue { level: "error" | "warn" | "info"; src: string; message: string } +interface Rebuilt { out: string; kind: string; reasons: string[]; src?: string } +interface Summary { pages: number; articles: number; categories: { name: string; out: string; count: number }[]; rebuilt: Rebuilt[]; unchanged: number; removed: string[]; copied: string[]; issues: Issue[]; ms: number; full: boolean; first: boolean; searchRebuilt: boolean; lang: string; bytes: number } +interface Build { docs: string; out: string; builtAt?: string; summary: Summary; title?: string } +interface ScanCat { name: string; out: string; articles: { src: string; title: string }[] } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const WHY: Record<string, [string, string]> = { new: ["新页面", "new"], missing: ["文件缺失", "file missing"], full: ["全量", "full"], content: ["内容改了", "content"], nav: ["同分类列表变了", "category list"], category: ["分类改了", "category"], cats: ["分类列表变了", "categories"], related: ["相关文章变了", "related"], prevnext: ["上一篇/下一篇变了", "prev/next"], site: ["站点设置", "site settings"], tpl: ["模板", "template"], list: ["文章列表变了", "article list"], intro: ["介绍改了", "intro"] }; +const root = document.getElementById("root")!; +const st: { folders: { path: string; count: number }[]; docs: string; out: string; title: string; build?: Build; scan?: ScanCat[]; page: string; preview?: string } = { folders: [], docs: "", out: "help-center", title: "", page: "index.html" }; + +async function busy<R>(work: () => Promise<R>): Promise<R | undefined> { + root.classList.add("busy"); + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message.replace(/^\[\w+\]\s*/, "") : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); } +} +async function loadScan() { if (!st.build) return; const r = await call<{ categories: ScanCat[] }>("hc_scan", { docs: st.build.docs }).catch(() => undefined); st.scan = r?.categories; } +async function preview(page = st.page) { + if (!st.build) return; + const r = await call<{ html: string; page: string }>("hc_preview", { out: st.build.out, page }).catch(() => undefined); + if (r) { st.page = r.page; st.preview = r.html; } + render(); +} +function take(b: Build) { + st.build = b; st.docs = b.docs; st.out = b.out; + const s = b.summary; + void updateContext(`Help center ${b.out}/ built from ${b.docs}/: ${s.articles} articles, ${s.categories.length} categories; last build rewrote ${s.rebuilt.length} page(s), ${s.unchanged} unchanged; ${s.issues.filter((i) => i.level === "error").length} error(s).`).catch(() => undefined); +} +onToolResult((v) => { if (v?.kind === "build") { take({ docs: v.docs as string, out: v.out as string, summary: v.summary as Summary }); void loadScan().then(() => preview()); } }); +const doBuild = async (full: boolean) => { + if (!st.docs) { toast(T("请先选择文档目录", "Choose the docs folder first"), "error"); return; } + const r = await busy(() => call<{ docs: string; out: string; summary: Summary }>("hc_build", { docs: st.docs, out: st.out || "help-center", ...(st.title ? { title: st.title } : {}), ...(full ? { full: true } : {}) }, 200_000)); + if (!r) return; + take(r); await loadScan(); await preview(); + const s = r.summary; + toast(s.first || s.full ? T(`已生成 ${s.pages} 个页面`, `Wrote ${s.pages} pages`) : T(`重建 ${s.rebuilt.length} 个页面,${s.unchanged} 个未变`, `Rebuilt ${s.rebuilt.length} page(s), ${s.unchanged} unchanged`)); +}; + +function render() { + applyTheme(); + const b = st.build, s = b?.summary; + const form = h("div", { class: "card" }, h("div", { class: "top" }, + h("label", { class: "fld grow" }, h("span", { class: "lb" }, T("文档目录(Markdown / HTML,子文件夹 = 分类)", "Docs folder (Markdown / HTML; sub-folders = categories)")), + h("select", { class: "docs", onchange: (e: Event) => { st.docs = (e.target as HTMLSelectElement).value; } }, h("option", { value: "" }, T("— 选择 —", "— choose —")), ...st.folders.map((f) => h("option", { value: f.path, selected: f.path === st.docs }, `${f.path === "." ? T("(工作区根目录)", "(workspace root)") : f.path}/ · ${f.count}`)))), + h("label", { class: "fld" }, h("span", { class: "lb" }, T("输出目录", "Output folder")), h("input", { class: "out", value: st.out, oninput: (e: Event) => { st.out = (e.target as HTMLInputElement).value; } })), + h("label", { class: "fld" }, h("span", { class: "lb" }, T("站点标题(可选)", "Site title (optional)")), h("input", { class: "title", value: st.title, placeholder: "help-center.json", oninput: (e: Event) => { st.title = (e.target as HTMLInputElement).value; } })), + h("button", { class: "primary build", onclick: () => void doBuild(false) }, b ? T("增量构建", "Build changes") : T("生成帮助中心", "Build help center")), + b ? h("button", { class: "full", onclick: () => void doBuild(true) }, T("全量重建", "Full rebuild")) : null)); + if (!b || !s) { + put(root, h("h1", {}, T("帮助中心制作", "Help Center Builder")), form, h("div", { class: "empty" }, T("选择一个放 Markdown / HTML 文档的文件夹,生成静态帮助中心:分类导航、全文搜索(离线可用,支持中文)、面包屑、目录、相关文章。之后改了文档再点“增量构建”,只重写受影响的页面,并列出原因。生成的文件夹可以直接上传到任意静态托管。", "Choose a folder of Markdown / HTML docs to generate a static help center: category navigation, full-text search (works offline, Chinese too), breadcrumbs, table of contents and related articles. After editing docs, Build changes rewrites only the affected pages and tells you why. Upload the folder to any static host."))); + return; + } + const errs = s.issues.filter((i) => i.level === "error").length, warns = s.issues.filter((i) => i.level === "warn").length; + const banner = h("div", { class: `sum ${errs ? "bad" : ""}` }, s.first || s.full + ? T(`已生成 ${b.out}/:${s.articles} 篇文章、${s.categories.length} 个分类、共 ${s.pages} 个页面(${s.ms} 毫秒)。`, `Built ${b.out}/: ${s.articles} articles, ${s.categories.length} categories, ${s.pages} pages (${s.ms} ms).`) + : T(`增量构建:重写 ${s.rebuilt.length} 个页面,${s.unchanged} 个未变${s.removed.length ? `,删除 ${s.removed.length} 个` : ""};搜索索引${s.searchRebuilt ? "已更新" : "未变"}(${s.ms} 毫秒)。`, `Incremental build: rewrote ${s.rebuilt.length} page(s), ${s.unchanged} unchanged${s.removed.length ? `, removed ${s.removed.length}` : ""}; search index ${s.searchRebuilt ? "updated" : "unchanged"} (${s.ms} ms).`), + errs || warns ? T(` 问题:${errs} 个错误、${warns} 个提醒。`, ` Problems: ${errs} error(s), ${warns} warning(s).`) : T(" 没有坏链。", " No broken links.")); + const rb = h("div", { class: "card" }, h("b", {}, T("本次重写的页面", "Pages rewritten this time")), h("div", { class: "scroll" }, h("ul", { class: "rb" }, + ...s.rebuilt.map((r) => h("li", { "data-out": r.out }, h("code", {}, r.out), ...r.reasons.map((k) => h("span", { class: "why" }, locale() === "zh" ? WHY[k]?.[0] ?? k : WHY[k]?.[1] ?? k)))), + ...s.removed.map((r) => h("li", { class: "removed" }, "✕ ", h("code", {}, r))))), s.rebuilt.length ? null : h("div", { class: "muted" }, T("没有页面需要重写。", "Nothing needed rewriting."))); + const iss = h("div", { class: "card iss" }, h("b", {}, T(`检查(${s.issues.length})`, `Checks (${s.issues.length})`)), ...(s.issues.length ? s.issues.map((i) => h("div", { class: i.level }, `${i.level === "error" ? "✗" : i.level === "warn" ? "!" : "·"} ${i.src}: ${i.message}`)) : [h("div", { class: "muted" }, T("✓ 没有坏链、缺失锚点或重复标题。", "✓ No broken links, missing anchors or duplicate titles."))])); + const pg = (out: string, label: string) => h("a", { class: out === st.page ? "on" : "", onclick: () => void preview(out) }, label); + const tree = h("div", { class: "card" }, h("b", {}, T("站点结构(点击预览)", "Site map (click to preview)")), h("ul", { class: "tree" }, h("li", {}, pg("index.html", T("首页", "Home"))), + ...(st.scan ?? s.categories.map((c) => ({ name: c.name, out: c.out, articles: [] }))).map((c) => h("li", {}, pg(c.out, c.name), ` (${c.articles.length || s.categories.find((x) => x.name === c.name)?.count || 0})`, c.articles.length ? h("ul", { class: "tree" }, ...c.articles.map((a) => h("li", {}, pg(a.src.replace(/\.(md|markdown|htm|html)$/i, ".html"), a.title)))) : null)), + h("li", {}, pg("search.html", T("搜索页", "Search page"))), h("li", {}, pg("404.html", "404")))); + const pv = st.preview ? h("div", { class: "card" }, h("div", { class: "row" }, h("b", { class: "grow" }, T("预览:", "Preview: "), h("code", {}, `${b.out}/${st.page}`)), h("span", { class: "muted" }, T("(静态预览,搜索在浏览器里打开站点后可用)", "(static; search works when you open the site in a browser)"))), h("iframe", { class: "pv", srcdoc: st.preview, sandbox: "" })) : null; + put(root, form, banner, h("div", { class: "split" }, h("div", {}, rb, iss, tree), h("div", {}, pv))); +} + +onHostContext(() => render()); +render(); +void initHost("help-center-builder", "0.1.0").then(async () => { + const r = await call<{ builds: Build[]; folders: { path: string; count: number }[] }>("hc_state").catch(() => undefined); + st.folders = r?.folders ?? []; + if (!st.docs && st.folders.length) st.docs = (st.folders.find((f) => /docs|help|articles|文档|帮助/i.test(f.path)) ?? st.folders[0]).path; + if (r?.builds?.[0]) { take(r.builds[0]); await loadScan(); await preview(); } + render(); +}); diff --git a/ui-plugins/help-center-builder/ui/panel.css b/ui-plugins/help-center-builder/ui/panel.css new file mode 100644 index 00000000..93d60422 --- /dev/null +++ b/ui-plugins/help-center-builder/ui/panel.css @@ -0,0 +1,19 @@ +.top { display:flex; gap:8px; align-items:end; flex-wrap:wrap; } +.fld { display:grid; gap:3px; } +.fld .lb { font-size:12px; color:var(--muted); } +.grow { flex:1; } +.sum { padding:8px 10px; border-radius:8px; margin:8px 0; background:var(--okbg); color:var(--ok); } +.sum.bad { background:var(--badbg); color:var(--bad); } +.chips { display:flex; gap:6px; flex-wrap:wrap; margin:6px 0; } +.chip { border:1px solid var(--line); border-radius:12px; padding:1px 9px; font-size:12px; background:var(--bg); } +.rb li, .iss div { margin:3px 0; } +.rb code, .tree code { font: 12px ui-monospace, Menlo, monospace; } +.why { display:inline-block; font-size:11px; padding:0 6px; border-radius:9px; background:var(--warnbg); color:var(--warn); margin-left:4px; } +.iss .error { color:var(--bad); } .iss .warn { color:var(--warn); } .iss .info { color:var(--muted); } +.tree { margin:0; padding-left:16px; } +.tree li { margin:2px 0; } +.tree a { cursor:pointer; color:var(--accent); } +.tree a.on { font-weight:700; } +iframe.pv { width:100%; height:720px; border:1px solid var(--line); border-radius:8px; background:#fff; } +.scroll { max-height:300px; overflow:auto; } +ul.rb { padding-left:18px; margin:4px 0; } From b9e8336e1091806201dfd085656572b285539297 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:33:09 -0400 Subject: [PATCH 09/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../skills/help-center-builder/SKILL.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 external_plugins/help-center-builder/skills/help-center-builder/SKILL.md diff --git a/external_plugins/help-center-builder/skills/help-center-builder/SKILL.md b/external_plugins/help-center-builder/skills/help-center-builder/SKILL.md new file mode 100644 index 00000000..96d42e62 --- /dev/null +++ b/external_plugins/help-center-builder/skills/help-center-builder/SKILL.md @@ -0,0 +1,12 @@ +--- +name: help-center-builder +description: 把 Markdown / HTML 文档文件夹生成静态帮助中心(分类导航、全文搜索、面包屑、目录、相关文章),支持增量构建(只重写受影响的页面并列出原因)和坏链检查。用户提到“帮助中心 / 知识库 / 文档站 / FAQ 网站 / 把这些文档做成网站”时使用。 +--- + +# 帮助中心制作 + +1. 找到文档目录(通常是 docs/、help/、articles/)。先用 `hc_scan({docs})` 看分类、文章数和问题,把坏链、失效锚点、缺标题这类问题告诉用户。 +2. 如果用户想定站点名称、主题色、分类顺序或说明,在文档目录里写 `help-center.json`:`{ "title", "description", "accent": "#rrggbb", "baseUrl", "footer", "categories": [{ "folder", "name", "description" }] }`。单篇文章的标题、排序、标签、相关文章写在 front matter 里(`title`、`order`、`tags`、`related`)。 +3. 用 `hc_build({docs, out?})` 生成(默认输出到 help-center/)。之后用户改了文档,再调用一次就是增量构建:只重写受影响的页面,返回结果里有每个页面被重写的原因,挑重点告诉用户。改了模板或想全部重新生成时加 `full: true`。 +4. 告诉用户怎么看:用浏览器打开 `help-center/index.html`(离线可用,搜索也能用);要上线的话,把整个文件夹上传到静态托管(Cloudflare Pages、Netlify、GitHub Pages 等)。设置了 `baseUrl` 才会生成 sitemap.xml 和 canonical 链接。 +5. 不在范围内的需求直接说明:反馈按钮、统计、评论、需要登录才能看的文章(需要后端)、多语言切换、代码高亮。 From 070a87b99edcdf545b2677cac0894eda45f42301 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:33:44 -0400 Subject: [PATCH 10/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../help-center-builder/src/kit/console.ts | 5 + .../help-center-builder/src/kit/server-kit.ts | 84 ++++++++++ .../help-center-builder/src/kit/workspace.ts | 151 ++++++++++++++++++ 3 files changed, 240 insertions(+) create mode 100644 ui-plugins/help-center-builder/src/kit/console.ts create mode 100644 ui-plugins/help-center-builder/src/kit/server-kit.ts create mode 100644 ui-plugins/help-center-builder/src/kit/workspace.ts diff --git a/ui-plugins/help-center-builder/src/kit/console.ts b/ui-plugins/help-center-builder/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/help-center-builder/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/help-center-builder/src/kit/server-kit.ts b/ui-plugins/help-center-builder/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/help-center-builder/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record<string, unknown>; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise<string>; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record<string, unknown>; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record<string, z.ZodType>; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise<ToolOutput>, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/help-center-builder/src/kit/workspace.ts b/ui-plugins/help-center-builder/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/help-center-builder/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise<boolean> { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise<Buffer> { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise<string> { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise<string> { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} From faf6c37f2d886674ada2da64487b98e14517ad3d Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:34:21 -0400 Subject: [PATCH 11/11] feat(ui-plugins): add Help Center Builder (help-center-builder) --- .../src/runtime/assets/search.js | 48 +++++++++++ .../src/runtime/assets/style.css | 84 +++++++++++++++++++ .../src/runtime/assets/tokenize.js | 19 +++++ 3 files changed, 151 insertions(+) create mode 100644 ui-plugins/help-center-builder/src/runtime/assets/search.js create mode 100644 ui-plugins/help-center-builder/src/runtime/assets/style.css create mode 100644 ui-plugins/help-center-builder/src/runtime/assets/tokenize.js diff --git a/ui-plugins/help-center-builder/src/runtime/assets/search.js b/ui-plugins/help-center-builder/src/runtime/assets/search.js new file mode 100644 index 00000000..08daad9c --- /dev/null +++ b/ui-plugins/help-center-builder/src/runtime/assets/search.js @@ -0,0 +1,48 @@ +/* global MiniSearch, hcTokenize, HC_SEARCH */ +(function () { + const root = document.documentElement.dataset.root || ""; + const L = JSON.parse(document.documentElement.dataset.strings || "{}"); + const data = window.HC_SEARCH; + if (!data || typeof MiniSearch === "undefined") return; + const ms = MiniSearch.loadJSON(JSON.stringify(data.index), { fields: data.fields, storeFields: [], tokenize: hcTokenize, processTerm: (t) => t }); + const opts = { boost: { title: 4, tags: 3, headings: 2 }, prefix: (t) => t.length > 2, fuzzy: (t) => (t.length > 4 ? 0.2 : false), combineWith: "AND" }; + const run = (q) => { let r = ms.search(q, opts); if (!r.length) r = ms.search(q, { ...opts, combineWith: "OR" }); return r.map((x) => ({ ...data.docs[x.id], score: x.score, terms: x.terms })); }; + const escH = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + const mark = (s, terms) => { + const t = [...new Set(terms)].filter(Boolean).sort((a, b) => b.length - a.length).map((x) => escH(x).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return t.length ? escH(s).replace(new RegExp(t.join("|"), "gi"), (m) => `<mark>${m}</mark>`).replace(/<\/mark><mark>/g, "") : escH(s); + }; + const item = (d, active) => `<a class="hit${active ? " active" : ""}" href="${root}${d.u}"><span class="hit-t">${mark(d.t, d.terms)}</span><span class="hit-c">${escH(d.c)}</span><span class="hit-d">${mark(d.d, d.terms)}</span></a>`; + + for (const form of document.querySelectorAll("form.search")) { + const input = form.querySelector("input"); + const box = form.querySelector(".results"); + let hits = [], sel = -1; + const draw = () => { + const q = input.value.trim(); + if (!q) { box.hidden = true; return; } + hits = run(q).slice(0, 8); + box.innerHTML = hits.length ? hits.map((d, i) => item(d, i === sel)).join("") + `<a class="all" href="${root}search.html?q=${encodeURIComponent(q)}">${escH(L.all || "All results")} →</a>` : `<div class="none">${escH((L.none || "No results for “%s”").replace("%s", q))}</div>`; + box.hidden = false; + }; + input.addEventListener("input", () => { sel = -1; draw(); }); + input.addEventListener("keydown", (e) => { + if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); if (!hits.length) return; sel = (sel + (e.key === "ArrowDown" ? 1 : -1) + hits.length) % hits.length; draw(); } + else if (e.key === "Escape") { box.hidden = true; input.blur(); } + else if (e.key === "Enter" && sel >= 0 && hits[sel]) { e.preventDefault(); location.href = root + hits[sel].u; } + }); + document.addEventListener("click", (e) => { if (!form.contains(e.target)) box.hidden = true; }); + input.addEventListener("focus", () => { if (input.value.trim()) draw(); }); + } + document.addEventListener("keydown", (e) => { if (e.key === "/" && !/input|textarea/i.test(document.activeElement.tagName)) { const i = document.querySelector("form.search input"); if (i) { e.preventDefault(); i.focus(); } } }); + + const page = document.getElementById("search-page"); + if (page) { + const q = new URLSearchParams(location.search).get("q") || ""; + const input = document.querySelector("form.search input"); + if (input) input.value = q; + const hits = q ? run(q) : []; + document.getElementById("search-count").textContent = q ? (L.count || "%n results for “%s”").replace("%n", hits.length).replace("%s", q) : ""; + page.innerHTML = hits.map((d) => item(d, false)).join("") || (q ? `<div class="none">${escH((L.none || "No results for “%s”").replace("%s", q))}</div>` : ""); + } +})(); diff --git a/ui-plugins/help-center-builder/src/runtime/assets/style.css b/ui-plugins/help-center-builder/src/runtime/assets/style.css new file mode 100644 index 00000000..2bebe217 --- /dev/null +++ b/ui-plugins/help-center-builder/src/runtime/assets/style.css @@ -0,0 +1,84 @@ +:root { --accent: #2563eb; --bg: #ffffff; --fg: #1f2933; --muted: #5f6b7a; --line: #e4e7ec; --soft: #f5f7fa; --mark: #fff3bf; --radius: 10px; color-scheme: light dark; } +@media (prefers-color-scheme: dark) { :root { --bg: #15181d; --fg: #e6e9ef; --muted: #9aa4b2; --line: #2b313a; --soft: #1d2128; --mark: #5c4b00; } } +* { box-sizing: border-box; } +html { scroll-padding-top: 80px; } +body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.65 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +.top { position: sticky; top: 0; z-index: 5; background: var(--bg); border-bottom: 1px solid var(--line); } +.top .inner { max-width: 1180px; margin: 0 auto; padding: 10px 24px; display: flex; gap: 20px; align-items: center; } +.brand { font-weight: 700; color: var(--fg); font-size: 17px; white-space: nowrap; display: flex; gap: 8px; align-items: center; } +.brand img { height: 28px; } +.brand .dot { width: 22px; height: 22px; border-radius: 6px; background: var(--accent); display: inline-block; } +form.search { position: relative; flex: 1; max-width: 520px; margin-left: auto; } +form.search input { width: 100%; font: inherit; font-size: 15px; padding: 8px 12px 8px 36px; border: 1px solid var(--line); border-radius: 999px; background: var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%238a94a3' stroke-width='2'%3E%3Ccircle cx='7' cy='7' r='5'/%3E%3Cpath d='m11 11 4 4'/%3E%3C/svg%3E") no-repeat 13px 50%; color: var(--fg); } +form.search input:focus { outline: 2px solid color-mix(in srgb, var(--accent) 40%, transparent); background-color: var(--bg); } +.results { text-align: left; position: absolute; left: 0; right: 0; top: calc(100% + 6px); background: var(--bg); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: 0 12px 32px rgba(0,0,0,.12); max-height: 70vh; overflow: auto; padding: 6px; } +.hit { display: grid; grid-template-columns: 1fr auto; gap: 0 10px; padding: 8px 10px; border-radius: 8px; color: var(--fg); } +.hit:hover, .hit.active { background: var(--soft); text-decoration: none; } +.hit-t { font-weight: 600; } +.hit-c { color: var(--muted); font-size: 12px; align-self: center; } +.hit-d { grid-column: 1 / -1; color: var(--muted); font-size: 14px; } +mark { background: var(--mark); color: inherit; border-radius: 2px; } +.results .all { display: block; padding: 8px 10px; font-size: 14px; } +.none { padding: 10px; color: var(--muted); } +.hero { background: linear-gradient(135deg, var(--accent), color-mix(in srgb, var(--accent) 60%, #000)); color: #fff; padding: 56px 24px 64px; text-align: center; } +.hero h1 { margin: 0 0 6px; font-size: 34px; } +.hero p { margin: 0 0 22px; opacity: .9; } +.hero form.search { margin: 0 auto; max-width: 620px; } +.hero form.search input { font-size: 17px; padding: 13px 16px 13px 42px; background-color: #fff; color: #1f2933; border: 0; background-position: 16px 50%; } +.wrap { max-width: 1180px; margin: 0 auto; padding: 28px 24px 60px; } +.cats { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 18px; } +.cat { border: 1px solid var(--line); border-radius: var(--radius); padding: 18px 20px; background: var(--bg); } +.cat h2 { margin: 0 0 4px; font-size: 19px; } +.cat p { margin: 0 0 10px; color: var(--muted); font-size: 15px; } +.cat ul { margin: 0; padding: 0; list-style: none; font-size: 15px; } +.cat li { padding: 3px 0; } +.cat .more { font-size: 14px; display: inline-block; margin-top: 6px; } +.count { color: var(--muted); font-size: 13px; font-weight: 400; } +.layout { display: grid; grid-template-columns: 240px minmax(0, 1fr) 210px; gap: 36px; max-width: 1180px; margin: 0 auto; padding: 24px; } +.layout.two { grid-template-columns: 240px minmax(0, 1fr); } +.side { position: sticky; top: 72px; align-self: start; max-height: calc(100vh - 90px); overflow: auto; font-size: 14px; } +.side h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 6px; } +.side ul { list-style: none; margin: 0 0 18px; padding: 0; } +.side li a { display: block; padding: 4px 10px; border-radius: 6px; color: var(--fg); } +.side li a:hover { background: var(--soft); text-decoration: none; } +.side li a.on { background: color-mix(in srgb, var(--accent) 12%, transparent); color: var(--accent); font-weight: 600; } +.crumbs { font-size: 14px; color: var(--muted); margin-bottom: 8px; } +.crumbs a { color: var(--muted); } +.crumbs span { margin: 0 6px; } +article h1 { font-size: 30px; line-height: 1.25; margin: 0 0 6px; } +.meta { color: var(--muted); font-size: 14px; margin-bottom: 18px; } +.lead { font-size: 18px; color: var(--muted); margin: 0 0 18px; } +article h2 { font-size: 22px; margin: 32px 0 10px; padding-top: 6px; } +article h3 { font-size: 18px; margin: 24px 0 8px; } +article img { max-width: 100%; height: auto; border: 1px solid var(--line); border-radius: 8px; } +article blockquote, article .note { margin: 16px 0; padding: 10px 16px; border-left: 4px solid var(--accent); background: var(--soft); border-radius: 0 8px 8px 0; } +article blockquote p { margin: 4px 0; } +article code { font: 0.88em ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: var(--soft); padding: .1em .35em; border-radius: 4px; } +article pre { background: var(--soft); padding: 14px 16px; border-radius: 8px; overflow: auto; line-height: 1.5; } +article pre code { background: none; padding: 0; } +.table-wrap { overflow-x: auto; margin: 14px 0; } +article table { border-collapse: collapse; min-width: 60%; font-size: 15px; } +article th, article td { border: 1px solid var(--line); padding: 7px 12px; text-align: left; vertical-align: top; } +article th { background: var(--soft); } +.toc { position: sticky; top: 72px; align-self: start; font-size: 13px; max-height: calc(100vh - 90px); overflow: auto; } +.toc h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 6px; } +.toc a { display: block; color: var(--muted); padding: 3px 0 3px 10px; border-left: 2px solid var(--line); } +.toc a.l3 { padding-left: 22px; } +.toc a:hover { color: var(--accent); border-left-color: var(--accent); text-decoration: none; } +.related { margin-top: 40px; border-top: 1px solid var(--line); padding-top: 18px; } +.related h2 { font-size: 17px; margin: 0 0 8px; padding: 0; } +.related ul { margin: 0; padding-left: 18px; } +.pn { display: flex; justify-content: space-between; gap: 16px; margin-top: 28px; } +.pn a { flex: 1; border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 14px; font-size: 15px; } +.pn a small { display: block; color: var(--muted); font-size: 12px; } +.pn a.next { text-align: right; } +.list { list-style: none; padding: 0; margin: 0; } +.list li { border-bottom: 1px solid var(--line); padding: 12px 0; } +.list li a { font-weight: 600; font-size: 17px; } +.list li p { margin: 2px 0 0; color: var(--muted); font-size: 15px; } +.intro { margin-bottom: 18px; } +footer.foot { border-top: 1px solid var(--line); color: var(--muted); font-size: 14px; text-align: center; padding: 22px; } +@media (max-width: 1000px) { .layout { grid-template-columns: 220px minmax(0, 1fr); } .toc { display: none; } } +@media (max-width: 720px) { .layout, .layout.two { grid-template-columns: 1fr; padding: 16px; } .side { position: static; max-height: none; } .top .inner { flex-wrap: wrap; } form.search { max-width: none; } .hero h1 { font-size: 26px; } } diff --git a/ui-plugins/help-center-builder/src/runtime/assets/tokenize.js b/ui-plugins/help-center-builder/src/runtime/assets/tokenize.js new file mode 100644 index 00000000..8209070c --- /dev/null +++ b/ui-plugins/help-center-builder/src/runtime/assets/tokenize.js @@ -0,0 +1,19 @@ +/* Shared by the build (Node) and the site search (browser): Latin words + CJK single characters and bigrams. */ +function hcTokenize(text) { + const out = []; + const s = String(text || "").normalize("NFKC").toLowerCase(); + const re = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{N}_]+(?:['’.-][\p{L}\p{N}_]+)*/gu; + let m; + while ((m = re.exec(s))) { + const w = m[0]; + if (/^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(w)) { + const chars = Array.from(w); + for (let i = 0; i < chars.length; i++) { out.push(chars[i]); if (i + 1 < chars.length) out.push(chars[i] + chars[i + 1]); } + } else { + out.push(w); + if (/[.'’-]/.test(w)) for (const p of w.split(/['’.-]/)) if (p) out.push(p); + } + } + return out; +} +if (typeof module !== "undefined") module.exports = { hcTokenize };