scripting-cli 1.2.5 → 1.3.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.
@@ -1,179 +0,0 @@
1
-
2
- import express from 'express';
3
- import http from 'http';
4
- import { Server as SocketIOServer } from 'socket.io';
5
- import os from 'os';
6
- import ip from 'ip';
7
- import Bonjour from 'bonjour';
8
- import chalk from 'chalk';
9
- import qrcode from 'qrcode-terminal';
10
- import { createTsConfig, createVSCodeSettings, ensureScriptsDirectory, } from './util';
11
- import { Controller } from './controller';
12
- import { initHttpRouter } from './http_router';
13
-
14
- const app = express();
15
- const server = http.createServer(app);
16
- const io = new SocketIOServer(server);
17
- const bonjour = Bonjour();
18
-
19
- // Keywords to identify VPN/virtual network adapters that should be excluded
20
- const VIRTUAL_ADAPTER_KEYWORDS = [
21
- 'virtual',
22
- 'vpn',
23
- 'vethernet',
24
- 'vmware',
25
- 'vmnet',
26
- 'vbox',
27
- 'virtualbox',
28
- 'docker',
29
- 'wsl',
30
- 'loopback',
31
- 'hamachi',
32
- 'tunngle',
33
- 'cloudflare',
34
- 'warp',
35
- 'tailscale',
36
- 'zerotier'
37
- ];
38
-
39
- // Preferred adapter names for real network interfaces
40
- const PREFERRED_ADAPTER_KEYWORDS = [
41
- 'ethernet',
42
- 'eth',
43
- 'wi-fi',
44
- 'wifi',
45
- 'wlan',
46
- 'en0',
47
- 'en1'
48
- ];
49
-
50
- /**
51
- * Get the local network IP address, filtering out VPN and virtual adapters.
52
- * Prioritizes real network adapters (Ethernet, Wi-Fi) over virtual ones.
53
- */
54
- function getLocalNetworkIP(): string | null {
55
- const interfaces = os.networkInterfaces();
56
- const results: { name: string; address: string; priority: number }[] = [];
57
-
58
- for (const [name, addrs] of Object.entries(interfaces)) {
59
- if (!addrs) continue;
60
-
61
- const lowerName = name.toLowerCase();
62
-
63
- // Skip virtual/VPN adapters
64
- if (VIRTUAL_ADAPTER_KEYWORDS.some(keyword => lowerName.includes(keyword))) {
65
- continue;
66
- }
67
-
68
- for (const addr of addrs) {
69
- // Only consider non-internal IPv4 addresses
70
- if (addr.family === 'IPv4' && !addr.internal) {
71
- // Skip certain IP ranges typically used by VPNs
72
- // 198.18.0.0/15 is reserved for network benchmark testing (Cloudflare WARP uses this)
73
- // 100.64.0.0/10 is Carrier-grade NAT (Tailscale uses this)
74
- const ip = addr.address;
75
- const firstOctet = parseInt(ip.split('.')[0], 10);
76
- const secondOctet = parseInt(ip.split('.')[1], 10);
77
-
78
- if (firstOctet === 198 && (secondOctet === 18 || secondOctet === 19)) {
79
- continue; // Skip 198.18.0.0/15
80
- }
81
- if (firstOctet === 100 && secondOctet >= 64 && secondOctet <= 127) {
82
- continue; // Skip 100.64.0.0/10
83
- }
84
-
85
- // Determine priority (lower is better)
86
- let priority = 10;
87
- if (PREFERRED_ADAPTER_KEYWORDS.some(keyword => lowerName.includes(keyword))) {
88
- priority = 1;
89
- }
90
-
91
- results.push({ name, address: ip, priority });
92
- }
93
- }
94
- }
95
-
96
- // Sort by priority and return the best match
97
- results.sort((a, b) => a.priority - b.priority);
98
- return results.length > 0 ? results[0].address : null;
99
- }
100
-
101
- export function startServer({ port, noAutoOpen, startBonjourService }: {
102
- port: number | undefined
103
- noAutoOpen: boolean | undefined
104
- startBonjourService: boolean | undefined
105
- }) {
106
-
107
- // console.log("port", port, "noAutoOpen", noAutoOpen);
108
-
109
- const PORT = port ?? 3000;
110
-
111
- initHttpRouter(app);
112
-
113
- io.on('connection', (socket) => {
114
- Controller.create(socket, noAutoOpen);
115
- console.log(chalk.blue(`Client [${socket.id}] connected`));
116
- });
117
-
118
- server.listen(PORT, async () => {
119
- createTsConfig(); // Create tsconfig.json when the server starts
120
- createVSCodeSettings(); // Create vscode settings.json when the server starts
121
- ensureScriptsDirectory(); // Ensure the scripts directory exists
122
-
123
- // await migrateOldFiles(); // Migrate old files to the scripts directory
124
-
125
- const ipAddress = getLocalNetworkIP() ?? ip.address();
126
- const address = `http://${ipAddress}:${PORT}`;
127
-
128
- if (startBonjourService) {
129
- console.log(`Server listening on ${chalk.bold.blue(address)}\n\n${chalk.yellow('You can select this server in the Scripting app to connect')}.\n`);
130
-
131
- console.log(`Alternatively, you can ${chalk.green.bold("use the Scripting app to scan")} the QR code and connect: `);
132
- } else {
133
- console.log(chalk.yellow.italic(`The bonjour service is not started, you can use \`--bonjour\` option to start it.`));
134
- console.log(`Server listening on ${chalk.bold.blue(address)}\nYou can ${chalk.green.bold("use the Scripting app to scan")} the QR code and connect: `);
135
- }
136
-
137
- qrcode.generate(address, { small: true });
138
-
139
- if (startBonjourService) {
140
-
141
- function gracefulShutdown() {
142
- console.log('Shutting down Bonjour...');
143
- service.stop(() => {
144
- bonjour.unpublishAll(() => {
145
- // wait for 500ms,let goodbye message be sent completely
146
- setTimeout(() => {
147
- bonjour.destroy();
148
- console.log('Bonjour services have been shut down properly.');
149
- process.exit(0);
150
- }, 500);
151
- });
152
- });
153
- }
154
-
155
- const service = bonjour.publish({
156
- name: 'Scripting-service',
157
- type: 'http',
158
- port: PORT,
159
- host: 'scripting-service.local',
160
- });
161
-
162
- // Register bonjour service error handler
163
- service.on('error', err => {
164
- console.error('Bonjour service error:', err);
165
- });
166
-
167
- ['SIGINT', 'SIGTERM'].forEach(sig =>
168
- process.once(sig, gracefulShutdown)
169
- );
170
-
171
- // Handle uncaught exceptions
172
- process.on('uncaughtException', err => {
173
- console.error('Uncaught exception:', err);
174
- gracefulShutdown();
175
- });
176
- }
177
-
178
- });
179
- }
package/src/util.ts DELETED
@@ -1,191 +0,0 @@
1
- import path from 'path';
2
- import crypto from 'crypto';
3
- import os from 'os';
4
- import childProcess from 'child_process';
5
- import fs from 'fs';
6
- import chalk from 'chalk';
7
- import { globalDtsFileName, scriptingDtsFileName } from './const';
8
-
9
- export function md5(content: string): string {
10
- return crypto
11
- .createHash('md5')
12
- .update(content)
13
- .digest('hex');
14
- }
15
-
16
- export function getPath(filename: string) {
17
- return path.join(process.cwd(), filename);
18
- }
19
-
20
- export function getScriptPath(filename?: string) {
21
- if (filename != null) {
22
- return path.join(process.cwd(), 'scripts', filename);
23
- }
24
- return path.join(process.cwd(), 'scripts');
25
- }
26
-
27
- export function tryOpenFileInVSCode(filePath: string) {
28
- let cmd = `code "${filePath}"`;
29
- if (os.platform() === "win32") {
30
- cmd = `cmd.exe /c ${cmd}`;
31
- } else if (os.platform() === "linux") {
32
- const shell = process.env["SHELL"];
33
- cmd = `${shell} -c ${cmd}`;
34
- } else {
35
- cmd = `"/Applications/Visual Studio Code.app/Contents/MacOS/Electron" "${filePath}"`;
36
- }
37
- childProcess.execSync(cmd);
38
- }
39
-
40
-
41
- // Function to create tsconfig.json
42
- export function createTsConfig() {
43
- const tsconfigContent = `{
44
- "compilerOptions": {
45
- "target": "ESNext",
46
- "lib": [
47
- "esnext"
48
- ],
49
- "allowJs": true,
50
- "strict": true,
51
- "esModuleInterop": true,
52
- "allowSyntheticDefaultImports": true,
53
- "forceConsistentCasingInFileNames": true,
54
- "noFallthroughCasesInSwitch": true,
55
- "module": "CommonJS",
56
- "resolveJsonModule": true,
57
- "skipLibCheck": true,
58
- "jsx": "react",
59
- "jsxFactory": "createElement",
60
- "jsxFragmentFactory": "Fragment",
61
- "paths": {
62
- "scripting": [
63
- "./dts/${scriptingDtsFileName}"
64
- ]
65
- }
66
- },
67
- "include": [
68
- "./dts/${globalDtsFileName}",
69
- "scripts"
70
- ]
71
- }`;
72
-
73
- const filePath = getPath('tsconfig.json');
74
- ensureDirectoryExistence(filePath);
75
-
76
- if (!fs.existsSync(filePath)) {
77
- fs.writeFileSync(filePath, tsconfigContent);
78
- console.log(chalk.green('tsconfig.json created.'));
79
- } else {
80
- const tsconfig = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
81
- if (tsconfig.include && !tsconfig.include.includes('scripts')) {
82
- tsconfig.include = [
83
- `./dts/${globalDtsFileName}`,
84
- "scripts"
85
- ];
86
- fs.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
87
- console.log(chalk.yellow('tsconfig.json updated to include scripts directory.'));
88
- } else {
89
- console.log(chalk.gray('tsconfig.json already exists.'));
90
- }
91
- }
92
- }
93
-
94
- export function createVSCodeSettings() {
95
- const settingsContent = `{
96
- "typescript.format.semicolons": "remove",
97
- "typescript.preferences.jsxAttributeCompletionStyle": "braces",
98
- }`;
99
-
100
- const filePath = getPath('.vscode/settings.json');
101
- ensureDirectoryExistence(filePath);
102
- if (!fs.existsSync(filePath)) {
103
- fs.writeFileSync(filePath, settingsContent);
104
- console.log(chalk.green('.vscode/settings.json created.'));
105
- } else {
106
- console.log(chalk.gray('.vscode/settings.json already exists.'));
107
- }
108
-
109
- }
110
-
111
- export function ensureScriptsDirectory() {
112
- const scriptsDir = getScriptPath();
113
- if (!fs.existsSync(scriptsDir)) {
114
- fs.mkdirSync(scriptsDir, { recursive: true });
115
- console.log(chalk.green('Scripts directory created.'));
116
- } else {
117
- console.log(chalk.gray('Scripts directory already exists.'));
118
- }
119
- }
120
-
121
- export function ensureDirectoryExistence(filePath: string) {
122
- const dirname = path.dirname(filePath);
123
- if (!fs.existsSync(dirname)) {
124
- fs.mkdirSync(dirname, { recursive: true });
125
- }
126
- }
127
-
128
- export async function writeDtsFiles(files: Record<string, string>) {
129
- await Promise.all(
130
- Object.entries(files).map(async ([filename, content]) => {
131
- const filePath = getPath(`dts/${filename}`);
132
- ensureDirectoryExistence(filePath);
133
- await
134
- fs
135
- .promises
136
- .writeFile(filePath, content)
137
- .catch((err) => {
138
- console.log(chalk.red(`Error writing file: ${err}`));
139
- });
140
- })
141
- );
142
- }
143
-
144
- export function getRelativePath(from: string, to: string) {
145
- const relativePath = path.relative(from, to);
146
- return relativePath.replaceAll("\\", "/");
147
- }
148
-
149
- export async function migrateOldFiles() {
150
- try {
151
- const list = await fs.promises.readdir(process.cwd());
152
- let hasMigrated = false;
153
-
154
- for (const file of list) {
155
-
156
- if (file === 'dts' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
157
- continue;
158
- }
159
-
160
- const filePath = path.join(process.cwd(), file);
161
-
162
- const stat = await fs.promises.stat(filePath);
163
-
164
- if (!stat.isDirectory()) {
165
- continue;
166
- }
167
-
168
- const newFilePath = path.join(process.cwd(), 'scripts', file);
169
-
170
- if (fs.existsSync(newFilePath)) {
171
- console.log(chalk.yellow(`File ${newFilePath} already exists, skipping...`));
172
- continue;
173
- }
174
-
175
- hasMigrated = true;
176
- console.log(chalk.blue(`Moving ${filePath} to ${newFilePath}`));
177
- await fs.promises.rename(filePath, newFilePath);
178
-
179
- }
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
-
187
- } catch (err) {
188
- console.log(`Failed to migrate old files: ${chalk.red(`${err}`)}`);
189
- }
190
-
191
- }
package/tsconfig.json DELETED
@@ -1,19 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ESNext",
4
- "module": "commonjs",
5
- "declaration": false,
6
- "outDir": "./dist",
7
- "strict": true,
8
- "allowSyntheticDefaultImports": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "forceConsistentCasingInFileNames": true,
12
- "baseUrl": ".",
13
- "paths": {
14
- "*": ["*", "src/*"]
15
- }
16
- },
17
- "include": ["src/**/*"],
18
- "exclude": ["node_modules"]
19
- }