scripting-cli 1.2.0 → 1.2.2

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/const.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scriptingDtsFileName = exports.globalDtsFileName = void 0;
4
+ exports.globalDtsFileName = 'global.d.ts';
5
+ exports.scriptingDtsFileName = 'scripting.d.ts';
@@ -9,6 +9,7 @@ const util_1 = require("./util");
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const chalk_1 = __importDefault(require("chalk"));
11
11
  const path_1 = __importDefault(require("path"));
12
+ const const_1 = require("./const");
12
13
  class Controller {
13
14
  static instances = new Map();
14
15
  static create(socket, noAutoOpen) {
@@ -27,10 +28,10 @@ class Controller {
27
28
  this.noAutoOpen = noAutoOpen;
28
29
  this.socket = socket;
29
30
  socket.emit("socketId", socket.id);
30
- socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
31
- socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
32
- socket.on('stopDebugScript', this.handleStopDebugScript);
33
- socket.on("getFileContent", this.handleGetFileContent);
31
+ // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
32
+ // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
33
+ // socket.on('stopDebugScript', this.handleStopDebugScript);
34
+ // socket.on("getFileContent", this.handleGetFileContent);
34
35
  socket.on("log", this.handleLog);
35
36
  socket.on("openFile", this.handleOpenFile);
36
37
  socket.on('disconnect', (reason) => {
@@ -43,7 +44,7 @@ class Controller {
43
44
  });
44
45
  fs_1.default.promises.readdir((0, util_1.getScriptPath)()).then((files) => {
45
46
  const serverScriptNames = files.filter((filename) => fs_1.default.statSync((0, util_1.getScriptPath)(filename)).isDirectory()
46
- && filename !== '.vscode'
47
+ && !filename.startsWith('.')
47
48
  && filename !== 'dts');
48
49
  socket.emit("serverScripts", serverScriptNames);
49
50
  });
@@ -54,8 +55,7 @@ class Controller {
54
55
  ignored: /(^|[\/\\])\../,
55
56
  persistent: true,
56
57
  });
57
- this.watcher
58
- .on('change', (filePath) => {
58
+ const updateHandler = (filePath) => {
59
59
  if (filePath.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
60
60
  // send file content md5 hash to client
61
61
  // const content = fs.readFileSync(filePath, 'utf-8');
@@ -74,22 +74,28 @@ class Controller {
74
74
  });
75
75
  });
76
76
  }
77
- // TODO, add support for other file types
78
- })
79
- .on('unlink', (filePath) => {
80
- const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
81
- this.socket?.emit('deleteFile', {
82
- scriptName,
83
- filePath: relativePath,
84
- });
85
- })
86
- .on('unlinkDir', (filePath) => {
77
+ else {
78
+ // Other file types, just notify the client to reload the file
79
+ const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
80
+ console.log(`[${chalk_1.default.bold.blue(scriptName)}] File changed: ${relativePath}`);
81
+ this.socket?.emit('otherFileChange', {
82
+ scriptName,
83
+ filePath: relativePath,
84
+ });
85
+ }
86
+ };
87
+ const deleteHandler = (filePath) => {
87
88
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
88
89
  this.socket?.emit('deleteFile', {
89
90
  scriptName,
90
91
  filePath: relativePath,
91
92
  });
92
- })
93
+ };
94
+ this.watcher
95
+ .on('add', updateHandler)
96
+ .on('change', updateHandler)
97
+ .on('unlink', deleteHandler)
98
+ .on('unlinkDir', deleteHandler)
93
99
  .on('error', error => console.log(chalk_1.default.bgRed(`Watcher error: ${error}`)))
94
100
  .on('ready', () => console.log(`[${chalk_1.default.bold.blue(scriptName)}] Watching files for changes`));
95
101
  }
@@ -107,8 +113,8 @@ class Controller {
107
113
  this.watcher = null;
108
114
  }
