scripting-cli 1.2.5 → 1.4.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/README_zh.md DELETED
@@ -1,106 +0,0 @@
1
- # Scripting 应用命令行工具
2
-
3
- 欢迎使用 `scripting-cli` 命令行工具,它旨在与 Scripting 应用集成。该工具允许您在使用喜爱的桌面编辑器(如 VSCode)开发脚本时,实现实时同步和预览。
4
-
5
- [English](./README.md) | [日本語](./README_ja.md) | [Deutsch](./README_de.md) | [Français](./README_fr.md) | [Italiano](./README_it.md)
6
-
7
- ## 先决条件
8
-
9
- 在使用 `scripting-cli` 之前,请确保满足以下要求:
10
-
11
- 1. **Node.js**:确保已安装最新版本的 Node.js。您可以通过运行以下命令检查当前版本:
12
-
13
- ```bash
14
- node -v
15
- ```
16
-
17
- 2. **Scripting 应用**:必须安装 Scripting 应用,以便连接由 `scripting-cli` 启动的本地服务。
18
-
19
- ## 安装
20
-
21
- 无需全局安装 `scripting-cli`,只需使用 `npx` 运行即可:
22
-
23
- ```bash
24
- npx scripting-cli <command>
25
- ```
26
-
27
- ## 使用方法
28
-
29
- ### 1. 创建工作目录
30
-
31
- 首先创建一个目录,用于存放您的 Scripting 应用脚本。例如:
32
-
33
- ```bash
34
- mkdir my-scripting-project
35
- cd my-scripting-project
36
- ```
37
-
38
- ### 2. 启动本地服务
39
-
40
- 在工作目录中,运行以下命令启动本地开发服务:
41
-
42
- ```bash
43
- npx scripting-cli start
44
- ```
45
-
46
- 默认情况下,服务将在端口 `3000` 上启动。如需指定其他端口,请使用 `--port` 选项:
47
-
48
- ```bash
49
- npx scripting-cli start --port=4000
50
- ```
51
-
52
- 要启用 Bonjour 支持,使 Scripting 应用自动检测本地服务,请添加 `--bonjour` 标志:
53
-
54
- ```bash
55
- npx scripting-cli start --bonjour
56
- ```
57
-
58
- ### 3. 连接 Scripting 应用
59
-
60
- 服务运行后,打开 **Scripting 应用** 并连接您刚刚启动的本地服务。这将建立应用与工作目录之间的连接。
61
-
62
- ### 4. 调试和同步代码
63
-
64
- 连接后,选择要调试的脚本项目。Scripting 应用将自动将该项目的代码同步到您的工作目录。
65
-
66
- ### 5. 实时代码同步
67
-
68
- 在桌面编辑器(如 VSCode)中编写并保存脚本时,更新的代码将自动同步到 Scripting 应用并实时执行,使开发和调试更加顺畅。
69
-
70
- ## 示例工作流程
71
-
72
- 1. 启动本地服务:
73
-
74
- ```bash
75
- npx scripting-cli start
76
- ```
77
-
78
- 2. 打开编辑器并编写脚本。
79
-
80
- 3. 保存脚本文件。
81
-
82
- 4. 更新的代码将自动同步到 Scripting 应用并执行。
83
-
84
- ## 附加信息
85
-
86
- * 默认端口为 `3000`。如果该端口已被占用,可使用 `--port` 选项指定其他端口。
87
- * 使用 `--no-auto-open` 标志可防止工具自动打开 `index.tsx` 或 `widget.tsx` 文件:
88
-
89
- ```bash
90
- npx scripting-cli start --no-auto-open
91
- ```
92
- * 要使用 Bonjour 服务,请确保系统支持该功能。在 Windows 上,可能需要手动安装 Bonjour。然后,使用 `--bonjour` 选项启用该服务。
93
- * 该工具适用于喜欢使用 VSCode 等桌面编辑器,并希望与 Scripting 应用实现无缝代码同步和调试的用户。
94
-
95
- ## 故障排除
96
-
97
- 如果遇到问题,请确保:
98
-
99
- * 使用的是 Node.js 版本 20 或更高。
100
- * Scripting 应用已正确连接到本地服务。
101
- * 所选端口未被其他进程占用。
102
- * 始终使用 `npx scripting-cli <command>` 运行工具,并确保软件包是最新的。
103
-
104
- ---
105
-
106
- 祝您在 Scripting 应用的开发工作中使用 `scripting-cli` 顺利!编码愉快!
package/src/const.ts DELETED
@@ -1,2 +0,0 @@
1
- export const globalDtsFileName = 'global.d.ts';
2
- export const scriptingDtsFileName = 'scripting.d.ts';
package/src/controller.ts DELETED
@@ -1,393 +0,0 @@
1
-
2
- import chokidar, { FSWatcher } from 'chokidar';
3
- import { Socket } from 'socket.io';
4
- import { ensureDirectoryExistence, getRelativePath, getScriptPath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
5
- import fs from 'fs';
6
- import chalk from 'chalk';
7
- import path from 'path';
8
- import { globalDtsFileName, scriptingDtsFileName } from './const';
9
-
10
- export class Controller {
11
-
12
- private static instances: Map<string, Controller> = new Map();
13
-
14
- static create(socket: Socket, noAutoOpen: boolean | undefined) {
15
- const ctrl = new Controller(socket, noAutoOpen);
16
- Controller.instances.set(socket.id, ctrl);
17
- return ctrl;
18
- }
19
-
20
- static get(socketId: string) {
21
- return Controller.instances.get(socketId);
22
- }
23
-
24
- watcher: FSWatcher | null = null;
25
- scriptName: string | null = null;
26
- socket: Socket | null = null;
27
- noAutoOpen: boolean | undefined;
28
-
29
- constructor(socket: Socket, noAutoOpen: boolean | undefined) {
30
- this.noAutoOpen = noAutoOpen;
31
- this.socket = socket;
32
-
33
- socket.emit("socketId", socket.id);
34
-
35
- // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
36
-
37
- // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
38
-
39
- // socket.on("getFileContent", this.handleGetFileContent);
40
-
41
- socket.on('stopDebugScript', this.handleStopDebugScript);
42
-
43
- socket.on("log", this.handleLog);
44
-
45
- socket.on("openFile", this.handleOpenFile)
46
-
47
- socket.on('disconnect', (reason) => {
48
- console.log(chalk.gray(`Client [${socket.id}] disconnected: ${reason}`));
49
- this.watcher?.close();
50
- this.watcher = null;
51
- this.scriptName = null;
52
- Controller.instances.delete(socket.id);
53
- socket.removeAllListeners();
54
- });
55
-
56
- fs.promises.readdir(getScriptPath()).then((files) => {
57
- const serverScriptNames = files.filter((filename) =>
58
- fs.statSync(getScriptPath(filename)).isDirectory()
59
- && !filename.startsWith('.')
60
- && filename !== 'dts'
61
- )
62
- socket.emit("serverScripts", serverScriptNames);
63
- })
64
- }
65
-
66
- createWatcher(scriptName: string) {
67
- const scriptDir = getScriptPath(scriptName)
68
- this.watcher = chokidar.watch(scriptDir, {
69
- ignored: /(^|[\/\\])\../,
70
- persistent: true,
71
- });
72
-
73
- const updateHandler = (filePath: string) => {
74
- if (filePath.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
75
- // send file content md5 hash to client
76
- // const content = fs.readFileSync(filePath, 'utf-8');
77
- fs.readFile(filePath, 'utf-8', (err, content) => {
78
- if (err) {
79
- console.log(chalk.red(`Error reading file: ${err}`));
80
- return;
81
- }
82
- const hash = md5(content);
83
- const relativePath = getRelativePath(scriptDir, filePath);
84
- console.log(
85
- `[${chalk.bold.blue(scriptName)}] File changed: [${hash}]${relativePath}`
86
- )
87
- this.socket?.emit('fileChange', {
88
- scriptName,
89
- filePath: relativePath,
90
- hash,
91
- });
92
- });
93
- } else {
94
- // Other file types, just notify the client to reload the file
95
- const relativePath = getRelativePath(scriptDir, filePath);
96
- console.log(
97
- `[${chalk.bold.blue(scriptName)}] File changed: ${relativePath}`
98
- )
99
- this.socket?.emit('otherFileChange', {
100
- scriptName,
101
- filePath: relativePath,
102
- });
103
- }
104
- };
105
-
106
- const deleteHandler = (filePath: string) => {
107
- const relativePath = getRelativePath(scriptDir, filePath);
108
- this.socket?.emit('deleteFile', {
109
- scriptName,
110
- filePath: relativePath,
111
- });
112
- };
113
-
114
- this.watcher
115
- .on('add', updateHandler)
116
- .on('change', updateHandler)
117
- .on('unlink', deleteHandler)
118
- .on('unlinkDir', deleteHandler)
119
- .on('error', error => console.log(chalk.bgRed(`Watcher error: ${error}`)))
120
- .on('ready', () => console.log(`[${chalk.bold.blue(scriptName)}] Watching files for changes`));
121
- }
122
-
123
- handleSyncScriptFromClient = async (data: {
124
- [globalDtsFileName]: string,
125
- [scriptingDtsFileName]: string,
126
- scriptName: string
127
- scriptFiles: Record<string, string>
128
- }, ack: (result: {
129
- error?: string
130
- success?: boolean
131
- }) => void) => {
132
-
133
- try {
134
- if (data.scriptName === this.scriptName) {
135
- ack({
136
- error: `Script [${data.scriptName}] is already initialized`,
137
- });
138
- return;
139
- }
140
-
141
- if (this.scriptName != null) {
142
- console.log(`Received new script, closing previous watcher`);
143
- this.watcher?.close();
144
- this.watcher = null;
145
- }
146
-
147
- await writeDtsFiles({
148
- [globalDtsFileName]: data[globalDtsFileName],
149
- [scriptingDtsFileName]: data[scriptingDtsFileName],
150
- });
151
-
152
- this.scriptName = data.scriptName;
153
-
154
- const scriptDir = getScriptPath(data.scriptName);
155
-
156
- ensureDirectoryExistence(scriptDir);
157
-
158
- await Promise.all(
159
- Object.entries(data.scriptFiles).map(async ([filename, content]) => {
160
- const filePath = path.join(scriptDir, filename);
161
- ensureDirectoryExistence(filePath);
162
- await fs.promises.writeFile(filePath, content);
163
- })
164
- );
165
-
166
- console.log(chalk.green(`${globalDtsFileName} and ${scriptingDtsFileName} and other script files saved.`));
167
-
168
- this.createWatcher(data.scriptName);
169
-
170
- ack({
171
- success: true,
172
- });
173
-
174
- if (!this.noAutoOpen) {
175
-
176
- // Open the entry file in VSCode after a delay
177
- // to ensure the response is sent. Because the open file command
178
- // may suspend the response and cause the client to not receive the ack.
179
- setTimeout(() => {
180
- const entryFilePath = path.join(scriptDir, "index.tsx")
181
- tryOpenFileInVSCode(entryFilePath);
182
- }, 1000);
183
- }
184
-
185
- } catch (e) {
186
- console.log(chalk.red(`Error: ${e}`));
187
- ack({
188
- error: `Failed to init and sync script files.\n${e}`,
189
- })
190
- }
191
-
192
- }
193
-
194
- handleSyncScriptFromServer = async (data: {
195
- 'global.d.ts': string,
196
- 'scripting.d.ts': string,
197
- scriptName: string,
198
- }, ack: (result: {
199
- error?: string,
200
- scriptFiles?: Record<string, {
201
- hash: string
202
- content: string
203
- }>
204
- otherFiles?: string[]
205
- }) => void) => {
206
- try {
207
- if (this.scriptName === data.scriptName) {
208
- ack({
209
- error: `Script ${data.scriptName} is already initialized`,
210
- });
211
- return;
212
- }
213
- if (this.scriptName != null) {
214
- console.log(`Received new script [${chalk.bold.blue(data.scriptName)}], closing previous watcher`);
215
- this.watcher?.close();
216
- this.watcher = null;
217
- }
218
-
219
- await writeDtsFiles({
220
- [globalDtsFileName]: data[globalDtsFileName],
221
- [scriptingDtsFileName]: data[scriptingDtsFileName],
222
- });
223
-
224
- const scriptDir = getScriptPath(data.scriptName);
225
-
226
- if (!fs.existsSync(scriptDir)) {
227
- ack({
228
- error: `Script directory ${scriptDir} does not exist`,
229
- });
230
- return;
231
- }
232
-
233
- const scriptFiles: Record<string, {
234
- hash: string
235
- content: string
236
- }> = {};
237
-
238
- const otherFiles: string[] = [];
239
-
240
- const readDir = async (dir: string) => {
241
- const files = await fs.promises.readdir(dir, { withFileTypes: true });
242
- await Promise.all(
243
- files.map(async (file) => {
244
- // ignore .git and .vscode directories
245
- if (file.name.startsWith('.git') || file.name.startsWith('.vscode')) {
246
- return;
247
- }
248
-
249
- // only read js, jsx, ts, tsx, json, md, txt files
250
- if (file.isFile()) {
251
- const filePath = path.join(dir, file.name);
252
- const relativePath = getRelativePath(scriptDir, filePath);
253
-
254
- if (file.name.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
255
- const content = await fs.promises.readFile(filePath, 'utf-8').catch((err) => {
256
- console.log(chalk.red(`Error reading file: ${err}`));
257
- });
258
- if (typeof content === "string") {
259
- scriptFiles[relativePath] = {
260
- hash: md5(content),
261
- content,
262
- };
263
- }
264
- } else {
265
- otherFiles.push(relativePath);
266
- }
267
- } else if (file.isDirectory()) {
268
- await readDir(path.join(dir, file.name));
269
- }
270
- })
271
- );
272
- };
273
-
274
- await readDir(scriptDir);
275
-
276
- this.scriptName = data.scriptName;
277
-
278
- ack({
279
- scriptFiles,
280
- otherFiles: otherFiles.length > 0 ? otherFiles : undefined,
281
- });
282
-
283
- this.createWatcher(data.scriptName);
284
-
285
- if (!this.noAutoOpen) {
286
- // Open the entry file in VSCode after a delay
287
- // to ensure the response is sent. Because the open file command
288
- // may suspend the response and cause the client to not receive the ack.
289
- setTimeout(() => {
290
- const entryFilePath = path.join(scriptDir, "index.tsx")
291
- tryOpenFileInVSCode(entryFilePath);
292
- }, 1000);
293
- }
294
- } catch (e) {
295
- ack({
296
- error: `Failed to init and pull script files.\n${e}`,
297
- });
298
- }
299
- }
300
-
301
- handleLog = (data: {
302
- scriptName: string
303
- content: string
304
- isError: boolean
305
- }) => {
306
- if (data.scriptName !== this.scriptName) {
307
- return;
308
- }
309
- console.log(`[${chalk.bold.blue(this.scriptName)}][${data.isError ? chalk.red("ERROR") : "LOG"
310
- }][${new Date().toLocaleTimeString()}] ${data.content}`);
311
- }
312
-
313
- handleOpenFile = async (data: {
314
- scriptName: string
315
- relativePath: string
316
- }) => {
317
- if (data.scriptName !== this.scriptName) {
318
- return;
319
- }
320
-
321
- const filePath = path.join(getScriptPath(this.scriptName), data.relativePath)
322
-
323
- if (!this.noAutoOpen && fs.existsSync(filePath)) {
324
- tryOpenFileInVSCode(filePath)
325
- }
326
-
327
- }
328
-
329
- handleStopDebugScript = (data: string, ack: (result: boolean) => void) => {
330
- if (data === this.scriptName) {
331
- console.log(`[${chalk.bold.blue(this.scriptName)}] Stop debug script`);
332
- this.watcher?.close();
333
- this.watcher = null;
334
- this.scriptName = null;
335
- ack(true);
336
- } else {
337
- ack(false);
338
- }
339
- }
340
-
341
- handleGetFileContent = async (data: {
342
- scriptName: string,
343
- relativePath: string
344
- }, ack: (result: {
345
- error?: string,
346
- content?: string
347
- }) => void) => {
348
- if (this.scriptName !== data.scriptName) {
349
- ack({
350
- error: `Script ${data.scriptName} is not initialized`,
351
- });
352
- return;
353
- }
354
-
355
- const filePath = path.join(getScriptPath(data.scriptName), data.relativePath);
356
- try {
357
- const content = await fs.promises.readFile(filePath, 'utf-8');
358
- ack({
359
- content,
360
- });
361
- } catch (e) {
362
- ack({
363
- error: `Failed to get file content.\n${e}`,
364
- });
365
- }
366
- }
367
-
368
- handleGetFilePath = async (data: {
369
- scriptName: string,
370
- relativePath: string
371
- }, ack: (result: {
372
- error?: string,
373
- filePath?: string
374
- }) => void) => {
375
- if (this.scriptName !== data.scriptName) {
376
- ack({
377
- error: `Script ${data.scriptName} is not initialized`,
378
- });
379
- return;
380
- }
381
-
382
- const filePath = path.join(getScriptPath(data.scriptName), data.relativePath);
383
- if (fs.existsSync(filePath)) {
384
- ack({
385
- filePath,
386
- });
387
- } else {
388
- ack({
389
- error: `File ${filePath} does not exist`,
390
- });
391
- }
392
- }
393
- }
@@ -1,168 +0,0 @@
1
- import express from 'express';
2
- import { Controller } from './controller';
3
- import chalk from 'chalk';
4
-
5
- const getFileContent: express.RequestHandler = (req, res) => {
6
- const {
7
- socketId,
8
- scriptName,
9
- relativePath,
10
- } = req.query as {
11
- scriptName: string;
12
- socketId: string;
13
- relativePath: string;
14
- };
15
-
16
- if (!socketId) {
17
- console.log(chalk.red(`Socket not found: ${socketId}`));
18
- }
19
-
20
- if (!scriptName || !relativePath) {
21
- res.json({
22
- error: "Missing parameters: scriptName or relativePath."
23
- });
24
- return;
25
- }
26
-
27
- const ctrl = Controller.get(socketId);
28
- if (!ctrl) {
29
- console.log(chalk.red(`Socket not found: ${socketId}`));
30
- res.json({
31
- error: "Socket not found."
32
- });
33
- return;
34
- }
35
-
36
- ctrl.handleGetFileContent({
37
- scriptName,
38
- relativePath,
39
- }, (result: any) => {
40
- if (result.error) {
41
- res.json({
42
- error: result.error
43
- });
44
- return;
45
- }
46
- res.json({
47
- content: result.content
48
- });
49
- })
50
- }
51
-
52
- const getFileData: express.RequestHandler = (req, res) => {
53
- const {
54
- socketId,
55
- scriptName,
56
- relativePath,
57
- } = req.query as {
58
- scriptName: string;
59
- socketId: string;
60
- relativePath: string;
61
- };
62
-
63
- if (!socketId) {
64
- console.log(chalk.red(`Socket not found: ${socketId}`));
65
- }
66
-
67
- if (!scriptName || !relativePath) {
68
- res.json({
69
- error: "Missing parameters: scriptName or relativePath."
70
- });
71
- return;
72
- }
73
-
74
- const ctrl = Controller.get(socketId);
75
- if (!ctrl) {
76
- console.log(chalk.red(`Socket not found: ${socketId}`));
77
- res.json({
78
- error: "Socket not found."
79
- });
80
- return;
81
- }
82
-
83
- ctrl.handleGetFilePath({
84
- scriptName,
85
- relativePath,
86
- }, (result: any) => {
87
- if (result.error) {
88
- res.status(500).send(result.error);
89
- return;
90
- }
91
- res.sendFile(result.filePath);
92
- })
93
- }
94
-
95
- const syncScriptFromClient: express.RequestHandler = (req, res) => {
96
- const params = req.body as {
97
- socketId: string;
98
- scriptName: string;
99
- scriptFiles: Record<string, string>;
100
- 'global.d.ts': string;
101
- 'scripting.d.ts': string;
102
- };
103
-
104
- const socketId = params.socketId;
105
-
106
- const ctrl = Controller.get(socketId);
107
-
108
- if (!ctrl) {
109
- console.log(chalk.red(`Socket not found: ${socketId}.`));
110
- res.json({
111
- error: "Socket not found."
112
- });
113
- return;
114
- }
115
-
116
- ctrl.handleSyncScriptFromClient(params, (result) => {
117
- if (result.error) {
118
- res.json({
119
- error: result.error
120
- });
121
- return;
122
- }
123
- res.json({
124
- success: true
125
- });
126
- })
127
- };
128
-
129
- const syncScriptFromServer: express.RequestHandler = (req, res) => {
130
- const params = req.body as {
131
- socketId: string;
132
- 'global.d.ts': string,
133
- 'scripting.d.ts': string,
134
- scriptName: string,
135
- };
136
-
137
- const socketId = params.socketId;
138
-
139
- const ctrl = Controller.get(socketId);
140
-
141
- if (!ctrl) {
142
- res.json({
143
- error: "Socket not found."
144
- });
145
- return;
146
- }
147
-
148
- ctrl.handleSyncScriptFromServer(params, (result) => {
149
- if (result.error) {
150
- res.json({
151
- error: result.error
152
- });
153
- return;
154
- }
155
- res.json({
156
- scriptFiles: result.scriptFiles
157
- });
158
- })
159
- };
160
-
161
- export function initHttpRouter(app: express.Express) {
162
- app.use(express.json({ limit: '50mb' }));
163
- app.use(express.urlencoded({ extended: true }));
164
- app.get("/getFileContent", getFileContent);
165
- app.get("/getFileData", getFileData);
166
- app.post("/syncScriptFromClient", syncScriptFromClient);
167
- app.post("/syncScriptFromServer", syncScriptFromServer);
168
- }