scripting-cli 1.2.4 → 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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Scripting App Command-Line Tool
2
2
 
3
- Welcome to the `scripting-cli`, the command-line tool designed for integrating with the Scripting app. This tool allows you to synchronize and preview your scripts in real-time as you develop them using your favorite desktop editor, such as VSCode.
3
+ Welcome to the `scripting-cli`, the command-line tool designed for integrating with the Scripting app. This tool allows you to synchronize and preview your scripts in real-time as you develop them using your favorite desktop editor (VSCode, Cursor, Windsurf, Zed, WebStorm, Vim, and more).
4
4
 
5
5
  [中文](./README_zh.md) | [日本語](./README_ja.md) | [Deutsch](./README_de.md) | [Français](./README_fr.md) | [Italiano](./README_it.md)
6
6
 
@@ -67,6 +67,79 @@ After connecting, select the script project you want to debug. The Scripting app
67
67
 
68
68
  As you write and save scripts using your desktop editor (e.g., VSCode), the changes will automatically sync with the Scripting app and be executed in real-time—making development and debugging much smoother.
69
69
 
70
+ ## Editor Selection and Config File
71
+
72
+ `scripting-cli` is no longer tied to VSCode. The first time you run `npx scripting-cli start`, you'll be prompted to choose the editor you actually use. Your choice is saved to `scripting.config.json` in your project root so the prompt won't appear again.
73
+
74
+ ### Supported editors
75
+
76
+ VSCode, VSCode Insiders, VSCodium, Cursor, Windsurf, Trae, Zed, WebStorm, IntelliJ IDEA, Fleet, Sublime Text, Nova, Vim, Neovim, Emacs, plus `custom` (any other command) and `none` (disable auto-open).
77
+
78
+ Editors detected on your `PATH` are marked with ✓ and listed first.
79
+
80
+ ### Per-run override
81
+
82
+ ```bash
83
+ # Use Cursor for this run only (does not modify scripting.config.json)
84
+ npx scripting-cli start --editor=cursor
85
+
86
+ # Re-run the interactive selection and overwrite the saved choice
87
+ npx scripting-cli start --reconfigure
88
+ ```
89
+
90
+ ### Config file
91
+
92
+ `scripting-cli` looks for the first config file it finds in this order:
93
+
94
+ ```
95
+ scripting.config.ts
96
+ scripting.config.mts
97
+ scripting.config.cts
98
+ scripting.config.js
99
+ scripting.config.mjs
100
+ scripting.config.cjs
101
+ scripting.config.json
102
+ ```
103
+
104
+ The default file is JSON so the npx flow stays zero-install. TypeScript and JavaScript files are loaded via [jiti](https://github.com/unjs/jiti).
105
+
106
+ ```jsonc
107
+ // scripting.config.json
108
+ {
109
+ "editor": "cursor", // see supported editors above
110
+ "editorCommand": "cursor", // optional, overrides the default command
111
+ "editorArgs": [], // optional, extra CLI args
112
+ "port": 3000,
113
+ "autoOpen": true,
114
+ "generateTsConfig": true, // set to false if you manage tsconfig.json yourself
115
+ "logLevel": "info" // "silent" | "error" | "warn" | "info" | "debug"
116
+ }
117
+ ```
118
+
119
+ CLI flags take precedence over the config file.
120
+
121
+ ### Type completion (TypeScript config)
122
+
123
+ To get autocomplete in `scripting.config.ts`, install scripting-cli as a dev dependency:
124
+
125
+ ```bash
126
+ npm i -D scripting-cli
127
+ ```
128
+
129
+ Then:
130
+
131
+ ```ts
132
+ // scripting.config.ts
133
+ import { defineConfig } from 'scripting-cli'
134
+
135
+ export default defineConfig({
136
+ editor: 'cursor',
137
+ port: 4000,
138
+ })
139
+ ```
140
+
141
+ You can also use `.ts` without installing the package — `npx scripting-cli start` still loads it via `jiti`. You just won't get IDE type hints.
142
+
70
143
  ## Example Workflow
71
144
 
72
145
  1. Start the local service:
@@ -89,8 +162,9 @@ As you write and save scripts using your desktop editor (e.g., VSCode), the chan
89
162
  ```bash
90
163
  npx scripting-cli start --no-auto-open
91
164
  ```
165
+ * Use `--editor=<key>` to override the configured editor for a single run, or `--reconfigure` to re-run the interactive editor selection.
92
166
  * To use the Bonjour service, ensure your system supports it. On Windows, you may need to install Bonjour manually. Then, use the `--bonjour` option to enable it.
93
- * This tool is ideal for users who prefer desktop editors like VSCode and want seamless code synchronization and debugging with the Scripting app.
167
+ * This tool works with any desktop editor and provides seamless code synchronization and debugging with the Scripting app.
94
168
 
95
169
  ## Troubleshooting
96
170
 
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
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
+ })();
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ const yargs_1 = __importDefault(require("yargs/yargs"));
41
+ const helpers_1 = require("yargs/helpers");
42
+ const start_server_1 = require("./start_server");
43
+ (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
44
+ .parserConfiguration({
45
+ "boolean-negation": false
46
+ })
47
+ .command('start', 'Start the scripting-cli server', (yargs) => {
48
+ return yargs
49
+ .options({
50
+ port: {
51
+ alias: ["p"],
52
+ describe: "The port the server listens on",
53
+ type: "number",
54
+ },
55
+ "no-auto-open": {
56
+ type: "boolean",
57
+ describe: "Do not open the index.tsx/widget.tsx file automatically",
58
+ },
59
+ bonjour: {
60
+ type: "boolean",
61
+ describe: "Enable bonjour service",
62
+ },
63
+ editor: {
64
+ type: "string",
65
+ describe: "Override the editor for this run (e.g. vscode, cursor, zed, webstorm)",
66
+ },
67
+ reconfigure: {
68
+ type: "boolean",
69
+ describe: "Force the interactive editor selection again, overwriting the saved config",
70
+ },
71
+ })
72
+ .usage("$0 start [--port=<port>] [--editor=<key>] [--reconfigure] [--no-auto-open] [--bonjour]")
73
+ .example([
74
+ ["$0 start -p=8000", "Start server and listen on 8000"],
75
+ ["$0 start --no-auto-open", "Start server without opening the entry file"],
76
+ ["$0 start --bonjour", "Start server with bonjour service"],
77
+ ["$0 start --editor=cursor", "Use Cursor for this run"],
78
+ ["$0 start --reconfigure", "Reselect the editor interactively"],
79
+ ]);
80
+ }, (argv) => {
81
+ (0, start_server_1.startServer)({
82
+ port: argv.port,
83
+ noAutoOpen: argv['no-auto-open'],
84
+ startBonjourService: argv.bonjour,
85
+ editorOverride: argv.editor,
86
+ reconfigure: argv.reconfigure,
87
+ });
88
+ })
89
+ .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
90
+ return yargs
91
+ .usage("$0 migrate")
92
+ .example([
93
+ ["$0 migrate", "Migrate the scripts in the workspace root directory to the scripts directory."]
94
+ ]);
95
+ }, async () => {
96
+ const { migrateOldFiles } = await Promise.resolve().then(() => __importStar(require('./util')));
97
+ await migrateOldFiles();
98
+ process.exit(0);
99
+ })
100
+ .showHelpOnFail(true)
101
+ .option('help', {
102
+ alias: 'h',
103
+ describe: 'Show help',
104
+ })
105
+ .demandCommand()
106
+ .parse();
@@ -0,0 +1,11 @@
1
+ import { ResolvedConfig, ScriptingConfig } from './types';
2
+ export declare function findConfigFile(cwd?: string): string | null;
3
+ export declare function loadConfigFile(filePath: string): Promise<ScriptingConfig>;
4
+ export declare function saveJsonConfig(config: ScriptingConfig, cwd?: string): string;
5
+ export interface ResolveOptions {
6
+ port?: number;
7
+ noAutoOpen?: boolean;
8
+ editorOverride?: string;
9
+ reconfigure?: boolean;
10
+ }
11
+ export declare function resolveConfig(opts: ResolveOptions): Promise<ResolvedConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findConfigFile = findConfigFile;
7
+ exports.loadConfigFile = loadConfigFile;
8
+ exports.saveJsonConfig = saveJsonConfig;
9
+ exports.resolveConfig = resolveConfig;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const chalk_1 = __importDefault(require("chalk"));
13
+ const jiti_1 = require("jiti");
14
+ const editors_1 = require("./editors");
15
+ const prompt_1 = require("./prompt");
16
+ const CONFIG_FILENAMES = [
17
+ 'scripting.config.ts',
18
+ 'scripting.config.mts',
19
+ 'scripting.config.cts',
20
+ 'scripting.config.js',
21
+ 'scripting.config.mjs',
22
+ 'scripting.config.cjs',
23
+ 'scripting.config.json',
24
+ ];
25
+ const DEFAULTS = {
26
+ editor: 'none',
27
+ editorArgs: [],
28
+ port: 3000,
29
+ autoOpen: true,
30
+ generateTsConfig: true,
31
+ logLevel: 'info',
32
+ };
33
+ function findConfigFile(cwd = process.cwd()) {
34
+ for (const name of CONFIG_FILENAMES) {
35
+ const p = path_1.default.join(cwd, name);
36
+ if (fs_1.default.existsSync(p))
37
+ return p;
38
+ }
39
+ return null;
40
+ }
41
+ async function loadConfigFile(filePath) {
42
+ if (filePath.endsWith('.json')) {
43
+ const raw = fs_1.default.readFileSync(filePath, 'utf-8');
44
+ try {
45
+ return JSON.parse(raw);
46
+ }
47
+ catch (e) {
48
+ console.log(chalk_1.default.red(`[config] Failed to parse ${path_1.default.basename(filePath)}: ${e}`));
49
+ return {};
50
+ }
51
+ }
52
+ try {
53
+ const jiti = (0, jiti_1.createJiti)(__filename, { interopDefault: true });
54
+ const mod = await jiti.import(filePath, { default: true });
55
+ if (mod && typeof mod === 'object') {
56
+ // jiti returns the default export directly when interopDefault is true
57
+ return mod;
58
+ }
59
+ return {};
60
+ }
61
+ catch (e) {
62
+ console.log(chalk_1.default.red(`[config] Failed to load ${path_1.default.basename(filePath)}: ${e}`));
63
+ return {};
64
+ }
65
+ }
66
+ function saveJsonConfig(config, cwd = process.cwd()) {
67
+ const filePath = path_1.default.join(cwd, 'scripting.config.json');
68
+ fs_1.default.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
69
+ console.log(chalk_1.default.green(`scripting.config.json created.`));
70
+ return filePath;
71
+ }
72
+ function mergeConfig(base, override) {
73
+ return {
74
+ editor: override.editor ?? base.editor,
75
+ editorCommand: override.editorCommand ?? base.editorCommand,
76
+ editorArgs: override.editorArgs ?? base.editorArgs,
77
+ port: override.port ?? base.port,
78
+ autoOpen: override.autoOpen ?? base.autoOpen,
79
+ generateTsConfig: override.generateTsConfig ?? base.generateTsConfig,
80
+ logLevel: override.logLevel ?? base.logLevel,
81
+ };
82
+ }
83
+ function resolveDefaults(config) {
84
+ return {
85
+ editor: config.editor ?? DEFAULTS.editor,
86
+ editorCommand: config.editorCommand,
87
+ editorArgs: config.editorArgs ?? DEFAULTS.editorArgs,
88
+ port: config.port ?? DEFAULTS.port,
89
+ autoOpen: config.autoOpen ?? DEFAULTS.autoOpen,
90
+ generateTsConfig: config.generateTsConfig ?? DEFAULTS.generateTsConfig,
91
+ logLevel: config.logLevel ?? DEFAULTS.logLevel,
92
+ };
93
+ }
94
+ async function resolveConfig(opts) {
95
+ const cwd = process.cwd();
96
+ const existing = findConfigFile(cwd);
97
+ let fileConfig = {};
98
+ if (existing && !opts.reconfigure) {
99
+ fileConfig = await loadConfigFile(existing);
100
+ console.log(chalk_1.default.gray(`Loaded config from ${path_1.default.basename(existing)}`));
101
+ }
102
+ // First-run or --reconfigure: ask the user.
103
+ // Skip the prompt when --editor is provided non-interactively, or when a config already specifies an editor.
104
+ const needPrompt = opts.reconfigure ||
105
+ (!fileConfig.editor && !opts.editorOverride);
106
+ if (needPrompt) {
107
+ const answers = await (0, prompt_1.promptForEditor)();
108
+ if (answers) {
109
+ fileConfig = { ...fileConfig, ...answers };
110
+ // Persist as JSON for npx-friendliness
111
+ saveJsonConfig(fileConfig, cwd);
112
+ }
113
+ }
114
+ const cliOverride = {};
115
+ if (opts.editorOverride)
116
+ cliOverride.editor = validateEditorKey(opts.editorOverride);
117
+ if (opts.port != null)
118
+ cliOverride.port = opts.port;
119
+ if (opts.noAutoOpen)
120
+ cliOverride.autoOpen = false;
121
+ const merged = mergeConfig(fileConfig, cliOverride);
122
+ return resolveDefaults(merged);
123
+ }
124
+ function validateEditorKey(value) {
125
+ const editor = (0, editors_1.getEditor)(value);
126
+ if (!editor) {
127
+ console.log(chalk_1.default.yellow(`[config] Unknown editor "${value}". Falling back to "none".`));
128
+ return 'none';
129
+ }
130
+ return editor.key;
131
+ }
@@ -0,0 +1,2 @@
1
+ export declare const globalDtsFileName = "global.d.ts";
2
+ export declare const scriptingDtsFileName = "scripting.d.ts";
@@ -0,0 +1,60 @@
1
+ import { FSWatcher } from 'chokidar';
2
+ import { Socket } from 'socket.io';
3
+ import { globalDtsFileName, scriptingDtsFileName } from './const';
4
+ import { ResolvedConfig } from './types';
5
+ export declare class Controller {
6
+ private static instances;
7
+ static create(socket: Socket, config: ResolvedConfig): Controller;
8
+ static get(socketId: string): Controller | undefined;
9
+ watcher: FSWatcher | null;
10
+ scriptName: string | null;
11
+ socket: Socket | null;
12
+ config: ResolvedConfig;
13
+ constructor(socket: Socket, config: ResolvedConfig);
14
+ createWatcher(scriptName: string): void;
15
+ handleSyncScriptFromClient: (data: {
16
+ [globalDtsFileName]: string;
17
+ [scriptingDtsFileName]: string;
18
+ scriptName: string;
19
+ scriptFiles: Record<string, string>;
20
+ }, ack: (result: {
21
+ error?: string;
22
+ success?: boolean;
23
+ }) => void) => Promise<void>;
24
+ handleSyncScriptFromServer: (data: {
25
+ "global.d.ts": string;
26
+ "scripting.d.ts": string;
27
+ scriptName: string;
28
+ }, ack: (result: {
29
+ error?: string;
30
+ scriptFiles?: Record<string, {
31
+ hash: string;
32
+ content: string;
33
+ }>;
34
+ otherFiles?: string[];
35
+ }) => void) => Promise<void>;
36
+ handleLog: (data: {
37
+ scriptName: string;
38
+ content: string;
39
+ isError: boolean;
40
+ }) => void;
41
+ handleOpenFile: (data: {
42
+ scriptName: string;
43
+ relativePath: string;
44
+ }) => Promise<void>;
45
+ handleStopDebugScript: (data: string, ack: (result: boolean) => void) => void;
46
+ handleGetFileContent: (data: {
47
+ scriptName: string;
48
+ relativePath: string;
49
+ }, ack: (result: {
50
+ error?: string;
51
+ content?: string;
52
+ }) => void) => Promise<void>;
53
+ handleGetFilePath: (data: {
54
+ scriptName: string;
55
+ relativePath: string;
56
+ }, ack: (result: {
57
+ error?: string;
58
+ filePath?: string;
59
+ }) => void) => Promise<void>;
60
+ }
@@ -10,10 +10,11 @@ const fs_1 = __importDefault(require("fs"));
10
10
  const chalk_1 = __importDefault(require("chalk"));
