hintshell 0.3.6 → 0.3.7

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
@@ -65,6 +65,10 @@ HintShell uses `fzf` to render the suggestion picker on Bash/Zsh (including **Gi
65
65
  Install via NPM to get the latest pre-built binaries for your platform:
66
66
  ```bash
67
67
  npm install -g hintshell@latest
68
+
69
+ or
70
+
71
+ npm i -g hintshell@latest --foreground-scripts
68
72
  ```
69
73
 
70
74
  ### 3. Initialize Shell Integration
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hintshell",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "Local, context-aware real-time command suggestions for PowerShell, Bash, and Zsh.",
5
5
  "keywords": [
6
6
  "shell-assistant",
@@ -41,7 +41,9 @@
41
41
  "LICENSE"
42
42
  ],
43
43
  "scripts": {
44
- "postinstall": "node scripts/npm-install.js"
44
+ "preinstall": "node scripts/npm-stop.js",
45
+ "postinstall": "node scripts/npm-install.js",
46
+ "test:installer": "node --test scripts/npm-install.test.js"
45
47
  },
46
48
  "os": [
47
49
  "win32",
@@ -9,10 +9,16 @@
9
9
  */
10
10
 
11
11
  const https = require("https");
12
+ const http = require("http");
12
13
  const fs = require("fs");
13
14
  const path = require("path");
14
- const { execSync, spawnSync } = require("child_process");
15
+ const { fileURLToPath } = require("url");
16
+ const { execFileSync } = require("child_process");
15
17
  const os = require("os");
18
+ const { stopRunningDaemon } = require("./npm-stop");
19
+
20
+ const REQUEST_TIMEOUT_MS = 30_000;
21
+ const MAX_REDIRECTS = 5;
16
22
 
17
23
  const REPO = "philau2512/hintshell";
18
24
  const VERSION = require("../package.json").version;
@@ -40,110 +46,118 @@ function getPlatformKey() {
40
46
  }
41
47
 
42
48
  function getDownloadUrl(target, ext) {
49
+ const overrideUrl = process.env.HINTSHELL_ASSET_URL;
50
+ if (overrideUrl) {
51
+ return overrideUrl
52
+ .replace("{target}", target)
53
+ .replace("{ext}", ext);
54
+ }
43
55
  return `https://github.com/${REPO}/releases/download/${TAG}/hintshell-${target}${ext}`;
44
56
  }
45
57
 
46
- function downloadFile(url, dest) {
58
+ function downloadFile(url, dest, options = {}) {
59
+ const requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
60
+ if (new URL(url).protocol === "file:") {
61
+ return new Promise((resolve, reject) => {
62
+ fs.copyFile(fileURLToPath(url), dest, (error) => (error ? reject(error) : resolve()));
63
+ });
64
+ }
65
+ const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
66
+
47
67
  return new Promise((resolve, reject) => {
48
- const follow = (url) => {
49
- https.get(url, (res) => {
68
+ let settled = false;
69
+ let activeRequest;
70
+ let activeFile;
71
+ let timeout;
72
+
73
+ const finish = (error) => {
74
+ if (settled) return;
75
+ settled = true;
76
+ clearTimeout(timeout);
77
+ activeRequest?.destroy();
78
+ activeFile?.destroy();
79
+ if (error) {
80
+ try {
81
+ fs.unlinkSync(dest);
82
+ } catch (_) {
83
+ /* no partial archive */
84
+ }
85
+ reject(error);
86
+ } else {
87
+ resolve();
88
+ }
89
+ };
90
+
91
+ const follow = (nextUrl, redirects = 0) => {
92
+ if (redirects > maxRedirects) {
93
+ finish(new Error(`Download failed: exceeded ${maxRedirects} redirects`));
94
+ return;
95
+ }
96
+
97
+ console.log(` Fetching release asset${redirects ? ` (redirect ${redirects})` : ""}...`);
98
+ const transport = new URL(nextUrl).protocol === "http:" ? http : https;
99
+ activeRequest = transport.get(nextUrl, (res) => {
50
100
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
51
- follow(res.headers.location);
101
+ res.resume();
102
+ follow(new URL(res.headers.location, nextUrl).toString(), redirects + 1);
52
103
  return;
53
104
  }
54
105
  if (res.statusCode !== 200) {
55
- reject(new Error(`Download failed: HTTP ${res.statusCode} from ${url}`));
106
+ res.resume();
107
+ finish(new Error(`Download failed: HTTP ${res.statusCode} from ${nextUrl}`));
56
108
  return;
57
109
  }
58
- const file = fs.createWriteStream(dest);
59
- res.pipe(file);
60
- file.on("finish", () => {
61
- file.close();
62
- resolve();
110
+
111
+ const totalBytes = Number(res.headers["content-length"] || 0);
112
+ let downloadedBytes = 0;
113
+ let lastReportedBytes = 0;
114
+ activeFile = fs.createWriteStream(dest);
115
+ res.on("data", (chunk) => {
116
+ downloadedBytes += chunk.length;
117
+ if (downloadedBytes - lastReportedBytes >= 5 * 1024 * 1024) {
118
+ lastReportedBytes = downloadedBytes;
119
+ const suffix = totalBytes
120
+ ? `/${Math.ceil(totalBytes / 1024 / 1024)} MB`
121
+ : " MB";
122
+ console.log(` Downloaded ${Math.floor(downloadedBytes / 1024 / 1024)}${suffix}`);
123
+ }
63
124
  });
64
- file.on("error", reject);
65
- }).on("error", reject);
125
+ res.on("error", finish);
126
+ activeFile.on("error", finish);
127
+ activeFile.on("finish", () => activeFile.close(() => finish()));
128
+ res.pipe(activeFile);
129
+ });
130
+
131
+ activeRequest.on("error", finish);
132
+ activeRequest.setTimeout(requestTimeoutMs, () => {
133
+ finish(new Error(`Download timed out after ${requestTimeoutMs / 1000}s`));
134
+ });
66
135
  };
136
+
137
+ timeout = setTimeout(() => {
138
+ finish(new Error(`Download timed out after ${requestTimeoutMs / 1000}s`));
139
+ }, requestTimeoutMs);
67
140
  follow(url);
68
141
  });
69
142
  }
70
143
 
71
144
  function extractArchive(archivePath, destDir) {
72
- if (os.platform() === "win32") {
73
- // Windows 10+ has tar (bsdtar) built-in which fully supports zip files.
74
- execSync(`tar -xf "${archivePath}" -C "${destDir}"`, { stdio: "inherit" });
75
- } else {
76
- execSync(`tar xzf "${archivePath}" -C "${destDir}"`, { stdio: "inherit" });
145
+ if (IS_WIN) {
146
+ const command = [
147
+ "$ErrorActionPreference = 'Stop'",
148
+ `Expand-Archive -LiteralPath '${archivePath.replace(/'/g, "''")}' -DestinationPath '${destDir.replace(/'/g, "''")}' -Force`,
149
+ ].join("; ");
150
+ execFileSync("powershell", ["-NoProfile", "-Command", command], { stdio: "inherit" });
151
+ return;
77
152
  }
153
+
154
+ execFileSync("tar", ["xzf", archivePath, "-C", destDir], { stdio: "inherit" });
78
155
  }
79
156
 
80
157
  function binName(base) {
81
158
  return IS_WIN ? `${base}.exe` : base;
82
159
  }
83
160
 
84
- /**
85
- * Stop running daemon so Windows can overwrite vendor/ and ~/.hintshell binaries.
86
- * Best-effort: never throw.
87
- */
88
- function stopRunningDaemon(reason) {
89
- console.log(`🛑 Stopping HintShell daemon (${reason})...`);
90
- const home = os.homedir();
91
- const candidates = [
92
- path.join(home, ".hintshell", "bin", binName("hintshell")),
93
- path.join(home, ".hintshell", "module", binName("hintshell")),
94
- path.join(__dirname, "..", "vendor", binName("hintshell")),
95
- ];
96
-
97
- for (const cli of candidates) {
98
- if (!fs.existsSync(cli)) continue;
99
- try {
100
- spawnSync(cli, ["stop"], {
101
- encoding: "utf8",
102
- timeout: 8000,
103
- windowsHide: true,
104
- });
105
- break;
106
- } catch (_) {
107
- /* try next */
108
- }
109
- }
110
-
111
- // Always force-kill leftovers (Windows file lock on hintshell-core.exe)
112
- try {
113
- if (IS_WIN) {
114
- spawnSync("taskkill", ["/F", "/IM", "hintshell-core.exe"], {
115
- stdio: "ignore",
116
- windowsHide: true,
117
- timeout: 5000,
118
- });
119
- spawnSync(
120
- "powershell",
121
- [
122
- "-NoProfile",
123
- "-Command",
124
- "Get-Process -Name 'hintshell-core' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue",
125
- ],
126
- { stdio: "ignore", windowsHide: true, timeout: 5000 }
127
- );
128
- } else {
129
- spawnSync("pkill", ["-f", "hintshell-core"], {
130
- stdio: "ignore",
131
- timeout: 5000,
132
- });
133
- }
134
- } catch (_) {
135
- /* ignore */
136
- }
137
-
138
- // Brief wait so OS releases file handles
139
- const until = Date.now() + 400;
140
- while (Date.now() < until) {
141
- /* spin — avoid Atomics/SharedArrayBuffer quirks */
142
- }
143
-
144
- console.log(" Daemon stop attempted (IPC + force kill).");
145
- }
146
-
147
161
  function runInit(vendorDir) {
148
162
  const cli = path.join(vendorDir, binName("hintshell"));
149
163
  if (!fs.existsSync(cli)) {
@@ -152,7 +166,7 @@ function runInit(vendorDir) {
152
166
  }
153
167
  console.log("📦 Running hintshell init (copy into ~/.hintshell + hooks)...");
154
168
  try {
155
- execSync(`"${cli}" init`, { stdio: "inherit", windowsHide: true });
169
+ execFileSync(cli, ["init"], { stdio: "inherit", windowsHide: true });
156
170
  } catch (err) {
157
171
  console.error("⚠️ hintshell init failed. Run manually: hintshell init");
158
172
  if (err && err.message) console.error(` ${err.message}`);
@@ -228,4 +242,8 @@ async function main() {
228
242
  }
229
243
  }
230
244
 
231
- main();
245
+ if (require.main === module) {
246
+ main();
247
+ }
248
+
249
+ module.exports = { downloadFile, getDownloadUrl };
@@ -0,0 +1,105 @@
1
+ const assert = require("node:assert/strict");
2
+ const fs = require("node:fs");
3
+ const http = require("node:http");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const test = require("node:test");
7
+
8
+ const { downloadFile, getDownloadUrl } = require("./npm-install");
9
+
10
+ function tempFile(name) {
11
+ return path.join(os.tmpdir(), `hintshell-${process.pid}-${Date.now()}-${name}`);
12
+ }
13
+
14
+ function listen(handler) {
15
+ const server = http.createServer(handler);
16
+ return new Promise((resolve) => {
17
+ server.listen(0, "127.0.0.1", () => resolve(server));
18
+ });
19
+ }
20
+
21
+ test("Windows stop script targets the live wrapper and daemon", () => {
22
+ const script = fs.readFileSync(path.join(__dirname, "npm-stop.js"), "utf8");
23
+ assert.match(script, /hintshell-core\.exe/);
24
+ assert.match(script, /hintshell\.exe/);
25
+ assert.match(script, /Get-Process -Name 'hintshell', 'hintshell-core'/);
26
+ });
27
+
28
+ test("isolated tests skip global process control", () => {
29
+ const script = fs.readFileSync(path.join(__dirname, "npm-stop.js"), "utf8");
30
+ assert.match(script, /HINTSHELL_SKIP_PROCESS_CONTROL/);
31
+ });
32
+
33
+ test("uses the local asset URL override for isolated installer tests", () => {
34
+ const previous = process.env.HINTSHELL_ASSET_URL;
35
+ process.env.HINTSHELL_ASSET_URL = "http://127.0.0.1:8123/hintshell-{target}{ext}";
36
+ try {
37
+ assert.equal(
38
+ getDownloadUrl("x86_64-pc-windows-msvc", ".zip"),
39
+ "http://127.0.0.1:8123/hintshell-x86_64-pc-windows-msvc.zip"
40
+ );
41
+ } finally {
42
+ if (previous === undefined) {
43
+ delete process.env.HINTSHELL_ASSET_URL;
44
+ } else {
45
+ process.env.HINTSHELL_ASSET_URL = previous;
46
+ }
47
+ }
48
+ });
49
+
50
+ test("downloads a release asset after a redirect", async () => {
51
+ const server = await listen((request, response) => {
52
+ if (request.url === "/release") {
53
+ response.writeHead(302, { location: "/asset" });
54
+ response.end();
55
+ return;
56
+ }
57
+ response.writeHead(200, { "content-length": "5" });
58
+ response.end("ready");
59
+ });
60
+ const destination = tempFile("redirect.zip");
61
+
62
+ try {
63
+ const address = server.address();
64
+ await downloadFile(`http://127.0.0.1:${address.port}/release`, destination, {
65
+ requestTimeoutMs: 1_000,
66
+ });
67
+ assert.equal(fs.readFileSync(destination, "utf8"), "ready");
68
+ } finally {
69
+ server.close();
70
+ fs.rmSync(destination, { force: true });
71
+ }
72
+ });
73
+
74
+ test("copies an isolated local file asset", async () => {
75
+ const source = tempFile("fixture.zip");
76
+ const destination = tempFile("local-copy.zip");
77
+ fs.writeFileSync(source, "fixture");
78
+
79
+ try {
80
+ await downloadFile(new URL(`file:///${source.replace(/\\/g, "/")}`).toString(), destination);
81
+ assert.equal(fs.readFileSync(destination, "utf8"), "fixture");
82
+ } finally {
83
+ fs.rmSync(source, { force: true });
84
+ fs.rmSync(destination, { force: true });
85
+ }
86
+ });
87
+
88
+ test("rejects a stalled download and removes its partial archive", async () => {
89
+ const server = await listen(() => {});
90
+ const destination = tempFile("timeout.zip");
91
+
92
+ try {
93
+ const address = server.address();
94
+ await assert.rejects(
95
+ downloadFile(`http://127.0.0.1:${address.port}/stalled`, destination, {
96
+ requestTimeoutMs: 50,
97
+ }),
98
+ /timed out/
99
+ );
100
+ assert.equal(fs.existsSync(destination), false);
101
+ } finally {
102
+ server.close();
103
+ fs.rmSync(destination, { force: true });
104
+ }
105
+ });
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
6
+ const { spawnSync } = require("child_process");
7
+
8
+ const IS_WIN = os.platform() === "win32";
9
+
10
+ function binName(base) {
11
+ return IS_WIN ? `${base}.exe` : base;
12
+ }
13
+
14
+ function run(command, args, options = {}) {
15
+ try {
16
+ return spawnSync(command, args, {
17
+ stdio: "ignore",
18
+ timeout: 5000,
19
+ windowsHide: true,
20
+ ...options,
21
+ });
22
+ } catch (_) {
23
+ return undefined;
24
+ }
25
+ }
26
+
27
+ function stopRunningDaemon(reason) {
28
+ console.log(`🛑 Stopping HintShell daemon (${reason})...`);
29
+ if (process.env.HINTSHELL_SKIP_PROCESS_CONTROL === "1") {
30
+ console.log(" HINTSHELL_SKIP_PROCESS_CONTROL=1 — skipped for isolated test.");
31
+ return;
32
+ }
33
+
34
+ const home = os.homedir();
35
+ const hintshellHome = process.env.HINTSHELL_HOME || path.join(home, ".hintshell");
36
+ const candidates = [
37
+ path.join(hintshellHome, "bin", binName("hintshell")),
38
+ path.join(hintshellHome, "module", binName("hintshell")),
39
+ path.join(__dirname, "..", "vendor", binName("hintshell")),
40
+ ];
41
+
42
+ for (const cli of candidates) {
43
+ if (!fs.existsSync(cli)) continue;
44
+ run(cli, ["stop"], { encoding: "utf8", timeout: 8000 });
45
+ break;
46
+ }
47
+
48
+ if (IS_WIN) {
49
+ run("taskkill", ["/F", "/IM", "hintshell-core.exe"]);
50
+ run("taskkill", ["/F", "/IM", "hintshell.exe"]);
51
+ run("powershell", [
52
+ "-NoProfile",
53
+ "-Command",
54
+ "Get-Process -Name 'hintshell', 'hintshell-core' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue",
55
+ ]);
56
+ } else {
57
+ run("pkill", ["-f", "hintshell-core"]);
58
+ }
59
+
60
+ console.log(" Daemon stop attempted (IPC + force kill).");
61
+ }
62
+
63
+ if (require.main === module) {
64
+ stopRunningDaemon("before npm install");
65
+ }
66
+
67
+ module.exports = { stopRunningDaemon };