@rasyid2567/urlscanner 0.1.0 → 1.0.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/dist/cli.js CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawn as spawn2 } from "child_process";
5
- import fs3 from "fs";
6
- import os from "os";
7
- import path3 from "path";
5
+ import fs4 from "fs";
6
+ import os2 from "os";
7
+ import path4 from "path";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // src/config.ts
11
- var APP_VERSION = "0.1.0";
11
+ var APP_VERSION = "1.0.0";
12
12
  var DEFAULT_PORT = 3847;
13
13
  var DEFAULT_HOST = "127.0.0.1";
14
14
  var CHROME_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36";
@@ -2376,7 +2376,7 @@ var TrustPositifService = class {
2376
2376
  try {
2377
2377
  const resp = await fetchFn(sourceUrl, {
2378
2378
  signal: controller.signal,
2379
- headers: { "User-Agent": "URLScanner/0.1.0" }
2379
+ headers: { "User-Agent": `URLScanner/${APP_VERSION}` }
2380
2380
  });
2381
2381
  if (!resp.ok) {
2382
2382
  throw new Error(`TrustPositif sync HTTP ${resp.status}`);
@@ -2510,13 +2510,40 @@ function startHttpServer(app, host, port) {
2510
2510
  });
2511
2511
  }
2512
2512
 
2513
+ // src/tui/browser.ts
2514
+ import { spawn } from "child_process";
2515
+ function openBrowser(url) {
2516
+ try {
2517
+ const platform = process.platform;
2518
+ let cmd = "xdg-open";
2519
+ let args = [url];
2520
+ if (platform === "darwin") {
2521
+ cmd = "open";
2522
+ args = [url];
2523
+ } else if (platform === "win32") {
2524
+ cmd = "cmd";
2525
+ args = ["/c", "start", "", url];
2526
+ }
2527
+ const child = spawn(cmd, args, {
2528
+ detached: true,
2529
+ stdio: "ignore",
2530
+ windowsHide: true
2531
+ });
2532
+ child.unref();
2533
+ return true;
2534
+ } catch {
2535
+ return false;
2536
+ }
2537
+ }
2538
+
2513
2539
  // src/tui/ansi.ts
2514
2540
  var ANSI = {
2515
2541
  reset: "\x1B[0m",
2516
2542
  bold: "\x1B[1m",
2517
2543
  dim: "\x1B[2m",
2518
2544
  amber: "\x1B[38;5;209m",
2519
- green: "\x1B[38;5;71m",
2545
+ brand: "\x1B[38;5;43m",
2546
+ green: "\x1B[38;5;78m",
2520
2547
  cyan: "\x1B[38;5;37m",
2521
2548
  red: "\x1B[38;5;203m",
2522
2549
  yellow: "\x1B[38;5;221m",
@@ -2536,31 +2563,6 @@ function padStart(str, width) {
2536
2563
  return " ".repeat(width - str.length) + str;
2537
2564
  }
2538
2565
 
2539
- // src/tui/browser.ts
2540
- import { spawn } from "child_process";
2541
- function openBrowser(url) {
2542
- try {
2543
- const platform = process.platform;
2544
- let cmd = "xdg-open";
2545
- let args = [url];
2546
- if (platform === "darwin") {
2547
- cmd = "open";
2548
- args = [url];
2549
- } else if (platform === "win32") {
2550
- cmd = "cmd";
2551
- args = ["/c", "start", "", url];
2552
- }
2553
- const child = spawn(cmd, args, {
2554
- detached: true,
2555
- stdio: "ignore"
2556
- });
2557
- child.unref();
2558
- return true;
2559
- } catch {
2560
- return false;
2561
- }
2562
- }
2563
-
2564
2566
  // src/tui/clipboard.ts
2565
2567
  import { spawnSync } from "child_process";
2566
2568
  function copyToClipboard(text) {
@@ -2610,7 +2612,7 @@ async function runInteractiveTui(url, ctx) {
2610
2612
  if (cursor < 0) cursor = 0;
2611
2613
  const lines = [];
2612
2614
  lines.push(
2613
- `${ANSI.amber}${ANSI.bold} URLScanner Terminal UI v${APP_VERSION}${ANSI.reset} ${ANSI.dim}\u2502${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`
2615
+ `${ANSI.brand}${ANSI.bold} URLScanner Terminal UI v${APP_VERSION}${ANSI.reset} ${ANSI.dim}\u2502${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`
2614
2616
  );
2615
2617
  lines.push(
2616
2618
  ` New: ${ANSI.bold}${counts.new_count}${ANSI.reset} In Progress: ${counts.claimed_count} Submitted: ${counts.submitted_count} Valid: ${counts.valid_count} CF Manual: ${counts.manual_count} Archive: ${counts.blocked_count + counts.parked_count + counts.dead_count}`
@@ -2841,23 +2843,27 @@ async function runInteractiveTui(url, ctx) {
2841
2843
  }
2842
2844
 
2843
2845
  // src/tui/launcher.ts
2844
- var MENU_ITEMS = [
2845
- { key: "web", label: "Web UI (Open in Browser)" },
2846
- { key: "tui", label: "Terminal UI (Interactive CLI)" },
2847
- { key: "daemon", label: "Run in Background (Daemon)" },
2848
- { key: "exit", label: "Exit" }
2849
- ];
2850
- function renderLauncherMenu(url, selectedIdx) {
2851
- const divider = `${ANSI.amber}============================================${ANSI.reset}`;
2846
+ function getMenuItems(_alreadyRunning = false) {
2847
+ return [
2848
+ { key: "web", label: "Web UI (Open in Browser)" },
2849
+ { key: "tui", label: "Terminal UI (Interactive CLI)" },
2850
+ { key: "daemon", label: "Hide to Tray (Background)" },
2851
+ { key: "exit", label: "Exit" }
2852
+ ];
2853
+ }
2854
+ function renderLauncherMenu(url, selectedIdx, alreadyRunning = false) {
2855
+ const divider = `${ANSI.brand}============================================${ANSI.reset}`;
2856
+ const items = getMenuItems(alreadyRunning);
2857
+ const statusSuffix = alreadyRunning ? ` ${ANSI.dim}(running in background)${ANSI.reset}` : "";
2852
2858
  const lines = [
2853
2859
  "",
2854
2860
  divider,
2855
- ` ${ANSI.amber}${ANSI.bold}Choose Interface (v${APP_VERSION})${ANSI.reset}`,
2856
- ` \u{1F680} ${ANSI.dim}Server:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
2861
+ ` ${ANSI.brand}${ANSI.bold}Choose Interface (v${APP_VERSION})${ANSI.reset}`,
2862
+ ` \u25CF ${ANSI.dim}Server:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}${statusSuffix}`,
2857
2863
  divider,
2858
2864
  ""
2859
2865
  ];
2860
- MENU_ITEMS.forEach((item, idx) => {
2866
+ items.forEach((item, idx) => {
2861
2867
  if (idx === selectedIdx) {
2862
2868
  lines.push(` ${ANSI.selectedBg} \u2605 ${item.label} ${ANSI.reset}`);
2863
2869
  } else {
@@ -2867,13 +2873,15 @@ function renderLauncherMenu(url, selectedIdx) {
2867
2873
  lines.push("", `${ANSI.dim} Use \u2191/\u2193 (or j/k) and Enter to select, Ctrl+C to quit${ANSI.reset}`, "");
2868
2874
  return lines.join("\n");
2869
2875
  }
2870
- async function runLauncherMenu(url) {
2876
+ async function runLauncherMenu(url, options) {
2871
2877
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
2872
2878
  return "web";
2873
2879
  }
2880
+ const alreadyRunning = Boolean(options?.alreadyRunning);
2881
+ const items = getMenuItems(alreadyRunning);
2874
2882
  let selected = 0;
2875
2883
  const draw = () => {
2876
- process.stdout.write(ANSI.clearScreen + renderLauncherMenu(url, selected));
2884
+ process.stdout.write(ANSI.clearScreen + renderLauncherMenu(url, selected, alreadyRunning));
2877
2885
  };
2878
2886
  return new Promise((resolve) => {
2879
2887
  const stdin = process.stdin;
@@ -2897,24 +2905,24 @@ async function runLauncherMenu(url) {
2897
2905
  }
2898
2906
  if (s === "\r" || s === "\n") {
2899
2907
  cleanup();
2900
- resolve(MENU_ITEMS[selected].key);
2908
+ resolve(items[selected].key);
2901
2909
  return;
2902
2910
  }
2903
2911
  if (s === "\x1B[A" || s === "k") {
2904
- selected = (selected - 1 + MENU_ITEMS.length) % MENU_ITEMS.length;
2912
+ selected = (selected - 1 + items.length) % items.length;
2905
2913
  draw();
2906
2914
  return;
2907
2915
  }
2908
2916
  if (s === "\x1B[B" || s === "j") {
2909
- selected = (selected + 1) % MENU_ITEMS.length;
2917
+ selected = (selected + 1) % items.length;
2910
2918
  draw();
2911
2919
  return;
2912
2920
  }
2913
- if (s >= "1" && s <= "4") {
2921
+ if (s >= "1" && s <= String(items.length)) {
2914
2922
  const idx = Number.parseInt(s, 10) - 1;
2915
2923
  selected = idx;
2916
2924
  cleanup();
2917
- resolve(MENU_ITEMS[selected].key);
2925
+ resolve(items[selected].key);
2918
2926
  }
2919
2927
  };
2920
2928
  stdin.on("data", onData);
@@ -2926,13 +2934,13 @@ async function runWebWaitingLoop(url, ctx, shouldOpen = true) {
2926
2934
  }
2927
2935
  const draw = () => {
2928
2936
  const counts = ctx.db.getQueueCounts();
2929
- const divider = `${ANSI.amber}============================================${ANSI.reset}`;
2937
+ const divider = `${ANSI.brand}============================================${ANSI.reset}`;
2930
2938
  process.stdout.write(
2931
2939
  ANSI.clearScreen + [
2932
2940
  "",
2933
2941
  divider,
2934
- ` ${ANSI.amber}${ANSI.bold}URLScanner Web UI Active (v${APP_VERSION})${ANSI.reset}`,
2935
- ` \u{1F680} ${ANSI.dim}URL:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
2942
+ ` ${ANSI.brand}${ANSI.bold}URLScanner Dashboard Active (v${APP_VERSION})${ANSI.reset}`,
2943
+ ` \u25CF ${ANSI.dim}URL:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
2936
2944
  divider,
2937
2945
  "",
2938
2946
  ` Ready Queue (New) : ${ANSI.bold}${counts.new_count}${ANSI.reset}`,
@@ -2979,9 +2987,312 @@ async function runWebWaitingLoop(url, ctx, shouldOpen = true) {
2979
2987
  });
2980
2988
  }
2981
2989
 
2990
+ // src/tui/tray.ts
2991
+ import fs3 from "fs";
2992
+ import { createRequire } from "module";
2993
+ import os from "os";
2994
+ import path3 from "path";
2995
+
2996
+ // src/tui/trayIcon.ts
2997
+ import { deflateSync } from "zlib";
2998
+ var CRC_TABLE = (() => {
2999
+ const table = new Uint32Array(256);
3000
+ for (let n = 0; n < 256; n++) {
3001
+ let c = n;
3002
+ for (let k = 0; k < 8; k++) {
3003
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
3004
+ }
3005
+ table[n] = c >>> 0;
3006
+ }
3007
+ return table;
3008
+ })();
3009
+ function crc32(buf) {
3010
+ let c = 4294967295;
3011
+ for (let i = 0; i < buf.length; i++) {
3012
+ c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
3013
+ }
3014
+ return (c ^ 4294967295) >>> 0;
3015
+ }
3016
+ function pngChunk(type, data) {
3017
+ const len = Buffer.alloc(4);
3018
+ len.writeUInt32BE(data.length, 0);
3019
+ const typeBuf = Buffer.from(type, "ascii");
3020
+ const crcBuf = Buffer.alloc(4);
3021
+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
3022
+ return Buffer.concat([len, typeBuf, data, crcBuf]);
3023
+ }
3024
+ function renderUrlScannerPixels(size) {
3025
+ const pixels = new Uint8Array(size * size * 4);
3026
+ const bg = [20, 36, 35, 255];
3027
+ const bgBorder = [20, 184, 166, 96];
3028
+ const teal = [20, 184, 166, 255];
3029
+ const white = [237, 237, 237, 235];
3030
+ const setPixel = (x, y, color) => {
3031
+ if (x < 0 || y < 0 || x >= size || y >= size) return;
3032
+ const idx = (y * size + x) * 4;
3033
+ pixels[idx] = color[0];
3034
+ pixels[idx + 1] = color[1];
3035
+ pixels[idx + 2] = color[2];
3036
+ pixels[idx + 3] = color[3];
3037
+ };
3038
+ const radius = size * 0.24;
3039
+ const cx = (size - 1) / 2;
3040
+ const cy = (size - 1) / 2;
3041
+ const half = size / 2 - 1;
3042
+ for (let y = 0; y < size; y++) {
3043
+ for (let x = 0; x < size; x++) {
3044
+ const dx = Math.max(Math.abs(x - cx) - (half - radius), 0);
3045
+ const dy = Math.max(Math.abs(y - cy) - (half - radius), 0);
3046
+ const dist = Math.hypot(dx, dy);
3047
+ if (dist <= radius) {
3048
+ if (dist >= radius - 1.2) {
3049
+ setPixel(x, y, bgBorder);
3050
+ } else {
3051
+ setPixel(x, y, bg);
3052
+ }
3053
+ }
3054
+ }
3055
+ }
3056
+ const s = (v) => v / 24 * size;
3057
+ const stroke = Math.max(1.5, size / 14);
3058
+ const drawRect = (x1, y1, x2, y2, color) => {
3059
+ const ix1 = Math.floor(s(x1));
3060
+ const iy1 = Math.floor(s(y1));
3061
+ const ix2 = Math.ceil(s(x2));
3062
+ const iy2 = Math.ceil(s(y2));
3063
+ for (let y = iy1; y <= iy2; y++) {
3064
+ for (let x = ix1; x <= ix2; x++) {
3065
+ setPixel(x, y, color);
3066
+ }
3067
+ }
3068
+ };
3069
+ const arm = 4.6;
3070
+ const t = 1.9;
3071
+ const pad = 4.2;
3072
+ drawRect(pad, pad, pad + arm, pad + t, teal);
3073
+ drawRect(pad, pad, pad + t, pad + arm, teal);
3074
+ drawRect(24 - pad - arm, pad, 24 - pad, pad + t, teal);
3075
+ drawRect(24 - pad - t, pad, 24 - pad, pad + arm, teal);
3076
+ drawRect(pad, 24 - pad - t, pad + arm, 24 - pad, teal);
3077
+ drawRect(pad, 24 - pad - arm, pad + t, 24 - pad, teal);
3078
+ drawRect(24 - pad - arm, 24 - pad - t, 24 - pad, 24 - pad, teal);
3079
+ drawRect(24 - pad - t, 24 - pad - arm, 24 - pad, 24 - pad, teal);
3080
+ const ringR = s(4.2);
3081
+ for (let y = 0; y < size; y++) {
3082
+ for (let x = 0; x < size; x++) {
3083
+ const dist = Math.hypot(x - cx, y - cy);
3084
+ if (Math.abs(dist - ringR) <= stroke * 0.48) {
3085
+ setPixel(x, y, white);
3086
+ }
3087
+ }
3088
+ }
3089
+ drawRect(5.2, 11.1, 18.8, 12.9, teal);
3090
+ const dotR = s(1.7);
3091
+ for (let y = 0; y < size; y++) {
3092
+ for (let x = 0; x < size; x++) {
3093
+ if (Math.hypot(x - cx, y - cy) <= dotR) {
3094
+ setPixel(x, y, teal);
3095
+ }
3096
+ }
3097
+ }
3098
+ return pixels;
3099
+ }
3100
+ function buildPngBase64(size = 64) {
3101
+ const rgba = renderUrlScannerPixels(size);
3102
+ const stride = size * 4;
3103
+ const raw = Buffer.alloc((stride + 1) * size);
3104
+ for (let y = 0; y < size; y++) {
3105
+ const rowStart = y * (stride + 1);
3106
+ raw[rowStart] = 0;
3107
+ Buffer.from(rgba.buffer, y * stride, stride).copy(raw, rowStart + 1);
3108
+ }
3109
+ const ihdr = Buffer.alloc(13);
3110
+ ihdr.writeUInt32BE(size, 0);
3111
+ ihdr.writeUInt32BE(size, 4);
3112
+ ihdr[8] = 8;
3113
+ ihdr[9] = 6;
3114
+ ihdr[10] = 0;
3115
+ ihdr[11] = 0;
3116
+ ihdr[12] = 0;
3117
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
3118
+ const compressed = deflateSync(raw);
3119
+ return Buffer.concat([
3120
+ signature,
3121
+ pngChunk("IHDR", ihdr),
3122
+ pngChunk("IDAT", compressed),
3123
+ pngChunk("IEND", Buffer.alloc(0))
3124
+ ]).toString("base64");
3125
+ }
3126
+ function buildIcoBase64(size = 32) {
3127
+ const rgba = renderUrlScannerPixels(size);
3128
+ const pixelBytes = size * size * 4;
3129
+ const andMaskRowBytes = Math.ceil(size / 32) * 4;
3130
+ const andMaskBytes = andMaskRowBytes * size;
3131
+ const imageSize = 40 + pixelBytes + andMaskBytes;
3132
+ const out = Buffer.alloc(6 + 16 + imageSize);
3133
+ out.writeUInt16LE(0, 0);
3134
+ out.writeUInt16LE(1, 2);
3135
+ out.writeUInt16LE(1, 4);
3136
+ out[6] = size === 256 ? 0 : size;
3137
+ out[7] = size === 256 ? 0 : size;
3138
+ out[8] = 0;
3139
+ out[9] = 0;
3140
+ out.writeUInt16LE(1, 10);
3141
+ out.writeUInt16LE(32, 12);
3142
+ out.writeUInt32LE(imageSize, 14);
3143
+ out.writeUInt32LE(22, 18);
3144
+ const bmpOffset = 22;
3145
+ out.writeUInt32LE(40, bmpOffset);
3146
+ out.writeInt32LE(size, bmpOffset + 4);
3147
+ out.writeInt32LE(size * 2, bmpOffset + 8);
3148
+ out.writeUInt16LE(1, bmpOffset + 12);
3149
+ out.writeUInt16LE(32, bmpOffset + 14);
3150
+ out.writeUInt32LE(0, bmpOffset + 16);
3151
+ out.writeUInt32LE(pixelBytes + andMaskBytes, bmpOffset + 20);
3152
+ let dst = bmpOffset + 40;
3153
+ for (let y = size - 1; y >= 0; y--) {
3154
+ for (let x = 0; x < size; x++) {
3155
+ const src = (y * size + x) * 4;
3156
+ out[dst++] = rgba[src + 2];
3157
+ out[dst++] = rgba[src + 1];
3158
+ out[dst++] = rgba[src];
3159
+ out[dst++] = rgba[src + 3];
3160
+ }
3161
+ }
3162
+ return out.toString("base64");
3163
+ }
3164
+ var TRAY_ICON_PNG_BASE64 = buildPngBase64(64);
3165
+ var TRAY_ICON_ICO_BASE64 = buildIcoBase64(32);
3166
+ function getTrayIconForPlatform(platform = process.platform) {
3167
+ return platform === "win32" ? TRAY_ICON_ICO_BASE64 : TRAY_ICON_PNG_BASE64;
3168
+ }
3169
+
3170
+ // src/tui/tray.ts
3171
+ function shouldEnableTray(options) {
3172
+ if (options.noTray) return false;
3173
+ const platform = options.platform ?? process.platform;
3174
+ const env = options.env ?? process.env;
3175
+ if (platform === "linux") {
3176
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
3177
+ }
3178
+ return platform === "win32" || platform === "darwin";
3179
+ }
3180
+ function getBinName(platform) {
3181
+ if (platform === "win32") return "tray_windows_release.exe";
3182
+ if (platform === "darwin") return "tray_darwin_release";
3183
+ if (platform === "linux") return "tray_linux_release";
3184
+ return null;
3185
+ }
3186
+ function prepareExecutableCopyDir() {
3187
+ const binName = getBinName(process.platform);
3188
+ if (!binName) return true;
3189
+ try {
3190
+ const require2 = createRequire(import.meta.url);
3191
+ const entryPath = require2.resolve("systray2");
3192
+ const pkgDir = path3.dirname(entryPath);
3193
+ const pkgJson = JSON.parse(fs3.readFileSync(path3.join(pkgDir, "package.json"), "utf8"));
3194
+ const version = pkgJson.version || "2.1.4";
3195
+ const srcBin = path3.join(pkgDir, "traybin", binName);
3196
+ const cacheRoot = path3.join(os.homedir(), ".cache", "node-systray");
3197
+ const destDir = path3.join(cacheRoot, version);
3198
+ const destBin = path3.join(destDir, binName);
3199
+ fs3.mkdirSync(destDir, { recursive: true });
3200
+ if (!fs3.existsSync(destBin)) {
3201
+ fs3.copyFileSync(srcBin, destBin);
3202
+ }
3203
+ if (process.platform !== "win32") {
3204
+ fs3.chmodSync(destBin, 493);
3205
+ }
3206
+ return cacheRoot;
3207
+ } catch {
3208
+ return true;
3209
+ }
3210
+ }
3211
+ async function startSystemTray(options) {
3212
+ if (!shouldEnableTray({ noTray: options.noTray })) {
3213
+ return null;
3214
+ }
3215
+ let systray = null;
3216
+ try {
3217
+ const copyDir = prepareExecutableCopyDir();
3218
+ const mod = await import("systray2");
3219
+ const SysTrayCtor = mod.default?.default ?? mod.default;
3220
+ const statusItem = {
3221
+ title: `URLScanner (:${options.port})`,
3222
+ tooltip: options.serverUrl,
3223
+ checked: false,
3224
+ enabled: false
3225
+ };
3226
+ const openItem = {
3227
+ title: "Open Dashboard",
3228
+ tooltip: `Open ${options.serverUrl} in browser`,
3229
+ checked: false,
3230
+ enabled: true
3231
+ };
3232
+ const quitItem = {
3233
+ title: "Quit",
3234
+ tooltip: "Stop URLScanner daemon",
3235
+ checked: false,
3236
+ enabled: true
3237
+ };
3238
+ const items = SysTrayCtor.separator ? [statusItem, SysTrayCtor.separator, openItem, quitItem] : [statusItem, openItem, quitItem];
3239
+ systray = new SysTrayCtor({
3240
+ menu: {
3241
+ icon: getTrayIconForPlatform(),
3242
+ title: "",
3243
+ tooltip: `URLScanner \u2014 ${options.serverUrl}`,
3244
+ items
3245
+ },
3246
+ debug: false,
3247
+ copyDir
3248
+ });
3249
+ await Promise.race([
3250
+ systray.ready(),
3251
+ new Promise(
3252
+ (_, reject) => setTimeout(() => reject(new Error("Tray initialization timed out")), 4e3)
3253
+ )
3254
+ ]);
3255
+ systray.onError((err) => {
3256
+ console.error(`Tray warning: ${err.message}`);
3257
+ });
3258
+ await systray.onClick((action) => {
3259
+ const clickedTitle = action.item?.title ?? "";
3260
+ if (clickedTitle === "Open Dashboard") {
3261
+ openBrowser(options.serverUrl);
3262
+ } else if (clickedTitle === "Quit") {
3263
+ options.onQuit();
3264
+ }
3265
+ });
3266
+ const activeTray = systray;
3267
+ return {
3268
+ kill: async () => {
3269
+ try {
3270
+ if (activeTray.process && !activeTray.killed) {
3271
+ await activeTray.kill(false);
3272
+ }
3273
+ } catch {
3274
+ try {
3275
+ activeTray.process?.kill("SIGKILL");
3276
+ } catch {
3277
+ }
3278
+ }
3279
+ }
3280
+ };
3281
+ } catch (err) {
3282
+ try {
3283
+ systray?.process?.kill("SIGKILL");
3284
+ } catch {
3285
+ }
3286
+ console.error(
3287
+ `System tray unavailable (${err instanceof Error ? err.message : String(err)}); running headless daemon.`
3288
+ );
3289
+ return null;
3290
+ }
3291
+ }
3292
+
2982
3293
  // src/cli.ts
2983
3294
  function defaultDataDir() {
2984
- return process.env.URLSCANNER_DATA_DIR || path3.join(os.homedir(), ".urlscanner");
3295
+ return process.env.URLSCANNER_DATA_DIR || path4.join(os2.homedir(), ".urlscanner");
2985
3296
  }
2986
3297
  function isProcessAlive(pid) {
2987
3298
  try {
@@ -2993,12 +3304,12 @@ function isProcessAlive(pid) {
2993
3304
  }
2994
3305
  function readPidFile(pidPath) {
2995
3306
  try {
2996
- if (!fs3.existsSync(pidPath)) return null;
2997
- const info = JSON.parse(fs3.readFileSync(pidPath, "utf8"));
3307
+ if (!fs4.existsSync(pidPath)) return null;
3308
+ const info = JSON.parse(fs4.readFileSync(pidPath, "utf8"));
2998
3309
  if (info && typeof info.pid === "number" && isProcessAlive(info.pid)) {
2999
3310
  return info;
3000
3311
  }
3001
- fs3.rmSync(pidPath, { force: true });
3312
+ fs4.rmSync(pidPath, { force: true });
3002
3313
  return null;
3003
3314
  } catch {
3004
3315
  return null;
@@ -3020,6 +3331,7 @@ Options:
3020
3331
  --tui Open Interactive Terminal UI directly
3021
3332
  --no-open Do not auto-open browser in Web UI mode
3022
3333
  --no-menu Run headless server without interactive terminal menu
3334
+ --no-tray Disable system tray icon in background daemon mode
3023
3335
  --daemon Run in background daemon mode
3024
3336
  -v, --version Print version
3025
3337
  -h, --help Show this help message
@@ -3037,8 +3349,20 @@ async function waitForHealth(url, timeoutMs = 6e3) {
3037
3349
  }
3038
3350
  return false;
3039
3351
  }
3352
+ async function checkExistingUrlScanner(host, port) {
3353
+ try {
3354
+ const resp = await fetch(`http://${host}:${port}/api/health`, {
3355
+ signal: AbortSignal.timeout(800)
3356
+ });
3357
+ if (!resp.ok) return false;
3358
+ const data = await resp.json();
3359
+ return data?.status === "ok" && typeof data.counts === "object";
3360
+ } catch {
3361
+ return false;
3362
+ }
3363
+ }
3040
3364
  async function handleStatus(dataDir) {
3041
- const pidPath = path3.join(dataDir, "server.pid");
3365
+ const pidPath = path4.join(dataDir, "server.pid");
3042
3366
  const info = readPidFile(pidPath);
3043
3367
  if (!info) {
3044
3368
  console.log("URLScanner daemon is not running.");
@@ -3050,11 +3374,11 @@ async function handleStatus(dataDir) {
3050
3374
  console.log(`Data dir: ${info.dataDir}`);
3051
3375
  }
3052
3376
  async function handleStop(dataDir) {
3053
- const pidPath = path3.join(dataDir, "server.pid");
3377
+ const pidPath = path4.join(dataDir, "server.pid");
3054
3378
  const info = readPidFile(pidPath);
3055
3379
  if (!info) {
3056
3380
  console.log("URLScanner daemon is not running.");
3057
- return;
3381
+ return false;
3058
3382
  }
3059
3383
  try {
3060
3384
  process.kill(info.pid, "SIGTERM");
@@ -3064,13 +3388,14 @@ async function handleStop(dataDir) {
3064
3388
  while (Date.now() < deadline && isProcessAlive(info.pid)) {
3065
3389
  await new Promise((r) => setTimeout(r, 150));
3066
3390
  }
3067
- fs3.rmSync(pidPath, { force: true });
3391
+ fs4.rmSync(pidPath, { force: true });
3068
3392
  console.log(`Stopped URLScanner daemon (PID ${info.pid}).`);
3393
+ return true;
3069
3394
  }
3070
- async function spawnDaemon(host, port, dataDir) {
3071
- fs3.mkdirSync(dataDir, { recursive: true });
3072
- const logPath = path3.join(dataDir, "server.log");
3073
- const logFd = fs3.openSync(logPath, "a");
3395
+ async function spawnDaemon(host, port, dataDir, noTray = false) {
3396
+ fs4.mkdirSync(dataDir, { recursive: true });
3397
+ const logPath = path4.join(dataDir, "server.log");
3398
+ const logFd = fs4.openSync(logPath, "a");
3074
3399
  const scriptPath = process.argv[1];
3075
3400
  const args = [
3076
3401
  scriptPath,
@@ -3082,22 +3407,30 @@ async function spawnDaemon(host, port, dataDir) {
3082
3407
  "--data-dir",
3083
3408
  dataDir
3084
3409
  ];
3410
+ if (noTray) {
3411
+ args.push("--no-tray");
3412
+ }
3085
3413
  const child = spawn2(process.execPath, args, {
3086
3414
  detached: true,
3087
- stdio: ["ignore", logFd, logFd]
3415
+ stdio: ["ignore", logFd, logFd],
3416
+ windowsHide: true
3088
3417
  });
3089
3418
  child.unref();
3090
3419
  const url = `http://${host === "127.0.0.1" ? "localhost" : host}:${port}`;
3091
3420
  const ok = await waitForHealth(`http://${host}:${port}`, 6e3);
3092
3421
  if (ok) {
3422
+ const trayEnabled = shouldEnableTray({ noTray });
3093
3423
  console.log(`
3094
3424
  \u{1F680} URLScanner running in background (PID ${child.pid})`);
3095
- console.log(` Web UI : ${url}`);
3096
- console.log(` Log : ${logPath}`);
3097
- console.log(` Kelola : urlscanner status | urlscanner stop
3425
+ console.log(` Dashboard : ${url}`);
3426
+ console.log(
3427
+ ` Tray : ${trayEnabled ? "Enabled (Open Dashboard / Quit)" : noTray ? "Disabled (--no-tray)" : "Headless"}`
3428
+ );
3429
+ console.log(` Log : ${logPath}`);
3430
+ console.log(` Manage : urlscanner status | urlscanner stop
3098
3431
  `);
3099
3432
  } else {
3100
- console.error(`Gagal menjalankan daemon. Cek log di ${logPath}`);
3433
+ console.error(`Failed to start daemon. Check logs at ${logPath}`);
3101
3434
  process.exitCode = 1;
3102
3435
  }
3103
3436
  }
@@ -3112,6 +3445,7 @@ async function main() {
3112
3445
  tui: { type: "boolean", default: false },
3113
3446
  "no-open": { type: "boolean", default: false },
3114
3447
  "no-menu": { type: "boolean", default: false },
3448
+ "no-tray": { type: "boolean", default: false },
3115
3449
  daemon: { type: "boolean", default: false },
3116
3450
  version: { type: "boolean", short: "v", default: false },
3117
3451
  help: { type: "boolean", short: "h", default: false }
@@ -3125,7 +3459,7 @@ async function main() {
3125
3459
  console.log(APP_VERSION);
3126
3460
  return;
3127
3461
  }
3128
- const dataDir = path3.resolve(values["data-dir"] || defaultDataDir());
3462
+ const dataDir = path4.resolve(values["data-dir"] || defaultDataDir());
3129
3463
  const subcommand = positionals[0];
3130
3464
  if (subcommand === "status") {
3131
3465
  await handleStatus(dataDir);
@@ -3137,31 +3471,55 @@ async function main() {
3137
3471
  }
3138
3472
  const host = values.host || DEFAULT_HOST;
3139
3473
  const port = Number.parseInt(values.port || String(DEFAULT_PORT), 10) || DEFAULT_PORT;
3140
- const dbPath = path3.join(dataDir, "scanner.db");
3474
+ const displayHost = host === "127.0.0.1" ? "localhost" : host;
3475
+ const dbPath = path4.join(dataDir, "scanner.db");
3141
3476
  const db = new AppDatabase(dbPath);
3142
3477
  const ctx = createContext(db);
3143
3478
  const app = createApp(ctx);
3144
- const started = await startHttpServer(app, host, port);
3145
- const displayHost = host === "127.0.0.1" ? "localhost" : host;
3146
- const serverUrl = `http://${displayHost}:${started.port}`;
3147
- const pidPath = path3.join(dataDir, "server.pid");
3479
+ const alreadyRunning = !values.daemon && await checkExistingUrlScanner(host, port);
3480
+ let started = null;
3481
+ if (!alreadyRunning) {
3482
+ try {
3483
+ started = await startHttpServer(app, host, port);
3484
+ } catch (err) {
3485
+ const code = err?.code;
3486
+ if (code === "EADDRINUSE") {
3487
+ console.error(
3488
+ `Port ${port} is already in use by another application. Try: urlscanner --port ${port + 1}`
3489
+ );
3490
+ } else {
3491
+ console.error(err);
3492
+ }
3493
+ db.close();
3494
+ process.exitCode = 1;
3495
+ return;
3496
+ }
3497
+ }
3498
+ const activePort = started ? started.port : port;
3499
+ const serverUrl = `http://${displayHost}:${activePort}`;
3500
+ const pidPath = path4.join(dataDir, "server.pid");
3148
3501
  if (values.daemon) {
3149
3502
  const pidInfo = {
3150
3503
  pid: process.pid,
3151
- port: started.port,
3504
+ port: activePort,
3152
3505
  host,
3153
3506
  dataDir,
3154
3507
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
3155
3508
  };
3156
- fs3.writeFileSync(pidPath, JSON.stringify(pidInfo, null, 2));
3509
+ fs4.writeFileSync(pidPath, JSON.stringify(pidInfo, null, 2));
3157
3510
  }
3511
+ let trayHandle = null;
3512
+ let shuttingDown = false;
3158
3513
  const shutdown = () => {
3514
+ if (shuttingDown) return;
3515
+ shuttingDown = true;
3516
+ void trayHandle?.kill();
3159
3517
  try {
3160
- started.server.close();
3518
+ started?.server.close();
3161
3519
  } catch {
3162
3520
  }
3163
3521
  if (values.daemon) {
3164
- fs3.rmSync(pidPath, { force: true });
3522
+ fs4.rmSync(pidPath, { force: true });
3165
3523
  }
3166
3524
  try {
3167
3525
  db.close();
@@ -3176,22 +3534,55 @@ async function main() {
3176
3534
  shutdown();
3177
3535
  process.exit(0);
3178
3536
  });
3179
- if (values.daemon || values["no-menu"]) {
3537
+ if (values.daemon) {
3180
3538
  console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
3539
+ trayHandle = await startSystemTray({
3540
+ serverUrl,
3541
+ port: activePort,
3542
+ noTray: values["no-tray"],
3543
+ onQuit: () => {
3544
+ shutdown();
3545
+ setTimeout(() => process.exit(0), 150);
3546
+ }
3547
+ });
3548
+ return;
3549
+ }
3550
+ if (values["no-menu"]) {
3551
+ if (alreadyRunning) {
3552
+ console.log(`URLScanner is already running on ${serverUrl}`);
3553
+ if (values.web && !values["no-open"]) {
3554
+ openBrowser(serverUrl);
3555
+ }
3556
+ db.close();
3557
+ return;
3558
+ }
3559
+ console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
3560
+ if (values.web && !values["no-open"]) {
3561
+ openBrowser(serverUrl);
3562
+ }
3181
3563
  return;
3182
3564
  }
3183
3565
  let mode = values.tui ? "tui" : values.web ? "web" : "menu";
3184
3566
  let firstWebOpen = !values["no-open"];
3185
3567
  while (true) {
3186
3568
  if (mode === "menu") {
3187
- const choice = await runLauncherMenu(serverUrl);
3569
+ const choice = await runLauncherMenu(serverUrl, { alreadyRunning });
3188
3570
  if (choice === "exit") {
3189
3571
  shutdown();
3190
3572
  process.exit(0);
3191
3573
  }
3574
+ if (choice === "stop") {
3575
+ shutdown();
3576
+ await handleStop(dataDir);
3577
+ process.exit(0);
3578
+ }
3192
3579
  if (choice === "daemon") {
3193
3580
  shutdown();
3194
- await spawnDaemon(host, started.port, dataDir);
3581
+ if (alreadyRunning) {
3582
+ await handleStop(dataDir);
3583
+ await new Promise((r) => setTimeout(r, 300));
3584
+ }
3585
+ await spawnDaemon(host, activePort, dataDir, values["no-tray"]);
3195
3586
  process.exit(0);
3196
3587
  }
3197
3588
  mode = choice;