11
11
  const path_1 = __importDefault(require("path"));
12
12
  const const_1 = require("./const");
13
+ const editors_1 = require("./editors");
13
14
  class Controller {
14
15
  static instances = new Map();
15
- static create(socket, noAutoOpen) {
16
- const ctrl = new Controller(socket, noAutoOpen);
16
+ static create(socket, config) {
17
+ const ctrl = new Controller(socket, config);
17
18
  Controller.instances.set(socket.id, ctrl);
18
19
  return ctrl;
19
20
  }
@@ -23,9 +24,9 @@ class Controller {
23
24
  watcher = null;
24
25
  scriptName = null;
25
26
  socket = null;
26
- noAutoOpen;
27
- constructor(socket, noAutoOpen) {
28
- this.noAutoOpen = noAutoOpen;
27
+ config;
28
+ constructor(socket, config) {
29
+ this.config = config;
29
30
  this.socket = socket;
30
31
  socket.emit("socketId", socket.id);
31
32
  // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
@@ -129,13 +130,13 @@ class Controller {
129
130
  ack({
130
131
  success: true,
131
132
  });
132
- if (!this.noAutoOpen) {
133
- // Open the entry file in VSCode after a delay
133
+ if (this.config.autoOpen) {
134
+ // Open the entry file in the configured editor after a delay
134
135
  // to ensure the response is sent. Because the open file command
135
136
  // may suspend the response and cause the client to not receive the ack.
136
137
  setTimeout(() => {
137
138
  const entryFilePath = path_1.default.join(scriptDir, "index.tsx");
138
- (0, util_1.tryOpenFileInVSCode)(entryFilePath);
139
+ (0, editors_1.openFileInEditor)(entryFilePath, this.config);
139
140
  }, 1000);
140
141
  }
141
142
  }
@@ -210,13 +211,13 @@ class Controller {
210
211
  otherFiles: otherFiles.length > 0 ? otherFiles : undefined,
211
212
  });
212
213
  this.createWatcher(data.scriptName);
213
- if (!this.noAutoOpen) {
214
- // Open the entry file in VSCode after a delay
214
+ if (this.config.autoOpen) {
215
+ // Open the entry file in the configured editor after a delay
215
216
  // to ensure the response is sent. Because the open file command
216
217
  // may suspend the response and cause the client to not receive the ack.
217
218
  setTimeout(() => {
218
219
  const entryFilePath = path_1.default.join(scriptDir, "index.tsx");
219
- (0, util_1.tryOpenFileInVSCode)(entryFilePath);
220
+ (0, editors_1.openFileInEditor)(entryFilePath, this.config);
220
221
  }, 1000);
221
222
  }
222
223
  }
@@ -237,8 +238,8 @@ class Controller {
237
238
  return;
238
239
  }
239
240
  const filePath = path_1.default.join((0, util_1.getScriptPath)(this.scriptName), data.relativePath);
240
- if (!this.noAutoOpen && fs_1.default.existsSync(filePath)) {
241
- (0, util_1.tryOpenFileInVSCode)(filePath);
241
+ if (this.config.autoOpen && fs_1.default.existsSync(filePath)) {
242
+ (0, editors_1.openFileInEditor)(filePath, this.config);
242
243
  }
243
244
  };
244
245
  handleStopDebugScript = (data, ack) => {
@@ -0,0 +1,18 @@
1
+ import { EditorDescriptor, EditorKey, ResolvedConfig } from './types';
2
+ export declare const EDITORS: EditorDescriptor[];
3
+ export declare function getEditor(key: EditorKey): EditorDescriptor | undefined;
4
+ /**
5
+ * Whether this editor should be marked as "detected" in the picker.
6
+ *
7
+ * Intentionally returns false for:
8
+ * - "custom" / "none": meta options, not real editors
9
+ * - terminal editors (vim/nvim/emacs): typically system-bundled on macOS/Linux,
10
+ * so detection is meaningless — listing them as detected would mislead users
11
+ * into thinking they're their primary editor.
12
+ *
13
+ * GUI editors are detected via PATH command first, then macOS app bundle as fallback.
14
+ */
15
+ export declare function isEditorAvailable(editor: EditorDescriptor): boolean;
16
+ export declare function detectAvailableEditors(): Set<EditorKey>;
17
+ export declare function openFileInEditor(filePath: string, config: ResolvedConfig): void;
18
+ export declare function writeEditorSettings(config: ResolvedConfig): void;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EDITORS = void 0;
7
+ exports.getEditor = getEditor;
8
+ exports.isEditorAvailable = isEditorAvailable;
9
+ exports.detectAvailableEditors = detectAvailableEditors;
10
+ exports.openFileInEditor = openFileInEditor;
11
+ exports.writeEditorSettings = writeEditorSettings;
12
+ const child_process_1 = __importDefault(require("child_process"));
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const os_1 = __importDefault(require("os"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const chalk_1 = __importDefault(require("chalk"));
17
+ const util_1 = require("./util");
18
+ exports.EDITORS = [
19
+ { key: 'vscode', displayName: 'Visual Studio Code', command: 'code', macAppName: 'Visual Studio Code.app', settingsTarget: 'vscode' },
20
+ { key: 'vscode-insiders', displayName: 'VSCode Insiders', command: 'code-insiders', macAppName: 'Visual Studio Code - Insiders.app', settingsTarget: 'vscode' },
21
+ { key: 'vscodium', displayName: 'VSCodium', command: 'codium', macAppName: 'VSCodium.app', settingsTarget: 'vscode' },
22
+ { key: 'cursor', displayName: 'Cursor', command: 'cursor', macAppName: 'Cursor.app', settingsTarget: 'vscode' },
23
+ { key: 'windsurf', displayName: 'Windsurf', command: 'windsurf', macAppName: 'Windsurf.app', settingsTarget: 'vscode' },
24
+ { key: 'trae', displayName: 'Trae', command: 'trae', macAppName: 'Trae.app', settingsTarget: 'vscode' },
25
+ { key: 'zed', displayName: 'Zed', command: 'zed', macAppName: 'Zed.app', settingsTarget: 'zed' },
26
+ { key: 'webstorm', displayName: 'WebStorm', command: 'webstorm', macAppName: 'WebStorm.app', settingsTarget: 'idea' },
27
+ { key: 'idea', displayName: 'IntelliJ IDEA', command: 'idea', macAppName: 'IntelliJ IDEA.app', settingsTarget: 'idea' },
28
+ { key: 'fleet', displayName: 'Fleet', command: 'fleet', macAppName: 'Fleet.app', settingsTarget: null },
29
+ { key: 'sublime', displayName: 'Sublime Text', command: 'subl', macAppName: 'Sublime Text.app', settingsTarget: null },
30
+ { key: 'nova', displayName: 'Nova', command: 'nova', macAppName: 'Nova.app', settingsTarget: null },
31
+ { key: 'vim', displayName: 'Vim (terminal)', command: 'vim', settingsTarget: null, terminalApp: true },
32
+ { key: 'nvim', displayName: 'Neovim (terminal)', command: 'nvim', settingsTarget: null, terminalApp: true },
33
+ { key: 'emacs', displayName: 'Emacs', command: 'emacs', settingsTarget: null, terminalApp: true },
34
+ { key: 'custom', displayName: 'Custom command', command: null, settingsTarget: null },
35
+ { key: 'none', displayName: 'Do not open files', command: null, settingsTarget: null },
36
+ ];
37
+ function getEditor(key) {
38
+ return exports.EDITORS.find(e => e.key === key);
39
+ }
40
+ const detectionCache = new Map();
41
+ function commandExists(command) {
42
+ if (detectionCache.has(command)) {
43
+ return detectionCache.get(command);
44
+ }
45
+ const isWin = os_1.default.platform() === 'win32';
46
+ const probe = isWin ? `where ${command}` : `command -v ${command}`;
47
+ try {
48
+ child_process_1.default.execSync(probe, { stdio: 'ignore', shell: isWin ? undefined : process.env.SHELL });
49
+ detectionCache.set(command, true);
50
+ return true;
51
+ }
52
+ catch {
53
+ detectionCache.set(command, false);
54
+ return false;
55
+ }
56
+ }
57
+ function macAppExists(appName) {
58
+ const candidates = [
59
+ path_1.default.join('/Applications', appName),
60
+ path_1.default.join(os_1.default.homedir(), 'Applications', appName),
61
+ ];
62
+ return candidates.some(p => fs_1.default.existsSync(p));
63
+ }
64
+ /**
65
+ * Whether this editor should be marked as "detected" in the picker.
66
+ *
67
+ * Intentionally returns false for:
68
+ * - "custom" / "none": meta options, not real editors
69
+ * - terminal editors (vim/nvim/emacs): typically system-bundled on macOS/Linux,
70
+ * so detection is meaningless — listing them as detected would mislead users
71
+ * into thinking they're their primary editor.
72
+ *
73
+ * GUI editors are detected via PATH command first, then macOS app bundle as fallback.
74
+ */
75
+ function isEditorAvailable(editor) {
76
+ if (editor.key === 'custom' || editor.key === 'none')
77
+ return false;
78
+ if (editor.terminalApp)
79
+ return false;
80
+ if (editor.command && commandExists(editor.command))
81
+ return true;
82
+ if (os_1.default.platform() === 'darwin' && editor.macAppName && macAppExists(editor.macAppName))
83
+ return true;
84
+ return false;
85
+ }
86
+ function detectAvailableEditors() {
87
+ const set = new Set();
88
+ for (const e of exports.EDITORS) {
89
+ if (isEditorAvailable(e))
90
+ set.add(e.key);
91
+ }
92
+ return set;
93
+ }
94
+ function openFileInEditor(filePath, config) {
95
+ const editor = getEditor(config.editor);
96
+ if (!editor || editor.key === 'none')
97
+ return;
98
+ const command = config.editorCommand ?? editor.command;
99
+ const args = config.editorArgs ?? [];
100
+ if (!command) {
101
+ if (editor.key === 'custom') {
102
+ console.log(chalk_1.default.yellow(`[editor] "custom" requires editorCommand to be set in scripting.config.*`));
103
+ }
104
+ return;
105
+ }
106
+ if (editor.terminalApp) {
107
+ // Don't hijack the server TTY with a terminal editor
108
+ console.log(chalk_1.default.gray(`[editor] Skipping auto-open for terminal editor "${editor.displayName}". File: ${filePath}`));
109
+ return;
110
+ }
111
+ try {
112
+ const platform = os_1.default.platform();
113
+ if (platform === 'win32') {
114
+ child_process_1.default.spawn('cmd.exe', ['/c', command, ...args, filePath], { stdio: 'ignore', detached: true }).unref();
115
+ return;
116
+ }
117
+ // Try the CLI command first
118
+ if (commandExists(command)) {
119
+ child_process_1.default.spawn(command, [...args, filePath], { stdio: 'ignore', detached: true }).unref();
120
+ return;
121
+ }
122
+ // macOS fallback: open -a "App Name"
123
+ if (platform === 'darwin' && editor.macAppName) {
124
+ child_process_1.default.spawn('open', ['-a', editor.macAppName, filePath], { stdio: 'ignore', detached: true }).unref();
125
+ return;
126
+ }
127
+ console.log(chalk_1.default.yellow(`[editor] Command "${command}" not found in PATH. Cannot open ${filePath}.`));
128
+ }
129
+ catch (err) {
130
+ console.log(chalk_1.default.red(`[editor] Failed to open file: ${err}`));
131
+ }
132
+ }
133
+ const VSCODE_SETTINGS = `{
134
+ "typescript.format.semicolons": "remove",
135
+ "typescript.preferences.jsxAttributeCompletionStyle": "braces"
136
+ }`;
137
+ const ZED_SETTINGS = `{
138
+ "languages": {
139
+ "TypeScript": {
140
+ "format_on_save": "on"
141
+ },
142
+ "TSX": {
143
+ "format_on_save": "on"
144
+ }
145
+ }
146
+ }`;
147
+ function writeEditorSettings(config) {
148
+ const editor = getEditor(config.editor);
149
+ if (!editor || !editor.settingsTarget)
150
+ return;
151
+ if (editor.settingsTarget === 'vscode') {
152
+ writeIfAbsent('.vscode/settings.json', VSCODE_SETTINGS);
153
+ }
154
+ else if (editor.settingsTarget === 'zed') {
155
+ writeIfAbsent('.zed/settings.json', ZED_SETTINGS);
156
+ }
157
+ else if (editor.settingsTarget === 'idea') {
158
+ // JetBrains projects need full .idea/ structure (IDE generates it on first open).
159
+ // We intentionally don't seed it here.
160
+ }
161
+ }
162
+ function writeIfAbsent(relative, content) {
163
+ const filePath = (0, util_1.getPath)(relative);
164
+ (0, util_1.ensureDirectoryExistence)(filePath);
165
+ if (!fs_1.default.existsSync(filePath)) {
166
+ fs_1.default.writeFileSync(filePath, content);
167
+ console.log(chalk_1.default.green(`${relative} created.`));
168
+ }
169
+ else {
170
+ console.log(chalk_1.default.gray(`${relative} already exists.`));
171
+ }
172
+ }