diff --git a/external_plugins/store-screenshot-studio/.zcode-plugin/plugin.json b/external_plugins/store-screenshot-studio/.zcode-plugin/plugin.json new file mode 100644 index 00000000..0066fa98 --- /dev/null +++ b/external_plugins/store-screenshot-studio/.zcode-plugin/plugin.json @@ -0,0 +1,65 @@ +{ + "name": "store-screenshot-studio", + "version": "0.1.0", + "description": "Turn raw app screenshots into App Store and Google Play listing images: headline and subheadline, iPhone / Android / iPad device frames, solid or gradient backgrounds, several languages, and exact store pixel sizes (iPhone 6.9″/6.5″/5.5″, iPad 13″, Play phone/tablet) exported as opaque PNGs. Checks long headlines, missing translations and blurry screenshots. Runs locally; no API keys.", + "description_i18n": { + "en": "Turn raw app screenshots into App Store and Google Play listing images: headline and subheadline, iPhone / Android / iPad device frames, solid or gradient backgrounds, several languages, and exact store pixel sizes (iPhone 6.9″/6.5″/5.5″, iPad 13″, Play phone/tablet) exported as opaque PNGs. Checks long headlines, missing translations and blurry screenshots. Runs locally; no API keys.", + "zh-CN": "把 App 原始截图做成 App Store 和 Google Play 的宣传截图:加主副标题、iPhone / 安卓 / iPad 设备边框、纯色或渐变背景,支持多语言,按商店要求的精确像素尺寸(iPhone 6.9″/6.5″/5.5″、iPad 13″、Google Play 手机/平板)导出无透明通道的 PNG。自动检查标题过长、缺少翻译和截图分辨率不足。全部本地处理,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "app-store", + "google-play", + "screenshots", + "aso", + "mockup", + "device-frame", + "localization", + "ios", + "android", + "应用商店" + ], + "skills": "skills", + "mcpServers": { + "store-screenshot-studio": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}", + "STORE_SHOTS_FONT": "${user_config.fontPath}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "应用商店截图制作", + "en-US": "Store Screenshot Studio" + }, + "icon": "smartphone", + "server": "store-screenshot-studio", + "resourceUri": "ui://store-screenshot-studio/panel.html", + "availability": "session" + } + ] + }, + "userConfig": { + "fontPath": { + "type": "string", + "default": "", + "title": "中文字体文件(可选)", + "description": "可选。标题文字使用的字体文件(.ttf/.otf/.ttc)完整路径。默认自动查找系统中文字体(macOS: 苹方 / 冬青黑体,Windows: 微软雅黑,Linux: Noto Sans CJK)。" + } + } +} diff --git a/external_plugins/store-screenshot-studio/LICENSE b/external_plugins/store-screenshot-studio/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/store-screenshot-studio/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/store-screenshot-studio/README.md b/external_plugins/store-screenshot-studio/README.md new file mode 100644 index 00000000..d52c5795 --- /dev/null +++ b/external_plugins/store-screenshot-studio/README.md @@ -0,0 +1,50 @@ +# Store Screenshot Studio + +Turn raw app screenshots into App Store and Google Play listing images: a headline and subheadline above or below the screen, a device frame, a solid or gradient background — in several languages and every store size at once. Preview and edit each slide in the side panel. + +## What it does + +- **Exact store sizes**: iPhone 6.9″ 1320×2868, 6.5″ 1284×2778, 5.5″ 1242×2208, iPad 13″ 2064×2752, Google Play phone 1080×1920 and 10″ tablet 1600×2560. Exported as **opaque RGB PNGs** (the stores reject transparency). +- **Device frames**: iPhone (Dynamic Island), Android (punch-hole camera), iPad/tablet bezel, or frameless with a soft shadow; any frame colour. The frame adapts to the screenshot's aspect ratio, so nothing is cropped. +- **Text**: bold headline and optional subheadline, top or bottom, automatic black/white text colour for contrast, auto-shrink to two lines; too-long text is shortened and flagged. +- **Languages**: any number of listing languages (`zh-Hans`, `en-US`, `ja`…); each slide keeps a headline per language. Missing translations fall back to the first language and are flagged. +- **Tablet screenshots**: give a separate tablet screenshot per slide for iPad / tablet sizes; when only a phone screenshot is available, you get a warning. +- **Checks**: long headlines, missing translations, low-resolution screenshots (would look blurry), more than 10 slides (App Store) or 8 (Google Play). +- **Output**: `store-screenshots///-.png`; settings in a reusable `.storeshots.json`. + +## Usage + +In ZCode Desktop, ask the agent: + +- "Make App Store screenshots from the images in screenshots/ — write a short headline for each in Chinese and English" +- "Export the listing images for iPhone 6.9″, iPad and Google Play with a dark gradient background" +- "Change the third headline in English to “Track every order” and export just that one" + +Or open "Store Screenshot Studio" from the session sidebar and tick screenshots in the order you want them. + +## Tools + +| Tool | Purpose | +|---|---| +| `shots_open` | Open screenshots (paths, folder or saved project) with languages, texts and sizes; check and open the panel | +| `project_save` | Save as `.storeshots.json` | +| `shots_export` | Export all, or filter by languages, sizes and slides | + +## Scope (v0.1) + +- Input: PNG and JPG screenshots (from the simulator, a device or a design tool). +- Not in v0.1: uploading to App Store Connect / Google Play Console (do that yourself or with fastlane), panoramic backgrounds spanning several slides, tilted 3D device mock-ups, App Preview videos, the Play feature graphic. +- The device frames are generic drawings, not Apple/Google marketing artwork. + +## Privacy, network and file writes + +- **Everything runs locally.** No network access, nothing is uploaded, no API keys or accounts. +- Reads the chosen screenshots and a system font; writes only inside the workspace (default `store-screenshots/`, plus the `.storeshots.json` you choose). No commands are executed and there are no hooks. + +## Build and test (developers) + +Source lives in `ui-plugins/store-screenshot-studio/`. From the repository root run `pnpm install --frozen-lockfile && pnpm build`, add `dist/local-marketplace` as a local source in the ZCode plugin store and install. Tests: `pnpm --filter @penova/plugin-store-screenshot-studio test` (exact sizes, opaque PNG, colours, text, tablet screenshot, warnings, project round-trip) and `test:e2e` (browser panel test; point `E2E_SCREENS` at real app screenshots). + +## Third-party components and licenses + +The plugin is MIT-licensed (author: Penova). Bundled dependencies: resvg-wasm (MPL-2.0, unmodified; source: https://github.com/yisibl/resvg-js), fontkit (MIT), pngjs (MIT), jpeg-js (BSD-3-Clause), the MCP SDK and ext-apps (MIT). The full list ships in `dist/THIRD_PARTY_NOTICES.txt`. The test screenshots are synthetic mock-ups of a fictional app. App Store is a trademark of Apple Inc.; Google Play is a trademark of Google LLC; this plugin is not affiliated with either. diff --git a/external_plugins/store-screenshot-studio/README_CN.md b/external_plugins/store-screenshot-studio/README_CN.md new file mode 100644 index 00000000..defa7c1e --- /dev/null +++ b/external_plugins/store-screenshot-studio/README_CN.md @@ -0,0 +1,50 @@ +# 应用商店截图制作 + +把 App 原始截图做成 App Store 和 Google Play 的宣传截图:在屏幕上方或下方加主副标题,套上设备边框,配纯色或渐变背景——多语言、所有商店尺寸一次完成。在侧栏预览并逐张编辑。 + +## 功能 + +- **精确的商店尺寸**:iPhone 6.9″ 1320×2868、6.5″ 1284×2778、5.5″ 1242×2208,iPad 13″ 2064×2752,Google Play 手机 1080×1920 和 10″ 平板 1600×2560。导出为**不带透明通道的 RGB PNG**(商店不接受透明图)。 +- **设备边框**:iPhone(灵动岛)、安卓(挖孔摄像头)、iPad/平板边框,或无边框加柔和阴影;机身颜色可选。边框按截图比例自动适配,不裁切内容。 +- **文字**:粗体主标题和可选副标题,放在上方或下方;自动选择黑/白文字保证对比度,自动缩小到两行内;仍然太长会截断并提示。 +- **多语言**:任意数量的商店语言(`zh-Hans`、`en-US`、`ja`…),每张截图按语言分别保存标题。缺少翻译时使用第一种语言的文字并提示。 +- **平板截图**:每张可单独指定平板截图用于 iPad / 平板尺寸;只有手机截图时会提示。 +- **检查**:标题过长、缺少翻译、截图分辨率不足(会模糊)、超过 10 张(App Store)或 8 张(Google Play)。 +- **输出**:`store-screenshots/<语言>/<尺寸>/<序号>-<名称>.png`;设置保存在可复用的 `.storeshots.json`。 + +## 使用 + +在 ZCode Desktop 中对 Agent 说: + +- “用 screenshots 文件夹里的截图做 App Store 宣传图,每张帮我写一句中英文标题” +- “用深色渐变背景导出 iPhone 6.9″、iPad 和 Google Play 尺寸” +- “把第三张的英文标题改成“Track every order”,只重新导出这一张” + +也可以在会话侧栏打开“应用商店截图制作”,按想要的顺序勾选截图。 + +## 工具 + +| 工具 | 作用 | +|---|---| +| `shots_open` | 打开截图(路径、文件夹或已保存项目),设置语言、文案和尺寸,检查并打开面板 | +| `project_save` | 保存为 `.storeshots.json` | +| `shots_export` | 导出全部,或按语言、尺寸、截图筛选导出 | + +## 范围(v0.1) + +- 输入:PNG 和 JPG 截图(模拟器、真机或设计工具导出)。 +- v0.1 不包含:上传到 App Store Connect / Google Play Console(请自行上传或用 fastlane)、跨多张的全景背景、倾斜的 3D 设备样机、App 预览视频、Google Play 置顶大图(feature graphic)。 +- 设备边框是通用绘制,不是 Apple/Google 的官方营销素材。 + +## 隐私、网络与文件写入 + +- **全部在本机处理。** 不联网、不上传、不需要 API 密钥或账号。 +- 读取所选截图和系统字体;只在工作区内写文件(默认 `store-screenshots/`,以及你指定的 `.storeshots.json`)。不执行命令,没有 hooks。 + +## 构建与测试(开发者) + +源码在 `ui-plugins/store-screenshot-studio/`。在仓库根目录运行 `pnpm install --frozen-lockfile && pnpm build`,把 `dist/local-marketplace` 添加为 ZCode 插件商店的本地来源后安装。测试:`pnpm --filter @penova/plugin-store-screenshot-studio test`(精确尺寸、无透明通道、颜色、文字、平板截图、警告、项目保存与读取)和 `test:e2e`(浏览器面板测试;可用 `E2E_SCREENS` 指向真实 App 截图)。 + +## 第三方组件与许可证 + +插件采用 MIT 许可证(作者:Penova)。打包的依赖:resvg-wasm(MPL-2.0,未修改;源码:https://github.com/yisibl/resvg-js)、fontkit(MIT)、pngjs(MIT)、jpeg-js(BSD-3-Clause)、MCP SDK 与 ext-apps(MIT)。完整清单随包附带于 `dist/THIRD_PARTY_NOTICES.txt`。测试截图为虚构 App 的合成样图。App Store 是 Apple Inc. 的商标,Google Play 是 Google LLC 的商标;本插件与二者无关。 diff --git a/external_plugins/store-screenshot-studio/skills/store-screenshot-studio/SKILL.md b/external_plugins/store-screenshot-studio/skills/store-screenshot-studio/SKILL.md new file mode 100644 index 00000000..c4de1b10 --- /dev/null +++ b/external_plugins/store-screenshot-studio/skills/store-screenshot-studio/SKILL.md @@ -0,0 +1,16 @@ +--- +name: store-screenshot-studio +description: 把 App 截图做成 App Store / Google Play 宣传截图(标题、设备边框、背景、多语言、各商店尺寸)。用户提到“应用商店截图 / App Store 截图 / Google Play 截图 / 上架截图 / ASO 截图”时使用。 +--- + +# 应用商店截图制作 + +全部在本机生成,不联网。 + +1. **准备文案**:先看每张截图(可以读取图片)判断它展示的功能,为每种语言写一个**短**标题(中文 ≤ 12 字,英文 2–6 个词)和可选副标题。标题讲用户得到的好处,不写功能名堆砌。把文案给用户确认。 +2. **打开**:`shots_open(paths | folder, locales, texts, presets?, theme?)`,`texts[i]` 是第 i 张的 `{"zh-Hans": {title, subtitle}, "en-US": {...}}`;或 `shots_open(project: "xxx.storeshots.json")`。截图顺序就是商店展示顺序,第一张最重要。最多 10 张(Google Play 只用前 8 张)。 + - 尺寸 id:`ios-6.9`(1320×2868,App Store 必需)、`ios-6.5`、`ios-5.5`、`ipad-13`(有 iPad 版时必需)、`play-phone`、`play-tablet`。 + - `theme`:`background`、`background2`(渐变,空字符串关闭)、`textColor`(auto 或颜色)、`frame`(auto/iphone/android/none)、`frameColor`、`textPosition`(top/bottom)、`deviceScale` 0.5–0.95、`bleed`、`titleScale`。 +3. **看检查结果**:标题过长 → 缩短;缺少翻译 → 补上该语言的 `text`;分辨率不足 → 请用户提供更清晰的截图;平板尺寸用的是手机截图 → 请用户提供 iPad 截图并写到 `slides[i].tabletImage`。 +4. **修改**:单张背景用 `slides[i].background`;改文案直接改 `slides[i].text[locale]`。`project_save(path, project)` 保存为 `.storeshots.json`。 +5. **导出**:`shots_export(project, locales?, presets?, indices?)` → `store-screenshots/<语言>/<尺寸>/<序号>-<名称>.png`。告诉用户上传时按序号顺序。本插件不上传到商店。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..db9c8adb 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,54 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "store-screenshot-studio", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/store-screenshot-studio", + "displayName": "Store Screenshot Studio", + "displayName_i18n": { + "en": "Store Screenshot Studio", + "zh-CN": "应用商店截图制作" + }, + "description": "Turn raw app screenshots into App Store and Google Play listing images: headline and subheadline, iPhone / Android / iPad device frames, solid or gradient backgrounds, several languages, and exact store pixel sizes (iPhone 6.9″/6.5″/5.5″, iPad 13″, Play phone/tablet) exported as opaque PNGs. Checks long headlines, missing translations and blurry screenshots. Runs locally; no API keys.", + "description_i18n": { + "en": "Turn raw app screenshots into App Store and Google Play listing images: headline and subheadline, iPhone / Android / iPad device frames, solid or gradient backgrounds, several languages, and exact store pixel sizes (iPhone 6.9″/6.5″/5.5″, iPad 13″, Play phone/tablet) exported as opaque PNGs. Checks long headlines, missing translations and blurry screenshots. Runs locally; no API keys.", + "zh-CN": "把 App 原始截图做成 App Store 和 Google Play 的宣传截图:加主副标题、iPhone / 安卓 / iPad 设备边框、纯色或渐变背景,支持多语言,按商店要求的精确像素尺寸(iPhone 6.9″/6.5″/5.5″、iPad 13″、Google Play 手机/平板)导出无透明通道的 PNG。自动检查标题过长、缺少翻译和截图分辨率不足。全部本地处理,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "app-store", + "google-play", + "screenshots", + "aso", + "mockup", + "device-frame", + "localization", + "ios", + "android", + "应用商店" + ], + "examplePrompts": [ + "Make App Store screenshots from the images in screenshots/ — write a short headline for each in Chinese and English", + "Export the listing images for iPhone 6.9″, iPad and Google Play with a dark gradient background", + "Change the third headline in English to “Track every order” and export just that one" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "用 screenshots 文件夹里的截图做 App Store 宣传图,每张帮我写一句中英文标题", + "用深色渐变背景导出 iPhone 6.9″、iPad 和 Google Play 尺寸", + "把第三张的英文标题改成“Track every order”,只重新导出这一张" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..73124ab3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -226,6 +226,52 @@ importers: ui-plugins/soundcraft: {} + ui-plugins/store-screenshot-studio: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + '@resvg/resvg-wasm': + specifier: 2.6.2 + version: 2.6.2 + fontkit: + specifier: 2.0.4 + version: 2.0.4 + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 + pngjs: + specifier: 7.0.0 + version: 7.0.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 + '@types/pngjs': + specifier: 6.0.5 + version: 6.0.5 + 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/typst-workbench: dependencies: '@modelcontextprotocol/sdk': @@ -1644,6 +1690,10 @@ packages: '@radix-ui/rect@1.1.0': resolution: {integrity: sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==} + '@resvg/resvg-wasm@2.6.2': + resolution: {integrity: sha512-FqALmHI8D4o6lk/LRWDnhw95z5eO+eAa6ORjVg09YRR7BkcM6oPHU9uyC0gtQG5vpFLvgpeU4+zEAz2H8APHNw==} + engines: {node: '>= 10'} + '@rolldown/binding-android-arm-eabi@1.2.11': resolution: {integrity: sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1884,6 +1934,9 @@ packages: '@types/pako@2.0.4': resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/pngjs@6.0.5': + resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==} + '@types/raf@3.4.3': resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==} @@ -2030,6 +2083,9 @@ packages: resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==} engines: {node: '>= 0.6.0'} + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + binary-extensions@2.3.0: resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} engines: {node: '>=8'} @@ -2045,6 +2101,9 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + brotli@1.3.3: + resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==} + browser-fs-access@0.29.1: resolution: {integrity: sha512-LSvVX5e21LRrXqVMhqtAwj5xPgDb+fXAIH80NsnCQ9xuZPs2xWsOREi24RKgZa1XOiQRbcmVrv87+ulOKsgjxw==} @@ -2109,6 +2168,10 @@ packages: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} + clone@2.1.2: + resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} + engines: {node: '>=0.8'} + clsx@1.1.1: resolution: {integrity: sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA==} engines: {node: '>=6'} @@ -2401,6 +2464,9 @@ packages: detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + dfa@1.2.0: + resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==} + diff@8.0.4: resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} engines: {node: '>=0.3.1'} @@ -2475,10 +2541,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'} @@ -2536,6 +2598,9 @@ packages: font-family-papandreou@0.2.0-patch2: resolution: {integrity: sha512-l/YiRdBSH/eWv6OF3sLGkwErL+n0MqCICi9mppTZBOCL5vixWGDqCYvRcuxB2h7RGCTzaTKOHT2caHvCXQPRlw==} + fontkit@2.0.4: + resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==} + fontoxpath@3.34.0: resolution: {integrity: sha512-7FgBQRohn4WR/2eVdYqZtKBFZkJNaiP4kGdfqS6bAg465og05ixGA2OgfMdxsO1mnX67+64JX/8JKclVqS+bzA==} @@ -2714,9 +2779,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: @@ -2735,6 +2797,9 @@ packages: react: optional: true + jpeg-js@0.4.4: + resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} + js-base64@3.9.4: resolution: {integrity: sha512-PtOMXpEGuP0RRiRXsjzHzl44dMHxSu2CPvAhinupR1tBa88me+1DPqsobl7eupn5UukjLkln1ZnAOAOXOrYG0Q==} @@ -3019,6 +3084,9 @@ packages: package-manager-detector@1.6.0: resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==} + pako@0.2.9: + resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -3068,10 +3136,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'} @@ -3101,6 +3165,10 @@ packages: png-chunks-extract@1.0.0: resolution: {integrity: sha512-ZiVwF5EJ0DNZyzAqld8BP1qyJBaGOFaq9zl579qfbkcmOwWLLO4I9L8i2O4j3HkI6/35i0nKG2n+dZplxiT89Q==} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + points-on-curve@0.2.0: resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} @@ -3216,6 +3284,9 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + restructure@3.0.2: + resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==} + rettime@0.11.7: resolution: {integrity: sha512-DoAm1WjR1eH7z8sHPtvvUMIZh4/CSKkGCz6CxPqOrEAnOGtOuHSnSE9OC+razqxKuf4ub7pAYyl/vZV0vGs5tg==} @@ -3380,21 +3451,16 @@ packages: thenify@3.3.1: resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + tiny-inflate@1.0.3: + resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + 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'} @@ -3473,6 +3539,12 @@ packages: resolution: {integrity: sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==} engines: {node: '>=22.19.0'} + unicode-properties@1.4.1: + resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==} + + unicode-trie@2.0.0: + resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==} + unifont@0.7.5: resolution: {integrity: sha512-ULe/Cs+ZIsq+dcFofNkhqielCrUJnb5mr+Yc4EBM2VlL+6OZR6+cjtI2mT1bJvRBrVncqHAbLURxmPLcCXzWMg==} @@ -3742,7 +3814,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 +4357,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 @@ -4911,6 +4983,8 @@ snapshots: '@radix-ui/rect@1.1.0': {} + '@resvg/resvg-wasm@2.6.2': {} + '@rolldown/binding-android-arm-eabi@1.2.11': optional: true @@ -5118,6 +5192,10 @@ snapshots: '@types/pako@2.0.4': {} + '@types/pngjs@6.0.5': + dependencies: + '@types/node': 25.5.0 + '@types/raf@3.4.3': optional: true @@ -5297,6 +5375,8 @@ snapshots: base64-arraybuffer@1.0.2: optional: true + base64-js@1.5.1: {} + binary-extensions@2.3.0: {} bind-event-listener@3.0.0: {} @@ -5319,6 +5399,10 @@ snapshots: dependencies: fill-range: 7.1.1 + brotli@1.3.3: + dependencies: + base64-js: 1.5.1 + browser-fs-access@0.29.1: {} bun@1.3.11: @@ -5417,6 +5501,8 @@ snapshots: wrap-ansi: 7.0.0 optional: true + clone@2.1.2: {} + clsx@1.1.1: {} color-convert@2.0.1: @@ -5702,6 +5788,8 @@ snapshots: detect-node-es@1.1.0: {} + dfa@1.2.0: {} + diff@8.0.4: {} dompurify@3.3.3: @@ -5809,13 +5897,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 +5955,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 @@ -5896,6 +5978,18 @@ snapshots: font-family-papandreou@0.2.0-patch2: {} + fontkit@2.0.4: + dependencies: + '@swc/helpers': 0.5.23 + brotli: 1.3.3 + clone: 2.1.2 + dfa: 1.2.0 + fast-deep-equal: 3.1.3 + restructure: 3.0.2 + tiny-inflate: 1.0.3 + unicode-properties: 1.4.1 + unicode-trie: 2.0.0 + fontoxpath@3.34.0: dependencies: prsc: 4.0.0 @@ -6048,8 +6142,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) @@ -6060,6 +6152,8 @@ snapshots: '@types/react': 19.2.14 react: 19.2.7 + jpeg-js@0.4.4: {} + js-base64@3.9.4: {} json-schema-traverse@1.0.0: {} @@ -6366,6 +6460,8 @@ snapshots: package-manager-detector@1.6.0: {} + pako@0.2.9: {} + pako@1.0.11: {} pako@2.0.3: {} @@ -6406,8 +6502,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6433,6 +6527,8 @@ snapshots: dependencies: crc-32: 0.3.0 + pngjs@7.0.0: {} + points-on-curve@0.2.0: {} points-on-curve@1.0.1: {} @@ -6565,6 +6661,8 @@ snapshots: resolve-pkg-maps@1.0.0: optional: true + restructure@3.0.2: {} + rettime@0.11.7: optional: true @@ -6745,7 +6843,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: @@ -6777,17 +6875,12 @@ snapshots: dependencies: any-promise: 1.3.0 - tinybench@2.9.0: {} + tiny-inflate@1.0.3: {} - tinyexec@1.1.1: {} + tinybench@2.9.0: {} 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) @@ -6861,6 +6954,16 @@ snapshots: undici@8.10.2: {} + unicode-properties@1.4.1: + dependencies: + base64-js: 1.5.1 + unicode-trie: 2.0.0 + + unicode-trie@2.0.0: + dependencies: + pako: 0.2.9 + tiny-inflate: 1.0.3 + unifont@0.7.5: dependencies: css-tree: 3.2.1 diff --git a/ui-plugins/store-screenshot-studio/package.json b/ui-plugins/store-screenshot-studio/package.json new file mode 100644 index 00000000..ffad314f --- /dev/null +++ b/ui-plugins/store-screenshot-studio/package.json @@ -0,0 +1,40 @@ +{ + "name": "@penova/plugin-store-screenshot-studio", + "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": "Store Screenshot Studio", + "assets": { + "@resvg/resvg-wasm/index_bg.wasm": "resvg.wasm" + } + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "@resvg/resvg-wasm": "2.6.2", + "fontkit": "2.0.4", + "jpeg-js": "0.4.4", + "pngjs": "7.0.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "@types/pngjs": "6.0.5", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/store-screenshot-studio/scripts/build.mjs b/ui-plugins/store-screenshot-studio/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/scripts/build.mjs @@ -0,0 +1,74 @@ +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) }); +} + +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/store-screenshot-studio/scripts/e2e.mts b/ui-plugins/store-screenshot-studio/scripts/e2e.mts new file mode 100644 index 00000000..da88e3e3 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/scripts/e2e.mts @@ -0,0 +1,74 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板。 +// 运行:node --experimental-strip-types scripts/e2e.mts(需要本机 Chrome,或设置 CHROME_PATH)。 +// 可用 E2E_SCREENS 指向一个装有真实 App 截图的文件夹(按文件名排序,最多取 4 张)。 +import assert from "node:assert/strict"; +import { copyFile, mkdir, mkdtemp, readdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "store-screenshot-studio-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "storeshots-e2e-")); +await mkdir(join(workspace, "截图")); +const fixtures = new URL("../test/fixtures/", import.meta.url).pathname; +for (const f of ["01-menu.png", "02-orders.png", "ipad-menu.png"]) await copyFile(join(fixtures, f), join(workspace, "截图", f)); +const extra = process.env.E2E_SCREENS ? (await readdir(process.env.E2E_SCREENS)).filter((f) => /\.(png|jpe?g)$/i.test(f)).sort().slice(0, 4) : []; +for (const [i, f] of extra.entries()) await copyFile(join(process.env.E2E_SCREENS!, f), join(workspace, "截图", `1${i}-${f}`)); +const paths = ["截图/01-menu.png", "截图/02-orders.png", ...extra.map((f, i) => `截图/1${i}-${f}`)]; + +const harness = await startHarness({ workspace }); +const step = (text: string) => process.stdout.write(`• ${text}\n`); +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1280, height: 1000 }); + step("empty panel lists workspace screenshots"); + await frame.locator("label", { hasText: "01-menu.png" }).waitFor(); + + step("agent opens the screenshots with copy in two languages"); + const zh = ["一键点单", "订单实时追踪", "随时随地查百科", "图文并茂一读就懂", "热门新闻一手掌握", "开放地图精准导航"]; + const en = ["Order in one tap", "Track every order", "Knowledge to go", "Rich articles", "Top stories", "Open maps"]; + const texts = paths.map((_, i) => ({ "zh-Hans": { title: zh[i] ?? "精彩功能", ...(i === 0 ? { subtitle: "常喝的咖啡,三秒下单" } : {}) }, "en-US": { title: en[i] ?? "Great features" } })); + await harness.agent(outer, "shots_open", { paths, locales: ["zh-Hans", "en-US"], texts, presets: ["ios-6.9", "ipad-13", "play-phone"], theme: { background: "#ecfdf5", background2: "#a7f3d0" } }); + await frame.locator(".strip .thumb img").nth(paths.length - 1).waitFor({ timeout: 180_000 }); + await frame.waitForFunction(() => !!(document.getElementById("large") as HTMLImageElement)?.src, null, { timeout: 60_000 }); + await outer.screenshot({ path: join(shots, "01-slides.png") }); + + step("switch style: dark gradient, android frame, text at bottom"); + await frame.locator(".side select").first().selectOption("android"); + await frame.locator(".side select").nth(1).selectOption("bottom"); + await frame.locator(".side input[type=color]").first().evaluate((el: HTMLInputElement) => { + el.value = "#0f172a"; + el.dispatchEvent(new Event("input", { bubbles: true })); + }); + await frame.waitForTimeout(6000); + await outer.screenshot({ path: join(shots, "02-style.png") }); + + step("edit the English headline of slide 2"); + await frame.locator(".tabs button", { hasText: "en-US" }).click(); + await frame.locator(".strip .thumb").nth(1).click(); + await frame.locator(".detail textarea").first().fill("See where your coffee is"); + await frame.waitForTimeout(2500); + await outer.screenshot({ path: join(shots, "03-english.png") }); + + step("iPad size with a tablet screenshot"); + await frame.locator(".toolbar select").selectOption("ipad-13"); + await frame.locator(".strip .thumb").first().click(); + await frame.locator(".detail select").first().selectOption("截图/ipad-menu.png"); + await frame.waitForTimeout(4000); + await outer.screenshot({ path: join(shots, "04-ipad.png") }); + + step("export all"); + await frame.locator("button", { hasText: "导出全部" }).click(); + await frame.locator("h2", { hasText: "已导出" }).waitFor({ timeout: 600_000 }); + for (const locale of ["zh-Hans", "en-US"]) for (const size of ["ios-6.9", "ipad-13", "play-phone"]) assert.equal((await readdir(join(workspace, "store-screenshots", locale, size))).length, paths.length); + await copyFile(join(workspace, "store-screenshots/en-US/ios-6.9/02-02-orders.png"), join(shots, "export-en-ios-02.png")); + await copyFile(join(workspace, "store-screenshots/zh-Hans/ipad-13/01-01-menu.png"), join(shots, "export-zh-ipad-01.png")); + await outer.screenshot({ path: join(shots, "05-exported.png") }); + assert.deepEqual(harness.errors, []); + step(`ok — ${paths.length} slides, screenshots in ${shots}`); +} catch (error) { + console.error("page errors:", harness.errors, harness.stderr.join("")); + throw error; +} finally { + await harness.close(); +} diff --git a/ui-plugins/store-screenshot-studio/scripts/harness.mjs b/ui-plugins/store-screenshot-studio/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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/store-screenshot-studio/scripts/licenses.mjs b/ui-plugins/store-screenshot-studio/scripts/licenses.mjs new file mode 100644 index 00000000..162c2a73 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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) { + 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")); +} diff --git a/ui-plugins/store-screenshot-studio/src/kit/color.ts b/ui-plugins/store-screenshot-studio/src/kit/color.ts new file mode 100644 index 00000000..b1728fb6 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/kit/color.ts @@ -0,0 +1,82 @@ +import { parseColor, type Raster } from "./raster.ts"; + +export type RGB = [number, number, number]; + +export const toHex = (c: RGB) => `#${c.map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")).join("")}`; + +export function luminance(c: RGB) { + const [r, g, b] = c.map((v) => { + const s = v / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +export function contrast(a: RGB, b: RGB) { + const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m); + return (x + 0.05) / (y + 0.05); +} + +/** 在 bg 上更易读的文字颜色。 */ +export function readableOn(bg: string | RGB, dark = "#111827", light = "#ffffff") { + const c = typeof bg === "string" ? parseColor(bg) : bg; + return contrast(c, parseColor(dark)) >= contrast(c, parseColor(light)) ? dark : light; +} + +export function mix(a: RGB, b: RGB, t: number): RGB { + return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; +} + +export function rgbToHsl([r, g, b]: RGB): [number, number, number] { + const [rn, gn, bn] = [r / 255, g / 255, b / 255]; + const max = Math.max(rn, gn, bn); + const min = Math.min(rn, gn, bn); + const l = (max + min) / 2; + if (max === min) return [0, 0, l]; + const d = max - min; + const s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + const h = max === rn ? (gn - bn) / d + (gn < bn ? 6 : 0) : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4; + return [h * 60, s, l]; +} + +/** 从图片里取主色:忽略透明、接近白/黑/灰的像素,按出现次数排序。 */ +export function extractPalette(image: Raster, count = 4): { colors: RGB[]; average: RGB; hasAlpha: boolean } { + const bins = new Map(); + let transparent = 0; + let total = 0; + const avg = [0, 0, 0]; + const step = Math.max(1, Math.floor((image.width * image.height) / 60000)); + for (let p = 0; p < image.width * image.height; p += step) { + const i = p * 4; + const a = image.data[i + 3]; + if (a < 128) { + transparent++; + continue; + } + const c: RGB = [image.data[i], image.data[i + 1], image.data[i + 2]]; + total++; + avg[0] += c[0]; + avg[1] += c[1]; + avg[2] += c[2]; + const [, s, l] = rgbToHsl(c); + if (s < 0.18 || l > 0.94 || l < 0.08) continue; + const key = ((c[0] >> 4) << 8) | ((c[1] >> 4) << 4) | (c[2] >> 4); + const bin = bins.get(key) ?? { n: 0, r: 0, g: 0, b: 0 }; + bin.n++; + bin.r += c[0]; + bin.g += c[1]; + bin.b += c[2]; + bins.set(key, bin); + } + const ranked = [...bins.values()].sort((a, b) => b.n - a.n); + // 抗锯齿边缘产生的过渡色数量很少,忽略。 + const sorted = ranked.filter((b) => b.n >= (ranked[0]?.n ?? 0) * 0.06).map((b) => [b.r / b.n, b.g / b.n, b.b / b.n] as RGB); + const colors: RGB[] = []; + for (const c of sorted) { + if (colors.length >= count) break; + const [h] = rgbToHsl(c); + if (colors.every((d) => Math.abs(rgbToHsl(d)[0] - h) > 18 || Math.abs(luminance(c) - luminance(d)) > 0.25)) colors.push(c); + } + const average: RGB = total ? [avg[0] / total, avg[1] / total, avg[2] / total] : [0, 0, 0]; + return { colors, average, hasAlpha: transparent > (image.width * image.height) / step / 50 }; +} diff --git a/ui-plugins/store-screenshot-studio/src/kit/console.ts b/ui-plugins/store-screenshot-studio/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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/store-screenshot-studio/src/kit/fontkit.d.ts b/ui-plugins/store-screenshot-studio/src/kit/fontkit.d.ts new file mode 100644 index 00000000..c3ad5cd3 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/kit/fontkit.d.ts @@ -0,0 +1 @@ +declare module "fontkit"; diff --git a/ui-plugins/store-screenshot-studio/src/kit/fonts.ts b/ui-plugins/store-screenshot-studio/src/kit/fonts.ts new file mode 100644 index 00000000..84e65845 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/kit/fonts.ts @@ -0,0 +1,90 @@ +import { readFile, stat } from "node:fs/promises"; +import { KitError } from "./workspace.ts"; + +/** 常见系统中文字体。TrueType 优先(PDF 子集嵌入最稳定),然后是集合字体。 */ +export const CJK_FONT_CANDIDATES = [ + // macOS + "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", + "/Library/Fonts/Arial Unicode.ttf", + "/System/Library/Fonts/Hiragino Sans GB.ttc", + "/System/Library/Fonts/STHeiti Medium.ttc", + "/System/Library/Fonts/STHeiti Light.ttc", + "/System/Library/Fonts/PingFang.ttc", + // Windows + "C:\\Windows\\Fonts\\simhei.ttf", + "C:\\Windows\\Fonts\\msyh.ttc", + "C:\\Windows\\Fonts\\simsun.ttc", + // Linux + "/usr/share/fonts/truetype/arphic/uming.ttc", + "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc", +]; + +export interface LoadedFont { + path: string; + /** 原始文件(可能是 .ttc 集合)。 */ + data: Buffer; +} + +const cache = new Map(); + +/** 用户指定的字体优先,否则按候选列表找第一个存在的中文字体。 */ +export async function findCjkFont(userPath?: string | null, candidates: string[] = CJK_FONT_CANDIDATES): Promise { + const configured = userPath?.trim() && !userPath.includes("${") ? userPath.trim() : undefined; + const list = configured ? [configured, ...candidates] : candidates; + for (const path of list) { + if (cache.has(path)) return cache.get(path)!; + try { + if (!(await stat(path)).isFile()) continue; + const font = { path, data: await readFile(path) }; + cache.set(path, font); + return font; + } catch { + // 继续查找 + } + } + throw new KitError( + "font_not_found", + "No Chinese-capable font was found. Set the plugin's fontPath setting to a .ttf/.otf/.ttc font file (for example Arial Unicode.ttf, Microsoft YaHei or Noto Sans CJK).", + ); +} + +/** 从 .ttc 字体集合中取出第 index 个字体,组成独立的 sfnt 文件(pdf-lib 只能嵌入单个字体)。 */ +export function extractFace(data: Uint8Array, index = 0): Uint8Array { + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + if (view.getUint32(0) !== 0x74746366) return data; // 不是 'ttcf' + const count = view.getUint32(8); + if (index >= count) throw new KitError("font_error", `Font collection has ${count} faces.`); + const offset = view.getUint32(12 + index * 4); + const numTables = view.getUint16(offset + 4); + const tables: { tag: number; checksum: number; start: number; length: number }[] = []; + for (let i = 0; i < numTables; i++) { + const record = offset + 12 + i * 16; + tables.push({ tag: view.getUint32(record), checksum: view.getUint32(record + 4), start: view.getUint32(record + 8), length: view.getUint32(record + 12) }); + } + const headerSize = 12 + numTables * 16; + let total = headerSize; + for (const table of tables) total += (table.length + 3) & ~3; + const out = new Uint8Array(total); + const outView = new DataView(out.buffer); + out.set(data.subarray(offset, offset + 12), 0); + let cursor = headerSize; + tables.forEach((table, i) => { + const record = 12 + i * 16; + outView.setUint32(record, table.tag); + outView.setUint32(record + 4, table.checksum); + outView.setUint32(record + 8, cursor); + outView.setUint32(record + 12, table.length); + out.set(data.subarray(table.start, table.start + table.length), cursor); + cursor += (table.length + 3) & ~3; + }); + return out; +} + +/** PDF 用字体:单个字体(集合取第一个),配合 fontkit 2 子集化嵌入。 */ +export async function findPdfFont(userPath?: string | null): Promise<{ path: string; face: Uint8Array; subset: boolean }> { + const font = await findCjkFont(userPath); + return { path: font.path, face: extractFace(font.data, 0), subset: true }; +} diff --git a/ui-plugins/store-screenshot-studio/src/kit/raster.ts b/ui-plugins/store-screenshot-studio/src/kit/raster.ts new file mode 100644 index 00000000..e711ec7a --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/kit/raster.ts @@ -0,0 +1,240 @@ +import jpeg from "jpeg-js"; +import { PNG } from "pngjs"; +import { KitError } from "./workspace.ts"; + +/** RGBA 8 位图像。 */ +export interface Raster { + width: number; + height: number; + data: Uint8ClampedArray | Uint8Array; +} + +export function createRaster(width: number, height: number, fill?: [number, number, number, number]): Raster { + const data = new Uint8ClampedArray(width * height * 4); + if (fill && (fill[0] || fill[1] || fill[2] || fill[3])) for (let i = 0; i < data.length; i += 4) data.set(fill, i); + return { width, height, data }; +} + +/** JPEG 的 EXIF 方向(1–8),没有则为 1。 */ +export function jpegOrientation(bytes: Uint8Array): number { + if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return 1; + let offset = 2; + while (offset + 4 < bytes.length) { + if (bytes[offset] !== 0xff) return 1; + const marker = bytes[offset + 1]; + const length = (bytes[offset + 2] << 8) | bytes[offset + 3]; + if (marker === 0xe1 && bytes[offset + 4] === 0x45 && bytes[offset + 5] === 0x78 && bytes[offset + 6] === 0x69 && bytes[offset + 7] === 0x66) { + const tiff = offset + 10; + const little = bytes[tiff] === 0x49; + const u16 = (at: number) => (little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]); + const u32 = (at: number) => (little ? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16)) + bytes[at + 3] * 16777216 : bytes[at] * 16777216 + ((bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3])); + const ifd = tiff + u32(tiff + 4); + const count = u16(ifd); + for (let i = 0; i < count; i++) { + const entry = ifd + 2 + i * 12; + if (entry + 12 > bytes.length) break; + if (u16(entry) === 0x0112) return u16(entry + 8) || 1; + } + return 1; + } + if (marker === 0xda) return 1; + offset += 2 + length; + } + return 1; +} + +function orient(image: Raster, orientation: number): Raster { + if (orientation <= 1 || orientation > 8) return image; + const { width: w, height: h, data } = image; + const swap = orientation >= 5; + const out = createRaster(swap ? h : w, swap ? w : h); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) { + let nx = x; + let ny = y; + switch (orientation) { + case 2: nx = w - 1 - x; break; + case 3: nx = w - 1 - x; ny = h - 1 - y; break; + case 4: ny = h - 1 - y; break; + case 5: nx = y; ny = x; break; + case 6: nx = h - 1 - y; ny = x; break; + case 7: nx = h - 1 - y; ny = w - 1 - x; break; + case 8: nx = y; ny = w - 1 - x; break; + } + const s = (y * w + x) * 4; + const d = (ny * out.width + nx) * 4; + out.data[d] = data[s]; + out.data[d + 1] = data[s + 1]; + out.data[d + 2] = data[s + 2]; + out.data[d + 3] = data[s + 3]; + } + return out; +} + +export function decodeImage(bytes: Uint8Array, name = "image"): Raster { + try { + if (bytes[0] === 0x89 && bytes[1] === 0x50) { + const png = PNG.sync.read(Buffer.from(bytes)); + return { width: png.width, height: png.height, data: new Uint8ClampedArray(png.data.buffer, png.data.byteOffset, png.data.length) }; + } + if (bytes[0] === 0xff && bytes[1] === 0xd8) { + const image = jpeg.decode(bytes, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024, maxResolutionInMP: 200 }); + return orient({ width: image.width, height: image.height, data: new Uint8ClampedArray(image.data.buffer) }, jpegOrientation(bytes)); + } + } catch (error) { + throw new KitError("bad_image", `Cannot decode ${name}: ${error instanceof Error ? error.message : error}`); + } + throw new KitError("unsupported_image", `${name}: only PNG and JPEG are supported (convert WebP/HEIC first).`); +} + +export function encodePng(image: Raster): Buffer { + const png = new PNG({ width: image.width, height: image.height }); + png.data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.length); + return PNG.sync.write(png, { colorType: 6 }); +} + +/** 不带透明通道的 PNG(应用商店截图等不接受 alpha)。 */ +export function encodePngOpaque(image: Raster, background: [number, number, number] = [255, 255, 255]): Buffer { + const png = new PNG({ width: image.width, height: image.height }); + png.data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.length); + return PNG.sync.write(png, { colorType: 2, inputHasAlpha: true, bgColor: { red: background[0], green: background[1], blue: background[2] } }); +} + +/** JPEG 不支持透明:先与背景色合成。 */ +export function encodeJpeg(image: Raster, quality = 90, background: [number, number, number] = [255, 255, 255]): Buffer { + const data = Buffer.alloc(image.width * image.height * 4); + for (let i = 0; i < data.length; i += 4) { + const a = image.data[i + 3] / 255; + data[i] = Math.round(image.data[i] * a + background[0] * (1 - a)); + data[i + 1] = Math.round(image.data[i + 1] * a + background[1] * (1 - a)); + data[i + 2] = Math.round(image.data[i + 2] * a + background[2] * (1 - a)); + data[i + 3] = 255; + } + return jpeg.encode({ width: image.width, height: image.height, data }, quality).data; +} + +/** 缩放:缩小用区域平均(预乘 alpha,避免透明边发黑),放大用双线性。 */ +export function resize(image: Raster, width: number, height: number): Raster { + width = Math.max(1, Math.round(width)); + height = Math.max(1, Math.round(height)); + if (width === image.width && height === image.height) return image; + const out = createRaster(width, height); + const sx = image.width / width; + const sy = image.height / height; + const src = image.data; + if (sx >= 1 && sy >= 1) { + for (let y = 0; y < height; y++) { + const y0 = y * sy; + const y1 = Math.min(image.height, (y + 1) * sy); + for (let x = 0; x < width; x++) { + const x0 = x * sx; + const x1 = Math.min(image.width, (x + 1) * sx); + let r = 0, g = 0, b = 0, a = 0, total = 0; + for (let yy = Math.floor(y0); yy < Math.ceil(y1); yy++) { + const wy = Math.min(yy + 1, y1) - Math.max(yy, y0); + for (let xx = Math.floor(x0); xx < Math.ceil(x1); xx++) { + const wgt = wy * (Math.min(xx + 1, x1) - Math.max(xx, x0)); + const i = (yy * image.width + xx) * 4; + const alpha = src[i + 3] * wgt; + r += src[i] * alpha; + g += src[i + 1] * alpha; + b += src[i + 2] * alpha; + a += alpha; + total += wgt; + } + } + const o = (y * width + x) * 4; + if (a > 0) { + out.data[o] = r / a; + out.data[o + 1] = g / a; + out.data[o + 2] = b / a; + } + out.data[o + 3] = a / total; + } + } + return out; + } + for (let y = 0; y < height; y++) { + const fy = Math.min(image.height - 1, Math.max(0, (y + 0.5) * sy - 0.5)); + const y0 = Math.floor(fy); + const y1 = Math.min(image.height - 1, y0 + 1); + const ty = fy - y0; + for (let x = 0; x < width; x++) { + const fx = Math.min(image.width - 1, Math.max(0, (x + 0.5) * sx - 0.5)); + const x0 = Math.floor(fx); + const x1 = Math.min(image.width - 1, x0 + 1); + const tx = fx - x0; + const o = (y * width + x) * 4; + const i00 = (y0 * image.width + x0) * 4, i10 = (y0 * image.width + x1) * 4, i01 = (y1 * image.width + x0) * 4, i11 = (y1 * image.width + x1) * 4; + const w00 = (1 - tx) * (1 - ty) * src[i00 + 3], w10 = tx * (1 - ty) * src[i10 + 3], w01 = (1 - tx) * ty * src[i01 + 3], w11 = tx * ty * src[i11 + 3]; + const a = w00 + w10 + w01 + w11; + if (a > 0) for (let c = 0; c < 3; c++) out.data[o + c] = (src[i00 + c] * w00 + src[i10 + c] * w10 + src[i01 + c] * w01 + src[i11 + c] * w11) / a; + out.data[o + 3] = a; + } + } + return out; +} + +/** 等比缩小到最长边不超过 max。 */ +export function fitWithin(image: Raster, max: number): Raster { + const scale = Math.min(1, max / Math.max(image.width, image.height)); + return scale < 1 ? resize(image, image.width * scale, image.height * scale) : image; +} + +/** 单通道盒式模糊(3 次近似高斯)。 */ +export function blurChannel(values: Float32Array, width: number, height: number, radius: number, passes = 3): Float32Array { + const r = Math.max(0, Math.round(radius)); + if (!r) return values; + let src = values; + let tmp = new Float32Array(values.length); + for (let pass = 0; pass < passes; pass++) { + for (let y = 0; y < height; y++) { + let sum = 0; + const row = y * width; + for (let x = -r; x <= r; x++) sum += src[row + Math.min(width - 1, Math.max(0, x))]; + for (let x = 0; x < width; x++) { + tmp[row + x] = sum / (2 * r + 1); + sum += src[row + Math.min(width - 1, x + r + 1)] - src[row + Math.max(0, x - r)]; + } + } + const out = new Float32Array(values.length); + for (let x = 0; x < width; x++) { + let sum = 0; + for (let y = -r; y <= r; y++) sum += tmp[Math.min(height - 1, Math.max(0, y)) * width + x]; + for (let y = 0; y < height; y++) { + out[y * width + x] = sum / (2 * r + 1); + sum += tmp[Math.min(height - 1, y + r + 1) * width + x] - tmp[Math.max(0, y - r) * width + x]; + } + } + src = out; + } + tmp = new Float32Array(0); + return src; +} + +export function parseColor(color: string | undefined, fallback: [number, number, number] = [255, 255, 255]): [number, number, number] { + const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((color ?? "").trim()); + if (!match) return fallback; + const hex = match[1].length === 3 ? [...match[1]].map((c) => c + c).join("") : match[1]; + return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)]; +} + +/** 把 src 按 alpha 叠到 dst 的 (dx, dy) 位置。 */ +export function drawOver(dst: Raster, src: Raster, dx: number, dy: number, opacity = 1) { + for (let y = 0; y < src.height; y++) { + const ty = y + dy; + if (ty < 0 || ty >= dst.height) continue; + for (let x = 0; x < src.width; x++) { + const tx = x + dx; + if (tx < 0 || tx >= dst.width) continue; + const s = (y * src.width + x) * 4; + const a = (src.data[s + 3] / 255) * opacity; + if (a <= 0) continue; + const d = (ty * dst.width + tx) * 4; + const da = dst.data[d + 3] / 255; + const oa = a + da * (1 - a); + for (let c = 0; c < 3; c++) dst.data[d + c] = (src.data[s + c] * a + dst.data[d + c] * da * (1 - a)) / oa; + dst.data[d + 3] = oa * 255; + } + } +} diff --git a/ui-plugins/store-screenshot-studio/src/kit/render.ts b/ui-plugins/store-screenshot-studio/src/kit/render.ts new file mode 100644 index 00000000..53a36ccd --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/kit/render.ts @@ -0,0 +1,203 @@ +import { readFile } from "node:fs/promises"; +import { Resvg, initWasm } from "@resvg/resvg-wasm"; +import * as fontkitModule from "fontkit"; +import { readFile as readFont } from "node:fs/promises"; +import { CJK_FONT_CANDIDATES, extractFace, findCjkFont } from "./fonts.ts"; +import { KitError } from "./workspace.ts"; + +const fontkit: any = fontkitModule; + +let wasmReady: Promise | undefined; +/** resvg 的 wasm 随插件分发(dist/resvg.wasm)。 */ +export function initRenderer(wasmPath: string) { + wasmReady ??= readFile(wasmPath).then((bytes) => initWasm(bytes)); + return wasmReady; +} + +export interface FontSet { + path: string; + family: string; + boldFamily?: string; + buffers: Uint8Array[]; + /** 文字宽度(px)。 */ + measure: (text: string, size: number, bold?: boolean) => number; +} + +interface Face { + familyName: string; + subfamilyName: string; + unitsPerEm: number; + layout: (text: string) => { advanceWidth: number }; +} + +const faceCount = (data: Uint8Array) => { + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + return view.getUint32(0) === 0x74746366 ? view.getUint32(8) : 1; +}; + +/** 屏幕/图片渲染优先选带粗体的集合字体。 */ +export const RENDER_FONT_CANDIDATES = [ + "/System/Library/Fonts/PingFang.ttc", + "/System/Library/Fonts/Hiragino Sans GB.ttc", + "/System/Library/Fonts/STHeiti Light.ttc", + "/System/Library/Fonts/STHeiti Medium.ttc", + "C:\\Windows\\Fonts\\msyh.ttc", + "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", + "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc", + ...CJK_FONT_CANDIDATES, +]; + +/** 同目录下的粗体文件(Noto CJK、微软雅黑、华文黑体)。 */ +const BOLD_SIBLINGS: [RegExp, string][] = [ + [/-Regular\.ttc$/, "-Bold.ttc"], + [/msyh\.ttc$/i, "msyhbd.ttc"], + [/STHeiti Light\.ttc$/, "STHeiti Medium.ttc"], + [/simhei\.ttf$/i, "msyhbd.ttc"], +]; + +let cached: { key: string; fonts: FontSet } | undefined; + +/** 载入中文字体(含同一集合里的粗体),供 SVG 渲染和排版测量使用。 */ +export async function loadFonts(userPath?: string | null): Promise { + const font = await findCjkFont(userPath, RENDER_FONT_CANDIDATES); + if (cached?.key === font.path) return cached.fonts; + const buffers: Uint8Array[] = [font.data]; + const faces: Face[] = []; + const addFaces = (data: Uint8Array) => { + for (let i = 0; i < Math.min(faceCount(data), 12); i++) { + try { + faces.push(fontkit.create(Buffer.from(extractFace(data, i))) as Face); + } catch { + // 跳过无法解析的字体 + } + } + }; + addFaces(font.data); + for (const [pattern, replacement] of BOLD_SIBLINGS) { + if (!pattern.test(font.path)) continue; + try { + const data = await readFont(font.path.replace(pattern, replacement)); + buffers.push(data); + addFaces(data); + } catch { + // 没有粗体文件时用描边加粗 + } + break; + } + if (!faces.length) throw new KitError("font_error", `Cannot read font ${font.path}`); + // 集合里优先简体中文字形(如 Noto Sans CJK SC),否则用第一个。 + const regular = faces.find((f) => /\bSC\b|GB|Simplified/i.test(f.familyName) && !/bold|black|heavy|w[6-9]/i.test(f.subfamilyName)) ?? faces[0]; + const isBold = (f: Face) => f !== regular && /bold|semibold|black|heavy|w6|w7|w8/i.test(`${f.subfamilyName} ${f.familyName}`); + const bold = + faces.find((f) => isBold(f) && f.familyName === regular.familyName) ?? + faces.find((f) => isBold(f) && f.familyName.replace(/\s*W\d$/, "") === regular.familyName.replace(/\s*W\d$/, "")) ?? + faces.find((f) => isBold(f) && f.familyName.split(" ")[0] === regular.familyName.split(" ")[0]); + const measureWith = (face: Face) => (text: string, size: number) => (face.layout(text).advanceWidth / face.unitsPerEm) * size; + const regularMeasure = measureWith(regular); + const boldMeasure = bold ? measureWith(bold) : (text: string, size: number) => regularMeasure(text, size) * 1.04; + const fonts: FontSet = { + path: font.path, + family: regular.familyName, + boldFamily: bold?.familyName, + buffers, + measure: (text, size, isBold) => (isBold ? boldMeasure(text, size) : regularMeasure(text, size)), + }; + cached = { key: font.path, fonts }; + return fonts; +} + +export interface RenderedPng { + png: Uint8Array; + width: number; + height: number; + pixels: Uint8Array; +} + +/** SVG → PNG。width 指定输出像素宽度(按比例缩放)。 */ +export async function renderSvg(svg: string, fonts: FontSet, width?: number): Promise { + if (!wasmReady) throw new KitError("renderer", "Renderer not initialised."); + await wasmReady; + const resvg = new Resvg(svg, { + font: { fontBuffers: fonts.buffers, defaultFontFamily: fonts.family, sansSerifFamily: fonts.family }, + fitTo: width ? { mode: "width", value: Math.round(width) } : { mode: "original" }, + shapeRendering: 2, + textRendering: 1, + imageRendering: 0, + }); + try { + const image = resvg.render(); + const result = { png: image.asPng(), width: image.width, height: image.height, pixels: image.pixels }; + image.free(); + return result; + } finally { + resvg.free(); + } +} + +export function escapeXml(text: string) { + return text.replace(/[<>&"']/g, (c) => ({ "<": "<", ">": ">", "&": "&", '"': """, "'": "'" })[c]!); +} + +/** 按宽度断行:英文按词,中文按字;超过 maxLines 时末行加省略号并标记 overflow。 */ +export function wrapLines(text: string, maxWidth: number, measure: (t: string) => number, maxLines = 99): { lines: string[]; overflow: boolean } { + const lines: string[] = []; + for (const paragraph of text.split(/\r?\n/)) { + const tokens = paragraph.match(/[A-Za-z0-9@._%+\-'’!?,;:)]+\s*|\s+|./gu) ?? [""]; + let line = ""; + for (const token of tokens) { + const next = line + token; + if (line && measure(next.trimEnd()) > maxWidth) { + lines.push(line.trimEnd()); + line = token.trimStart(); + // 中文标点不放行首。 + if (/^[,。、;:!?)」』”’,.;:!?)]/.test(line) && lines.length) { + lines[lines.length - 1] += line[0]; + line = line.slice(1); + } + } else line = next; + } + lines.push(line.trimEnd()); + // 避免最后一行只剩一个汉字。 + const n = lines.length; + if (n >= 2 && [...lines[n - 1]].length === 1 && /\p{Script=Han}/u.test(lines[n - 1]) && [...lines[n - 2]].length > 3) { + const prev = [...lines[n - 2]]; + const moved = prev.pop()!; + if (/\p{Script=Han}/u.test(moved)) { + lines[n - 2] = prev.join("").trimEnd(); + lines[n - 1] = moved + lines[n - 1]; + } + } + } + if (lines.length <= maxLines) return { lines, overflow: false }; + const kept = lines.slice(0, maxLines); + let last = kept[maxLines - 1]; + while (last && measure(`${last}…`) > maxWidth) last = last.slice(0, -1); + kept[maxLines - 1] = `${last}…`; + return { lines: kept, overflow: true }; +} + +/** 在框里放下文字的最大字号(不小于 minSize)。 */ +export function fitTextBlock(text: string, box: { width: number; height: number }, options: { size: number; minSize: number; lineHeight?: number; maxLines?: number }, measure: (t: string, size: number) => number) { + const lineHeight = options.lineHeight ?? 1.25; + for (let size = options.size; size >= options.minSize; size -= Math.max(1, Math.round(size * 0.04))) { + const { lines, overflow } = wrapLines(text, box.width, (t) => measure(t, size), options.maxLines); + if (!overflow && lines.length * size * lineHeight <= box.height) return { size, lines, overflow: false }; + } + const size = options.minSize; + const maxLines = Math.max(1, Math.min(options.maxLines ?? 99, Math.floor(box.height / (size * lineHeight)))); + const { lines } = wrapLines(text, box.width, (t) => measure(t, size), maxLines); + return { size, lines, overflow: true }; +} + +/** 生成多行 :x 为对齐基准点,y 为第一行顶部。 */ +export function textSvg(lines: string[], options: { x: number; y: number; size: number; color: string; family: string; weight?: number; anchor?: "start" | "middle" | "end"; lineHeight?: number; boldStroke?: boolean }) { + const lineHeight = options.lineHeight ?? 1.25; + const stroke = options.boldStroke ? ` stroke="${options.color}" stroke-width="${(options.size * 0.035).toFixed(2)}" stroke-linejoin="round"` : ""; + return lines + .map((line, i) => { + const baseline = options.y + options.size * (0.88 + i * lineHeight); + return `${escapeXml(line)}`; + }) + .join(""); +} diff --git a/ui-plugins/store-screenshot-studio/src/kit/server-kit.ts b/ui-plugins/store-screenshot-studio/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 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; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + 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/store-screenshot-studio/src/kit/workspace.ts b/ui-plugins/store-screenshot-studio/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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 { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + 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 { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + 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); +} diff --git a/ui-plugins/store-screenshot-studio/src/main.ts b/ui-plugins/store-screenshot-studio/src/main.ts new file mode 100644 index 00000000..f0702eff --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/main.ts @@ -0,0 +1,15 @@ +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, + fontPath: process.env.STORE_SHOTS_FONT, + log: (line) => process.stderr.write(`[store-screenshot-studio] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/store-screenshot-studio/src/server.ts b/ui-plugins/store-screenshot-studio/src/server.ts new file mode 100644 index 00000000..1b8549a3 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/server.ts @@ -0,0 +1,321 @@ +import { readFile, stat } from "node:fs/promises"; +import { basename, extname, join } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { decodeImage, encodeJpeg, encodePng, encodePngOpaque, fitWithin, parseColor, resize } from "./kit/raster.ts"; +import { initRenderer, loadFonts, renderSvg, type FontSet } from "./kit/render.ts"; +import { KitError, Workspace, safeFileName } from "./kit/workspace.ts"; +import { PRESETS, WARNING_TEXT, normalizeTheme, slideSvg, type Preset, type ScreenImage, type Slide, type Theme } from "./shots.ts"; + +export const NAME = "store-screenshot-studio"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const IMAGE_EXTS = [".png", ".jpg", ".jpeg"]; +const MAX_SLIDES = 10; + +export interface Project { + version: 1; + locales: string[]; + slides: Slide[]; + theme: Theme; + presets: string[]; + outputDir: string; +} + +export interface ServerOptions { + workspaceRoot: string; + assetRoot: string; + fontPath?: string; + log?: (line: string) => void; +} + +const LOCALE_RE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/; + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + 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 wasm = join(options.assetRoot, "resvg.wasm"); + let fontsPromise: Promise | undefined; + const fonts = async () => { + await initRenderer(wasm); + return (fontsPromise ??= loadFonts(options.fontPath).catch((error) => { + fontsPromise = undefined; + throw error; + })); + }; + + const screenCache = new Map(); + /** 截图转成 data URI;预览时缩小以加快渲染。 */ + async function screenOf(path: string, maxWidth?: number): Promise { + const info = await stat(ws.resolve(path)).catch(() => { + throw new KitError("not_found", `Screenshot not found: ${path}`); + }); + const key = `${path}|${info.mtimeMs}|${maxWidth ?? 0}`; + const hit = screenCache.get(key); + if (hit) return hit; + const bytes = await ws.read(path, 60 * 1024 * 1024); + const image = decodeImage(bytes, path); + let screen: ScreenImage; + if (maxWidth && image.width > maxWidth) { + const small = resize(image, maxWidth, Math.round((image.height * maxWidth) / image.width)); + screen = { href: `data:image/jpeg;base64,${encodeJpeg(small, 85).toString("base64")}`, width: small.width, height: small.height, sourceWidth: image.width }; + } else { + const isPng = bytes[0] === 0x89; + // EXIF 旋转过的 JPEG 重新编码,保证方向正确。 + const href = isPng ? `data:image/png;base64,${Buffer.from(bytes).toString("base64")}` : `data:image/png;base64,${encodePng(image).toString("base64")}`; + screen = { href, width: image.width, height: image.height, sourceWidth: image.width }; + } + screenCache.set(key, screen); + if (screenCache.size > 40) screenCache.delete(screenCache.keys().next().value!); + return screen; + } + + function normalizeProject(value: unknown): Project { + if (!value || typeof value !== "object") throw new KitError("bad_project", "Project must be an object."); + const p = value as Partial; + const locales = (Array.isArray(p.locales) ? p.locales : []).map(String).filter((l) => LOCALE_RE.test(l)); + if (!locales.length) locales.push("zh-Hans"); + const slides: Slide[] = (Array.isArray(p.slides) ? p.slides : []) + .map((s) => (typeof s === "string" ? { image: s, text: {} } : s)) + .filter((s): s is Slide => !!s && typeof s.image === "string") + .map((s) => { + ws.resolve(s.image); + if (s.tabletImage) ws.resolve(s.tabletImage); + const text: Slide["text"] = {}; + for (const [locale, t] of Object.entries(s.text && typeof s.text === "object" ? s.text : {})) { + if (!t || typeof t !== "object") continue; + text[locale] = { + ...(typeof t.title === "string" ? { title: t.title.slice(0, 160) } : {}), + ...(typeof t.subtitle === "string" ? { subtitle: t.subtitle.slice(0, 240) } : {}), + }; + } + return { + image: s.image, + ...(typeof s.tabletImage === "string" && s.tabletImage ? { tabletImage: s.tabletImage } : {}), + text, + ...(typeof s.background === "string" && s.background ? { background: s.background } : {}), + ...(typeof s.background2 === "string" && s.background2 ? { background2: s.background2 } : {}), + }; + }); + if (slides.length > MAX_SLIDES) throw new KitError("too_many_slides", `At most ${MAX_SLIDES} screenshots (the App Store limit).`); + const presets = (Array.isArray(p.presets) && p.presets.length ? p.presets.map(String) : ["ios-6.9", "ios-6.5", "play-phone"]).filter((id) => PRESETS.some((x) => x.id === id)); + if (!presets.length) throw new KitError("no_preset", `Choose at least one size: ${PRESETS.map((x) => x.id).join(", ")}`); + return { + version: 1, + locales: [...new Set(locales)], + slides, + theme: normalizeTheme(p.theme), + presets, + outputDir: typeof p.outputDir === "string" && p.outputDir.trim() ? p.outputDir.trim() : "store-screenshots", + }; + } + + async function loadProject(value: unknown): Promise<{ project: Project; path?: string }> { + if (typeof value === "string") { + let parsed: unknown; + try { + parsed = JSON.parse(await ws.readText(value)); + } catch (error) { + if (error instanceof KitError) throw error; + throw new KitError("bad_project", `${value} is not valid JSON.`); + } + return { project: normalizeProject(parsed), path: value }; + } + return { project: normalizeProject(value) }; + } + + const presetOf = (id: string): Preset => { + const preset = PRESETS.find((p) => p.id === id); + if (!preset) throw new KitError("bad_preset", `Unknown size "${id}". Available: ${PRESETS.map((p) => p.id).join(", ")}`); + return preset; + }; + + async function render(project: Project, index: number, preset: Preset, locale: string, width?: number) { + const slide = project.slides[index]; + if (!slide) throw new KitError("bad_index", `No screenshot #${index}.`); + const tablet = preset.device === "tablet"; + const path = tablet && slide.tabletImage ? slide.tabletImage : slide.image; + const screen = await screenOf(path, width ? Math.min(1400, Math.round(width * 1.2)) : undefined); + const f = await fonts(); + const { svg, warnings, background } = slideSvg({ preset, theme: project.theme, slide, locale, locales: project.locales, screen, fonts: f, usingPhoneOnTablet: tablet && !slide.tabletImage && screen.height / screen.width > 1.6 }); + const rendered = await renderSvg(svg, f, width && width < preset.width ? width : undefined); + return { rendered, warnings, background }; + } + + /** 不渲染,只检查文字长度、翻译和截图清晰度。 */ + async function check(project: Project) { + const problems: string[] = []; + for (const [index, slide] of project.slides.entries()) { + let screen: ScreenImage; + try { + screen = await screenOf(slide.image, 64); + } catch (error) { + problems.push(`#${index + 1} ${slide.image}: ${error instanceof Error ? error.message : error}`); + continue; + } + for (const preset of project.presets.map(presetOf)) { + for (const locale of project.locales) { + const { warnings } = slideSvg({ preset, theme: project.theme, slide, locale, locales: project.locales, screen: { ...screen, sourceWidth: screen.sourceWidth }, fonts: await fonts(), usingPhoneOnTablet: preset.device === "tablet" && !slide.tabletImage && screen.height / screen.width > 1.6 }); + for (const w of warnings) { + const line = `#${index + 1} ${slide.image} [${w === "missing_translation" || w.endsWith("too_long") ? locale : preset.id}]: ${WARNING_TEXT[w] ?? w}`; + if (!problems.includes(line)) problems.push(line); + } + } + } + } + return problems; + } + + const projectInput = z.union([z.string(), z.record(z.string(), z.unknown())]).describe("Project object, or the workspace path of a saved .storeshots.json project."); + + tool( + "shots_open", + { + description: + "Open Store Screenshot Studio: turn raw app screenshots (PNG/JPG in the workspace) into App Store / Google Play listing images with a headline, subheadline, device frame and background, in several languages and store sizes. Pass `paths` or `folder` (sorted by name) plus optional `locales` and per-slide `texts`, or a saved `project` (.storeshots.json). Opens the side panel.", + input: { + paths: z.array(z.string()).max(MAX_SLIDES).optional().describe("Screenshot paths in slide order."), + folder: z.string().optional().describe("Folder of screenshots (sorted by file name)."), + locales: z.array(z.string()).optional().describe('Listing languages, e.g. ["zh-Hans", "en-US"]. The first one is the fallback.'), + texts: z + .array(z.record(z.string(), z.object({ title: z.string().optional(), subtitle: z.string().optional() }))) + .optional() + .describe('Per slide: {"": {title, subtitle}}. Keep titles short (2–6 words / ≤ 12 Chinese characters).'), + presets: z.array(z.string()).optional().describe(`Sizes. Built-in: ${PRESETS.map((p) => p.id).join(", ")}.`), + theme: z.record(z.string(), z.unknown()).optional().describe('{background, background2?, textColor:"auto"|#hex, frame:"auto"|"iphone"|"android"|"none", frameColor, textPosition:"top"|"bottom", deviceScale 0.5–0.95, bleed, titleScale}'), + project: z.string().optional().describe("Workspace path of a saved .storeshots.json project."), + }, + openPanel: true, + readOnly: true, + timeoutMs: 300_000, + }, + async ({ paths, folder, locales, texts, presets, theme, project: projectPath }) => { + let loaded: { project: Project; path?: string }; + if (projectPath) loaded = await loadProject(projectPath); + else { + const list = [...(paths ?? [])]; + if (folder) list.push(...(await ws.list({ dir: folder, exts: IMAGE_EXTS, recursive: false, limit: 200 })).map((f) => f.path).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))); + if (!list.length) throw new KitError("missing_input", "Pass screenshot `paths`, a `folder`, or a saved `project`."); + if (list.length > MAX_SLIDES) throw new KitError("too_many_slides", `${list.length} screenshots given; the App Store allows at most ${MAX_SLIDES}. Pick the best ones.`); + loaded = { project: normalizeProject({ slides: [...new Set(list)].map((image, i) => ({ image, text: texts?.[i] ?? {} })), locales, presets, theme }) }; + } + const { project } = loaded; + const problems = await check(project); + const play = project.presets.some((id) => presetOf(id).store === "google-play") && project.slides.length > 8; + const lines = [ + `${project.slides.length} screenshot(s), languages ${project.locales.join(", ")}, sizes ${project.presets.join(", ")} → ${project.outputDir}///`, + ...(project.slides.some((s) => !Object.keys(s.text).length) ? ["Some slides have no headline yet — write short marketing headlines per language (texts) based on what each screenshot shows, then confirm with the user."] : []), + ...(play ? ["Google Play shows at most 8 phone screenshots; only the first 8 will be used there."] : []), + ...(problems.length ? ["Check:", ...problems.slice(0, 40).map((p) => `- ${p}`)] : ["No layout problems found."]), + "Next: let the user review in the panel, then call shots_export.", + ]; + return { text: lines.join("\n"), structured: { kind: "project", project, projectPath: loaded.path, presets: PRESETS, problems } }; + }, + ); + + tool( + "shots_preview", + { + description: "Render one listing image for the panel preview (PNG, base64).", + input: { project: projectInput, index: z.number().int().min(0), preset: z.string().optional(), locale: z.string().optional(), width: z.number().int().min(64).max(1400).optional() }, + visibility: ["app"], + readOnly: true, + }, + async ({ project: value, index, preset: presetId, locale, width }) => { + const { project } = await loadProject(value); + const preset = presetOf(presetId ?? project.presets[0]); + const { rendered, warnings } = await render(project, index, preset, locale ?? project.locales[0], width ?? 360); + return { text: `#${index + 1} ${preset.id}`, structured: { image: Buffer.from(rendered.png).toString("base64"), mime: "image/png", warnings: warnings.map((w) => WARNING_TEXT[w] ?? w), codes: warnings } }; + }, + ); + + tool( + "project_save", + { + description: + 'Save as a .storeshots.json project. Shape: {locales:[...], slides:[{image, tabletImage?, text:{:{title?, subtitle?}}, background?, background2?}], theme:{background, background2?, textColor, frame, frameColor, textPosition, deviceScale, bleed, titleScale}, presets:[ids], outputDir}.', + input: { path: z.string(), project: z.record(z.string(), z.unknown()) }, + }, + async ({ path, project: value }) => { + const project = normalizeProject(value); + const target = /\.json$/i.test(path) ? path : `${path}.storeshots.json`; + const written = await ws.write(target, JSON.stringify(project, null, 2) + "\n"); + return { text: `Saved ${written}.`, structured: { kind: "saved", path: written, project } }; + }, + ); + + tool( + "shots_export", + { + description: + "Export listing images: ///-.png (opaque PNG, exact store pixel size). Optional filters: `locales`, `presets`, `indices` (0-based slides).", + input: { project: projectInput, locales: z.array(z.string()).optional(), presets: z.array(z.string()).optional(), indices: z.array(z.number().int().min(0)).optional() }, + timeoutMs: 900_000, + }, + async ({ project: value, locales, presets, indices }) => { + const { project } = await loadProject(value); + const files: string[] = []; + const problems: string[] = []; + const out = project.outputDir.replace(/\/+$/, ""); + for (const locale of locales?.length ? locales : project.locales) { + if (!LOCALE_RE.test(locale)) throw new KitError("bad_locale", `Invalid language code "${locale}".`); + for (const presetId of presets?.length ? presets : project.presets) { + const preset = presetOf(presetId); + for (const [index, slide] of project.slides.entries()) { + if (indices && !indices.includes(index)) continue; + if (preset.store === "google-play" && index >= 8) continue; + const { rendered, warnings, background } = await render(project, index, preset, locale); + for (const w of warnings) problems.push(`${locale}/${preset.id} #${index + 1}: ${WARNING_TEXT[w] ?? w}`); + const stem = safeFileName(basename(slide.image, extname(slide.image)), "screen"); + const png = encodePngOpaque({ width: rendered.width, height: rendered.height, data: rendered.pixels }, parseColor(background)); + files.push(await ws.write(`${out}/${safeFileName(locale)}/${preset.id}/${String(index + 1).padStart(2, "0")}-${stem}.png`, png)); + } + } + } + const unique = [...new Set(problems)]; + return { + text: [`Wrote ${files.length} image(s) to ${out}/.`, ...(unique.length ? ["Check:", ...unique.slice(0, 60).map((p) => `- ${p}`)] : [])].join("\n"), + structured: { kind: "exported", files, problems: unique, outputDir: out }, + }; + }, + ); + + tool( + "screen_thumbs", + { + description: "Small thumbnails of raw screenshots for the panel.", + input: { paths: z.array(z.string()).max(60) }, + visibility: ["app"], + readOnly: true, + }, + async ({ paths }) => { + const thumbs: Record = {}; + for (const path of paths) { + try { + thumbs[path] = encodeJpeg(fitWithin(decodeImage(await ws.read(path, 60 * 1024 * 1024), path), 200), 75).toString("base64"); + } catch { + // 无法解码的图片显示占位 + } + } + return { text: `${Object.keys(thumbs).length} thumbnail(s)`, structured: { thumbs } }; + }, + ); + + tool( + "workspace_images", + { description: "List PNG/JPG files in the workspace for the panel picker.", input: {}, visibility: ["app"], readOnly: true }, + async () => { + const files = await ws.list({ exts: IMAGE_EXTS, limit: 1000 }); + return { text: `${files.length} image(s)`, structured: { files: files.map((f) => f.path).filter((p) => !p.startsWith("store-screenshots/")) } }; + }, + ); + + return server; +} diff --git a/ui-plugins/store-screenshot-studio/src/shots.ts b/ui-plugins/store-screenshot-studio/src/shots.ts new file mode 100644 index 00000000..fd669687 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/src/shots.ts @@ -0,0 +1,198 @@ +import { mix, readableOn } from "./kit/color.ts"; +import { parseColor } from "./kit/raster.ts"; +import { escapeXml, fitTextBlock, textSvg, type FontSet } from "./kit/render.ts"; + +export type Frame = "auto" | "iphone" | "android" | "none"; + +export interface Preset { + id: string; + label: string; + width: number; + height: number; + device: "phone" | "tablet"; + store: "app-store" | "google-play"; +} + +export const PRESETS: Preset[] = [ + { id: "ios-6.9", label: "iPhone 6.9″ 1320×2868", width: 1320, height: 2868, device: "phone", store: "app-store" }, + { id: "ios-6.5", label: "iPhone 6.5″ 1284×2778", width: 1284, height: 2778, device: "phone", store: "app-store" }, + { id: "ios-5.5", label: "iPhone 5.5″ 1242×2208", width: 1242, height: 2208, device: "phone", store: "app-store" }, + { id: "ipad-13", label: "iPad 13″ 2064×2752", width: 2064, height: 2752, device: "tablet", store: "app-store" }, + { id: "play-phone", label: "Google Play phone 1080×1920", width: 1080, height: 1920, device: "phone", store: "google-play" }, + { id: "play-tablet", label: "Google Play 10″ tablet 1600×2560", width: 1600, height: 2560, device: "tablet", store: "google-play" }, +]; + +export interface Theme { + background: string; + /** 设置后为上下渐变。 */ + background2?: string; + textColor: string; + frame: Frame; + frameColor: string; + textPosition: "top" | "bottom"; + deviceScale: number; + /** 设备超出画布底部(或顶部),更有冲击力。 */ + bleed: boolean; + titleScale: number; +} + +export const DEFAULT_THEME: Theme = { + background: "#eef2ff", + background2: "#c7d2fe", + textColor: "auto", + frame: "auto", + frameColor: "#111111", + textPosition: "top", + deviceScale: 0.78, + bleed: false, + titleScale: 1, +}; + +export interface SlideText { + title?: string; + subtitle?: string; +} + +export interface Slide { + image: string; + /** 平板尺寸使用的截图(可选)。 */ + tabletImage?: string; + text: Record; + background?: string; + background2?: string; +} + +export interface ScreenImage { + href: string; + width: number; + height: number; + /** 原始截图像素宽度(判断清晰度)。 */ + sourceWidth: number; +} + +const isHex = (v: unknown): v is string => typeof v === "string" && /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v.trim()); +const hex = (v: string) => (v.startsWith("#") ? v : `#${v}`).toLowerCase(); + +export function normalizeTheme(value: Partial | undefined): Theme { + const t = { ...DEFAULT_THEME }; + if (!value) return t; + if (isHex(value.background)) t.background = hex(value.background); + if (value.background2 === "" || value.background2 === null) t.background2 = undefined; + else if (isHex(value.background2)) t.background2 = hex(value.background2); + if (isHex(value.textColor)) t.textColor = hex(value.textColor); + if (isHex(value.frameColor)) t.frameColor = hex(value.frameColor); + if (value.frame && ["auto", "iphone", "android", "none"].includes(value.frame)) t.frame = value.frame; + if (value.textPosition === "bottom") t.textPosition = "bottom"; + if (typeof value.deviceScale === "number") t.deviceScale = Math.min(0.95, Math.max(0.5, value.deviceScale)); + if (typeof value.bleed === "boolean") t.bleed = value.bleed; + if (typeof value.titleScale === "number") t.titleScale = Math.min(1.6, Math.max(0.6, value.titleScale)); + return t; +} + +/** 生成一张商店截图的 SVG。 */ +export function slideSvg(options: { preset: Preset; theme: Theme; slide: Slide; locale: string; locales: string[]; screen: ScreenImage; fonts: FontSet; usingPhoneOnTablet?: boolean }) { + const { preset, slide, screen, fonts } = options; + const theme = { ...options.theme, ...(isHex(slide.background) ? { background: slide.background, background2: isHex(slide.background2) ? slide.background2 : undefined } : {}) }; + const W = preset.width; + const H = preset.height; + const warnings: string[] = []; + const text = slide.text[options.locale] ?? {}; + const fallback = slide.text[options.locales[0]] ?? {}; + if (!text.title && !text.subtitle && (fallback.title || fallback.subtitle)) warnings.push("missing_translation"); + const title = (text.title ?? (text.subtitle ? "" : fallback.title) ?? "").trim(); + const subtitle = (text.subtitle ?? (text.title ? "" : fallback.subtitle) ?? "").trim(); + const bgA = parseColor(theme.background); + const bgB = theme.background2 ? parseColor(theme.background2) : bgA; + const ink = theme.textColor === "auto" ? readableOn(mix(bgA, bgB, theme.textPosition === "top" ? 0.15 : 0.85)) : theme.textColor; + const parts: string[] = []; + parts.push( + theme.background2 + ? `` + : ``, + ); + + // 文字区。 + const unit = Math.min(W, H * 0.62); + const margin = H * 0.05; + const textW = W * 0.86; + const titleBox = { width: textW, height: H * 0.11 }; + const titleFit = title + ? fitTextBlock(title, titleBox, { size: Math.round(unit * 0.085 * theme.titleScale), minSize: Math.round(unit * 0.045), maxLines: 2, lineHeight: 1.2 }, (t, s) => fonts.measure(t, s, true)) + : undefined; + const subFit = subtitle + ? fitTextBlock(subtitle, { width: textW, height: H * 0.07 }, { size: Math.round(unit * 0.05 * theme.titleScale), minSize: Math.round(unit * 0.032), maxLines: 2, lineHeight: 1.3 }, (t, s) => fonts.measure(t, s)) + : undefined; + if (titleFit?.overflow) warnings.push("title_too_long"); + if (subFit?.overflow) warnings.push("subtitle_too_long"); + const titleH = titleFit ? titleFit.lines.length * titleFit.size * 1.2 : 0; + const gap = titleFit && subFit ? unit * 0.025 : 0; + const subH = subFit ? subFit.lines.length * subFit.size * 1.3 : 0; + const textH = titleH + gap + subH; + const textTop = theme.textPosition === "top" ? margin + Math.max(0, (H * 0.16 - textH) / 2) : H - margin - textH - Math.max(0, (H * 0.16 - textH) / 2); + + // 设备区。 + const tablet = preset.device === "tablet"; + const frame: Exclude = theme.frame === "auto" ? "iphone" : theme.frame; + const aspect = screen.height / screen.width; + const areaTop = theme.textPosition === "top" ? margin + Math.max(textH, H * 0.16) + H * 0.035 : (theme.bleed ? 0 : margin); + const areaBottom = theme.textPosition === "top" ? (theme.bleed ? H : H - margin) : H - margin - Math.max(textH, H * 0.16) - H * 0.035; + const bezelK = frame === "none" ? 0 : tablet ? 0.03 : 0.035; + let screenW = (W * theme.deviceScale) / (1 + bezelK * 2); + let screenH = screenW * aspect; + const outerH = (h: number, w: number) => h + w * bezelK * 2; + if (!theme.bleed && outerH(screenH, screenW) > areaBottom - areaTop) { + screenW = (areaBottom - areaTop) / (aspect + bezelK * 2); + screenH = screenW * aspect; + } + const bezel = screenW * bezelK; + const deviceW = screenW + bezel * 2; + const deviceH = screenH + bezel * 2; + const dx = (W - deviceW) / 2; + const dy = theme.textPosition === "top" ? areaTop : theme.bleed ? areaBottom - deviceH : areaTop + (areaBottom - areaTop - deviceH) / 2; + const sx = dx + bezel; + const sy = dy + bezel; + const screenR = frame === "none" ? screenW * 0.045 : tablet ? screenW * 0.035 : frame === "android" ? screenW * 0.075 : screenW * 0.115; + const outerR = screenR + bezel; + if (screen.sourceWidth < screenW * 0.6) warnings.push("low_resolution"); + if (options.usingPhoneOnTablet) warnings.push("phone_screenshot_on_tablet"); + + const shadowBlur = deviceW * 0.03; + parts.push( + `` + + ``, + ); + if (frame !== "none") { + parts.push(``); + // 边框高光,让深色机身在深色背景上也能看清轮廓。 + const edge = readableOn(theme.frameColor) === "#ffffff" ? "#ffffff" : "#000000"; + parts.push(``); + } else { + parts.push(``); + } + parts.push(``); + if (frame === "iphone" && !tablet) { + const iw = screenW * 0.3; + const ih = screenW * 0.088; + parts.push(``); + } else if (frame === "android" && !tablet) { + const r = screenW * 0.022; + parts.push(``); + } + + // 文字放在最上层(设备出血时不被遮住)。 + if (titleFit) parts.push(textSvg(titleFit.lines, { x: W / 2, y: textTop, size: titleFit.size, color: ink, family: fonts.boldFamily ?? fonts.family, weight: 700, anchor: "middle", lineHeight: 1.2, boldStroke: !fonts.boldFamily })); + if (subFit) parts.push(textSvg(subFit.lines, { x: W / 2, y: textTop + titleH + gap, size: subFit.size, color: ink, family: fonts.family, anchor: "middle", lineHeight: 1.3 })); + + const svg = `${parts.join("")}`; + return { svg, warnings, background: theme.background }; +} + +export const WARNING_TEXT: Record = { + missing_translation: "no text for this language — the first language's text is used", + title_too_long: "headline is too long and was shortened", + subtitle_too_long: "subheadline is too long and was shortened", + low_resolution: "screenshot resolution is low for this size — it will look blurry", + phone_screenshot_on_tablet: "tablet size uses a phone screenshot — add a tablet screenshot (tabletImage) for iPad / tablet listings", +}; + +export const xml = escapeXml; diff --git a/ui-plugins/store-screenshot-studio/test/fixtures/01-menu.png b/ui-plugins/store-screenshot-studio/test/fixtures/01-menu.png new file mode 100644 index 00000000..6795e893 Binary files /dev/null and b/ui-plugins/store-screenshot-studio/test/fixtures/01-menu.png differ diff --git a/ui-plugins/store-screenshot-studio/test/fixtures/02-orders.png b/ui-plugins/store-screenshot-studio/test/fixtures/02-orders.png new file mode 100644 index 00000000..6ef2c0b7 Binary files /dev/null and b/ui-plugins/store-screenshot-studio/test/fixtures/02-orders.png differ diff --git a/ui-plugins/store-screenshot-studio/test/fixtures/03-lowres.png b/ui-plugins/store-screenshot-studio/test/fixtures/03-lowres.png new file mode 100644 index 00000000..35f9b0ce Binary files /dev/null and b/ui-plugins/store-screenshot-studio/test/fixtures/03-lowres.png differ diff --git a/ui-plugins/store-screenshot-studio/test/fixtures/SOURCES.md b/ui-plugins/store-screenshot-studio/test/fixtures/SOURCES.md new file mode 100644 index 00000000..e762bca8 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/test/fixtures/SOURCES.md @@ -0,0 +1 @@ +Screens in this folder are synthetic mock-ups drawn for these tests (fictional app) and are released under the plugin's MIT license. diff --git a/ui-plugins/store-screenshot-studio/test/fixtures/ipad-menu.png b/ui-plugins/store-screenshot-studio/test/fixtures/ipad-menu.png new file mode 100644 index 00000000..e1b24829 Binary files /dev/null and b/ui-plugins/store-screenshot-studio/test/fixtures/ipad-menu.png differ diff --git a/ui-plugins/store-screenshot-studio/test/tools.test.ts b/ui-plugins/store-screenshot-studio/test/tools.test.ts new file mode 100644 index 00000000..654df9ab --- /dev/null +++ b/ui-plugins/store-screenshot-studio/test/tools.test.ts @@ -0,0 +1,104 @@ +import { mkdtemp, readFile, mkdir, copyFile, readdir } from "node:fs/promises"; +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 { PNG } from "pngjs"; +import { beforeAll, describe, expect, it } from "vitest"; +import { createServer } from "../src/server.ts"; + +let workspace: string; +let client: Client; +const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; +const pixel = (png: PNG, x: number, y: number) => { + const i = (Math.round(y) * png.width + Math.round(x)) * 4; + return [png.data[i], png.data[i + 1], png.data[i + 2]]; +}; +const near = (a: number[], b: number[], tol = 14) => a.every((v, i) => Math.abs(v - b[i]) <= tol); + +beforeAll(async () => { + workspace = await mkdtemp(join(tmpdir(), "storeshots-")); + await mkdir(join(workspace, "screens")); + for (const f of ["01-menu.png", "02-orders.png", "03-lowres.png", "ipad-menu.png"]) await copyFile(join(import.meta.dirname, "fixtures", f), join(workspace, "screens", f)); + const server = createServer({ workspaceRoot: workspace, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + client = new Client({ name: "test", version: "1" }); + await Promise.all([server.connect(a), client.connect(b)]); +}); + +const texts = [ + { "zh-Hans": { title: "一键点单", subtitle: "常喝的咖啡,三秒下单" }, "en-US": { title: "Order in one tap", subtitle: "Your usual coffee in three seconds" } }, + { "zh-Hans": { title: "订单实时追踪" }, "en-US": { title: "Track every order live" } }, + { "zh-Hans": { title: "会员积分随时查看,积分可以兑换咖啡、甜点和周边,每月还有专属优惠券和生日礼遇等你来领" } }, +]; + +describe("store-screenshot-studio", () => { + it("opens screenshots with texts and flags long titles, missing translations and low resolution", async () => { + const result = await call("shots_open", { paths: ["screens/01-menu.png", "screens/02-orders.png", "screens/03-lowres.png"], locales: ["zh-Hans", "en-US"], texts, presets: ["ios-6.9", "play-phone"] }); + expect(result.isError).toBeFalsy(); + const problems: string[] = result.structuredContent.problems; + expect(problems.some((p) => p.startsWith("#3") && p.includes("[en-US]") && p.includes("no text for this language"))).toBe(true); + expect(problems.some((p) => p.startsWith("#3") && p.includes("[zh-Hans]") && p.includes("headline is too long"))).toBe(true); + expect(problems.some((p) => p.startsWith("#3") && p.includes("blurry"))).toBe(true); + expect(problems.some((p) => p.startsWith("#1"))).toBe(false); + }); + + it("exports exact store sizes as opaque PNGs per language and size", async () => { + const opened = await call("shots_open", { paths: ["screens/01-menu.png", "screens/02-orders.png"], locales: ["zh-Hans", "en-US"], texts, presets: ["ios-6.9", "ios-6.5", "play-phone"], theme: { background: "#1f7a4d", background2: "", frame: "iphone" } }); + const exported = await call("shots_export", { project: opened.structuredContent.project }); + expect(exported.isError).toBeFalsy(); + const files: string[] = exported.structuredContent.files; + expect(files.length).toBe(2 * 3 * 2); + expect(files).toContain("store-screenshots/zh-Hans/ios-6.9/01-01-menu.png"); + expect(files).toContain("store-screenshots/en-US/play-phone/02-02-orders.png"); + const sizes: Record = { "ios-6.9": [1320, 2868], "ios-6.5": [1284, 2778], "play-phone": [1080, 1920] }; + for (const [id, [w, hgt]] of Object.entries(sizes)) { + const buf = await readFile(join(workspace, `store-screenshots/en-US/${id}/01-01-menu.png`)); + expect(buf[25]).toBe(2); // PNG colour type 2 = RGB,没有 alpha + const png = PNG.sync.read(buf); + expect([png.width, png.height]).toEqual([w, hgt]); + expect(near(pixel(png, 10, 10), [0x1f, 0x7a, 0x4d])).toBe(true); + } + // 中文标题区域有白色文字。 + const zh = PNG.sync.read(await readFile(join(workspace, "store-screenshots/zh-Hans/ios-6.9/01-01-menu.png"))); + let white = 0; + for (let x = 200; x < 1120; x += 2) for (let y = 120; y < 420; y += 2) if (near(pixel(zh, x, y), [255, 255, 255], 30)) white++; + expect(white).toBeGreaterThan(800); + // 截图内容出现在设备屏幕里(绿色标题栏)。 + let green = 0; + for (let y = 600; y < 1400; y += 4) if (near(pixel(zh, 660, y), [31, 122, 77], 20)) green++; + expect(green).toBeGreaterThan(5); + }); + + it("uses the tablet screenshot for iPad sizes and warns when only a phone screenshot is given", async () => { + const base = { locales: ["en-US"], presets: ["ipad-13"], slides: [{ image: "screens/01-menu.png", text: { "en-US": { title: "Menu" } } }] }; + const phoneOnly = await call("shots_open", { paths: ["screens/01-menu.png"], presets: ["ipad-13"], locales: ["en-US"] }); + expect(phoneOnly.structuredContent.problems.join("\n")).toContain("tablet size uses a phone screenshot"); + const withTablet = { ...base, slides: [{ ...base.slides[0], tabletImage: "screens/ipad-menu.png" }] }; + const preview = await call("shots_preview", { project: withTablet, index: 0, width: 516 }); + expect(preview.structuredContent.codes).toEqual([]); + const png = PNG.sync.read(Buffer.from(preview.structuredContent.image, "base64")); + expect(png.width).toBe(516); + expect(png.height).toBe(688); + }); + + it("saves, reloads, filters the export and rejects outside paths and >10 slides", async () => { + const opened = await call("shots_open", { folder: "screens", locales: ["en-US"], presets: ["play-phone"] }); + const project = opened.structuredContent.project; + expect(project.slides.map((s: any) => s.image)).toEqual(["screens/01-menu.png", "screens/02-orders.png", "screens/03-lowres.png", "screens/ipad-menu.png"]); + project.theme.textPosition = "bottom"; + project.theme.bleed = true; + project.slides[0].text["en-US"] = { title: "Hello" }; + const saved = await call("project_save", { path: "listing", project }); + expect(saved.structuredContent.path).toBe("listing.storeshots.json"); + const reopened = await call("shots_open", { project: "listing.storeshots.json" }); + expect(reopened.structuredContent.project.theme.textPosition).toBe("bottom"); + const only = await call("shots_export", { project: "listing.storeshots.json", indices: [0], outputDir: "x" }); + expect(only.structuredContent.files).toEqual(["store-screenshots/en-US/play-phone/01-01-menu.png"]); + const bad = await call("shots_open", { paths: ["../secret.png"] }); + expect(bad.structuredContent.error.code).toBe("outside_workspace"); + const many = await call("shots_open", { paths: Array.from({ length: 11 }, () => "screens/01-menu.png").map((p, i) => `${p}?${i}`) }); + expect(many.isError).toBe(true); + expect((await readdir(join(workspace, "store-screenshots/en-US/play-phone"))).length).toBeGreaterThan(0); + }); +}); diff --git a/ui-plugins/store-screenshot-studio/test/workspace-links.test.ts b/ui-plugins/store-screenshot-studio/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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" }); + }); +}); diff --git a/ui-plugins/store-screenshot-studio/tsconfig.json b/ui-plugins/store-screenshot-studio/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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/store-screenshot-studio/ui/env.d.ts b/ui-plugins/store-screenshot-studio/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/store-screenshot-studio/ui/kit.css b/ui-plugins/store-screenshot-studio/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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/store-screenshot-studio/ui/kit.ts b/ui-plugins/store-screenshot-studio/ui/kit.ts new file mode 100644 index 00000000..fe0bce0d --- /dev/null +++ b/ui-plugins/store-screenshot-studio/ui/kit.ts @@ -0,0 +1,128 @@ +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 | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | 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 | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | 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>(name: string, args: Record = {}, timeout = 300_000): Promise { + 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 | 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 { + 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( + tag: K, + props: Record = {}, + ...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 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"; +} diff --git a/ui-plugins/store-screenshot-studio/ui/main.ts b/ui-plugins/store-screenshot-studio/ui/main.ts new file mode 100644 index 00000000..49324ecc --- /dev/null +++ b/ui-plugins/store-screenshot-studio/ui/main.ts @@ -0,0 +1,264 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, sendMessage, toast } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface Theme { background: string; background2?: string; textColor: string; frame: "auto" | "iphone" | "android" | "none"; frameColor: string; textPosition: "top" | "bottom"; deviceScale: number; bleed: boolean; titleScale: number } +interface Slide { image: string; tabletImage?: string; text: Record; background?: string; background2?: string } +interface Project { version: 1; locales: string[]; slides: Slide[]; theme: Theme; presets: string[]; outputDir: string } +interface Preset { id: string; label: string; width: number; height: number; device: string; store: string } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); + +const state: { + project?: Project; + projectPath: string; + presets: Preset[]; + previews: Map; + selected: number; + locale: string; + preset: string; + images: string[]; + result?: { files: string[]; problems: string[]; outputDir: string }; +} = { projectPath: "listing.storeshots.json", presets: [], previews: new Map(), selected: 0, locale: "", preset: "", images: [] }; + +const root = document.getElementById("root")!; + +async function busy(work: () => Promise): Promise { + root.classList.add("busy"); + try { + return await work(); + } catch (error) { + toast(error instanceof Error ? error.message : String(error), "error"); + return undefined; + } finally { + root.classList.remove("busy"); + } +} + +function load(value: Record) { + state.project = value.project as Project; + state.presets = (value.presets as Preset[]) ?? state.presets; + if (typeof value.projectPath === "string") state.projectPath = value.projectPath; + if (!state.project.locales.includes(state.locale)) state.locale = state.project.locales[0]; + if (!state.project.presets.includes(state.preset)) state.preset = state.project.presets[0]; + state.selected = Math.min(state.selected, Math.max(0, state.project.slides.length - 1)); + state.previews.clear(); + state.result = undefined; + render(); + void refreshAll(); +} + +let generation = 0; +async function refreshAll() { + const token = ++generation; + const count = state.project?.slides.length ?? 0; + for (let i = 0; i < count; i++) { + if (token !== generation) return; + await refreshOne(i); + } + if (token === generation) await refreshOne(state.selected, true); +} + +async function refreshOne(index: number, large = false) { + const project = state.project; + if (!project?.slides[index]) return; + try { + const result = await call<{ image: string; mime: string; warnings: string[] }>("shots_preview", { project, index, preset: state.preset, locale: state.locale, width: large ? 600 : 300 }); + const src = `data:${result.mime};base64,${result.image}`; + if (large) { + const img = document.getElementById("large") as HTMLImageElement | null; + if (img) img.src = src; + const box = document.getElementById("warnings"); + box?.replaceChildren(...(result.warnings.length ? result.warnings.map((w) => h("div", { class: "badge bad" }, w)) : [h("span", { class: "badge ok" }, T("没问题", "Looks good"))])); + } else { + state.previews.set(index, { src, warnings: result.warnings }); + document.querySelector(`.thumb[data-index="${index}"]`)?.replaceWith(thumb(index)); + } + } catch (error) { + if (large) toast(error instanceof Error ? error.message : String(error), "error"); + } +} + +let debounce: ReturnType | undefined; +function changed(scope: "all" | "one") { + clearTimeout(debounce); + debounce = setTimeout(() => { + if (scope === "all") void refreshAll(); + else { + void refreshOne(state.selected); + void refreshOne(state.selected, true); + } + }, 350); +} + +function render() { + applyTheme(); + root.replaceChildren(state.project ? editor() : picker()); +} + +async function loadImages() { + if (state.images.length) return; + const result = await call<{ files: string[] }>("workspace_images").catch(() => ({ files: [] as string[] })); + state.images = result.files; + if (result.files.length) render(); +} + +function picker() { + void loadImages(); + const chosen: string[] = []; + return h("div", {}, + h("h1", {}, T("应用商店截图制作", "Store Screenshot Studio")), + h("p", { class: "muted" }, T("把 App 原始截图做成 App Store / Google Play 的宣传图:加标题、设备边框和背景,多语言、多尺寸一键导出。", "Turn raw app screenshots into App Store / Google Play listing images with headlines, device frames and backgrounds — many languages and sizes at once.")), + h("div", { class: "card" }, + h("div", { class: "pick-list" }, ...(state.images.length + ? state.images.map((file) => h("label", {}, h("input", { type: "checkbox", onchange: (e: Event) => { const on = (e.target as HTMLInputElement).checked; if (on) chosen.push(file); else chosen.splice(chosen.indexOf(file), 1); } }), file)) + : [h("div", { class: "empty" }, T("工作区里还没有截图(PNG/JPG)", "No PNG/JPG screenshots in the workspace yet"))])), + h("div", { class: "row" }, h("span", { class: "muted small" }, T("按勾选顺序排列", "Slides follow the order you tick")), h("button", { class: "primary", onclick: () => chosen.length && open({ paths: chosen }) }, T("开始制作", "Start"))), + ), + ); +} + +async function open(args: Record) { + const result = await busy(() => call>("shots_open", args, 300_000)); + if (result) load(result); +} + +function slider(label: string, value: number, min: number, max: number, step: number, format: (v: number) => string, onInput: (v: number) => void) { + const out = h("span", { class: "value" }, format(value)); + return h("label", { class: "slider" }, h("span", {}, label), + h("input", { type: "range", min, max, step, value, oninput: (e: Event) => { const v = Number((e.target as HTMLInputElement).value); out.textContent = format(v); onInput(v); } }), out); +} + +function themeControls(theme: Theme) { + const set = (patch: Partial) => { Object.assign(theme, patch); changed("all"); }; + return h("div", { class: "controls" }, + h("label", {}, h("input", { type: "color", value: theme.background, oninput: (e: Event) => set({ background: (e.target as HTMLInputElement).value }) }), T("背景", "Background"), + h("input", { type: "checkbox", checked: !!theme.background2, onchange: (e: Event) => { set({ background2: (e.target as HTMLInputElement).checked ? theme.background : undefined }); render(); } }), T("渐变", "Gradient"), + theme.background2 ? h("input", { type: "color", value: theme.background2, oninput: (e: Event) => set({ background2: (e.target as HTMLInputElement).value }) }) : null), + h("label", {}, h("input", { type: "checkbox", checked: theme.textColor === "auto", onchange: (e: Event) => { set({ textColor: (e.target as HTMLInputElement).checked ? "auto" : "#111827" }); render(); } }), T("文字颜色自动", "Auto text colour"), + theme.textColor !== "auto" ? h("input", { type: "color", value: theme.textColor, oninput: (e: Event) => set({ textColor: (e.target as HTMLInputElement).value }) }) : null), + h("label", {}, T("设备边框", "Device frame"), h("select", { onchange: (e: Event) => set({ frame: (e.target as HTMLSelectElement).value as Theme["frame"] }) }, + ...([["auto", T("自动(iPhone)", "Auto (iPhone)")], ["iphone", "iPhone"], ["android", "Android"], ["none", T("无边框", "None")]] as const).map(([v, l]) => h("option", { value: v, selected: theme.frame === v }, l)))), + h("label", {}, h("input", { type: "color", value: theme.frameColor, oninput: (e: Event) => set({ frameColor: (e.target as HTMLInputElement).value }) }), T("机身颜色", "Frame colour")), + h("label", {}, T("文字位置", "Text"), h("select", { onchange: (e: Event) => set({ textPosition: (e.target as HTMLSelectElement).value as Theme["textPosition"] }) }, + h("option", { value: "top", selected: theme.textPosition === "top" }, T("上方", "Top")), h("option", { value: "bottom", selected: theme.textPosition === "bottom" }, T("下方", "Bottom")))), + slider(T("设备大小", "Device size"), theme.deviceScale, 0.5, 0.95, 0.01, (v) => `${Math.round(v * 100)}%`, (v) => set({ deviceScale: v })), + slider(T("标题大小", "Title size"), theme.titleScale, 0.6, 1.6, 0.05, (v) => `${Math.round(v * 100)}%`, (v) => set({ titleScale: v })), + h("label", {}, h("input", { type: "checkbox", checked: theme.bleed, onchange: (e: Event) => set({ bleed: (e.target as HTMLInputElement).checked }) }), T("设备超出画面边缘", "Let the device bleed off the edge")), + ); +} + +function thumb(index: number) { + const preview = state.previews.get(index); + const slide = state.project!.slides[index]; + const card = h("div", { class: `thumb ${index === state.selected ? "selected" : ""} ${preview?.warnings.length ? "warn" : ""}`, onclick: () => { state.selected = index; render(); void refreshOne(index, true); } }, + preview ? h("img", { src: preview.src, alt: slide.image }) : h("div", { class: "placeholder" }, "…"), + h("div", { class: "cap" }, `${index + 1}. ${slide.image.split("/").pop()}`), + preview?.warnings.length ? h("span", { class: "flag", title: preview.warnings.join("\n") }, "!") : null, + ); + card.dataset.index = String(index); + return card; +} + +function editor() { + const project = state.project!; + void loadImages(); + const slide = project.slides[state.selected]; + const text = slide ? (slide.text[state.locale] ??= {}) : undefined; + const newLocale = h("input", { type: "text", size: 7, placeholder: "en-US" }); + const move = (delta: number) => { + const j = state.selected + delta; + if (j < 0 || j >= project.slides.length) return; + [project.slides[state.selected], project.slides[j]] = [project.slides[j], project.slides[state.selected]]; + state.selected = j; + state.previews.clear(); + render(); + changed("all"); + }; + return h("div", {}, + h("div", { class: "toolbar" }, + h("div", { class: "tabs" }, ...project.locales.map((l) => h("button", { class: l === state.locale ? "on" : "", onclick: () => { state.locale = l; state.previews.clear(); render(); changed("all"); } }, l))), + newLocale, h("button", { onclick: () => { const v = newLocale.value.trim(); if (/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(v) && !project.locales.includes(v)) { project.locales.push(v); state.locale = v; state.previews.clear(); render(); changed("all"); } } }, T("+ 语言", "+ Language")), + h("select", { onchange: (e: Event) => { state.preset = (e.target as HTMLSelectElement).value; state.previews.clear(); render(); changed("all"); } }, + ...state.presets.filter((p) => project.presets.includes(p.id)).map((p) => h("option", { value: p.id, selected: p.id === state.preset }, p.label))), + h("span", { class: "spacer" }), + h("input", { value: state.projectPath, size: 22, title: T("项目文件", "Project file"), oninput: (e: Event) => (state.projectPath = (e.target as HTMLInputElement).value) }), + h("button", { onclick: save }, T("保存项目", "Save project")), + h("button", { class: "primary", onclick: exportAll }, T("导出全部", "Export all")), + ), + h("div", { class: "layout" }, + h("div", { class: "side" }, + h("div", { class: "card" }, h("h2", {}, T("样式(所有截图)", "Style (all slides)")), themeControls(project.theme)), + h("div", { class: "card controls" }, h("h2", {}, T("导出尺寸", "Sizes")), + ...state.presets.map((p) => h("label", {}, h("input", { type: "checkbox", checked: project.presets.includes(p.id), onchange: (e: Event) => { + project.presets = (e.target as HTMLInputElement).checked ? [...project.presets, p.id] : project.presets.filter((id) => id !== p.id); + if (!project.presets.includes(state.preset)) state.preset = project.presets[0] ?? ""; + render(); + } }), p.label)), + h("label", {}, T("输出到", "Output"), h("input", { type: "text", value: project.outputDir, oninput: (e: Event) => (project.outputDir = (e.target as HTMLInputElement).value) })), + ), + ), + h("div", { class: "main" }, + h("div", { class: "strip" }, ...project.slides.map((_, i) => thumb(i))), + slide && text ? h("div", { class: "card detail" }, + h("div", { class: "detail-img" }, h("img", { id: "large", alt: slide.image })), + h("div", { class: "controls" }, + h("h2", {}, `${state.selected + 1}. ${slide.image} · ${state.locale}`), + h("div", { id: "warnings", class: "row" }), + h("label", {}, T("标题", "Headline")), h("textarea", { oninput: (e: Event) => { text.title = (e.target as HTMLTextAreaElement).value; changed("one"); } }, text.title ?? ""), + h("label", {}, T("副标题", "Subheadline")), h("textarea", { oninput: (e: Event) => { text.subtitle = (e.target as HTMLTextAreaElement).value; changed("one"); } }, text.subtitle ?? ""), + h("label", {}, h("input", { type: "checkbox", checked: !!slide.background, onchange: (e: Event) => { slide.background = (e.target as HTMLInputElement).checked ? project.theme.background : undefined; slide.background2 = undefined; render(); changed("one"); } }), T("这张单独设背景", "Own background"), + slide.background ? h("input", { type: "color", value: slide.background, oninput: (e: Event) => { slide.background = (e.target as HTMLInputElement).value; changed("one"); } }) : null), + h("label", {}, T("平板截图", "Tablet screenshot"), h("select", { onchange: (e: Event) => { slide.tabletImage = (e.target as HTMLSelectElement).value || undefined; changed("one"); } }, + h("option", { value: "" }, T("(用手机截图)", "(use phone screenshot)")), ...state.images.map((f) => h("option", { value: f, selected: f === slide.tabletImage }, f)))), + h("div", { class: "row" }, + h("button", { onclick: () => move(-1) }, "←"), h("button", { onclick: () => move(1) }, "→"), + h("button", { onclick: () => { project.slides.splice(state.selected, 1); state.selected = Math.max(0, state.selected - 1); state.previews.clear(); render(); changed("all"); } }, T("移除", "Remove")), + h("button", { onclick: () => sendMessage(T(`请根据第 ${state.selected + 1} 张截图(${slide.image})的内容,为 ${project.locales.join("、")} 各写一个简短的商店宣传标题和副标题,更新到项目里。`, `Please write a short store headline and subheadline for screenshot ${state.selected + 1} (${slide.image}) in ${project.locales.join(", ")} and update the project.`)) }, T("让 Agent 写文案", "Ask the agent for copy")), + ), + project.slides.length < 10 ? h("label", {}, T("添加截图", "Add screenshot"), h("select", { onchange: (e: Event) => { const v = (e.target as HTMLSelectElement).value; if (v) { project.slides.push({ image: v, text: {} }); state.selected = project.slides.length - 1; render(); changed("all"); } } }, + h("option", { value: "" }, "…"), ...state.images.map((f) => h("option", { value: f }, f)))) : null, + ), + ) : h("div", { class: "empty" }, T("没有截图", "No screenshots")), + state.result ? h("div", { class: "card" }, + h("h2", {}, T(`已导出 ${state.result.files.length} 张到 ${state.result.outputDir}/`, `Exported ${state.result.files.length} images to ${state.result.outputDir}/`)), + ...state.result.problems.slice(0, 20).map((p) => h("div", { class: "muted small" }, p)), + ) : null, + ), + ), + ); +} + +async function save() { + const result = await busy(() => call<{ path: string }>("project_save", { path: state.projectPath, project: state.project })); + if (result) { + state.projectPath = result.path; + toast(T(`已保存 ${result.path}`, `Saved ${result.path}`)); + } +} + +async function exportAll() { + const result = await busy(() => call<{ files: string[]; problems: string[]; outputDir: string }>("shots_export", { project: state.project }, 900_000)); + if (result) { + state.result = result; + render(); + void refreshOne(state.selected, true); + toast(T(`已导出 ${result.files.length} 张`, `Exported ${result.files.length} images`)); + } +} + +onToolResult((value) => { + if (!value || value.error) return; + if (value.kind === "project") load(value); + else if (value.kind === "exported" && state.project) { + state.result = value as never; + render(); + } else if (value.kind === "saved" && state.project) state.projectPath = value.path as string; +}); +onHostContext(() => applyTheme()); +render(); +void initHost("store-screenshot-studio", "0.1.0").then(() => render()); diff --git a/ui-plugins/store-screenshot-studio/ui/panel.css b/ui-plugins/store-screenshot-studio/ui/panel.css new file mode 100644 index 00000000..909d75ca --- /dev/null +++ b/ui-plugins/store-screenshot-studio/ui/panel.css @@ -0,0 +1,23 @@ +.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding-bottom:8px; border-bottom:1px solid var(--line); margin-bottom:8px; } +.spacer { flex:1; } +.layout { display:grid; grid-template-columns: 270px minmax(0,1fr); gap: 10px; } +@media (max-width: 760px) { .layout { grid-template-columns: 1fr; } } +.controls { display:flex; flex-direction:column; gap:6px; } +.controls label { white-space: nowrap; } +.controls label > input[type="text"], .controls label > select { flex:1; min-width:0; } +.slider { display:grid; grid-template-columns: 80px 1fr 40px; gap:6px; } +.slider .value { text-align:right; color: var(--muted); font-variant-numeric: tabular-nums; } +.tabs { display:flex; gap:4px; flex-wrap:wrap; } +.tabs button.on { background: var(--accent); border-color: var(--accent); color:#fff; } +.strip { display:flex; gap:10px; overflow-x:auto; padding-bottom:6px; } +.strip .thumb { flex: 0 0 150px; } +.thumb img { aspect-ratio: auto; } +.thumb .placeholder { height: 290px; display:flex; align-items:center; justify-content:center; color: var(--muted); } +.thumb.warn { border-color: #f59e0b; } +.thumb .flag { position:absolute; top:4px; right:4px; background:#f59e0b; color:#fff; border-radius:50%; width:18px; height:18px; text-align:center; font-weight:700; font-size:12px; line-height:18px; } +.detail { display:grid; grid-template-columns: minmax(0, 300px) minmax(0, 1fr); gap: 12px; } +@media (max-width: 900px) { .detail { grid-template-columns: 1fr; } } +.detail-img img { width:100%; display:block; border:1px solid var(--line); border-radius:6px; min-height: 100px; } +.detail textarea { width: 100%; min-height: 44px; resize: vertical; } +.pick-list { display:flex; flex-direction:column; gap:4px; max-height: 40vh; overflow:auto; } +.small { font-size: 11px; } diff --git a/ui-plugins/store-screenshot-studio/vitest.config.ts b/ui-plugins/store-screenshot-studio/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/store-screenshot-studio/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 } });