feat: 新增 plugin/ 插件化形态(funjia.print-tag)+ 可选 SN 条码/二维码

把本工程的标签排版能力改造成 FunjiaUI 远端插件,放进 plugin/ 子目录,
与原独立 Web 版并存(两者功能一致,模板/版面/打印行为逐项对齐)。

- 入口从 createApp().mount() 改为 activate(ctx) + ctx.addRoute,注册 1 菜单 / 1 路由 / 2 命令
- 11 个模板的渲染收敛成 SpecTag,差异集中到 templates/registry.ts(字段/选项/默认值原样保留)
- 店铺名 / 电话从写死改为可配置,记忆在插件私有存储
- 内置二维码图片改为打包 data URL —— 远端插件没有自己的 public/
- 去掉 @headlessui/vue(换原生 select)与 Tailwind,样式类名统一 pt- 前缀避免污染宿主
- 可选接入宿主 api::sn-code:按 SN 生成真 Code 128 条码与可扫二维码;
  关闭时(默认)完全保持原静态二维码行为。领码优先贴到已排版的格子,不够才新建
- 新增 commands: print-tag:issue-sn / print-tag:render-svg(后者纯本地出图,供其它插件复用)
- code128.ts 实现真 Code 128 Set B(含校验位);二维码走 qrcode-generator(真 QR)
- 自带本地预览器(preview/mock-api.ts 补了 /api/sn-codes mock)与 deploy / verify 脚本
- verify.mjs 修掉一处误报:源码边界判据改为「解析后是否逃出工程根」,
  而不是「说明符是否以 .. 开头」(后者会把 src/components/X.vue → ../codes 误判为越界)

