ms-vite-plugin 1.3.2 → 1.3.4

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/dist/device.js DELETED
@@ -1,325 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.runOnDevice = runOnDevice;
37
- exports.runUIOnDevice = runUIOnDevice;
38
- exports.stopOnDevice = stopOnDevice;
39
- const fsExtra = __importStar(require("fs-extra"));
40
- const path = __importStar(require("path"));
41
- const build_js_1 = require("./build.js");
42
- /**
43
- * 读取并校验设备连接参数
44
- * @param options 命令选项
45
- * @returns 返回标准化后的设备地址信息
46
- * @example
47
- * parseDeviceOptions({ ip: "192.168.1.10", port: "9800" })
48
- */
49
- function parseDeviceOptions(options) {
50
- const ip = options.ip?.trim();
51
- const portText = (options.port ?? "9800").trim();
52
- const port = Number.parseInt(portText, 10);
53
- if (!ip) {
54
- throw new Error("请通过 --ip 指定设备 IP 地址");
55
- }
56
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
57
- throw new Error(`无效端口: ${portText}`);
58
- }
59
- return { ip, port };
60
- }
61
- /**
62
- * 计算 Buffer 的 CRC32 值
63
- * @param input 二进制输入数据
64
- * @returns CRC32 十六进制字符串(8位)
65
- * @example
66
- * calculateCrc32FromBuffer(Buffer.from("hello"))
67
- */
68
- function calculateCrc32FromBuffer(input) {
69
- let crc = 0xffffffff;
70
- for (let i = 0; i < input.length; i += 1) {
71
- crc ^= input[i];
72
- for (let j = 0; j < 8; j += 1) {
73
- if ((crc & 1) === 1) {
74
- crc = (crc >>> 1) ^ 0xedb88320;
75
- }
76
- else {
77
- crc >>>= 1;
78
- }
79
- }
80
- }
81
- const finalValue = (crc ^ 0xffffffff) >>> 0;
82
- return finalValue.toString(16).padStart(8, "0");
83
- }
84
- /**
85
- * 计算文件的 CRC32 值
86
- * @param filePath 文件路径
87
- * @returns CRC32 十六进制字符串(8位)
88
- * @example
89
- * await calculateCrc32("/tmp/a.txt")
90
- */
91
- async function calculateCrc32(filePath) {
92
- const fileBuffer = await fsExtra.readFile(filePath);
93
- return calculateCrc32FromBuffer(fileBuffer);
94
- }
95
- /**
96
- * 递归收集目录中的所有文件
97
- * @param rootDir 需要遍历的根目录
98
- * @param bundlePrefix 输出到设备时的目录前缀
99
- * @returns 返回可同步文件列表(含 size 与 crc32)
100
- * @example
101
- * await collectFilesInDir("/tmp/project/ui", "ui")
102
- */
103
- async function collectFilesInDir(rootDir, bundlePrefix) {
104
- const files = [];
105
- async function walk(dir) {
106
- const entries = await fsExtra.readdir(dir, { withFileTypes: true });
107
- for (const entry of entries) {
108
- const fullPath = path.join(dir, entry.name);
109
- if (entry.isDirectory()) {
110
- await walk(fullPath);
111
- }
112
- else if (entry.isFile()) {
113
- const relPath = path.relative(rootDir, fullPath).replace(/\\/g, "/");
114
- const stat = await fsExtra.stat(fullPath);
115
- files.push({
116
- path: fullPath,
117
- bundlePath: `${bundlePrefix}/${relPath}`,
118
- size: stat.size,
119
- crc32: await calculateCrc32(fullPath),
120
- });
121
- }
122
- }
123
- }
124
- if (await fsExtra.pathExists(rootDir)) {
125
- await walk(rootDir);
126
- }
127
- return files;
128
- }
129
- /**
130
- * 读取项目运行所需的元信息
131
- * @param workspacePath 项目根目录
132
- * @returns 返回 projectName、appVersion 与 packageJsonPath
133
- * @example
134
- * await getProjectMeta("/Users/demo/project")
135
- */
136
- async function getProjectMeta(workspacePath) {
137
- const packageJsonPath = path.join(workspacePath, "package.json");
138
- const packageJson = await fsExtra.readJSON(packageJsonPath);
139
- const projectName = packageJson.name;
140
- const appVersion = packageJson.appVersion;
141
- if (!projectName) {
142
- throw new Error("请在 package.json 中添加 name 字段");
143
- }
144
- if (!appVersion) {
145
- throw new Error("请在 package.json 中添加 appVersion 字段");
146
- }
147
- return { projectName, appVersion, packageJsonPath };
148
- }
149
- /**
150
- * 收集运行前需要同步的文件
151
- * @param workspacePath 项目根目录
152
- * @returns 返回项目文件清单(含 size 与 crc32)
153
- * @example
154
- * await collectProjectFiles("/Users/demo/project")
155
- */
156
- async function collectProjectFiles(workspacePath) {
157
- const scriptDistPath = path.join(workspacePath, "dist", "scripts");
158
- const scriptSrcPath = path.join(workspacePath, "scripts");
159
- const uiPath = path.join(workspacePath, "ui");
160
- const resPath = path.join(workspacePath, "res");
161
- const packageJsonPath = path.join(workspacePath, "package.json");
162
- const useDistScripts = await fsExtra.pathExists(scriptDistPath);
163
- const scriptPath = useDistScripts ? scriptDistPath : scriptSrcPath;
164
- const files = [
165
- {
166
- path: packageJsonPath,
167
- bundlePath: "package.json",
168
- size: (await fsExtra.stat(packageJsonPath)).size,
169
- crc32: await calculateCrc32(packageJsonPath),
170
- },
171
- ];
172
- const [scriptFiles, uiFiles, resFiles] = await Promise.all([
173
- collectFilesInDir(scriptPath, "scripts"),
174
- collectFilesInDir(uiPath, "ui"),
175
- collectFilesInDir(resPath, "res"),
176
- ]);
177
- files.push(...scriptFiles, ...uiFiles, ...resFiles);
178
- return files;
179
- }
180
- /**
181
- * 获取设备上的文件列表
182
- * @param ip 设备 IP 地址
183
- * @param port 设备端口
184
- * @param projectName 项目名称
185
- * @returns 设备当前文件信息列表
186
- * @example
187
- * await listDeviceFiles("192.168.1.10", 9800, "demo")
188
- */
189
- async function listDeviceFiles(ip, port, projectName) {
190
- const url = new URL(`http://${ip}:${port}/api/files`);
191
- url.searchParams.set("projectName", projectName);
192
- const response = await fetch(url.toString(), { method: "GET" });
193
- if (!response.ok) {
194
- throw new Error(`文件列表请求失败: ${response.statusText}`);
195
- }
196
- const data = (await response.json());
197
- return Array.isArray(data) ? data : [];
198
- }
199
- /**
200
- * 将项目文件增量同步到设备
201
- * @param workspacePath 项目根目录
202
- * @param ip 设备 IP 地址
203
- * @param port 设备端口
204
- * @returns 同步完成后返回 Promise<void>
205
- * @example
206
- * await syncProjectToDevice("/Users/demo/project", "192.168.1.10", 9800)
207
- */
208
- async function syncProjectToDevice(workspacePath, ip, port) {
209
- const { projectName, appVersion } = await getProjectMeta(workspacePath);
210
- console.log("🔎 正在获取设备文件列表...");
211
- const deviceFiles = await listDeviceFiles(ip, port, projectName);
212
- const deviceFileMap = new Map(deviceFiles.map((file) => [file.path, file]));
213
- console.log("📂 正在分析项目文件...");
214
- const files = await collectProjectFiles(workspacePath);
215
- const filesToSync = [];
216
- for (const file of files) {
217
- const deviceFile = deviceFileMap.get(file.bundlePath);
218
- const requireSyncFile = file.bundlePath.includes("main.js") ||
219
- file.bundlePath.includes("main.py");
220
- if (!deviceFile) {
221
- filesToSync.push(file);
222
- continue;
223
- }
224
- const changed = deviceFile.size !== file.size ||
225
- deviceFile.crc32.toLowerCase() !== file.crc32.toLowerCase();
226
- if (requireSyncFile || changed) {
227
- filesToSync.push(file);
228
- }
229
- }
230
- console.log(`📦 发现 ${filesToSync.length} 个文件需要同步`);
231
- if (filesToSync.length === 0) {
232
- console.log("✅ 无需同步文件");
233
- return;
234
- }
235
- let syncedCount = 0;
236
- for (const file of filesToSync) {
237
- syncedCount += 1;
238
- console.log(`⬆️ [${syncedCount}/${filesToSync.length}] 同步 ${file.bundlePath}`);
239
- const binary = await fsExtra.readFile(file.path);
240
- const url = new URL(`http://${ip}:${port}/debug/patchSync`);
241
- url.searchParams.set("path", file.bundlePath);
242
- url.searchParams.set("projectName", projectName);
243
- url.searchParams.set("appVersion", appVersion);
244
- const response = await fetch(url.toString(), {
245
- method: "POST",
246
- headers: {
247
- "Content-Type": "application/octet-stream",
248
- },
249
- body: binary,
250
- });
251
- if (!response.ok) {
252
- throw new Error(`同步失败: ${file.bundlePath} (状态码: ${response.status})`);
253
- }
254
- }
255
- console.log(`✅ 同步完成,共 ${filesToSync.length} 个文件`);
256
- }
257
- /**
258
- * 发送设备动作请求
259
- * @param action 动作名称,支持 run 与 stop
260
- * @param ip 设备 IP 地址
261
- * @param port 设备端口
262
- * @returns 请求成功时返回 Promise<void>
263
- * @example
264
- * await requestDeviceAction("stop", "192.168.1.10", 9800)
265
- */
266
- async function requestDeviceAction(action, ip, port) {
267
- const url = `http://${ip}:${port}/api/${action}`;
268
- const response = await fetch(url, { method: "GET" });
269
- if (!response.ok) {
270
- throw new Error(`${action} 失败,状态码: ${response.status}`);
271
- }
272
- }
273
- /**
274
- * 在设备上运行项目(先同步后运行)
275
- * @param options 命令选项
276
- * @returns 执行完成后返回 Promise<void>
277
- * @example
278
- * await runOnDevice({ ip: "192.168.1.10", port: "9800", path: "./demo" })
279
- */
280
- async function runOnDevice(options) {
281
- const workspacePath = options.path
282
- ? path.resolve(options.path)
283
- : process.cwd();
284
- const { ip, port } = parseDeviceOptions(options);
285
- console.log(`🔧 开始构建项目: ${workspacePath}`);
286
- await (0, build_js_1.buildAll)(true, workspacePath);
287
- console.log(`📦 开始同步项目到设备: ${ip}:${port}`);
288
- await syncProjectToDevice(workspacePath, ip, port);
289
- console.log(`🚀 开始运行项目: ${ip}:${port}`);
290
- await requestDeviceAction("run", ip, port);
291
- console.log("✅ 运行请求已发送");
292
- }
293
- /**
294
- * 在设备上预览 UI(先同步后调用 runUI)
295
- * @param options 命令选项
296
- * @returns 执行完成后返回 Promise<void>
297
- * @example
298
- * await runUIOnDevice({ ip: "192.168.1.10", port: "9800", path: "./demo" })
299
- */
300
- async function runUIOnDevice(options) {
301
- const workspacePath = options.path
302
- ? path.resolve(options.path)
303
- : process.cwd();
304
- const { ip, port } = parseDeviceOptions(options);
305
- console.log(`🔧 开始构建项目: ${workspacePath}`);
306
- await (0, build_js_1.buildAll)(true, workspacePath);
307
- console.log(`📦 开始同步项目到设备: ${ip}:${port}`);
308
- await syncProjectToDevice(workspacePath, ip, port);
309
- console.log(`🖼️ 开始预览 UI: ${ip}:${port}`);
310
- await requestDeviceAction("runUI", ip, port);
311
- console.log("✅ UI 预览请求已发送");
312
- }
313
- /**
314
- * 停止设备上的项目
315
- * @param options 命令选项
316
- * @returns 执行完成后返回 Promise<void>
317
- * @example
318
- * await stopOnDevice({ ip: "192.168.1.10", port: "9800" })
319
- */
320
- async function stopOnDevice(options) {
321
- const { ip, port } = parseDeviceOptions(options);
322
- console.log(`🛑 开始停止项目: ${ip}:${port}`);
323
- await requestDeviceAction("stop", ip, port);
324
- console.log("✅ 停止请求已发送");
325
- }
@@ -1,9 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- /**
3
- * 注册 Control API 对应 MCP 工具
4
- * @param server MCP 服务实例
5
- * @returns 无返回值
6
- * @example
7
- * registerControlTools(server)
8
- */
9
- export declare function registerControlTools(server: McpServer): void;
@@ -1,201 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.registerControlTools = registerControlTools;
37
- const z = __importStar(require("zod/v4"));
38
- const tool_utils_1 = require("./tool-utils");
39
- /**
40
- * 请求控制路由
41
- * @param endpoint 控制 API 名称
42
- * @param query 可选查询参数
43
- * @returns 返回设备端 JSON 响应
44
- * @example
45
- * const payload = await requestControlApi("home")
46
- */
47
- async function requestControlApi(endpoint, query) {
48
- const target = await (0, tool_utils_1.resolveRuntimeHttpTarget)();
49
- return (0, tool_utils_1.requestRuntimePathJson)(target, `/api/control/${endpoint}`, query);
50
- }
51
- /**
52
- * 将控制类 API 响应格式化为 MCP 文本
53
- * @param actionName 操作名称
54
- * @param payload 设备端响应
55
- * @returns 返回标准文本工具响应
56
- * @example
57
- * formatControlResult("返回桌面", { success: true })
58
- */
59
- function formatControlResult(actionName, payload) {
60
- const success = payload.success === true;
61
- if ("data" in payload) {
62
- return (0, tool_utils_1.createTextToolResult)(`${actionName}${success ? "成功" : "失败"}:\n${(0, tool_utils_1.formatRuntimeJsonText)(payload.data)}`, !success);
63
- }
64
- return (0, tool_utils_1.createTextToolResult)(`${actionName}${success ? "成功" : "失败"}`, !success);
65
- }
66
- /**
67
- * 注册 Control API 对应 MCP 工具
68
- * @param server MCP 服务实例
69
- * @returns 无返回值
70
- * @example
71
- * registerControlTools(server)
72
- */
73
- function registerControlTools(server) {
74
- server.registerTool("control_home", {
75
- title: "Control Home",
76
- description: "返回桌面。",
77
- inputSchema: {},
78
- }, async () => formatControlResult("返回桌面", await requestControlApi("home")));
79
- server.registerTool("control_click", {
80
- title: "Control Click",
81
- description: "点击指定坐标。",
82
- inputSchema: {
83
- x: z.number().int().min(0).describe("点击坐标 x"),
84
- y: z.number().int().min(0).describe("点击坐标 y"),
85
- duration: z
86
- .number()
87
- .int()
88
- .min(0)
89
- .optional()
90
- .describe("按压时长,默认 20"),
91
- jitter: z.boolean().optional().describe("是否启用抖动,默认 false"),
92
- },
93
- }, async ({ x, y, duration, jitter }) => formatControlResult("点击", await requestControlApi("click", { x, y, duration, jitter })));
94
- server.registerTool("control_double_click", {
95
- title: "Control Double Click",
96
- description: "双击指定坐标。",
97
- inputSchema: {
98
- x: z.number().int().min(0).describe("双击坐标 x"),
99
- y: z.number().int().min(0).describe("双击坐标 y"),
100
- duration: z
101
- .number()
102
- .int()
103
- .min(0)
104
- .optional()
105
- .describe("单次按压时长,默认 20"),
106
- interval: z
107
- .number()
108
- .int()
109
- .min(0)
110
- .optional()
111
- .describe("两次点击间隔,默认 20"),
112
- jitter: z.boolean().optional().describe("是否启用抖动,默认 false"),
113
- },
114
- }, async ({ x, y, duration, interval, jitter }) => formatControlResult("双击", await requestControlApi("doubleClick", {
115
- x,
116
- y,
117
- duration,
118
- interval,
119
- jitter,
120
- })));
121
- server.registerTool("control_swipe", {
122
- title: "Control Swipe",
123
- description: "从起点滑动到终点。",
124
- inputSchema: {
125
- startX: z.number().int().min(0).describe("起点 x"),
126
- startY: z.number().int().min(0).describe("起点 y"),
127
- endX: z.number().int().min(0).describe("终点 x"),
128
- endY: z.number().int().min(0).describe("终点 y"),
129
- duration: z
130
- .number()
131
- .int()
132
- .min(0)
133
- .optional()
134
- .describe("滑动时长,默认 100"),
135
- jitter: z.boolean().optional().describe("是否启用抖动,默认 false"),
136
- steps: z.number().int().min(1).optional().describe("分段步数,默认 6"),
137
- },
138
- }, async ({ startX, startY, endX, endY, duration, jitter, steps }) => formatControlResult("滑动", await requestControlApi("swipe", {
139
- startX,
140
- startY,
141
- endX,
142
- endY,
143
- duration,
144
- jitter,
145
- steps,
146
- })));
147
- server.registerTool("control_press_button", {
148
- title: "Control Press Button",
149
- description: "按下指定系统按键。",
150
- inputSchema: {
151
- button: z.string().min(1).describe("按钮名称"),
152
- },
153
- }, async ({ button }) => formatControlResult("按键", await requestControlApi("pressButton", { button })));
154
- server.registerTool("control_input", {
155
- title: "Control Input",
156
- description: "输入文本。",
157
- inputSchema: {
158
- text: z.string().min(1).describe("待输入文本"),
159
- },
160
- }, async ({ text }) => formatControlResult("输入", await requestControlApi("input", { text })));
161
- server.registerTool("control_backspace", {
162
- title: "Control Backspace",
163
- description: "执行退格操作。",
164
- inputSchema: {
165
- count: z.number().int().min(1).optional().describe("退格次数,默认 1"),
166
- },
167
- }, async ({ count }) => formatControlResult("退格", await requestControlApi("backspace", { count })));
168
- server.registerTool("control_enter", {
169
- title: "Control Enter",
170
- description: "执行回车操作。",
171
- inputSchema: {},
172
- }, async () => formatControlResult("回车", await requestControlApi("enter")));
173
- server.registerTool("control_start_app", {
174
- title: "Control Start App",
175
- description: "启动指定应用。",
176
- inputSchema: {
177
- bundleId: z.string().min(1).describe("应用 bundleId"),
178
- },
179
- }, async ({ bundleId }) => formatControlResult("启动应用", await requestControlApi("startApp", { bundleId })));
180
- server.registerTool("control_activate_app", {
181
- title: "Control Activate App",
182
- description: "激活指定应用。",
183
- inputSchema: {
184
- bundleId: z.string().min(1).describe("应用 bundleId"),
185
- },
186
- }, async ({ bundleId }) => formatControlResult("激活应用", await requestControlApi("activateApp", { bundleId })));
187
- server.registerTool("control_stop_app", {
188
- title: "Control Stop App",
189
- description: "停止指定应用。",
190
- inputSchema: {
191
- bundleId: z.string().min(1).describe("应用 bundleId"),
192
- },
193
- }, async ({ bundleId }) => formatControlResult("停止应用", await requestControlApi("stopApp", { bundleId })));
194
- server.registerTool("control_open_url", {
195
- title: "Control Open URL",
196
- description: "打开指定 URL。",
197
- inputSchema: {
198
- url: z.string().min(1).describe("目标 URL"),
199
- },
200
- }, async ({ url }) => formatControlResult("打开 URL", await requestControlApi("openURL", { url })));
201
- }
@@ -1,9 +0,0 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- /**
3
- * 注册 HID API 对应 MCP 工具
4
- * @param server MCP 服务实例
5
- * @returns 无返回值
6
- * @example
7
- * registerHidTools(server)
8
- */
9
- export declare function registerHidTools(server: McpServer): void;