ai-profile-switch 0.0.0-stage → 2.2.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/src/lib/ui.mjs ADDED
@@ -0,0 +1,89 @@
1
+ // ANSI colors, terminal capability detection, and box-drawing helpers.
2
+ // Single source for any module that writes to stdout/stderr.
3
+
4
+ export const hasColor = Boolean(process.stdout.isTTY || process.env.FORCE_COLOR)
5
+ && !process.env.NO_COLOR
6
+ && process.env.TERM !== 'dumb';
7
+
8
+ // On legacy Windows consoles (cmd.exe without UTF-8 codepage), Unicode box
9
+ // characters may not render. Detect via the WT_SESSION env var (set by
10
+ // Windows Terminal) or non-Windows platforms.
11
+ export const supportsUnicode = Boolean(
12
+ process.env.WT_SESSION
13
+ || process.env.TERM_PROGRAM
14
+ || process.platform !== 'win32'
15
+ );
16
+
17
+ const ESC = '\x1b[';
18
+ const RESET = hasColor ? `${ESC}0m` : '';
19
+ const c = (code) => hasColor ? `${ESC}${code}m` : '';
20
+
21
+ export const color = {
22
+ bold: (s) => `${c('1')}${s}${RESET}`,
23
+ dim: (s) => `${c('2')}${s}${RESET}`,
24
+ green: (s) => `${c('32')}${s}${RESET}`,
25
+ yellow: (s) => `${c('33')}${s}${RESET}`,
26
+ blue: (s) => `${c('34')}${s}${RESET}`,
27
+ cyan: (s) => `${c('36')}${s}${RESET}`,
28
+ red: (s) => `${c('31')}${s}${RESET}`,
29
+ };
30
+
31
+ export function cursorControl(output = process.stdout) {
32
+ const enabled = Boolean(output.isTTY) && process.env.TERM !== 'dumb';
33
+ return {
34
+ enabled,
35
+ up: (n) => enabled ? `${ESC}${n}A` : '',
36
+ clearLine: enabled ? `${ESC}2K` : '',
37
+ clearDown: enabled ? `${ESC}0J` : '',
38
+ };
39
+ }
40
+
41
+ // Symbols with ASCII fallback for non-Unicode terminals.
42
+ export const sym = {
43
+ check: supportsUnicode ? '✓' : 'v',
44
+ warn: supportsUnicode ? '⚠' : '!',
45
+ cross: supportsUnicode ? '✗' : 'x',
46
+ info: supportsUnicode ? 'ℹ' : 'i',
47
+ arrow: supportsUnicode ? '›' : '>',
48
+ cursor: supportsUnicode ? '❯' : '>',
49
+ dots: supportsUnicode ? '…' : '...',
50
+ bulletOn: supportsUnicode ? '●' : '*',
51
+ bulletOff: supportsUnicode ? '○' : 'o',
52
+ dash: supportsUnicode ? '──' : '--',
53
+ };
54
+
55
+ const BOX_TL = supportsUnicode ? '╭' : '+';
56
+ const BOX_TR = supportsUnicode ? '╮' : '+';
57
+ const BOX_BL = supportsUnicode ? '╰' : '+';
58
+ const BOX_BR = supportsUnicode ? '╯' : '+';
59
+ const BOX_H = supportsUnicode ? '─' : '-';
60
+ const BOX_V = supportsUnicode ? '│' : '|';
61
+
62
+ export function box(lines) {
63
+ const maxLen = Math.max(...lines.map(stripAnsi).map(l => l.length));
64
+ const pad = (s) => s + ' '.repeat(maxLen - stripAnsi(s).length);
65
+ const top = ` ${BOX_TL}${BOX_H.repeat(maxLen + 2)}${BOX_TR}`;
66
+ const bottom = ` ${BOX_BL}${BOX_H.repeat(maxLen + 2)}${BOX_BR}`;
67
+ const body = lines.map(l => ` ${BOX_V} ${pad(l)} ${BOX_V}`).join('\n');
68
+ return `${top}\n${body}\n${bottom}`;
69
+ }
70
+
71
+ export function success(msg) {
72
+ process.stdout.write(` ${color.green(sym.check)} ${msg}\n`);
73
+ }
74
+
75
+ export function warn(msg) {
76
+ process.stdout.write(` ${color.yellow(sym.warn)} ${msg}\n`);
77
+ }
78
+
79
+ export function error(msg) {
80
+ process.stderr.write(` ${color.red(sym.cross)} ${msg}\n`);
81
+ }
82
+
83
+ export function info(msg) {
84
+ process.stdout.write(` ${color.blue(sym.info)} ${msg}\n`);
85
+ }
86
+
87
+ export function stripAnsi(s) {
88
+ return s.replace(/\x1b\[[0-9;]*m/g, '');
89
+ }
@@ -0,0 +1,55 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { SELF_PKG } from './constants.mjs';
5
+
6
+ export function parseSemver(value) {
7
+ if (typeof value !== 'string') throw new Error(`Invalid version: ${value}`);
8
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+[\w.-]+)?$/.exec(value);
9
+ if (!match) throw new Error(`Invalid version: ${value}`);
10
+ return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] ?? null };
11
+ }
12
+
13
+ export function compareSemver(a, b) {
14
+ const left = parseSemver(a);
15
+ const right = parseSemver(b);
16
+ for (const key of ['major', 'minor', 'patch']) {
17
+ if (left[key] !== right[key]) return left[key] > right[key] ? 1 : -1;
18
+ }
19
+ if (left.pre === right.pre) return 0;
20
+ if (!left.pre) return 1;
21
+ if (!right.pre) return -1;
22
+ const leftParts = left.pre.split('.');
23
+ const rightParts = right.pre.split('.');
24
+ for (let i = 0; i < Math.max(leftParts.length, rightParts.length); i++) {
25
+ if (leftParts[i] === rightParts[i]) continue;
26
+ if (leftParts[i] === undefined) return -1;
27
+ if (rightParts[i] === undefined) return 1;
28
+ const leftNumeric = /^\d+$/.test(leftParts[i]);
29
+ const rightNumeric = /^\d+$/.test(rightParts[i]);
30
+ if (leftNumeric && rightNumeric) return Number(leftParts[i]) > Number(rightParts[i]) ? 1 : -1;
31
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
32
+ return leftParts[i] > rightParts[i] ? 1 : -1;
33
+ }
34
+ return 0;
35
+ }
36
+
37
+ export async function fetchLatestVersion(pkg = SELF_PKG) {
38
+ const registry = process.env.CAS_TEST_REGISTRY_URL || 'https://registry.npmjs.org';
39
+ let response;
40
+ try {
41
+ response = await fetch(`${registry}/${pkg.replace('/', '%2f')}/latest`, { signal: AbortSignal.timeout(5000) });
42
+ } catch (err) {
43
+ throw new Error(`Could not reach the package registry: ${err.message}`, { cause: err });
44
+ }
45
+ if (!response.ok) throw new Error(`Registry returned HTTP ${response.status}`);
46
+ const data = await response.json();
47
+ parseSemver(data.version);
48
+ return data.version;
49
+ }
50
+
51
+ export async function computeUpdatePlan({ fetchVersion = fetchLatestVersion } = {}) {
52
+ const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../../package.json'), 'utf8'));
53
+ const latest = await fetchVersion(SELF_PKG);
54
+ return { self: { pkg: SELF_PKG, installed: pkg.version, latest, hasUpdate: compareSemver(pkg.version, latest) < 0 } };
55
+ }
@@ -0,0 +1,32 @@
1
+ # Claude Switch fish integration
2
+
3
+ function __claude_switch_cli
4
+ set -l runtime "$HOME/.claude-profiles/_runtime/bin/cli.mjs"
5
+ if not test -f "$runtime"; or not command -q node
6
+ echo 'Shell runtime unavailable. Run: npx ai-profile-switch@latest install-shell' >&2
7
+ return 127
8
+ end
9
+ command node "$runtime" $argv
10
+ end
11
+
12
+ function __claude_switch_launch
13
+ set -l profile $argv[1]
14
+ set -e argv[1]
15
+ set -l hook "$HOME/.claude-profiles/$profile/pre-launch.fish"
16
+ command fish -c 'set -l hook $argv[1]; set -e argv[1]; if test -f "$hook"; source "$hook"; or exit $status; end; exec $argv' "$hook" node "$HOME/.claude-profiles/_runtime/bin/cli.mjs" shell launch --profile "$profile" -- $argv
17
+ end
18
+
19
+ function claude
20
+ set -l selected (__claude_switch_cli shell pick --print)
21
+ or return $status
22
+ test -n "$selected"; or return 1
23
+ __claude_switch_launch "$selected" $argv
24
+ end
25
+
26
+ function cpf
27
+ __claude_switch_cli manage $argv
28
+ end
29
+
30
+ function claude-pick
31
+ __claude_switch_cli shell pick
32
+ end
@@ -0,0 +1,78 @@
1
+ # Claude Switch PowerShell integration
2
+
3
+ function __claude_switch_cli {
4
+ $profileHome = $env:USERPROFILE
5
+ if (!$profileHome) { $profileHome = $env:HOME }
6
+ $runtime = Join-Path $profileHome '.claude-profiles/_runtime/bin/cli.mjs'
7
+ $node = Get-Command node -CommandType Application -ErrorAction SilentlyContinue
8
+ if (!(Test-Path $runtime) -or !$node) {
9
+ $global:LASTEXITCODE = 127
10
+ Write-Error 'Shell runtime unavailable. Run: npx ai-profile-switch@latest install-shell' -ErrorAction Continue
11
+ return
12
+ }
13
+ $hadTransport = Test-Path Env:CLAUDE_SWITCH_ARGV
14
+ $previousTransport = $env:CLAUDE_SWITCH_ARGV
15
+ $previousEncoding = [Console]::OutputEncoding
16
+ $exitCode = 1
17
+ try {
18
+ $payload = ConvertTo-Json -Compress -Depth 3 -InputObject @{
19
+ runtime = $runtime
20
+ args = @($args)
21
+ previous = $previousTransport
22
+ }
23
+ $env:CLAUDE_SWITCH_ARGV = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($payload))
24
+ $bootstrap = @'
25
+ const payload = JSON.parse(Buffer.from(process.env.CLAUDE_SWITCH_ARGV, 'base64').toString('utf8'));
26
+ if (payload.previous === null) delete process.env.CLAUDE_SWITCH_ARGV;
27
+ else process.env.CLAUDE_SWITCH_ARGV = payload.previous;
28
+ process.argv = [process.execPath, payload.runtime, ...payload.args];
29
+ await import((await import('node:url')).pathToFileURL(payload.runtime).href);
30
+ '@
31
+ $ErrorActionPreference = 'Continue'
32
+ $PSNativeCommandUseErrorActionPreference = $false
33
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
34
+ & $node.Source --input-type=module --eval $bootstrap
35
+ $exitCode = $LASTEXITCODE
36
+ } finally {
37
+ [Console]::OutputEncoding = $previousEncoding
38
+ if ($hadTransport) { $env:CLAUDE_SWITCH_ARGV = $previousTransport }
39
+ else { Remove-Item Env:CLAUDE_SWITCH_ARGV -ErrorAction SilentlyContinue }
40
+ $global:LASTEXITCODE = $exitCode
41
+ }
42
+ }
43
+
44
+ function __claude_switch_launch {
45
+ $profile = $args[0]
46
+ $forwarded = @($args | Select-Object -Skip 1)
47
+ $profileHome = $env:USERPROFILE
48
+ if (!$profileHome) { $profileHome = $env:HOME }
49
+ $hook = Join-Path $profileHome ".claude-profiles/$profile/pre-launch.ps1"
50
+ $saved = @{}
51
+ Get-ChildItem Env: | ForEach-Object { $saved[$_.Name] = $_.Value }
52
+ try {
53
+ if (Test-Path $hook) {
54
+ $ErrorActionPreference = 'Stop'
55
+ $global:LASTEXITCODE = 0
56
+ . $hook
57
+ if (!$? -or $LASTEXITCODE -ne 0) { return }
58
+ }
59
+ __claude_switch_cli shell launch --profile $profile '--' @forwarded
60
+ } catch {
61
+ if (!$LASTEXITCODE) { $global:LASTEXITCODE = 1 }
62
+ Write-Error $_ -ErrorAction Continue
63
+ } finally {
64
+ Get-ChildItem Env: | ForEach-Object {
65
+ if (!$saved.ContainsKey($_.Name)) { Remove-Item "Env:$($_.Name)" }
66
+ }
67
+ foreach ($name in $saved.Keys) { Set-Item "Env:$name" $saved[$name] }
68
+ }
69
+ }
70
+
71
+ function claude {
72
+ $selected = __claude_switch_cli shell pick --print
73
+ if ($LASTEXITCODE -ne 0 -or !$selected) { return }
74
+ __claude_switch_launch $selected @args
75
+ }
76
+
77
+ function cpf { __claude_switch_cli manage @args }
78
+ function claude-pick { __claude_switch_cli shell pick }
@@ -0,0 +1,38 @@
1
+ #!/bin/sh
2
+ # Claude Switch shell integration
3
+
4
+ __claude_switch_cli() {
5
+ local runtime="$HOME/.claude-profiles/_runtime/bin/cli.mjs"
6
+ if [ ! -f "$runtime" ] || ! command -v node >/dev/null 2>&1; then
7
+ printf 'Shell runtime unavailable. Run: npx ai-profile-switch@latest install-shell\n' >&2
8
+ return 127
9
+ fi
10
+ command node "$runtime" "$@"
11
+ }
12
+
13
+ __claude_switch_launch() (
14
+ local profile="$1"
15
+ shift
16
+ local hook="$HOME/.claude-profiles/$profile/pre-launch.sh"
17
+ if [ -f "$hook" ]; then
18
+ set -a
19
+ . "$hook" || return $?
20
+ set +a
21
+ fi
22
+ __claude_switch_cli shell launch --profile "$profile" -- "$@"
23
+ )
24
+
25
+ claude() {
26
+ local selected
27
+ selected=$(__claude_switch_cli shell pick --print) || return $?
28
+ [ -n "$selected" ] || return 1
29
+ __claude_switch_launch "$selected" "$@"
30
+ }
31
+
32
+ cpf() {
33
+ __claude_switch_cli manage "$@"
34
+ }
35
+
36
+ claude-pick() {
37
+ __claude_switch_cli shell pick
38
+ }