已发布到插件仓库:funjia.print-tag@1.0.0
This commit is contained in:
2026-10-03 23:48:32 +08:00
parent 1896d1032b
commit ef41d98838
43 changed files with 8835 additions and 0 deletions
+13
View File
@@ -4,6 +4,19 @@
---
## 两种形态
| 位置 | 形态 | 用途 |
| --- | --- | --- |
| 仓库根目录(本 README 描述的部分) | 独立 Web 应用 | `npm run dev` 直接跑,适合快速改模板 / 试排版 |
| [`plugin/`](./plugin/README.md) | **FunjiaUI 远端插件** `funjia.print-tag` | 装进宿主(设备管理 → 标签打印),并支持**可选**接入 SN 码接口生成真条码 / 二维码 |
两个形态功能一致:44 格版面、11 个内置模板、批量填充、逐格编辑、打印边距全部保持原样。
插件形态额外把「店铺名 / 电话」做成可配置,并加了可选的 SN 码能力。
插件工程里也有一个自带 mock 后端的本地预览器,改代码不必每次都装进宿主。
---
## 功能简介
### 标签版面
+11
View File
@@ -0,0 +1,11 @@
# 依赖
node_modules/
# 构建产物(产物通过 scripts/deploy.mjs 交付给仓库,不进版本库)
dist/
# 日志与系统文件
*.log
.logs/
.DS_Store
Thumbs.db
+146
View File
@@ -0,0 +1,146 @@
# 标签打印插件(`funjia.print-tag`)
本目录是 `print-tag-system` 的**插件化形态**:同一套标签排版 / 打印能力,
改造成可被 FunjiaUI 宿主装载的远端插件,并加了**可选的 SN 码 → 条码 / 二维码**能力。
- 插件 id:`funjia.print-tag`
- 产物:`dist/PrintTagBundle.iife.js` + `dist/PrintTagBundle.css`(IIFE,自注册)
- 上架位置:`funjia-plugin-repository` 插件仓库的 `repository/plugins/funjia.print-tag/1.0.0/`
仓库根目录那份 `src/` 是**原独立 Web 版**,两者并存、互不影响。
---
## 一、和原 Web 版的关系
| 能力 | 原 Web 版 | 本插件 |
| --- | --- | --- |
| 启动方式 | `createApp(App).mount('#app')`,自己起 Vite 服务 | 宿主装载 → `activate(ctx)` → `ctx.addRoute` 挂页面 |
| 路由 / 菜单 | 无(单页) | 注册到宿主侧边栏(设备管理 → 标签打印) |
| 内置模板 | 11 个 `.vue` 文件 | 11 个模板,渲染收敛成 `SpecTag`,差异集中在 `templates/registry.ts` |
| 二维码图片 | 站点根目录 `/qrcode.png` | 打包成 data URL 内置(远端插件没有自己的 `public/`) |
| 下拉选择 | `@headlessui/vue` Listbox | 原生 `<select>`(少 30KB,且浮层不会进打印流) |
| 样式 | Tailwind 4 + 全局 CSS | 纯 CSS,**类名一律 `pt-` 前缀**(插件 CSS 是注入宿主全局的) |
| 店铺名 / 电话 | 写死在每个模板里 | 面板可改,记忆到插件私有存储 |
| SN 码 / 条码 / 二维码 | 无 | **可选**(见第三节) |
标签尺寸、44 格版面、模板字段与选项、打印边距、双击隐藏等行为**逐项保持原样**。
---
## 二、开发与交付
```bash
cd plugin
npm install
npm run dev # 本地预览(http://127.0.0.1:5310),改 src/** 立刻生效
npm run build # 产物落到 dist/
npm run typecheck # tsc --noEmit
npm run verify # 自检:清单自洽 / 源码边界 / 产物形态 / 预览资产
npm run preview # 产物模式预览(http://127.0.0.1:5310/artifact.html),验 external 与 CSS 抽取
```
交付到插件仓库(构建 → 归档 → 重写索引,一步到位):
```bash
node scripts/deploy.mjs --repo ../plugin-repo --no-build
```
> ⚠️ **发布脚本要求 `plugins/dist/` 里齐备 `repo.config.json` 中所有插件的产物**
> (那是它的暂存区,已被 gitignore)。仓库里其它插件的产物在 `repository/plugins/`
> 下已归档,回填即可:
>
> ```bash
> cd ../plugin-repo
> for d in repository/plugins/*/*/; do for f in "$d"*; do
> b=$(basename "$f"); [ "$b" = plugin.json ] || cp -n "$f" plugins/dist/
> done; done
> node scripts/publish-repo.mjs
> ```
---
## 三、SN 码 / 条码 / 二维码(可选)
面板「② SN 码 · 条码 / 二维码(可选)」有一个总开关,**默认关闭**。
| 开关 | 行为 |
| --- | --- |
| 关闭 | 完全保持原样:左侧用内置静态二维码图,不调用任何接口 |
| 开启 | 走宿主后端 `api::sn-code`,按 SN 现场生成**真 Code 128 条码**与**可扫二维码** |
开启后:
- **批量领码并填充** —— 优先贴到「已排好版但还没 SN」的格子上,不够才往空格新建标签
(顺序很重要:先排版再贴码才是真实用法,否则点一下会多出一堆空壳标签);
- 单格编辑面板里可手工填 SN,或「领 1 条」单独取码;
- **校验选中格 SN** —— 格式 + 校验位 + 台账存在性,都由后端判定。
接口(与 `funjia.sn-tools` 插件共用同一套后端):
```
GET /api/sn-codes/meta 业务类型 / 默认前缀 / 码长
POST /api/sn-codes/generate 单条发放
POST /api/sn-codes/batch 批量发放 → { items: [...] }
POST /api/sn-codes/verify 校验 → { valid, reason, exists, record }
```
两个命令也注册给了别的插件:
- `print-tag:issue-sn` —— 按业务类型领 N 条 SN;
- `print-tag:render-svg` —— **纯本地**把文本渲染成条码 / 二维码 SVG(不调接口)。
别的插件想在自己的标签上画码,调这一条即可,不必各自引一份条码库、
也不必各自踩一遍 Code 128 校验位的坑。
### 物理尺寸:必须知道的三个数
标签格是 `48.5mm × 25.4mm`。格子放不下两个「全尺寸」图形,所以:
| 项 | 值 | 说明 |
| --- | --- | --- |
| 二维码模块 | 约 0.54mm/模块 | 16 位 SN 在 EC-M 下是 25×25 模块,18mm 出图 → 203dpi 下约 4 个点/模块,很稳 |
| 二维码(开条码后) | 约 0.34mm/模块 | 条码条吃掉 6.6mm,二维码被挤到约 11mm |
| 条码模块 | 约 0.199mm(7.8 mil) | 46mm 宽塞 211 个模块(16 位 SN)。**这已接近 Code 128 下限 7.5 mil**,203dpi 下每模块不到 2 个点 |
界面上会把这两个数**实时算出来**并给出建议(换 300dpi / 关掉条码)。
> 一句话:**二维码是可靠路径,条码在这个格子上是「勉强够用」**。
> 需要高可靠条码时应换更大的标签纸,或让标签软件(BarTender 等)去出图。
---
## 四、目录结构
```
plugin/
├── plugin.config.json ★ 元数据唯一真源(id / 版本 / 产物名 / 扩展点声明)
├── postcss.config.js 截断 PostCSS 查找链(否则会加载仓库根目录的 Tailwind 配置)
├── src/
│ ├── index.ts ★ 插件入口:生命周期 + 注册菜单/路由/2 个命令
│ ├── codes.ts Code 128 与真 QR 的 SVG 生成(纯函数,单位 mm)
│ ├── sdk.ts / runtime.ts 宿主能力契约与 ctx 持有者
│ ├── components/ LabelCell / TagShell / DynamicForm / Input / Select
│ ├── templates/ SpecTag / ErrorTag / CustomTag + registry.ts(模板注册表)
│ ├── pages/PrintTagPage.vue ★ 主页面:44 格版面 + 面板 + SN 集成
│ └── assets/default-qr.ts 内置默认二维码(data URL)
├── scripts/ deploy / verify
└── preview/ 本地预览器(迷你宿主 + 调试面板 + mock 后端)
```
`preview/mock-api.ts` 里**额外实现了 `/api/sn-codes/*`**(模板原本只有通用 CRUD)。
少了它,本地一打开 SN 开关就是 404,只能走「构建 → 发布 → 装进宿主 → 点一遍」,
一圈几分钟。注意:mock 的号段与校验位算法是本地自定的,**只验链路、别对号段**。
---
## 五、已知边界
- **`--no-build` 之外的重建**:`dist/` 与 `node_modules/` 已被仓库根 `.gitignore` 忽略,不会进版本库。
- **print 样式是临时注入的**:打印时才插 `<style media="print">`,`afterprint` 时移除。
常驻的话,用户在宿主里打印**任何别的页面**都会得到一张白纸 —— 插件 CSS 分不清
「现在打印的是不是我的页面」。
- **`postcss.config.js` 不能删**:本工程住在有 Tailwind 的仓库里,Vite 的 PostCSS
配置查找会往上走,加载到那份 Tailwind 配置后构建直接失败。
- **预览器做不到的三件事**(没有真 FunjiaUI、`ctx.plugin.repository` 为空、无路由守卫)
见 `funjia-plugin-starter` 的 README §3.3。
+17
View File
@@ -0,0 +1,17 @@
/**
* 插件工程的模块声明补充。
*
* `*.vue` 的 shim 是必需的:`Inspection.ts` / `HealthReport.ts` 里
* `import InspectionPage from "../pages/InspectionPage.vue"` 在运行时由
* `@vitejs/plugin-vue` 处理,但 `tsc` 不认识 `.vue`,没有这个声明
* 类型检查会直接报 `Cannot find module`。
*
* 只声明 `default` 一个导出是有意的 —— 本工程的页面组件全部用
* `<script setup>`,产出就是默认导出;声明成 `any` 之外的东西反而会骗人。
*/
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
+702
View File
@@ -0,0 +1,702 @@
{
"name": "funjia-plugin-print-tag",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "funjia-plugin-print-tag",
"version": "1.0.0",
"dependencies": {
"qrcode-generator": "^2.0.4"
},
"devDependencies": {
"@element-plus/icons-vue": "^2.0.6",
"@types/node": "^17.0.25",
"@vitejs/plugin-vue": "^2.3.4",
"element-plus": "2.1.10",
"typescript": "^4.5.4",
"vite": "^2.9.5",
"vue": "3.2.33"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.9",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.8",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@ctrl/tinycolor": {
"version": "3.6.1",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/@element-plus/icons-vue": {
"version": "2.3.2",
"dev": true,
"license": "MIT",
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/@floating-ui/core": {
"version": "0.6.2",
"dev": true,
"license": "MIT"
},
"node_modules/@floating-ui/dom": {
"version": "0.4.5",
"dev": true,
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^0.6.2"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"dev": true,
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@types/lodash": {
"version": "4.17.25",
"dev": true,
"license": "MIT"
},
"node_modules/@types/lodash-es": {
"version": "4.17.12",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/lodash": "*"
}
},
"node_modules/@types/node": {
"version": "17.0.45",
"dev": true,
"license": "MIT"
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.14",
"dev": true,
"license": "MIT"
},
"node_modules/@vitejs/plugin-vue": {
"version": "2.3.4",
"resolved": "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-2.3.4.tgz",
"integrity": "sha512-IfFNbtkbIm36O9KB8QodlwwYvTEsJb4Lll4c2IwB3VHc2gie2mSPtSzL0eYay7X2jd/2WX02FjSGTWR6OPr/zg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
},
"peerDependencies": {
"vite": "^2.5.10",
"vue": "^3.2.25"
}
},
"node_modules/@vue/compiler-core": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.16.4",
"@vue/shared": "3.2.33",
"estree-walker": "^2.0.2",
"source-map": "^0.6.1"
}
},
"node_modules/@vue/compiler-dom": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/compiler-core": "3.2.33",
"@vue/shared": "3.2.33"
}
},
"node_modules/@vue/compiler-sfc": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.16.4",
"@vue/compiler-core": "3.2.33",
"@vue/compiler-dom": "3.2.33",
"@vue/compiler-ssr": "3.2.33",
"@vue/reactivity-transform": "3.2.33",
"@vue/shared": "3.2.33",
"estree-walker": "^2.0.2",
"magic-string": "^0.25.7",
"postcss": "^8.1.10",
"source-map": "^0.6.1"
}
},
"node_modules/@vue/compiler-ssr": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/compiler-dom": "3.2.33",
"@vue/shared": "3.2.33"
}
},
"node_modules/@vue/reactivity": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/shared": "3.2.33"
}
},
"node_modules/@vue/reactivity-transform": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.16.4",
"@vue/compiler-core": "3.2.33",
"@vue/shared": "3.2.33",
"estree-walker": "^2.0.2",
"magic-string": "^0.25.7"
}
},
"node_modules/@vue/runtime-core": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/reactivity": "3.2.33",
"@vue/shared": "3.2.33"
}
},
"node_modules/@vue/runtime-dom": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/runtime-core": "3.2.33",
"@vue/shared": "3.2.33",
"csstype": "^2.6.8"
}
},
"node_modules/@vue/server-renderer": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/compiler-ssr": "3.2.33",
"@vue/shared": "3.2.33"
},
"peerDependencies": {
"vue": "3.2.33"
}
},
"node_modules/@vue/shared": {
"version": "3.2.33",
"dev": true,
"license": "MIT"
},
"node_modules/@vueuse/metadata": {
"version": "8.9.4",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/async-validator": {
"version": "4.2.5",
"dev": true,
"license": "MIT"
},
"node_modules/csstype": {
"version": "2.6.21",
"dev": true,
"license": "MIT"
},
"node_modules/dayjs": {
"version": "1.11.23",
"dev": true,
"license": "MIT"
},
"node_modules/element-plus": {
"version": "2.1.10",
"dev": true,
"license": "MIT",
"dependencies": {
"@ctrl/tinycolor": "^3.4.1",
"@element-plus/icons-vue": "^1.1.4",
"@floating-ui/dom": "^0.4.4",
"@popperjs/core": "^2.11.5",
"@types/lodash": "^4.14.181",
"@types/lodash-es": "^4.17.6",
"@vueuse/core": "^8.2.5",
"async-validator": "^4.0.7",
"dayjs": "^1.11.0",
"escape-html": "^1.0.3",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"lodash-unified": "^1.0.2",
"memoize-one": "^6.0.0",
"normalize-wheel-es": "^1.1.2"
},
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/element-plus/node_modules/@element-plus/icons-vue": {
"version": "1.1.4",
"dev": true,
"license": "MIT",
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/element-plus/node_modules/@vueuse/core": {
"version": "8.9.4",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.14",
"@vueuse/metadata": "8.9.4",
"@vueuse/shared": "8.9.4",
"vue-demi": "*"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.1.0",
"vue": "^2.6.0 || ^3.2.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
},
"vue": {
"optional": true
}
}
},
"node_modules/element-plus/node_modules/@vueuse/core/node_modules/@vueuse/shared": {
"version": "8.9.4",
"dev": true,
"license": "MIT",
"dependencies": {
"vue-demi": "*"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.1.0",
"vue": "^2.6.0 || ^3.2.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
},
"vue": {
"optional": true
}
}
},
"node_modules/element-plus/node_modules/@vueuse/core/node_modules/vue-demi": {
"version": "0.14.10",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.14.54",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=12"
},
"optionalDependencies": {
"@esbuild/linux-loong64": "0.14.54",
"esbuild-android-64": "0.14.54",
"esbuild-android-arm64": "0.14.54",
"esbuild-darwin-64": "0.14.54",
"esbuild-darwin-arm64": "0.14.54",
"esbuild-freebsd-64": "0.14.54",
"esbuild-freebsd-arm64": "0.14.54",
"esbuild-linux-32": "0.14.54",
"esbuild-linux-64": "0.14.54",
"esbuild-linux-arm": "0.14.54",
"esbuild-linux-arm64": "0.14.54",
"esbuild-linux-mips64le": "0.14.54",
"esbuild-linux-ppc64le": "0.14.54",
"esbuild-linux-riscv64": "0.14.54",
"esbuild-linux-s390x": "0.14.54",
"esbuild-netbsd-64": "0.14.54",
"esbuild-openbsd-64": "0.14.54",
"esbuild-sunos-64": "0.14.54",
"esbuild-windows-32": "0.14.54",
"esbuild-windows-64": "0.14.54",
"esbuild-windows-arm64": "0.14.54"
}
},
"node_modules/esbuild-windows-64": {
"version": "0.14.54",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"dev": true,
"license": "MIT"
},
"node_modules/estree-walker": {
"version": "2.0.2",
"dev": true,
"license": "MIT"
},
"node_modules/function-bind": {
"version": "1.1.2",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"dev": true,
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/is-core-module": {
"version": "2.17.0",
"dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"dev": true,
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.18.1",
"dev": true,
"license": "MIT"
},
"node_modules/lodash-unified": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/lodash-unified/-/lodash-unified-1.0.3.tgz",
"integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/lodash-es": "*",
"lodash": "*",
"lodash-es": "*"
}
},
"node_modules/magic-string": {
"version": "0.25.9",
"dev": true,
"license": "MIT",
"dependencies": {
"sourcemap-codec": "^1.4.8"
}
},
"node_modules/memoize-one": {
"version": "6.0.0",
"dev": true,
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.19",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/normalize-wheel-es": {
"version": "1.2.0",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/path-parse": {
"version": "1.0.7",
"dev": true,
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"dev": true,
"license": "ISC"
},
"node_modules/postcss": {
"version": "8.5.28",
"dev": true,
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.18",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/qrcode-generator": {
"version": "2.0.4",
"resolved": "https://registry.npmmirror.com/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
"integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
"license": "MIT"
},
"node_modules/resolve": {
"version": "1.22.12",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"is-core-module": "^2.16.1",
"path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0"
},
"bin": {
"resolve": "bin/resolve"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/rollup": {
"version": "2.77.3",
"dev": true,
"license": "MIT",
"bin": {
"rollup": "dist/bin/rollup"
},
"engines": {
"node": ">=10.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.2",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/sourcemap-codec": {
"version": "1.4.8",
"dev": true,
"license": "MIT"
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/typescript": {
"version": "4.9.5",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
}
},
"node_modules/vite": {
"version": "2.9.18",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "^0.14.27",
"postcss": "^8.4.13",
"resolve": "^1.22.0",
"rollup": ">=2.59.0 <2.78.0"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
"node": ">=12.2.0"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
},
"peerDependencies": {
"less": "*",
"sass": "*",
"stylus": "*"
},
"peerDependenciesMeta": {
"less": {
"optional": true
},
"sass": {
"optional": true
},
"stylus": {
"optional": true
}
}
},
"node_modules/vue": {
"version": "3.2.33",
"dev": true,
"license": "MIT",
"dependencies": {
"@vue/compiler-dom": "3.2.33",
"@vue/compiler-sfc": "3.2.33",
"@vue/runtime-dom": "3.2.33",
"@vue/server-renderer": "3.2.33",
"@vue/shared": "3.2.33"
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "funjia-plugin-print-tag",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "FunjiaUI 插件:标签打印(A4 4×11 / 44 格排版、批量填充、逐格编辑;可选接入 SN 码接口生成真 Code 128 条码与可扫二维码)",
"scripts": {
"dev": "vite --config vite.preview.config.ts",
"preview": "vite build && vite --config vite.preview.config.ts --mode artifact",
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc --noEmit",
"deploy": "node scripts/deploy.mjs",
"verify": "node scripts/verify.mjs"
},
"dependencies": {
"qrcode-generator": "^2.0.4"
},
"devDependencies": {
"@element-plus/icons-vue": "^2.0.6",
"@types/node": "^17.0.25",
"@vitejs/plugin-vue": "^2.3.4",
"element-plus": "2.1.10",
"typescript": "^4.5.4",
"vite": "^2.9.5",
"vue": "3.2.33"
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"id": "funjia.print-tag",
"name": "标签打印",
"version": "1.0.0",
"kind": "iife",
"artifact": "PrintTagBundle.iife.js",
"style": "PrintTagBundle.css",
"globalKey": "PrintTagBundle",
"description": "A4 标签纸 4×11 / 44 格排版打印:内置台式机 / 一体机 / 硬盘 / 售后 / 自定义文字等模板,支持批量填充与逐格编辑。可选接入 SN 码接口(api::sn-code),按 SN 生成真 Code 128 条码与可扫二维码贴在标签上;关闭时沿用原静态二维码图片。",
"author": "funjia",
"tags": [
"标签打印",
"条码",
"二维码",
"SN",
"设备管理"
],
"permissions": [
"menu",
"route",
"command",
"ui",
"storage",
"http",
"event"
],
"activation": "lazy",
"contributes": {
"menus": [
"标签打印"
],
"routes": [
"/plugin/funjia-print-tag/"
],
"commands": [
"print-tag:issue-sn",
"print-tag:render-svg"
],
"description": "1 个页面(44 格标签排版 + 批量填充 + 逐格编辑 + 可选 SN 条码/二维码)、2 个命令(print-tag:issue-sn、print-tag:render-svg)"
}
}
+17
View File
@@ -0,0 +1,17 @@
/**
* 这个文件的作用是「**让 Vite 别再往上找**」。
*
* 本工程住在 `print-tag-system` 仓库里(`plugin/` 子目录),而仓库根目录有一份
* `postcss.config.js`(原 Web 版用 Tailwind 4)。Vite 的 PostCSS 配置查找会
* **从工程根一路往上走**,于是构建插件时会加载到那份 Tailwind 配置 ——
* 而插件的 node_modules 里根本没有 `@tailwindcss/postcss`,构建直接失败:
*
* Failed to load PostCSS config … Cannot find module '@tailwindcss/postcss'
*
* 插件**不需要 Tailwind**:它的样式是自带的普通 CSS(类名 `pt-` 前缀)。
* 所以这里放一份空配置把查找链截断 —— 比去改 `vite.config.ts`(模板里明确
* 标注「无需改」)或在父目录里做特判都干净。
*/
export default {
plugins: {},
};
+689
View File
@@ -0,0 +1,689 @@
<template>
<div class="pv">
<!-- ------------------------------------------------------ 顶栏 -->
<header class="pv-top">
<div class="pv-top__line">
<h1 class="pv-top__name">{{ config.name }}</h1>
<code class="pv-top__id">{{ config.id }}</code>
<el-tag size="small" :type="loader.mode === 'source' ? 'success' : 'warning'" effect="dark">
{{ loader.label }}模式
</el-tag>
<el-tag size="small" :type="phaseType">{{ phaseText }}</el-tag>
<span v-if="state.activatedAt" class="pv-top__time">启用时间 {{ state.activatedAt }}</span>
</div>
<div class="pv-top__line pv-top__meta">
<span>v{{ config.version }}</span>
<span>形态 {{ config.kind }}</span>
<span>activation {{ config.activation ?? "未声明" }}</span>
<span v-if="config.globalKey">globalKey {{ config.globalKey }}</span>
<span v-if="config.style">style {{ config.style }}</span>
<span class="pv-top__warn">repository 字段为空(预览等同于「手工填 URL 安装」)</span>
</div>
<div class="pv-top__line pv-top__ops">
<el-button v-if="isIdle" type="primary" size="small" :loading="busy" @click="start">
装载并启用
</el-button>
<template v-else>
<el-button size="small" :loading="busy" @click="stop">停用</el-button>
<el-button size="small" :loading="busy" @click="rerun">重新装载</el-button>
<el-button size="small" type="danger" plain @click="remove">卸载</el-button>
</template>
<!--
登录区。这里显示的是**真实**登录态(令牌来自 `/api/auth/login`,
请求时由请求层自动带上),不再是早前那个「模拟已登录」开关 ——
开关是个谎话:它让插件以为自己拿到了用户,而接口根本没带令牌。
-->
<div class="pv-auth">
<template v-if="state.user">
<el-tag size="small" type="success" effect="plain">
{{ state.user.name }} · {{ state.user.role }}
</el-tag>
<el-button size="small" :loading="state.authBusy" @click="onLogout">退出登录</el-button>
</template>
<template v-else>
<el-tag size="small" type="info" effect="plain">未登录</el-tag>
<el-button size="small" type="primary" plain @click="openLogin">登录</el-button>
</template>
</div>
</div>
</header>
<p class="pv-hint">{{ loader.hint }}</p>
<!-- 令牌失效:任何一次接口调用拿到 401 都会走到这里(宿主里对应「跳登录页」) -->
<el-alert
v-if="state.authNotice && !state.user"
type="warning"
:closable="false"
show-icon
:title="`登录态已失效:${state.authNotice}`"
class="pv-alert"
/>
<el-alert v-if="error" type="error" :closable="false" show-icon :title="error" class="pv-alert" />
<el-alert
v-for="w in warnings"
:key="w"
type="warning"
:closable="false"
show-icon
:title="w"
class="pv-alert"
/>
<!-- -------------------------------------------- 菜单 + 页面 + 命令 -->
<div class="pv-body">
<aside class="pv-side">
<section>
<h3>侧边菜单 <em>{{ state.menus.length }}</em></h3>
<ul class="pv-list">
<li
v-for="m in state.menus"
:key="m.id"
:class="{ 'is-active': isCurrent(m.path) }"
@click="pick(m.path)"
>
<span class="pv-list__title">{{ m.title }}</span>
<code>{{ m.path || "(无路径)" }}</code>
</li>
<li v-if="!state.menus.length" class="pv-list__empty">activate 里没有注册菜单</li>
</ul>
</section>
<section>
<h3>路由 <em>{{ state.routes.length }}</em></h3>
<ul class="pv-list">
<li
v-for="r in state.routes"
:key="r.name"
:class="{ 'is-active': isCurrent(r.path) }"
@click="pick(r.path)"
>
<span class="pv-list__title">{{ r.name }}</span>
<code>{{ r.path }}</code>
</li>
<li v-if="!state.routes.length" class="pv-list__empty">activate 里没有注册路由</li>
</ul>
</section>
</aside>
<main class="pv-main">
<section class="pv-stage">
<div class="pv-bar">
<span class="pv-bar__label">页面区</span>
<code v-if="selectedRoute">{{ selectedRoute.path }}</code>
<span v-else class="pv-muted">(未选中路由)</span>
</div>
<div class="pv-stage__body">
<component v-if="selectedRoute" :is="selectedRoute.component" />
<div v-else class="pv-empty">
<p>没有可渲染的页面。</p>
<p>
插件用 <code>ctx.addRoute({ path, component })</code> 注册页面,注册完这里就会显示。
</p>
</div>
</div>
</section>
<section class="pv-stage pv-stage--cmd">
<div class="pv-bar">
<span class="pv-bar__label">命令台</span>
<span class="pv-muted">命令是跨插件协作的正规通道 —— 在这里直接调它,看返回值</span>
</div>
<div class="pv-cmd__form">
<el-select
v-model="cmdName"
size="small"
placeholder="选一个命令"
:disabled="!commandNames.length"
style="width: 200px"
>
<el-option v-for="n in commandNames" :key="n" :label="n" :value="n" />
</el-select>
<el-input
v-model="cmdArgs"
size="small"
placeholder='参数(JSON 数组),如 ["世界"]'
style="width: 260px"
/>
<el-button size="small" type="primary" :disabled="!cmdName" @click="runCommand">执行</el-button>
<span v-if="!commandNames.length" class="pv-muted">当前没有注册命令</span>
</div>
<pre v-if="cmdResult" class="pv-cmd__result" :class="{ 'is-error': !cmdResult.ok }">{{
cmdResult.ok ? format(cmdResult.value) : cmdResult.error
}}</pre>
<div v-if="cmdResult" class="pv-cmd__ms">耗时 {{ cmdResult.ms.toFixed(1) }} ms</div>
</section>
</main>
</div>
<!-- --------------------------------------------------- 底部面板 -->
<el-tabs v-model="bottomTab" class="pv-bottom">
<el-tab-pane name="log">
<template #label>日志<em v-if="state.logs.length"> {{ state.logs.length }}</em></template>
<div class="pv-bar">
<span class="pv-muted">logger 与 ui.* 的输出都落在这里(真实宿主里进浏览器控制台)</span>
<el-button size="small" type="text" @click="host.clearLogs()">清空</el-button>
</div>
<div ref="logBox" class="pv-lines">
<div v-for="l in state.logs" :key="l.seq" class="pv-line" :class="'is-' + l.level">
<span class="pv-line__time">{{ l.time }}</span>
<span class="pv-line__tag">{{ l.level }}</span>
<span class="pv-line__text">{{ l.text }}</span>
</div>
<div v-if="!state.logs.length" class="pv-line__empty">(暂无输出 —— 点上面的「装载并启用」)</div>
</div>
</el-tab-pane>
<el-tab-pane name="event">
<template #label>事件<em v-if="state.events.length"> {{ state.events.length }}</em></template>
<div class="pv-cmd__form">
<el-select
v-model="evChannel"
size="small"
placeholder="选一个通道"
:disabled="!channelOptions.length"
style="width: 230px"
>
<el-option v-for="c in channelOptions" :key="c.value" :label="c.label" :value="c.value" />
</el-select>
<el-input v-model="evArgs" size="small" placeholder="参数(JSON),如 [{ &quot;a&quot;: 1 }]" style="width: 230px" />
<el-button size="small" :disabled="!evChannel" @click="fireEvent">手动触发</el-button>
<span class="pv-muted">局部通道的事件名在宿主里会自动加插件前缀,所以不必担心重名</span>
</div>
<div class="pv-lines">
<div v-for="e in state.events" :key="e.seq" class="pv-line is-event">
<span class="pv-line__time">{{ e.time }}</span>
<span class="pv-line__tag">{{ e.scope === "global" ? "全局" : "局部" }}</span>
<span class="pv-line__text"><code>{{ e.name }}</code><template v-if="e.payload"> {{ e.payload }}</template></span>
</div>
<div v-if="!state.events.length" class="pv-line__empty">(暂无事件流水)</div>
</div>
</el-tab-pane>
<el-tab-pane name="ext">
<template #label>扩展点</template>
<div class="pv-ext">
<div class="pv-ext__col">
<h4>仪表盘卡片 <em>{{ state.widgets.length }}</em></h4>
<ul>
<li v-for="w in state.widgets" :key="w.id">{{ w.id }} · span={{ w.span ?? "默认" }}</li>
<li v-if="!state.widgets.length" class="pv-list__empty">无</li>
</ul>
<h4>顶栏动作 <em>{{ state.toolbarActions.length }}</em></h4>
<ul>
<li v-for="a in state.toolbarActions" :key="a.id">{{ a.title }}({{ a.id }})</li>
<li v-if="!state.toolbarActions.length" class="pv-list__empty">无</li>
</ul>
<h4>设置区块 <em>{{ state.settingsSections.length }}</em></h4>
<ul>
<li v-for="s in state.settingsSections" :key="s.id">{{ s.title }}</li>
<li v-if="!state.settingsSections.length" class="pv-list__empty">无</li>
</ul>
</div>
<div class="pv-ext__col">
<h4>视图模型 / 配置类 <em>{{ Object.keys(state.viewModels).length }}</em></h4>
<ul>
<li v-for="(_, name) in state.viewModels" :key="name">{{ name }}</li>
<li v-if="!Object.keys(state.viewModels).length" class="pv-list__empty">无</li>
</ul>
<h4>命令 <em>{{ commandNames.length }}</em></h4>
<ul>
<li v-for="n in commandNames" :key="n">{{ n }} · {{ state.commands[n].description || "无说明" }}</li>
<li v-if="!commandNames.length" class="pv-list__empty">无</li>
</ul>
<h4>待回收项 <em>{{ state.disposerCount }}</em></h4>
<p class="pv-note">
停用时宿主会一次性回收这些注册(连同 <code>ctx.onDispose()</code> 登记的自清理函数)。
停用后回到本页看,菜单和路由应当<strong>全部消失</strong>。
</p>
</div>
</div>
</el-tab-pane>
<el-tab-pane name="storage">
<template #label>私有存储<em v-if="Object.keys(state.storage).length"> {{ Object.keys(state.storage).length }}</em></template>
<div class="pv-bar">
<span class="pv-muted">
<code>ctx.storage</code> 的实时内容(真实宿主落在浏览器存储里,按插件 id 隔离,卸载时清空)
</span>
<span>
<el-button size="small" type="text" @click="host.syncStorageMirror()">刷新</el-button>
<el-button size="small" type="text" @click="host.clearStorage()">清空</el-button>
</span>
</div>
<div class="pv-kv">
<div v-for="(v, k) in state.storage" :key="k" class="pv-kv__row">
<code>{{ k }}</code><span>{{ v }}</span>
</div>
<div v-if="!Object.keys(state.storage).length" class="pv-line__empty">
(空 —— 插件还没往 storage 里写过东西)
</div>
</div>
</el-tab-pane>
</el-tabs>
<!--
登录框。对应宿主里的登录页(`src/views/LoginView.vue`)——
预览没有路由与守卫,所以「未登录」的表现就是一个可以随时关掉的弹窗,
而不是「整站被拦到登录页」。接口该回 401 的照样回 401。
-->
<el-dialog v-model="loginVisible" title="登录预览后端" width="380px" append-to-body>
<p class="pv-login__tip">
预览的 <code>/api</code> 来自内置的最小后端 <code>preview/mock-api.ts</code>
(响应契约与宿主一致)。登录后,插件里每一次
<code>ctx.http</code> 请求都会自动带上 <code>Authorization</code> 头。
</p>
<el-form label-width="52px" @submit.prevent>
<el-form-item label="账号">
<el-input v-model="loginForm.account" placeholder="funjia" @keyup.enter="submitLogin" />
</el-form-item>
<el-form-item label="密码">
<el-input
v-model="loginForm.password"
type="password"
show-password
placeholder="funjia123"
@keyup.enter="submitLogin"
/>
</el-form-item>
</el-form>
<el-alert v-if="dialogMessage" type="error" :closable="false" show-icon :title="dialogMessage" />
<div v-if="demos.length" class="pv-login__demos">
<span class="pv-muted">演示账号(点一下填入):</span>
<el-tag
v-for="d in demos"
:key="d.account"
size="small"
class="pv-login__demo"
@click="fillDemo(d)"
>
{{ d.account }} / {{ d.password }}({{ d.role }})
</el-tag>
</div>
<p v-else class="pv-login__tip pv-muted">
当前后端没有提供演示账号接口(真后端不会有)——手工填账号密码即可。
</p>
<template #footer>
<el-button size="small" @click="loginVisible = false">取消</el-button>
<el-button size="small" type="primary" :loading="state.authBusy" @click="submitLogin">
登录
</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
/**
* 预览界面。
*
* 定位是**开发时的镜子**:把插件注册出来的东西全部摊开 —— 菜单、页面、
* 命令、事件、扩展点、私有存储 —— 好回答「我实现的东西长什么样」。
*
* 生命周期按钮刻意与宿主同语义:
*
* | 按钮 | 发生什么 |
* | ---- | -------- |
* | 装载并启用 | `install`(仅首次)→ `activate`;注册项进注册表 |
* | 停用 | `deactivate` → **统一回收**全部注册项 |
* | 卸载 | 停用 + `uninstall` + 清空私有存储与 install 标记 |
* | 重新装载 | 源码模式刷新页面;产物模式重新拉一次产物 |
*
* 尤其是「停用」:点完回来看一眼,菜单和路由应该全没了。这条最容易验证
* 「插件有没有偷偷留下幽灵菜单」,而在宿主里要装两遍才看得出来。
*/
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import type { PreviewHost, CommandResult } from "./host";
import type { PluginConfig, PreviewLoader } from "./loaders";
import type { DemoAccount } from "./api-contract";
const props = defineProps<{
host: PreviewHost;
loader: PreviewLoader;
config: PluginConfig;
}>();
const state = props.host.state;
const busy = ref(false);
const error = ref("");
/** 当前装载到的插件模块(用来驱动停用/卸载)。名字避开 `module` —— 它在别处是个敏感词 */
const pluginModule = ref<any>(null);
const selectedRoute = ref<any>(null);
const bottomTab = ref("log");
const logBox = ref<HTMLElement | null>(null);
/* ------------------------------------------------------------ 生命周期 */
const isIdle = computed(() => state.phase !== "active");
const phaseText = computed(() =>
state.phase === "active" ? "已启用" : state.phase === "error" ? "出错" : "未启用"
);
const phaseType = computed(() =>
state.phase === "active" ? "success" : state.phase === "error" ? "danger" : "info"
);
async function start() {
if (busy.value) return;
busy.value = true;
error.value = "";
try {
const loaded = await props.loader.getModule();
pluginModule.value = loaded.module;
for (const note of loaded.notes) props.host.pushLog("info", note);
await props.host.activate(loaded.module);
// 装载完自动选中第一个路由,省一次点击
selectedRoute.value = state.routes[0] ?? null;
} catch (e) {
error.value = String((e as Error)?.message ?? e);
props.host.pushLog("error", error.value);
} finally {
busy.value = false;
}
}
async function stop() {
busy.value = true;
try {
await props.host.deactivate(pluginModule.value);
} finally {
busy.value = false;
}
}
async function rerun() {
// 源码模式下模块已经求值过(自注册被消费、模块内状态也变了),
// 重新装载最可靠的方式是刷新页面 —— 预览启动很快,刷新几乎无感
if (props.loader.reloadPageOnRerun) {
location.reload();
return;
}
busy.value = true;
try {
await props.host.deactivate(pluginModule.value);
await start();
} finally {
busy.value = false;
}
}
async function remove() {
busy.value = true;
try {
await props.host.uninstall(pluginModule.value);
pluginModule.value = null;
selectedRoute.value = null;
} finally {
busy.value = false;
}
}
/* -------------------------------------------------------- 菜单与页面 */
function pick(path?: string) {
if (!path) return;
const hit = state.routes.find((r) => r.path === path);
if (hit) selectedRoute.value = hit;
}
const isCurrent = (path?: string) => !!path && selectedRoute.value?.path === path;
// 重新装载后旧的 route 对象已经失效,指向它会让页面区渲染不出东西
watch(
() => state.routes.map((r) => r.path).join("|"),
() => {
if (!state.routes.includes(selectedRoute.value)) {
selectedRoute.value = state.routes[0] ?? null;
}
}
);
/* ------------------------------------------------------------ 命令台 */
const commandNames = computed(() => Object.keys(state.commands));
const cmdName = ref("");
const cmdArgs = ref("[]");
const cmdResult = ref<CommandResult | null>(null);
watch(
commandNames,
(names) => {
if (!names.includes(cmdName.value)) cmdName.value = names[0] ?? "";
},
{ immediate: true }
);
function parseArgs(text: string): { args: any[]; error?: string } {
const trimmed = text.trim();
if (!trimmed) return { args: [] };
try {
const parsed = JSON.parse(trimmed);
return { args: Array.isArray(parsed) ? parsed : [parsed] };
} catch (e) {
return { args: [], error: (e as Error).message };
}
}
async function runCommand() {
const { args, error: bad } = parseArgs(cmdArgs.value);
if (bad) {
cmdResult.value = { ok: false, error: `参数不是合法 JSON:${bad}`, ms: 0 };
return;
}
cmdResult.value = await props.host.callCommand(cmdName.value, args);
}
/* ------------------------------------------------------------ 事件 */
const channelOptions = computed(() =>
state.channels.map((c) => ({
value: `${c.scope}:${c.name}`,
label: `${c.scope === "global" ? "全局" : "局部"} · ${c.name}`,
}))
);
const evChannel = ref("");
const evArgs = ref("[]");
watch(
() => channelOptions.value.map((c) => c.value).join("|"),
() => {
if (!channelOptions.value.some((c) => c.value === evChannel.value)) {
evChannel.value = channelOptions.value[0]?.value ?? "";
}
},
{ immediate: true }
);
function fireEvent() {
const idx = evChannel.value.indexOf(":");
const scope = evChannel.value.slice(0, idx);
const name = evChannel.value.slice(idx + 1);
const { args, error: bad } = parseArgs(evArgs.value);
if (bad) props.host.pushLog("warn", `事件参数不是合法 JSON(${bad}),已按空参数触发`);
if (scope === "global") props.host.invokeGlobal(name, args);
else props.host.invokeLocal(name, args);
}
/* ------------------------------------------------------------ 登录态 */
/**
* 登录框的状态。
*
* `demos` 是从 `/api/auth/demo-accounts` 取回来的 —— **不是写死在界面里**。
* 真后端没有这个接口时它为空数组,整块演示账号区域自动消失,
* 界面因此不需要知道「当前连的是 mock 还是真后端」。
*/
const loginVisible = ref(false);
const loginError = ref("");
const loginForm = reactive({ account: "", password: "" });
const demos = ref<DemoAccount[]>([]);
function fillDemo(d: DemoAccount) {
loginForm.account = d.account;
loginForm.password = d.password;
// 清掉「上一次登录失败」的提示:用户换了账号,旧错误已经没意义了。
// ⚠️ 这里只清 `loginError`(本次表单的错误),**不能碰 `state.authNotice`** ——
// 上面那句「凭什么是它弹出的框」归 state 管,见 `dialogMessage`。
loginError.value = "";
}
function openLogin() {
// 手动打开时把上一次的失效提示清掉,否则会带着一句不相干的旧原因弹出来
state.authNotice = "";
loginError.value = "";
loginVisible.value = true;
}
async function submitLogin() {
loginError.value = "";
const account = loginForm.account.trim();
if (!account || !loginForm.password) {
loginError.value = "请输入账号与密码";
return;
}
const result = await props.host.login(account, loginForm.password);
if (!result.ok) {
loginError.value = result.message || "登录失败";
return;
}
loginVisible.value = false;
// 密码不留在内存里:预览页面对的是开发者的真机,没必要留一份
loginForm.password = "";
}
async function onLogout() {
await props.host.logout();
loginVisible.value = false;
}
/**
* 对话框里那条提示。
*
* ## 为什么不是直接用一个 `loginError`
*
* 这里有两个**来源不同**的原因,早前把它们塞进同一个 `ref` 时踩过一个很隐蔽的坑:
*
* 1. **本次登录失败**(密码错)→ 表单自己的状态,换账号就该清掉;
* 2. **凭什么是它弹出的框**(令牌失效 / 接口需要登录)→ 属于会话层的事实,
* 存在 `state.authNotice` 里。
*
* 合成一个 ref 之后,「切换演示账号」那次 `loginError = ""` 会把第 2 类原因
* 一起抹掉。而这个抹除只在**请求先后的竞态**下发生(启动恢复的 401 早于
* 演示账号请求),所以表现是「有时弹出来的框没有提示、有时又有」。
*
* 现在:表单原因覆盖会话原因,会话原因**只读不改**,谁也抹不掉谁。
*/
const dialogMessage = computed(() => loginError.value || state.authNotice);
/** 取演示账号。真后端没有这个接口 → 空数组 → 界面自动收起那一块 */
async function loadDemos() {
demos.value = await props.host.demoAccounts();
}
/**
* 令牌失效 / 需要登录时自动把登录框弹出来。
*
* 监听的是**计数器**而不是提示文本:watch 只在值变化时触发,
* 而未登录时连点两次「拉设备列表」会给出两条一模一样的 401 ——
* 只看文本的话第二次就不会弹框了。
*
* 宿主里这一步是「清会话 + 跳登录页」,预览没有路由,对应物就是这个弹窗。
*/
watch(
() => state.authNoticeSeq,
() => {
if (!state.authNotice || state.user) return;
// 弹框的原因是「会话失效 / 接口需要登录」,不是上一次的密码错误 —— 清掉表单那份,
// 让提示完整地由 state.authNotice 提供(见 dialogMessage 的说明)
loginError.value = "";
loginVisible.value = true;
}
);
/* ------------------------------------------------------------ 杂项 */
/** 日志跟着长 —— 不自动滚到底的话,最新那条永远要手动拉 */
watch(
() => state.logs.length,
async () => {
await nextTick();
if (logBox.value) logBox.value.scrollTop = logBox.value.scrollHeight;
}
);
/**
* 静态可查的配置问题。
*
* 这里只挑「预览里就能判定」的几条;真正的体检(产物、checksum、索引一致性)
* 在 `npm run verify` 与仓库的 `repo-doctor` 里,不在这里重复做。
*/
const warnings = computed(() => {
const out: string[] = [];
const contributes = props.config.contributes ?? {};
const hasEntry = (contributes.menus?.length ?? 0) > 0 || (contributes.routes?.length ?? 0) > 0;
if (props.config.activation === "lazy" && !hasEntry) {
out.push(
"activation 是 lazy,但 contributes 里既没有 menus 也没有 routes —— 宿主找不到入口," +
"延迟装载的插件会被退回 eager(代价是启动变慢)"
);
}
if (state.phase === "active" && !state.routes.length) {
out.push("activate 跑完了,但没有注册任何路由 —— 页面区会是空的,用户也找不到这个插件");
}
if (props.config.style && props.loader.mode === "source") {
out.push(
`plugin.config.json 声明了 style=${props.config.style},但源码模式不产出 CSS 文件 —— ` +
"想验证样式真的被抽出来,切到产物模式(npm run preview)"
);
}
return out;
});
const format = (value: any) => {
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
};
onMounted(async () => {
props.host.syncStorageMirror();
if (props.loader.mode === "artifact") {
props.host.pushLog("info", "产物模式:正在从 /artifact/ 加载 dist/ 里的产物…");
}
/**
* ⚠️ 会话恢复必须**早于**插件装载。
*
* 插件的 `activate` 里会调 `ctx.getUser()` 决定「要不要渲染管理入口」。
* 如果那时会话还没接回来,它会认为没人登录 —— 页面看着正常、功能却是降级过的,
* 而且没有任何报错。宿主里是同一条约束(还要更严:早于路由守卫),
* 见宿主 `src/main.ts` 的启动步骤。
*
* 顺带取一次演示账号;取不到(真后端)不影响装载。
*/
await Promise.all([props.host.restoreSession(), loadDemos()]);
// 首次打开就预填一个演示账号,省掉手打密码;只在表单为空时填,不覆盖用户输入
if (!loginForm.account && !loginForm.password && demos.value.length) fillDemo(demos.value[0]);
start();
});
</script>
+117
View File
@@ -0,0 +1,117 @@
/**
* 预览器的**接口契约**:客户端(`preview/host.ts`)与服务端(`preview/mock-api.ts`)
* 共用这一份定义。
*
* ## 为什么单独一个文件
*
* 这两边是同一份契约的两个实现方。如果各写各的 `AuthUser`、各写各的
* `parseAuthHeader`、各写各的令牌前缀,那么「客户端以为令牌是 `Bearer x`、
* 服务端以为就是 `x`」这类错误**不会有任何编译错误**,只会表现为
* 「登录成功但所有接口都 401」。
*
* 放一个文件里,改一边就同时改了另一边。
*
* ## 它不管什么
*
* 这里只有**线上跑的东西**(存储键、令牌形状、响应包络、请求头解析)。
* 数据表种子、内存 CRUD 逻辑属于实现,在 `mock-api.ts` 里。
*
* ## 与宿主的关系
*
* 契约本身**以宿主为准**(`src/mock/auth.ts` + `src/core/http/index.ts`):
* 同一个地址、同一个包络、同样的 401 语义。预览器是独立工程、拿不到宿主源码,
* 所以这里是一份**手抄的副本** —— 它必然有漂移的风险,这是一处已知的取舍,
* 由 `npm run verify` 的契约断言兜住最关键的几个字段。
*/
/* ------------------------------------------------------------ 存储键 */
/**
* 令牌存储键。
*
* **刻意与宿主不同名**(宿主是 `funjia-plugin-host:token`)。两者平时确实是
* 不同的 origin(预览 5310 / 宿主 5180),但一旦有人把预览挂到宿主同源的
* 子路径下调试,同名的键就会互相覆盖 —— 表现为「预览里登录把宿主的会话踢了」,
* 而且没人会往 localStorage 的键名上想。
*/
export const TOKEN_KEY = "funjia-plugin-preview:token";
/** 用户信息存储键,理由同上 */
export const USER_KEY = "funjia-plugin-preview:user";
/* ------------------------------------------------------------ 令牌形状 */
/** 令牌前缀。明文自描述,肉眼能看出「这是预览 mock 签的」 */
export const TOKEN_PREFIX = "mock";
/** 令牌有效期,与宿主 mock 一致 */
export const TOKEN_TTL_MS = 2 * 60 * 60 * 1000;
/* -------------------------------------------------------------- 类型 */
/** 登录用户(**不含密码**)。字段与宿主 mock 返回的 `user` 对齐 */
export interface AuthUser {
id: number;
name: string;
account: string;
role: string;
dept?: string;
}
/** 演示账号:登录页直接列出来,省掉「文档里翻账号」这一步 */
export interface DemoAccount {
account: string;
password: string;
role: string;
}
/** 统一响应包络。`code === 0` 表示成功 */
export interface ApiResult<T = any> {
code: number;
msg: string;
data: T;
total?: number;
}
/* ------------------------------------------------------------ 约定值 */
/**
* 未授权的业务码。
*
* 与宿主取同一个数字,且**刻意与 HTTP 状态码同值** —— 于是客户端一句
* `result.code === 401` 就能同时覆盖「内置 mock 返回的 code」与
* 「真后端返回的 HTTP 401」(后者由请求层归一成前者)。见 `host.ts` 的 `httpCall`。
*/
export const UNAUTHORIZED_CODE = 401;
/**
* 登录态广播的**全局事件名**(与宿主 `src/core/session.ts` 完全一致)。
*
* 插件用 `ctx.event.onGlobal("user:login", ...)` 监听的就是这两条。
* 预览器也发同样的名字,插件才能在预览里验到「登出后我被通知了」。
*/
export const AUTH_EVENTS = {
login: "user:login",
logout: "user:logout",
} as const;
/* -------------------------------------------------------- 请求头解析 */
/**
* 从 `Authorization` 头的值里取出裸令牌。
*
* **严格校验 `Bearer ` 前缀**,与真后端(和宿主 mock)同口径。
* 宽松处理会把「客户端忘了加前缀」这个 bug 藏起来 —— 而这个 bug 在
* 预览阶段暴露出来只需要一次请求,拖到接真后端那天就变成了
* 「登录明明成功、接口全 401」。
*
* 只有**服务端**(`mock-api.ts`)用到它;放在这里是因为它描述的是
* 契约的校验规则,写错就两边对不上。
*/
export function parseAuthHeader(raw?: string): { token: string; reason?: string } {
const value = (raw || "").trim();
if (!value) return { token: "", reason: "缺少 Authorization 请求头" };
if (!/^Bearer\s+/i.test(value)) {
return { token: "", reason: "Authorization 头缺少 `Bearer ` 前缀" };
}
const token = value.replace(/^Bearer\s+/i, "").trim();
return token ? { token } : { token: "", reason: "Authorization 头里的令牌为空" };
}
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>插件预览 · 产物模式</title>
<!--
与 index.html 同一份 import map,理由见那边。
产物模式**真的会用到它**:dist/ 里的 ESM 产物保留着裸说明符 `from "vue"`,
浏览器要靠这张表才知道去哪儿取 Vue。
-->
<script type="importmap">
{
"imports": {
"vue": "/runtime.ts",
"funjiaui": "/shims/funjiaui.ts"
}
}
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="/main-artifact.ts"></script>
</body>
</html>
+96
View File
@@ -0,0 +1,96 @@
/**
* 全局契约的**最小安装**(副作用模块:import 即生效)。
*
* ## 为什么它得单独存在,不能写进 host.ts
*
* 插件的入口脚本在**模块求值的那一刻**就调用了 `window.FunjiaPlugin.register()`
* —— 也就是 `src/index.ts` 只要被 import,注册就已经发生完了。而预览宿主
* (ctx、扩展点注册表、界面)是之后才建起来的。如果契约安装晚于插件源码求值,
* 就会看到那句熟悉的报错:
*
* > 找不到 window.FunjiaPlugin:本脚本必须由宿主页面加载
*
* 而真正的原因只是**顺序**。ESM 的求值顺序是「按 import 声明顺序、深度优先」,
* 所以只要让本模块排在插件源码前面就够了:
*
* ```ts
* import "./contract"; // ① 先求值:契约就位
* import plugin from "../src/index"; // ② 后求值:register 落进队列,不会落空
* ```
*
* 这与宿主里的顺序问题同源:宿主也是「先 `installHostGlobals()`,再装载插件」。
*
* ## 它只装「谁来接」的部分
*
* 队列 + `window.vue` + `window.funjiaui` 兜底 + `window.FunjiaHost` 骨架。
* 真正的 ctx、扩展点注册表、回收逻辑在 `host.ts` 里,由预览界面驱动。
* 这样拆开还有一个好处:`window.FunjiaHost` 是个**稳定的对象引用**,
* 插件在求值时就算把它存起来了,后面 `host.ts` 补充实现(`Object.assign` 到同一个
* 对象上)它也能看到 —— 而不是拿着一个过期的空壳。
*/
import * as Vue from "vue";
import { createFunjiauiFallback } from "./shims/funjiaui";
/** 宿主版本。带 `-preview` 后缀是刻意的:插件若据此分支,日志里能一眼看出环境 */
export const HOST_VERSION = "1.0.0-preview";
/** 宿主标识,对应真实宿主的 `funjia-plugin-host` */
export const HOST_NAME = "funjia-plugin-host-preview";
/** 插件自注册时提交的形状(与宿主 `loader.ts` 的注册队列一致) */
export interface PendingRegistration {
manifest: { id?: string; [key: string]: any };
module: any;
}
/**
* 自注册队列。
*
* 用队列而不是「立即认领」,是因为真实宿主也这么做:脚本可能在宿主还没准备好
* 元数据(来自仓库索引)时就把自己注册进来了。预览沿用同一套语义,
* 免得出现「预览里能认领、宿主里认领不到」的差异。
*/
export const pendingRegistrations: PendingRegistration[] = [];
/** `window.FunjiaHost` 的骨架。**引用要稳定** —— host.ts 会往这个对象上补实现 */
export const hostInfo: Record<string, any> = {
name: HOST_NAME,
version: HOST_VERSION,
http: {
// 先给一个「明说没接上」的实现。host.ts 会换成真的请求层
// (真发请求、带鉴权头、401 统一处理 —— 见 host.ts 的 send)
get: async () => ({ code: 0, msg: "preview: 尚未接入请求层", data: null }),
post: async () => ({ code: 0, msg: "preview: 尚未接入请求层", data: null }),
put: async () => ({ code: 0, msg: "preview: 尚未接入请求层", data: null }),
del: async () => ({ code: 0, msg: "preview: 尚未接入请求层", data: null }),
},
getViewModel: () => undefined,
// 骨架里先给个「没人登录」。host.ts 会覆盖成读真实会话的那两个
getUser: () => null,
isLoggedIn: () => false,
stats: () => ({}),
};
const w = window as any;
// window.vue:**必须是预览页自己那一份 Vue**。IIFE 插件从全局取它,
// 取到的就是渲染这个页面的同一个实例 —— 这正是「同实例」的保证。
w.vue = Vue;
// window.funjiaui:桩(见 shims/funjiaui.ts)。Proxy 能兜住任意名字
w.funjiaui = createFunjiauiFallback();
w.FunjiaHost = hostInfo;
w.FunjiaPlugin = {
register(input: PendingRegistration) {
pendingRegistrations.push(input);
},
};
console.info(
`[preview] %c全局契约已安装%c:window.vue / window.funjiaui(桩) / window.FunjiaHost / window.FunjiaPlugin(版本 ${HOST_VERSION})`,
"color:#3b82f6;font-weight:bold",
"color:inherit"
);
+891
View File
@@ -0,0 +1,891 @@
/**
* 预览用的迷你宿主。
*
* ## 它做什么
*
* 把真实宿主在启动时做的事,在浏览器里搭一份**最小可跑**的版本:
* 扩展点注册表(菜单/路由/命令/事件/视图模型)、`ctx` 工厂、以及
* 「注册即自动回收」的禁用语义。好让插件在**不构建、不发布、不开宿主**
* 的情况下被看见。
*
* ## 它明确不做什么(这段比上面那段重要)
*
* | 缺口 | 后果 / 怎么办 |
* | ---- | ------------- |
* | 没有路由框架 | 预览直接把注册的页面组件渲染出来。真实宿主里的路径规则、权限、嵌套路由验不到 |
* | `funjiaui` 是桩 | 用 `UmTable` 等真实行为要在宿主里看;预览只保证不崩、有占位 |
* | 后端是**内置 mock** | `ctx.http` 真的发请求、真的拿得到数据,但数据是 `preview/mock-api.ts` 里的固定几行,进程重启即重置。接真后端用 `PREVIEW_API_TARGET` 代理过去 |
* | 没有路由守卫 | 预览有登录/登出,但「未登录一律拦到登录页」是**宿主**的行为,预览不拦 —— 插件页面在未登录时照样打得开,只是接口会回 401 |
* | 不做权限判定 | `ctx.getUser()` 拿得到真实角色,但拦不拦由插件自己写。宿主里也一样,只是宿主多了守卫那一层 |
* | 不校验完整性 | 产物模式加载的是本地 `dist/`,不做 checksum 比对 |
*
* 所以请把预览当作**开发时的镜子**,而不是验收环境:
*
* > 预览里看不到的东西 ≠ 宿主里也没问题。
* > 交付前那一次 `deploy` + 宿主安装,仍然要走。
*
* ## 与真实宿主的实现差异(有意为之)
*
* 真实宿主的扩展点注册表在 `src/core/plugin/extensionRegistry.ts`,预览这份是
* **独立实现**,没有 import 宿主的任何模块 —— 插件工程看不到宿主源码,
* 也不该为了预览去依赖它。代价是两边可能慢慢漂移,收益是插件工程零宿主依赖。
* 判断「漂移了没有」的方式很直接:在宿主里装一次,对比行为。
*/
import { markRaw, reactive } from "vue";
import type { PluginCtx, PluginModule } from "../src/sdk";
import { HOST_NAME, HOST_VERSION, hostInfo, pendingRegistrations } from "./contract";
import {
AUTH_EVENTS,
TOKEN_KEY,
UNAUTHORIZED_CODE,
USER_KEY,
type ApiResult,
type AuthUser,
type DemoAccount,
} from "./api-contract";
/** 宿主注入给插件的元数据。真实宿主里来自仓库索引条目 */
export interface PreviewManifest {
id: string;
name: string;
version: string;
kind: string;
activation?: string;
repository?: string;
checksum?: string;
}
export type LogLevel = "debug" | "info" | "warn" | "error" | "ui";
export interface LogItem {
seq: number;
level: LogLevel;
text: string;
time: string;
}
export interface EventItem {
seq: number;
scope: "local" | "global";
name: string;
payload: string;
time: string;
}
export interface CommandResult {
ok: boolean;
value?: any;
error?: string;
ms: number;
}
const MAX_LOG = 400;
/** 屏蔽 Vue 把组件对象变成响应式代理 —— 那会让 Vue 自己发出警告,且渲染行为改变 */
function raw<T>(value: T): T {
return (typeof value === "object" && value !== null) ? markRaw(value as any) : value;
}
export function createPreviewHost(manifest: PreviewManifest) {
/* ------------------------------------------------------------ 状态 */
const state = reactive({
menus: [] as any[],
routes: [] as any[],
widgets: [] as any[],
toolbarActions: [] as any[],
settingsSections: [] as any[],
viewModels: {} as Record<string, any>,
commands: {} as Record<string, any>,
logs: [] as LogItem[],
events: [] as EventItem[],
/** 插件私有存储的镜像(真身在 localStorage,这里只为了界面能显示) */
storage: {} as Record<string, any>,
/** 已注册的事件通道(供界面手动触发) */
channels: [] as { scope: "local" | "global"; name: string }[],
/** idle(未启用)/ active(已启用)/ error(activate 抛错) */
phase: "idle" as "idle" | "active" | "error",
error: "",
activatedAt: "",
/** 上一次 activate 里登记了多少个自动清理项 */
disposerCount: 0,
/** 预览环境的登录态:`null` = 未登录,与宿主 `ctx.getUser()` 同口径 */
user: null as AuthUser | null,
/** 裸令牌(**不带** `Bearer ` 前缀 —— 前缀由请求层统一补,见 authHeaderOf) */
token: "",
/** 上一次鉴权失败的原因。401 时由 send 写入,界面据此给提示 */
authNotice: "",
/**
* 401 计数器。**不能只用 `authNotice` 文本**:
* 界面用 `watch` 监听它来弹登录框,而 watch 只在**值变化**时触发 ——
* 连续两次同样的 401(比如未登录时点了两次「拉列表」)第二次就不会弹框了,
* 表现为「第一次有反应、之后点着没动静」。计数器每次必增,绕开这个坑。
*/
authNoticeSeq: 0,
/** 登录/登出进行中,界面用来禁用按钮 */
authBusy: false,
});
let seq = 0;
const now = () => new Date().toLocaleTimeString("zh-CN", { hour12: false });
function pushLog(level: LogLevel, text: string) {
state.logs.push({ seq: ++seq, level, text, time: now() });
if (state.logs.length > MAX_LOG) state.logs.splice(0, state.logs.length - MAX_LOG);
}
function pushEvent(scope: "local" | "global", name: string, args: any[]) {
// 事件流水单独一个列表:它和日志混在一起会看不清「谁发了什么、谁收到了」
state.events.push({
seq: ++seq,
scope,
name,
payload: args.length ? safeStringify(args.length === 1 ? args[0] : args) : "",
time: now(),
});
if (state.events.length > MAX_LOG) state.events.splice(0, state.events.length - MAX_LOG);
}
function safeStringify(value: any): string {
try {
const s = typeof value === "string" ? value : JSON.stringify(value);
return s === undefined ? String(value) : s;
} catch {
return String(value);
}
}
/* -------------------------------------------------- 插件私有存储 */
// 用 localStorage 而不是内存 Map:刷新页面后插件还能看到自己上次存的东西,
// 这样「install 只跑一次」「bootCount 递增」这类行为才验得出来
const prefix = `funjia-preview:${manifest.id}:`;
function storageKeys(): string[] {
const keys: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k.startsWith(prefix)) keys.push(k.slice(prefix.length));
}
return keys;
}
function syncStorageMirror() {
const dump: Record<string, any> = {};
for (const k of storageKeys()) dump[k] = localStorage.getItem(prefix + k);
state.storage = dump;
}
const storage = {
get<T = any>(key: string, fallback?: T): T {
const raw = localStorage.getItem(prefix + key);
if (raw === null) return fallback as T;
try {
return JSON.parse(raw) as T;
} catch {
return raw as unknown as T;
}
},
set(key: string, value: any) {
localStorage.setItem(prefix + key, JSON.stringify(value));
syncStorageMirror();
},
remove(key: string) {
localStorage.removeItem(prefix + key);
syncStorageMirror();
},
};
function clearStorage() {
for (const k of storageKeys()) localStorage.removeItem(prefix + k);
syncStorageMirror();
}
/* -------------------------------------------------------- 事件总线 */
/**
* 局部 / 全局两个通道分成两个 Map,而不是「一个带前缀的复合 key」。
*
* 复合 key 看着省事,但读回来要靠 `split` 的位置约定 —— 写错不会报错,
* 只会让「已注册通道」列表显示成别的字段(第一版就踩了这个:通道名
* 解析成了插件 id,于是界面上出现一个 `:acme.hello` 这样的鬼东西)。
* 分成两个 Map,结构上就不可能串。
*/
const localListeners = new Map<string, Set<(...args: any[]) => void>>();
const globalListeners = new Map<string, Set<(...args: any[]) => void>>();
const bucketOf = (scope: "local" | "global") =>
scope === "global" ? globalListeners : localListeners;
function syncChannels() {
const out: { scope: "local" | "global"; name: string }[] = [];
for (const name of localListeners.keys()) out.push({ scope: "local", name });
for (const name of globalListeners.keys()) out.push({ scope: "global", name });
state.channels = out;
}
function on(scope: "local" | "global", name: string, handler: (...args: any[]) => void) {
const bucket = bucketOf(scope);
if (!bucket.has(name)) bucket.set(name, new Set());
bucket.get(name)!.add(handler);
syncChannels();
return () => {
bucket.get(name)?.delete(handler);
syncChannels();
};
}
function emit(scope: "local" | "global", name: string, args: any[]) {
pushEvent(scope, name, args);
const set = bucketOf(scope).get(name);
if (!set || set.size === 0) {
pushLog("debug", `emit ${scope === "global" ? "全局" : "局部"}事件 ${name} —— 当前没有监听者`);
return;
}
for (const handler of [...set]) {
try {
handler(...args);
} catch (e) {
// 一个监听器抛错不该带崩整条总线 —— 真实宿主也是逐个隔离的
pushLog("error", `事件监听器抛错(${name}):${(e as Error)?.message ?? e}`);
}
}
}
/* -------------------------------------------------- 回收与注册表 */
const disposers: Array<() => void> = [];
function track(dispose: () => void) {
disposers.push(dispose);
return dispose;
}
function runDisposers() {
// 倒序执行:后注册的先撤,与「栈」的直觉一致
for (const fn of disposers.splice(0).reverse()) {
try {
fn();
} catch (e) {
pushLog("warn", `自动清理项抛错:${(e as Error)?.message ?? e}`);
}
}
}
/** 清空注册表。真实宿主在禁用时做的正是这件事 —— 所以插件不需要写反注册 */
function clearRegistry() {
state.menus = [];
state.routes = [];
state.widgets = [];
state.toolbarActions = [];
state.settingsSections = [];
state.viewModels = {};
state.commands = {};
localListeners.clear();
globalListeners.clear();
state.channels = [];
}
/** 从数组里摘掉一个元素,并返回「摘掉」这个动作 —— 这就是注册返回的 disposer */
function register<T>(list: T[], item: T): () => void {
list.push(raw(item));
return () => {
const i = list.indexOf(item);
if (i >= 0) list.splice(i, 1);
};
}
/* ------------------------------------------------------------ 登录态 */
/**
* 令牌与用户信息的读写集中在这几个小函数里,别处**不再直接碰 localStorage**。
*
* 宿主里对应的是 `src/core/auth/token.ts`。之所以要收敛:老版本把令牌的存取
* 散在三处(会话层读写、请求层 `getItem`、清空时各自 `removeItem`),
* 任何一处改了 key 都会出现「登录明明成功、请求却不带令牌」——
* 只在运行时暴露,且一定会被误判成后端问题。
*/
function readStoredToken(): string {
try {
return localStorage.getItem(TOKEN_KEY) || "";
} catch {
// 隐私模式读不到就当匿名,别让一个存储异常把启动带崩
return "";
}
}
function readStoredUser(): AuthUser | null {
try {
const raw = localStorage.getItem(USER_KEY);
return raw ? (JSON.parse(raw) as AuthUser) : null;
} catch {
return null;
}
}
function saveAuth(token: string, user: AuthUser | null) {
state.token = token;
state.user = user ? raw(user) : null;
try {
localStorage.setItem(TOKEN_KEY, token);
if (user) localStorage.setItem(USER_KEY, JSON.stringify(user));
else localStorage.removeItem(USER_KEY);
} catch {
// 存不下(隐私模式 / 配额满)不影响当前会话,只是刷新后要重新登录
}
}
function clearAuth() {
state.token = "";
state.user = null;
try {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);
} catch {
/* 同上:清不掉也不该抛 */
}
}
/**
* `Authorization` 头的值。未登录返回**空串** → 请求头里干脆不带这个字段。
*
* 前缀只在这里补一次。localStorage 里存的是**裸令牌** —— 想验证这条约定
* 有没有被破坏,看 `mock-api.ts`:它按真后端的严格程度校验那个头,
* 少一个 `Bearer ` 就当未授权。
*/
const authHeaderOf = () => (state.token ? `Bearer ${state.token}` : "");
/**
* 广播登录态。**事件名与宿主完全一致**(`src/core/session.ts` 的 `globalBus`),
* 所以插件里那句 `ctx.event.onGlobal("user:logout", ...)` 在预览里同样接到东西。
*/
function broadcastAuth(name: string, payload?: any) {
emit("global", name, payload === undefined ? [] : [payload]);
}
/**
* 未授权的统一处理:清会话(如果有)+ 提示 + 广播。
*
* **清会话这一步必须幂等**:一个页面并发五个请求时,401 会连着来五次。
* 判据是「当前会话是否已经空了」—— 与宿主 session 侧同构。
*
* ## 与宿主**有意不同**的一处
*
* 宿主靠**路由守卫**保证「未登录根本进不来任何页面」,所以它只在
* 「原本有会话、现在失效了」时才提示。预览没有守卫:一个未登录的插件页面
* 照样打得开,这时如果 401 一声不吭,作者看到的是「点了按钮没反应」,
* 而真正的原因在浏览器网络面板里(一个 401)—— 这属于最难查的一类问题。
*
* 所以预览里**一律**把登录框弹出来,并在文案上区分两种情况。
*/
function handleUnauthorized(reason: string) {
const hadSession = !!(state.token || state.user);
if (hadSession) {
clearAuth();
broadcastAuth(AUTH_EVENTS.logout);
}
state.authNotice = hadSession
? reason || "登录状态已失效,请重新登录"
: `接口需要登录(${reason || "未登录"})—— 登录后重试`;
state.authNoticeSeq += 1;
pushLog(
"warn",
hadSession
? `接口返回 401(${state.authNotice})→ 已清除预览环境的登录态`
: `接口返回 401:${state.authNotice}`
);
}
/**
* 启动恢复:刷新页面后把登录态接回来。
*
* ⚠️ **必须在插件装载之前完成** —— 插件 `activate` 里的 `ctx.getUser()`
* 会据此判断「有没有人登录」。宿主里这个顺序更严格(还要早于路由守卫),
* 预览里没有路由,只剩这一条约束。见 `App.vue` 的 `onMounted`。
*
* 三个取舍都与宿主一致:
* - **没有令牌就立即返回,不发请求** —— 未登录的首屏不该为一次必然 401 的往返付延迟;
* - 有令牌却没有用户信息 → 本地数据不一致,**丢掉重来**;
* - **后端不可达时保留登录态** —— 网络抖动不该把用户清下线。
*/
async function restoreSession() {
const token = readStoredToken();
if (!token) {
clearAuth();
return;
}
const cached = readStoredUser();
if (!cached) {
clearAuth();
pushLog("warn", "启动恢复:本地有令牌但没有用户信息(数据不一致),已清除");
return;
}
state.token = token;
state.user = raw(cached);
let result: ApiResult<AuthUser>;
try {
result = await send("GET", "/api/auth/me", undefined);
} catch (e) {
// 网络层失败:保留本地登录态(与宿主 bootstrapSession 的 catch 分支同口径)
pushLog("warn", `启动恢复:后端不可达,沿用本地登录态(${(e as Error)?.message ?? e})`);
return;
}
if (result.code === UNAUTHORIZED_CODE) {
// 401 已经由 send → handleUnauthorized 处理(清态 + 提示 + 广播),这里不重复
return;
}
if (result.code !== 0 || !result.data) {
clearAuth();
pushLog("warn", `启动恢复失败(${result.msg}),已清除本地登录态`);
return;
}
// 用服务端的权威信息覆盖本地缓存:名字、角色可能已被改过
saveAuth(token, result.data);
pushLog("info", `启动恢复:已登录为 ${state.user?.name}(${state.user?.role})`);
}
/**
* 登录。业务失败(账号密码不对)**不抛错**,返回 `{ ok: false, message }` ——
* 与宿主 `session.login()` 的返回形状一致,登录页两边都能直接用。
*/
async function login(account: string, password: string): Promise<{ ok: boolean; message?: string }> {
if (state.authBusy) return { ok: false, message: "正在处理上一个请求,请稍候" };
state.authBusy = true;
state.authNotice = "";
const hadUser = !!state.user;
try {
const result = await send("POST", "/api/auth/login", { account, password });
if (result.code !== 0 || !result.data?.token) {
// 刻意不区分「账号不存在」与「密码错误」:与后端、宿主同口径,避免账号枚举
return { ok: false, message: result.msg || "登录失败" };
}
const user = result.data.user as AuthUser;
saveAuth(result.data.token, user);
pushLog("info", `已登录:${user?.name ?? account}(${user?.role ?? ""})`);
// 只在「从无到有」时广播:恢复会话会用服务端信息覆盖一次,那不算新登录
if (!hadUser && user) broadcastAuth(AUTH_EVENTS.login, user);
return { ok: true };
} catch (e) {
return { ok: false, message: `网络异常:${(e as Error)?.message ?? e}` };
} finally {
state.authBusy = false;
}
}
/**
* 登出。
*
* 通知后端是**尽力而为**:令牌已过期时这个请求本身就是必然 401,
* 但本地**必须**清干净 —— 否则用户会卡在「点了退出还是登录态」里,
* 只能手动清 localStorage。这里用 try/catch 而不是让 401 抛出来打断清理。
*/
async function logout() {
if (state.authBusy) return;
state.authBusy = true;
try {
await send("POST", "/api/auth/logout", {});
} catch {
// 后端不通不影响登出:本地清掉就等于登出了
} finally {
clearAuth();
state.authNotice = "";
state.authBusy = false;
// 广播放最后:监听者拿到事件时,登录态已经是干净的了
broadcastAuth(AUTH_EVENTS.logout);
pushLog("info", "已退出登录:本地令牌与用户信息已清空");
}
}
/**
* 演示账号清单(登录页直接列出来,省掉「翻文档找账号」这一步)。
*
* 走接口而不是写死在界面里是有意的:**真后端不会实现这个接口**,
* 那时这里返回空数组,登录页自动把整块收起来 ——
* 界面不需要知道「当前连的是 mock 还是真后端」。
*
* 用 `rawRequest` 而不是 `send`:这是一次探针调用,
* 失败是正常情况,不该在日志里刷一条 404 警告,也不该触发 401 处理。
*/
async function demoAccounts(): Promise<DemoAccount[]> {
try {
const result = await rawRequest<DemoAccount[]>("GET", "/api/auth/demo-accounts", undefined);
return result.code === 0 && Array.isArray(result.data) ? result.data : [];
} catch {
// 真后端没有这个接口 → 静默留空
return [];
}
}
/* --------------------------------------------------------- ctx 请求层 */
/**
* 请求层错误(**基础设施**故障,不是业务码)。
*
* 与宿主的 `HttpError` 同形:业务码非 0 **不抛错**(老系统的写法是
* `const {code,msg} = await api.add()`,抛错会让那套写法全部失效),
* 只有连不上、网关 5xx、响应不是 JSON 这类才抛。
*/
class PreviewHttpError extends Error {
constructor(public readonly status: number, message: string, public readonly url: string) {
super(message);
this.name = "PreviewHttpError";
}
}
/** 把参数对象拼成查询串,跳过空值(与宿主 `toQuery` 同规则) */
function toQuery(params?: Record<string, any>): string {
if (!params) return "";
const parts: string[] = [];
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null || value === "") continue;
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
return parts.length ? `?${parts.join("&")}` : "";
}
/**
* 发一个请求(不含 401 处理,见 `send`)。
*
* ## 与宿主 `src/core/http/index.ts` 的 `realRequest` 对齐
*
* | 情况 | 这里 | 宿主 |
* | ---- | ---- | ---- |
* | HTTP 401 | 归一成 `{code: 401}`,**不抛** | 同 |
* | 其它非 2xx | **抛** `PreviewHttpError` | 抛 `HttpError` |
* | 响应是包络 | 原样返回 | 同 |
* | 响应是裸数据 | 补成 `{code: 0, data}` | 同 |
*
* 老版本的预览桩子在这三处都不一样:HTTP 状态码直接当业务码、
* 把整个包络塞进 `data`(于是插件拿到的 `res.data.rows` 永远是 `undefined`)、
* 出错一律返回 `code: -1` 从不抛。结果是**预览里过得去的代码,到宿主里全是坑** ——
* 这里刻意改成同构。
*/
async function rawRequest<T = any>(method: string, url: string, payload: any): Promise<ApiResult<T>> {
const verb = (method || "GET").toUpperCase();
const finalUrl = verb === "GET" || verb === "DELETE" ? `${url}${toQuery(payload)}` : url;
const headers: Record<string, string> = {
"Content-Type": "application/json;charset=utf-8",
"Cache-Control": "no-cache",
};
// 未登录时**不带** Authorization 字段,而不是带一个空值 ——
// 某些网关对空的 `Authorization: ` 会直接拒请求(而不是当匿名)
const authorization = authHeaderOf();
if (authorization) headers.Authorization = authorization;
const res = await fetch(finalUrl, {
method: verb,
headers,
body: verb === "GET" || verb === "DELETE" ? undefined : JSON.stringify(payload ?? {}),
});
if (res.status === 401) {
return { code: UNAUTHORIZED_CODE, msg: "未登录或登录已过期", data: null as unknown as T };
}
if (!res.ok) {
throw new PreviewHttpError(res.status, `请求失败 ${res.status}:${url}`, url);
}
const text = await res.text();
let parsed: any = null;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new PreviewHttpError(res.status, `响应不是合法 JSON:${url}`, url);
}
// 真后端可能只返回裸数据(没有 code 包装),这里补齐成统一形状
if (parsed && typeof parsed === "object" && "code" in parsed) return parsed as ApiResult<T>;
return { code: 0, msg: "ok", data: parsed as T };
}
/**
* `ctx.http` 的入口:请求 + 统一的 401 处理。
*
* 401 是**唯一有副作用**的一种返回:清会话、提示、广播登出。
* **插件不需要为它写任何代码** —— 拿到 401 直接 return 即可,与宿主一致。
*/
async function send<T = any>(method: string, url: string, payload?: any): Promise<ApiResult<T>> {
const label = `http.${method.toLowerCase()}(${url})`;
try {
const result = await rawRequest<T>(method, url, payload);
if (result.code === UNAUTHORIZED_CODE) {
pushLog("warn", `${label} → 401`);
handleUnauthorized(result.msg);
} else {
pushLog("info", `${label} → code ${result.code}${result.code === 0 ? "(ok)" : `(${result.msg})`}`);
}
return result;
} catch (e) {
const err = e as PreviewHttpError;
pushLog("error", `${label} 失败:${err?.message ?? err}`);
throw e;
}
}
/** `ctx.http` 的四个方法。`payload` 对 GET/DELETE 是查询参数,对其它是请求体 */
const httpCall = (method: string, url: string, payload?: any) => send(method, url, payload);
/* ---------------------------------------------------------------- ctx */
function createCtx(): PluginCtx {
const ctx: PluginCtx = {
hostVersion: HOST_VERSION,
plugin: {
id: manifest.id,
name: manifest.name,
version: manifest.version,
kind: manifest.kind,
repository: manifest.repository,
checksum: manifest.checksum,
},
logger: {
debug: (...a: any[]) => pushLog("debug", a.map(safeStringify).join(" ")),
info: (...a: any[]) => pushLog("info", a.map(safeStringify).join(" ")),
warn: (...a: any[]) => pushLog("warn", a.map(safeStringify).join(" ")),
error: (...a: any[]) => pushLog("error", a.map(safeStringify).join(" ")),
},
storage,
http: {
// 与宿主 `PluginHttp` 同形:多一个 request(),给「method 是算出来的」场景用
request: (options: any) => {
const method = String(options?.method || "GET").toUpperCase();
const payload = method === "GET" || method === "DELETE" ? options?.params : options?.data;
return httpCall(method, options?.url, payload);
},
get: (url, params) => httpCall("GET", url, params),
post: (url, data) => httpCall("POST", url, data),
put: (url, data) => httpCall("PUT", url, data),
del: (url, params) => httpCall("DELETE", url, params),
},
ui: {
success: (m: string) => pushLog("ui", `success: ${m}`),
error: (m: string) => pushLog("ui", `error: ${m}`),
warning: (m: string) => pushLog("ui", `warning: ${m}`),
info: (m: string) => pushLog("ui", `info: ${m}`),
// 用浏览器原生弹窗:够真(会阻塞),也不必为此引入一套消息组件
confirm: async (m: string, title = "确认") => window.confirm(`${title}\n\n${m}`),
alert: async (m: string, title = "提示") => {
window.alert(`${title}\n\n${m}`);
},
},
/**
* 当前登录用户。**与宿主同口径**:直接返回会话里的那个用户对象,
* 未登录返回 `null`(而不是一个假的「预览用户」)——
* 插件据此做角色降级,预览里才能真的验到「普通用户看不到某个按钮」。
*
* 返回展开后的副本而不是原对象:调用方顺手改一下不该影响会话。
*/
getUser: () => (state.user ? { ...state.user } : null),
addMenu: (menu) => track(register(state.menus, menu)),
addRoute: (route) => track(register(state.routes, route)),
addWidget: (w) => track(register(state.widgets, w)),
addToolbarAction: (a) => track(register(state.toolbarActions, a)),
addSettingsSection: (s) => track(register(state.settingsSections, s)),
addViewModel: (model) => {
state.viewModels[model.name] = raw(model.target);
return track(() => {
delete state.viewModels[model.name];
});
},
getViewModel: (name) => state.viewModels[name],
addCommand: (command) => {
state.commands[command.name] = raw(command);
return track(() => {
delete state.commands[command.name];
});
},
getCommand: (name) => state.commands[name],
event: {
on: (name, handler) => track(on("local", name, handler)),
emit: (name, ...args) => emit("local", name, args),
onGlobal: (name, handler) => track(on("global", name, handler)),
emitGlobal: (name, ...args) => emit("global", name, args),
},
onDispose: (fn) => track(fn),
};
return ctx;
}
/* -------------------------------------------------------- 生命周期 */
/** 认领自注册队列里属于本插件的模块(真实宿主按 manifest.id 认领,这里同样) */
function claim(): PluginModule | null {
const i = pendingRegistrations.findIndex((r) => r?.manifest?.id === manifest.id);
if (i < 0) return null;
return pendingRegistrations.splice(i, 1)[0].module as PluginModule;
}
/** 探测自注册队列里都有谁 —— 认领失败时用来给出可执行的提示 */
function pendingIds(): string[] {
return pendingRegistrations.map((r) => String(r?.manifest?.id ?? "(无 id)"));
}
const installedFlag = `funjia-preview:meta:${manifest.id}:installed`;
let currentCtx: PluginCtx | null = null;
async function activate(module: PluginModule) {
// 重新启用前先清干净:真实宿主在禁用时已经回收过,这里保证同一语义
runDisposers();
clearRegistry();
const ctx = createCtx();
currentCtx = ctx;
state.error = "";
try {
// install 一辈子只跑一次 —— 用持久化标记模拟「首次装载」,与真实宿主同口径
if (localStorage.getItem(installedFlag) !== "1") {
await module.install?.(ctx);
localStorage.setItem(installedFlag, "1");
pushLog("info", "install 已执行(首次装载,标记已持久化:刷新或重新启用都不会再跑)");
}
await module.activate?.(ctx);
state.phase = "active";
state.activatedAt = now();
state.disposerCount = disposers.length;
pushLog(
"info",
`activate 完成:注册 ${state.menus.length} 菜单 / ${state.routes.length} 路由 / ` +
`${Object.keys(state.commands).length} 命令 / ${state.channels.length} 事件通道,` +
`${disposers.length} 个待回收项`
);
} catch (e) {
state.phase = "error";
state.error = String((e as Error)?.message ?? e);
pushLog("error", `activate 抛错:${state.error}`);
throw e;
}
}
async function deactivate(module?: PluginModule | null) {
if (module) {
try {
await module.deactivate?.(currentCtx as PluginCtx);
} catch (e) {
pushLog("error", `deactivate 抛错:${(e as Error)?.message ?? e}`);
}
}
runDisposers();
clearRegistry();
state.disposerCount = 0;
state.activatedAt = "";
state.phase = "idle";
pushLog("info", "已停用:菜单/路由/命令/事件监听全部回收(真实宿主在同一时机做同样的事)");
}
async function uninstall(module?: PluginModule | null) {
await deactivate(module);
if (module) {
try {
await module.uninstall?.(currentCtx as PluginCtx);
} catch (e) {
pushLog("error", `uninstall 抛错:${(e as Error)?.message ?? e}`);
}
}
clearStorage();
localStorage.removeItem(installedFlag);
pushLog("info", "已卸载:插件私有存储与 install 标记已清空(下次启用会重新走 install)");
}
/* ------------------------------------------------ 供预览界面调用 */
async function callCommand(name: string, args: any[]): Promise<CommandResult> {
const started = performance.now();
const command = state.commands[name];
if (!command) {
const ms = performance.now() - started;
pushLog("warn", `调用命令 ${name} 失败:未注册`);
return { ok: false, error: `命令 ${name} 未注册`, ms };
}
try {
const value = await command.handler(...args);
const ms = performance.now() - started;
pushLog("info", `调用命令 ${name} → ${safeStringify(value)}(${ms.toFixed(1)}ms)`);
return { ok: true, value, ms };
} catch (e) {
const ms = performance.now() - started;
const error = String((e as Error)?.message ?? e);
pushLog("error", `调用命令 ${name} 抛错:${error}`);
return { ok: false, error, ms };
}
}
function invokeLocal(name: string, args: any[]) {
emit("local", name, args);
}
function invokeGlobal(name: string, args: any[]) {
emit("global", name, args);
}
/* ---------------------------------------------- 补全 window.FunjiaHost */
// hostInfo 是 contract.ts 里那个**同一个对象引用**。这里只补字段,
// 不换对象 —— 插件若在模块求值时就把 window.FunjiaHost 存起来了,也能看到这些实现
Object.assign(hostInfo, {
name: HOST_NAME,
version: HOST_VERSION,
http: {
get: (url: string, params?: any) => httpCall("GET", url, params),
post: (url: string, data?: any) => httpCall("POST", url, data),
put: (url: string, data?: any) => httpCall("PUT", url, data),
del: (url: string, params?: any) => httpCall("DELETE", url, params),
},
getViewModel: (name: string) => state.viewModels[name],
// 与宿主 `FunjiaHost.getUser/isLoggedIn` 同名同义。给**没有 ctx** 的
// 裸脚本插件用(例如纯配置类插件),它们在预览里也要能判断登录态
getUser: () => (state.user ? { ...state.user } : null),
isLoggedIn: () => !!state.user,
stats: () => ({
menus: state.menus.length,
routes: state.routes.length,
widgets: state.widgets.length,
toolbarActions: state.toolbarActions.length,
settingsSections: state.settingsSections.length,
viewModels: Object.keys(state.viewModels).length,
commands: Object.keys(state.commands).length,
}),
});
return {
manifest,
state,
pushLog,
claim,
pendingIds,
activate,
deactivate,
uninstall,
callCommand,
invokeLocal,
invokeGlobal,
/* 登录态:预览界面用它渲染顶栏的登录区,插件页面靠 `ctx.getUser()` 读 */
login,
logout,
restoreSession,
demoAccounts,
clearLogs: () => {
state.logs = [];
state.events = [];
},
clearStorage,
syncStorageMirror,
};
}
export type PreviewHost = ReturnType<typeof createPreviewHost>;
+35
View File
@@ -0,0 +1,35 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>插件预览 · 源码模式</title>
<!--
⚠️ import map 必须**静态写在 head 里**,且排在第一个 module 脚本之前。
模块加载一旦开始,再插入 <script type="importmap"> 会被浏览器**静默忽略**
—— 不报错、不生效,症状是 ESM 产物里那句 `import { ref } from "vue"`
解析失败。import map 也没有「回退」语法,所以只声明一次、位置固定。
两个映射分别指向:
- vue → preview/runtime.ts(把预览页自己那份 Vue 原样再导出,保证同实例)
- funjiaui → preview/shims/funjiaui.ts(桩,见该文件顶部说明)
源码模式其实用不到它(源码由 Vite 处理裸说明符),但留着,
好让「源码模式 » 产物模式」的切换不依赖任何额外前提。
-->
<script type="importmap">
{
"imports": {
"vue": "/runtime.ts",
"funjiaui": "/shims/funjiaui.ts"
}
}
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="/main-source.ts"></script>
</body>
</html>
+195
View File
@@ -0,0 +1,195 @@
/**
* 「插件从哪来」的两种模式。
*
* | 模式 | 插件来源 | 回答的问题 | 快慢 |
* | ---- | -------- | ---------- | ---- |
* | `source` | `src/index.ts` 的静态 import | 我写的东西长什么样、逻辑对不对 | 改完即见(Vite 热更新) |
* | `artifact` | `dist/` 里的真实产物 | **交给宿主的那几个字节**能不能跑 | 要先 `npm run build` |
*
* 之所以两个都要,是因为它们会分别失败在不同的地方:
*
* - 源码模式跑得通、产物模式跑不通 → 问题在**构建配置**(`external` 没生效、
* 产物名不对、`output.globals` 映射错了、样式没抽出来);
* - 两个都跑通、宿主里不跑 → 问题在**仓库与装载链路**(路径、`checksum`、
* import map、`activation` 与 `contributes` 不匹配)。
*
* 这条分界线能省掉大量「到底哪一步坏了我」的排查时间,所以别只用一个模式。
*/
import type { PluginModule } from "../src/sdk";
import { pendingRegistrations } from "./contract";
/** `plugin.config.json` 的形状(只声明预览用得上的字段) */
export interface PluginConfig {
id: string;
name: string;
version: string;
kind: "iife" | "esm";
artifact: string;
style?: string;
globalKey?: string;
activation?: string;
[key: string]: any;
}
export interface LoadedPlugin {
module: PluginModule;
/** 装载过程中的说明,会写进预览的日志台 —— 让「怎么装载的」可见 */
notes: string[];
}
export interface PreviewLoader {
mode: "source" | "artifact";
/** 顶栏徽标上的短标签 */
label: string;
/** 一句话说明这个模式在验什么 */
hint: string;
/**
* 点「重新装载」时是不是该刷新页面。
*
* 源码模式:模块已经求值过(自注册被消费、模块内状态也变了),重新装载
* 最可靠的方式是刷新页面 —— 预览页启动很快,刷新几乎无感。
* 产物模式:重新拉一次产物即可,不必刷新。
*/
reloadPageOnRerun: boolean;
getModule(): Promise<LoadedPlugin>;
}
/* ------------------------------------------------------------ 工具 */
/**
* 用 `<script>` 加载产物 —— 与宿主装载 IIFE 插件的方式完全一致。
*
* `async = false` 是有意的:让脚本按插入顺序执行。这里只有一个脚本,
* 但不写会让「加载完成」与「执行完成」之间多一个不确定的间隙。
*/
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const el = document.createElement("script");
el.src = src;
el.async = false;
el.onload = () => resolve();
el.onerror = () =>
reject(
new Error(
`产物加载失败:${src}\n` +
"多半是还没构建 —— 跑一次 npm run build(或直接用 npm run preview,它会先构建)。"
)
);
document.head.appendChild(el);
});
}
/**
* 注入样式表,模拟宿主按 `manifest.style` 注入插件样式。
*
* 失败**不阻断**装载:样式拿不到插件逻辑照样能跑,真实宿主也是尽力注入。
* (但控制台里会留一条 404,能看出 `style` 字段写了却没产出对应文件。)
*/
function injectStyle(href: string): Promise<void> {
return new Promise((resolve) => {
const el = document.createElement("link");
el.rel = "stylesheet";
el.href = href;
el.onload = () => resolve();
el.onerror = () => resolve();
document.head.appendChild(el);
});
}
/** 从自注册队列里认领指定 id 的插件(真实宿主的认领动作,在此复刻) */
function claimById(id: string): PluginModule | null {
const i = pendingRegistrations.findIndex((r) => r?.manifest?.id === id);
if (i < 0) return null;
return pendingRegistrations.splice(i, 1)[0].module as PluginModule;
}
/* ------------------------------------------------------- 源码模式 */
/**
* 源码模式。
*
* 模块由调用方**静态 import** 并传进来 —— 这一点是必需的:只有静态依赖,
* Vite 的 HMR 依赖图里才有它,改 `pages/*.vue` 才能热更新;而且静态 import
* 的求值顺序受 import 声明控制,契约(`./contract`)能排在它前面先执行。
*/
export function createSourceLoader(module: PluginModule): PreviewLoader {
return {
mode: "source",
label: "源码",
hint: "直接跑 src/ 下的源码:改页面组件由 Vite 热更新,不走构建、不碰仓库",
reloadPageOnRerun: true,
async getModule() {
return {
module,
notes: ["模块来自 src/index.ts 的静态 import(契约已先于它求值,所以自注册不会落空)"],
};
},
};
}
/* ------------------------------------------------------- 产物模式 */
/**
* 产物模式:把 `dist/` 里的东西当远端插件装一遍。
*
* 每一步都刻意贴着宿主的真实动作:
*
* 1. 按 `manifest.style` 注入 CSS(宿主的做法);
* 2. `iife` → `<script src>`;`esm` → `import()`,裸说明符由 import map 解析;
* 3. 认领:先看自注册队列(`window.FunjiaPlugin.register`),再退回
* `window[globalKey]` —— 与宿主的两条认领通道一致。
*/
export function createArtifactLoader(config: PluginConfig): PreviewLoader {
return {
mode: "artifact",
label: "产物",
hint: "加载 dist/ 里的真实产物,走宿主装载时的同一套路径规则(能验 external 是否真的生效)",
reloadPageOnRerun: false,
async getModule() {
const notes: string[] = [];
// 每次装载都换一个查询串,避免浏览器把上一次的产物缓存住 ——
// 「重新装载还是旧行为」是最容易浪费时间的假象之一
const bust = `?t=${Date.now()}`;
if (config.style) {
await injectStyle(`/artifact/${config.style}`);
notes.push(`已按 manifest.style 注入 ${config.style}`);
}
if (config.kind === "esm") {
const mod = await import(/* @vite-ignore */ `/artifact/${config.artifact}${bust}`);
notes.push(
"以 ESM 形态 import():产物里的裸说明符 vue 由 index.html 的 import map 解析到预览页同一份 Vue"
);
const module = (mod as any).default ?? mod;
if (!module) throw new Error("ESM 产物没有默认导出,宿主会拿不到插件对象");
return { module, notes };
}
await loadScript(`/artifact/${config.artifact}${bust}`);
const claimed = claimById(config.id);
if (claimed) {
notes.push("产物自注册成功(window.FunjiaPlugin.register),按 id 认领");
return { module: claimed, notes };
}
const byGlobal = config.globalKey ? (window as any)[config.globalKey] : undefined;
if (byGlobal) {
notes.push(`走老生态通道 window.${config.globalKey} 认领`);
return { module: byGlobal, notes };
}
// 这条报错要尽量说清「是哪一环断了」——它对应宿主里那个
// 「脚本已执行,但自注册队列与全局变量都没拿到插件」的经典现场
throw new Error(
`产物已执行,但两条认领通道都没拿到插件:\n` +
` · 自注册队列里没有 id 为 "${config.id}" 的注册(检查 src/index.ts 里的 PLUGIN_ID)\n` +
` · window.${config.globalKey} 也是空的(检查 plugin.config.json 的 globalKey,` +
`以及产物是不是被打成了 namespace:window.X = { default: … })`
);
},
};
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 产物模式入口(`npm run preview`)。
*
* 与源码模式唯一的区别:**不 import `../src/index`**。
*
* 这里加载的是 `dist/` 里的真实产物(`/artifact/<产物名>`),走的是宿主装载
* 远端插件时的同一套路径规则:`<script src>` 加载 IIFE、`import()` 加载 ESM、
* 按 `manifest.style` 注入 CSS、再按 id 或全局名认领。
*
* 所以这个模式回答的问题很具体:**我交出去的产物,换台机器还能不能跑。**
* 源码跑得通但这里跑不通,就是构建配置的问题(external、产物名、globalKey…)。
*/
import "./contract"; // 契约仍然要装:产物自注册时需要有队列接住
import config from "../plugin.config.json";
import { mountPreview } from "./mount";
import { createArtifactLoader } from "./loaders";
import type { PluginConfig } from "./loaders";
mountPreview(config as PluginConfig, createArtifactLoader(config as PluginConfig));
+22
View File
@@ -0,0 +1,22 @@
/**
* 源码模式入口(`npm run dev`)。
*
* ⚠️ **import 的书写顺序就是执行顺序,不能调换:**
*
* 1. `./contract` —— 先把契约装上(`window.FunjiaPlugin` 的队列)
* 2. `../src/index` —— 插件源码求值,此时它的自注册才有地方落
*
* 调换的话会看到「找不到 window.FunjiaPlugin:本脚本必须由宿主页面加载」,
* 而真正的原因只是顺序 —— 这类误判(去查路径、CORS、缓存,绕一大圈)
* 正是预览器存在的意义之一:它把顺序固定下来,让环境问题不再伪装成代码问题。
*/
import "./contract"; // ① 必须是第一个
import pluginModule from "../src/index"; // ② 插件源码,在契约之后求值
import config from "../plugin.config.json";
import { mountPreview } from "./mount";
import { createSourceLoader } from "./loaders";
import type { PluginConfig } from "./loaders";
mountPreview(config as PluginConfig, createSourceLoader(pluginModule as any));
+498
View File
@@ -0,0 +1,498 @@
/**
* 预览器的最小后端(Vite 中间件)。
*
* ## 为什么预览器需要它
*
* 插件里最常见的功能就是「拉列表、存表单」。如果预览环境一律把 http 拦掉,
* 插件作者就只能看到一堆「被拦截」的日志 —— 页面渲染对不对能验,**功能对不对验不了**。
* 这个中间件让 `ctx.http.get("/api/device/list")` 在预览里真的能拿到数据。
*
* ## 它与宿主 mock 的关系
*
* 宿主自己也有一套 mock(`src/mock/`),跑在**浏览器内**、拦的是前端请求。
* 预览器是独立工程,拿不到那套代码(也不该依赖宿主源码),所以这里**重写一份**
* —— 但只重写「数据与路由」这层,契约里的关键定义与客户端共用,见下。
*
* 代价是两份实现可能漂移。因此约定:
*
* - **接口契约以宿主为准**,这里是它的**子集**(只实现最常用的几个);
* - 响应形状、`code` 取值、401 的语义**必须一致** —— 不一致就等于骗了插件作者;
* - 契约里那几个**线上跑的东西**(存储键、令牌形状、包络、请求头解析)
* 不在这份文件里重写,而是与客户端共用 `preview/api-contract.ts`;
* - 真后端就绪后,用 `PREVIEW_API_TARGET` 把 `/api` 代理过去,
* 这份 mock 自动让位(见 `vite.preview.config.ts`)。
*
* ## 401 与宿主对齐的地方
*
* 1. 未授权同时给 **HTTP 401** 和 **`code: 401`**(宿主 http 层认后者,
* 但真后端可能只给状态码,两边都给最稳);
* 2. `Authorization` 必须是 `Bearer <token>`,**严格校验前缀** ——
* 这样「请求层忘了加前缀」会在预览阶段暴露;
* 3. 登录接口用 `code: 1` 表达密码错误(业务失败),**不用 401**
* (401 的含义是「未授权」,会被上层当成「令牌失效」去清会话)。
*/
import type { IncomingMessage, ServerResponse } from "node:http";
import {
TOKEN_PREFIX,
TOKEN_TTL_MS,
UNAUTHORIZED_CODE,
parseAuthHeader,
type ApiResult,
type AuthUser,
} from "./api-contract";
/* ------------------------------------------------------------------ 类型 */
/** 用户表里的一行 = 对外的用户 + 密码(密码**绝不**出现在响应里) */
interface MockUser extends AuthUser {
password: string;
}
type Row = Record<string, any>;
/* ------------------------------------------------------------------ 数据 */
/** 与宿主 `src/mock/auth.ts` 的演示账号保持一致 */
const USERS: MockUser[] = [
{
id: 1,
account: "funjia",
password: "funjia123",
name: "管理员",
role: "超级管理员",
dept: "信息中心",
},
{
id: 2,
account: "viewer",
password: "viewer123",
name: "巡检员",
role: "普通用户",
dept: "运维组",
},
];
/**
* 种子数据:宿主 `src/mock/db.ts` 的一小部分。
*
* 刻意**不搬全**。预览要的是「有数据可看」,不是「数据与宿主逐行一致」;
* 搬全了一份 10 行的设备表反而会让这里变成第二个需要同步维护的地方。
*/
const SEED: Record<string, Row[]> = {
device: [
{ id: 1, code: "PC-2024-0001", name: "联想 ThinkCentre M720", category: "主机", brand: "联想", status: "在租", price: 1200, owner: "市政务服务中心信息科" },
{ id: 2, code: "MN-2024-0031", name: "AOC 24B1XH", category: "显示器", brand: "AOC", status: "在租", price: 300, owner: "市政务服务中心信息科" },
{ id: 3, code: "PC-2024-0007", name: "戴尔 OptiPlex 3080", category: "主机", brand: "戴尔", status: "闲置", price: 1100, owner: "" },
{ id: 4, code: "AIO-2024-0002", name: "惠普 ProOne 400 G6", category: "一体机", brand: "惠普", status: "维修中", price: 1600, owner: "第三实验中学" },
],
notice: [
{ id: 1, title: "租赁设备季度巡检安排", level: "重要", publisher: "运维组", content: "本季度巡检覆盖全部在租设备。" },
{ id: 2, title: "系统升级通知", level: "普通", publisher: "系统管理员", content: "本周六 22:00 升级,期间暂停服务约 30 分钟。" },
],
};
/* -------------------------------------------------------------- 响应助手 */
const ok = (data: any, total?: number): ApiResult => ({
code: 0,
msg: "ok",
data,
...(total === undefined ? {} : { total }),
});
const fail = (msg: string, code = 1): ApiResult => ({ code, msg, data: null });
const unauthorized = (reason: string): ApiResult => ({
code: UNAUTHORIZED_CODE,
msg: reason || "未登录或登录已过期",
data: null,
});
/* ------------------------------------------------------------------ 令牌 */
const toPublic = (user: MockUser): AuthUser => {
const { password: _password, ...rest } = user;
return rest;
};
function signToken(userId: number, ttl: number = TOKEN_TTL_MS): string {
const exp = Date.now() + ttl;
const nonce = Math.random().toString(36).slice(2, 10);
return `${TOKEN_PREFIX}.${userId}.${exp}.${nonce}`;
}
function verifyToken(token: string): { ok: true; user: AuthUser } | { ok: false; reason: string } {
const parts = String(token || "").split(".");
if (parts.length !== 4 || parts[0] !== TOKEN_PREFIX) {
return { ok: false, reason: "令牌格式不正确" };
}
const userId = Number(parts[1]);
const exp = Number(parts[2]);
if (!Number.isFinite(userId) || !Number.isFinite(exp)) {
return { ok: false, reason: "令牌格式不正确" };
}
if (Date.now() > exp) return { ok: false, reason: "登录状态已过期,请重新登录" };
const user = USERS.find((item) => item.id === userId);
if (!user) return { ok: false, reason: "令牌对应的用户不存在" };
return { ok: true, user: toPublic(user) };
}
/* ------------------------------------------------------------------ 请求 */
function readBody(req: IncomingMessage): Promise<any> {
return new Promise((resolve) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
// 1MB 上限:预览后端不该被一个大 body 拖死
if (raw.length > 1024 * 1024) raw = raw.slice(0, 1024 * 1024);
});
req.on("end", () => {
try {
resolve(raw ? JSON.parse(raw) : {});
} catch {
resolve({});
}
});
req.on("error", () => resolve({}));
});
}
/* ------------------------------------------------------------------ SN 码 */
/**
* SN 码的预览后端(对应宿主后端的 `api::sn-code` 模块)。
*
* ## 为什么模板里要额外带这一段
*
* 模板自带的通用 CRUD 只覆盖 `/api/<name>/list|detail|add|update|delete`,
* 而「标签打印」插件的核心增量能力是**可选接入 SN 码接口** —— 少了这一段,
* `npm run dev` 里一打开「② SN 码」开关就是 404,本地根本验不了,
* 只能构建 → 发布 → 装进宿主 → 点一遍,一圈几分钟。
*
* ## 与真后端的关系
*
* 参数口径(`targetType` / `count` / `refId` / `refLabel` / `remark`、返回
* `{ items }`、校验返回 `{ valid, reason, exists, record }`)**照着真后端抄**,
* 但**数据是进程内的**、格式里的校验位算法也是这里自己定的 ——
* 所以:**别看号段,只验链路**。真要对接,关掉开关或设 `PREVIEW_API_TARGET`。
*/
/** 业务类型 → 号段前缀。真后端同结构,前缀值以真后端 `/meta` 为准 */
const SN_PREFIX: Record<string, string> = {
DEVICE: "ZP",
PART: "PJ",
LEASE: "ZL",
MAINTENANCE: "SH",
CUSTOMER: "KH",
OTHER: "SN",
};
/** 校验位:body 各字符按 31 进制滚动求和后取模 36,映射到 0-9A-Z */
function snChecksum(body: string): string {
let sum = 0;
for (let i = 0; i < body.length; i += 1) {
sum = (sum * 31 + body.charCodeAt(i)) % 36;
}
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[sum];
}
function makeSn(targetType: string, seq: number): string {
const pad = (n: number) => String(n).padStart(2, "0");
const now = new Date();
const prefix = SN_PREFIX[targetType] || "SN";
const body = `${prefix}-${String(now.getFullYear()).slice(2)}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${String(seq).padStart(4, "0")}`;
return `${body}-${snChecksum(body)}`;
}
function issueSn(ledger: Row[], body: any, count: number): Row[] {
const targetType = String(body?.targetType || "DEVICE");
const batch = `B${Date.now().toString(36).toUpperCase()}`;
const out: Row[] = [];
for (let i = 0; i < count; i += 1) {
const sn = makeSn(targetType, ledger.length + 1);
const row: Row = {
sn,
targetType,
batch,
status: "ISSUED",
issuedAt: new Date().toISOString(),
...(body?.refId ? { refId: body.refId } : {}),
...(body?.refLabel ? { refLabel: body.refLabel } : {}),
...(body?.remark ? { remark: body.remark } : {}),
};
ledger.push(row);
out.push(row);
}
return out;
}
/** 命中 `/api/sn-codes*` 时返回结果;不命中返回 null,交回通用流程 */
function handleSnCode(
method: string,
path: string,
query: Record<string, string>,
body: any,
store: Record<string, Row[]>
): ApiResult | null {
if (path !== "/api/sn-codes" && !path.startsWith("/api/sn-codes/")) return null;
if (!store.__sn) store.__sn = [];
const ledger = store.__sn;
if (method === "GET" && path === "/api/sn-codes/meta") {
return ok({
targetTypes: Object.keys(SN_PREFIX),
defaultPrefix: SN_PREFIX,
typicalLength: 15,
maxLength: 16,
});
}
if (method === "POST" && path === "/api/sn-codes/generate") {
return ok(issueSn(ledger, body, 1)[0]);
}
if (method === "POST" && path === "/api/sn-codes/batch") {
const count = Math.min(Math.max(1, Number(body?.count) || 1), 200);
const items = issueSn(ledger, body, count);
return ok({ items, batch: items[0]?.batch });
}
if (method === "POST" && path === "/api/sn-codes/verify") {
const text = String(body?.sn || "").trim();
if (!text) return ok({ valid: false, reason: "EMPTY" });
const matched = text.match(/^([A-Z]{2})-(\d{6})-(\d{4})-([0-9A-Z])$/);
if (!matched) return ok({ valid: false, reason: "FORMAT" });
if (snChecksum(`${matched[1]}-${matched[2]}-${matched[3]}`) !== matched[4]) {
return ok({ valid: false, reason: "CHECKSUM" });
}
const record = ledger.find((row) => row.sn === text) || null;
return ok({ valid: true, exists: !!record, record });
}
if (method === "GET" && path === "/api/sn-codes") {
const pageSize = Number(query.pageSize) || 50;
let rows = ledger.slice();
for (const key of ["targetType", "status", "batch"] as const) {
if (query[key]) rows = rows.filter((row) => String(row[key]) === query[key]);
}
if (query.sn) rows = rows.filter((row) => String(row.sn).includes(query.sn));
// 看最新发放的在前,和真后端一致
rows = rows.slice().reverse();
return ok(rows.slice(0, pageSize), rows.length);
}
const voided = path.match(/^\/api\/sn-codes\/([^/]+)\/void$/);
if (method === "POST" && voided) {
const target = ledger.find((row) => row.sn === decodeURIComponent(voided[1]));
if (!target) return fail("SN 不存在");
target.status = "VOID";
target.voidedAt = new Date().toISOString();
return ok(target);
}
return null;
}
/* ------------------------------------------------------------------ 路由 */
/**
* 路由分发。
*
* `store` 由调用方传进来(而不是读模块级的变量):数据必须**每个预览进程一份**,
* 且要能被 `createPreviewApi()` 的闭包持有 —— 写成模块级单例的话,
* 多次创建中间件会共用一份脏数据。
*/
function handle(
method: string,
path: string,
query: Record<string, string>,
body: any,
store: Record<string, Row[]>,
authorization?: string
): ApiResult {
/* ---- 免登录 ---- */
if (method === "POST" && path === "/api/auth/login") {
const user = USERS.find(
(item) => item.account === String(body.account || "").trim() && item.password === body.password
);
if (!user) return fail("账号或密码不正确");
return ok({
token: signToken(user.id),
expiresIn: Math.floor(TOKEN_TTL_MS / 1000),
user: toPublic(user),
});
}
// 登出幂等且免登录:令牌已过期时也必须能登出,否则用户卡在跳不出去的状态
if (method === "POST" && path === "/api/auth/logout") return ok(true);
if (method === "GET" && path === "/api/auth/demo-accounts") {
return ok(USERS.map((u) => ({ account: u.account, password: u.password, role: u.role })));
}
/* ---- 鉴权闸门:以下一律要求合法令牌 ---- */
const parsed = parseAuthHeader(authorization);
if (parsed.reason) return unauthorized(parsed.reason);
const auth = verifyToken(parsed.token);
if (!auth.ok) return unauthorized(auth.reason);
if (method === "GET" && path === "/api/auth/me") return ok(auth.user);
/* ---- SN 码:插件专属接口,优先于通用 CRUD 匹配 ---- */
const snResult = handleSnCode(method, path, query, body, store);
if (snResult) return snResult;
/* ---- 通用 CRUD ---- */
const crud = path.match(/^\/api\/([\w-]+)\/(list|detail|add|update|delete)$/);
if (crud) {
const [, name, action] = crud;
// 集合不存在就就地创建:宿主也是这个行为(`collection()` 动态建表),
// 于是插件自带的数据表不需要先在种子里登记
if (!store[name]) store[name] = [];
const storeRows = store[name];
if (action === "list") {
const page = Number(query.page) || 1;
const pageSize = Number(query.pageSize) || 10;
const keyword = (query.keyword || "").trim().toLowerCase();
/**
* 保留字不参与等值过滤。
*
* `userId` / `pluginId` 尤其要注意:宿主会给插件请求自动附加这两个归属参数
* (见宿主 mock 的同名路由),把它们当业务字段去等值过滤会**永远筛出空集**,
* 而症状是「列表页一个插件都查不到数据」—— 很难往参数名上想。
*/
const RESERVED = ["page", "pageSize", "keyword", "userId", "pluginId"];
let matched = storeRows.slice();
for (const [key, value] of Object.entries(query)) {
if (RESERVED.includes(key)) continue;
if (value === undefined || value === null || value === "") continue;
matched = matched.filter((row) => String(row[key]) === String(value));
}
if (keyword) {
// 关键字按**第一行的字段名**搜(与宿主 `db.query` 的默认 keywordFields 一致),
// 而不是按每一行自己的字段 —— 否则字段不齐的行会搜出不一样的结果
const fields = Object.keys(matched[0] || {});
matched = matched.filter((row) =>
fields.some((field) => String((row as Row)[field] ?? "").toLowerCase().includes(keyword))
);
}
const start = (page - 1) * pageSize;
// 列表的 `data` 是**数组本身**,条数是同级的 `total` —— 与宿主一致。
// (写成 `data: { rows, total }` 是最常见的抄错,插件那边会永远拿不到行)
return ok(matched.slice(start, start + pageSize), matched.length);
}
if (action === "detail") {
return ok(storeRows.find((row) => String(row.id) === String(query.id)) || null);
}
if (action === "add") {
const nextId = storeRows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0) + 1;
const row: Row = { ...body, id: nextId, createdAt: new Date().toISOString() };
storeRows.push(row);
return ok(row);
}
if (action === "update") {
const index = storeRows.findIndex((row) => String(row.id) === String(body.id));
if (index < 0) return fail("记录不存在");
storeRows[index] = { ...storeRows[index], ...body };
return ok(storeRows[index]);
}
if (action === "delete") {
const raw = body.ids !== undefined ? body.ids : body.id;
const ids = (Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]).map(String);
if (!ids.length) return fail("没有指定要删除的记录");
const before = storeRows.length;
// 整体替换而不是原地 splice:保持「store 里的数组对象」这一层的稳定性,
// detail/update 拿到的是同一份引用,语义简单
store[name] = storeRows.filter((row) => !ids.includes(String(row.id)));
return ok(before - store[name].length);
}
}
// 明确报「没有这个接口」而不是静默 404 —— 插件作者一眼就知道是路径写错了,
// 而不是后端挂了
return fail(`预览后端没有这个接口:${method} ${path}(实现见 preview/mock-api.ts)`, 404);
}
/* ------------------------------------------------------------------ 出口 */
/**
* 创建中间件。数据存在闭包里,**进程重启即重置**(预览不需要持久化)。
*/
export function createPreviewApi() {
// 深拷贝:种子数据不该被请求改到,否则第二次装载就看到脏数据了
const store: Record<string, Row[]> = JSON.parse(JSON.stringify(SEED));
/**
* 已经提醒过的空集合名。
*
* 通用 CRUD 会**动态创建**没见过的集合(宿主同行为),于是表名打错
* (`/api/devices/list` 而种子是 `device`)的表现是「接口成功、列表是空的」——
* 看起来像「没数据」,不像「表名错了」。
*
* 响应**不动**(那是契约,宿主也是这么答的),只在预览服务端的终端里提醒一句:
* 那里正是开发者跑 `npm run dev` 时盯着的窗口。用 Set 去重,只提醒一次。
*/
const warned = new Set<string>();
const seedKeys = new Set(Object.keys(SEED));
function warnIfUnknownCollection(path: string) {
const match = path.match(/^\/api\/([\w-]+)\/(list|detail)$/);
if (!match) return;
const [, name] = match;
if (seedKeys.has(name) || warned.has(name)) return;
warned.add(name);
console.warn(
`\n \x1b[33m[preview]\x1b[0m 集合 \`${name}\` 不在预览种子里,已自动建成空表(宿主也是这样)。` +
`\n 如果你以为它有数据,先检查表名拼写;种子里现有:${[...seedKeys].join(" / ")}\n`
);
}
return async function previewApiMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: (err?: any) => void
): Promise<void> {
const rawUrl = req.url || "/";
const path = rawUrl.split("?")[0];
if (!path.startsWith("/api/")) return next();
const query: Record<string, string> = {};
for (const [key, value] of new URL(rawUrl, "http://127.0.0.1").searchParams) {
query[key] = value;
}
const method = (req.method || "GET").toUpperCase();
const body = method === "GET" ? {} : await readBody(req);
if (method === "GET") warnIfUnknownCollection(path);
let result: ApiResult;
try {
result = handle(method, path, query, body, store, req.headers.authorization);
} catch (error) {
result = fail(`预览后端内部错误:${(error as Error)?.message ?? error}`, 500);
}
// 未授权同时给 HTTP 状态码与业务码:真后端可能只给其一,
// 两边都给能让预览的行为最接近「两种后端都试过」
res.statusCode = result.code === UNAUTHORIZED_CODE ? UNAUTHORIZED_CODE : 200;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.setHeader("Cache-Control", "no-store");
res.end(JSON.stringify(result));
};
}
+59
View File
@@ -0,0 +1,59 @@
/**
* 预览页的挂载入口 —— 两个 entry(源码 / 产物)共用这一份。
*
* 这里做的事,对应真实宿主 `main.ts` 里的同一批步骤:装 Element Plus、
* 注册图标、创建宿主、挂载界面。差别只在「宿主是谁」。
*/
import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as Icons from "@element-plus/icons-vue";
import App from "./App.vue";
import "./style.css";
import { createPreviewHost, type PreviewManifest } from "./host";
import * as apiContract from "./api-contract";
import type { PluginConfig, PreviewLoader } from "./loaders";
export function mountPreview(config: PluginConfig, loader: PreviewLoader): void {
const manifest: PreviewManifest = {
id: config.id,
name: config.name,
version: config.version,
kind: config.kind,
activation: config.activation,
/**
* `repository` / `checksum` 刻意留空。
*
* 预览不是从仓库装的,对应的是真实宿主里「手工填 URL 安装」那一种情形 ——
* 而 `ctx.plugin.repository` 有没有值,本身就是插件判断自己来源的判据
* (`demo.repo-badge` 就靠它显示「来自仓库」)。
* 所以:**依赖 `repository` 的分支在预览里走不到**,这是已知且刻意的差异,
* 界面顶部也会标出来。
*/
repository: undefined,
checksum: undefined,
};
const host = createPreviewHost(manifest);
const app = createApp(App, { host, loader, config });
app.use(ElementPlus);
// 图标全量注册,与宿主一致 —— 插件的 menuIcon: "Star" 在预览里才显示得出来
for (const [name, component] of Object.entries(Icons)) {
app.component(name, component as any);
}
app.mount("#app");
document.title = `插件预览 · ${config.name}(${loader.label}模式)`;
// 顺手挂到 window 上:卡住的时候可以直接在控制台里手玩
//
// `apiContract` 也一起挂出来,是为了让**排查与自动化脚本**能读到契约常量
// (存储键、401 的业务码…),而不是在几处各写一遍字面量 ——
// 写错了不会有任何编译错误,只会让脚本「查了一个错的键」然后静默通过。
(window as any).__preview__ = { host, manifest, config, loader, apiContract };
}
+27
View File
@@ -0,0 +1,27 @@
/**
* ESM 产物在预览环境里的 `vue` 解析目标。
*
* `preview/index.html` 的 import map 把裸说明符 `vue` 指到这里。ESM 产物里
* 保留着 `import { ref } from "vue"` 这样的裸说明符(rollup 的 `output.globals`
* 对 ESM 无效),浏览器不认识它,必须由 import map 指到一个真实 URL。
*
* ```js
* // 产物里(没被改写)
* import { defineComponent, ref } from "vue";
* ```
*
* ## 为什么是 `export * from "vue"` 而不是指向别处
*
* 预览页自己已经加载了一份 Vue(`main.ts` 里 `createApp`)。本文件把**同一份**
* 重新导出,于是产物拿到的 Vue 和预览页用的是同一个实例 —— 这正是宿主
* `funjia-runtime.js` 存在的理由,只是预览环境里它的作用域小得多。
*
* 如果这里换成另一份 Vue(比如让产物自带、或从这里 import 一个别的副本),
* 症状是**页面画得出来但完全点不动** —— 事件与响应式不在同一个依赖图里。
* 所以这个文件只有一行,且不要动。
*
* > 注意 `export *` 不导出 `default`。宿主那份 runtime 也是同样写法,
* > 插件应当用具名导入(`import { ref } from "vue"`),这一点与宿主一致。
*/
export * from "vue";
+164
View File
@@ -0,0 +1,164 @@
/**
* 预览环境里的 `funjiaui` 替身。
*
* ## 先讲清楚它不是什么
*
* **它不是 FunjiaUI。** 预览服务器只装了 Vue 和 Element Plus —— FunjiaUI 是
* 宿主的私有依赖(`git+…#v1.4.0` 那种),插件工程没有理由依赖它,预览也不该
* 为了它把安装成本抬上去。所以这里是一组桩:**保证 import 成功、装饰器调用
* 不崩、占位可见**,但不会产生任何真实表格/表单行为。
*
* 于是有一条你得记住的边界:
*
* > 预览里能跑通 ≠ 宿主里一定能跑通。
* > 预览回答的是「我写的这些东西长什么样」,用到 FunjiaUI 深水区
* > (`UmTable` 的列配置、远程配置类、装饰器元数据)的行为仍然要在宿主里验一遍。
*
* ## 两条通道,两个实现
*
* | 通道 | 谁在用 | 实现 |
* | ---- | ------ | ---- |
* | ESM 具名导入 `import { UmTable } from "funjiaui"` | `kind: esm` 的产物 | 本文件的静态导出 |
* | 全局取用 `window.funjiaui.UmTable` | `kind: iife` 的产物 | `createFunjiauiFallback()` 的 Proxy |
*
* ESM 必须有**静态具名导出**(浏览器要能在实例化阶段解析出每一个名字),所以
* 下面是一个个列出来的,不能用循环生成。IIFE 走 Proxy,任意名字都能兜住,
* 代价是拿到的东西一律是「装饰器桩」形态(能当装饰器、能当函数调,不能当组件渲染)。
*
* 如果你 import 了一个下面没列的名字,`npm run verify` 会指出来让你补 ——
* 这样桩和实际用法不会悄悄脱节。
*/
import { defineComponent, h } from "vue";
/* ------------------------------------------------------------ 组件桩 */
const STUB_STYLE = {
border: "1px dashed #e6a23c",
borderRadius: "6px",
padding: "8px 10px",
margin: "4px 0",
background: "#fdf6ec",
color: "#a06d1f",
fontSize: "12px",
lineHeight: "1.6",
};
/**
* 把组件渲染成一块显眼的占位。
*
* 刻意做得「丑且明显」—— 它必须和真实界面区分得开,否则会出现
* 「预览里看着挺正常,装到宿主里发现完全不是这回事」这种最坏的情况。
*/
function stubComponent(name: string) {
return defineComponent({
name,
inheritAttrs: false,
setup(_props, { slots }) {
return () =>
h("div", { style: STUB_STYLE, "data-funjiaui-stub": name }, [
`[预览桩] funjiaui.${name} —— 真实渲染要在宿主里看`,
slots.default ? h("div", { style: { marginTop: "4px", opacity: "0.75" } }, slots.default()) : null,
]);
},
});
}
export const AreaTree = stubComponent("AreaTree");
export const Iconfont = stubComponent("Iconfont");
export const UmByClass = stubComponent("UmByClass");
export const UmByClassEnhance = stubComponent("UmByClassEnhance");
export const UmColumnRender = stubComponent("UmColumnRender");
export const UmDialog = stubComponent("UmDialog");
export const UmDistrictTree = stubComponent("UmDistrictTree");
export const UmDistrictTreeNode = stubComponent("UmDistrictTreeNode");
export const UmPagination = stubComponent("UmPagination");
export const UmRemoteClass = stubComponent("UmRemoteClass");
export const UmSearchForm = stubComponent("UmSearchForm");
export const UmSyncNodeForm = stubComponent("UmSyncNodeForm");
export const UmTable = stubComponent("UmTable");
export const UmTableColumn = stubComponent("UmTableColumn");
export const UmTableDialog = stubComponent("UmTableDialog");
export const UmTableForm = stubComponent("UmTableForm");
export const UmTableOperate = stubComponent("UmTableOperate");
export const UmTableToolbar = stubComponent("UmTableToolbar");
export const UmTree = stubComponent("UmTree");
export const UmTreeSelect = stubComponent("UmTreeSelect");
/* ---------------------------------------------------------- 装饰器桩 */
/**
* 装饰器桩:要同时吃得下两种写法。
*
* ```ts
* class X { @TableColumnPropertyDecorator({ title: "编号" }) code = "" }
* class Y { @TableColumnPropertyDecorator code = "" }
* ```
*
* 判据是「参数里有没有『类/原型 + 字符串属性名』」—— 有就是被当成装饰器直接调用了。
* 工厂形式先收到一份配置对象,此时返回**自身**,等下一次调用落到直用分支,
* 于是两种写法都不会抛 `… is not a function`。
*
* 配置类插件的**定义期**就执行装饰器,所以这里一旦崩,整个插件模块都求值不了 ——
* 表现是「脚本已执行但没拿到插件」,极容易误判成路径问题。这就是为什么它必须够宽容。
*/
function stubDecorator(...args: any[]): any {
const looksLikeDecoratorCall =
args.length >= 2 &&
(typeof args[0] === "function" || (typeof args[0] === "object" && args[0] !== null)) &&
typeof args[1] === "string";
if (looksLikeDecoratorCall) return args[2];
return stubDecorator;
}
export const TableColumnMethodDecorator = stubDecorator;
export const TableColumnPropertyDecorator = stubDecorator;
export const TableFormColumnPropertyDecorator = stubDecorator;
export const TableSearchFormPropertyDecorator = stubDecorator;
/* -------------------------------------------------------- 常量与工具 */
export const DEFAULT_DEFER_TYPES: any[] = [];
export const EVENT_PHASES: any[] = [];
export const FIXED_VALUES: any[] = [];
export const SAFE_SCRIPT_PATH = "";
/** 纯函数居多,给个「形状对得上」的空实现,够插件在预览里跑通非 UI 流程 */
export const toGlobalKey = (name: string): string => String(name).replace(/[^A-Za-z0-9_$]/g, "_");
export const normalizeFieldName = (name: string): string => String(name);
export const transformFields = (..._args: any[]): Record<string, any> => ({});
export const collectClassMembers = (..._args: any[]): any[] => [];
export const collectDataColumns = (..._args: any[]): any[] => [];
export const collectOperateGroups = (..._args: any[]): any[] => [];
export const collectToolbar = (..._args: any[]): any[] => [];
export const collectTypedTasks = (..._args: any[]): any[] => [];
export const sortTasksByPriority = (..._args: any[]): any[] => [];
export const buildOperateColumn = (..._args: any[]): any => null;
export const resolveScriptUrl = (..._args: any[]): string => "";
export const loadRemoteScript = async (..._args: any[]): Promise<void> => undefined;
export const clearRemoteScript = (): void => undefined;
/* ------------------------------------------------------ Proxy 兜底 */
/**
* `window.funjiaui` 的兜底实现(给 IIFE 插件用)。
*
* Proxy 能兜住**任意**名字,所以老插件里那些没被上面列全的 API 也不会抛错。
* 局限要说清楚:取到的值统一是「装饰器桩」形态 —— 当装饰器用没问题,
* 当组件渲染不行(组件需要 `render`/`setup`,不是普通函数)。
* 真遇到这种插件,就在上面补一个具名 `stubComponent`。
*/
export function createFunjiauiFallback(): any {
const cache = new Map<string, any>();
return new Proxy(
{ __previewStub: true },
{
get(_target, key) {
if (typeof key === "symbol") return undefined;
if (!cache.has(key)) cache.set(key, stubDecorator);
return cache.get(key);
},
has: () => true,
}
);
}
+534
View File
@@ -0,0 +1,534 @@
/**
* 预览界面的样式。
*
* 只作用于预览页本身,**不进插件产物** —— `preview/` 目录不参与
* `vite.config.ts` 的 lib 构建,所以这里的任何东西都不会被发布出去。
*
* 类名统一 `pv-` 前缀,避免与插件自己的样式(`hello-page__xxx` 那类)撞车 ——
* 预览里两者是同一个页面,撞了会很难判断问题在哪一边。
*/
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
height: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
font-size: 13px;
color: #1f2329;
background: #f5f7fa;
}
#app {
height: 100%;
}
.pv {
height: 100%;
display: flex;
flex-direction: column;
}
/* ------------------------------------------------------------- 顶栏 */
.pv-top {
flex: none;
background: #fff;
border-bottom: 1px solid #e4e7ed;
padding: 10px 16px 12px;
}
.pv-top__line {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.pv-top__line + .pv-top__line {
margin-top: 6px;
}
.pv-top__name {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.pv-top__id {
font-size: 12px;
color: #6b7280;
background: #f3f4f6;
border-radius: 4px;
padding: 1px 6px;
}
.pv-top__meta {
font-size: 12px;
color: #6b7280;
}
.pv-top__meta > span:not(:last-child)::after {
content: "·";
margin-left: 8px;
color: #d0d5dd;
}
.pv-top__time {
font-size: 12px;
color: #9aa1ac;
}
.pv-top__warn {
color: #b07d1f;
}
.pv-top__ops {
gap: 10px;
}
.pv-hint {
flex: none;
margin: 0;
padding: 6px 16px;
background: #f0f6ff;
border-bottom: 1px solid #e4e7ed;
color: #4b5563;
font-size: 12px;
}
/* ---------------------------------------------------------- 提示条 */
.pv-alert {
flex: none;
margin: 8px 16px 0;
width: auto;
}
/* ------------------------------------------------------ 主体两栏 */
.pv-body {
flex: 1;
min-height: 0;
display: flex;
gap: 12px;
padding: 12px 16px;
overflow: hidden;
}
.pv-side {
flex: none;
width: 232px;
overflow: auto;
background: #fff;
border: 1px solid #e4e7ed;
border-radius: 6px;
padding: 8px 10px 12px;
}
.pv-side section + section {
margin-top: 14px;
}
.pv-side h3 {
margin: 0 0 6px;
font-size: 12px;
font-weight: 600;
color: #4b5563;
}
.pv-side h3 em {
font-style: normal;
color: #9aa1ac;
font-weight: 400;
}
.pv-list {
margin: 0;
padding: 0;
list-style: none;
}
.pv-list li {
padding: 5px 8px;
border-radius: 4px;
cursor: pointer;
display: flex;
flex-direction: column;
gap: 1px;
line-height: 1.4;
}
.pv-list li:hover {
background: #f5f7fa;
}
.pv-list li.is-active {
background: #ecf5ff;
}
.pv-list__title {
font-weight: 500;
}
.pv-list li code {
font-size: 11px;
color: #9aa1ac;
}
.pv-list__empty {
cursor: default;
color: #b6bcc6;
font-size: 12px;
padding: 4px 8px;
}
.pv-list__empty:hover {
background: transparent;
}
.pv-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 12px;
overflow: auto;
}
.pv-stage {
background: #fff;
border: 1px solid #e4e7ed;
border-radius: 6px;
}
.pv-stage__body {
padding: 14px;
}
/* 命令台不跟着页面一起长高,给它一个自己的滚动区 */
.pv-stage--cmd .pv-cmd__result {
max-height: 200px;
overflow: auto;
}
.pv-bar {
display: flex;
align-items: center;
gap: 10px;
padding: 7px 12px;
border-bottom: 1px solid #eef1f5;
background: #fafbfc;
border-radius: 6px 6px 0 0;
font-size: 12px;
}
.pv-bar__label {
font-weight: 600;
color: #4b5563;
}
.pv-bar code {
color: #6b7280;
}
.pv-bar .el-button {
margin-left: auto;
}
.pv-muted {
color: #9aa1ac;
font-size: 12px;
}
.pv-empty {
color: #9aa1ac;
padding: 28px 12px;
text-align: center;
line-height: 1.9;
}
.pv-empty p {
margin: 0;
}
.pv-empty code {
background: #f3f4f6;
border-radius: 3px;
padding: 1px 5px;
}
/* ------------------------------------------------------------ 命令台 */
.pv-cmd__form {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 10px 12px;
}
.pv-cmd__result {
margin: 0 12px 8px;
padding: 10px 12px;
background: #f7f8fa;
border: 1px solid #eef1f5;
border-radius: 5px;
font-family: Consolas, Menlo, monospace;
font-size: 12px;
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
color: #1f2329;
}
.pv-cmd__result.is-error {
background: #fef0f0;
border-color: #fde2e2;
color: #c0392b;
}
.pv-cmd__ms {
padding: 0 12px 10px;
font-size: 11px;
color: #9aa1ac;
}
/* ------------------------------------------------------------ 底部 */
.pv-bottom {
flex: none;
height: 33vh;
display: flex;
flex-direction: column;
background: #fff;
border-top: 1px solid #e4e7ed;
padding: 0 16px;
overflow: hidden;
}
/* el-tabs 的内容区要能自己滚,否则日志长了会把整个页面顶长 */
.pv-bottom > .el-tabs__header {
margin: 0 0 6px;
}
.pv-bottom .el-tabs__content {
flex: 1;
min-height: 0;
overflow: auto;
}
.pv-bottom .el-tab-pane {
height: 100%;
display: flex;
flex-direction: column;
}
.pv-bottom .el-tabs__item em {
font-style: normal;
color: #9aa1ac;
font-size: 11px;
margin-left: 4px;
}
/* ------------------------------------------------------- 日志/事件台 */
.pv-lines {
flex: 1;
min-height: 0;
overflow: auto;
font-family: Consolas, Menlo, monospace;
font-size: 12px;
line-height: 1.75;
padding: 4px 0 10px;
}
.pv-line {
display: flex;
gap: 8px;
padding: 1px 4px;
border-radius: 3px;
}
.pv-line:hover {
background: #f7f8fa;
}
.pv-line__time {
flex: none;
color: #b6bcc6;
}
.pv-line__tag {
flex: none;
width: 42px;
text-align: center;
border-radius: 3px;
font-size: 11px;
line-height: 18px;
height: 18px;
background: #eef1f5;
color: #6b7280;
}
.pv-line__text {
min-width: 0;
word-break: break-word;
white-space: pre-wrap;
}
.pv-line.is-debug {
color: #9aa1ac;
}
.pv-line.is-info .pv-line__tag {
background: #ecf5ff;
color: #337ecc;
}
.pv-line.is-warn .pv-line__tag {
background: #fdf6ec;
color: #b07d1f;
}
.pv-line.is-warn .pv-line__text {
color: #a06d1f;
}
.pv-line.is-error .pv-line__tag {
background: #fef0f0;
color: #c0392b;
}
.pv-line.is-error .pv-line__text {
color: #c0392b;
}
.pv-line.is-ui .pv-line__tag {
background: #f0f9eb;
color: #529b2e;
}
.pv-line.is-event .pv-line__tag {
background: #f4f0ff;
color: #6b4fc4;
}
.pv-line__empty {
color: #b6bcc6;
padding: 6px 4px;
}
/* ------------------------------------------------------------ 扩展点 */
.pv-ext {
display: flex;
gap: 24px;
padding: 6px 2px 12px;
}
.pv-ext__col {
flex: 1;
min-width: 0;
}
.pv-ext h4 {
margin: 12px 0 4px;
font-size: 12px;
font-weight: 600;
color: #4b5563;
}
.pv-ext h4 em {
font-style: normal;
color: #9aa1ac;
font-weight: 400;
}
.pv-ext ul {
margin: 0;
padding-left: 18px;
color: #4b5563;
line-height: 1.8;
}
.pv-note {
margin: 4px 0 0;
color: #6b7280;
font-size: 12px;
line-height: 1.8;
}
.pv-note code {
background: #f3f4f6;
border-radius: 3px;
padding: 1px 4px;
}
/* ---------------------------------------------------------- 登录区 */
/* 顶栏最右:用 margin-left:auto 推开,而不是给左侧那一串按钮加 flex ——
* 左侧按钮的数量会随装载状态变(1 个还是 4 个),靠自动外边距最稳 */
.pv-auth {
margin-left: auto;
display: flex;
align-items: center;
gap: 8px;
}
.pv-login__tip {
margin: 0 0 12px;
font-size: 12px;
line-height: 1.7;
color: #6b7280;
}
.pv-login__tip code {
background: #f3f4f6;
border-radius: 3px;
padding: 1px 4px;
}
.pv-login__demos {
margin-top: 12px;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.pv-login__demo {
cursor: pointer;
}
/* ---------------------------------------------------------- 存储视图 */
.pv-kv {
padding: 4px 2px 12px;
}
.pv-kv__row {
display: flex;
gap: 12px;
padding: 3px 4px;
border-bottom: 1px solid #f5f7fa;
font-family: Consolas, Menlo, monospace;
font-size: 12px;
}
.pv-kv__row code {
flex: none;
width: 180px;
color: #6b7280;
}
.pv-kv__row span {
min-width: 0;
word-break: break-word;
}
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env node
/**
* 把本工程构建出的插件**交付给插件仓库**。
*
* ## 它替你做了哪四件事
*
* 1. 读 `plugin.config.json` —— 元数据的唯一真源;
* 2. 构建产物(除非 `--no-build`);
* 3. 把产物放进出仓库的构建目录(`<repo>/plugins/dist/`);
* 4. 把元数据条目**合并**进 `<repo>/repo.config.json`(按 id 覆盖,不动别人);
* 5. 跑一次仓库的发布脚本,归档 + 重写索引。
*
* 可选再加一步:`--host <宿主路径>` 让宿主立刻同步仓库(不然宿主要等下一次构建)。
*
* ## 为什么第 4 步是「合并」而不是「覆盖整个文件」
*
* `repo.config.json` 是**整个仓库**的发布清单,里面有别人的插件。用本工程的
* 单条元数据去覆盖它,等于把仓库里其它插件全部删掉 —— 这是最容易造成
* 「发布一个插件、下架全部插件」这种事故的地方,所以这里按 id 精确定位。
*
* ## 用法
*
* npm run build && node scripts/deploy.mjs --repo ../funjia-plugin-repository
* node scripts/deploy.mjs --repo ../funjia-plugin-repository --host "../插件化管理系统"
* node scripts/deploy.mjs --repo <路径> --no-build # 用 dist/ 里已有的产物
*
* 仓库路径也可以走环境变量:`PLUGIN_REPO=/path/to/repo npm run deploy`
*/
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const distDir = join(root, "dist");
const args = process.argv.slice(2);
const argValue = (name) => {
const i = args.indexOf(name);
return i >= 0 && args[i + 1] ? args[i + 1] : null;
};
const repoPath = argValue("--repo") || process.env.PLUGIN_REPO;
const hostPath = argValue("--host");
const skipBuild = args.includes("--no-build");
if (!repoPath) {
console.error("[deploy] missing --repo <path to funjia-plugin-repository>");
console.error("[deploy] example: node scripts/deploy.mjs --repo ../funjia-plugin-repository");
process.exit(1);
}
const repoRoot = resolve(root, repoPath);
const configFile = join(repoRoot, "repo.config.json");
const repoSrcDir = join(repoRoot, "plugins", "dist");
const publishScript = join(repoRoot, "scripts", "publish-repo.mjs");
if (!existsSync(configFile) || !existsSync(publishScript)) {
console.error(`[deploy] ${repoRoot} does not look like a plugin repository`);
console.error("[deploy] expected repo.config.json and scripts/publish-repo.mjs");
process.exit(1);
}
/* ------------------------------------------------------------------ 1. 读元数据 */
const meta = JSON.parse(readFileSync(join(root, "plugin.config.json"), "utf8"));
if (!meta.id || !meta.artifact) {
console.error("[deploy] plugin.config.json needs at least id and artifact");
process.exit(1);
}
console.log(`[deploy] plugin: ${meta.id}@${meta.version} (${meta.kind})`);
/* ------------------------------------------------------------------ 2. 构建 */
if (skipBuild) {
console.log("[deploy] --no-build: using existing dist/");
} else {
const viteBin = join(root, "node_modules", "vite", "bin", "vite.js");
if (!existsSync(viteBin)) {
console.error(`[deploy] vite not found at ${viteBin} - run npm install first`);
process.exit(1);
}
console.log("[deploy] building…");
const build = spawnSync(process.execPath, [viteBin, "build"], { cwd: root, stdio: "inherit" });
if (build.status !== 0) {
console.error(`[deploy] build failed (exit ${build.status})`);
process.exit(1);
}
}
/* ------------------------------------------------------------------ 3. 交付产物 */
/** 覆盖式复制(不用 copyFileSync:目标已存在时本机 shim 会拦 unlink) */
function put(from, to) {
mkdirSync(dirname(to), { recursive: true });
writeFileSync(to, readFileSync(from));
}
const files = [meta.artifact, meta.style].filter(Boolean);
mkdirSync(repoSrcDir, { recursive: true });
for (const file of files) {
const src = join(distDir, file);
if (!existsSync(src)) {
console.error(`[deploy] built artifact missing: dist/${file}`);
console.error("[deploy] check plugin.config.json 的 artifact / style 是否与产物名一致");
process.exit(1);
}
put(src, join(repoSrcDir, file));
console.log(`[deploy] artifact -> plugins/dist/${file} (${(statSync(src).size / 1024).toFixed(1)} KB)`);
}
/* ------------------------------------------------------------------ 4. 合并仓库清单 */
const repoConfig = JSON.parse(readFileSync(configFile, "utf8"));
if (!Array.isArray(repoConfig.plugins)) repoConfig.plugins = [];
// 只把「发布清单认识的字段」写进去:checksum / size / entry / publishedAt
// 由仓库的发布脚本计算,手工写进去只会过期。
const entry = {
id: meta.id,
name: meta.name,
version: meta.version,
description: meta.description,
author: meta.author,
kind: meta.kind,
artifact: meta.artifact,
style: meta.style,
globalKey: meta.globalKey,
requires: meta.requires,
permissions: meta.permissions,
contributes: meta.contributes,
activation: meta.activation,
tags: meta.tags,
homepage: meta.homepage,
};
const clean = Object.fromEntries(Object.entries(entry).filter(([, v]) => v !== undefined));
const slot = repoConfig.plugins.findIndex((p) => p.id === meta.id);
if (slot >= 0) {
const before = repoConfig.plugins[slot];
repoConfig.plugins[slot] = clean;
console.log(
`[deploy] repo.config.json: updated ${meta.id} (${before.version} -> ${clean.version})`
);
} else {
repoConfig.plugins.push(clean);
console.log(`[deploy] repo.config.json: added ${meta.id} (${clean.version})`);
}
writeFileSync(configFile, JSON.stringify(repoConfig, null, 2) + "\n", "utf8");
/* ------------------------------------------------------------------ 5. 发布 */
console.log("[deploy] publishing into the repository…");
const publish = spawnSync(process.execPath, [publishScript], { cwd: repoRoot, stdio: "inherit" });
if (publish.status !== 0) {
console.error(`[deploy] publish failed (exit ${publish.status})`);
process.exit(1);
}
/* ------------------------------------------------------------------ 6. 可选:同步到宿主 */
if (hostPath) {
const hostRoot = resolve(root, hostPath);
const syncScript = join(hostRoot, "scripts", "sync-repo.mjs");
if (!existsSync(syncScript)) {
console.warn(`[deploy] --host given but no scripts/sync-repo.mjs in ${hostRoot} - skipped`);
} else {
console.log("[deploy] syncing repository into the host…");
const sync = spawnSync(process.execPath, [syncScript, "--from", join(repoRoot, "repository")], {
cwd: hostRoot,
stdio: "inherit",
});
if (sync.status !== 0) {
console.warn(`[deploy] host sync failed (exit ${sync.status}) - run it manually`);
}
}
}
console.log("");
console.log(`[deploy] done: ${meta.id}@${meta.version} is in the repository.`);
console.log("[deploy] next:");
console.log("[deploy] - 仓库服务已开着的话,刷新管理台就能看到它");
console.log(`[deploy] - 宿主:cd <宿主> && npm run sync:repo (或 npm run build:all)`);
+312
View File
@@ -0,0 +1,312 @@
#!/usr/bin/env bash
# 预览器「调接口 + 登录鉴权」端到端验收。
#
# ## 它要证明的六件事
#
# | 组 | 主题 |
# | -- | ---- |
# | A | 未登录时**插件页面照样打得开**(预览没有路由守卫),但接口回 401 并自动弹登录框 |
# | B | 演示账号能登录;令牌落盘为**裸令牌**(客户端不加 `Bearer ` 前缀)|
# | C | **登录后插件真的拿到了数据** —— `ctx.http` 走通,表格渲染出种子的 4 行 |
# | D | 令牌过期:启动恢复识别 401 → 清令牌 + 弹登录框(插件一行代码都不用写)|
# | E | 退出登录:清空本地凭据,回到未登录态 |
# | F | **后端契约**(curl 直连,不经浏览器):401 语义、严格 `Bearer ` 前缀、列表形状、未知接口 |
#
# ## 三条写断言的经验(都是踩过才写的)
#
# 1. **判据用「关键标记串」而不是整串相等**。直接断
# `text === "管理员 · 超级管理员"` 会在标签多一个空格时假失败;
# 这里一律 `grep -q` 关键子串。
# 2. **「弹出了登录框」不等于「请求真的被拒了」**。登录框可能在别的路径上被打开,
# 所以 401 那一组必须同时断言 **HTTP 状态码 + `code` 字段**(F 组用 curl 直验)。
# 3. **F 组刻意不走浏览器**:`fetch` 在页面里会被别的东西影响(拦截、重试、
# service worker),而接口契约要的是「后端到底返回了什么」。
# curl 直接打,结论不可争辩。
#
# ## 前置(脚本不会自己起服务)
#
# cd <插件工程> && node node_modules/vite/bin/vite.js --config vite.preview.config.ts --port 5310
#
# 用法:bash scripts/verify-preview.sh [http://127.0.0.1:5310]
#
# ⚠️ 必须**整段放在后台跑**(run_in_background):前台执行 `agent-browser open`
# 会被进程管理 SIGTERM 掉,表现为「无任何输出 + 退出码 1」。
set -u
export PATH="/c/Users/Administrator/.workbuddy/binaries/node/versions/22.22.2-3:$PATH"
cd "$(dirname "$0")/.." || exit 1
mkdir -p .logs .shots
AB="agent-browser"
BASE="${1:-http://127.0.0.1:5310}"
OUT=".logs/verify-preview.txt"
: > "$OUT"
# 演示账号(与 preview/mock-api.ts 的 USERS 保持一致)
DEMO_ACCOUNT="funjia"
DEMO_PASSWORD="funjia123"
DEMO_NAME="管理员"
DEMO_ROLE="超级管理员"
# 种子数据里 device 表的条数(见 preview/mock-api.ts 的 SEED)
SEED_DEVICE_ROWS=4
# 令牌存储键:**从页面里读**,不在这里再写一个字面量。
# 两边各写一遍的话,键名改了脚本会「查一个不存在的键」然后静默通过。
KEY_EXPR='window.__preview__.apiContract.TOKEN_KEY'
PASS=0
FAIL=0
ok() { PASS=$((PASS + 1)); echo " PASS $1" >> "$OUT"; }
ng() { FAIL=$((FAIL + 1)); echo " FAIL $1" >> "$OUT"; [ -n "${2:-}" ] && echo " 实际:$2" >> "$OUT"; }
note() { echo " $1" >> "$OUT"; }
step() { echo "" >> "$OUT"; echo "===== $1 =====" >> "$OUT"; }
run() { timeout -k 5 "${T:-60}" $AB "$@" >> "$OUT" 2>&1; }
# 跑一段 JS 并把返回值压成单行(去掉引号与转义),便于 grep
probe() { timeout -k 5 60 $AB eval "$1" 2>/dev/null | sed 's/[\\"]//g' | tr -d '\r\n'; }
# 登录框是否**可见**。
#
# ⚠️ 不能只判 `!!document.querySelector('.el-dialog')` —— Element Plus 关闭对话框时
# 只是把它 `v-show` 起来,DOM **留在页面上**,于是那个判据永远是 true。
# 拿它当「弹框是否弹出」的判据,会让断言在该亮红灯的时候变绿(我第一次就栽在这)。
DIALOG_OPEN="(()=>{const o=document.querySelector('.el-overlay');if(!o)return false;const s=getComputedStyle(o);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';})()"
dialog_open() { probe "$DIALOG_OPEN"; }
# ⚠️ **点页面里的东西之前必须先 scrollintoview。**
#
# agent-browser 的 `click` 不自动滚动 —— 元素在视口外时,它按元素的坐标派发鼠标事件,
# 于是点击落在**别的元素**上(或者干脆落在页面外),而命令照样报「✓ Done」。
# 表现是「断言莫名其妙全红,但手动在页面上点一下又是好的」,能查很久。
# 顶栏/弹窗里的元素天然在视口内,不需要这一步;页面区(`.pv-stage__body`)里的需要。
click_in_page() { # $1=选择器
run scrollintoview "$1" >/dev/null
run click "$1" >/dev/null
}
expect() { # $1=说明 $2=期望子串 $3=实际值
if printf '%s' "$3" | grep -q "$2"; then ok "$1"; else ng "$1" "$3"; fi
}
expect_not() {
if printf '%s' "$3" | grep -q "$2"; then ng "$1" "$3"; else ok "$1"; fi
}
# 直接打接口拿一份登录凭据,供「预置登录态」用。
# 拿的是**接口原样的响应**而不是自己拼的:token 与 user 都从响应里抠出来,
# 脚本里不再抄一份字段(抄了就会在字段改动时静默失效)。
api_login() {
curl -s --noproxy '*' -X POST "$BASE/api/auth/login" \
-H 'Content-Type: application/json' \
-d "{\"account\":\"$DEMO_ACCOUNT\",\"password\":\"$DEMO_PASSWORD\"}"
}
api_token() { printf '%s' "$1" | sed -n 's/.*"token":"\([^"]*\)".*/\1/p'; }
api_user() { printf '%s' "$1" | sed -n 's/.*"user":\({[^}]*}\).*/\1/p'; }
# 预置一个已登录的本地状态(绕开表单)。
# ⚠️ **两个键都要写**:宿主的启动恢复要求「令牌 + 用户信息」同时存在,
# 只有令牌会被判成「本地数据不一致」直接清掉 —— 这正是本脚本第一次跑时
# E 组失败的原因(表现是「预置了令牌却还是未登录」)。
seed_auth() { # $1=token $2=user(JSON)
run eval "localStorage.setItem(window.__preview__.apiContract.TOKEN_KEY, '$1'); localStorage.setItem(window.__preview__.apiContract.USER_KEY, '$2')" >/dev/null
}
# 确保登录框是开着的,好让任意一组都能单独跑
ensure_login_dialog() {
if [ "$(dialog_open)" != "true" ]; then
run click ".pv-auth button" >/dev/null
sleep 1
fi
}
echo "############ verify-preview BASE=$BASE $(date +%H:%M:%S) ############" >> "$OUT"
# ---------------------------------------------------------------------------
step "A. 未登录:页面能打开(预览不拦页面),但接口回 401 并弹登录框"
# ⚠️ 必须**先清掉上一次运行留下的登录态**。
#
# agent-browser 的浏览器是**持久**的(daemon 里存着 profile),上一轮登录的令牌
# 还在 localStorage 里。不清就直接开跑,第一组断言会以「已登录」的状态开始 ——
# 现象是「未登录该被拦的地方一个都没拦」,而所有断言看起来都在正常执行。
run open "$BASE" >/dev/null
sleep 2
run eval "localStorage.clear()" >/dev/null
run reload >/dev/null
sleep 3
note "首屏 => $(probe "JSON.stringify({title:document.title,auth:document.querySelector('.pv-auth')?.innerText,page:!!document.querySelector('.pv-stage__body .hello-page'),dialog:!!document.querySelector('.el-dialog')})")"
A_AUTH=$(probe "document.querySelector('.pv-auth')?.innerText ?? ''")
A_PAGE=$(probe "document.querySelector('.pv-stage__body .hello-page')?.innerText?.slice(0,40) ?? ''")
A_TOKEN=$(probe "localStorage.getItem($KEY_EXPR)")
expect "首屏是未登录态" "未登录" "$A_AUTH"
# 「页面能打开」必须用**只有真页面才成立**的特征来证,不能只证「不是登录页」
expect "插件页面真的渲染出来了(预览没有路由守卫)" "你好插件" "$A_PAGE"
expect_not "未登录时没有令牌落盘" "mock\." "$A_TOKEN"
expect "首屏没有自动弹登录框(没令牌就不发请求)" "false" "$(dialog_open)"
# 未登录点「拉设备列表」→ 401 → 自动弹登录框
click_in_page ".hello-page__api-ops button.el-button--primary"
sleep 2
A_AFTER=$(probe "JSON.stringify({msg:document.querySelector('.el-dialog .el-alert__title')?.innerText ?? '',log:window.__preview__.host.state.logs.slice(-1)[0]?.text ?? ''})")
note "未登录调用接口后 => dialog=$(dialog_open) $A_AFTER"
expect "未登录调接口后自动弹出登录框" "true" "$(dialog_open)"
expect "提示里点明了原因(接口需要登录)" "接口需要登录" "$A_AFTER"
expect "宿主日志里留了一条 401" "401" "$A_AFTER"
# ---------------------------------------------------------------------------
step "B. 登录:演示账号可用,令牌落盘为裸令牌"
ensure_login_dialog
B_DEMO=$(probe "document.querySelector('.pv-login__demo')?.innerText ?? ''")
note "演示账号 chip => $B_DEMO"
expect "登录框里列出了演示账号" "$DEMO_ACCOUNT" "$B_DEMO"
expect "演示账号带了角色说明" "$DEMO_ROLE" "$B_DEMO"
# 点演示账号 chip 填入,再点「登录」
run click ".pv-login__demo" >/dev/null
sleep 1
run click ".el-dialog__footer button.el-button--primary" >/dev/null
sleep 2
B_STATE=$(probe "JSON.stringify({auth:document.querySelector('.pv-auth')?.innerText ?? '',token:localStorage.getItem($KEY_EXPR) ?? ''})")
note "登录后 => $B_STATE"
expect "顶栏显示出登录用户" "$DEMO_NAME" "$B_STATE"
expect "顶栏显示出角色" "$DEMO_ROLE" "$B_STATE"
expect "令牌已落盘" "mock\." "$B_STATE"
# 前缀由请求层统一补 —— localStorage 里必须是裸令牌。
# 存成 "Bearer mocks.xxx" 的话请求头会变成 "Bearer Bearer xxx",且只在接真后端时暴露
expect_not "落盘的是裸令牌(不带 Bearer 前缀)" "Bearer" "$B_STATE"
expect "登录成功后登录框关闭" "false" "$(dialog_open)"
# ---------------------------------------------------------------------------
step "C. 登录后插件真的拿到数据(ctx.http 走通)"
click_in_page ".hello-page__api-ops button.el-button--primary"
sleep 2
C_STATE=$(probe "JSON.stringify({rows:document.querySelectorAll('.hello-page__api-table tbody tr').length,msg:document.querySelector('.hello-page__api-msg .el-alert__title')?.innerText ?? '',user:document.querySelector('.hello-page__api-user')?.innerText ?? ''})")
note "插件页 => $C_STATE"
expect "表格渲染出了种子数据的行数($SEED_DEVICE_ROWS 行)" "rows:$SEED_DEVICE_ROWS" "$C_STATE"
expect "提示里报了取回条数与总数" "共 $SEED_DEVICE_ROWS 条" "$C_STATE"
expect "页面拿到的登录用户来自 ctx.getUser()" "$DEMO_NAME" "$C_STATE"
# 换一个表再拉一次:证明请求层不是「只对某一个接口特判」
click_in_page ".hello-page__api-ops button:not(.el-button--primary)"
sleep 2
C_NOTICE=$(probe "document.querySelector('.hello-page__api-msg .el-alert__title')?.innerText ?? ''")
note "公告列表 => $C_NOTICE"
expect "同一个请求层能拉别的表" "租赁设备季度巡检安排" "$C_NOTICE"
# ---------------------------------------------------------------------------
step "D. 令牌过期:启动恢复识别 401 → 清令牌 + 弹登录框"
# 造一个**已过期**的令牌:形状合法(mock.<uid>.<exp>.<nonce>),exp 是 1970 年。
# 用户信息也要一起写 —— 只有令牌的话启动恢复会先在「数据不一致」那一步清掉,
# 根本走不到「拿令牌去问后端」这一步(那样等于没验到 401)。
seed_auth "mock.1.1.abcdefgh" "$(api_user "$(api_login)")"
run reload >/dev/null
sleep 3
D_STATE=$(probe "JSON.stringify({auth:document.querySelector('.pv-auth')?.innerText ?? '',token:localStorage.getItem(window.__preview__.apiContract.TOKEN_KEY) ?? 'null',msg:document.querySelector('.el-dialog .el-alert__title')?.innerText ?? ''})")
note "带过期令牌刷新后 => dialog=$(dialog_open) $D_STATE"
expect "过期令牌在启动恢复时被清掉" "token:null" "$D_STATE"
expect "回到未登录态" "未登录" "$D_STATE"
expect "自动弹出登录框" "true" "$(dialog_open)"
expect "提示说的是「登录已过期」而不是「未登录」" "过期" "$D_STATE"
# 这一条区分「会话失效」与「从来没登录过」——
# 两条路都会弹框,但文案必须不一样,否则用户不知道该不该重新登录
expect_not "过期提示与「从未登录」的文案区分开" "接口需要登录" "$D_STATE"
# ---------------------------------------------------------------------------
step "E. 退出登录:清空本地凭据"
LOGIN_JSON=$(api_login)
seed_auth "$(api_token "$LOGIN_JSON")" "$(api_user "$LOGIN_JSON")"
run reload >/dev/null
sleep 3
E_BEFORE=$(probe "document.querySelector('.pv-auth')?.innerText ?? ''")
expect "预置令牌后刷新即为已登录" "$DEMO_NAME" "$E_BEFORE"
run click ".pv-auth button" >/dev/null
sleep 2
E_AFTER=$(probe "JSON.stringify({auth:document.querySelector('.pv-auth')?.innerText ?? '',token:localStorage.getItem(window.__preview__.apiContract.TOKEN_KEY) ?? 'null'})")
note "退出后 => $E_AFTER"
expect "退出后回到未登录态" "未登录" "$E_AFTER"
expect "退出后令牌已清空" "token:null" "$E_AFTER"
# ---------------------------------------------------------------------------
step "F. 后端契约(curl 直连,不经浏览器)"
CT='Content-Type: application/json'
curl_of() { curl -s --noproxy '*' -w '\nHTTP:%{http_code}' "$@"; }
F_BAD=$(curl_of -X POST "$BASE/api/auth/login" -H "$CT" -d '{"account":"funjia","password":"wrong-password"}')
note "错误密码 => $(echo "$F_BAD" | tr -d '\r\n')"
# 密码错误是**业务失败**,不是未授权。回 401 会被上层当成「令牌失效」去清会话
expect "密码错误:HTTP 不是 401" "HTTP:200" "$F_BAD"
expect "密码错误:业务码是 1" '"code":1' "$F_BAD"
expect_not "密码错误:不带 401 业务码" '"code":401' "$F_BAD"
F_LOGIN=$(curl_of -X POST "$BASE/api/auth/login" -H "$CT" -d "{\"account\":\"$DEMO_ACCOUNT\",\"password\":\"$DEMO_PASSWORD\"}")
expect "正确密码:业务码 0" '"code":0' "$F_LOGIN"
expect "正确密码:返回了令牌" '"token":"mock\.' "$F_LOGIN"
F_ANON=$(curl_of "$BASE/api/device/list?page=1&pageSize=5")
note "匿名请求 => $(echo "$F_ANON" | tr -d '\r\n')"
expect "匿名请求:HTTP 401" "HTTP:401" "$F_ANON"
expect "匿名请求:业务码 401" '"code":401' "$F_ANON"
TOKEN=$(api_token "$(api_login)")
# 只带裸令牌、**不加 Bearer 前缀** —— 这一步专门验「严格校验前缀」。
# 宽松的实现在这里会给 200,于是「请求层忘了加前缀」的 bug 一路潜伏到接真后端
F_NOPREFIX=$(curl_of "$BASE/api/device/list?page=1&pageSize=5" -H "Authorization: $TOKEN")
note "缺 Bearer 前缀 => $(echo "$F_NOPREFIX" | tr -d '\r\n')"
expect "缺 Bearer 前缀:按未授权处理" '"code":401' "$F_NOPREFIX"
expect "缺 Bearer 前缀:提示点明是前缀问题" "Bearer" "$F_NOPREFIX"
F_OK=$(curl_of "$BASE/api/device/list?page=1&pageSize=5" -H "Authorization: Bearer $TOKEN")
note "带 Bearer => $(echo "$F_OK" | tr -d '\r\n')"
expect "带 Bearer:业务码 0" '"code":0' "$F_OK"
# 列表形状:data 是**数组**、total 是**同级字段**。
# 写成 data:{rows,total} 是最常见的抄错,症状是「接口成功但表格永远空着」
expect "列表形状:data 是数组" '"data":\[' "$F_OK"
expect "列表形状:total 与 data 同级" '"total":' "$F_OK"
if printf '%s' "$F_OK" | grep -q '"data":{"rows"'; then
ng "列表形状:data 不能是 {rows,total}" "$F_OK"
else
ok "列表形状:data 就是数组(不是 {rows,total})"
fi
# 未知**接口**(不匹配通用 CRUD 形状):必须明确说是预览后端没实现。
# 用 `/api/meta/overview` 举例是有意的 —— 宿主有这条接口(`src/mock/` 里的聚合数字),
# 预览的 mock 没实现它,这正是插件作者最容易撞上的那一类:
# 「在宿主里跑得好好的,到预览里就没了」,得一眼看出是预览的缺口而不是自己写错了。
F_404=$(curl_of "$BASE/api/meta/overview" -H "Authorization: Bearer $TOKEN")
note "未知接口 => $(echo "$F_404" | tr -d '\r\n')"
expect "未知接口:明确说是预览后端没实现" "预览后端没有这个接口" "$F_404"
# 未知**集合名**是另一回事:通用 CRUD 会动态建空表(宿主同行为),
# 于是返回成功 + 空数组。这条断言的作用是把「与宿主一致」这件事钉住 ——
# 哪天有人想把它改成 404,会先在这里看到自己改掉了契约。
F_GHOST=$(curl_of "$BASE/api/ghost-table/list" -H "Authorization: Bearer $TOKEN")
note "未知集合名 => $(echo "$F_GHOST" | tr -d '\r\n')"
expect "未知集合名:动态建空表并返回成功(与宿主一致)" '"code":0' "$F_GHOST"
expect "未知集合名:data 是空数组、total 是 0" '"total":0' "$F_GHOST"
F_PUB=$(curl_of "$BASE/api/auth/demo-accounts")
expect "演示账号接口免登录可用" '"code":0' "$F_PUB"
expect "演示账号接口列出了 funjia" "$DEMO_ACCOUNT" "$F_PUB"
# ---------------------------------------------------------------------------
step "G. 截图与控制台"
run screenshot .shots/preview-auth.png >/dev/null
run console >/dev/null
note "控制台片段见 .logs/verify-preview.txt 上方的 console 输出"
echo "" >> "$OUT"
echo "############ 结果:PASS=$PASS FAIL=$FAIL ############" >> "$OUT"
echo "PASS=$PASS FAIL=$FAIL"
exit $([ "$FAIL" -eq 0 ] && echo 0 || echo 1)
+597
View File
@@ -0,0 +1,597 @@
#!/usr/bin/env node
/**
* 插件自检 —— 在 deploy 之前把「必然会在别处报错」的问题在这里拦下。
*
* ## 为什么需要它
*
* 这个工程里有一批值**必须严格一致**,一旦不一致,报错点离原因很远:
*
* | 不一致 | 你看到的现象 | 真正的原因 |
* | ---- | ---- | ---- |
* | `artifact` 与仓库条目对不上 | 发布脚本说「找不到产物」 | 两处各写了一遍文件名 |
* | `globalKey` 与产物全局名对不上 | 脚本加载成功、插件不出现 | 宿主无从认领 |
* | `kind` 与 artifact 后缀对不上 | 宿主按 IIFE 插标签、拿到 ESM 源码 | 后缀是给人看的,得自己保证 |
* | 版本号硬编码进源码 | 发了新版本却显示旧版本 | 版本该由索引在运行时注入 |
*
* 前三条在 `vite.config.ts` 里已经拦了一部分(构建时才炸),
* 本脚本的价值是**在构建之前**、并且**跨工程**(连仓库的 `repo.config.json` 一起看)。
*
* ## 用法
*
* npm run verify
* npm run verify -- --repo ../funjia-plugin-repository # 顺带校验仓库条目
* PLUGIN_REPO=../funjia-plugin-repository npm run verify
*/
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
/* ------------------------------------------------------------------ 输出 */
let errors = 0;
let warnings = 0;
const ok = (m) => console.log(` OK ${m}`);
const bad = (m) => {
errors += 1;
console.log(` FAIL ${m}`);
};
const warn = (m) => {
warnings += 1;
console.log(` WARN ${m}`);
};
const info = (m) => console.log(` ${m}`);
const step = (m) => console.log(`\n${m}`);
/* ------------------------------------------------------------------ 入参 */
function parseArgs(argv) {
const out = { repo: process.env.PLUGIN_REPO || null };
for (let i = 0; i < argv.length; i += 1) {
if (argv[i] === "--repo") out.repo = argv[i + 1];
}
return out;
}
const args = parseArgs(process.argv.slice(2));
/* ------------------------------------------------------------- 组 A:清单 */
step("组 A · plugin.config.json");
const cfgFile = join(root, "plugin.config.json");
if (!existsSync(cfgFile)) {
console.error(`找不到 ${cfgFile} —— 这个文件是插件元数据的唯一真源。`);
process.exit(1);
}
let cfg;
try {
cfg = JSON.parse(readFileSync(cfgFile, "utf8"));
} catch (e) {
console.error(`plugin.config.json 不是合法 JSON:${e.message}`);
process.exit(1);
}
// 这四项缺任何一个,构建或发布就一定失败,所以在这里就说清楚
for (const key of ["id", "name", "version", "kind", "artifact"]) {
if (!cfg[key] || typeof cfg[key] !== "string") bad(`缺少必填字段 ${key}`);
}
if (errors === 0) ok("必填字段齐全(id / name / version / kind / artifact)");
if (cfg.kind && !["iife", "esm"].includes(cfg.kind)) {
bad(`kind = ${JSON.stringify(cfg.kind)},只允许 "iife" 或 "esm"(没有 builtin)`);
} else if (cfg.kind) {
ok(`kind = ${cfg.kind}`);
}
/**
* 版本号必须是「数字点分」。
*
* 因为仓库按点分段比大小(`1.10.0 > 1.9.0`),写了 `v1.0` 或 `1.0.0-beta`
* 之后排序就会静默错位 —— 不是报错,是「更新提示不出现」,更难查。
*/
if (cfg.version && !/^\d+(\.\d+)*$/.test(cfg.version)) {
bad(`version = ${JSON.stringify(cfg.version)},应为数字点分(如 1.0.0)`);
} else if (cfg.version) {
ok(`version = ${cfg.version}`);
}
/**
* 命名建议(只警告,不拦):`<组织>.<模块>`。
*
* 这不是洁癖:`id` 是安装/卸载/事件前缀共用的唯一键,带上组织前缀才不会
* 和别人的插件撞车。仓库里所有官方示例都遵循这个形状。
*/
if (cfg.id && !/^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/.test(cfg.id)) {
warn(`id = ${JSON.stringify(cfg.id)} 不像 <组织>.<模块>(全小写、连字符、至少一个点)`);
} else if (cfg.id) {
ok(`id = ${cfg.id}(符合 <组织>.<模块>)`);
}
/* --------------------------------------------------- artifact / kind 一致 */
if (cfg.artifact) {
const shapeOk = /^[A-Za-z0-9_.-]+\.(iife|es)\.js$/.test(cfg.artifact);
if (!shapeOk) {
bad(`artifact = ${JSON.stringify(cfg.artifact)},应为 "<Name>.iife.js" 或 "<Name>.es.js"`);
} else {
ok(`artifact = ${cfg.artifact}`);
// 后缀必须与 kind 对上:宿主是「按 kind 决定装载方式」的,
// 后缀写错不会立刻炸 —— 而是按错误的方式去装,现象是插件不出现。
const suffix = cfg.artifact.endsWith(".iife.js") ? "iife" : "esm";
if (cfg.kind && suffix !== cfg.kind) {
bad(
`artifact 后缀(${cfg.artifact})暗示 ${suffix},但 kind = ${cfg.kind} —— 两者必须一致;` +
`发布后宿主会按 kind 去装,后缀只在这里被校验`
);
} else if (cfg.kind) {
ok(`artifact 后缀与 kind 一致(${cfg.kind})`);
}
}
}
if (cfg.style && !cfg.style.endsWith(".css")) {
bad(`style = ${JSON.stringify(cfg.style)} 应以 .css 结尾`);
} else if (cfg.style) {
ok(`style = ${cfg.style}`);
}
/* ------------------------------------------------------------ globalKey */
/**
* `globalKey` 会被 rollup 直接写进产物当全局变量名,所以必须是合法标识符。
* 走 `window.FunjiaPlugin.register()` 自注册通道的插件其实不依赖它,
* 但 rollup 仍然需要这个名字(`lib.name`),所以不能省。
*/
if (cfg.globalKey) {
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(cfg.globalKey)) {
bad(`globalKey = ${JSON.stringify(cfg.globalKey)} 不是合法 JS 标识符`);
} else {
ok(`globalKey = ${cfg.globalKey}`);
}
} else if (cfg.kind === "iife") {
warn("未声明 globalKey:构建会按 id 推断一个,但老生态(window.<key>)认领通道就用不了");
} else {
ok("esm 形态无需 globalKey");
}
/* ------------------------------------------------------- 组 B:源码边界 */
step("组 B · 源码边界");
/**
* 剥掉注释再扫描。
*
* **必须做这一步**:文档注释里天然会出现反面示例,比如
*
* ```
* * - ❌ `import { x } from "../../src/…"` —— 绝不能引宿主内部实现
* ```
*
* 不剥注释的话,这条「说明什么叫违规」的注释本身会被判成违规,
* 于是自检脚本永远报一个假错 —— 而假错比没有错更糟:真错会被一起忽略。
*
* 行注释用 `[^:]\/\/` 而非裸 `\/\/`,是为了不误伤 `https://` 这类串里的双斜杠。
*/
function stripComments(text) {
return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
}
const srcDir = join(root, "src");
const entryFile = join(srcDir, "index.ts");
if (!existsSync(entryFile)) {
bad("找不到 src/index.ts —— 构建入口");
} else {
const entry = readFileSync(entryFile, "utf8");
/**
* 自注册是本模板推荐的认领方式:产物全局名可以与插件 id 完全不同
* (产物叫 HelloBundle,插件 id 是 acme.hello),一个脚本也能塞多个插件。
*/
if (entry.includes("FunjiaPlugin.register")) {
ok("src/index.ts 走自注册通道(window.FunjiaPlugin.register)");
} else if (cfg.globalKey && entry.includes("export default")) {
warn("未发现 window.FunjiaPlugin.register:将依赖 window.<globalKey> 认领(老生态通道)");
} else {
bad(
"src/index.ts 既没有 window.FunjiaPlugin.register,也不确定有默认导出 —— " +
"宿主可能加载成功但认领不到插件"
);
}
/* ---------------- 版本号硬编码 ---------------- */
// 版本由仓库索引在运行时注入(ctx.plugin.version)。硬编码的后果是
// 「发了 0.2.0,界面上还显示 0.1.0」,而且换了 id 复制工程时会连版本一起带过去。
if (cfg.version) {
const offenders = [];
const walk = (dir) => {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) {
walk(p);
continue;
}
if (!/\.(ts|js|vue|tsx|jsx)$/.test(name)) continue;
const text = stripComments(readFileSync(p, "utf8"));
if (text.includes(cfg.version)) offenders.push(p.slice(root.length + 1));
}
};
walk(srcDir);
if (offenders.length > 0) {
bad(
`源码里出现了 version 字面量 ${cfg.version}(${offenders.join(", ")})—— ` +
`版本应取 ctx.plugin.version,让仓库索引当唯一真源`
);
} else {
ok(`源码未硬编码版本 ${cfg.version}(改用 ctx.plugin.version)`);
}
}
/* ---------------- 不许引宿主内部实现 ---------------- */
// 引了宿主源码,宿主重构一次插件就整体失效。要能力就走 ctx(天然向前兼容)。
//
// ⚠️ 判据是「**解析后是否逃出工程根**」,不是「说明符是不是以 .. 开头」。
// 模板原始版把两者当成一回事(只白名单 `../sdk` / `../runtime` / `../pages`),
// 于是任何把代码分到子目录的插件(`src/components/X.vue` 里 `import "../codes"`)
// 都会被误报成「引了工程外部模块」—— 报错点看着吓人,其实什么毛病都没有。
// 改成真正做一次路径解析,`..` 只在真的越出 root 时才算泄漏。
const leaked = [];
const scanImports = (dir) => {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) {
scanImports(p);
continue;
}
if (!/\.(ts|js|vue|tsx|jsx)$/.test(name)) continue;
const text = stripComments(readFileSync(p, "utf8"));
for (const m of text.matchAll(/from\s+["']([^"']+)["']/g)) {
const spec = m[1];
// 裸说明符(vue / qrcode-generator / funjiaui)走打包器解析,不属于本组管辖
if (!spec.startsWith(".")) continue;
const resolved = resolve(dirname(p), spec);
const inside = resolved === root || resolved.startsWith(root + sep);
if (!inside) leaked.push(`${relative(root, p)} → ${spec}`);
}
}
};
scanImports(srcDir);
if (leaked.length > 0) {
bad(`发现了指向工程外部的 import(插件不能依赖宿主实现):\n ${leaked.join("\n ")}`);
} else {
ok("没有引用工程外部的模块(插件保持独立交付物)");
}
}
/* ------------------------------------------------- 组 C:构建产物(可选) */
step("组 C · 构建产物");
const distDir = join(root, "dist");
if (!existsSync(distDir)) {
info("dist/ 还不存在 —— 先 npm run build,或忽略(本组只是额外确认)");
} else {
const artifactPath = cfg.artifact ? join(distDir, cfg.artifact) : null;
if (artifactPath && existsSync(artifactPath)) {
const kb = (statSync(artifactPath).size / 1024).toFixed(1);
ok(`dist/${cfg.artifact} 存在(${kb} KB)`);
} else if (artifactPath) {
bad(`dist/${cfg.artifact} 不存在 —— artifact 名字与构建输出对不上`);
}
if (cfg.style) {
if (existsSync(join(distDir, cfg.style))) {
ok(`dist/${cfg.style} 存在`);
} else if (existsSync(artifactPath || "")) {
// 组件里没写 <style> 时 vite 不会产出 CSS —— 此时应把 style 从配置里去掉,
// 否则宿主会去注入一个 404 的样式表。
warn(`dist/${cfg.style} 不存在,但配置里声明了 style —— 页面若无 <style> 请去掉该字段`);
}
}
/* ---------------- external 是否真的生效 ---------------- */
// 这是插件构建后果最严重的一类错误:Vue 被内联进产物,宿主里就有了两份 Vue 实例,
// 症状是「页面画得出来、但完全点不动」,而且**不报任何错**。
// `npm run preview` 能直接看出来(点一下页面按钮就知道),这里补一道静态判断,
// 好在构建之后、交付之前就拦住。
if (artifactPath && existsSync(artifactPath)) {
const text = readFileSync(artifactPath, "utf8");
const sizeKb = statSync(artifactPath).size / 1024;
// Vue 3 运行时压缩后也在 90KB 上下,而一个普通插件不该有这么重
const VUE_RUNTIME_KB = 60;
if (sizeKb > VUE_RUNTIME_KB) {
warn(
`产物 ${sizeKb.toFixed(1)} KB,偏大 —— 若非有意为之,检查 vue / funjiaui 是不是被内联了` +
`(内联 = 宿主里两份 Vue = 页面点不动,且不报错)`
);
}
if (cfg.kind === "iife") {
// IIFE 的 external 会变成「把全局当参数传进去」,压缩后形如 `}(vue);`
const head = text.slice(0, 240);
const tail = text.slice(-240);
if (/[(,]vue\)|\.vue\)/.test(tail) || /function\s*\(\s*vue\s*\)/.test(head)) {
ok("IIFE 产物把 vue 当外部依赖(可见 }(vue) / function(vue)),没内联");
} else {
warn("IIFE 产物里没找到对全局 vue 的外部引用 —— 确认 vue 是否被内联进来了");
}
} else if (cfg.kind === "esm") {
if (/from\s*["']vue["']/.test(text)) {
ok('ESM 产物保留了裸说明符 from "vue"(交给宿主 import map 解析)');
} else {
warn('ESM 产物里没看到 from "vue" —— 确认 vue 是否被内联进来了');
}
}
}
}
/* ------------------------------------------- 组 D:与仓库条目交叉校验 */
step("组 D · 与仓库条目交叉校验");
const repoDir = args.repo ? resolve(root, args.repo) : null;
if (!repoDir) {
info("未指定仓库路径,跳过(--repo <路径> 或 PLUGIN_REPO 环境变量可开启)");
} else {
const repoCfgFile = join(repoDir, "repo.config.json");
if (!existsSync(repoCfgFile)) {
bad(`在 ${repoCfgFile} 找不到 repo.config.json —— 仓库路径对吗?`);
} else {
const repoCfg = JSON.parse(readFileSync(repoCfgFile, "utf8"));
const entry = (repoCfg.plugins || []).find((p) => p.id === cfg.id);
if (!entry) {
info(`仓库清单里还没有 ${cfg.id} —— 首次 deploy 时会自动加进去`);
} else {
const pairs = [
["artifact", cfg.artifact, entry.artifact],
["kind", cfg.kind, entry.kind],
["globalKey", cfg.globalKey, entry.globalKey],
];
let drifted = 0;
for (const [field, mine, theirs] of pairs) {
// 一边没写就不算「漂移」(globalKey 对 ESM 形态本来就没有)
if (mine === undefined || theirs === undefined) continue;
if (mine !== theirs) {
bad(`仓库条目 ${cfg.id} 的 ${field} = ${JSON.stringify(theirs)},本工程是 ${JSON.stringify(mine)}`);
drifted += 1;
}
}
if (drifted === 0) ok(`仓库条目 ${cfg.id} 的 artifact / kind / globalKey 与本工程一致`);
// 版本漂移不算错:本地改了版本还没 deploy 是正常的开发中间态
if (entry.version !== cfg.version) {
info(`版本待发布:本工程 ${cfg.version},仓库当前 ${entry.version}(deploy 后会更新)`);
}
}
}
}
/* ------------------------------------------------------ 组 E:本地预览 */
step("组 E · 本地预览");
const previewDir = join(root, "preview");
const previewCfg = join(root, "vite.preview.config.ts");
const REQUIRED_PREVIEW_FILES = [
"index.html",
"artifact.html",
"main-source.ts",
"main-artifact.ts",
"App.vue",
"mount.ts",
"host.ts",
"contract.ts",
"loaders.ts",
"runtime.ts",
"shims/funjiaui.ts",
"style.css",
// 预览的接口能力:契约(两侧共用)+ 最小后端
"api-contract.ts",
"mock-api.ts",
];
if (!existsSync(previewDir)) {
bad("找不到 preview/ —— npm run dev / npm run preview 会起不来");
} else if (!existsSync(previewCfg)) {
bad("找不到 vite.preview.config.ts —— 预览服务器没有配置");
} else {
const missing = REQUIRED_PREVIEW_FILES.filter((f) => !existsSync(join(previewDir, f)));
if (missing.length > 0) {
bad(`预览缺少文件:${missing.join("、")}`);
} else {
ok(`预览资产齐全(${REQUIRED_PREVIEW_FILES.length} 个文件 + vite.preview.config.ts)`);
}
/* ---------------- import map 必须在 head 里静态声明 ---------------- */
// 这是最容易踩、又最难查的一条:模块加载开始之后再插入 import map,
// 浏览器会**静默忽略**它 —— 不报错,只是 ESM 产物里的 "vue" 解析不了。
for (const page of ["index.html", "artifact.html"]) {
const file = join(previewDir, page);
if (!existsSync(file)) continue;
const html = readFileSync(file, "utf8");
const mapAt = html.indexOf('type="importmap"');
const moduleAt = html.indexOf('type="module"');
if (mapAt < 0) {
bad(`${page} 里没有 import map —— ESM 产物里的裸说明符 "vue" 会解析失败`);
} else if (moduleAt >= 0 && mapAt > moduleAt) {
bad(
`${page} 的 import map 排在了 <script type="module"> 之后 —— ` +
`浏览器会静默忽略它(不报错,只是不生效)`
);
} else {
ok(`${page} 的 import map 静态声明在 module 脚本之前`);
}
}
/* ---------------- 契约必须先于插件源码求值 ---------------- */
// ESM 按 import 声明顺序求值。插件源码一旦先跑,它的 register 就没有队列可落,
// 报出来的是「找不到 window.FunjiaPlugin」—— 看着像环境问题,其实是顺序问题。
const mainSourceFile = join(previewDir, "main-source.ts");
if (existsSync(mainSourceFile)) {
const text = readFileSync(mainSourceFile, "utf8");
const atContract = text.indexOf('"./contract"');
const atPlugin = text.indexOf('"../src/index"');
if (atContract < 0) {
bad("main-source.ts 没有 import ./contract —— 插件自注册会落空");
} else if (atPlugin >= 0 && atContract > atPlugin) {
bad(
"main-source.ts 里 ../src/index 排在 ./contract 之前 —— " +
"插件源码求值时契约还没装,会误报「找不到 window.FunjiaPlugin」"
);
} else {
ok("main-source.ts 先 import 契约、后 import 插件源码(顺序正确)");
}
}
/* ---------------- funjiaui 桩要覆盖实际用到的名字 ---------------- */
// 桩和用法脱节的代价很具体:预览里报 "does not provide an export named …",
// 而宿主里其实是好的 —— 白查一轮。所以在这里对齐。
const shimFile = join(previewDir, "shims/funjiaui.ts");
if (existsSync(shimFile)) {
const shimText = readFileSync(shimFile, "utf8");
const shimExports = new Set();
for (const m of shimText.matchAll(/export\s+(?:const|function|class)\s+([A-Za-z0-9_$]+)/g)) {
shimExports.add(m[1]);
}
for (const m of shimText.matchAll(/export\s*\{([^}]+)\}/g)) {
for (const part of m[1].split(",")) {
const name = part.trim().split(/\s+as\s+/).pop().trim();
if (name) shimExports.add(name);
}
}
const usedFromFunjiaui = new Set();
const collectFunjiauiUsage = (dir) => {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) {
collectFunjiauiUsage(p);
continue;
}
if (!/\.(ts|js|vue|tsx|jsx)$/.test(name)) continue;
const text = stripComments(readFileSync(p, "utf8"));
for (const m of text.matchAll(/import\s*(?:type\s*)?\{([^}]+)\}\s*from\s*["']funjiaui["']/g)) {
for (const part of m[1].split(",")) {
const nm = part.trim().split(/\s+as\s+/)[0].trim();
if (nm) usedFromFunjiaui.add(nm);
}
}
}
};
collectFunjiauiUsage(srcDir);
if (usedFromFunjiaui.size === 0) {
ok("源码没有 import funjiaui(预览桩仍在位,备用)");
} else {
const gaps = [...usedFromFunjiaui].filter((n) => !shimExports.has(n));
if (gaps.length > 0) {
bad(
`源码从 "funjiaui" 导入了预览桩里没有的名字:${gaps.join("、")} —— ` +
`预览会报「does not provide an export named」,请补进 preview/shims/funjiaui.ts`
);
} else {
ok(`源码用到的 ${usedFromFunjiaui.size} 个 funjiaui 导出都在预览桩里`);
}
}
}
/* ---------------- 接口契约:客户端与服务端必须共用一份 ---------------- */
//
// 预览的 `/api` 有两个实现方:`mock-api.ts`(服务端)与 `host.ts`(客户端)。
// 它们各写一份 `parseAuthHeader`、各写一份令牌前缀的话,「客户端以为令牌是
// `Bearer x`、服务端以为就是 `x`」这类错误**不会有任何编译错误** ——
// 只会表现为「登录成功但所有接口都 401」,而且要到接真后端时才暴露。
// 所以这里钉住:定义只能有一处,两侧都必须 import 它。
{
const contractFile = join(previewDir, "api-contract.ts");
const mockFile = join(previewDir, "mock-api.ts");
const hostFile = join(previewDir, "host.ts");
if (!existsSync(contractFile)) {
bad("找不到 preview/api-contract.ts —— 接口契约没有唯一真源,两侧会各自漂移");
} else {
const contractText = stripComments(readFileSync(contractFile, "utf8"));
// 契约里必须有的东西。少一个,某一侧就会自己补一份本地定义
const REQUIRED_EXPORTS = [
"TOKEN_KEY",
"USER_KEY",
"TOKEN_PREFIX",
"TOKEN_TTL_MS",
"UNAUTHORIZED_CODE",
"AUTH_EVENTS",
"parseAuthHeader",
];
const missingExports = REQUIRED_EXPORTS.filter(
(name) => !new RegExp(`export\\s+(?:const|function|interface|type)\\s+${name}\\b`).test(contractText)
);
if (missingExports.length > 0) {
bad(`api-contract.ts 缺少导出:${missingExports.join("、")}`);
} else {
ok(`接口契约导出了 ${REQUIRED_EXPORTS.length} 项关键定义(存储键 / 令牌 / 401 / 请求头解析)`);
}
// ⚠️ `UNAUTHORIZED_CODE` 必须是 **401**:它同时承担「业务码」与
// 「与 HTTP 状态码同值」两个角色,客户端那句 `code === 401` 才能一条覆盖两条路径。
const codeMatch = contractText.match(/UNAUTHORIZED_CODE\s*=\s*(\d+)/);
if (!codeMatch) {
bad("api-contract.ts 里找不到 UNAUTHORIZED_CODE 的取值");
} else if (codeMatch[1] !== "401") {
bad(
`UNAUTHORIZED_CODE 是 ${codeMatch[1]},必须是 401 —— ` +
`与 HTTP 状态码同值才能让客户端一条判断覆盖 mock 与真后端两条路径`
);
} else {
ok("UNAUTHORIZED_CODE = 401(与 HTTP 状态码同值)");
}
// 两侧都必须 import 契约,而不是各写各的
for (const [file, label] of [
[mockFile, "mock-api.ts(服务端)"],
[hostFile, "host.ts(客户端)"],
]) {
if (!existsSync(file)) continue;
const text = readFileSync(file, "utf8");
if (!/from\s+["']\.\/api-contract["']/.test(text)) {
bad(`${label} 没有从 ./api-contract 取契约 —— 这里会出现第二份定义`);
} else {
ok(`${label} 从 ./api-contract 取契约`);
}
// 本地再声明一遍 = 漂移的开始,直接拦掉
if (/\bfunction\s+parseAuthHeader\b/.test(stripComments(text))) {
bad(`${label} 自己又写了一份 parseAuthHeader —— 请求头的校验规则会出现两个版本`);
}
}
}
/* ---------------- 预览服务器要真的把后端接上 ---------------- */
const previewCfgText = existsSync(previewCfg) ? readFileSync(previewCfg, "utf8") : "";
if (!/createPreviewApi/.test(previewCfgText)) {
bad(
"vite.preview.config.ts 没有接上 createPreviewApi —— " +
"预览里 ctx.http 会 404,插件作者会以为是自己代码写错了"
);
} else {
ok("vite.preview.config.ts 已接上内置后端(/api 有应答)");
}
if (!/PREVIEW_API_TARGET/.test(previewCfgText)) {
warn("vite.preview.config.ts 里没有 PREVIEW_API_TARGET —— 预览无法切到真后端");
} else {
ok("vite.preview.config.ts 支持 PREVIEW_API_TARGET 代理到真后端");
}
}
}
/* ------------------------------------------------------------------ 汇总 */
console.log("");
console.log(
(errors === 0 ? "OK " : "FAIL ") +
`summary: ${errors} error(s), ${warnings} warning(s) (${cfg.id || "unknown"}@${cfg.version || "?"})`
);
process.exit(errors === 0 ? 0 : 1);
File diff suppressed because one or more lines are too long
+303
View File
@@ -0,0 +1,303 @@
/**
* 条码 / 二维码生成(纯函数,不碰 DOM)。
*
* 两条不同的实现路线,理由不同:
*
* - **条码**:自己实现真正的 **Code 128 Set B**。SN 码的全部意义就是「贴在设备上
* 一扫就调出记录」,一个扫不出来的条码等于一张废图。Code 128 的编码规则是
* 封闭的(107 张模式表 + 校验位),自己写比引库更可控,也不会多一份依赖。
*
* - **二维码**:走 `qrcode-generator`。真 QR 要 RS 纠错、掩码评估、版本容量协商,
* 自己写等于重造一整个库,而且没有测试向量就无从验证正确性。这个库零依赖、
* 单文件、被用了十几年,比手搓靠谱得多。
*
* ## 单位是毫米
*
* 标签格子是 `48.5mm × 25.4mm` 的物理尺寸,所以这里的 SVG 直接以 **mm** 出图
* (`width="18mm"`)—— 浏览器里 1mm = 96/25.4px 与 CSS 一致,打印到纸上就是
* 真实尺寸。若改用 px,换个打印 DPI 就会走形。
*
* ⚠️ 条码**绝不能**靠 `width="100%"` + `preserveAspectRatio="none"` 拉伸:
* 那会让每个模块的宽度不再相等,扫码枪直接读不出来。所以下面按「可用宽度 ÷
* 模块总数」算出模块宽度,宁可牺牲一点精度也要保证等宽。
*/
import qrcode from "qrcode-generator";
/* ================================================================== */
/* Code 128 Set B */
/* ================================================================== */
/**
* Code 128 的 107 个模式(index 0..106),每个是 6 位数字串
* (三组「条宽.空宽」交替排列;停止符是 7 位)。
*
* 这张表是 Code 128 规范的一部分,**必须原样使用**,改一个数字就会让所有码都扫不出来。
*/
const CODE128_PATTERNS = [
"212222", "222122", "222221", "121223", "121322", "131222", "122213", "122312", "132212",
"221213", "221312", "231212", "112232", "122132", "122231", "113222", "123122", "123221",
"223211", "221132", "221231", "213212", "223112", "312131", "311222", "321122", "321221",
"312212", "322112", "322211", "212123", "212321", "232121", "111323", "131123", "131321",
"112313", "132113", "132311", "211313", "231113", "231311", "112133", "112331", "132131",
"113123", "113321", "133121", "313121", "211331", "231131", "213113", "213311", "213131",
"311123", "311321", "331121", "312113", "312311", "332111", "314111", "221411", "431111",
"111224", "111422", "121124", "121421", "141122", "141221", "112214", "112412", "122114",
"122411", "142112", "142211", "241211", "221114", "413111", "241112", "134111", "111242",
"121142", "121241", "114212", "124112", "124211", "411212", "421112", "421211", "212141",
"214121", "412121", "111143", "111341", "131141", "114113", "114311", "411113", "411311",
"113141", "114131", "311141", "411131", "211412", "211214", "211232", "2331112",
];
const START_B = 104; // Start Code B
const STOP = 106; // 停止符(含终止条,13 位而不是 11 位)
/** 静区:规范要求两侧各留 ≥10 个模块,少了扫码枪会贴着读不到 */
const QUIET_MODULES = 10;
/**
* 把文本转成 Code 128 的位串(`'1'` 条 / `'0'` 空)。
*
* 只支持 Set B 的可打印 ASCII(0x20..0x7E)—— SN 码是 `ZP-260928-0001-R`
* 这种纯 ASCII,完全够用,也避免引入更难处理的 Set C 切换逻辑。
*/
export function code128Bits(text: string): string {
const codes: number[] = [START_B];
for (const ch of text) {
const code = ch.charCodeAt(0);
if (code < 32 || code > 126) {
throw new Error(`文本含 Code128 Set B 不支持的字符:${JSON.stringify(ch)}`);
}
codes.push(code - 32); // Set B 映射:0x20..0x7E → 0..94
}
// 校验位:(起始值 + Σ(码值 × 位置)) mod 103
// ⚠️ 这一步绝对不能省 —— 少了它扫码枪要么拒读、要么读出乱码,而且肉眼完全看不出来。
let sum = START_B;
for (let i = 1; i < codes.length; i += 1) sum += codes[i] * i;
codes.push(sum % 103);
codes.push(STOP);
return codes
.map((c) => {
const pattern = CODE128_PATTERNS[c];
if (!pattern) throw new Error(`Code128 模式缺失:${c}`);
let bits = "";
for (let i = 0; i < pattern.length; i += 1) {
bits += (i % 2 === 0 ? "1" : "0").repeat(Number(pattern[i]));
}
return bits;
})
.join("");
}
export interface BarcodeOptions {
/** 含静区的总宽度(mm)。默认 46mm(一个标签格 48.5mm 去掉左右各 1.25mm 余量) */
widthMm?: number;
/** 条高(mm),默认 7 */
heightMm?: number;
/** 是否在条码下方显示文本,默认 true */
showText?: boolean;
/** 文本字号(mm),默认 1.9 */
textMm?: number;
}
/**
* 条码 SVG 的总高度(mm)—— **渲染与「页面估算可用空间」必须走同一个函数**。
*
* 页面要靠这个数算出「条码条占掉多少高度、二维码还剩多少」。如果那边自己
* 再拍一个 6.5mm 之类的常数,这里一改字号,估出来的二维码尺寸就不对了 ——
* 而症状是「界面上写着 12mm,打印出来 9mm」,只能在纸上发现。
*/
export function code128HeightMm(opts: Pick<BarcodeOptions, "heightMm" | "textMm" | "showText"> = {}): number {
const heightMm = opts.heightMm ?? 7;
const textMm = opts.textMm ?? 1.9;
const showText = opts.showText !== false;
// 条高 + (文本字号 + 0.7mm 上下留白)
return heightMm + (showText ? textMm + 0.7 : 0);
}
/**
* 标签格里的条码条参数。
*
* 4.2mm 条高是**取舍后的值**:Code 128 规范建议条高 ≥ 符号长度的 15%
* (46mm × 15% ≈ 6.9mm),但这个格子总共只有 25.4mm 高 —— 给条码留 7mm,
* 左侧二维码和 4 行规格文字就没地方了。手持激光枪扫 4.2mm 高的 Code 128
* 通常没问题,但**线阵扫描头需要在垂直方向对准**,所以面板上把实际规格
* 算给用户看,而不是让人到纸上才发现扫不动。
*/
export const LABEL_BARCODE_OPTS = { widthMm: 46, heightMm: 4.2, textMm: 1.7 } as const;
/** 条码条在标签里实际占用的高度(mm) */
export const LABEL_BARCODE_STRIP_MM = code128HeightMm(LABEL_BARCODE_OPTS);
/**
* 生成 Code 128 条码 SVG。
*
* 宽度是「**塞进**给定毫米数」而不是固定模块宽度 —— 因为 SN 长度可变
* (`ZP-260928-0001-R` 是 16 位,短码只有 12 位),固定模块宽度会时宽时窄。
*/
export function code128Svg(text: string, opts: BarcodeOptions = {}): string {
const widthMm = opts.widthMm ?? 46;
const heightMm = opts.heightMm ?? 7;
const showText = opts.showText !== false;
const textMm = opts.textMm ?? 1.9;
let bits: string;
try {
bits = code128Bits(text);
} catch {
// 含非法字符时给一段几何图形占位,而不是让整张标签渲染不出来
bits = "1101001000011010010000";
}
const totalModules = bits.length + QUIET_MODULES * 2;
// 保留两位小数(1/100 mm = 0.01mm ≈ 0.038 个 96dpi 像素),足够且不会累积漂移
const moduleMm = Math.max(0.08, Math.floor((widthMm / totalModules) * 100) / 100);
const inkWidthMm = bits.length * moduleMm;
const totalWidthMm = inkWidthMm + QUIET_MODULES * moduleMm * 2;
const totalHeightMm = code128HeightMm({ heightMm, textMm, showText });
// 把连续的 '1' 合成一条 rect:比逐模块画少几十个节点,打印更稳
const rects: string[] = [];
let i = 0;
while (i < bits.length) {
if (bits[i] === "1") {
let run = 1;
while (bits[i + run] === "1") run += 1;
rects.push(
`<rect x="${((QUIET_MODULES + i) * moduleMm).toFixed(3)}" y="0.2" ` +
`width="${(run * moduleMm).toFixed(3)}" height="${heightMm}" fill="#000"/>`
);
i += run;
} else {
i += 1;
}
}
/**
* ⚠️ 单位陷阱(这个文件里最容易踩的一处):
*
* 本 SVG 的 `viewBox` 是「**毫米即用户单位**」—— `viewBox="0 0 43.89 6.60"`
* 配 `width="43.89mm" height="6.60mm"`,于是 1 用户单位 = 1mm,
* 里面所有坐标(条宽、y、x)都是直接拿毫米当数字用的。
*
* 既然如此,样式里的长度也**只能用 `px`**(在 SVG 里 px 就是用户单位),
* **绝不能写 `mm`**:写 mm 会被浏览器先按 CSS 换算成 px(×3.78),
* 再被 viewBox 缩放一次(×3.78),等于放大 14 倍。
*
* 这个错误的症状极具迷惑性:属性看着完全正确(`font-size:1.7mm`),
* `getComputedStyle` 也报 6.4px,但 `getBoundingClientRect()` 是 236px 宽
* —— 因为它在**用户单位**里是 6.4,再被 viewBox 放大 3.78。
* 表现出来就是「条码下面的 SN 文字大得盖住条码」,而且只在渲染后才看得出。
*/
const textEl = showText
? `<text x="${(totalWidthMm / 2).toFixed(3)}" y="${(heightMm + textMm + 0.25).toFixed(3)}" ` +
`text-anchor="middle" fill="#000" ` +
`style="font-family:Consolas,Monaco,monospace;font-size:${textMm}px;letter-spacing:0.1px">` +
`${escapeXml(text)}</text>`
: "";
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="${totalWidthMm.toFixed(2)}mm" ` +
`height="${totalHeightMm.toFixed(2)}mm" viewBox="0 0 ${totalWidthMm.toFixed(3)} ${totalHeightMm.toFixed(3)}">` +
`<rect width="100%" height="100%" fill="#fff"/>` +
rects.join("") +
textEl +
`</svg>`
);
}
/* ================================================================== */
/* 二维码(真 QR,可扫) */
/* ================================================================== */
export type QrEcLevel = "L" | "M" | "Q" | "H";
export interface QrOptions {
/** 纠错等级,默认 M */
ec?: QrEcLevel;
/** 静区模块数,默认 4(QR 规范要求) */
quiet?: number;
/** 墨色,默认纯黑 */
dark?: string;
}
/**
* 生成**可扫**的二维码 SVG(真 QR Code,ISO/IEC 18004)。
*
* `typeNumber = 0` 让库按内容自动选版本;SN 只有十几位,实际落在版本 1~2,
* 21~25 个模块,在 18mm 的格子里是 0.7~0.9mm/模块 —— 203dpi 打印完全够扫。
*
* ## 为什么出图不写死 mm
*
* 条码必须写死 mm(模块宽度一旦被缩放就不等宽,扫不出);二维码相反:
* 它是**正方形、模块等宽等比**,整张图缩放不破坏任何编码语义。
* 所以这里只给 `viewBox` + `width/height="100%"`,**物理尺寸交给 CSS**
* (`.pt-qrcode`)决定 —— 这样「有没有条码条、格子剩多高」变化时,
* 二维码会自己跟着缩,不需要在 JS 里重复算一遍布局。
*/
export function qrSvg(text: string, opts: QrOptions = {}): string {
const quiet = opts.quiet ?? 4;
const dark = opts.dark ?? "#000";
let model: { getModuleCount(): number; isDark(r: number, c: number): boolean } | null = null;
try {
const qr = qrcode(0, opts.ec ?? "M");
qr.addData(text);
qr.make();
model = qr;
} catch {
model = null;
}
if (!model) {
// 内容拿不出(空串 / 超长)时给一个「未编码」占位框,避免整张标签塌掉
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" ` +
`viewBox="0 0 10 10" preserveAspectRatio="xMidYMid meet">` +
`<rect width="10" height="10" fill="#fff"/>` +
`<rect x="0.3" y="0.3" width="9.4" height="9.4" fill="none" stroke="#111" stroke-width="0.3"/></svg>`
);
}
const count = model.getModuleCount();
const span = count + quiet * 2;
const cells: string[] = [];
for (let r = 0; r < count; r += 1) {
for (let c = 0; c < count; c += 1) {
if (!model.isDark(r, c)) continue;
cells.push(
`<rect x="${c + quiet}" y="${r + quiet}" width="1" height="1" fill="${dark}"/>`
);
}
}
return (
`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" ` +
`viewBox="0 0 ${span} ${span}" shape-rendering="crispEdges" ` +
`preserveAspectRatio="xMidYMid meet">` +
`<rect width="${span}" height="${span}" fill="#fff"/>${cells.join("")}</svg>`
);
}
/* ================================================================== */
/* 辅助 */
/* ================================================================== */
/** 转义 XML 特殊字符,避免文本里的 & < > 把 SVG 弄坏 */
export function escapeXml(input: unknown): string {
return String(input ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
/** SVG 字符串 → 可直接下载 / 贴进 `img` 的 data URL */
export function svgToDataUrl(svg: string): string {
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}
+329
View File
@@ -0,0 +1,329 @@
<template>
<form class="pt-form" @submit.prevent="submitForm">
<div v-for="(item, index) in formConfig.formItems" :key="index" class="pt-form__item">
<!-- 单行文本框 -->
<template v-if="item.type === 'input' || item.type === 'password'">
<Input :title="item.label" :type="item.type" v-model="formData[item.key]" />
<span v-if="errors[item.key]" class="pt-form__error">{{ errors[item.key] }}</span>
</template>
<!-- 多行文本框 -->
<template v-else-if="item.type === 'textarea'">
<label class="pt-form__label">{{ item.label }}</label>
<textarea
v-model="formData[item.key]"
class="pt-form__textarea"
:rows="item.rows || 3"
:placeholder="item.placeholder || `请输入${item.label}`"
></textarea>
<span v-if="errors[item.key]" class="pt-form__error">{{ errors[item.key] }}</span>
</template>
<!-- 下拉选择 -->
<template v-else-if="item.type === 'select'">
<label class="pt-form__label">{{ item.label }}</label>
<select v-model="formData[item.key]" class="pt-form__select">
<option v-for="(opt, idx) in item.options" :key="idx" :value="opt.value">
{{ opt.label }}
</option>
</select>
</template>
<!-- 复选框 -->
<template v-else-if="item.type === 'checkbox'">
<label class="pt-form__label">{{ item.label }}</label>
<label v-for="(opt, idx) in item.options" :key="idx" class="pt-form__choice">
<input type="checkbox" :value="opt.value" v-model="formData[item.key]" />
{{ opt.label }}
</label>
</template>
<!-- 单选框 -->
<template v-else-if="item.type === 'radio'">
<label class="pt-form__label">{{ item.label }}</label>
<label v-for="(opt, idx) in item.options" :key="idx" class="pt-form__choice">
<input type="radio" :value="opt.value" v-model="formData[item.key]" />
{{ opt.label }}
</label>
</template>
<!-- 动态内容行:行数可增删,每行可设置文字 / 字号 / 颜色 / 加粗 -->
<div v-else-if="item.type === 'lines'" class="pt-lines">
<label class="pt-lines__label">{{ item.label }}</label>
<div v-for="(row, rIdx) in formData[item.key] || []" :key="rIdx" class="pt-lines__row">
<div class="pt-lines__head">
<span class="pt-lines__no">第 {{ rIdx + 1 }} 行</span>
<label class="pt-lines__opt">字号(mm)
<select v-model="row.size" class="pt-lines__mini">
<option v-for="s in item.sizeOptions || defaultSizeOptions" :key="s" :value="Number(s)">
{{ s }}
</option>
</select>
</label>
<label v-if="item.colorOptions" class="pt-lines__opt">颜色
<span class="pt-lines__dot" :style="{ backgroundColor: row.color || '#000000' }"></span>
<select v-model="row.color" class="pt-lines__mini">
<option v-for="c in item.colorOptions" :key="c.value" :value="c.value">{{ c.label }}</option>
</select>
</label>
<label class="pt-lines__opt" title="是否加粗">
<input type="checkbox" v-model="row.bold" /> 加粗
</label>
<button
type="button"
class="pt-lines__del"
:disabled="(formData[item.key] || []).length <= 1"
@click="removeLine(item.key, rIdx)"
>删除</button>
</div>
<textarea
v-model="row.text"
class="pt-form__textarea"
:rows="item.rowRows || 2"
:placeholder="`第 ${rIdx + 1} 行内容(可换行)`"
></textarea>
</div>
<button
type="button"
class="pt-btn pt-lines__add"
:disabled="(formData[item.key] || []).length >= (item.maxLines || 20)"
@click="addLine(item.key, item)"
>+ 添加一行</button>
</div>
</div>
<button class="pt-btn pt-btn--primary" type="submit">{{ submitText }}</button>
</form>
</template>
<script setup>
import { reactive, ref, watch } from "vue";
import Input from "./Input.vue";
/**
* 通用动态表单:由模板自带的 `formSchema` 描述生成。
*
* 这一层是「模板可以自己长出新字段」的关键 —— 新增一个规格标签只需要写
* schema + 一个渲染组件,编辑器一行都不用改。
*/
const props = defineProps({
formConfig: { type: Object, required: true },
initialData: { type: Object, default: () => ({}) },
submitText: { type: String, default: "提交" },
});
const emit = defineEmits(["submit"]);
/** 深拷贝:表单编辑不应反向污染模板默认值 / 已添加的格子数据 */
const clone = (obj) => JSON.parse(JSON.stringify(obj ?? {}));
const formData = reactive(clone(props.initialData));
const errors = ref({});
const defaultSizeOptions = [2, 2.5, 3, 3.5, 4, 4.5, 5, 6, 7, 8];
// 父组件切换模板 / 选中别的格子时,重新灌一遍初始值
watch(
() => props.initialData,
(next) => {
const fresh = clone(next);
Object.keys(formData).forEach((key) => delete formData[key]);
Object.assign(formData, fresh);
errors.value = {};
},
{ deep: true }
);
function addLine(key, item) {
if (!Array.isArray(formData[key])) formData[key] = [];
formData[key].push({ text: "", size: Number(item.lineDefaults?.size) || 4, bold: false, color: item.lineDefaults?.color || "#000000" });
}
function removeLine(key, index) {
if ((formData[key] || []).length <= 1) return;
formData[key].splice(index, 1);
}
function validateForm() {
const next = {};
let valid = true;
props.formConfig.formItems.forEach((item) => {
if (item.required && !formData[item.key]) {
next[item.key] = item.rules?.[0]?.message || `${item.label}不能为空`;
valid = false;
}
});
errors.value = next;
return valid;
}
function submitForm() {
if (validateForm()) emit("submit", clone(formData));
}
</script>
<style>
.pt-form__item {
margin-bottom: 10px;
}
.pt-form__label {
display: block;
margin-bottom: 4px;
font-size: 12px;
font-weight: 600;
color: #64748b;
}
.pt-form__error {
display: block;
margin-top: 4px;
font-size: 12px;
color: #dc2626;
}
.pt-form__select,
.pt-form__textarea {
width: 100%;
box-sizing: border-box;
padding: 7px 10px;
border: 1.5px solid #dbe3ec;
border-radius: 9px;
font-size: 13.5px;
font-family: inherit;
color: #1e293b;
background: #f8fafc;
outline: none;
transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}
.pt-form__textarea {
resize: vertical;
line-height: 1.5;
}
.pt-form__select:focus,
.pt-form__textarea:focus {
border-color: #3498db;
background: #fff;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.16);
}
.pt-form__choice {
display: inline-flex;
align-items: center;
gap: 4px;
margin-right: 12px;
font-size: 13px;
color: #334155;
cursor: pointer;
}
/* ---------------- 动态内容行编辑器 ---------------- */
.pt-lines {
max-width: 100%;
}
.pt-lines__label {
display: block;
margin: 0 0 6px;
font-size: 13px;
font-weight: 600;
color: #2c3e50;
}
.pt-lines__row {
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 8px 10px;
margin-bottom: 8px;
background: #f8fafc;
}
.pt-lines__head {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 6px;
font-size: 12.5px;
color: #64748b;
}
.pt-lines__no {
font-weight: 700;
color: #334155;
}
.pt-lines__opt {
display: inline-flex;
align-items: center;
gap: 4px;
cursor: pointer;
}
.pt-lines__dot {
display: inline-block;
width: 11px;
height: 11px;
border-radius: 50%;
border: 1px solid #cbd5e1;
background: #000;
}
.pt-lines__mini {
width: auto;
padding: 2px 6px;
font-size: 12.5px;
border: 1.5px solid #dbe3ec;
border-radius: 6px;
background: #fff;
color: #1e293b;
outline: none;
}
.pt-lines__del {
margin-left: auto;
border: none;
background: #fee2e2;
color: #b91c1c;
font-size: 12px;
padding: 3px 10px;
border-radius: 6px;
cursor: pointer;
}
.pt-lines__del:hover:not(:disabled) {
background: #fecaca;
}
.pt-lines__del:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.pt-lines__add {
width: 100%;
border: 1.5px dashed #3498db;
background: transparent;
color: #3498db;
padding: 6px 0;
font-size: 13px;
}
.pt-lines__add:hover:not(:disabled) {
background: #eef6fd;
}
.pt-lines__add:disabled {
border-color: #cbd5e1;
color: #94a3b8;
cursor: not-allowed;
}
</style>
+82
View File
@@ -0,0 +1,82 @@
<template>
<label class="pt-input">
<span class="pt-input__label">{{ title }}</span>
<input
class="pt-input__field"
:type="type ?? 'text'"
:value="modelValue"
:placeholder="placeholder || `请输入${title}`"
@input="onInput"
/>
</label>
</template>
<script setup lang="ts">
/**
* 带标签的输入框(标签编辑器与顶栏共用)。
*
* 用受控的 `:value` + `@input` 而不是 `v-model` 配局部 ref:原工程那版把
* `modelValue` 拷进局部 ref 再回抛,**父组件重置值后子组件不会跟着变**
* (新建一格、切换模板时最容易踩),受控写法没有这个问题。
*
* `type="number"` 时这里**主动转成数字**再抛。别指望组件上的 `v-model.number`
* ——修饰符在自定义组件上是交给子组件自己处理的,不转的话父组件拿到的是字符串
* (`"3"` 参与 `count + 1` 会变成 `"31"` 这种静默 bug)。
*
* 样式全部挂在 `.pt-input` 之下 —— 插件 CSS 是全局注入的,绝不能出现
* `input { … }` 这种裸标签选择器,那会把宿主的表单一起改掉。
*/
const props = defineProps({
title: { type: String, default: "" },
type: { type: String, default: "text" },
modelValue: { type: [String, Number], default: "" },
placeholder: { type: String, default: "" },
});
const emit = defineEmits(["update:modelValue"]);
function onInput(event: Event) {
const raw = (event.target as HTMLInputElement).value;
if (props.type === "number") {
// 空串保留空串(清空输入框时不至于变成 0),其余转数字
emit("update:modelValue", raw === "" ? "" : Number(raw));
return;
}
emit("update:modelValue", raw);
}
</script>
<style>
.pt-input {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.pt-input__label {
font-size: 12px;
font-weight: 600;
color: #64748b;
}
.pt-input__field {
width: 100%;
box-sizing: border-box;
padding: 7px 10px;
border: 1.5px solid #dbe3ec;
border-radius: 9px;
font-size: 13.5px;
font-family: inherit;
color: #1e293b;
background: #f8fafc;
outline: none;
transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}
.pt-input__field:focus {
border-color: #3498db;
background: #fff;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.16);
}
</style>
+153
View File
@@ -0,0 +1,153 @@
<template>
<div
class="pt-cell"
:class="{
'pt-cell--filled': !!item?.name,
'pt-cell--placeholder': !item?.name,
'pt-cell--selected': selected,
'pt-cell--hidden': !!item?.hidden,
}"
:title="!item?.name ? '空格:单击选中后可编辑' : item.hidden ? '已隐藏(双击恢复显示)' : '双击隐藏内容'"
@click="emit('select')"
@dblclick.prevent="emit('toggle-hide')"
>
<div class="pt-cell__inner" :class="item?.hidden ? 'pt-hide' : 'pt-show'">
<slot v-if="item?.name"></slot>
</div>
<div class="pt-cell__idx"><span>{{ index + 1 }}</span></div>
</div>
</template>
<script setup>
/**
* 单个标签格外壳。
*
* 只负责「格子长什么样 + 交互 + 打印时的显隐」,内容由插槽里的模板组件决定 ——
* 这样模板换一套,格子的选中 / 隐藏 / 序号行为完全不用跟着改。
*
* 所有类名以 `pt-`(print tag)开头:插件样式是**注入宿主全局**的,
* 不加前缀就有和宿主或别的插件撞车的风险。
*/
defineProps({
index: { type: Number, required: true },
item: { type: Object, default: null },
selected: { type: Boolean, default: false },
});
const emit = defineEmits(["select", "toggle-hide"]);
</script>
<style>
/* ====== 标签格子通用外观(含占位 / 选中 / 隐藏 / 打印控制) ====== */
.pt-cell {
display: flex;
justify-content: center;
align-content: flex-start;
margin: 0.25mm;
cursor: pointer;
user-select: none;
position: relative;
background: #fff;
border: 0.1mm dashed transparent;
transition: border-color 0.12s ease, box-shadow 0.12s ease, background-color 0.12s ease;
overflow: hidden;
}
.pt-cell--filled {
border: 0.1mm dashed #87cefa;
}
/* 空格(屏幕上的编辑引导,打印时不会出现) */
.pt-cell--placeholder {
border: 0.1mm dashed #dde5ef;
}
.pt-cell:hover {
background-color: #f4f9ff;
}
.pt-cell--selected {
background-color: #eaf3ff;
box-shadow: inset 0 0 0 1.6px #3b82f6;
z-index: 1;
}
.pt-cell--filled.pt-cell--selected {
border-color: #3b82f6;
}
/* 已隐藏(内容不打印) */
.pt-cell--hidden {
background-image: repeating-linear-gradient(135deg, #fff 0 7mm, #f2f7fd 7mm 14mm);
}
/* 格子序号角标(屏幕辅助,打印不输出) */
.pt-cell__idx {
position: absolute;
top: 0.6mm;
right: 1.2mm;
font-size: 3mm;
line-height: 1;
color: #a9b9cc;
pointer-events: none;
z-index: 2;
}
.pt-cell--selected .pt-cell__idx {
color: #2563eb;
font-weight: 700;
}
.pt-cell--hidden .pt-cell__idx {
color: #90a3b8;
}
.pt-hide {
visibility: hidden;
}
.pt-show {
visibility: visible;
}
.pt-cell__inner {
height: 100%;
width: 100%;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}
/* 最后一行的 4 个格子:给打印页脚留出空隙 */
.pt-cell:nth-child(n + 41) {
padding-bottom: 4mm;
}
/* ====== 打印 ====== */
@media print {
/* 序号角标与空格引导均不打印 */
.pt-cell__idx,
.pt-cell--placeholder {
visibility: hidden !important;
border-color: transparent !important;
background: transparent !important;
}
.pt-cell--hidden {
background: transparent !important;
}
.pt-cell {
box-shadow: none !important;
background: transparent !important;
}
.pt-hide * {
visibility: hidden !important;
}
.pt-show {
visibility: visible;
}
}
</style>
+84
View File
@@ -0,0 +1,84 @@
<template>
<label class="pt-select">
<span v-if="title" class="pt-select__label">{{ title }}</span>
<select
class="pt-select__field"
:value="modelValue?.label ?? ''"
@change="onChange"
>
<option v-for="opt in data" :key="opt.label" :value="opt.label">
{{ opt.label }}
</option>
</select>
</label>
</template>
<script setup lang="ts">
/**
* 模板下拉选择。
*
* 原工程用的是 `@headlessui/vue` 的 Listbox(自绘下拉)。这里换成原生 `<select>`,
* 两个理由:
*
* 1. **插件是独立产物**:headlessui 会整包打进插件(+30KB),而它提供的
* 「键盘可达 / ARIA」原生 `<select>` 本来就有;
* 2. **打印安全**:Listbox 展开时是一层绝对定位的浮层,落在标签纸上方;
* 原生下拉由浏览器绘制,永远不进打印流。
*
* 回传的仍然是**整个选项对象**(而不是 label 字符串),这样调用方拿到的
* 就是 `{ label, formSchema, formData }` 那一份,不必再去数组里 find 一次。
*/
const props = defineProps({
title: { type: String, default: "" },
data: { type: Array, default: () => [] },
modelValue: { type: Object, default: null },
});
const emit = defineEmits(["update:modelValue"]);
interface Option {
label: string;
}
function onChange(event: Event) {
const label = (event.target as HTMLSelectElement).value;
const next = (props.data as Option[]).find((item) => item.label === label);
if (next) emit("update:modelValue", next);
}
</script>
<style>
.pt-select {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.pt-select__label {
font-size: 12px;
font-weight: 600;
color: #64748b;
}
.pt-select__field {
width: 100%;
box-sizing: border-box;
padding: 7px 10px;
border: 1.5px solid #dbe3ec;
border-radius: 9px;
font-size: 13.5px;
font-family: inherit;
color: #1e293b;
background: #f8fafc;
outline: none;
cursor: pointer;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.pt-select__field:focus {
border-color: #3498db;
background: #fff;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.16);
}
</style>
+167
View File
@@ -0,0 +1,167 @@
<template>
<div class="pt-body">
<div class="pt-main">
<!-- 左侧固定信息区:二维码 + 店铺 + 电话 -->
<div v-if="showLeft" class="pt-left">
<!-- SN 模式下换成真二维码;没填 SN 时退回内置静态图,不留白 -->
<div v-if="qrHtml" class="pt-qrcode" v-html="qrHtml"></div>
<img v-else class="pt-qrcode-img" :src="label.defaultImage" alt="" />
<div class="pt-shop">{{ label.shopName }}</div>
<div class="pt-phone">{{ label.phone }}</div>
</div>
<!-- 各模板自己的内容(规格文字 / 自定义行 / 售后说明…) -->
<div class="pt-content"><slot /></div>
</div>
<!-- 可选:底部整宽条码条(Code 128 + SN 文本) -->
<div v-if="barcodeHtml" class="pt-barcode" v-html="barcodeHtml"></div>
</div>
</template>
<script setup>
import { computed } from "vue";
import { LABEL_BARCODE_OPTS, code128Svg, qrSvg } from "../codes";
/**
* 标签内容外壳(所有模板共用)。
*
* ## 为什么单独抽一层
*
* 「左侧二维码 + 店铺 + 电话」和「底部条码条」是所有规格标签**共有**的部分,
* 而原工程把这套结构在每个模板里各抄了一遍。抄 9 遍的后果是:接入 SN 码时
* 要改 9 个文件,而且很容易漏掉一两个。抽成外壳后,模板只关心自己那几行规格文字。
*
* ## 二维码 / 条码的开关语义(这就是「可选」的落点)
*
* - `label.showQr = false` → 完全保持原行为:内置静态二维码图片,不碰 SN;
* - `label.showQr = true` 且这一格有 SN → 渲染**可扫的真二维码**;
* - `label.showQr = true` 但这一格没填 SN → 仍退回静态图(避免出现空白格);
* - `label.showBarcode = true` 且这一格有 SN → 底部加一条整宽 Code 128 条码。
*
* 条码条会占掉约 6.5mm 高度,二维码因此变小 —— 这是物理尺寸决定的,
* 面板上有提示,不在这里偷偷缩放。
*/
const props = defineProps({
/** 该格的标签上下文(SN / 开关 / 店铺信息 / 内置图片) */
label: { type: Object, required: true },
/** 该模板是否要左侧固定信息区(售后 / 自定义文字模板不要) */
showLeft: { type: Boolean, default: true },
});
const qrHtml = computed(() => {
const { showQr, sn } = props.label || {};
if (!showQr || !sn) return "";
return qrSvg(String(sn));
});
const barcodeHtml = computed(() => {
const { showBarcode, sn } = props.label || {};
if (!showBarcode || !sn) return "";
// 参数取自 codes.ts 的共享常量:页面估算「二维码还剩多少高度」用的是同一份
return code128Svg(String(sn), LABEL_BARCODE_OPTS);
});
</script>
<style>
.pt-body {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 0;
}
.pt-main {
flex: 1 1 auto;
min-height: 0;
display: flex;
width: 100%;
}
/* ---------------- 左侧固定信息区 ---------------- */
.pt-left {
width: 24mm;
flex: 0 0 24mm;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
font-size: 3mm;
line-height: 3mm;
color: #87cefa;
overflow: hidden;
}
/* 二维码:高度由可用高度决定(减去店铺 + 电话两行约 6.8mm),宽度按 1:1 推出。
这样有没有条码条都能自动适配,不需要在 JS 里算布局。
⚠️ 6.8mm 不是一个随手写的小数:两行文字 line-height 3mm = 6mm,
加上 0.4mm 下边距 = 6.4mm,再留 0.4mm 余量。写 6mm 会让图片底部被裁掉 2px。 */
.pt-qrcode {
flex: 0 0 auto;
height: min(var(--pt-qr-size, 19mm), calc(100% - 6.8mm));
aspect-ratio: 1 / 1;
margin-bottom: 0.4mm;
}
.pt-qrcode svg {
display: block;
width: 100%;
height: 100%;
}
.pt-qrcode-img {
flex: 0 1 auto;
min-height: 0;
height: calc(100% - 6.8mm);
width: 100%;
object-fit: contain;
margin-bottom: 0.4mm;
}
.pt-shop,
.pt-phone {
flex: 0 0 auto;
white-space: nowrap;
}
/* ---------------- 右侧内容区 ---------------- */
.pt-content {
flex: 1 1 auto;
min-width: 0;
height: 100%;
display: flex;
}
/* 规格类模板在 .pt-right 里排 4 行等宽文字。
⚠️ 字号必须跟着「有没有条码条」变:条码条吃掉 6.6mm 后主区只剩约 17.8mm,
而 4 行 4mm 字(行高 1.2)要 19.2mm —— 第 4 行会直接压到条码上,
而且这个重叠**只在打印出来才看得清**。所以字号由页面的 `--pt-spec-font` 提供:
没有条码时仍是原来的 4mm,与原工程像素级一致。 */
.pt-right {
display: grid;
align-content: center;
align-items: center;
justify-content: center;
height: 100%;
width: auto;
font-size: var(--pt-spec-font, 4mm);
line-height: 1.2;
}
/* ---------------- 底部条码条 ---------------- */
.pt-barcode {
flex: 0 0 auto;
width: 100%;
display: flex;
justify-content: center;
align-items: flex-end;
overflow: hidden;
}
.pt-barcode svg {
display: block;
}
</style>
+169
View File
@@ -0,0 +1,169 @@
/**
* 标签打印插件 —— 入口。
*
* 把原来的 `print-tag-system`(独立 Vue3 + Vite 单页应用)改造成 FunjiaUI 的
* **远端插件**:不再自己起服务、自己管路由,而是由宿主装载,能力全部通过 `ctx` 拿。
*
* ## 改造的边界在哪
*
* | 原来 | 现在 |
* | ---- | ---- |
* | `createApp(App).mount('#app')` | `activate(ctx)` + `ctx.addRoute`,页面挂进宿主 |
* | `/qrcode.png` 从站点根目录取 | 打包成 data URL 内置进产物(远端插件没有自己的 public/) |
* | 自己写 CSS 全局注入 | 仍然全局注入,但类名一律 `pt-` 前缀,避免污染宿主 |
* | `window.print()` 直接调 | 不变,但打印样式改为**临时注入 / 打完即撤** |
* | 无后端 | 可选接入宿主的 `api::sn-code`(见 `pages/PrintTagPage.vue` 的「② SN 码」) |
*
* ## 为什么用自注册通道
*
* 产物全局名叫 `PrintTagBundle`,插件 id 是 `funjia.print-tag` —— 两者可以完全无关。
* 老生态约定「全局名 = 插件名首字母大写」在改名 / 一个脚本塞多个插件时会很别扭,
* 所以这里用 `window.FunjiaPlugin.register({ manifest: { id }, module })`。
* 两种通道宿主都认,用自注册只是更清晰。
*/
import type { PluginCtx, PluginModule } from "./sdk";
import { setCtx } from "./runtime";
import PrintTagPage from "./pages/PrintTagPage.vue";
import { code128Svg, qrSvg } from "./codes";
/** 必须与 plugin.config.json 的 id 完全一致 —— 宿主按它认领产物 */
const PLUGIN_ID = "funjia.print-tag";
/** 路由段;宿主会补成 `/plugin/funjia-print-tag/console` */
const ROUTE_SEGMENT = "console";
const plugin: PluginModule = {
install(ctx: PluginCtx) {
// 一辈子只跑一次:适合放不可逆的初始化。这里没有要迁移的数据,留个痕迹即可。
ctx.storage.set("installedAt", ctx.storage.get<string>("installedAt") || new Date().toISOString());
ctx.logger.info(`[${PLUGIN_ID}] install:首次装载(版本 ${ctx.plugin.version})`);
},
activate(ctx: PluginCtx) {
// ⚠️ 必须调用:pages/*.vue 里的 `useCtx()` 靠它拿到宿主能力。
// 插件模块与页面在同一个产物里共享模块作用域,所以这一行就注入了整个插件。
setCtx(ctx);
/* ---------------- 菜单 + 路由 ---------------- */
// 先菜单、再路由:宿主里「菜单项才是权威」,addMenu 时若路由已存在会用新的
// 菜单 meta 重建路由,顺序反了 title 会在那一刻缺失。
const offMenu = ctx.addMenu({
id: `${PLUGIN_ID}:console`,
title: "标签打印",
icon: "Printer",
path: ROUTE_SEGMENT,
order: 7,
group: "设备管理",
});
const offRoute = ctx.addRoute({
name: "funjia-print-tag-console",
path: ROUTE_SEGMENT,
component: PrintTagPage,
menuTitle: "标签打印",
menuIcon: "Printer",
menuOrder: 7,
meta: { title: "标签打印", icon: "Printer" },
});
/* ---------------- 命令:跨插件协作的正规通道 ---------------- */
// ① 领码:让别的插件(比如 SN 码工具)不必自己再写一遍发放逻辑
const offIssueCmd = ctx.addCommand({
name: "print-tag:issue-sn",
description: "按业务类型领 N 条 SN 码(走宿主 api::sn-code),返回单条对象或数组",
handler: async (
input: { targetType?: string; count?: number; refId?: string; refLabel?: string; remark?: string } = {}
) => {
const count = Math.max(1, Number(input.count) || 1);
const base = {
targetType: input.targetType || "DEVICE",
...(input.refId ? { refId: input.refId } : {}),
...(input.refLabel ? { refLabel: input.refLabel } : {}),
...(input.remark ? { remark: input.remark } : {}),
};
if (count > 1) {
const res = await ctx.http.post<any>("/api/sn-codes/batch", { ...base, count });
if (res.code !== 0) throw new Error(res.msg || "批量领码失败");
return res.data?.items || res.data || [];
}
const res = await ctx.http.post<any>("/api/sn-codes/generate", base);
if (res.code !== 0) throw new Error(res.msg || "领码失败");
return res.data;
},
});
// ② 出图:**纯本地、不调接口**。任何插件想给自己的标签画条码 / 二维码,
// 调这一条就行 —— 省掉各自引一份条码库、以及各自踩一遍 Code 128 校验位的坑。
const offRenderCmd = ctx.addCommand({
name: "print-tag:render-svg",
description: '把文本渲染成条码 / 二维码 SVG:render-svg({ text, type }) → { barcode?, qr? }',
handler: (input: { text: string; type?: "qr" | "barcode" | "both"; widthMm?: number; heightMm?: number } = { text: "" }) => {
const type = input.type || "both";
const text = String(input.text ?? "");
const out: { barcode?: string; qr?: string } = {};
if (!text) return out;
if (type === "barcode" || type === "both") {
out.barcode = code128Svg(text, { widthMm: input.widthMm ?? 46, heightMm: input.heightMm ?? 7 });
}
if (type === "qr" || type === "both") {
out.qr = qrSvg(text);
}
return out;
},
});
/* ---------------- 插件私有存储 ---------------- */
const bootCount = (ctx.storage.get<number>("bootCount", 0) || 0) + 1;
ctx.storage.set("bootCount", bootCount);
ctx.storage.set("lastActivatedAt", new Date().toISOString());
/* ---------------- 事件 ---------------- */
// 局部通道:宿主自动加插件前缀,所以 "issued" 这种通用名字不会和别人撞。
const offEvent = ctx.event.on("issued", (payload: unknown) => {
ctx.logger.debug("已领码并填入标签", payload);
});
ctx.logger.info(
`[${PLUGIN_ID}] activate:1 个页面 + 2 个命令(第 ${bootCount} 次启用,版本 ${ctx.plugin.version})`
);
// 显式登记清理项:宿主也会兜底回收,但自己登记更干净,
// 尤其是插件将来挂了定时器 / 全局监听时(那种宿主看不见)。
ctx.onDispose(() => {
offMenu();
offRoute();
offIssueCmd();
offRenderCmd();
offEvent();
ctx.logger.info(`[${PLUGIN_ID}] 清理项已执行(菜单/路由/命令/事件已撤)`);
});
},
deactivate(ctx: PluginCtx) {
// 通常不用写:宿主会统一回收注册项。这里只把 ctx 还回去,
// 避免页面组件在插件被禁用后还拿着旧上下文。
setCtx(null);
ctx.logger.info(`[${PLUGIN_ID}] deactivate:注册项已由宿主回收`);
},
uninstall(ctx: PluginCtx) {
// 宿主会连插件私有存储一起清空(店铺名 / 电话 / SN 开关都存在那里)。
ctx.logger.info(`[${PLUGIN_ID}] uninstall:插件私有存储即将被清空`);
},
};
if (window.FunjiaPlugin) {
window.FunjiaPlugin.register({ manifest: { id: PLUGIN_ID }, module: plugin });
} else {
// 宿主没注入全局契约时给一句明确的话,否则表现为「脚本加载了但什么都没发生」,
// 排查时会先去怀疑路径 / CORS / 缓存,绕一大圈才回到真正的原因。
console.error(
`[${PLUGIN_ID}] 找不到 window.FunjiaPlugin:本脚本必须由宿主页面加载,不能单独引入。`
);
}
export default plugin;
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
/**
* 插件内的宿主环境持有者。
*
* 插件模块(`src/*.ts`)与页面组件(`pages/*.vue`)是**同一个构建产物**里的两个文件,
* 共享同一个模块作用域。于是激活时把 `ctx` 存下来,页面组件就能拿到宿主能力,
* 而不必去 import 宿主的任何实现代码。
*
* 这是远端插件的标准做法:**能力靠注入,不靠 import**。
* 反过来(页面里直接 import 宿主模块)会让插件与宿主版本强绑定,
* 宿主一升级,插件产物就可能整体失效。
*/
import type { PluginCtx } from "./sdk";
let current: PluginCtx | null = null;
export function setCtx(ctx: PluginCtx | null): void {
current = ctx;
}
/** 取宿主上下文;未激活时给出明确错误,而不是让页面静默渲染空白 */
export function useCtx(): PluginCtx {
if (!current) {
throw new Error("插件上下文尚未注入:请确认插件已启用(activate 已执行)");
}
return current;
}
+210
View File
@@ -0,0 +1,210 @@
/**
* 插件侧 SDK 契约(本地声明版)。
*
* ## 为什么这里是一份「手抄」的类型,而不是 import 宿主的类型
*
* 远端插件是**独立交付物**:它由外部团队构建、上传脚本、被宿主加载。
* 让它 `import type { PluginContext } from "../../src/core/plugin/types"`
* 意味着插件与宿主源码目录强耦合 —— 宿主重构一次,所有插件的构建就全废。
*
* 真实项目里的做法是宿主发布一个 SDK 包(如 `@funjia/plugin-sdk`),
* 插件依赖那个包的版本。本演示把这份契约就地声明,作用等价:
* **插件只依赖契约,不依赖宿主实现**。
*
* 当宿主新增扩展点时,这里补一个方法即可 —— 而且旧插件不补也能继续跑
* (TypeScript 的类型是编译期的,运行时只认实际调用)。
*/
/** 释放函数:调用即撤销这次注册 */
export type Disposer = () => void;
/** 宿主注入给插件的运行环境 */
export interface PluginCtx {
/** 宿主版本(如 `1.0.0`),插件可据此做兼容分支 */
hostVersion: string;
plugin: {
id: string;
name: string;
version: string;
kind: string;
/**
* 插件来自哪个**插件仓库**(从仓库安装时由宿主写入)。
*
* 手工填 URL 安装的插件没有这个字段 —— 所以「插件能不能知道自己是
* 从哪个仓库来的」本身就是「有没有走仓库」的判据(`demo.repo-badge` 就靠它)。
*/
repository?: string;
/** 仓库索引里声明的产物 SHA-256(留档) */
checksum?: string;
};
logger: {
debug(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
};
/** 插件私有存储(宿主按插件 id 做了命名空间隔离) */
storage: {
get<T = any>(key: string, fallback?: T): T;
set(key: string, value: any): void;
remove(key: string): void;
};
/**
* 请求层:插件不直接碰 fetch / axios。
*
* 走它的好处是「鉴权头、mock 适配、`{ code, msg, data }` 规整」都由宿主统一做;
* 直连 fetch 的插件在换后端协议时会一起坏掉。
*
* ## 三条与返回值有关的约定(踩过才知道)
*
* 1. **业务码非 0 不抛错**,只是 `code !== 0`;只有网络层故障(后端没起、
* 网关 5xx、响应不是 JSON)才抛 —— 所以 `try/catch` 是兜底,不是主流程。
* 2. **`code === 401` 什么都不用做**:宿主已经接管(清会话 + 跳登录页),
* 直接 `return` 即可。插件再跳一次路由只会造成重复跳转。
* 3. **列表数据的形状**是 `data` 存数组、`total` 存总数(同级),
* 不是 `data.rows`。
*/
http: {
/** 需要显式指定 method 时用它;日常用下面四个更省事 */
request<T = any>(options: RequestOptions): Promise<ApiResult<T>>;
/** `params` 会被拼成查询串 */
get<T = any>(url: string, params?: Record<string, any>): Promise<ApiResult<T>>;
post<T = any>(url: string, data?: any): Promise<ApiResult<T>>;
put<T = any>(url: string, data?: any): Promise<ApiResult<T>>;
/** `params` 会被拼成查询串 */
del<T = any>(url: string, params?: Record<string, any>): Promise<ApiResult<T>>;
};
/** 消息提示(宿主用 Element Plus 实现,插件不必自己 import) */
ui: {
success(message: string): void;
error(message: string): void;
warning(message: string): void;
info(message: string): void;
confirm(message: string, title?: string): Promise<boolean>;
alert(message: string, title?: string): Promise<void>;
};
/** 当前登录用户(未登录返回 null) */
getUser(): Record<string, any> | null;
/** 侧边菜单 */
addMenu(menu: {
id: string;
title: string;
icon?: string;
path?: string;
order?: number;
group?: string;
}): Disposer;
/** 路由页面 */
addRoute(route: {
name: string;
path: string;
component: unknown;
/** 附加到 `route.meta`,宿主会补上 `plugin` / `viewModel` */
meta?: Record<string, unknown>;
menuTitle?: string;
menuIcon?: string;
menuOrder?: number;
}): Disposer;
/** 仪表盘卡片(`span` 为 1~12 栅格宽度) */
addWidget(widget: { id: string; title: string; component: unknown; span?: number; order?: number }): Disposer;
/** 顶栏动作按钮 */
addToolbarAction(action: {
id: string;
title: string;
icon?: string;
handler: () => void | Promise<void>;
order?: number;
}): Disposer;
/** 设置页区块 */
addSettingsSection(section: { id: string; title: string; component: unknown; order?: number }): Disposer;
/** 注册配置类(视图模型) */
addViewModel(model: { name: string; target: unknown; description?: string }): Disposer;
/** 取已注册的配置类(跨插件读取别人的 viewModel) */
getViewModel(name: string): unknown;
/** 命令:跨插件调用 */
addCommand(command: { name: string; handler: (...args: any[]) => any; description?: string }): Disposer;
/** 命令查询;返回 undefined 表示对方插件未启用,插件应自行降级 */
getCommand(name: string): { name: string; handler: (...args: any[]) => any } | undefined;
/** 事件总线:局部通道(宿主自动加插件前缀)/ 全局通道 */
event: {
on(event: string, handler: (...args: any[]) => void): Disposer;
emit(event: string, ...args: any[]): void;
onGlobal(event: string, handler: (...args: any[]) => void): Disposer;
emitGlobal(event: string, ...args: any[]): void;
};
/** 登记自清理函数(定时器、全局监听等宿主看不见的资源) */
onDispose(fn: Disposer): Disposer;
}
/** 与老系统保持一致的接口返回结构 */
export interface ApiResult<T = any> {
code: number;
msg: string;
data: T;
total?: number;
}
/**
* `ctx.http.request()` 的参数。
*
* 只在「method 是算出来的」或「要带缓存开关」时才需要它;
* 其它情况用 `get / post / put / del` 更短也更难写错 ——
* 尤其是别把 `params` 和 `data` 搞混:前者拼进 URL(GET/DELETE),
* 后者是请求体(POST/PUT)。
*/
export interface RequestOptions {
url: string;
method?: "GET" | "POST" | "PUT" | "DELETE";
/** GET / DELETE 的查询参数 */
params?: Record<string, any>;
/** POST / PUT 的请求体 */
data?: any;
}
/** 插件模块:ESM 的 default 导出 / IIFE 挂在 window 上的对象 */
export interface PluginModule {
activate(ctx: PluginCtx): void | Promise<void>;
deactivate?(ctx: PluginCtx): void | Promise<void>;
install?(ctx: PluginCtx): void | Promise<void>;
uninstall?(ctx: PluginCtx): void | Promise<void>;
}
/** 宿主注入的全局对象(IIFE 插件从 window 上取) */
declare global {
interface Window {
vue: any;
funjiaui: any;
/** 插件自注册通道:适合一个脚本里包含多个插件的情况 */
FunjiaPlugin?: { register(input: any): void };
/**
* 宿主信息与只读能力。
*
* `http` 是给**不通过 `activate(ctx)` 起手的脚本**用的(例如裸配置类插件):
* 它们没有 `ctx`,又想用宿主统一的请求层(鉴权头、mock 适配、错误规整)。
*/
FunjiaHost?: {
name: string;
version: string;
http: {
get<T = any>(url: string, params?: Record<string, any>): Promise<ApiResult<T>>;
post<T = any>(url: string, data?: any): Promise<ApiResult<T>>;
put<T = any>(url: string, data?: any): Promise<ApiResult<T>>;
del<T = any>(url: string, params?: Record<string, any>): Promise<ApiResult<T>>;
};
/**
* 当前登录用户;未登录返回 `null`。
*
* 与 `ctx.getUser()` 是同一个东西 —— 这里这份是给**没有 `ctx` 的裸脚本插件**
* 用的(例如纯配置类插件),它们要按角色隐藏按钮、或判断「现在有没有人登录」,
* 只有这一个入口。
*/
getUser(): Record<string, any> | null;
/** 是否已登录。等价于 `getUser() !== null`,但读起来直白得多 */
isLoggedIn(): boolean;
getViewModel(name: string): unknown;
stats(): Record<string, number>;
};
}
}
export type {};
+68
View File
@@ -0,0 +1,68 @@
<template>
<TagShell :label="label" :show-left="false">
<div v-if="visibleLines.length" class="pt-ct">
<div v-for="(line, idx) in visibleLines" :key="idx" class="pt-ct__line" :style="lineStyle(line)">
{{ line.text }}
</div>
</div>
</TagShell>
</template>
<script setup lang="ts">
import { computed } from "vue";
import TagShell from "../components/TagShell.vue";
/**
* 自定义文字标签:行数可自由增删,每行可单独设字号 / 颜色 / 加粗。
*
* 空行**既不在格子上占位、也不显示** —— 这既是「留白」的实现方式,
* 也顺手成了一个「临时停用某一行」的开关(清空文字即可,不必删行)。
*/
const props = defineProps({
config: { type: Object, default: () => ({}) },
label: { type: Object, required: true },
});
interface Line {
text?: string;
size?: number | string;
bold?: boolean;
color?: string;
}
const visibleLines = computed(() =>
((props.config?.lines || []) as Line[]).filter((line) => String(line?.text ?? "").trim() !== "")
);
function lineStyle(line: Line) {
const size = Number(line?.size) || 4;
return {
fontSize: `${size}mm`,
lineHeight: `${Math.max(1.1, size * 1.25).toFixed(2)}mm`,
fontWeight: line?.bold ? "bold" : "normal",
color: line?.color || "#000000",
};
}
</script>
<style>
.pt-ct {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.4mm;
overflow: hidden;
}
.pt-ct__line {
width: 100%;
text-align: center;
white-space: pre-wrap;
word-break: break-word;
overflow-wrap: anywhere;
color: #000;
}
</style>
+54
View File
@@ -0,0 +1,54 @@
<template>
<TagShell :label="label" :show-left="false">
<div class="pt-error">
<div class="pt-error__title">{{ config.title }}</div>
<div class="pt-error__reason">{{ config.reason }}</div>
<div class="pt-error__time">{{ config.time }}</div>
</div>
</TagShell>
</template>
<script setup lang="ts">
import TagShell from "../components/TagShell.vue";
/**
* 售后 / 故障标签:只有标题 + 说明 + 时间,**不要**左侧固定信息区。
*
* `show-left=false` 时会话里那套「店铺 + 电话 + 二维码」整块不渲染,
* 但**底部条码条仍然有效** —— 售后单号贴个条码一扫就能调出工单,
* 这正是「可选」该有的粒度:两块各自独立开关,不是一刀切。
*/
defineProps({
config: { type: Object, default: () => ({}) },
label: { type: Object, required: true },
});
</script>
<style>
.pt-error {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
padding: 0 1mm;
box-sizing: border-box;
}
.pt-error__title {
color: red;
font-size: 0.8cm;
line-height: 1.1;
}
.pt-error__reason {
font-size: 4mm;
line-height: 4.4mm;
margin-top: 2mm;
}
.pt-error__time {
font-size: 4mm;
line-height: 4.4mm;
}
</style>
+38
View File
@@ -0,0 +1,38 @@
<template>
<TagShell :label="label">
<div class="pt-right">
<div v-for="key in fields" :key="key">{{ config?.[key] }}</div>
</div>
</TagShell>
</template>
<script setup lang="ts">
import TagShell from "../components/TagShell.vue";
/**
* 规格类标签(台式机 / 一体机 / 硬盘)的通用渲染器。
*
* ## 为什么把 9 个近乎一样的组件合成 1 个
*
* 原工程里 `I5_10400F_16G_256G_1060.vue`、`22寸一体机_4G_120G.vue`、
* `HardDisk.vue` 等 9 个文件的结构**完全一致**:左侧固定信息区 + 右侧 4 行文字。
* 它们之间唯一的差别是「这 4 行取 config 的哪 4 个键」,以及各自的表单 schema。
*
* 9 份拷贝在「接入 SN 码」这件事上会变成 9 处修改,漏一个就有一个模板不显示条码;
* 字段顺序也只能靠肉眼比对。所以这里把「渲染」和「字段表」拆开:
*
* - 渲染 → 本组件(一份,永远一致);
* - 字段顺序 → `registry.ts` 里每个模板的 `fields` 数组(一眼能看出差别)。
*
* 需要给某个模板开小灶(换布局、加图标)时,再单独写一个组件即可 —— 注册表里
* `component` 指向谁就渲染谁,不受这里影响。
*/
defineProps({
/** 该格保存的模板字段值 */
config: { type: Object, default: () => ({}) },
/** 标签上下文(SN / 二维码开关 / 店铺信息) */
label: { type: Object, required: true },
/** 右侧按顺序显示的字段名 */
fields: { type: Array, default: () => [] },
});
</script>
+281
View File
@@ -0,0 +1,281 @@
/**
* 模板注册表 —— 新增一个标签模板只需要在这里加一项。
*
* ## 一项由四部分组成
*
* | 字段 | 作用 |
* | ---- | ---- |
* | `label` | 下拉里显示的名字,**同时是该格存储的模板标识**(换名字等于换模板) |
* | `component` | 标签怎么画(`SpecTag` 通用渲染 / 专用组件) |
* | `formSchema` | 编辑表单长什么样(由 `DynamicForm` 通用渲染) |
* | `formData` | 新格的默认值 |
* | `fields` | 仅 `SpecTag` 用:右侧按顺序显示的字段名 |
*
* ## 与原工程的关系
*
* 原 `print-tag-system` 里 9 个规格模板是 9 个几乎一样的 `.vue` 文件,
* 差别只有「右侧取哪 4 个字段」和各自的选项表。这里把渲染收敨成 `SpecTag`,
* 把差异集中到这张表 —— 行为(字段、选项、默认值、顺序)与原工程逐项对齐。
*/
import type { Component } from "vue";
import SpecTag from "./SpecTag.vue";
import ErrorTag from "./ErrorTag.vue";
import CustomTag from "./CustomTag.vue";
export interface FormItem {
type: string;
label: string;
key: string;
required?: boolean;
rows?: number;
rowRows?: number;
placeholder?: string;
options?: Array<{ label: string; value: string }>;
rules?: Array<{ message: string }>;
[key: string]: unknown;
}
export interface FormSchema {
formItems: FormItem[];
}
export interface TagTemplate {
/** 下拉显示名,也是格子里的模板标识 */
label: string;
component: Component;
formSchema: FormSchema;
formData: Record<string, any>;
/** 仅 SpecTag 使用:右侧规格行按此顺序取值 */
fields?: string[];
}
/* ------------------------------------------------------------------ */
/* 复用的选项表 */
/* ------------------------------------------------------------------ */
const CPU_MEMORY = [
{ label: "8G", value: "8G" },
{ label: "16G", value: "16G" },
{ label: "32G", value: "32G" },
];
const CPU_MEMORY_LITE = [
{ label: "8G", value: "8G" },
{ label: "4G", value: "4G" },
{ label: "16G", value: "16G" },
];
const DISK_FULL = [
{ label: "120G", value: "120G" },
{ label: "256G", value: "256G" },
{ label: "256G+1tb", value: "256G+1tb" },
{ label: "512G", value: "512G" },
{ label: "1tb", value: "1tb" },
];
const DISK_LITE = [
{ label: "120G", value: "120G" },
{ label: "256G", value: "256G" },
{ label: "512G", value: "512G" },
];
const GPU_OPTIONS = [
{ label: "1060", value: "1060(3,5,6)" },
{ label: "960", value: "960" },
{ label: "1660", value: "1660" },
{ label: "2060", value: "2060" },
{ label: "3060", value: "3060" },
{ label: "4060", value: "4060" },
];
const OS_OPTIONS = [
{ label: "无", value: "" },
{ label: "win10", value: "win10" },
{ label: "win7", value: "win7" },
];
/** 台式机(带独显)三兄弟:CPU / 内存 / 硬盘 / 显卡 */
const desktopWithGpu = (cpu: string, memory: string, hardDisk: string, graphicsCard: string): Pick<TagTemplate, "formSchema" | "formData" | "fields"> => ({
fields: ["cpu", "memory", "hardDisk", "graphicsCard"],
formSchema: {
formItems: [
{ type: "input", label: "CPU", key: "cpu", required: true },
{ type: "select", label: "内存", key: "memory", options: CPU_MEMORY },
{ type: "select", label: "硬盘", key: "hardDisk", options: DISK_FULL },
{ type: "select", label: "显卡", key: "graphicsCard", options: GPU_OPTIONS },
],
},
formData: { cpu, memory, hardDisk, graphicsCard },
});
/** 台式机(核显):CPU / 内存 / 硬盘 / 操作系统 */
const desktopWithOs = (cpu: string, memory: string, hardDisk: string, system: string): Pick<TagTemplate, "formSchema" | "formData" | "fields"> => ({
fields: ["cpu", "memory", "hardDisk", "system"],
formSchema: {
formItems: [
{ type: "input", label: "CPU", key: "cpu", required: true },
{ type: "select", label: "内存", key: "memory", options: CPU_MEMORY_LITE },
{ type: "select", label: "硬盘", key: "hardDisk", options: DISK_LITE },
{ type: "select", label: "操作系统", key: "system", options: OS_OPTIONS },
],
},
formData: { cpu, memory, hardDisk, system },
});
/** 一体机:标题 / CPU / 内存 / 硬盘 */
const allInOne = (name: string, cpu: string, memory: string, hardDisk: string): Pick<TagTemplate, "formSchema" | "formData" | "fields"> => ({
fields: ["name", "cpu", "memory", "hardDisk"],
formSchema: {
formItems: [
{ type: "input", label: "标题", key: "name", required: true },
{ type: "input", label: "CPU", key: "cpu", required: true },
{ type: "select", label: "内存", key: "memory", options: CPU_MEMORY_LITE },
{ type: "select", label: "硬盘", key: "hardDisk", options: DISK_LITE },
],
},
formData: { name, cpu, memory, hardDisk },
});
/* ------------------------------------------------------------------ */
/* 注册表 */
/* ------------------------------------------------------------------ */
export const TEMPLATES: TagTemplate[] = [
{
label: "I5_10400F_16G_256G_1060",
component: SpecTag,
...desktopWithGpu("i5 10400F", "16G", "256G", "1060(3,5,6)"),
},
{
label: "I5_10400F_16G_256G_2060",
component: SpecTag,
...desktopWithGpu("i5 10400F", "16G", "512G", "2060"),
},
{
label: "I5_9400F_16G_256G_1060",
component: SpecTag,
...desktopWithGpu("i5 9400F", "16G", "256G", "1060(3,5,6)"),
},
{
label: "I5_4590_8G_120G",
component: SpecTag,
...desktopWithOs("i5 4590", "8G", "120G", ""),
},
{
label: "I3_4130_8G_120G",
component: SpecTag,
...desktopWithOs("i3 4130", "8G", "120G", ""),
},
{
label: "G3260_8G_120G",
component: SpecTag,
...desktopWithOs("G3260", "8G", "120G", ""),
},
{
label: "24寸一体机_I5_3代_8G_256G",
component: SpecTag,
...allInOne("24寸一体机", "I5 3代", "8G", "256G"),
},
{
label: "22寸一体机_4G_120G",
component: SpecTag,
...allInOne("22寸一体机", "M380", "8G", "256G"),
},
{
label: "HardDisk",
component: SpecTag,
fields: ["system", "partition", "hardDisk", "brand"],
formSchema: {
formItems: [
{ type: "select", label: "系统", key: "system", options: [
{ label: "win10", value: "win10" },
{ label: "win7", value: "win7" },
{ label: "win11", value: "win11" },
] },
{ type: "select", label: "分区", key: "partition", options: [
{ label: "MBR", value: "MBR" },
{ label: "GPT", value: "GPT" },
] },
{ type: "select", label: "硬盘", key: "hardDisk", options: [
{ label: "120G", value: "120G" },
{ label: "128G", value: "128G" },
{ label: "256G", value: "256G" },
{ label: "240G", value: "240G" },
{ label: "512G", value: "512G" },
{ label: "480G", value: "480G" },
{ label: "1TB", value: "1TB" },
{ label: "960G", value: "960G" },
] },
{ type: "select", label: "品牌", key: "brand", options: [
{ label: "泽域", value: "泽域" },
{ label: "华鑫云", value: "华鑫云" },
{ label: "昂达", value: "昂达" },
{ label: "金士顿", value: "金士顿" },
{ label: "其它", value: "其它" },
] },
],
},
formData: { system: "win10", partition: "MBR", hardDisk: "256G", brand: "泽域" },
},
{
label: "Error",
component: ErrorTag,
formSchema: {
formItems: [
{ type: "select", label: "标题", key: "title", options: [
{ label: "售后", value: "售后" },
{ label: "故障", value: "故障" },
{ label: "资料备份", value: "资料备份" },
{ label: "维修/升级", value: "维修/升级" },
] },
{ type: "input", label: "说明", key: "reason" },
{ type: "input", label: "时间", key: "time" },
],
},
formData: { title: "售后", reason: "硬盘卡,无法格式化", time: "" },
},
{
label: "CustomTag",
component: CustomTag,
formSchema: {
formItems: [
{
type: "lines",
label: "标签内容(每行显示为一个文本行)",
key: "lines",
lineDefaults: { text: "", size: 4, bold: false, color: "#000000" },
sizeOptions: [2, 2.5, 3, 3.5, 4, 4.5, 5, 6, 7, 8],
colorOptions: [
{ label: "黑色", value: "#000000" },
{ label: "深灰", value: "#374151" },
{ label: "红色", value: "#dc2626" },
{ label: "橙色", value: "#ea580c" },
{ label: "蓝色", value: "#2563eb" },
{ label: "绿色", value: "#16a34a" },
],
maxLines: 20,
},
],
},
formData: {
lines: [
{ text: "", size: 5, bold: true, color: "#000000" },
{ text: "", size: 3.5, bold: false, color: "#dc2626" },
],
},
},
];
/** 下拉选项:只带 label / formSchema / formData,足够渲染表单 */
export const TEMPLATE_OPTIONS = TEMPLATES.map(({ label, formSchema, formData }) => ({
label,
formSchema,
formData,
}));
/** 模板标识 → 渲染组件 */
export const TEMPLATE_COMPONENTS = new Map(TEMPLATES.map((t) => [t.label, t.component]));
/** 模板标识 → 右侧字段顺序 */
export const TEMPLATE_FIELDS = new Map(TEMPLATES.map((t) => [t.label, t.fields ?? []]));
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "es2015",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"lib": ["es2015", "dom"],
"skipLibCheck": true,
"esModuleInterop": true,
"isolatedModules": true,
"noEmit": true,
"types": ["node"],
"baseUrl": ".",
// 预览页要 import ../plugin.config.json(Vite 本来就能处理,是 tsc 需要这个开关)
"resolveJsonModule": true
},
"include": [
"src/**/*.ts",
"src/**/*.vue",
"preview/**/*.ts",
"preview/**/*.vue",
"env.d.ts"
]
}
+96
View File
@@ -0,0 +1,96 @@
/**
* 插件构建配置(一个工程 = 一个插件)。
*
* ## 唯一的真源是 `plugin.config.json`
*
* 产物文件名、IIFE 全局名、格式(IIFE / ESM)全部从这里读 —— 不在这里写第二遍。
* 理由很实际:这几个值**必须**与「发布到仓库时那条 `repo.config.json` 条目」
* 完全一致(`artifact` 对不上 → 发布脚本找不到产物;`globalKey` 对不上 →
* 脚本加载成功但宿主认领不到插件)。让它们只有一个来源,就不会对不上。
*
* ## 依赖共享的规矩(别改,除非你知道后果)
*
* `vue` 与 `funjiaui` **必须 external**,由宿主提供:
*
* - IIFE:靠 `output.globals` 映射到 `window.vue` / `window.funjiaui`;
* - ESM:`output.globals` 对 ESM 无效(rollup 会忽略),产物里保留裸说明符
* `from "vue"`,由宿主的 import map 解析;宿主还有一条不依赖 import map 的
* 兜底通道,所以你不需要为此做任何事。
*
* 为什么必须共享 `vue`:插件与宿主各打一份 Vue,会导致**两份响应式系统互相不认**,
* 症状是「页面渲染出来了、但完全点不动」。这是最容易踩、也最难看懂的一个坑。
*
* 其它依赖(element-plus、lodash、图表库…)**不要 external**,让它们打进产物。
* 插件体积大一点没关系,宿主不必为了插件把整个组件库挂到全局。
*/
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
const root = __dirname;
const cfg = JSON.parse(readFileSync(resolve(root, "plugin.config.json"), "utf8"));
const FORMAT = cfg.kind === "esm" ? "es" : "iife";
/**
* IIFE 需要 `lib.name`(rollup 用它生成 `var <name> = …`)。
*
* - 走 `window.<globalKey>` 通道的插件:必须与 `globalKey` 一致;
* - 走 `window.FunjiaPlugin.register()` 自注册通道的插件:这个名字不影响认领,
* 但仍然要是合法标识符(rollup 会直接把它写进代码)。
*/
const GLOBAL_NAME = cfg.globalKey || cfg.id.replace(/[^A-Za-z0-9_$]/g, "_");
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(GLOBAL_NAME)) {
throw new Error(
`plugin.config.json 的 globalKey 不合法:${JSON.stringify(GLOBAL_NAME)}\n` +
"它会被写进产物当全局变量名,必须以字母 / _ / $ 开头,其后只含字母、数字、_、$。"
);
}
if (!/^[A-Za-z0-9_.-]+\.(iife|es)\.js$/.test(cfg.artifact)) {
throw new Error(
`plugin.config.json 的 artifact 不合法:${JSON.stringify(cfg.artifact)}\n` +
'它同时是产物文件名与仓库索引里的 artifact 字段,形状应为 "<Name>.iife.js" 或 "<Name>.es.js"。'
);
}
/** 与宿主 `installHostGlobals()` 挂的全局严格对应 */
const HOST_GLOBALS: Record<string, string> = {
vue: "vue",
funjiaui: "funjiaui",
};
export default defineConfig({
root,
plugins: [vue()],
build: {
target: "es2015",
outDir: resolve(root, "dist"),
// 一个工程只有一个插件,可以放心清空 —— 避免上一版的陈旧产物被误发布
emptyOutDir: true,
// 样式不拆成多份:宿主按 manifest.style 注入**一个**文件,拆了会漏注入
cssCodeSplit: false,
sourcemap: false,
lib: {
entry: resolve(root, "src/index.ts"),
name: GLOBAL_NAME,
formats: [FORMAT],
// 产物名直接取自 plugin.config.json —— 与仓库索引里的 artifact 天然一致
fileName: () => cfg.artifact,
},
rollupOptions: {
external: Object.keys(HOST_GLOBALS),
output: {
globals: HOST_GLOBALS,
assetFileNames: cfg.style || `${GLOBAL_NAME}[extname]`,
// ⚠️ 不能省:否则「导出被 rollup 判成 namespace」时,
// 产物会变成 `window.X = { default: class {} }`,宿主拿到后
// **不报错、但页面渲染不出任何东西** —— 最难查的一类静默失败。
...(FORMAT === "iife" ? { exports: "default" as const } : {}),
},
},
},
});
+172
View File
@@ -0,0 +1,172 @@
/**
* 预览服务器配置(`npm run dev` / `npm run preview`)。
*
* ## 与 `vite.config.ts` 的分工
*
* | 配置 | 干什么 | 形态 |
* | ---- | ------ | ---- |
* | `vite.config.ts` | **构建**产物 | lib 模式,`vue` / `funjiaui` 必须 external |
* | `vite.preview.config.ts` | **预览**插件 | 应用模式,root 指向 `preview/` |
*
* 两者不能合并。构建时必须把 `vue` external 掉,产物才能交给宿主的 Vue 跑;
* 而预览时必须把 `vue` 真正打进来,页面才能渲染。同一个 Vite 进程做不到两种
* 相反的依赖策略,所以分两个配置 —— 这也是为什么 `npm run build` 与
* `npm run dev` 用的是不同的配置文件。
*
* ## 预览服务器多了什么
*
* 两个中间件,都是为了让「预览」尽量接近「真宿主」:
*
* 1. **静态中间件**:把 `/artifact/<文件名>` 映射到工程的 `dist/`。
* 产物模式(`npm run preview`)要靠它按**真实 URL** 加载产物 ——
* IIFE 走 `<script src>`、ESM 走 `import()`,和宿主装载时是同一套路径规则。
* 2. **`/api` 后端**:见下。
*
* ## `/api` 从哪来(这就是「预览里能不能调接口」的答案)
*
* | 情况 | `/api/**` 去哪 | 什么时候用 |
* | ---- | ------------- | ---------- |
* | 默认 | 内置 mock 后端(`preview/mock-api.ts`) | 平时开发:不依赖任何外部服务,`ctx.http` 立刻有数据 |
* | 设了 `PREVIEW_API_TARGET` | **代理到那个地址** | 真后端(或宿主的 dev server)已经起来了,想连它调 |
*
* ```bash
* # 连本机跑着的宿主 dev server(它有完整的 /api mock)
* PREVIEW_API_TARGET=http://127.0.0.1:5180 npm run dev
* ```
*
* 走代理而不是让页面直连,是为了**绕开跨域**:浏览器眼里请求始终是发给
* `127.0.0.1:5310` 的同源请求,CORS 与 Cookie 的 SameSite 规则都不会插一脚。
* 这与宿主里 dev 阶段的代理做法是同一个套路。
*
* ⚠️ 两个后端给出的数据**不会一致**:内置 mock 是几个固定行,
* 宿主 mock 有它自己那套种子数据。别拿预览看到的数据去对宿主的账。
*/
import { defineConfig } from "vite";
import type { Plugin } from "vite";
import vue from "@vitejs/plugin-vue";
import { createReadStream, existsSync, statSync } from "node:fs";
import { extname, resolve, sep } from "node:path";
import { createPreviewApi } from "./preview/mock-api";
const projectRoot = __dirname;
/** 预览页的根目录:`/` 就是工程里的 `preview/` */
const previewRoot = resolve(projectRoot, "preview");
/** 构建产物目录(`vite.config.ts` 里 `outDir` 指的是同一处) */
const artifactDir = resolve(projectRoot, "dist");
/**
* 真后端地址。**设了就停用内置 mock**,把 `/api/**` 整个转过去。
*
* 只认 `http://` / `https://` 开头的值:写错了(比如少个协议)就直接忽略并
* 在内置 mock 的响应里说明,而不是让 Vite 的 proxy 在启动时报一句难懂的话。
* 一个空的/半截的配置是这里最容易犯的错。
*/
const apiTarget = (process.env.PREVIEW_API_TARGET || "").trim();
const hasApiTarget = /^https?:\/\//i.test(apiTarget);
/** 端口。刻意避开宿主链路上的三个端口,这样插件预览、宿主 dev、插件仓库可以同时开着 */
const PREVIEW_PORT = 5310;
const MIME: Record<string, string> = {
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
};
/**
* `/artifact/*` → `dist/*`。
*
* 不把这个目录放进 `publicDir` 是有意的:`publicDir` 里的东西会被当作
* 工程的静态资源被 Vite 处理(比如 ts 会被转译、import 会被重写),
* 而产物必须**原样**送出 —— 预览的意义就在于看到「浏览器拿到的那几个字节」。
*/
function artifactServer(): Plugin {
return {
name: "preview:artifact-server",
configureServer(server) {
server.middlewares.use((req, res, next) => {
const url = (req.url || "").split("?")[0];
if (!url.startsWith("/artifact/")) return next();
const rel = decodeURIComponent(url.slice("/artifact/".length));
const file = resolve(artifactDir, rel);
// 路径穿越防护:解析之后再确认仍在 dist 内,比过滤 ".." 字符串可靠
if (file !== artifactDir && !file.startsWith(artifactDir + sep)) {
res.statusCode = 403;
res.end("forbidden");
return;
}
if (!existsSync(file) || !statSync(file).isFile()) {
// 给出可执行的下一步,而不是一个干巴巴的 404 —— 这是预览时最常见的卡点
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end(`产物不存在:dist/${rel}\n跑一次 npm run build(npm run preview 会自动先构建)。\n`);
return;
}
res.setHeader("Content-Type", MIME[extname(file)] || "application/octet-stream");
// 开发期不缓存:否则改了产物刷新页面还是旧的,会误判成「构建没生效」
res.setHeader("Cache-Control", "no-store");
createReadStream(file).pipe(res);
});
},
};
}
/**
* 内置的 `/api` 后端。
*
* 只在**没有**配 `PREVIEW_API_TARGET` 时装上。这个判断不能省:
* Vite 的 proxy 中间件排在所有插件中间件**之后**(插件 `configureServer`
* 是前置钩子,proxy 是内部中间件),所以内置 mock 一旦装上就会**抢在代理前面**
* 把 `/api/**` 全部吃掉 —— 于是「配了真后端地址却还是 mock 数据」,
* 而且看不出原因。宁可在这里少装一个中间件。
*/
function apiServer(): Plugin {
return {
name: "preview:api-server",
configureServer(server) {
if (hasApiTarget) {
server.config.logger.info(
`\n \x1b[36m[preview]\x1b[0m /api → 代理到 ${apiTarget}(内置 mock 已停用)\n`
);
return;
}
server.config.logger.info(
"\n \x1b[36m[preview]\x1b[0m /api → 内置 mock 后端(preview/mock-api.ts;" +
"连真后端设 PREVIEW_API_TARGET=http://host:port)\n"
);
server.middlewares.use(createPreviewApi());
},
};
}
export default defineConfig({
root: previewRoot,
plugins: [vue(), artifactServer(), apiServer()],
resolve: {
// element-plus 会带上自己依赖的 vue,dedupe 保证全站只有一份 Vue 实例
dedupe: ["vue"],
},
optimizeDeps: {
// 预先打包,避免首屏「发现新依赖 → 重新预构建 → 整页刷新」的抖动
include: ["vue", "element-plus", "@element-plus/icons-vue"],
},
server: {
host: "127.0.0.1",
port: PREVIEW_PORT,
// 预览页要 import 工程根下的 ../src/**。默认的 allow 列表不一定覆盖到,
// 显式放行工程根,否则会被 dev server 的文件服务策略拦掉
fs: { allow: [projectRoot] },
// 只有配了合法地址才装代理。路径**原样转发**(不剥掉 /api),
// 这样后端的挂载点与生产环境一致,不用为预览额外加一条重写规则
...(hasApiTarget
? { proxy: { "/api": { target: apiTarget, changeOrigin: true } } }
: {}),
},
});