@gengjiawen/os-init 1.25.0 → 1.26.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.26.1](https://github.com/gengjiawen/os-init/compare/v1.26.0...v1.26.1) (2026-06-05)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * source bashrc from bash_profile on macOS ([8f5c9ae](https://github.com/gengjiawen/os-init/commit/8f5c9ae43e122766399d7a8584b91afabf5b9b7b))
9
+ * update vulnerable dependencies ([88eb62b](https://github.com/gengjiawen/os-init/commit/88eb62b2ce5706823c87f1dd1d827b10461a42c1))
10
+ * use dot nameservers for clash ([1b72d01](https://github.com/gengjiawen/os-init/commit/1b72d0138487173252d2b7ec295727317b4a8d34))
11
+
12
+ ## [1.26.0](https://github.com/gengjiawen/os-init/compare/v1.25.0...v1.26.0) (2026-05-25)
13
+
14
+
15
+ ### Features
16
+
17
+ * disable claude attribution header ([143f161](https://github.com/gengjiawen/os-init/commit/143f161d71f5b1b4984f3a6513081c8b66b6aa4b))
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * add system DNS to mihomo template ([37c844e](https://github.com/gengjiawen/os-init/commit/37c844e36837b191af00092c1538b10351b87a37))
23
+ * persist claude pnpm build approval ([dd10751](https://github.com/gengjiawen/os-init/commit/dd1075168f9e82a35b31049e2f61a64ba009812b))
24
+ * update mihomo sniffer config ([54df04d](https://github.com/gengjiawen/os-init/commit/54df04d48219041c0b4ab867cb80150f81639396))
25
+
3
26
  ## [1.25.0](https://github.com/gengjiawen/os-init/compare/v1.24.0...v1.25.0) (2026-05-19)
4
27
 
5
28
 
package/README.md CHANGED
@@ -90,21 +90,29 @@ Use a custom Cursor state database path when needed:
90
90
  pnpx @gengjiawen/os-init disable-ts-extension --db "$HOME/Library/Application Support/Cursor/User/globalStorage/state.vscdb"
91
91
  ```
92
92
 
93
- ### Generate Mihomo Config
93
+ ### Setup Environment Variables
94
+
95
+ ```bash
96
+ pnpx @gengjiawen/os-init setup-env
97
+ ```
98
+
99
+ Writes PNPM_HOME, RUSTUP_HOME, CARGO_HOME, and PATH entries (brew, cargo, pnpm, jsvu, yarn) to `~/.bashrc`. Automatically detects brew prefix per platform and only adds the rustup stable toolchain bin on macOS. On macOS, it also creates or updates `~/.bash_profile` so Bash login shells load `~/.bashrc`. Idempotent — safe to run multiple times.
100
+
101
+ ### Generate Clash Config
94
102
 
95
103
  ```bash
96
104
  pnpx @gengjiawen/os-init set-clash
97
105
  pnpx @gengjiawen/os-init set-clash --download
98
- pnpx @gengjiawen/os-init set-clash --target ~/mihomo/config.yml
106
+ pnpx @gengjiawen/os-init set-clash --target ~/clash/config.yml
99
107
  ```
100
108
 
101
- Generates a Mihomo `config.yml` from the built-in template. This command will:
109
+ Generates a Clash `config.yml` from the built-in template. This command will:
102
110
 
103
111
  - Write `./config.yml` in the current directory by default
104
- - Download the Mihomo binary to the config directory when `--download` is set
112
+ - Download the Clash binary to the config directory when `--download` is set
105
113
  - Support a custom output path with `-t, --target <path>`
106
114
 
107
- After generating the config, you can keep Mihomo running with pm2:
115
+ After generating the config, you can keep Clash running with pm2:
108
116
 
109
117
  ```bash
110
118
  pm2 start mihomo --name mihomo -- -f /absolute/path/to/config.yml && pm2 save
package/bin/bin.js CHANGED
@@ -14,9 +14,10 @@ const {
14
14
  writeRaycastConfig,
15
15
  setupDevEnvironment,
16
16
  setupAndroidEnvironment,
17
- writeMihomoConfig,
18
- downloadMihomoBinary,
17
+ writeClashConfig,
18
+ downloadClashBinary,
19
19
  disableCursorTypescriptExtension,
20
+ setupEnv,
20
21
  } = require('../build')
21
22
  const { appendFishImportScript } = require('../build/fish-shell-utils')
22
23
 
@@ -262,30 +263,52 @@ program
262
263
  }
263
264
  })
264
265
 
266
+ program
267
+ .command('setup-env')
268
+ .description(
269
+ 'setup environment variables in .bashrc (PATH, PNPM_HOME, CARGO_HOME, RUSTUP_HOME); on macOS ensure .bash_profile sources it'
270
+ )
271
+ .action(async () => {
272
+ try {
273
+ const { bashrcPath, bashProfilePath, changed } = setupEnv()
274
+ console.log(
275
+ changed
276
+ ? `Environment variables written to: ${bashrcPath}`
277
+ : `Environment variables already configured in: ${bashrcPath}`
278
+ )
279
+ if (bashProfilePath) {
280
+ console.log(`Bash profile configured at: ${bashProfilePath}`)
281
+ }
282
+ } catch (err) {
283
+ console.error('Failed to setup environment:', err.message)
284
+ process.exit(1)
285
+ }
286
+ })
287
+
265
288
  program
266
289
  .command('set-clash')
267
- .description('generate clash/mihomo config.yml in current directory')
268
- .option('-t, --target <path>', 'Target path for mihomo config.yml')
269
- .option('--download', 'Download Mihomo binary to the config directory')
290
+ .description('generate clash config.yml in current directory')
291
+ .option('-t, --target <path>', 'Target path for clash config.yml')
292
+ .option('--download', 'Download Clash binary to the config directory')
270
293
  .action(async (options) => {
271
294
  try {
272
- const { configPath } = writeMihomoConfig(options.target)
295
+ const { configPath } = writeClashConfig(options.target)
273
296
  const resolvedConfigPath = path.resolve(configPath)
274
297
  let mihomoCommand = 'mihomo'
275
298
 
276
299
  if (options.download) {
277
- const { binaryPath, downloadUrl, version } = await downloadMihomoBinary(
300
+ const { binaryPath, downloadUrl, version } = await downloadClashBinary(
278
301
  path.dirname(resolvedConfigPath)
279
302
  )
280
303
  mihomoCommand = path.resolve(binaryPath)
281
- console.log(`Mihomo download URL: ${downloadUrl}`)
282
- console.log(`Mihomo version: ${version}`)
283
- console.log(`Mihomo binary downloaded to: ${binaryPath}`)
304
+ console.log(`Clash download URL: ${downloadUrl}`)
305
+ console.log(`Clash version: ${version}`)
306
+ console.log(`Clash binary downloaded to: ${binaryPath}`)
284
307
  }
285
308
 
286
309
  const pm2Command = `pm2 start ${shellEscape(mihomoCommand)} --name mihomo -- -f ${shellEscape(resolvedConfigPath)} && pm2 save`
287
310
  console.log(`Clash config written to: ${configPath}`)
288
- console.log('Run Mihomo with pm2:')
311
+ console.log('Run Clash with pm2:')
289
312
  console.log(` ${pm2Command}`)
290
313
  } catch (err) {
291
314
  console.error('Failed to generate Clash config:', err.message)
@@ -24,10 +24,21 @@ async function installAllAgentsDeps(options = {}) {
24
24
  if (options.full) {
25
25
  packages.push('opencode-ai');
26
26
  }
27
- const usePnpm = await (0, utils_1.commandExists)('pnpm');
28
- if (usePnpm) {
27
+ const pnpmVersion = await (0, utils_1.getCommandVersion)('pnpm');
28
+ if (pnpmVersion !== null) {
29
29
  console.log('pnpm detected. Installing agent dependencies with pnpm...');
30
- await (0, execa_1.execa)('pnpm', ['--allow-build=@anthropic-ai/claude-code', 'add', '-g', ...packages], {
30
+ const supportsAllowBuild = (0, utils_1.pnpmSupportsAllowBuild)(pnpmVersion);
31
+ if (supportsAllowBuild) {
32
+ await (0, utils_1.allowPnpmGlobalBuild)('@anthropic-ai/claude-code');
33
+ }
34
+ await (0, execa_1.execa)('pnpm', [
35
+ ...(supportsAllowBuild
36
+ ? ['--allow-build=@anthropic-ai/claude-code']
37
+ : []),
38
+ 'add',
39
+ '-g',
40
+ ...packages,
41
+ ], {
31
42
  stdio: 'inherit',
32
43
  env: utils_1.PNPM_INSTALL_ENV,
33
44
  });
@@ -0,0 +1,8 @@
1
+ export declare function downloadClashBinary(targetDir: string): Promise<{
2
+ binaryPath: string;
3
+ downloadUrl: string;
4
+ version: string;
5
+ }>;
6
+ export declare function writeClashConfig(targetPath?: string): {
7
+ configPath: string;
8
+ };
@@ -1,14 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.downloadMihomoBinary = downloadMihomoBinary;
4
- exports.writeMihomoConfig = writeMihomoConfig;
3
+ exports.downloadClashBinary = downloadClashBinary;
4
+ exports.writeClashConfig = writeClashConfig;
5
5
  const fs = require("fs");
6
6
  const os = require("os");
7
7
  const path = require("path");
8
8
  const zlib_1 = require("zlib");
9
9
  const unzip_url_1 = require("@gengjiawen/unzip-url");
10
10
  const utils_1 = require("./utils");
11
- const MIHOMO_CONFIG_TEMPLATE = `mixed-port: 7890
11
+ const CLASH_CONFIG_TEMPLATE = `mixed-port: 7890
12
12
  mode: rule
13
13
  log-level: info
14
14
  dns:
@@ -18,11 +18,16 @@ dns:
18
18
  - 1.1.1.1
19
19
  - 223.5.5.5
20
20
  - 119.29.29.29
21
+ # Regular domain queries use these DoT upstream DNS servers plus system DNS.
22
+ nameserver:
23
+ - tls://dns.alidns.com:853
24
+ - tls://dns.google:853
25
+ - system://
21
26
  sniffer:
22
27
  enable: true
23
- sniffing:
24
- - tls
25
- - http
28
+ sniff:
29
+ TLS:
30
+ HTTP:
26
31
  tun:
27
32
  enable: true
28
33
  stack: system
@@ -53,11 +58,11 @@ rules:
53
58
  # - GEOIP,CN,DIRECT
54
59
  - MATCH,PROXY
55
60
  `;
56
- const MIHOMO_LATEST_RELEASE_API_URL = 'https://api.github.com/repos/MetaCubeX/mihomo/releases/latest';
57
- function getMihomoBinaryFilename(platform = process.platform) {
61
+ const CLASH_LATEST_RELEASE_API_URL = 'https://api.github.com/repos/MetaCubeX/mihomo/releases/latest';
62
+ function getClashBinaryFilename(platform = process.platform) {
58
63
  return platform === 'win32' ? 'mihomo.exe' : 'mihomo';
59
64
  }
60
- function getMihomoPlatformToken(platform = process.platform) {
65
+ function getClashPlatformToken(platform = process.platform) {
61
66
  switch (platform) {
62
67
  case 'linux':
63
68
  return 'linux';
@@ -66,10 +71,10 @@ function getMihomoPlatformToken(platform = process.platform) {
66
71
  case 'win32':
67
72
  return 'windows';
68
73
  default:
69
- throw new Error(`Unsupported platform for Mihomo download: ${platform}`);
74
+ throw new Error(`Unsupported platform for Clash download: ${platform}`);
70
75
  }
71
76
  }
72
- function getMihomoArchTokens(arch = process.arch) {
77
+ function getClashArchTokens(arch = process.arch) {
73
78
  switch (arch) {
74
79
  case 'x64':
75
80
  return ['amd64'];
@@ -80,10 +85,10 @@ function getMihomoArchTokens(arch = process.arch) {
80
85
  case 'ia32':
81
86
  return ['386'];
82
87
  default:
83
- throw new Error(`Unsupported architecture for Mihomo download: ${arch}`);
88
+ throw new Error(`Unsupported architecture for Clash download: ${arch}`);
84
89
  }
85
90
  }
86
- function getMihomoCpuLevelTokens(platform = process.platform, arch = process.arch) {
91
+ function getClashCpuLevelTokens(platform = process.platform, arch = process.arch) {
87
92
  if (platform !== 'linux' && platform !== 'darwin') {
88
93
  return [];
89
94
  }
@@ -92,10 +97,10 @@ function getMihomoCpuLevelTokens(platform = process.platform, arch = process.arc
92
97
  }
93
98
  return ['v3', 'v2', 'v1'];
94
99
  }
95
- function findMihomoAsset(assets, platform = process.platform, arch = process.arch) {
96
- const platformToken = getMihomoPlatformToken(platform);
97
- const archTokens = getMihomoArchTokens(arch);
98
- const cpuLevelTokens = getMihomoCpuLevelTokens(platform, arch);
100
+ function findClashAsset(assets, platform = process.platform, arch = process.arch) {
101
+ const platformToken = getClashPlatformToken(platform);
102
+ const archTokens = getClashArchTokens(arch);
103
+ const cpuLevelTokens = getClashCpuLevelTokens(platform, arch);
99
104
  const extension = platform === 'win32' ? '.zip' : '.gz';
100
105
  const candidates = assets.filter((asset) => asset.name.startsWith(`mihomo-${platformToken}-`) &&
101
106
  asset.name.endsWith(extension));
@@ -130,7 +135,7 @@ function findMihomoAsset(assets, platform = process.platform, arch = process.arc
130
135
  return fallbackMatches[0];
131
136
  }
132
137
  }
133
- throw new Error(`No Mihomo binary found for platform ${platform} and architecture ${arch}.`);
138
+ throw new Error(`No Clash binary found for platform ${platform} and architecture ${arch}.`);
134
139
  }
135
140
  function findFileRecursively(rootDir, matcher) {
136
141
  const entries = fs.readdirSync(rootDir, { withFileTypes: true });
@@ -148,30 +153,30 @@ function findFileRecursively(rootDir, matcher) {
148
153
  }
149
154
  return null;
150
155
  }
151
- async function fetchMihomoLatestRelease() {
152
- const response = await fetch(MIHOMO_LATEST_RELEASE_API_URL, {
156
+ async function fetchClashLatestRelease() {
157
+ const response = await fetch(CLASH_LATEST_RELEASE_API_URL, {
153
158
  headers: {
154
159
  Accept: 'application/vnd.github+json',
155
160
  'User-Agent': '@gengjiawen/os-init',
156
161
  },
157
162
  });
158
163
  if (!response.ok) {
159
- throw new Error(`Failed to fetch Mihomo release metadata: ${response.status} ${response.statusText}`);
164
+ throw new Error(`Failed to fetch Clash release metadata: ${response.status} ${response.statusText}`);
160
165
  }
161
166
  return (await response.json());
162
167
  }
163
- async function downloadMihomoBinary(targetDir) {
168
+ async function downloadClashBinary(targetDir) {
164
169
  (0, utils_1.ensureDir)(targetDir);
165
- const release = await fetchMihomoLatestRelease();
166
- const asset = findMihomoAsset(release.assets);
167
- const binaryPath = path.join(targetDir, getMihomoBinaryFilename());
170
+ const release = await fetchClashLatestRelease();
171
+ const asset = findClashAsset(release.assets);
172
+ const binaryPath = path.join(targetDir, getClashBinaryFilename());
168
173
  if (process.platform === 'win32') {
169
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'os-init-mihomo-'));
174
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'os-init-clash-'));
170
175
  try {
171
176
  await (0, unzip_url_1.unzip)(asset.browser_download_url, tempDir);
172
177
  const extractedBinary = findFileRecursively(tempDir, /^mihomo.*\.exe$/i);
173
178
  if (!extractedBinary) {
174
- throw new Error(`Mihomo executable was not found in asset ${asset.name}.`);
179
+ throw new Error(`Clash executable was not found in asset ${asset.name}.`);
175
180
  }
176
181
  fs.copyFileSync(extractedBinary, binaryPath);
177
182
  }
@@ -187,7 +192,7 @@ async function downloadMihomoBinary(targetDir) {
187
192
  },
188
193
  });
189
194
  if (!response.ok) {
190
- throw new Error(`Failed to download Mihomo binary: ${response.status} ${response.statusText}`);
195
+ throw new Error(`Failed to download Clash binary: ${response.status} ${response.statusText}`);
191
196
  }
192
197
  const compressedBinary = Buffer.from(await response.arrayBuffer());
193
198
  fs.writeFileSync(binaryPath, (0, zlib_1.gunzipSync)(compressedBinary));
@@ -199,9 +204,9 @@ async function downloadMihomoBinary(targetDir) {
199
204
  version: release.tag_name,
200
205
  };
201
206
  }
202
- function writeMihomoConfig(targetPath) {
207
+ function writeClashConfig(targetPath) {
203
208
  const configPath = targetPath || path.join(process.cwd(), 'config.yml');
204
209
  (0, utils_1.ensureDir)(path.dirname(configPath));
205
- fs.writeFileSync(configPath, MIHOMO_CONFIG_TEMPLATE);
210
+ fs.writeFileSync(configPath, CLASH_CONFIG_TEMPLATE);
206
211
  return { configPath };
207
212
  }
@@ -11,6 +11,7 @@ const utils_1 = require("./utils");
11
11
  const CLAUDE_BASE_URL = 'https://ai.gengjiawen.com/api/claude/';
12
12
  const CLAUDE_AUTO_COMPACT_WINDOW = '128000';
13
13
  const CLAUDE_DISABLE_1M_CONTEXT = '1';
14
+ const CLAUDE_ATTRIBUTION_HEADER = '0';
14
15
  function getClaudeSettingsDir() {
15
16
  return path.join(os.homedir(), '.claude');
16
17
  }
@@ -34,7 +35,8 @@ const CLAUDE_SETTINGS_TEMPLATE = `{
34
35
  "ANTHROPIC_BASE_URL": "${CLAUDE_BASE_URL}",
35
36
  "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
36
37
  "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "${CLAUDE_AUTO_COMPACT_WINDOW}",
37
- "CLAUDE_CODE_DISABLE_1M_CONTEXT": "${CLAUDE_DISABLE_1M_CONTEXT}"
38
+ "CLAUDE_CODE_DISABLE_1M_CONTEXT": "${CLAUDE_DISABLE_1M_CONTEXT}",
39
+ "CLAUDE_CODE_ATTRIBUTION_HEADER": "${CLAUDE_ATTRIBUTION_HEADER}"
38
40
  },
39
41
  "includeCoAuthoredBy": false,
40
42
  "apiKeyHelper": "echo 'API_KEY_PLACEHOLDER'",
@@ -76,6 +78,10 @@ function writeVSCodeClaudePluginConfig(apiKey) {
76
78
  name: 'CLAUDE_CODE_DISABLE_1M_CONTEXT',
77
79
  value: CLAUDE_DISABLE_1M_CONTEXT,
78
80
  },
81
+ {
82
+ name: 'CLAUDE_CODE_ATTRIBUTION_HEADER',
83
+ value: CLAUDE_ATTRIBUTION_HEADER,
84
+ },
79
85
  ], {
80
86
  formattingOptions: {
81
87
  insertSpaces: true,
@@ -101,10 +107,21 @@ function writeClaudeConfig(apiKey) {
101
107
  }
102
108
  async function installDeps() {
103
109
  const packages = ['@anthropic-ai/claude-code'];
104
- const usePnpm = await (0, utils_1.commandExists)('pnpm');
105
- if (usePnpm) {
110
+ const pnpmVersion = await (0, utils_1.getCommandVersion)('pnpm');
111
+ if (pnpmVersion !== null) {
106
112
  console.log('pnpm detected. Installing dependencies with pnpm...');
107
- await (0, execa_1.execa)('pnpm', ['--allow-build=@anthropic-ai/claude-code', 'add', '-g', ...packages], {
113
+ const supportsAllowBuild = (0, utils_1.pnpmSupportsAllowBuild)(pnpmVersion);
114
+ if (supportsAllowBuild) {
115
+ await (0, utils_1.allowPnpmGlobalBuild)('@anthropic-ai/claude-code');
116
+ }
117
+ await (0, execa_1.execa)('pnpm', [
118
+ ...(supportsAllowBuild
119
+ ? ['--allow-build=@anthropic-ai/claude-code']
120
+ : []),
121
+ 'add',
122
+ '-g',
123
+ ...packages,
124
+ ], {
108
125
  stdio: 'inherit',
109
126
  env: utils_1.PNPM_INSTALL_ENV,
110
127
  });
package/build/index.d.ts CHANGED
@@ -7,5 +7,6 @@ export { writeOpencodeConfig, installOpencodeDeps } from './opencode';
7
7
  export { writeAllAgentsConfig, installAllAgentsDeps } from './all-agents';
8
8
  export { setupDevEnvironment } from './dev-setup';
9
9
  export { setupAndroidEnvironment } from './android-setup';
10
- export { writeMihomoConfig, downloadMihomoBinary } from './mihomo';
10
+ export { writeClashConfig, downloadClashBinary } from './clash';
11
+ export { setupEnv } from './setup-env';
11
12
  export { CURSOR_TYPESCRIPT_EXTENSION_ID, disableCursorTypescriptExtension, getCursorStateDbPath, mergeDisabledExtension, } from './cursor';
package/build/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mergeDisabledExtension = exports.getCursorStateDbPath = exports.disableCursorTypescriptExtension = exports.CURSOR_TYPESCRIPT_EXTENSION_ID = exports.downloadMihomoBinary = exports.writeMihomoConfig = exports.setupAndroidEnvironment = exports.setupDevEnvironment = exports.installAllAgentsDeps = exports.writeAllAgentsConfig = exports.installOpencodeDeps = exports.writeOpencodeConfig = exports.installCodexDeps = exports.writeCodexConfig = exports.installDeps = exports.writeClaudeConfig = void 0;
3
+ exports.mergeDisabledExtension = exports.getCursorStateDbPath = exports.disableCursorTypescriptExtension = exports.CURSOR_TYPESCRIPT_EXTENSION_ID = exports.setupEnv = exports.downloadClashBinary = exports.writeClashConfig = exports.setupAndroidEnvironment = exports.setupDevEnvironment = exports.installAllAgentsDeps = exports.writeAllAgentsConfig = exports.installOpencodeDeps = exports.writeOpencodeConfig = exports.installCodexDeps = exports.writeCodexConfig = exports.installDeps = exports.writeClaudeConfig = void 0;
4
4
  exports.writeRaycastConfig = writeRaycastConfig;
5
5
  const fs = require("fs");
6
6
  const path = require("path");
@@ -54,9 +54,11 @@ var dev_setup_1 = require("./dev-setup");
54
54
  Object.defineProperty(exports, "setupDevEnvironment", { enumerable: true, get: function () { return dev_setup_1.setupDevEnvironment; } });
55
55
  var android_setup_1 = require("./android-setup");
56
56
  Object.defineProperty(exports, "setupAndroidEnvironment", { enumerable: true, get: function () { return android_setup_1.setupAndroidEnvironment; } });
57
- var mihomo_1 = require("./mihomo");
58
- Object.defineProperty(exports, "writeMihomoConfig", { enumerable: true, get: function () { return mihomo_1.writeMihomoConfig; } });
59
- Object.defineProperty(exports, "downloadMihomoBinary", { enumerable: true, get: function () { return mihomo_1.downloadMihomoBinary; } });
57
+ var clash_1 = require("./clash");
58
+ Object.defineProperty(exports, "writeClashConfig", { enumerable: true, get: function () { return clash_1.writeClashConfig; } });
59
+ Object.defineProperty(exports, "downloadClashBinary", { enumerable: true, get: function () { return clash_1.downloadClashBinary; } });
60
+ var setup_env_1 = require("./setup-env");
61
+ Object.defineProperty(exports, "setupEnv", { enumerable: true, get: function () { return setup_env_1.setupEnv; } });
60
62
  var cursor_1 = require("./cursor");
61
63
  Object.defineProperty(exports, "CURSOR_TYPESCRIPT_EXTENSION_ID", { enumerable: true, get: function () { return cursor_1.CURSOR_TYPESCRIPT_EXTENSION_ID; } });
62
64
  Object.defineProperty(exports, "disableCursorTypescriptExtension", { enumerable: true, get: function () { return cursor_1.disableCursorTypescriptExtension; } });
@@ -0,0 +1,5 @@
1
+ export declare function setupEnv(): {
2
+ bashrcPath: string;
3
+ bashProfilePath?: string;
4
+ changed: boolean;
5
+ };
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setupEnv = setupEnv;
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const os = require("os");
7
+ const MARKER_START = '# ===== os-init setup-env - START =====';
8
+ const MARKER_END = '# ===== os-init setup-env - END =====';
9
+ const BASH_PROFILE_MARKER_START = '# ===== os-init setup-env bash_profile - START =====';
10
+ const BASH_PROFILE_MARKER_END = '# ===== os-init setup-env bash_profile - END =====';
11
+ function getBrewPrefix() {
12
+ if (process.platform === 'darwin') {
13
+ if (fs.existsSync('/opt/homebrew/bin/brew')) {
14
+ return '/opt/homebrew';
15
+ }
16
+ return '/usr/local';
17
+ }
18
+ return '/home/linuxbrew/.linuxbrew';
19
+ }
20
+ function getPnpmHome() {
21
+ const home = os.homedir();
22
+ if (process.platform === 'darwin') {
23
+ return path.join(home, 'Library', 'pnpm');
24
+ }
25
+ return path.join(home, '.pnpm');
26
+ }
27
+ function generateBashrcContent() {
28
+ const brewPrefix = getBrewPrefix();
29
+ const home = os.homedir();
30
+ const pnpmHome = getPnpmHome();
31
+ const cargoHome = path.join(home, '.cargo');
32
+ const rustupHome = path.join(home, '.rustup');
33
+ const pathEntries = [
34
+ `${brewPrefix}/bin`,
35
+ `${brewPrefix}/sbin`,
36
+ pnpmHome,
37
+ `${cargoHome}/bin`,
38
+ `${home}/.jsvu/bin`,
39
+ `${home}/.local/bin`,
40
+ `${home}/.yarn/bin`,
41
+ ];
42
+ if (process.platform === 'darwin') {
43
+ pathEntries.push(`${rustupHome}/toolchains/stable-aarch64-apple-darwin/bin`);
44
+ }
45
+ return `${MARKER_START}
46
+ export PNPM_HOME="${pnpmHome}"
47
+ export RUSTUP_HOME="${rustupHome}"
48
+ export CARGO_HOME="${cargoHome}"
49
+ export PATH="${pathEntries.join(':')}:$PATH"
50
+ ${MARKER_END}
51
+ `;
52
+ }
53
+ function generateBashProfileContent() {
54
+ return `${BASH_PROFILE_MARKER_START}
55
+ if [ -f "$HOME/.bashrc" ]; then
56
+ . "$HOME/.bashrc"
57
+ fi
58
+ ${BASH_PROFILE_MARKER_END}
59
+ `;
60
+ }
61
+ function stripLeadingNewline(content) {
62
+ if (content.startsWith('\r\n')) {
63
+ return content.slice(2);
64
+ }
65
+ if (content.startsWith('\n')) {
66
+ return content.slice(1);
67
+ }
68
+ return content;
69
+ }
70
+ function bashProfileSourcesBashrc(content) {
71
+ return content
72
+ .split(/\r?\n/)
73
+ .some((line) => /^\s*(?:source|\.)\s+(?:"\$HOME\/\.bashrc"|'\$HOME\/\.bashrc'|\$HOME\/\.bashrc|~\/\.bashrc)(?:\s|$)/.test(line));
74
+ }
75
+ function ensureMacBashProfileSourcesBashrc(home) {
76
+ const bashProfilePath = path.join(home, '.bash_profile');
77
+ let currentContent = '';
78
+ if (fs.existsSync(bashProfilePath)) {
79
+ currentContent = fs.readFileSync(bashProfilePath, 'utf-8');
80
+ }
81
+ if (currentContent.includes(BASH_PROFILE_MARKER_START) ||
82
+ bashProfileSourcesBashrc(currentContent)) {
83
+ return { bashProfilePath, changed: false };
84
+ }
85
+ const newBlock = (currentContent && !currentContent.endsWith('\n') ? '\n' : '') +
86
+ generateBashProfileContent();
87
+ fs.appendFileSync(bashProfilePath, newBlock);
88
+ return { bashProfilePath, changed: true };
89
+ }
90
+ function setupEnv() {
91
+ const home = os.homedir();
92
+ const bashrcPath = path.join(home, '.bashrc');
93
+ let currentContent = '';
94
+ if (fs.existsSync(bashrcPath)) {
95
+ currentContent = fs.readFileSync(bashrcPath, 'utf-8');
96
+ }
97
+ if (currentContent.includes(MARKER_START)) {
98
+ const startIdx = currentContent.indexOf(MARKER_START);
99
+ const endIdx = currentContent.indexOf(MARKER_END, startIdx);
100
+ if (endIdx !== -1) {
101
+ const before = currentContent.slice(0, startIdx);
102
+ const after = stripLeadingNewline(currentContent.slice(endIdx + MARKER_END.length));
103
+ const newBlock = generateBashrcContent();
104
+ const nextContent = before + newBlock + after;
105
+ const bashrcChanged = nextContent !== currentContent;
106
+ if (bashrcChanged) {
107
+ fs.writeFileSync(bashrcPath, nextContent);
108
+ }
109
+ if (process.platform === 'darwin') {
110
+ const profileResult = ensureMacBashProfileSourcesBashrc(home);
111
+ return {
112
+ bashrcPath,
113
+ bashProfilePath: profileResult.bashProfilePath,
114
+ changed: bashrcChanged || profileResult.changed,
115
+ };
116
+ }
117
+ return { bashrcPath, changed: bashrcChanged };
118
+ }
119
+ }
120
+ const newBlock = (currentContent && !currentContent.endsWith('\n') ? '\n' : '') +
121
+ generateBashrcContent();
122
+ fs.appendFileSync(bashrcPath, newBlock);
123
+ if (process.platform === 'darwin') {
124
+ const profileResult = ensureMacBashProfileSourcesBashrc(home);
125
+ return {
126
+ bashrcPath,
127
+ bashProfilePath: profileResult.bashProfilePath,
128
+ changed: true,
129
+ };
130
+ }
131
+ return { bashrcPath, changed: true };
132
+ }
package/build/utils.d.ts CHANGED
@@ -2,4 +2,7 @@ export declare const PNPM_INSTALL_ENV: {
2
2
  PNPM_CONFIG_ENABLE_PRE_POST_SCRIPTS: string;
3
3
  };
4
4
  export declare function ensureDir(dirPath: string): void;
5
+ export declare function getCommandVersion(command: string): Promise<string | null>;
6
+ export declare function pnpmSupportsAllowBuild(version: string): boolean;
7
+ export declare function allowPnpmGlobalBuild(packageName: string): Promise<void>;
5
8
  export declare function commandExists(command: string): Promise<boolean>;
package/build/utils.js CHANGED
@@ -2,24 +2,60 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PNPM_INSTALL_ENV = void 0;
4
4
  exports.ensureDir = ensureDir;
5
+ exports.getCommandVersion = getCommandVersion;
6
+ exports.pnpmSupportsAllowBuild = pnpmSupportsAllowBuild;
7
+ exports.allowPnpmGlobalBuild = allowPnpmGlobalBuild;
5
8
  exports.commandExists = commandExists;
6
9
  const fs = require("fs");
10
+ const path = require("path");
7
11
  const execa_1 = require("execa");
12
+ const yaml = require("yaml");
8
13
  exports.PNPM_INSTALL_ENV = {
9
14
  PNPM_CONFIG_ENABLE_PRE_POST_SCRIPTS: 'true',
10
15
  };
11
16
  function ensureDir(dirPath) {
12
17
  fs.mkdirSync(dirPath, { recursive: true });
13
18
  }
14
- async function commandExists(command) {
19
+ async function getCommandVersion(command) {
15
20
  try {
16
- const { failed } = await (0, execa_1.execa)(command, ['--version'], {
17
- stdio: 'ignore',
21
+ const { failed, stdout } = await (0, execa_1.execa)(command, ['--version'], {
22
+ stdio: 'pipe',
18
23
  reject: false,
19
24
  });
20
- return !failed;
25
+ return failed ? null : stdout.trim();
21
26
  }
22
27
  catch (error) {
23
- return false;
28
+ return null;
24
29
  }
25
30
  }
31
+ function pnpmSupportsAllowBuild(version) {
32
+ const major = Number.parseInt(version, 10);
33
+ return Number.isInteger(major) && major >= 10;
34
+ }
35
+ function isRecord(value) {
36
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
37
+ }
38
+ async function allowPnpmGlobalBuild(packageName) {
39
+ const { stdout } = await (0, execa_1.execa)('pnpm', ['root', '-g']);
40
+ const globalRoot = stdout.trim();
41
+ if (globalRoot.length === 0) {
42
+ throw new Error('Unable to locate pnpm global root.');
43
+ }
44
+ ensureDir(globalRoot);
45
+ const workspacePath = path.join(globalRoot, 'pnpm-workspace.yaml');
46
+ const source = fs.existsSync(workspacePath)
47
+ ? fs.readFileSync(workspacePath, 'utf8')
48
+ : '';
49
+ const parsed = source.trim().length > 0 ? yaml.parse(source) : {};
50
+ const workspace = isRecord(parsed) ? parsed : {};
51
+ const existingAllowBuilds = workspace.allowBuilds;
52
+ const allowBuilds = isRecord(existingAllowBuilds)
53
+ ? { ...existingAllowBuilds }
54
+ : {};
55
+ allowBuilds[packageName] = true;
56
+ workspace.allowBuilds = allowBuilds;
57
+ fs.writeFileSync(workspacePath, yaml.stringify(workspace));
58
+ }
59
+ async function commandExists(command) {
60
+ return (await getCommandVersion(command)) !== null;
61
+ }