109
115
  await (0, util_1.writeDtsFiles)({
110
- "global.d.ts": data["global.d.ts"],
111
- "scripting.d.ts": data["scripting.d.ts"],
116
+ [const_1.globalDtsFileName]: data[const_1.globalDtsFileName],
117
+ [const_1.scriptingDtsFileName]: data[const_1.scriptingDtsFileName],
112
118
  });
113
119
  this.scriptName = data.scriptName;
114
120
  const scriptDir = (0, util_1.getScriptPath)(data.scriptName);
@@ -118,7 +124,7 @@ class Controller {
118
124
  (0, util_1.ensureDirectoryExistence)(filePath);
119
125
  await fs_1.default.promises.writeFile(filePath, content);
120
126
  }));
121
- console.log(chalk_1.default.green('global.d.ts and scripting.d.ts and other script files saved.'));
127
+ console.log(chalk_1.default.green(`${const_1.globalDtsFileName} and ${const_1.scriptingDtsFileName} and other script files saved.`));
122
128
  this.createWatcher(data.scriptName);
123
129
  ack({
124
130
  success: true,
@@ -154,8 +160,8 @@ class Controller {
154
160
  this.watcher = null;
155
161
  }
156
162
  await (0, util_1.writeDtsFiles)({
157
- "global.d.ts": data["global.d.ts"],
158
- "scripting.d.ts": data["scripting.d.ts"],
163
+ globalDtsFileName: data[const_1.globalDtsFileName],
164
+ scriptingDtsFileName: data[const_1.scriptingDtsFileName],
159
165
  });
160
166
  const scriptDir = (0, util_1.getScriptPath)(data.scriptName);
161
167
  if (!fs_1.default.existsSync(scriptDir)) {
@@ -165,20 +171,31 @@ class Controller {
165
171
  return;
166
172
  }
167
173
  const scriptFiles = {};
174
+ const otherFiles = [];
168
175
  const readDir = async (dir) => {
169
176
  const files = await fs_1.default.promises.readdir(dir, { withFileTypes: true });
170
177
  await Promise.all(files.map(async (file) => {
178
+ // ignore .git and .vscode directories
179
+ if (file.name.startsWith('.git') || file.name.startsWith('.vscode')) {
180
+ return;
181
+ }
182
+ // only read js, jsx, ts, tsx, json, md, txt files
171
183
  if (file.isFile()) {
172
184
  const filePath = path_1.default.join(dir, file.name);
173
185
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
174
- const content = await fs_1.default.promises.readFile(filePath, 'utf-8').catch((err) => {
175
- console.log(chalk_1.default.red(`Error reading file: ${err}`));
176
- });
177
- if (typeof content === "string") {
178
- scriptFiles[relativePath] = {
179
- hash: (0, util_1.md5)(content),
180
- content,
181
- };
186
+ if (file.name.match(/\.(js(x)?|ts(x)?|json|md|txt)$/)) {
187
+ const content = await fs_1.default.promises.readFile(filePath, 'utf-8').catch((err) => {
188
+ console.log(chalk_1.default.red(`Error reading file: ${err}`));
189
+ });
190
+ if (typeof content === "string") {
191
+ scriptFiles[relativePath] = {
192
+ hash: (0, util_1.md5)(content),
193
+ content,
194
+ };
195
+ }
196
+ }
197
+ else {
198
+ otherFiles.push(relativePath);
182
199
  }
183
200
  }
184
201
  else if (file.isDirectory()) {
@@ -190,6 +207,7 @@ class Controller {
190
207
  this.scriptName = data.scriptName;
191
208
  ack({
192
209
  scriptFiles,
210
+ otherFiles: otherFiles.length > 0 ? otherFiles : undefined,
193
211
  });
194
212
  this.createWatcher(data.scriptName);
195
213
  if (!this.noAutoOpen) {
@@ -255,5 +273,24 @@ class Controller {
255
273
  });
256
274
  }
257
275
  };
276
+ handleGetFilePath = async (data, ack) => {
277
+ if (this.scriptName !== data.scriptName) {
278
+ ack({
279
+ error: `Script ${data.scriptName} is not initialized`,
280
+ });
281
+ return;
282
+ }
283
+ const filePath = path_1.default.join((0, util_1.getScriptPath)(data.scriptName), data.relativePath);
284
+ if (fs_1.default.existsSync(filePath)) {
285
+ ack({
286
+ filePath,
287
+ });
288
+ }
289
+ else {
290
+ ack({
291
+ error: `File ${filePath} does not exist`,
292
+ });
293
+ }
294
+ };
258
295
  }
259
296
  exports.Controller = Controller;
@@ -41,6 +41,36 @@ const getFileContent = (req, res) => {
41
41
  });
42
42
  });
43
43
  };
44
+ const getFileData = (req, res) => {
45
+ const { socketId, scriptName, relativePath, } = req.query;
46
+ if (!socketId) {
47
+ console.log(chalk_1.default.red(`Socket not found: ${socketId}`));
48
+ }
49
+ if (!scriptName || !relativePath) {
50
+ res.json({
51
+ error: "Missing parameters: scriptName or relativePath."
52
+ });
53
+ return;
54
+ }
55
+ const ctrl = controller_1.Controller.get(socketId);
56
+ if (!ctrl) {
57
+ console.log(chalk_1.default.red(`Socket not found: ${socketId}`));
58
+ res.json({
59
+ error: "Socket not found."
60
+ });
61
+ return;
62
+ }
63
+ ctrl.handleGetFilePath({
64
+ scriptName,
65
+ relativePath,
66
+ }, (result) => {
67
+ if (result.error) {
68
+ res.status(500).send(result.error);
69
+ return;
70
+ }
71
+ res.sendFile(result.filePath);
72
+ });
73
+ };
44
74
  const syncScriptFromClient = (req, res) => {
45
75
  const params = req.body;
46
76
  const socketId = params.socketId;
@@ -90,6 +120,7 @@ function initHttpRouter(app) {
90
120
  app.use(express_1.default.json({ limit: '50mb' }));
91
121
  app.use(express_1.default.urlencoded({ extended: true }));
92
122
  app.get("/getFileContent", getFileContent);
123
+ app.get("/getFileData", getFileData);
93
124
  app.post("/syncScriptFromClient", syncScriptFromClient);
94
125
  app.post("/syncScriptFromServer", syncScriptFromServer);
95
126
  }
package/dist/index.js CHANGED
@@ -1,5 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
3
36
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
38
  };
@@ -55,6 +88,17 @@ const start_server_1 = require("./start_server");
55
88
  noAutoOpen: argv['no-auto-open'],
56
89
  startBonjourService: argv.bonjour,
57
90
  });
91
+ })
92
+ .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
93
+ return yargs
94
+ .usage("$0 migrate")
95
+ .example([
96
+ ["$0 migrate", "Migrate the scripts in the workspace root directory to the scripts directory."]
97
+ ]);
98
+ }, async () => {
99
+ const { migrateOldFiles } = await Promise.resolve().then(() => __importStar(require('./util')));
100
+ await migrateOldFiles();
101
+ process.exit(0);
58
102
  })
