@hezor-master/plugin-api 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # @hezor-master/plugin-api
2
+
3
+ 后端能力包 SDK。纯类型定义与打包 CLI,零运行时依赖。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install @hezor-master/plugin-api
9
+ # 或
10
+ bun add @hezor-master/plugin-api
11
+ ```
12
+
13
+ 需要 peer dependency `hono`:
14
+
15
+ ```bash
16
+ npm install hono
17
+ ```
18
+
19
+ ## 使用
20
+
21
+ 能力包从 `register(ctx: PluginContext)` 开始:
22
+
23
+ ```ts
24
+ import type { PluginContext } from "@hezor-master/plugin-api"
25
+
26
+ export function register(ctx: PluginContext) {
27
+ ctx.http.register((app) => {
28
+ app.get("/hello", (c) => c.text("Hello from plugin"))
29
+ })
30
+
31
+ ctx.jobs.registerHandler("send-email", async (job) => {
32
+ // ...
33
+ })
34
+ }
35
+ ```
36
+
37
+ ## PluginContext API
38
+
39
+ | 属性 | 类型 | 说明 |
40
+ |------|------|------|
41
+ | `http` | `PluginHttp` | 注册 Hono 路由,支持 prefix |
42
+ | `jobs` | `PluginJobs` | 注册/触发后台任务 |
43
+ | `events` | `PluginEvents` | 发布/订阅事件 |
44
+ | `collection<T>(name)` | `Collection<T>` | 数据库表 CRUD(自动迁移) |
45
+ | `log` | `PluginLogger` | 结构化日志 |
46
+ | `config` | `PluginConfig` | 插件配置读写 |
47
+ | `workspaceId` | `PluginWorkspaceId` | 工作区 ID 编解码 |
48
+ | `conversion` | `PluginConversion` | 文档格式转换 |
49
+ | `opencli` | `PluginOpenCli` | 调用 OpenCode CLI |
50
+ | `plugin` | `PluginIdentity` | 插件自身元信息 |
51
+
52
+ ## CLI 命令
53
+
54
+ ```bash
55
+ npx plugin-package # 打包能力包为 ZIP
56
+ npx plugin-build # 构建并打包
57
+ npx plugin-release <ver> # 发布新版本
58
+ ```
59
+
60
+ ## License
61
+
62
+ MIT
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ import { execSync } from "node:child_process"
3
+ import { existsSync } from "node:fs"
4
+ import { resolve } from "node:path"
5
+
6
+ const cwd = process.cwd()
7
+ const uiDir = resolve(cwd, "ui")
8
+
9
+ // 1. 构建后端
10
+ if (existsSync(resolve(cwd, "package.json"))) {
11
+ try {
12
+ execSync("bun run build", { cwd, stdio: "inherit" })
13
+ } catch {
14
+ // 没有 build 脚本就跳过
15
+ }
16
+ }
17
+
18
+ // 2. 构建前端(如果有 ui 项目)
19
+ if (existsSync(resolve(uiDir, "package.json"))) {
20
+ execSync("bun run build", { cwd: uiDir, stdio: "inherit" })
21
+ }
22
+
23
+ // 3. 打包
24
+ execSync("plugin-package", { cwd, stdio: "inherit" })
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../dist/packager/index.js";
3
+
4
+ const args = process.argv.slice(2);
5
+ run(args);
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ import { execSync } from "node:child_process"
3
+ import { readFileSync, writeFileSync, existsSync } from "node:fs"
4
+ import { resolve } from "node:path"
5
+
6
+ const cwd = process.cwd()
7
+
8
+ function readJSON(path) {
9
+ return JSON.parse(readFileSync(path, "utf-8"))
10
+ }
11
+
12
+ function writeJSON(path, data) {
13
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n")
14
+ }
15
+
16
+ const arg = process.argv[2]
17
+ if (!arg || arg === "--help" || arg === "-h") {
18
+ console.log("Usage: plugin-release <version>")
19
+ console.log(" version: exact version (e.g., 2.3.0) or semver bump (patch, minor, major)")
20
+ console.log()
21
+ console.log("Releases a new version by updating package.json and plugin.json,")
22
+ console.log("creating a git tag, and pushing to origin.")
23
+ process.exit(arg ? 0 : 1)
24
+ }
25
+
26
+ const pkgPath = resolve(cwd, "package.json")
27
+ if (!existsSync(pkgPath)) {
28
+ console.error("FATAL: package.json not found")
29
+ process.exit(1)
30
+ }
31
+
32
+ // 检查是否有未提交的更改
33
+ const status = execSync("git status --porcelain", { cwd, encoding: "utf-8" }).trim()
34
+ if (status) {
35
+ console.error("FATAL: 存在未提交的更改,请先提交或暂存后再发布")
36
+ console.error(status)
37
+ process.exit(1)
38
+ }
39
+
40
+ const pkg = readJSON(pkgPath)
41
+ const currentVersion = pkg.version
42
+
43
+ let newVersion
44
+ if (["patch", "minor", "major"].includes(arg)) {
45
+ const [major, minor, patch] = currentVersion.split(".").map(Number)
46
+ if (arg === "major") {
47
+ newVersion = `${major + 1}.0.0`
48
+ } else if (arg === "minor") {
49
+ newVersion = `${major}.${minor + 1}.0`
50
+ } else {
51
+ newVersion = `${major}.${minor}.${patch + 1}`
52
+ }
53
+ } else {
54
+ newVersion = arg
55
+ }
56
+
57
+ console.log(`Releasing v${newVersion} (was v${currentVersion})`)
58
+
59
+ const manifestPath = resolve(cwd, "plugin.json")
60
+
61
+ if (newVersion !== currentVersion) {
62
+ pkg.version = newVersion
63
+ writeJSON(pkgPath, pkg)
64
+
65
+ if (existsSync(manifestPath)) {
66
+ const manifest = readJSON(manifestPath)
67
+ manifest.version = newVersion
68
+ writeJSON(manifestPath, manifest)
69
+ }
70
+
71
+ execSync(`git add package.json` + (existsSync(manifestPath) ? " plugin.json" : ""), { cwd, stdio: "inherit" })
72
+ execSync(`git commit -m "release v${newVersion}"`, { cwd, stdio: "inherit" })
73
+ } else {
74
+ console.log("Version unchanged, skipping commit")
75
+ }
76
+
77
+ execSync(`git tag -af v${newVersion} -m "v${newVersion}"`, { cwd, stdio: "inherit" })
78
+ execSync(`git push origin HEAD`, { cwd, stdio: "inherit" })
79
+ execSync(`git push origin v${newVersion} --force`, { cwd, stdio: "inherit" })
80
+
81
+ console.log(`Released v${newVersion}`)
@@ -0,0 +1,194 @@
1
+ /**
2
+ * @hezor-master/plugin-api — 后端纯类型定义
3
+ *
4
+ * 本文件只包含 TypeScript 类型定义,无运行时代码。
5
+ * 零外部依赖,零 import(除 bun:sqlite 等内置模块)。
6
+ */
7
+ export interface PluginIdentity {
8
+ id: string;
9
+ version: string;
10
+ dir: string;
11
+ dataDir: string;
12
+ }
13
+ export interface PluginHttp {
14
+ register(setup: (app: import("hono").Hono) => void | Promise<void>, options?: {
15
+ prefix?: string;
16
+ }): Promise<void>;
17
+ addPublicRoutes(routes: string[]): void;
18
+ addPublicPathPrefixes(prefixes: string[]): void;
19
+ }
20
+ export interface PluginConfig {
21
+ get<T = unknown>(key: string, defaultValue?: T): T | undefined;
22
+ set<T = unknown>(key: string, value: T): void;
23
+ all(): Record<string, unknown>;
24
+ }
25
+ export interface PluginWorkspaceId {
26
+ normalizeWorkspaceDir(dir: string): string;
27
+ encodeWorkspaceId(dir: string): string;
28
+ decodeWorkspaceId(workspaceId: string): string;
29
+ workspaceIdFromDir(dir: string): string;
30
+ }
31
+ export interface PluginConversion {
32
+ convertToMarkdown(sourcePath: string, filename: string, mimeType: string): Promise<string>;
33
+ supportsConversion(filename: string, mimeType: string): boolean;
34
+ }
35
+ export interface PluginOpenCli {
36
+ runOpenCliCommand(command: string, kwargs: Record<string, unknown>, timeoutMs?: number, channelId?: string): Promise<unknown>;
37
+ checkChannelStatus(channelId: string): Promise<{
38
+ status: string;
39
+ error?: string;
40
+ }>;
41
+ }
42
+ export interface Collection<T> {
43
+ findAll(): Promise<T[]>;
44
+ findById(id: number | string): Promise<T | undefined>;
45
+ create(data: Partial<T>): Promise<T>;
46
+ update(id: number | string, data: Partial<T>): Promise<T | undefined>;
47
+ delete(id: number | string): Promise<void>;
48
+ findPage(options?: FindPageOptions): Promise<PaginatedResult<T>>;
49
+ query(sql: string, params?: unknown[]): Promise<unknown[]>;
50
+ }
51
+ export interface FindPageOptions {
52
+ page?: number;
53
+ pageSize?: number;
54
+ orderBy?: string;
55
+ order?: "asc" | "desc";
56
+ where?: Record<string, unknown>;
57
+ }
58
+ export interface PaginatedResult<T> {
59
+ data: T[];
60
+ total: number;
61
+ page: number;
62
+ pageSize: number;
63
+ totalPages: number;
64
+ }
65
+ export interface PluginJobs {
66
+ enqueue(jobType: string, payload: Record<string, unknown>, options?: {
67
+ scheduledAt?: number;
68
+ userId?: string;
69
+ workspaceId?: string;
70
+ }): Promise<{
71
+ id: string;
72
+ }>;
73
+ registerHandler(jobType: string, handler: (ctx: JobContext) => Promise<JobResult>, options?: {
74
+ pool?: string;
75
+ }): void;
76
+ registerPool(name: string, concurrency: number): void;
77
+ }
78
+ export interface JobContext {
79
+ jobId: string;
80
+ payload: Record<string, unknown>;
81
+ ownerUserId: string;
82
+ workspaceId: string;
83
+ log: PluginLogger;
84
+ }
85
+ export type JobResult = {
86
+ disposition: "complete";
87
+ result?: unknown;
88
+ } | {
89
+ disposition: "session";
90
+ sessionId: string;
91
+ verifier?: JobVerifier;
92
+ };
93
+ export interface JobVerifier {
94
+ check: (args: {
95
+ sessionId: string;
96
+ }) => Promise<{
97
+ verified: boolean;
98
+ result?: unknown;
99
+ }>;
100
+ }
101
+ export interface PluginEvents {
102
+ publish(type: string, payload: unknown, options?: {
103
+ userId?: string;
104
+ broadcast?: boolean;
105
+ }): void;
106
+ subscribe(type: string, handler: (payload: unknown) => void): () => void;
107
+ }
108
+ export interface TransactionDb {
109
+ query<T = unknown>(sql: string, params?: unknown[]): T[];
110
+ execute(sql: string, params?: unknown[]): number;
111
+ }
112
+ export interface PluginDb {
113
+ query<T = unknown>(sql: string, params?: unknown[]): T[];
114
+ execute(sql: string, params?: unknown[]): number;
115
+ exec(sql: string): void;
116
+ transaction<T>(fn: (trx: TransactionDb) => T): T;
117
+ }
118
+ /**
119
+ * Helper to create namespaced event names following the convention:
120
+ * `{pluginId}:{eventName}`
121
+ *
122
+ * Example: `pluginEvent("my-analytics", "page-viewed")` → `"my-analytics:page-viewed"`
123
+ */
124
+ export declare function pluginEvent(pluginId: string, eventName: string): string;
125
+ export interface PluginLogger {
126
+ info(msg: string, ...args: unknown[]): void;
127
+ warn(msg: string, ...args: unknown[]): void;
128
+ error(msg: string, ...args: unknown[]): void;
129
+ debug(msg: string, ...args: unknown[]): void;
130
+ }
131
+ export interface PluginContext {
132
+ log: PluginLogger;
133
+ plugin: PluginIdentity;
134
+ collection<T>(tableName: string): Collection<T>;
135
+ jobs: PluginJobs;
136
+ events: PluginEvents;
137
+ http: PluginHttp;
138
+ config: PluginConfig;
139
+ workspaceId: PluginWorkspaceId;
140
+ db: PluginDb;
141
+ conversion: PluginConversion;
142
+ opencli: PluginOpenCli;
143
+ reload?: (workspace?: string) => Promise<void>;
144
+ }
145
+ export type PluginRegister = (ctx: PluginContext) => void | Promise<void>;
146
+ export interface QuickPrompt {
147
+ label: string;
148
+ prompt: string;
149
+ }
150
+ export interface PluginManifest {
151
+ id: string;
152
+ name: string;
153
+ version: string;
154
+ description: string;
155
+ author: string;
156
+ minCoreVersion: string;
157
+ dependencies?: Record<string, string>;
158
+ server: boolean;
159
+ ui: boolean;
160
+ runtime: boolean;
161
+ workspace: boolean;
162
+ db: boolean;
163
+ entry?: string;
164
+ /** Sidebar display name */
165
+ label: string;
166
+ /** Sidebar icon name */
167
+ icon: string;
168
+ /** Agent ID to activate on click (optional) */
169
+ agent?: string;
170
+ /** Quick prompts shown when agent is activated */
171
+ quickPrompts?: QuickPrompt[];
172
+ /** Extra iframe tabs beyond the main UI */
173
+ tabs?: Array<{
174
+ id: string;
175
+ label: string;
176
+ icon?: string;
177
+ }>;
178
+ }
179
+ export type PluginState = "not-installed" | "downloading" | "installed" | "disabled" | "active" | "uninstalled";
180
+ /** States that can be persisted in registry.json */
181
+ export type PersistedState = "installed" | "disabled" | "active";
182
+ export interface RegistryEntry {
183
+ id: string;
184
+ version: string;
185
+ installedAt: number;
186
+ updatedAt: number;
187
+ state: PersistedState;
188
+ manifest: PluginManifest;
189
+ }
190
+ export interface RegistryFile {
191
+ version: number;
192
+ entries: Record<string, RegistryEntry>;
193
+ }
194
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;CACjB;AAID,MAAM,WAAW,UAAU;IACzB,QAAQ,CACN,KAAK,EAAE,CAAC,GAAG,EAAE,OAAO,MAAM,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EACzD,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAC5B,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAA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CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,wBAAwB;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,+CAA+C;IAC/C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kDAAkD;IAClD,YAAY,CAAC,EAAE,WAAW,EAAE,CAAC;IAC7B,2CAA2C;IAC3C,IAAI,CAAC,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC5D;AAED,MAAM,MAAM,WAAW,GACnB,eAAe,GACf,aAAa,GACb,WAAW,GACX,UAAU,GACV,QAAQ,GACR,aAAa,CAAC;AAElB,oDAAoD;AACpD,MAAM,MAAM,cAAc,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,CAAC;AAIjE,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,cAAc,CAAC;IACtB,QAAQ,EAAE,cAAc,CAAC;CAC1B;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CACxC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @hezor-master/plugin-api — 后端纯类型定义
3
+ *
4
+ * 本文件只包含 TypeScript 类型定义,无运行时代码。
5
+ * 零外部依赖,零 import(除 bun:sqlite 等内置模块)。
6
+ */
7
+ /**
8
+ * Helper to create namespaced event names following the convention:
9
+ * `{pluginId}:{eventName}`
10
+ *
11
+ * Example: `pluginEvent("my-analytics", "page-viewed")` → `"my-analytics:page-viewed"`
12
+ */
13
+ export function pluginEvent(pluginId, eventName) {
14
+ return `${pluginId}:${eventName}`;
15
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * plugin-package — 插件打包 CLI
3
+ *
4
+ * 零外部依赖,仅使用 Node.js 内置模块。
5
+ */
6
+ interface PackageOptions {
7
+ manifestPath: string;
8
+ outDir: string;
9
+ cwd: string;
10
+ watch: boolean;
11
+ }
12
+ export declare function run(args: string[]): void;
13
+ /** 内部导出以便测试 */
14
+ export declare function packagePlugin(options: PackageOptions): string | null;
15
+ export {};
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/packager/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AA8BH,UAAU,cAAc;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,OAAO,CAAC;CAChB;AAwBD,wBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAcxC;AAuGD,eAAe;AACf,wBAAgB,aAAa,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,CAiGpE"}
@@ -0,0 +1,238 @@
1
+ /**
2
+ * plugin-package — 插件打包 CLI
3
+ *
4
+ * 零外部依赖,仅使用 Node.js 内置模块。
5
+ */
6
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, watch, } from "node:fs";
7
+ import { resolve } from "node:path";
8
+ import { spawnSync } from "node:child_process";
9
+ // ── 能力 → 必需文件/目录映射 ─────────────────────────────────
10
+ const REQUIRED_BY_CAPABILITY = {
11
+ server: ["dist/server/index.js"],
12
+ ui: ["ui/dist/index.html"],
13
+ runtime: ["runtime"],
14
+ workspace: ["workspace"],
15
+ db: ["db/migrations"],
16
+ };
17
+ /** 监听模式下需要监视的路径(相对于项目根目录) */
18
+ const WATCH_PATHS = [
19
+ "plugin.json",
20
+ "ui/dist",
21
+ "dist/server",
22
+ "runtime",
23
+ "workspace",
24
+ "db/migrations",
25
+ ];
26
+ // ── 主入口 ────────────────────────────────────────────────────
27
+ export function run(args) {
28
+ const options = parseArgs(args);
29
+ if (options.watch) {
30
+ runWatchMode(options);
31
+ }
32
+ else {
33
+ const result = packagePlugin(options);
34
+ if (result) {
35
+ console.log(`Plugin ZIP created: ${result}`);
36
+ }
37
+ else {
38
+ console.error("[plugin-package] Packaging failed");
39
+ process.exit(1);
40
+ }
41
+ }
42
+ }
43
+ // ── 参数解析 ─────────────────────────────────────────────────
44
+ function parseArgs(args) {
45
+ let manifestPath = "./plugin.json";
46
+ let outDir = "./dist";
47
+ let watch = false;
48
+ for (let i = 0; i < args.length; i++) {
49
+ switch (args[i]) {
50
+ case "--manifest":
51
+ manifestPath = args[++i];
52
+ break;
53
+ case "--out-dir":
54
+ outDir = args[++i];
55
+ break;
56
+ case "--watch":
57
+ watch = true;
58
+ break;
59
+ case "--help":
60
+ case "-h":
61
+ printHelp();
62
+ process.exit(0);
63
+ default:
64
+ if (args[i].startsWith("-")) {
65
+ console.error(`[plugin-package] Unknown option: ${args[i]}`);
66
+ printHelp();
67
+ process.exit(1);
68
+ }
69
+ break;
70
+ }
71
+ }
72
+ const cwd = process.cwd();
73
+ return { manifestPath, outDir, cwd, watch };
74
+ }
75
+ function printHelp() {
76
+ console.log(`
77
+ Usage: plugin-package [options]
78
+
79
+ Options:
80
+ --manifest <path> Path to plugin.json (default: ./plugin.json)
81
+ --out-dir <path> Output directory (default: ./dist)
82
+ --watch Watch files and auto-repackage on change
83
+ --help, -h Show this help
84
+ `);
85
+ }
86
+ // ── Watch 模式 ────────────────────────────────────────────────
87
+ function runWatchMode(options) {
88
+ const { cwd, manifestPath } = options;
89
+ console.log("[plugin-package] Watch mode enabled. Watching for changes...");
90
+ // 先打包一次
91
+ const initial = packagePlugin(options);
92
+ if (initial) {
93
+ console.log(`Initial build: ${initial}`);
94
+ }
95
+ else {
96
+ console.error("[plugin-package] Initial build failed, entering watch mode anyway");
97
+ }
98
+ const watchers = [];
99
+ for (const relPath of WATCH_PATHS) {
100
+ const fullPath = resolve(cwd, relPath);
101
+ if (!existsSync(fullPath))
102
+ continue;
103
+ try {
104
+ const w = watch(fullPath, { recursive: true }, (_event, filename) => {
105
+ if (!filename)
106
+ return;
107
+ console.log(`[plugin-package] Change detected: ${relPath}/${filename}`);
108
+ const result = packagePlugin(options);
109
+ if (result) {
110
+ console.log(`Re-packaged: ${result}`);
111
+ }
112
+ else {
113
+ console.error("[plugin-package] Re-package failed");
114
+ }
115
+ });
116
+ watchers.push(w);
117
+ }
118
+ catch {
119
+ // 单个路径监听失败不影响其他路径
120
+ }
121
+ }
122
+ // 保持进程存活
123
+ process.on("SIGINT", () => {
124
+ console.log("\n[plugin-package] Watch mode terminated");
125
+ watchers.forEach((w) => w.close());
126
+ process.exit(0);
127
+ });
128
+ process.on("SIGTERM", () => {
129
+ watchers.forEach((w) => w.close());
130
+ process.exit(0);
131
+ });
132
+ }
133
+ // ── 打包逻辑 ─────────────────────────────────────────────────
134
+ /** 内部导出以便测试 */
135
+ export function packagePlugin(options) {
136
+ const { manifestPath, outDir, cwd } = options;
137
+ // 1. 读取插件清单
138
+ const manifestFullPath = resolve(cwd, manifestPath);
139
+ if (!existsSync(manifestFullPath)) {
140
+ console.error(`FATAL: Manifest not found at ${manifestFullPath}`);
141
+ return null;
142
+ }
143
+ let manifest;
144
+ try {
145
+ manifest = JSON.parse(readFileSync(manifestFullPath, "utf8"));
146
+ }
147
+ catch (err) {
148
+ console.error(`FATAL: Invalid manifest JSON at ${manifestPath}:`, err.message);
149
+ return null;
150
+ }
151
+ // 2. 验证清单必填字段
152
+ if (!manifest.id || !manifest.name || !manifest.version) {
153
+ console.error('FATAL: Manifest must contain "id", "name", and "version" fields');
154
+ return null;
155
+ }
156
+ // 3. 按能力声明验证构建产物
157
+ for (const [cap, paths] of Object.entries(REQUIRED_BY_CAPABILITY)) {
158
+ if (manifest[cap]) {
159
+ for (const relPath of paths) {
160
+ const fullPath = resolve(cwd, relPath);
161
+ if (!existsSync(fullPath)) {
162
+ console.error(`FATAL: plugin.json declares "${cap}=true" but required file/dir "${relPath}" not found at ${fullPath}`);
163
+ return null;
164
+ }
165
+ }
166
+ }
167
+ }
168
+ // 4. 创建 staging 目录
169
+ const stagingDir = resolve(cwd, outDir, "zip");
170
+ rmSync(stagingDir, { recursive: true, force: true });
171
+ mkdirSync(stagingDir, { recursive: true });
172
+ const pluginRoot = cwd;
173
+ // 5. 复制 plugin.json
174
+ cpSync(manifestFullPath, resolve(stagingDir, "plugin.json"));
175
+ // 6. 复制 server 构建产物
176
+ const serverDist = resolve(pluginRoot, "dist/server/index.js");
177
+ if (existsSync(serverDist)) {
178
+ mkdirSync(resolve(stagingDir, "server"), { recursive: true });
179
+ cpSync(serverDist, resolve(stagingDir, "server/index.js"));
180
+ }
181
+ // 7. 复制 UI 构建产物
182
+ const uiDist = resolve(pluginRoot, "ui/dist");
183
+ if (existsSync(uiDist)) {
184
+ cpSync(uiDist, resolve(stagingDir, "ui"), { recursive: true, force: true });
185
+ }
186
+ // 8. 复制 runtime
187
+ const runtimeDir = resolve(pluginRoot, "runtime");
188
+ if (existsSync(runtimeDir)) {
189
+ cpSync(runtimeDir, resolve(stagingDir, "runtime"), { recursive: true, force: true });
190
+ }
191
+ // 9. 复制 workspace
192
+ const workspaceDir = resolve(pluginRoot, "workspace");
193
+ if (existsSync(workspaceDir)) {
194
+ cpSync(workspaceDir, resolve(stagingDir, "workspace"), { recursive: true, force: true });
195
+ }
196
+ // 10. 复制 db migrations
197
+ const dbDir = resolve(pluginRoot, "db/migrations");
198
+ if (existsSync(dbDir)) {
199
+ cpSync(dbDir, resolve(stagingDir, "db/migrations"), { recursive: true, force: true });
200
+ }
201
+ // 11. 创建 ZIP
202
+ const zipName = `${manifest.id}-plugin-${manifest.version}.zip`;
203
+ const zipPath = resolve(cwd, outDir, zipName);
204
+ const zipCreated = createZip(stagingDir, zipPath);
205
+ if (!zipCreated) {
206
+ console.error("FATAL: Could not create ZIP. PowerShell and zip both failed.");
207
+ return null;
208
+ }
209
+ // 12. 验证 ZIP 存在
210
+ if (!existsSync(zipPath)) {
211
+ console.error(`FATAL: ZIP file not found at expected path: ${zipPath}`);
212
+ return null;
213
+ }
214
+ return zipPath;
215
+ }
216
+ // ── ZIP 创建 ─────────────────────────────────────────────────
217
+ function createZip(sourceDir, destPath) {
218
+ // 先尝试 PowerShell (Windows)
219
+ const globPath = process.platform === "win32" ? ".\\*" : "./*";
220
+ const psResult = spawnSync("powershell", [
221
+ "-NoProfile",
222
+ "Compress-Archive",
223
+ "-Path",
224
+ globPath,
225
+ "-DestinationPath",
226
+ destPath,
227
+ "-Force",
228
+ ], { cwd: sourceDir, stdio: "pipe" });
229
+ if (psResult.status === 0) {
230
+ return true;
231
+ }
232
+ // 回退到系统 zip (Unix/macOS)
233
+ const zipResult = spawnSync("zip", ["-r", destPath, "."], {
234
+ cwd: sourceDir,
235
+ stdio: "pipe",
236
+ });
237
+ return zipResult.status === 0;
238
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@hezor-master/plugin-api",
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./packager": {
13
+ "types": "./dist/packager/index.d.ts",
14
+ "default": "./dist/packager/index.js"
15
+ }
16
+ },
17
+ "bin": {
18
+ "plugin-package": "./bin/plugin-package.js",
19
+ "plugin-build": "./bin/plugin-build.mjs",
20
+ "plugin-release": "./bin/plugin-release.mjs"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "bin",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "tsc",
33
+ "clean": "rm -rf dist",
34
+ "prepublishOnly": "bun run clean && bun run build && bun run typecheck && bun run test",
35
+ "test": "vitest run",
36
+ "typecheck": "tsc --noEmit",
37
+ "release": "./bin/plugin-release.mjs"
38
+ },
39
+ "peerDependencies": {
40
+ "hono": "4.10.7"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^26.1.0",
44
+ "jsdom": "^26",
45
+ "typescript": "^6",
46
+ "vitest": "^4"
47
+ },
48
+ "license": "MIT"
49
+ }