hintshell 0.3.6 → 0.3.8

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
@@ -62,9 +62,9 @@ HintShell uses `fzf` to render the suggestion picker on Bash/Zsh (including **Gi
62
62
  - **Windows PowerShell**: No extra dependencies for the real-time overlay.
63
63
 
64
64
  ### 2. Install HintShell
65
- Install via NPM to get the latest pre-built binaries for your platform:
65
+ Install via npm to get the latest pre-built binaries for your platform. Add `--foreground-scripts` to show the binary download, extraction, and setup output (this is also what `hs update` uses):
66
66
  ```bash
67
- npm install -g hintshell@latest
67
+ npm install -g hintshell@latest --foreground-scripts
68
68
  ```
69
69
 
70
70
  ### 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.8",
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,124 @@ 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
+ let parsedUrl;
61
+ try {
62
+ parsedUrl = new URL(url);
63
+ } catch {
64
+ return Promise.reject(new Error(`Download failed: invalid URL ${url}`));
65
+ }
66
+ if (parsedUrl.protocol === "file:") {
67
+ return new Promise((resolve, reject) => {
68
+ fs.copyFile(fileURLToPath(url), dest, (error) => (error ? reject(error) : resolve()));
69
+ });
70
+ }
71
+ const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
72
+
47
73
  return new Promise((resolve, reject) => {
48
- const follow = (url) => {
49
- https.get(url, (res) => {
74
+ let settled = false;
75
+ let activeRequest;
76
+ let activeFile;
77
+ let timeout;
78
+
79
+ const finish = (error) => {
80
+ if (settled) return;
81
+ settled = true;
82
+ clearTimeout(timeout);
83
+ activeRequest?.destroy();
84
+ activeFile?.destroy();
85
+ if (error) {
86
+ try {
87
+ fs.unlinkSync(dest);
88
+ } catch (_) {
89
+ /* no partial archive */
90
+ }
91
+ reject(error);
92
+ } else {
93
+ resolve();
94
+ }
95
+ };
96
+
97
+ const follow = (nextUrl, redirects = 0) => {
98
+ if (redirects > maxRedirects) {
99
+ finish(new Error(`Download failed: exceeded ${maxRedirects} redirects`));
100
+ return;
101
+ }
102
+
103
+ console.log(` Fetching release asset${redirects ? ` (redirect ${redirects})` : ""}...`);
104
+ const transport = new URL(nextUrl).protocol === "http:" ? http : https;
105
+ activeRequest = transport.get(nextUrl, (res) => {
50
106
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
51
- follow(res.headers.location);
107
+ res.resume();
108
+ follow(new URL(res.headers.location, nextUrl).toString(), redirects + 1);
52
109
  return;
53
110
  }
54
111
  if (res.statusCode !== 200) {
55
- reject(new Error(`Download failed: HTTP ${res.statusCode} from ${url}`));
112
+ res.resume();
113
+ finish(new Error(`Download failed: HTTP ${res.statusCode} from ${nextUrl}`));
56
114
  return;
57
115
  }
58
- const file = fs.createWriteStream(dest);
59
- res.pipe(file);
60
- file.on("finish", () => {
61
- file.close();
62
- resolve();
116
+
117
+ const totalBytes = Number(res.headers["content-length"] || 0);
118
+ let downloadedBytes = 0;
119
+ let lastReportedBytes = 0;
120
+ activeFile = fs.createWriteStream(dest);
121
+ res.on("data", (chunk) => {
122
+ downloadedBytes += chunk.length;
123
+ if (downloadedBytes - lastReportedBytes >= 5 * 1024 * 1024) {
124
+ lastReportedBytes = downloadedBytes;
125
+ const suffix = totalBytes
126
+ ? `/${Math.ceil(totalBytes / 1024 / 1024)} MB`
127
+ : " MB";
128
+ console.log(` Downloaded ${Math.floor(downloadedBytes / 1024 / 1024)}${suffix}`);
129
+ }
63
130
  });
64
- file.on("error", reject);
65
- }).on("error", reject);
131
+ res.on("error", finish);
132
+ activeFile.on("error", finish);
133
+ activeFile.on("finish", () => activeFile.close(() => finish()));
134
+ res.pipe(activeFile);
135
+ });
136
+
137
+ activeRequest.on("error", finish);
138
+ activeRequest.setTimeout(requestTimeoutMs, () => {
139
+ finish(new Error(`Download timed out after ${requestTimeoutMs / 1000}s`));
140
+ });
66
141
  };
142
+
143
+ timeout = setTimeout(() => {
144
+ finish(new Error(`Download timed out after ${requestTimeoutMs / 1000}s`));
145
+ }, requestTimeoutMs);
67
146
  follow(url);
68
147
  });
69
148
  }
70
149
 
71
150
  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" });
151
+ if (IS_WIN) {
152
+ const command = [
153
+ "$ErrorActionPreference = 'Stop'",
154
+ `Expand-Archive -LiteralPath '${archivePath.replace(/'/g, "''")}' -DestinationPath '${destDir.replace(/'/g, "''")}' -Force`,
155
+ ].join("; ");
156
+ execFileSync("powershell", ["-NoProfile", "-Command", command], { stdio: "inherit" });
157
+ return;
77
158
  }
159
+
160
+ execFileSync("tar", ["xzf", archivePath, "-C", destDir], { stdio: "inherit" });
78
161
  }
79
162
 
80
163
  function binName(base) {
81
164
  return IS_WIN ? `${base}.exe` : base;
82
165
  }
83
166
 
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
167
  function runInit(vendorDir) {
148
168
  const cli = path.join(vendorDir, binName("hintshell"));
149
169
  if (!fs.existsSync(cli)) {
@@ -152,7 +172,7 @@ function runInit(vendorDir) {
152
172
  }
153
173
  console.log("📦 Running hintshell init (copy into ~/.hintshell + hooks)...");
154
174
  try {
155
- execSync(`"${cli}" init`, { stdio: "inherit", windowsHide: true });
175
+ execFileSync(cli, ["init"], { stdio: "inherit", windowsHide: true });
156
176
  } catch (err) {
157
177
  console.error("⚠️ hintshell init failed. Run manually: hintshell init");
158
178
  if (err && err.message) console.error(` ${err.message}`);
@@ -228,4 +248,8 @@ async function main() {
228
248
  }
229
249
  }
230
250
 
231
- main();
251
+ if (require.main === module) {
252
+ main();
253
+ }
254
+
255
+ module.exports = { downloadFile, getDownloadUrl };
@@ -0,0 +1,117 @@
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 stops only live wrapper processes", () => {
22
+ const script = fs.readFileSync(path.join(__dirname, "npm-stop.js"), "utf8");
23
+ assert.match(script, /hintshell-core\.exe/);
24
+ assert.match(script, /Name = 'hintshell\.exe'/);
25
+ assert.match(script, /CommandLine -match/);
26
+ assert.match(script, /CommandLine -match .*bash/);
27
+ assert.doesNotMatch(script, /taskkill", \["\/F", "\/IM", "hintshell\.exe"\]/);
28
+ assert.doesNotMatch(script, /Get-Process -Name 'hintshell', 'hintshell-core'/);
29
+ });
30
+
31
+ test("PowerShell update exposes npm lifecycle progress without duplicate init", () => {
32
+ const module = fs.readFileSync(
33
+ path.join(__dirname, "..", "integrations", "powershell", "HintShellModule", "HintShellModule.psm1"),
34
+ "utf8"
35
+ );
36
+ assert.match(module, /npm install -g hintshell@latest --foreground-scripts --fetch-timeout=30000 --fetch-retries=1/);
37
+ assert.doesNotMatch(module, /Ensuring local install \(hintshell init\)/);
38
+ });
39
+
40
+ test("isolated tests skip global process control", () => {
41
+ const script = fs.readFileSync(path.join(__dirname, "npm-stop.js"), "utf8");
42
+ assert.match(script, /HINTSHELL_SKIP_PROCESS_CONTROL/);
43
+ });
44
+
45
+ test("uses the local asset URL override for isolated installer tests", () => {
46
+ const previous = process.env.HINTSHELL_ASSET_URL;
47
+ process.env.HINTSHELL_ASSET_URL = "http://127.0.0.1:8123/hintshell-{target}{ext}";
48
+ try {
49
+ assert.equal(
50
+ getDownloadUrl("x86_64-pc-windows-msvc", ".zip"),
51
+ "http://127.0.0.1:8123/hintshell-x86_64-pc-windows-msvc.zip"
52
+ );
53
+ } finally {
54
+ if (previous === undefined) {
55
+ delete process.env.HINTSHELL_ASSET_URL;
56
+ } else {
57
+ process.env.HINTSHELL_ASSET_URL = previous;
58
+ }
59
+ }
60
+ });
61
+
62
+ test("downloads a release asset after a redirect", async () => {
63
+ const server = await listen((request, response) => {
64
+ if (request.url === "/release") {
65
+ response.writeHead(302, { location: "/asset" });
66
+ response.end();
67
+ return;
68
+ }
69
+ response.writeHead(200, { "content-length": "5" });
70
+ response.end("ready");
71
+ });
72
+ const destination = tempFile("redirect.zip");
73
+
74
+ try {
75
+ const address = server.address();
76
+ await downloadFile(`http://127.0.0.1:${address.port}/release`, destination, {
77
+ requestTimeoutMs: 1_000,
78
+ });
79
+ assert.equal(fs.readFileSync(destination, "utf8"), "ready");
80
+ } finally {
81
+ server.close();
82
+ fs.rmSync(destination, { force: true });
83
+ }
84
+ });
85
+
86
+ test("copies an isolated local file asset", async () => {
87
+ const source = tempFile("fixture.zip");
88
+ const destination = tempFile("local-copy.zip");
89
+ fs.writeFileSync(source, "fixture");
90
+
91
+ try {
92
+ await downloadFile(new URL(`file:///${source.replace(/\\/g, "/")}`).toString(), destination);
93
+ assert.equal(fs.readFileSync(destination, "utf8"), "fixture");
94
+ } finally {
95
+ fs.rmSync(source, { force: true });
96
+ fs.rmSync(destination, { force: true });
97
+ }
98
+ });
99
+
100
+ test("rejects a stalled download and removes its partial archive", async () => {
101
+ const server = await listen(() => {});
102
+ const destination = tempFile("timeout.zip");
103
+
104
+ try {
105
+ const address = server.address();
106
+ await assert.rejects(
107
+ downloadFile(`http://127.0.0.1:${address.port}/stalled`, destination, {
108
+ requestTimeoutMs: 50,
109
+ }),
110
+ /timed out/
111
+ );
112
+ assert.equal(fs.existsSync(destination), false);
113
+ } finally {
114
+ server.close();
115
+ fs.rmSync(destination, { force: true });
116
+ }
117
+ });
@@ -0,0 +1,66 @@
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("powershell", [
51
+ "-NoProfile",
52
+ "-Command",
53
+ "Get-CimInstance Win32_Process -Filter \"Name = 'hintshell.exe'\" | Where-Object { $_.CommandLine -match '\\s+bash(?:\\s|$)' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }",
54
+ ]);
55
+ } else {
56
+ run("pkill", ["-f", "hintshell-core"]);
57
+ }
58
+
59
+ console.log(" Daemon stop attempted (IPC + force kill).");
60
+ }
61
+
62
+ if (require.main === module) {
63
+ stopRunningDaemon("before npm install");
64
+ }
65
+
66
+ module.exports = { stopRunningDaemon };