scripting-cli 1.1.5 → 1.1.6

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.
@@ -0,0 +1,346 @@
1
+
2
+ import chokidar, { FSWatcher } from 'chokidar';
3
+ import { Socket } from 'socket.io';
4
+ import { ensureDirectoryExistence, getPath, getRelativePath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
5
+ import fs from 'fs';
6
+ import chalk from 'chalk';
7
+ import path from 'path';
8
+
9
+ export class Controller {
10
+
11
+ private static instances: Map<string, Controller> = new Map();
12
+
13
+ static create(socket: Socket) {
14
+ const ctrl = new Controller(socket);
15
+ Controller.instances.set(socket.id, ctrl);
16
+ return ctrl;
17
+ }
18
+
19
+ static get(socketId: string) {
20
+ return Controller.instances.get(socketId);
21
+ }
22
+
23
+ watcher: FSWatcher | null = null;
24
+ scriptName: string | null = null;
25
+ socket: Socket | null = null;
26
+
27
+ constructor(socket: Socket) {
28
+ this.socket = socket;
29
+
30
+ socket.emit("socketId", socket.id);
31
+
32
+ socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
33
+
34
+ socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
35
+
36
+ socket.on('stopDebugScript', this.handleStopDebugScript);
37
+
38
+ socket.on("getFileContent", this.handleGetFileContent);
39
+
40
+ socket.on("log", this.handleLog);
41
+
42
+ socket.on("openFile", this.handleOpenFile)
43
+
44
+ socket.on('disconnect', (reason) => {
45
+ console.log(chalk.gray(`Client [${socket.id}] disconnected: ${reason}`));
46
+ this.watcher?.close();
47
+ this.watcher = null;
48
+ this.scriptName = null;
49
+ Controller.instances.delete(socket.id);
50
+ socket.removeAllListeners();
51
+ });
52
+
53
+ fs.promises.readdir(process.cwd()).then((files) => {
54
+ const serverScriptNames = files.filter((filename) =>
55
+ fs.statSync(filename).isDirectory()
56
+ && filename !== '.vscode'
57
+ && filename !== 'dts'
58
+ )
59
+ socket.emit("serverScripts", serverScriptNames);
60
+ })
61
+ }
62
+
63
+ createWatcher(scriptName: string) {
64
+ const scriptDir = getPath(scriptName)
65
+ this.watcher = chokidar.watch(scriptDir, {
66
+ ignored: /(^|[\/\\])\../,
67
+ persistent: true,
68
+ });
69
+
70
+ this.watcher
71
+ .on('change', (filePath) => {
72
+ if (filePath.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
73
+ // send file content md5 hash to client
74
+ // const content = fs.readFileSync(filePath, 'utf-8');
75
+ fs.readFile(filePath, 'utf-8', (err, content) => {
76
+ if (err) {
77
+ console.log(chalk.red(`Error reading file: ${err}`));
78
+ return;
79
+ }
80
+ const hash = md5(content);
81
+ const relativePath = getRelativePath(scriptDir, filePath);
82
+ console.log(
83
+ `[${chalk.bold.blue(scriptName)}] File changed: [${hash}]${relativePath}`
84
+ )
85
+ this.socket?.emit('fileChange', {
86
+ scriptName,
87
+ filePath: relativePath,
88
+ hash,
89
+ });
90
+ });
91
+ }
92
+ // TODO, add support for other file types
93
+ })
94
+ .on('unlink', (filePath) => {
95
+ const relativePath = getRelativePath(scriptDir, filePath);
96
+ this.socket?.emit('deleteFile', {
97
+ scriptName,
98
+ filePath: relativePath,
99
+ });
100
+ })
101
+ .on('unlinkDir', (filePath) => {
102
+ const relativePath = getRelativePath(scriptDir, filePath);
103
+ this.socket?.emit('deleteFile', {
104
+ scriptName,
105
+ filePath: relativePath,
106
+ });
107
+ })
108
+ .on('error', error => console.log(chalk.bgRed(`Watcher error: ${error}`)))
109
+ .on('ready', () => console.log(`[${chalk.bold.blue(scriptName)}] Watching files for changes`));
110
+ }
111
+
112
+ handleSyncScriptFromClient = async (data: {
113
+ 'global.d.ts': string,
114
+ 'scripting.d.ts': string,
115
+ scriptName: string
116
+ scriptFiles: Record<string, string>
117
+ }, ack: (result: {
118
+ error?: string
119
+ success?: boolean
120
+ }) => void) => {
121
+
122
+ try {
123
+ if (data.scriptName === this.scriptName) {
124
+ ack({
125
+ error: `Script [${data.scriptName}] is already initialized`,
126
+ });
127
+ return;
128
+ }
129
+
130
+ if (this.scriptName != null) {
131
+ console.log(`Received new script, closing previous watcher`);
132
+ this.watcher?.close();
133
+ this.watcher = null;
134
+ }
135
+
136
+ await writeDtsFiles({
137
+ "global.d.ts": data["global.d.ts"],
138
+ "scripting.d.ts": data["scripting.d.ts"],
139
+ });
140
+
141
+ this.scriptName = data.scriptName;
142
+
143
+ const scriptName = data.scriptName;
144
+
145
+ const scriptDir = getPath(data.scriptName);
146
+
147
+ const tsconfig = require(getPath('tsconfig.json'));
148
+
149
+ if (!tsconfig.include.includes(scriptName)) {
150
+ tsconfig.include.push(scriptName);
151
+ await fs.promises.writeFile(getPath('tsconfig.json'), JSON.stringify(tsconfig, null, 2))
152
+ }
153
+
154
+ ensureDirectoryExistence(scriptDir);
155
+
156
+ await Promise.all(
157
+ Object.entries(data.scriptFiles).map(async ([filename, content]) => {
158
+ const filePath = path.join(scriptDir, filename);
159
+ ensureDirectoryExistence(filePath);
160
+ await fs.promises.writeFile(filePath, content);
161
+ })
162
+ );
163
+
164
+ console.log(chalk.green('global.d.ts and scripting.d.ts and other script files saved.'));
165
+
166
+ this.createWatcher(data.scriptName);
167
+
168
+ ack({
169
+ success: true,
170
+ });
171
+
172
+ // Open the entry file in VSCode after a delay
173
+ // to ensure the response is sent. Because the open file command
174
+ // may suspend the response and cause the client to not receive the ack.
175
+ setTimeout(() => {
176
+ const entryFilePath = path.join(scriptDir, "index.tsx")
177
+ tryOpenFileInVSCode(entryFilePath);
178
+ }, 1000);
179
+
180
+ } catch (e) {
181
+ console.log(chalk.red(`Error: ${e}`));
182
+ ack({
183
+ error: `Failed to init and sync script files.\n${e}`,
184
+ })
185
+ }
186
+
187
+ }
188
+
189
+ handleSyncScriptFromServer = async (data: {
190
+ 'global.d.ts': string,
191
+ 'scripting.d.ts': string,
192
+ scriptName: string,
193
+ }, ack: (result: {
194
+ error?: string,
195
+ scriptFiles?: Record<string, {
196
+ hash: string
197
+ content: string
198
+ }>
199
+ }) => void) => {
200
+ try {
201
+ if (this.scriptName === data.scriptName) {
202
+ ack({
203
+ error: `Script ${data.scriptName} is already initialized`,
204
+ });
205
+ return;
206
+ }
207
+ if (this.scriptName != null) {
208
+ console.log(`Received new script [${chalk.bold.blue(data.scriptName)}], closing previous watcher`);
209
+ this.watcher?.close();
210
+ this.watcher = null;
211
+ }
212
+
213
+ await writeDtsFiles({
214
+ "global.d.ts": data["global.d.ts"],
215
+ "scripting.d.ts": data["scripting.d.ts"],
216
+ });
217
+
218
+ const scriptDir = getPath(data.scriptName);
219
+
220
+ if (!fs.existsSync(scriptDir)) {
221
+ ack({
222
+ error: `Script directory ${scriptDir} does not exist`,
223
+ });
224
+ return;
225
+ }
226
+
227
+ const scriptFiles: Record<string, {
228
+ hash: string
229
+ content: string
230
+ }> = {};
231
+
232
+ const readDir = async (dir: string) => {
233
+ const files = await fs.promises.readdir(dir, { withFileTypes: true });
234
+ await Promise.all(
235
+ files.map(async (file) => {
236
+ if (file.isFile()) {
237
+ const filePath = path.join(dir, file.name);
238
+ const relativePath = getRelativePath(scriptDir, filePath);
239
+ const content = await fs.promises.readFile(filePath, 'utf-8').catch((err) => {
240
+ console.log(chalk.red(`Error reading file: ${err}`));
241
+ });
242
+ if (typeof content === "string") {
243
+ scriptFiles[relativePath] = {
244
+ hash: md5(content),
245
+ content,
246
+ };
247
+ }
248
+ } else if (file.isDirectory()) {
249
+ await readDir(path.join(dir, file.name));
250
+ }
251
+ })
252
+ );
253
+ };
254
+
255
+ await readDir(scriptDir);
256
+
257
+ this.scriptName = data.scriptName;
258
+
259
+ ack({
260
+ scriptFiles,
261
+ });
262
+
263
+ this.createWatcher(data.scriptName);
264
+
265
+ // Open the entry file in VSCode after a delay
266
+ // to ensure the response is sent. Because the open file command
267
+ // may suspend the response and cause the client to not receive the ack.
268
+ setTimeout(() => {
269
+ const entryFilePath = path.join(scriptDir, "index.tsx")
270
+ tryOpenFileInVSCode(entryFilePath);
271
+ }, 1000);
272
+
273
+ } catch (e) {
274
+ ack({
275
+ error: `Failed to init and pull script files.\n${e}`,
276
+ });
277
+ }
278
+ }
279
+
280
+ handleLog = (data: {
281
+ scriptName: string
282
+ content: string
283
+ isError: boolean
284
+ }) => {
285
+ if (data.scriptName !== this.scriptName) {
286
+ return;
287
+ }
288
+ console.log(`[${chalk.bold.blue(this.scriptName)}][${data.isError ? chalk.red("ERROR") : "LOG"
289
+ }][${new Date().toLocaleTimeString()}] ${data.content}`);
290
+ }
291
+
292
+ handleOpenFile = async (data: {
293
+ scriptName: string
294
+ relativePath: string
295
+ }) => {
296
+ if (data.scriptName !== this.scriptName) {
297
+ return;
298
+ }
299
+
300
+ const filePath = path.join(getPath(this.scriptName), data.relativePath)
301
+
302
+ if (fs.existsSync(filePath)) {
303
+ tryOpenFileInVSCode(filePath)
304
+ }
305
+
306
+ }
307
+
308
+ handleStopDebugScript = (data: string, ack: (result: boolean) => void) => {
309
+ if (data === this.scriptName) {
310
+ console.log(`[${chalk.bold.blue(this.scriptName)}] Stop debug script`);
311
+ this.watcher?.close();
312
+ this.watcher = null;
313
+ this.scriptName = null;
314
+ ack(true);
315
+ } else {
316
+ ack(false);
317
+ }
318
+ }
319
+
320
+ handleGetFileContent = async (data: {
321
+ scriptName: string,
322
+ relativePath: string
323
+ }, ack: (result: {
324
+ error?: string,
325
+ content?: string
326
+ }) => void) => {
327
+ if (this.scriptName !== data.scriptName) {
328
+ ack({
329
+ error: `Script ${data.scriptName} is not initialized`,
330
+ });
331
+ return;
332
+ }
333
+
334
+ const filePath = path.join(getPath(data.scriptName), data.relativePath);
335
+ try {
336
+ const content = await fs.promises.readFile(filePath, 'utf-8');
337
+ ack({
338
+ content,
339
+ });
340
+ } catch (e) {
341
+ ack({
342
+ error: `Failed to get file content.\n${e}`,
343
+ });
344
+ }
345
+ }
346
+ }
@@ -0,0 +1,124 @@
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 syncScriptFromClient: express.RequestHandler = (req, res) => {
53
+ const params = req.body as {
54
+ socketId: string;
55
+ scriptName: string;
56
+ scriptFiles: Record<string, string>;
57
+ 'global.d.ts': string;
58
+ 'scripting.d.ts': string;
59
+ };
60
+
61
+ const socketId = params.socketId;
62
+
63
+ const ctrl = Controller.get(socketId);
64
+
65
+ if (!ctrl) {
66
+ console.log(chalk.red(`Socket not found: ${socketId}.`));
67
+ res.json({
68
+ error: "Socket not found."
69
+ });
70
+ return;
71
+ }
72
+
73
+ ctrl.handleSyncScriptFromClient(params, (result) => {
74
+ if (result.error) {
75
+ res.json({
76
+ error: result.error
77
+ });
78
+ return;
79
+ }
80
+ res.json({
81
+ success: true
82
+ });
83
+ })
84
+ };
85
+
86
+ const syncScriptFromServer: express.RequestHandler = (req, res) => {
87
+ const params = req.body as {
88
+ socketId: string;
89
+ 'global.d.ts': string,
90
+ 'scripting.d.ts': string,
91
+ scriptName: string,
92
+ };
93
+
94
+ const socketId = params.socketId;
95
+
96
+ const ctrl = Controller.get(socketId);
97
+
98
+ if (!ctrl) {
99
+ res.json({
100
+ error: "Socket not found."
101
+ });
102
+ return;
103
+ }
104
+
105
+ ctrl.handleSyncScriptFromServer(params, (result) => {
106
+ if (result.error) {
107
+ res.json({
108
+ error: result.error
109
+ });
110
+ return;
111
+ }
112
+ res.json({
113
+ scriptFiles: result.scriptFiles
114
+ });
115
+ })
116
+ };
117
+
118
+ export function initHttpRouter(app: express.Express) {
119
+ app.use(express.json({ limit: '50mb' }));
120
+ app.use(express.urlencoded({ extended: true }));
121
+ app.get("/getFileContent", getFileContent);
122
+ app.post("/syncScriptFromClient", syncScriptFromClient);
123
+ app.post("/syncScriptFromServer", syncScriptFromServer);
124
+ }