From 4fb20a2cd6f7b7d653861d00c7eca4ff7ea3c70a Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:21:49 +0800 Subject: [PATCH 01/10] feat(ui-plugins): add Offline Site Packer (offline-site-packer) --- marketplace.json | 50 +++++++++++++++++++++++ pnpm-lock.yaml | 102 +++++++++++++++++++++++++---------------------- 2 files changed, 104 insertions(+), 48 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..f743e711 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "offline-site-packer", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/offline-site-packer", + "displayName": "Offline Site Packer", + "displayName_i18n": { + "en": "Offline Site Packer", + "zh-CN": "网站离线打包" + }, + "description": "Turn a built static website into an offline copy that opens by double-clicking index.html: crawls every internal page from the home page, rewrites root-relative, pretty and extension-less links (and CSS url()/@import, srcset) to relative file paths, copies only the files used, adds an offline full-text search box (MiniSearch, ⌘K) to every page, and reports broken links, missing files, external links and pages nothing links to. Writes a folder and a zip. No server, no network.", + "description_i18n": { + "en": "Turn a built static website into an offline copy that opens by double-clicking index.html: crawls every internal page from the home page, rewrites root-relative, pretty and extension-less links (and CSS url()/@import, srcset) to relative file paths, copies only the files used, adds an offline full-text search box (MiniSearch, ⌘K) to every page, and reports broken links, missing files, external links and pages nothing links to. Writes a folder and a zip. No server, no network.", + "zh-CN": "把构建好的静态网站做成离线版,双击 index.html 就能浏览:从首页出发爬取所有站内页面,把根路径、目录式和省略扩展名的链接(以及 CSS 的 url()/@import、srcset)改成相对文件路径,只复制用到的文件,给每个页面加上离线全文搜索(MiniSearch,⌘K),并报告坏链、缺失文件、外部链接和没被链接的页面。输出文件夹和 zip。不需要服务器,不联网。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "utilities", + "keywords": [ + "offline", + "static site", + "documentation", + "zip", + "file://", + "search", + "broken links", + "minisearch", + "离线", + "网站打包", + "文档", + "坏链检查" + ], + "examplePrompts": [ + "Make an offline copy of the docs site in dist/", + "Check this site for broken links", + "Pack the help site into a zip that works without internet" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把 dist 里的文档站做成离线版", + "检查这个网站有没有坏链", + "把帮助网站打包成不联网也能看的 zip" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..10499946 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -174,6 +174,43 @@ importers: specifier: 4.6.5 version: 4.6.5 + ui-plugins/offline-site-packer: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + fflate: + specifier: 0.8.2 + version: 0.8.2 + minisearch: + specifier: 7.2.0 + version: 7.2.0 + 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.0)) + ui-plugins/openpencil: dependencies: '@modelcontextprotocol/sdk': @@ -2475,10 +2512,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'} @@ -2522,8 +2555,8 @@ packages: picomatch: optional: true - fflate@0.8.3: - resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + fflate@0.8.2: + resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} @@ -2714,9 +2747,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: @@ -2906,6 +2936,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 +3101,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'} @@ -3383,18 +3412,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3763,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4306,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 @@ -4400,7 +4421,7 @@ snapshots: diff: 8.0.4 es-toolkit: 1.46.1 expr-eval: 2.0.2 - fflate: 0.8.3 + fflate: 0.8.2 fontoxpath: 3.34.0 fzstd: 0.1.1 js-base64: 3.9.4 @@ -4421,11 +4442,11 @@ snapshots: '@open-pencil/kiwi': 0.14.0 '@open-pencil/scene-graph': 0.14.0 es-toolkit: 1.46.1 - fflate: 0.8.3 + fflate: 0.8.2 '@open-pencil/kiwi@0.14.0': dependencies: - fflate: 0.8.3 + fflate: 0.8.2 fzstd: 0.1.1 '@open-pencil/mcp@0.14.0': @@ -5809,13 +5830,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,15 +5888,11 @@ 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 - fflate@0.8.3: {} + fflate@0.8.2: {} fill-range@7.1.1: dependencies: @@ -6048,8 +6063,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) @@ -6070,7 +6083,7 @@ snapshots: dependencies: '@babel/runtime': 7.29.7 fast-png: 6.4.0 - fflate: 0.8.3 + fflate: 0.8.2 optionalDependencies: canvg: 3.0.11 core-js: 3.50.0 @@ -6224,6 +6237,8 @@ snapshots: dependencies: mime-db: 1.54.0 + minisearch@7.2.0: {} + mlly@1.8.2: dependencies: acorn: 8.16.0 @@ -6406,8 +6421,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6758,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6792,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) From ee9cc718327c8d87e0bd3880c16b589aa5646c46 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:22:24 +0800 Subject: [PATCH 02/10] feat(ui-plugins): add Offline Site Packer (offline-site-packer) --- external_plugins/offline-site-packer/LICENSE | 21 +++++++++ .../offline-site-packer/README.md | 47 +++++++++++++++++++ .../offline-site-packer/README_CN.md | 47 +++++++++++++++++++ 3 files changed, 115 insertions(+) create mode 100644 external_plugins/offline-site-packer/LICENSE create mode 100644 external_plugins/offline-site-packer/README.md create mode 100644 external_plugins/offline-site-packer/README_CN.md diff --git a/external_plugins/offline-site-packer/LICENSE b/external_plugins/offline-site-packer/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/offline-site-packer/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/offline-site-packer/README.md b/external_plugins/offline-site-packer/README.md new file mode 100644 index 00000000..7772312a --- /dev/null +++ b/external_plugins/offline-site-packer/README.md @@ -0,0 +1,47 @@ +# Offline Site Packer + +Turn a built **static website** (docs, help centre, product site) into an offline copy that opens by double-clicking `index.html`, with no server and no internet. + +## What it does + +- **Crawl**: starts at `index.html` and follows every internal link (``, ``, ``; +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) }); +} + +// 离线包里给浏览器用的 MiniSearch UMD 版(包的 exports 不开放该子路径,直接按文件路径复制)。 +await mkdir(join(dist, "vendor"), { recursive: true }); +await copyFile(join(root, "node_modules/minisearch/dist/umd/index.js"), join(dist, "vendor/minisearch.umd.js")); + +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/offline-site-packer/scripts/e2e.mts b/ui-plugins/offline-site-packer/scripts/e2e.mts new file mode 100644 index 00000000..f3e05f15 --- /dev/null +++ b/ui-plugins/offline-site-packer/scripts/e2e.mts @@ -0,0 +1,63 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板; +// 然后用 Chrome 直接以 file:// 打开离线包,验证样式、图片、页面跳转和离线搜索。需要 Chrome。 +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "offline-site-packer-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "osp-e2e-")); +execFileSync(process.execPath, [process.env.SITE_SAMPLE ?? "/workspace/zcode-new-plugins/samples/site/make-site.mjs", join(workspace, "lumen-docs/public")]); +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +try { + const { outer, frame, context } = await harness.open("?locale=zh-CN", { width: 1400, height: 950 }); + step("user picks the site folder, enters the public URL and checks it"); + await frame.locator("select.dir").selectOption("lumen-docs/public"); + await frame.locator("input.base").fill("https://docs.lumen-example.com/"); + await frame.locator("button", { hasText: "只检查" }).click(); + await frame.locator(".stat.bad b", { hasText: "2" }).waitFor({ timeout: 30_000 }); + await frame.locator("tr.brk", { hasText: "/guide/firmware" }).waitFor(); + await frame.locator(".muted", { hasText: "仅检查,未写入文件" }).waitFor(); + step("user packs it"); + await frame.locator("button", { hasText: "生成离线包" }).click(); + await frame.locator(".done", { hasText: "lumen-docs-offline/" }).waitFor({ timeout: 60_000 }); + await frame.locator(".ext", { hasText: "https://shop.lumen-example.com/" }).waitFor(); + await outer.screenshot({ path: join(shots, "01-report.png") }); + assert.ok((await stat(join(workspace, "lumen-docs-offline.zip"))).size > 10_000); + + step("open the offline copy straight from disk (file://)"); + const page = await context.newPage(); + const pageErrors: string[] = []; + page.on("pageerror", (e) => pageErrors.push(String(e))); + page.on("console", (m) => { if (m.type() === "error") pageErrors.push(m.text()); }); + await page.setViewportSize({ width: 1100, height: 760 }); + await page.goto(pathToFileURL(join(workspace, "lumen-docs-offline/index.html")).href); + assert.equal(await page.locator("h1").evaluate((e) => getComputedStyle(e).color), "rgb(124, 45, 18)", "@import'ed theme.css applied"); + assert.ok(await page.locator("main img").evaluate((i) => (i as HTMLImageElement).naturalWidth > 0), "srcset image loaded"); + assert.match(await page.locator("header").evaluate((e) => getComputedStyle(e).backgroundImage), /header-bg\.png/); + await page.locator("nav.side a", { hasText: "Install" }).click(); + await page.waitForURL(/guide\/install\.html$/); + assert.ok(await page.locator("main img").evaluate((i) => (i as HTMLImageElement).naturalWidth > 0)); + await page.locator("a", { hasText: "pairing" }).first().click(); + await page.waitForURL(/guide\/pairing\.html$/); + step("offline search: Ctrl+K → “colour temperature” → Scenes"); + await page.keyboard.press("Control+k"); + await page.locator("#osp input").fill("colour temperature"); + await page.locator("#osp li a").first().waitFor(); + await page.screenshot({ path: join(shots, "02-offline-search.png") }); + await page.locator("#osp li a", { hasText: "Scenes" }).first().click(); + await page.waitForURL(/guide\/scenes\/index\.html$/); + await page.locator("h1", { hasText: "Scenes" }).waitFor(); + await page.screenshot({ path: join(shots, "03-offline-page.png") }); + const real = pageErrors.filter((e) => !/missing-diagram\.png|ERR_FILE_NOT_FOUND|favicon/.test(e)); + assert.deepEqual(real, [], "no script errors on file:// pages"); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + await harness.close(); +} diff --git a/ui-plugins/offline-site-packer/scripts/harness.mjs b/ui-plugins/offline-site-packer/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/offline-site-packer/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/offline-site-packer/scripts/licenses.mjs b/ui-plugins/offline-site-packer/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/offline-site-packer/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 714f5e92e9ea1912ade4ef4df361282f4c351b76 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:24:46 +0800 Subject: [PATCH 06/10] feat(ui-plugins): add Offline Site Packer (offline-site-packer) --- ui-plugins/offline-site-packer/src/main.ts | 14 ++ ui-plugins/offline-site-packer/src/pack.ts | 199 +++++++++++++++++++ ui-plugins/offline-site-packer/src/server.ts | 84 ++++++++ ui-plugins/offline-site-packer/src/widget.ts | 28 +++ 4 files changed, 325 insertions(+) create mode 100644 ui-plugins/offline-site-packer/src/main.ts create mode 100644 ui-plugins/offline-site-packer/src/pack.ts create mode 100644 ui-plugins/offline-site-packer/src/server.ts create mode 100644 ui-plugins/offline-site-packer/src/widget.ts diff --git a/ui-plugins/offline-site-packer/src/main.ts b/ui-plugins/offline-site-packer/src/main.ts new file mode 100644 index 00000000..48f323f4 --- /dev/null +++ b/ui-plugins/offline-site-packer/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(`[offline-site-packer] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/offline-site-packer/src/pack.ts b/ui-plugins/offline-site-packer/src/pack.ts new file mode 100644 index 00000000..2a21e7eb --- /dev/null +++ b/ui-plugins/offline-site-packer/src/pack.ts @@ -0,0 +1,199 @@ +import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { dirname, join, posix } from "node:path"; +import MiniSearch from "minisearch"; +import { zipSync } from "fflate"; +import { SEARCH_CSS, SEARCH_JS } from "./widget.ts"; + +export interface PackOptions { + /** 网站上线地址,例如 https://docs.example.com/ —— 指向它的绝对链接按站内链接处理 */ + baseUrl?: string; + search?: boolean; + /** 把没被链接到的文件也放进离线包 */ + includeUnlinked?: boolean; + /** UMD 版 MiniSearch 源码(写入 _offline/minisearch.js) */ + minisearchUmd: string; + /** 只检查,不写文件 */ + dryRun?: boolean; +} +export interface LinkIssue { from: string; href: string; kind: "page" | "asset" } +export interface Report { + source: string; output: string; zip?: string; + pages: { path: string; title: string; words: number }[]; + assets: number; files: number; bytes: number; rewritten: number; + broken: LinkIssue[]; + external: { href: string; from: string[] }[]; + orphans: string[]; + unused: string[]; + warnings: string[]; + search: boolean; +} + +const MARKER = "_offline/.packed-by-offline-site-packer"; +const SKIP_SCHEMES = /^(mailto|tel|javascript|data|blob|sms|about):/i; +type Ref = { type: "skip" } | { type: "external"; href: string } | { type: "internal"; target: string; hash: string } | { type: "broken"; path: string }; + +async function walk(root: string): Promise { + const out: string[] = []; + const go = async (abs: string, rel: string) => { + for (const e of await readdir(abs, { withFileTypes: true })) { + if (e.name.startsWith(".") || e.name === "node_modules") continue; + const r = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) await go(join(abs, e.name), r); + else if (e.isFile()) out.push(r); + } + }; + await go(root, ""); + return out.sort(); +} + +export const isHtml = (p: string) => /\.html?$/i.test(p); +const decode = (s: string) => { try { return decodeURIComponent(s); } catch { return s; } }; +export function htmlText(s: string) { + return s.replace(/||/gi, " ").replace(/<[^>]+>/g, " ") + .replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'|'/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))) + .replace(/\s+/g, " ").trim(); +} + +export function resolveRef(files: Set, from: string, raw: string, base?: URL): Ref { + let ref = raw.trim().replace(/&/g, "&"); + if (!ref || ref.startsWith("#") || SKIP_SCHEMES.test(ref) || ref.includes("{{")) return { type: "skip" }; + let path: string; + if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(ref)) { + let u: URL; + try { u = new URL(ref, base ?? "https://unknown.invalid/"); } catch { return { type: "skip" }; } + if (!/^https?:$/.test(u.protocol)) return { type: "skip" }; + if (!base || u.host !== base.host || !u.pathname.startsWith(base.pathname)) return { type: "external", href: u.href }; + ref = "/" + u.pathname.slice(base.pathname.length) + u.search + u.hash; + } + const hashAt = ref.indexOf("#"); + const hash = hashAt >= 0 ? ref.slice(hashAt) : ""; + path = decode(ref.slice(0, hashAt >= 0 ? hashAt : undefined).replace(/\?.*$/, "")); + if (base && path.startsWith(base.pathname) && base.pathname !== "/") path = "/" + path.slice(base.pathname.length); + let p = path.startsWith("/") ? posix.normalize(path.slice(1) || ".") : posix.normalize(posix.join(posix.dirname(from), path || posix.basename(from))); + if (p === "." ) p = ""; + if (p.startsWith("..")) return { type: "broken", path }; + const dirLike = path.endsWith("/") || p === ""; + const stem = p.replace(/\/$/, ""); + const candidates = dirLike ? [posix.join(stem, "index.html")] : [stem, `${stem}.html`, posix.join(stem, "index.html")]; + const hit = candidates.find((c) => files.has(c.replace(/^\.\//, ""))); + return hit ? { type: "internal", target: hit, hash } : { type: "broken", path }; +} + +const relLink = (from: string, target: string) => { + const r = posix.relative(posix.dirname(from), target); + return r || posix.basename(target); +}; + +/** 打包:从 index.html 出发爬所有站内页面,把链接改成相对路径(file:// 可用),收集资源,生成离线搜索。 */ +export async function pack(srcAbs: string, outAbs: string, names: { source: string; output: string }, opts: PackOptions): Promise { + const all = await walk(srcAbs); + const files = new Set(all); + if (!files.has("index.html")) throw new Error(`${names.source}/index.html not found — choose the folder that contains the site's home page (for example dist/ or public/).`); + const base = opts.baseUrl ? new URL(opts.baseUrl.endsWith("/") ? opts.baseUrl : `${opts.baseUrl}/`) : undefined; + const report: Report = { source: names.source, output: names.output, pages: [], assets: 0, files: 0, bytes: 0, rewritten: 0, broken: [], external: [], orphans: [], unused: [], warnings: [], search: opts.search !== false }; + const ext = new Map>(); + const used = new Set(["index.html"]); + const queue = ["index.html"]; + const outputs = new Map(); + const brokenSeen = new Set(); + const docs: { id: number; url: string; title: string; text: string }[] = []; + + const handle = (from: string, raw: string, kind: "page" | "asset"): string | undefined => { + const r = resolveRef(files, from, raw, base); + if (r.type === "skip") return undefined; + if (r.type === "external") { if (!ext.has(r.href)) ext.set(r.href, new Set()); ext.get(r.href)!.add(from); return undefined; } + if (r.type === "broken") { const k = `${from}|${raw}`; if (!brokenSeen.has(k)) { brokenSeen.add(k); report.broken.push({ from, href: raw.trim(), kind }); } return undefined; } + if (!used.has(r.target)) { used.add(r.target); queue.push(r.target); } + const link = relLink(from, r.target) + r.hash; + if (link !== raw.trim()) report.rewritten++; + return link; + }; + const css = (from: string, text: string) => text + .replace(/@import\s+(?:url\(\s*)?(["']?)([^"')\s;]+)\1\s*\)?/gi, (m, q, u) => { const n = handle(from, u, "asset"); return n ? `@import url("${n}")` : m; }) + .replace(/url\(\s*(["']?)([^"')]+)\1\s*\)/gi, (m, q, u) => { if (/^data:/i.test(u)) return m; const n = handle(from, u, "asset"); return n ? `url("${n}")` : m; }); + const attrRe = /(\s)(href|src|srcset|poster|action|data-src|data-srcset)(\s*=\s*)("([^"]*)"|'([^']*)'|([^\s"'>]+))/gi; + const tag = (from: string, t: string) => { + const name = /^<([\w-]+)/.exec(t)?.[1].toLowerCase() ?? ""; + if (name === "base") { report.warnings.push(`${from}: removed (links are rewritten relative to each page).`); return ""; } + let out = t.replace(attrRe, (m, sp, attr, eq, _q, dq, sq, bare) => { + const val: string = dq ?? sq ?? bare ?? ""; + const a = attr.toLowerCase(); + if (a === "action" || (name === "link" && /rel\s*=\s*["']?(canonical|alternate|preconnect|dns-prefetch|manifest)/i.test(t) && a === "href")) return m; + const kind = (name === "a" || name === "area" || name === "iframe") ? "page" : "asset"; + let next: string | undefined; + if (a.endsWith("srcset")) { + let changed = false; + next = val.split(",").map((part) => { const [u, ...d] = part.trim().split(/\s+/); const n = u ? handle(from, u, "asset") : undefined; if (n) changed = true; return [n ?? u, ...d].join(" "); }).join(", "); + if (!changed) next = undefined; + } else next = handle(from, val, kind); + return next === undefined ? m : `${sp}${attr}${eq}"${next.replace(/"/g, """)}"`; + }); + out = out.replace(/(\sstyle\s*=\s*)"([^"]*)"/i, (m, p, s) => `${p}"${css(from, s)}"`); + return out; + }; + const html = (from: string, src: string) => src.replace(/]*>[\s\S]*?<\/script>|]*>[\s\S]*?<\/style>||<[a-zA-Z][^<>]*>/g, (m) => { + if (m.startsWith("