@traylinx/switchailocal 0.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.
Files changed (3) hide show
  1. package/README.md +37 -0
  2. package/bin.js +267 -0
  3. package/package.json +28 -0
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # switchAILocal
2
+
3
+ One local endpoint. All your AI providers.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ npx @traylinx/switchailocal
9
+ ```
10
+
11
+ That's it. This downloads and runs the switchAILocal binary for your platform.
12
+
13
+ ## What is switchAILocal?
14
+
15
+ A unified AI API gateway that runs locally, providing a single OpenAI-compatible endpoint (`http://localhost:18080`) to access all your AI providers seamlessly.
16
+
17
+ **Supported providers:** OpenAI, Claude, Gemini, Ollama, LM Studio, Groq, OpenRouter, and many more.
18
+
19
+ ## Options
20
+
21
+ ```bash
22
+ # Run a specific version
23
+ npx @traylinx/switchailocal --version=v1.0.0
24
+
25
+ # Pass flags to switchAILocal
26
+ npx @traylinx/switchailocal --port 8080
27
+ ```
28
+
29
+ ## Configuration
30
+
31
+ On first run, a default config is created at `~/.switchailocal/config.yaml`. Edit it to add your API keys.
32
+
33
+ ## Links
34
+
35
+ - [GitHub](https://github.com/traylinx/switchAILocal)
36
+ - [Documentation](https://github.com/traylinx/switchAILocal#readme)
37
+ - [Docker](https://github.com/traylinx/switchAILocal/pkgs/container/switchailocal)
package/bin.js ADDED
@@ -0,0 +1,267 @@
1
+ #!/usr/bin/env node
2
+
3
+ // switchAILocal npx launcher
4
+ // Downloads the pre-built binary for the current platform and runs it.
5
+ // Binary source: GitHub Releases (https://github.com/traylinx/switchAILocal/releases)
6
+
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ import { createWriteStream, existsSync, mkdirSync, chmodSync, unlinkSync, writeFileSync } from "node:fs";
9
+ import { get as httpsGet } from "node:https";
10
+ import { homedir, platform, arch } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ const REPO = "traylinx/switchAILocal";
14
+ const BINARY_NAME = "switchAILocal";
15
+ const DEFAULT_PORT = 18080;
16
+
17
+ // ── Platform Detection ──────────────────────────────────────────
18
+
19
+ function getPlatform() {
20
+ const p = platform();
21
+ const a = arch();
22
+
23
+ const osMap = { darwin: "darwin", linux: "linux", win32: "windows" };
24
+ const archMap = { arm64: "arm64", x64: "amd64", ia32: "386" };
25
+
26
+ const os = osMap[p];
27
+ const cpu = archMap[a];
28
+
29
+ if (!os || !cpu) {
30
+ console.error(`Unsupported platform: ${p}/${a}`);
31
+ process.exit(1);
32
+ }
33
+
34
+ const ext = os === "windows" ? ".zip" : ".tar.gz";
35
+ const bin = os === "windows" ? `${BINARY_NAME}.exe` : BINARY_NAME;
36
+
37
+ return { os, arch: cpu, ext, bin };
38
+ }
39
+
40
+ // ── Version Resolution ──────────────────────────────────────────
41
+
42
+ function parseVersion(args) {
43
+ for (let i = 0; i < args.length; i++) {
44
+ if (args[i] === "--version" && args[i + 1]) {
45
+ args.splice(i, 2);
46
+ return args[i + 1];
47
+ }
48
+ if (args[i].startsWith("--version=")) {
49
+ const ver = args[i].split("=")[1];
50
+ args.splice(i, 1);
51
+ return ver;
52
+ }
53
+ }
54
+ return "latest";
55
+ }
56
+
57
+ async function resolveLatestVersion() {
58
+ return new Promise((resolve, reject) => {
59
+ const options = {
60
+ hostname: "api.github.com",
61
+ path: `/repos/${REPO}/releases/latest`,
62
+ headers: { "User-Agent": "switchailocal-npx" },
63
+ };
64
+ httpsGet(options, (res) => {
65
+ if (res.statusCode === 302 || res.statusCode === 301) {
66
+ // Follow redirect
67
+ httpsGet(res.headers.location, { headers: options.headers }, handleResponse);
68
+ return;
69
+ }
70
+ handleResponse(res);
71
+ }).on("error", reject);
72
+
73
+ function handleResponse(res) {
74
+ let data = "";
75
+ res.on("data", (chunk) => (data += chunk));
76
+ res.on("end", () => {
77
+ try {
78
+ const release = JSON.parse(data);
79
+ if (release.tag_name) {
80
+ resolve(release.tag_name);
81
+ } else {
82
+ reject(new Error("No releases found"));
83
+ }
84
+ } catch (e) {
85
+ reject(e);
86
+ }
87
+ });
88
+ res.on("error", reject);
89
+ }
90
+ });
91
+ }
92
+
93
+ // ── Cache Directory ─────────────────────────────────────────────
94
+
95
+ function getCacheDir(version) {
96
+ const home = homedir();
97
+ let base;
98
+ switch (platform()) {
99
+ case "darwin":
100
+ base = join(home, "Library", "Caches", "switchailocal");
101
+ break;
102
+ case "win32":
103
+ base = join(process.env.LOCALAPPDATA || join(home, "AppData", "Local"), "switchailocal");
104
+ break;
105
+ default:
106
+ base = join(process.env.XDG_CACHE_HOME || join(home, ".cache"), "switchailocal");
107
+ }
108
+ return join(base, version, "bin");
109
+ }
110
+
111
+ // ── Download ────────────────────────────────────────────────────
112
+
113
+ function followRedirects(url) {
114
+ return new Promise((resolve, reject) => {
115
+ httpsGet(url, { headers: { "User-Agent": "switchailocal-npx" } }, (res) => {
116
+ if (res.statusCode === 302 || res.statusCode === 301) {
117
+ followRedirects(res.headers.location).then(resolve, reject);
118
+ return;
119
+ }
120
+ if (res.statusCode !== 200) {
121
+ reject(new Error(`HTTP ${res.statusCode} fetching ${url}`));
122
+ return;
123
+ }
124
+ resolve(res);
125
+ }).on("error", reject);
126
+ });
127
+ }
128
+
129
+ async function downloadAndExtract(version, plat, destDir) {
130
+ // GoReleaser strips the 'v' prefix from the version in archive names
131
+ // but the GitHub release tag keeps it. e.g. tag=v1.0.0, archive=switchAILocal_1.0.0_...
132
+ const archiveVersion = version.startsWith("v") ? version.slice(1) : version;
133
+ const archiveName = `${BINARY_NAME}_${archiveVersion}_${plat.os}_${plat.arch}${plat.ext}`;
134
+ const url = `https://github.com/${REPO}/releases/download/${version}/${archiveName}`;
135
+
136
+ console.log(`Downloading switchAILocal ${version} for ${plat.os}/${plat.arch}...`);
137
+
138
+ mkdirSync(destDir, { recursive: true });
139
+ const tmpFile = join(destDir, `download-${process.pid}.tmp`);
140
+
141
+ try {
142
+ const res = await followRedirects(url);
143
+ const total = parseInt(res.headers["content-length"], 10) || 0;
144
+ let downloaded = 0;
145
+
146
+ await new Promise((resolve, reject) => {
147
+ const ws = createWriteStream(tmpFile);
148
+ res.on("data", (chunk) => {
149
+ downloaded += chunk.length;
150
+ if (total > 0) {
151
+ const pct = ((downloaded / total) * 100).toFixed(0);
152
+ const mb = (downloaded / 1048576).toFixed(1);
153
+ process.stdout.write(`\r ${pct}% (${mb} MB)`);
154
+ }
155
+ });
156
+ res.pipe(ws);
157
+ ws.on("finish", () => { console.log(""); resolve(); });
158
+ ws.on("error", reject);
159
+ res.on("error", reject);
160
+ });
161
+
162
+ // Extract — only the binary from the archive
163
+ if (plat.ext === ".tar.gz") {
164
+ execFileSync("tar", ["xzf", tmpFile, "-C", destDir, "--include", plat.bin], { stdio: "pipe" });
165
+ } else {
166
+ // Windows: use PowerShell to extract
167
+ execFileSync("powershell", [
168
+ "-Command",
169
+ `Expand-Archive -Path '${tmpFile}' -DestinationPath '${destDir}' -Force`,
170
+ ], { stdio: "pipe" });
171
+ }
172
+
173
+ chmodSync(join(destDir, plat.bin), 0o755);
174
+ } finally {
175
+ try { unlinkSync(tmpFile); } catch {}
176
+ }
177
+ }
178
+
179
+ // ── Config Setup ────────────────────────────────────────────────
180
+
181
+ function ensureConfig() {
182
+ const home = homedir();
183
+ const configDir = join(home, ".switchailocal");
184
+ const configFile = join(configDir, "config.yaml");
185
+
186
+ if (!existsSync(configFile)) {
187
+ mkdirSync(configDir, { recursive: true });
188
+ const defaultConfig = `# switchAILocal configuration
189
+ # See: https://github.com/traylinx/switchAILocal#configuration
190
+
191
+ port: ${DEFAULT_PORT}
192
+
193
+ # Uncomment and add your API keys:
194
+ # gemini-api-key:
195
+ # - api-key: "your-gemini-key"
196
+ # claude-api-key:
197
+ # - api-key: "your-claude-key"
198
+ # openai-api-key:
199
+ # - api-key: "your-openai-key"
200
+
201
+ # Auto-discover local models:
202
+ ollama:
203
+ enabled: true
204
+ auto-discover: true
205
+ `;
206
+ writeFileSync(configFile, defaultConfig, { mode: 0o600 });
207
+ console.log(`Created default config at ${configFile}`);
208
+ console.log(`Edit it to add your API keys, then restart.\n`);
209
+ }
210
+
211
+ return configFile;
212
+ }
213
+
214
+ // ── Main ────────────────────────────────────────────────────────
215
+
216
+ async function main() {
217
+ const args = process.argv.slice(2);
218
+ let version = parseVersion(args);
219
+
220
+ const plat = getPlatform();
221
+
222
+ // Resolve latest version
223
+ if (version === "latest") {
224
+ try {
225
+ version = await resolveLatestVersion();
226
+ console.log(`Latest version: ${version}`);
227
+ } catch (e) {
228
+ console.error(`Could not resolve latest version: ${e.message}`);
229
+ console.error("Tip: specify a version with --version=v1.0.0");
230
+ process.exit(1);
231
+ }
232
+ }
233
+
234
+ // Check cache
235
+ const cacheDir = getCacheDir(version);
236
+ const binaryPath = join(cacheDir, plat.bin);
237
+
238
+ if (!existsSync(binaryPath)) {
239
+ try {
240
+ await downloadAndExtract(version, plat, cacheDir);
241
+ } catch (e) {
242
+ console.error(`\nFailed to download: ${e.message}`);
243
+ console.error(`\nTry manually: https://github.com/${REPO}/releases`);
244
+ process.exit(1);
245
+ }
246
+ }
247
+
248
+ // Verify binary works
249
+ try {
250
+ execFileSync(binaryPath, ["--version"], { stdio: "pipe", timeout: 5000 });
251
+ } catch {
252
+ // Binary might not support --version flag, that's ok
253
+ }
254
+
255
+ // Run
256
+ const result = spawnSync(binaryPath, args, {
257
+ stdio: "inherit",
258
+ env: { ...process.env },
259
+ });
260
+
261
+ process.exit(result.status ?? 1);
262
+ }
263
+
264
+ main().catch((e) => {
265
+ console.error(e.message);
266
+ process.exit(1);
267
+ });
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@traylinx/switchailocal",
3
+ "version": "0.2.0",
4
+ "description": "One local endpoint. All your AI providers. Install and run switchAILocal instantly.",
5
+ "bin": {
6
+ "switchailocal": "bin.js"
7
+ },
8
+ "type": "module",
9
+ "keywords": [
10
+ "ai",
11
+ "gateway",
12
+ "proxy",
13
+ "openai",
14
+ "claude",
15
+ "gemini",
16
+ "ollama",
17
+ "llm",
18
+ "api"
19
+ ],
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/traylinx/switchAILocal.git",
24
+ "directory": "npx/switchailocal"
25
+ },
26
+ "homepage": "https://github.com/traylinx/switchAILocal",
27
+ "dependencies": {}
28
+ }