59
103
  .showHelpOnFail(true)
60
104
  .option('help', {
@@ -30,7 +30,7 @@ function startServer({ port, noAutoOpen, startBonjourService }) {
30
30
  (0, util_1.createTsConfig)(); // Create tsconfig.json when the server starts
31
31
  (0, util_1.createVSCodeSettings)(); // Create vscode settings.json when the server starts
32
32
  (0, util_1.ensureScriptsDirectory)(); // Ensure the scripts directory exists
33
- await (0, util_1.migrateOldFiles)(); // Migrate old files to the scripts directory
33
+ // await migrateOldFiles(); // Migrate old files to the scripts directory
34
34
  const ipAddress = ip_1.default.address();
35
35
  const address = `http://${ipAddress}:${PORT}`;
36
36
  if (startBonjourService) {
@@ -44,7 +44,7 @@ function startServer({ port, noAutoOpen, startBonjourService }) {
44
44
  qrcode_terminal_1.default.generate(address, { small: true });
45
45
  if (startBonjourService) {
46
46
  function gracefulShutdown() {
47
- console.log('Shutting down Bonjour…');
47
+ console.log('Shutting down Bonjour...');
48
48
  service.stop(() => {
49
49
  bonjour.unpublishAll(() => {
50
50
  // wait for 500ms,let goodbye message be sent completely
package/dist/util.js CHANGED
@@ -20,6 +20,7 @@ const os_1 = __importDefault(require("os"));
20
20
  const child_process_1 = __importDefault(require("child_process"));
21
21
  const fs_1 = __importDefault(require("fs"));
22
22
  const chalk_1 = __importDefault(require("chalk"));
23
+ const const_1 = require("./const");
23
24
  function md5(content) {
24
25
  return crypto_1.default
25
26
  .createHash('md5')
@@ -71,12 +72,12 @@ function createTsConfig() {
71
72
  "jsxFragmentFactory": "Fragment",
72
73
  "paths": {
73
74
  "scripting": [
74
- "./dts/scripting.d.ts"
75
+ "./dts/${const_1.scriptingDtsFileName}"
75
76
  ]
76
77
  }
77
78
  },
78
79
  "include": [
79
- "./dts/global.d.ts",
80
+ "./dts/${const_1.globalDtsFileName}",
80
81
  "scripts"
81
82
  ]
82
83
  }`;
@@ -90,7 +91,7 @@ function createTsConfig() {
90
91
  const tsconfig = JSON.parse(fs_1.default.readFileSync(filePath, 'utf-8'));
91
92
  if (tsconfig.include && !tsconfig.include.includes('scripts')) {
92
93
  tsconfig.include = [
93
- "./dts/global.d.ts",
94
+ `./dts/${const_1.globalDtsFileName}`,
94
95
  "scripts"
95
96
  ];
96
97
  fs_1.default.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
@@ -151,8 +152,9 @@ function getRelativePath(from, to) {
151
152
  async function migrateOldFiles() {
152
153
  try {
153
154
  const list = await fs_1.default.promises.readdir(process.cwd());
155
+ let hasMigrated = false;
154
156
  for (const file of list) {
155
- if (file === 'dts' || file === '.vscode' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules') {
157
+ if (file === 'dts' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
156
158
  continue;
157
159
  }
158
160
  const filePath = path_1.default.join(process.cwd(), file);
@@ -165,9 +167,16 @@ async function migrateOldFiles() {
165
167
  console.log(chalk_1.default.yellow(`File ${newFilePath} already exists, skipping...`));
166
168
  continue;
167
169
  }
170
+ hasMigrated = true;
168
171
  console.log(chalk_1.default.blue(`Moving ${filePath} to ${newFilePath}`));
169
172
  await fs_1.default.promises.rename(filePath, newFilePath);
170
173
  }
174
+ if (hasMigrated) {
175
+ console.log(chalk_1.default.green('Old files migrated to the scripts directory.'));
176
+ }
177
+ else {
178
+ console.log(chalk_1.default.gray('No old files to migrate.'));
179
+ }
171
180
  }
172
181
  catch (err) {
173
182
  console.log(`Failed to migrate old files: ${chalk_1.default.red(`${err}`)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scripting-cli",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "This plugin integrates the desktop editor synchronization feature of the Scripting app.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
package/src/const.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const globalDtsFileName = 'global.d.ts';
2
+ export const scriptingDtsFileName = 'scripting.d.ts';
package/src/controller.ts CHANGED
@@ -1,10 +1,11 @@
1
1
 
2
2
  import chokidar, { FSWatcher } from 'chokidar';
3
3
  import { Socket } from 'socket.io';
4
- import { ensureDirectoryExistence, getPath, getRelativePath, getScriptPath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
4
+ import { ensureDirectoryExistence, getRelativePath, getScriptPath, md5, tryOpenFileInVSCode, writeDtsFiles } from './util';
5
5
  import fs from 'fs';
6
6
  import chalk from 'chalk';
7
7
  import path from 'path';
8
+ import { globalDtsFileName, scriptingDtsFileName } from './const';
8
9
 
9
10
  export class Controller {
10
11
 
@@ -31,13 +32,13 @@ export class Controller {
31
32
 
32
33
  socket.emit("socketId", socket.id);
33
34
 
34
- socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
35
+ // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
35
36
 
36
- socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
37
+ // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
37
38
 
38
- socket.on('stopDebugScript', this.handleStopDebugScript);
39
+ // socket.on('stopDebugScript', this.handleStopDebugScript);
39
40
 
40
- socket.on("getFileContent", this.handleGetFileContent);
41
+ // socket.on("getFileContent", this.handleGetFileContent);
41
42
 
42
43
  socket.on("log", this.handleLog);
43
44
 
@@ -55,7 +56,7 @@ export class Controller {
55
56
  fs.promises.readdir(getScriptPath()).then((files) => {
56
57
  const serverScriptNames = files.filter((filename) =>
57
58
  fs.statSync(getScriptPath(filename)).isDirectory()
58
- && filename !== '.vscode'
59
+ && !filename.startsWith('.')
59
60
  && filename !== 'dts'
60
61
  )
61
62
  socket.emit("serverScripts", serverScriptNames);
@@ -69,51 +70,59 @@ export class Controller {
69
70
  persistent: true,
70
71
  });
71
72
 
72
- this.watcher
73
- .on('change', (filePath) => {
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
- });
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,
92
91
  });
93
- }
94
- // TODO, add support for other file types
95
- })
96
- .on('unlink', (filePath) => {
97
- const relativePath = getRelativePath(scriptDir, filePath);
98
- this.socket?.emit('deleteFile', {
99
- scriptName,
100
- filePath: relativePath,
101
92
  });
102
- })
103
- .on('unlinkDir', (filePath) => {
93
+ } else {
94
+ // Other file types, just notify the client to reload the file
104
95
  const relativePath = getRelativePath(scriptDir, filePath);
105
- this.socket?.emit('deleteFile', {
96
+ console.log(
97
+ `[${chalk.bold.blue(scriptName)}] File changed: ${relativePath}`
98
+ )
99
+ this.socket?.emit('otherFileChange', {
106
100
  scriptName,
107
101
  filePath: relativePath,
108
102
  });
109
- })
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)
110
119
  .on('error', error => console.log(chalk.bgRed(`Watcher error: ${error}`)))
111
120
  .on('ready', () => console.log(`[${chalk.bold.blue(scriptName)}] Watching files for changes`));
112
121
  }
113
122
 
114
123
  handleSyncScriptFromClient = async (data: {
115
- 'global.d.ts': string,
116
- 'scripting.d.ts': string,
124
+ [globalDtsFileName]: string,
125
+ [scriptingDtsFileName]: string,
117
126
  scriptName: string
118
127
  scriptFiles: Record<string, string>
119
128
  }, ack: (result: {
@@ -136,8 +145,8 @@ export class Controller {
136
145
  }
137
146
 
138
147
  await writeDtsFiles({
139
- "global.d.ts": data["global.d.ts"],
140
- "scripting.d.ts": data["scripting.d.ts"],
148
+ [globalDtsFileName]: data[globalDtsFileName],
149
+ [scriptingDtsFileName]: data[scriptingDtsFileName],
141
150
  });
142
151
 
143
152
  this.scriptName = data.scriptName;
@@ -154,7 +163,7 @@ export class Controller {
154
163
  })
155
164
  );
156
165
 
157
- console.log(chalk.green('global.d.ts and scripting.d.ts and other script files saved.'));
166
+ console.log(chalk.green(`${globalDtsFileName} and ${scriptingDtsFileName} and other script files saved.`));
158
167
 
159
168
  this.createWatcher(data.scriptName);
160
169
 
@@ -192,6 +201,7 @@ export class Controller {
192
201
  hash: string
193
202
  content: string
194
203
  }>
204
+ otherFiles?: string[]
195
205
  }) => void) => {
196
206
  try {
197
207
  if (this.scriptName === data.scriptName) {
@@ -207,8 +217,8 @@ export class Controller {
207
217
  }
208
218
 
209
219
  await writeDtsFiles({
210
- "global.d.ts": data["global.d.ts"],
211
- "scripting.d.ts": data["scripting.d.ts"],
220
+ globalDtsFileName: data[globalDtsFileName],
221
+ scriptingDtsFileName: data[scriptingDtsFileName],
212
222
  });
213
223
 
214
224
  const scriptDir = getScriptPath(data.scriptName);
@@ -225,21 +235,34 @@ export class Controller {
225
235
  content: string
226
236
  }> = {};
227
237
 
238
+ const otherFiles: string[] = [];
239
+
228
240
  const readDir = async (dir: string) => {
229
241
  const files = await fs.promises.readdir(dir, { withFileTypes: true });
230
242
  await Promise.all(
231
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
232
250
  if (file.isFile()) {
233
251
  const filePath = path.join(dir, file.name);
234
252
  const relativePath = getRelativePath(scriptDir, filePath);
235
- const content = await fs.promises.readFile(filePath, 'utf-8').catch((err) => {
236
- console.log(chalk.red(`Error reading file: ${err}`));
237
- });
238
- if (typeof content === "string") {
239
- scriptFiles[relativePath] = {
240
- hash: md5(content),
241
- content,
242
- };
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);
243
266
  }
244
267
  } else if (file.isDirectory()) {
245
268
  await readDir(path.join(dir, file.name));
@@ -254,6 +277,7 @@ export class Controller {
254
277
 
255
278
  ack({
256
279
  scriptFiles,
280
+ otherFiles: otherFiles.length > 0 ? otherFiles : undefined,
257
281
  });
258
282
 
259
283
  this.createWatcher(data.scriptName);
@@ -340,4 +364,30 @@ export class Controller {
340
364
  });
341
365
  }
342
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
+ }
343
393
  }
@@ -49,6 +49,49 @@ const getFileContent: express.RequestHandler = (req, res) => {
49
49
  })
50
50
  }
51
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
+
52
95
  const syncScriptFromClient: express.RequestHandler = (req, res) => {
53
96
  const params = req.body as {
54
97
  socketId: string;
@@ -119,6 +162,7 @@ export function initHttpRouter(app: express.Express) {
119
162
  app.use(express.json({ limit: '50mb' }));
120
163
  app.use(express.urlencoded({ extended: true }));
121
164
  app.get("/getFileContent", getFileContent);
165
+ app.get("/getFileData", getFileData);
122
166
  app.post("/syncScriptFromClient", syncScriptFromClient);
123
167
  app.post("/syncScriptFromServer", syncScriptFromServer);
124
168
  }
package/src/index.ts CHANGED
@@ -54,6 +54,17 @@ yargs(hideBin(process.argv))
54
54
  startBonjourService: argv.bonjour,
55
55
  });
56
56
  })
57
+ .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
58
+ return yargs
59
+ .usage("$0 migrate")
60
+ .example([
61
+ ["$0 migrate", "Migrate the scripts in the workspace root directory to the scripts directory."]
62
+ ]);
63
+ }, async () => {
64
+ const { migrateOldFiles } = await import('./util');
65
+ await migrateOldFiles();
66
+ process.exit(0);
67
+ })
57
68
  .showHelpOnFail(true)
58
69
  .option('help', {
59
70
  alias: 'h',
@@ -6,7 +6,7 @@ import ip from 'ip';
6
6
  import Bonjour from 'bonjour';
7
7
  import chalk from 'chalk';
8
8
  import qrcode from 'qrcode-terminal';
9
- import { createTsConfig, createVSCodeSettings, ensureScriptsDirectory, migrateOldFiles, } from './util';
9
+ import { createTsConfig, createVSCodeSettings, ensureScriptsDirectory, } from './util';
10
10
  import { Controller } from './controller';
11
11
  import { initHttpRouter } from './http_router';
12
12
 
@@ -36,7 +36,8 @@ export function startServer({ port, noAutoOpen, startBonjourService }: {
36
36
  createTsConfig(); // Create tsconfig.json when the server starts
37
37
  createVSCodeSettings(); // Create vscode settings.json when the server starts
38
38
  ensureScriptsDirectory(); // Ensure the scripts directory exists
39
- await migrateOldFiles(); // Migrate old files to the scripts directory
39
+
40
+ // await migrateOldFiles(); // Migrate old files to the scripts directory
40
41
 
41
42
  const ipAddress = ip.address()
42
43
  const address = `http://${ipAddress}:${PORT}`;
@@ -55,7 +56,7 @@ export function startServer({ port, noAutoOpen, startBonjourService }: {
55
56
  if (startBonjourService) {
56
57
 
57
58
  function gracefulShutdown() {
58
- console.log('Shutting down Bonjour…');
59
+ console.log('Shutting down Bonjour...');
59
60
  service.stop(() => {
60
61
  bonjour.unpublishAll(() => {
61
62
  // wait for 500ms,let goodbye message be sent completely
package/src/util.ts CHANGED
@@ -4,6 +4,7 @@ import os from 'os';
4
4
  import childProcess from 'child_process';
5
5
  import fs from 'fs';
6
6
  import chalk from 'chalk';
7
+ import { globalDtsFileName, scriptingDtsFileName } from './const';
7
8
 
8
9
  export function md5(content: string): string {
9
10
  return crypto
@@ -59,12 +60,12 @@ export function createTsConfig() {
59
60
  "jsxFragmentFactory": "Fragment",
60
61
  "paths": {
61
62
  "scripting": [
62
- "./dts/scripting.d.ts"
63
+ "./dts/${scriptingDtsFileName}"
63
64
  ]
64
65
  }
65
66
  },
66
67
  "include": [
67
- "./dts/global.d.ts",
68
+ "./dts/${globalDtsFileName}",
68
69
  "scripts"
69
70
  ]
70
71
  }`;
@@ -79,7 +80,7 @@ export function createTsConfig() {
79
80
  const tsconfig = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
80
81
  if (tsconfig.include && !tsconfig.include.includes('scripts')) {
81
82
  tsconfig.include = [
82
- "./dts/global.d.ts",
83
+ `./dts/${globalDtsFileName}`,
83
84
  "scripts"
84
85
  ];
85
86
  fs.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
@@ -148,10 +149,11 @@ export function getRelativePath(from: string, to: string) {
148
149
  export async function migrateOldFiles() {
149
150
  try {
150
151
  const list = await fs.promises.readdir(process.cwd());
152
+ let hasMigrated = false;
151
153
 
152
154
  for (const file of list) {
153
155
 
154
- if (file === 'dts' || file === '.vscode' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules') {
156
+ if (file === 'dts' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
155
157
  continue;
156
158
  }
157
159
 
@@ -170,11 +172,18 @@ export async function migrateOldFiles() {
170
172
  continue;
171
173
  }
172
174
 
175
+ hasMigrated = true;
173
176
  console.log(chalk.blue(`Moving ${filePath} to ${newFilePath}`));
174
177
  await fs.promises.rename(filePath, newFilePath);
175
178
 
176
179
  }
177
180
 
181
+ if (hasMigrated) {
182
+ console.log(chalk.green('Old files migrated to the scripts directory.'));
183
+ } else {
184
+ console.log(chalk.gray('No old files to migrate.'));
185
+ }
186
+
178
187
  } catch (err) {
179
188
  console.log(`Failed to migrate old files: ${chalk.red(`${err}`)}`);
180
189
  }