@nexiq/cli 1.0.1 → 1.0.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.
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Utilities for managing the nexiq backend server process:
3
+ * - Resolving the server binary path
4
+ * - Starting / stopping the server (foreground or detached)
5
+ * - Querying health via WebSocket ping
6
+ * - Cache inspection / clearing
7
+ */
8
+
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import os from "node:os";
12
+ import { spawn, execSync } from "node:child_process";
13
+ import { createRequire } from "node:module";
14
+ import { WebSocket } from "ws";
15
+ import net from "node:net";
16
+
17
+ export const BACKEND_PORT = 3030;
18
+
19
+ // ~/.nexiq/ is the global cache root used by the server
20
+ const GLOBAL_NEXIQ_DIR = path.join(os.homedir(), ".nexiq");
21
+ const PID_FILE = path.join(GLOBAL_NEXIQ_DIR, "server.pid");
22
+ const LOG_FILE = path.join(GLOBAL_NEXIQ_DIR, "server.log");
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Server binary resolution
26
+ // ---------------------------------------------------------------------------
27
+
28
+ /**
29
+ * Resolve the path to the compiled server `index.js`.
30
+ */
31
+ export function resolveServerDist(): string | null {
32
+ // 1. Env override
33
+ if (process.env.REACT_MAP_SERVER_PATH) {
34
+ return process.env.REACT_MAP_SERVER_PATH;
35
+ }
36
+
37
+ // 2. Monorepo sibling path
38
+ // We try multiple ways to get the current file directory
39
+ let currentDir = "";
40
+ try {
41
+ currentDir = path.dirname(new URL(import.meta.url).pathname);
42
+ } catch {
43
+ // @ts-ignore
44
+ currentDir = typeof __dirname !== "undefined" ? __dirname : process.cwd();
45
+ }
46
+
47
+ const siblingPath = path.resolve(
48
+ currentDir,
49
+ "../../..", // dist/cli.js -> dist -> nexiq-cli -> packages -> nexiq root
50
+ "server",
51
+ "dist",
52
+ "index.js",
53
+ );
54
+ if (fs.existsSync(siblingPath)) {
55
+ return siblingPath;
56
+ }
57
+
58
+ // 3. Resolve from installed @nexiq/server package
59
+ try {
60
+ const require = createRequire(import.meta.url || `file://${process.cwd()}/index.js`);
61
+ const resolved = require.resolve("@nexiq/server");
62
+ if (fs.existsSync(resolved)) return resolved;
63
+ } catch {
64
+ // not installed
65
+ }
66
+
67
+ return null;
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Port check
72
+ // ---------------------------------------------------------------------------
73
+
74
+ export async function isPortOpen(port: number, host = "127.0.0.1"): Promise<boolean> {
75
+ return new Promise((resolve) => {
76
+ const socket = new net.Socket();
77
+ const onError = () => {
78
+ socket.destroy();
79
+ resolve(false);
80
+ };
81
+ socket.setTimeout(400);
82
+ socket.once("error", onError);
83
+ socket.once("timeout", onError);
84
+ socket.connect(port, host, () => {
85
+ socket.destroy();
86
+ resolve(true);
87
+ });
88
+ });
89
+ }
90
+
91
+ export async function isServerAlive(port: number = BACKEND_PORT): Promise<boolean> {
92
+ return new Promise((resolve) => {
93
+ const ws = new WebSocket(`ws://localhost:${port}`);
94
+ const timeout = setTimeout(() => {
95
+ ws.terminate();
96
+ resolve(false);
97
+ }, 600);
98
+
99
+ ws.on("open", () => {
100
+ clearTimeout(timeout);
101
+ ws.terminate();
102
+ resolve(true);
103
+ });
104
+
105
+ ws.on("error", () => {
106
+ clearTimeout(timeout);
107
+ resolve(false);
108
+ });
109
+ });
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // PID file helpers
114
+ // ---------------------------------------------------------------------------
115
+
116
+ function ensureNexiqDir() {
117
+ if (!fs.existsSync(GLOBAL_NEXIQ_DIR)) {
118
+ fs.mkdirSync(GLOBAL_NEXIQ_DIR, { recursive: true });
119
+ }
120
+ }
121
+
122
+ function writePid(pid: number) {
123
+ ensureNexiqDir();
124
+ fs.writeFileSync(PID_FILE, `${pid}\n`, "utf8");
125
+ }
126
+
127
+ function readPid(): number | null {
128
+ if (!fs.existsSync(PID_FILE)) return null;
129
+ const raw = fs.readFileSync(PID_FILE, "utf8").trim();
130
+ const pid = parseInt(raw, 10);
131
+ return isNaN(pid) ? null : pid;
132
+ }
133
+
134
+ function clearPid() {
135
+ if (fs.existsSync(PID_FILE)) {
136
+ fs.unlinkSync(PID_FILE);
137
+ }
138
+ }
139
+
140
+ function isPidAlive(pid: number): boolean {
141
+ try {
142
+ // Signal 0 = check existence without sending a real signal
143
+ process.kill(pid, 0);
144
+ return true;
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+
150
+ function pidFileModifiedAt(): Date | null {
151
+ if (!fs.existsSync(PID_FILE)) return null;
152
+ return fs.statSync(PID_FILE).mtime;
153
+ }
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // Start / Stop
157
+ // ---------------------------------------------------------------------------
158
+
159
+ export interface StartResult {
160
+ ok: boolean;
161
+ pid?: number;
162
+ port?: number;
163
+ alreadyRunning?: boolean;
164
+ error?: string;
165
+ }
166
+
167
+ /**
168
+ * Start the server in the foreground (no detach).
169
+ * The process stays alive as long as the CLI is running.
170
+ * Callers that want daemon mode should use startDetached().
171
+ */
172
+ export async function startServerForeground(port: number = BACKEND_PORT): Promise<never> {
173
+ const serverDist = resolveServerDist();
174
+ if (!serverDist) {
175
+ console.error("Could not find the nexiq server. Please build it first (pnpm build).");
176
+ process.exit(1);
177
+ }
178
+
179
+ const child = spawn("node", [serverDist], {
180
+ stdio: ["inherit", "inherit", "inherit", "ipc"],
181
+ env: { ...process.env, PORT: String(port), NODE_ENV: "production" },
182
+ });
183
+
184
+ child.on("error", (err) => {
185
+ console.error("Server failed to start:", err.message);
186
+ process.exit(1);
187
+ });
188
+
189
+ await new Promise<void>((_, reject) =>
190
+ child.on("exit", (code) => reject(new Error(`Server exited with code ${code}`))),
191
+ );
192
+
193
+ process.exit(0);
194
+ }
195
+
196
+ /**
197
+ * Start the server detached (daemon mode) — writes PID file.
198
+ */
199
+ export async function startServerDetached(port: number = BACKEND_PORT): Promise<StartResult> {
200
+ // Already alive?
201
+ if (await isServerAlive(port)) {
202
+ const pid = readPid();
203
+ return { ok: true, alreadyRunning: true, pid: pid ?? undefined, port };
204
+ }
205
+
206
+ const serverDist = resolveServerDist();
207
+ if (!serverDist) {
208
+ return { ok: false, error: "Could not find the nexiq server binary. Run `pnpm build` in packages/server first." };
209
+ }
210
+
211
+ ensureNexiqDir();
212
+
213
+ const logStream = fs.openSync(LOG_FILE, "a");
214
+
215
+ const child = spawn("node", [serverDist], {
216
+ detached: true,
217
+ stdio: ["ignore", logStream, logStream, "ipc"],
218
+ env: { ...process.env, PORT: String(port), NODE_ENV: "production" },
219
+ });
220
+
221
+ const pid = child.pid;
222
+ if (!pid) {
223
+ return { ok: false, error: "Failed to get PID from spawned process" };
224
+ }
225
+
226
+ child.unref();
227
+ writePid(pid);
228
+
229
+ // Wait up to 4s for the server to be reachable
230
+ const start = Date.now();
231
+ while (Date.now() - start < 4000) {
232
+ await sleep(300);
233
+ if (await isServerAlive(port)) {
234
+ return { ok: true, pid, port };
235
+ }
236
+ }
237
+
238
+ // Server didn't come up — clean up
239
+ clearPid();
240
+ return { ok: false, error: "Server started but did not become reachable within 4s. Check ~/.nexiq/server.log" };
241
+ }
242
+
243
+ export interface StopResult {
244
+ ok: boolean;
245
+ message: string;
246
+ }
247
+
248
+ export async function stopServer(): Promise<StopResult> {
249
+ const pid = readPid();
250
+
251
+ if (!pid) {
252
+ // Check if something is on the port even without a PID file
253
+ if (await isServerAlive()) {
254
+ return { ok: false, message: "Server appears to be running but no PID file found. Stop it manually." };
255
+ }
256
+ return { ok: true, message: "Server is not running." };
257
+ }
258
+
259
+ if (!isPidAlive(pid)) {
260
+ clearPid();
261
+ return { ok: true, message: `Server (PID ${pid}) was already stopped. Cleaned up PID file.` };
262
+ }
263
+
264
+ try {
265
+ process.kill(pid, "SIGTERM");
266
+ // Wait up to 3s for it to die
267
+ const start = Date.now();
268
+ while (Date.now() - start < 3000) {
269
+ await sleep(200);
270
+ if (!isPidAlive(pid)) break;
271
+ }
272
+ clearPid();
273
+ return { ok: true, message: `Server (PID ${pid}) stopped.` };
274
+ } catch (err) {
275
+ return { ok: false, message: `Failed to stop server: ${err instanceof Error ? err.message : String(err)}` };
276
+ }
277
+ }
278
+
279
+ export interface ServerStatus {
280
+ running: boolean;
281
+ pid?: number;
282
+ port?: number;
283
+ uptimeMs?: number;
284
+ serverDist: string | null;
285
+ logFile: string;
286
+ }
287
+
288
+ export async function getServerStatus(port: number = BACKEND_PORT): Promise<ServerStatus> {
289
+ const pid = readPid();
290
+ const alive = await isServerAlive(port);
291
+ const startedAt = pidFileModifiedAt();
292
+
293
+ return {
294
+ running: alive,
295
+ pid: pid ?? undefined,
296
+ port: alive ? port : undefined,
297
+ uptimeMs: alive && startedAt ? Date.now() - startedAt.getTime() : undefined,
298
+ serverDist: resolveServerDist(),
299
+ logFile: LOG_FILE,
300
+ };
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Cache inspection
305
+ // ---------------------------------------------------------------------------
306
+
307
+ export interface CacheEntry {
308
+ /** Project path (dir name inside ~/.nexiq/<hash>/<projectPath>) */
309
+ label: string;
310
+ /** Absolute path to the cache dir */
311
+ cachePath: string;
312
+ /** Total size in bytes */
313
+ sizeBytes: number;
314
+ /** Last modified time */
315
+ lastModified: Date;
316
+ }
317
+
318
+ function dirSizeBytes(dirPath: string): number {
319
+ let total = 0;
320
+ try {
321
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
322
+ for (const entry of entries) {
323
+ const full = path.join(dirPath, entry.name);
324
+ if (entry.isDirectory()) {
325
+ total += dirSizeBytes(full);
326
+ } else {
327
+ try {
328
+ total += fs.statSync(full).size;
329
+ } catch {
330
+ // ignore
331
+ }
332
+ }
333
+ }
334
+ } catch {
335
+ // ignore unreadable dirs
336
+ }
337
+ return total;
338
+ }
339
+
340
+ export function getCacheEntries(): CacheEntry[] {
341
+ if (!fs.existsSync(GLOBAL_NEXIQ_DIR)) return [];
342
+
343
+ const entries: CacheEntry[] = [];
344
+
345
+ // The server stores project caches directly in ~/.nexiq/<encoded-project-path>/
346
+ const items = fs.readdirSync(GLOBAL_NEXIQ_DIR, { withFileTypes: true });
347
+ for (const item of items) {
348
+ if (!item.isDirectory()) continue;
349
+ const fullPath = path.join(GLOBAL_NEXIQ_DIR, item.name);
350
+ const stat = fs.statSync(fullPath);
351
+ const sizeBytes = dirSizeBytes(fullPath);
352
+ entries.push({
353
+ label: decodeURIComponent(item.name.replace(/_/g, "/")),
354
+ cachePath: fullPath,
355
+ sizeBytes,
356
+ lastModified: stat.mtime,
357
+ });
358
+ }
359
+
360
+ return entries.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
361
+ }
362
+
363
+ export function clearCacheEntries(entries: CacheEntry[]): void {
364
+ for (const entry of entries) {
365
+ fs.rmSync(entry.cachePath, { recursive: true, force: true });
366
+ }
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // Helpers
371
+ // ---------------------------------------------------------------------------
372
+
373
+ function sleep(ms: number) {
374
+ return new Promise((r) => setTimeout(r, ms));
375
+ }
376
+
377
+ export function formatBytes(bytes: number): string {
378
+ if (bytes < 1024) return `${bytes} B`;
379
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
380
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
381
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
382
+ }
383
+
384
+ export function formatDuration(ms: number): string {
385
+ if (ms < 1000) return `${ms}ms`;
386
+ const s = Math.floor(ms / 1000);
387
+ if (s < 60) return `${s}s`;
388
+ const m = Math.floor(s / 60);
389
+ if (m < 60) return `${m}m ${s % 60}s`;
390
+ const h = Math.floor(m / 60);
391
+ return `${h}h ${m % 60}m`;
392
+ }
package/tsconfig.json CHANGED
@@ -3,21 +3,14 @@
3
3
  "target": "ESNext",
4
4
  "module": "NodeNext",
5
5
  "moduleResolution": "NodeNext",
6
+ "jsx": "react-jsx",
6
7
  "declaration": true,
7
8
  "outDir": "dist",
9
+ "rootDir": "src",
8
10
  "strict": true,
9
11
  "esModuleInterop": true,
10
12
  "skipLibCheck": true,
11
- "forceConsistentCasingInFileNames": true,
12
- "baseUrl": ".",
13
- "paths": {
14
- "@nexiq/analyser": ["../analyser/src/index.ts"],
15
- "@nexiq/analyser/*": ["../analyser/src/*"],
16
- "@nexiq/shared": ["../shared/src/index.ts"],
17
- "@nexiq/shared/db": ["../shared/src/db/index.ts"],
18
- "@nexiq/shared/*": ["../shared/src/*"],
19
- "@nexiq/extension-sdk": ["../extension-sdk/src/index.ts"],
20
- "@nexiq/extension-sdk/*": ["../extension-sdk/src/*"]
21
- }
22
- }
23
- }
13
+ "forceConsistentCasingInFileNames": true
14
+ },
15
+ "include": ["src"]
16
+ }
package/tsup.config.ts CHANGED
@@ -1,8 +1,45 @@
1
1
  import { defineConfig } from "tsup";
2
2
 
3
3
  export default defineConfig({
4
- entry: ["src/index.ts"],
4
+ entry: ["src/cli.tsx"],
5
5
  format: ["esm"],
6
- dts: false,
6
+ target: "node18",
7
7
  clean: true,
8
+ dts: false,
9
+ banner: {
10
+ js: `#!/usr/bin/env node
11
+ import { createRequire as __createRequire } from 'node:module';
12
+ const require = __createRequire(import.meta.url);
13
+ `,
14
+ },
15
+ // Bundle only the ones that cause version conflicts or need to be standalone
16
+ noExternal: [
17
+ "ink",
18
+ "ink-spinner",
19
+ "react",
20
+ "react-dom",
21
+ "react-reconciler",
22
+ "meow",
23
+ "signal-exit"
24
+ ],
25
+ // Exclude node built-ins and problematic native/peer deps
26
+ external: [
27
+ "ws",
28
+ "react-devtools-core",
29
+ "yoga-layout",
30
+ "yoga-wasm-web",
31
+ "assert",
32
+ "buffer",
33
+ "child_process",
34
+ "crypto",
35
+ "events",
36
+ "fs",
37
+ "module",
38
+ "net",
39
+ "os",
40
+ "path",
41
+ "stream",
42
+ "url",
43
+ "util"
44
+ ],
8
45
  });