@tpmjs/cli 0.1.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 (97) hide show
  1. package/README.md +127 -0
  2. package/bin/run.js +5 -0
  3. package/dist/commands/agent/chat.d.ts +23 -0
  4. package/dist/commands/agent/chat.js +608 -0
  5. package/dist/commands/agent/chat.js.map +1 -0
  6. package/dist/commands/agent/create.d.ts +22 -0
  7. package/dist/commands/agent/create.js +549 -0
  8. package/dist/commands/agent/create.js.map +1 -0
  9. package/dist/commands/agent/delete.d.ts +19 -0
  10. package/dist/commands/agent/delete.js +529 -0
  11. package/dist/commands/agent/delete.js.map +1 -0
  12. package/dist/commands/agent/list.d.ts +16 -0
  13. package/dist/commands/agent/list.js +535 -0
  14. package/dist/commands/agent/list.js.map +1 -0
  15. package/dist/commands/agent/update.d.ts +25 -0
  16. package/dist/commands/agent/update.js +547 -0
  17. package/dist/commands/agent/update.js.map +1 -0
  18. package/dist/commands/auth/login.d.ts +21 -0
  19. package/dist/commands/auth/login.js +603 -0
  20. package/dist/commands/auth/login.js.map +1 -0
  21. package/dist/commands/auth/logout.d.ts +13 -0
  22. package/dist/commands/auth/logout.js +227 -0
  23. package/dist/commands/auth/logout.js.map +1 -0
  24. package/dist/commands/auth/status.d.ts +14 -0
  25. package/dist/commands/auth/status.js +542 -0
  26. package/dist/commands/auth/status.js.map +1 -0
  27. package/dist/commands/auth/whoami.d.ts +14 -0
  28. package/dist/commands/auth/whoami.js +500 -0
  29. package/dist/commands/auth/whoami.js.map +1 -0
  30. package/dist/commands/collection/add.d.ts +18 -0
  31. package/dist/commands/collection/add.js +509 -0
  32. package/dist/commands/collection/add.js.map +1 -0
  33. package/dist/commands/collection/create.d.ts +17 -0
  34. package/dist/commands/collection/create.js +521 -0
  35. package/dist/commands/collection/create.js.map +1 -0
  36. package/dist/commands/collection/delete.d.ts +19 -0
  37. package/dist/commands/collection/delete.js +531 -0
  38. package/dist/commands/collection/delete.js.map +1 -0
  39. package/dist/commands/collection/import.d.ts +18 -0
  40. package/dist/commands/collection/import.js +546 -0
  41. package/dist/commands/collection/import.js.map +1 -0
  42. package/dist/commands/collection/list.d.ts +16 -0
  43. package/dist/commands/collection/list.js +531 -0
  44. package/dist/commands/collection/list.js.map +1 -0
  45. package/dist/commands/collection/remove.d.ts +18 -0
  46. package/dist/commands/collection/remove.js +501 -0
  47. package/dist/commands/collection/remove.js.map +1 -0
  48. package/dist/commands/collection/update.d.ts +20 -0
  49. package/dist/commands/collection/update.js +522 -0
  50. package/dist/commands/collection/update.js.map +1 -0
  51. package/dist/commands/doctor.d.ts +14 -0
  52. package/dist/commands/doctor.js +592 -0
  53. package/dist/commands/doctor.js.map +1 -0
  54. package/dist/commands/mcp/config.d.ts +19 -0
  55. package/dist/commands/mcp/config.js +265 -0
  56. package/dist/commands/mcp/config.js.map +1 -0
  57. package/dist/commands/mcp/serve.d.ts +23 -0
  58. package/dist/commands/mcp/serve.js +689 -0
  59. package/dist/commands/mcp/serve.js.map +1 -0
  60. package/dist/commands/playground.d.ts +23 -0
  61. package/dist/commands/playground.js +666 -0
  62. package/dist/commands/playground.js.map +1 -0
  63. package/dist/commands/publish/check.d.ts +17 -0
  64. package/dist/commands/publish/check.js +544 -0
  65. package/dist/commands/publish/check.js.map +1 -0
  66. package/dist/commands/publish/preview.d.ts +19 -0
  67. package/dist/commands/publish/preview.js +291 -0
  68. package/dist/commands/publish/preview.js.map +1 -0
  69. package/dist/commands/tool/execute.d.ts +21 -0
  70. package/dist/commands/tool/execute.js +574 -0
  71. package/dist/commands/tool/execute.js.map +1 -0
  72. package/dist/commands/tool/info.d.ts +18 -0
  73. package/dist/commands/tool/info.js +537 -0
  74. package/dist/commands/tool/info.js.map +1 -0
  75. package/dist/commands/tool/init.d.ts +24 -0
  76. package/dist/commands/tool/init.js +461 -0
  77. package/dist/commands/tool/init.js.map +1 -0
  78. package/dist/commands/tool/search.d.ts +20 -0
  79. package/dist/commands/tool/search.js +566 -0
  80. package/dist/commands/tool/search.js.map +1 -0
  81. package/dist/commands/tool/trending.d.ts +15 -0
  82. package/dist/commands/tool/trending.js +523 -0
  83. package/dist/commands/tool/trending.js.map +1 -0
  84. package/dist/commands/tool/validate.d.ts +15 -0
  85. package/dist/commands/tool/validate.js +555 -0
  86. package/dist/commands/tool/validate.js.map +1 -0
  87. package/dist/commands/update.d.ts +15 -0
  88. package/dist/commands/update.js +228 -0
  89. package/dist/commands/update.js.map +1 -0
  90. package/dist/hooks/init.d.ts +5 -0
  91. package/dist/hooks/init.js +8 -0
  92. package/dist/hooks/init.js.map +1 -0
  93. package/dist/index.d.ts +262 -0
  94. package/dist/index.js +473 -0
  95. package/dist/index.js.map +1 -0
  96. package/oclif.manifest.json +1699 -0
  97. package/package.json +104 -0
@@ -0,0 +1,603 @@
1
+ import { Command, Flags, Args } from '@oclif/core';
2
+ import open from 'open';
3
+ import { createServer } from 'http';
4
+ import { URL } from 'url';
5
+ import Conf from 'conf';
6
+ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
9
+ import Table from 'cli-table3';
10
+ import ora from 'ora';
11
+ import pc from 'picocolors';
12
+
13
+ // src/commands/auth/login.ts
14
+ var CONFIG_DIR = path.join(os.homedir(), ".tpmjs");
15
+ var CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
16
+ path.join(CONFIG_DIR, "history");
17
+ function ensureConfigDir() {
18
+ if (!fs.existsSync(CONFIG_DIR)) {
19
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
20
+ }
21
+ }
22
+ var configStore = new Conf({
23
+ projectName: "tpmjs",
24
+ cwd: CONFIG_DIR,
25
+ configName: "config",
26
+ defaults: {
27
+ apiUrl: "https://tpmjs.com/api",
28
+ defaultOutput: "human",
29
+ verbose: false,
30
+ analytics: false
31
+ }
32
+ });
33
+ function getConfigValue(key) {
34
+ return configStore.get(key);
35
+ }
36
+ function loadCredentials() {
37
+ ensureConfigDir();
38
+ if (!fs.existsSync(CREDENTIALS_FILE)) {
39
+ return null;
40
+ }
41
+ try {
42
+ const content = fs.readFileSync(CREDENTIALS_FILE, "utf-8");
43
+ return JSON.parse(content);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ function saveCredentials(credentials) {
49
+ ensureConfigDir();
50
+ const content = JSON.stringify(credentials, null, 2);
51
+ fs.writeFileSync(CREDENTIALS_FILE, content, { mode: 384 });
52
+ }
53
+ function getApiKey() {
54
+ if (process.env.TPMJS_API_KEY) {
55
+ return process.env.TPMJS_API_KEY;
56
+ }
57
+ const creds = loadCredentials();
58
+ if (creds?.apiKey) {
59
+ return creds.apiKey;
60
+ }
61
+ return void 0;
62
+ }
63
+ function getApiUrl() {
64
+ return process.env.TPMJS_API_URL ?? getConfigValue("apiUrl") ?? "https://tpmjs.com/api";
65
+ }
66
+
67
+ // src/lib/api-client.ts
68
+ var TpmClient = class {
69
+ baseUrl;
70
+ apiKey;
71
+ timeout;
72
+ constructor(options = {}) {
73
+ this.baseUrl = options.baseUrl ?? getApiUrl();
74
+ this.apiKey = options.apiKey ?? getApiKey();
75
+ this.timeout = options.timeout ?? 3e4;
76
+ }
77
+ async request(endpoint, options = {}) {
78
+ const url = `${this.baseUrl}${endpoint}`;
79
+ const headers = {
80
+ "Content-Type": "application/json",
81
+ ...options.headers
82
+ };
83
+ if (this.apiKey) {
84
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
85
+ }
86
+ const controller = new AbortController();
87
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
88
+ try {
89
+ const response = await fetch(url, {
90
+ ...options,
91
+ headers,
92
+ signal: controller.signal
93
+ });
94
+ const data = await response.json();
95
+ if (!response.ok) {
96
+ throw new ApiError(
97
+ data.message || data.error || `HTTP ${response.status}`,
98
+ response.status,
99
+ data
100
+ );
101
+ }
102
+ return data;
103
+ } finally {
104
+ clearTimeout(timeoutId);
105
+ }
106
+ }
107
+ // Health check
108
+ async health() {
109
+ return this.request("/health");
110
+ }
111
+ // Stats
112
+ async getStats() {
113
+ return this.request("/stats");
114
+ }
115
+ // Tools
116
+ async searchTools(options = {}) {
117
+ const params = new URLSearchParams();
118
+ if (options.query) params.set("q", options.query);
119
+ if (options.category) params.set("category", options.category);
120
+ if (options.limit) params.set("limit", String(options.limit));
121
+ if (options.offset) params.set("offset", String(options.offset));
122
+ const queryString = params.toString();
123
+ const endpoint = queryString ? `/tools?${queryString}` : "/tools";
124
+ return this.request(endpoint);
125
+ }
126
+ async getTool(packageName, toolName) {
127
+ return this.request(`/tools/${encodeURIComponent(packageName)}/${encodeURIComponent(toolName)}`);
128
+ }
129
+ async getToolBySlug(slug) {
130
+ const searchResult = await this.searchTools({ query: slug, limit: 1 });
131
+ if (searchResult.data && searchResult.data.length > 0) {
132
+ const tool = searchResult.data.find((t) => t.slug === slug) || searchResult.data[0];
133
+ return { success: true, data: tool };
134
+ }
135
+ return { success: false, error: "Tool not found" };
136
+ }
137
+ async getTrendingTools(options = {}) {
138
+ const params = new URLSearchParams();
139
+ if (options.limit) params.set("limit", String(options.limit));
140
+ if (options.offset) params.set("offset", String(options.offset));
141
+ const queryString = params.toString();
142
+ const endpoint = queryString ? `/tools/trending?${queryString}` : "/tools/trending";
143
+ return this.request(endpoint);
144
+ }
145
+ async validateTpmjsField(field) {
146
+ return this.request("/tools/validate", {
147
+ method: "POST",
148
+ body: JSON.stringify(field)
149
+ });
150
+ }
151
+ async executeTool(slug, params) {
152
+ return this.request(`/tools/${encodeURIComponent(slug)}/execute`, {
153
+ method: "POST",
154
+ body: JSON.stringify(params)
155
+ });
156
+ }
157
+ async *executeToolStream(slug, params) {
158
+ const url = `${this.baseUrl}/tools/${encodeURIComponent(slug)}/execute`;
159
+ const headers = {
160
+ "Content-Type": "application/json",
161
+ "Accept": "text/event-stream"
162
+ };
163
+ if (this.apiKey) {
164
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
165
+ }
166
+ const response = await fetch(url, {
167
+ method: "POST",
168
+ headers,
169
+ body: JSON.stringify({ ...params, stream: true })
170
+ });
171
+ if (!response.ok) {
172
+ const errorText = await response.text();
173
+ throw new ApiError(errorText || `HTTP ${response.status}`, response.status);
174
+ }
175
+ if (!response.body) {
176
+ throw new ApiError("No response body", 0);
177
+ }
178
+ const reader = response.body.getReader();
179
+ const decoder = new TextDecoder();
180
+ let buffer = "";
181
+ try {
182
+ while (true) {
183
+ const { done, value } = await reader.read();
184
+ if (done) {
185
+ yield { type: "done", data: "" };
186
+ break;
187
+ }
188
+ buffer += decoder.decode(value, { stream: true });
189
+ const lines = buffer.split("\n");
190
+ buffer = lines.pop() ?? "";
191
+ for (const line of lines) {
192
+ if (line.startsWith("data: ")) {
193
+ const data = line.slice(6);
194
+ if (data === "[DONE]") {
195
+ yield { type: "done", data: "" };
196
+ return;
197
+ }
198
+ try {
199
+ const parsed = JSON.parse(data);
200
+ yield { type: parsed.type || "text", data: parsed.content || parsed.data || data };
201
+ } catch {
202
+ yield { type: "text", data };
203
+ }
204
+ }
205
+ }
206
+ }
207
+ } finally {
208
+ reader.releaseLock();
209
+ }
210
+ }
211
+ // Agents
212
+ async listAgents(options = {}) {
213
+ const params = new URLSearchParams();
214
+ if (options.limit) params.set("limit", String(options.limit));
215
+ if (options.offset) params.set("offset", String(options.offset));
216
+ const queryString = params.toString();
217
+ const endpoint = queryString ? `/agents?${queryString}` : "/agents";
218
+ return this.request(endpoint);
219
+ }
220
+ async getAgent(id) {
221
+ return this.request(`/agents/${id}`);
222
+ }
223
+ async createAgent(input) {
224
+ return this.request("/agents", {
225
+ method: "POST",
226
+ body: JSON.stringify(input)
227
+ });
228
+ }
229
+ async updateAgent(id, input) {
230
+ return this.request(`/agents/${id}`, {
231
+ method: "PATCH",
232
+ body: JSON.stringify(input)
233
+ });
234
+ }
235
+ async deleteAgent(id) {
236
+ return this.request(`/agents/${id}`, {
237
+ method: "DELETE"
238
+ });
239
+ }
240
+ // Collections
241
+ async listCollections(options = {}) {
242
+ const params = new URLSearchParams();
243
+ if (options.limit) params.set("limit", String(options.limit));
244
+ if (options.offset) params.set("offset", String(options.offset));
245
+ const queryString = params.toString();
246
+ const endpoint = queryString ? `/collections?${queryString}` : "/collections";
247
+ return this.request(endpoint);
248
+ }
249
+ async getCollection(id) {
250
+ return this.request(`/collections/${id}`);
251
+ }
252
+ async createCollection(input) {
253
+ return this.request("/collections", {
254
+ method: "POST",
255
+ body: JSON.stringify(input)
256
+ });
257
+ }
258
+ async updateCollection(id, input) {
259
+ return this.request(`/collections/${id}`, {
260
+ method: "PATCH",
261
+ body: JSON.stringify(input)
262
+ });
263
+ }
264
+ async deleteCollection(id) {
265
+ return this.request(`/collections/${id}`, {
266
+ method: "DELETE"
267
+ });
268
+ }
269
+ async addToolsToCollection(id, toolIds) {
270
+ for (const toolId of toolIds) {
271
+ await this.request(`/collections/${id}/tools/${toolId}`, {
272
+ method: "POST"
273
+ });
274
+ }
275
+ return { success: true };
276
+ }
277
+ async removeToolFromCollection(id, toolId) {
278
+ return this.request(`/collections/${id}/tools/${toolId}`, {
279
+ method: "DELETE"
280
+ });
281
+ }
282
+ // User
283
+ async whoami() {
284
+ return this.request("/user/profile");
285
+ }
286
+ async listApiKeys() {
287
+ return this.request("/user/tpmjs-api-keys");
288
+ }
289
+ // Check if authenticated
290
+ isAuthenticated() {
291
+ return !!this.apiKey;
292
+ }
293
+ };
294
+ var ApiError = class extends Error {
295
+ constructor(message, statusCode, data) {
296
+ super(message);
297
+ this.statusCode = statusCode;
298
+ this.data = data;
299
+ this.name = "ApiError";
300
+ }
301
+ };
302
+ var OutputFormatter = class {
303
+ options;
304
+ constructor(options = {}) {
305
+ this.options = options;
306
+ }
307
+ // Output as JSON
308
+ json(data) {
309
+ console.log(JSON.stringify(data, null, 2));
310
+ }
311
+ // Output a table
312
+ table(data, columns) {
313
+ if (this.options.json) {
314
+ this.json(data);
315
+ return;
316
+ }
317
+ const table = new Table({
318
+ head: columns.map((col) => pc.bold(col.header)),
319
+ colWidths: columns.map((col) => col.width ?? null),
320
+ style: {
321
+ head: [],
322
+ border: []
323
+ }
324
+ });
325
+ for (const row of data) {
326
+ table.push(columns.map((col) => String(row[col.key] ?? "")));
327
+ }
328
+ console.log(table.toString());
329
+ }
330
+ // Success message
331
+ success(message) {
332
+ if (this.options.json) return;
333
+ console.log(pc.green("\u2713"), message);
334
+ }
335
+ // Error message
336
+ error(message, details) {
337
+ if (this.options.json) {
338
+ this.json({ error: message, details });
339
+ return;
340
+ }
341
+ console.error(pc.red("\u2717"), message);
342
+ if (details && this.options.verbose) {
343
+ console.error(pc.dim(details));
344
+ }
345
+ }
346
+ // Warning message
347
+ warning(message) {
348
+ if (this.options.json) return;
349
+ console.log(pc.yellow("\u26A0"), message);
350
+ }
351
+ // Info message
352
+ info(message) {
353
+ if (this.options.json) return;
354
+ console.log(pc.blue("\u2139"), message);
355
+ }
356
+ // Debug message (only in verbose mode)
357
+ debug(message) {
358
+ if (this.options.json) return;
359
+ if (this.options.verbose) {
360
+ console.log(pc.dim(`[debug] ${message}`));
361
+ }
362
+ }
363
+ // Plain text output
364
+ text(message) {
365
+ if (this.options.json) return;
366
+ console.log(message);
367
+ }
368
+ // Heading
369
+ heading(text) {
370
+ if (this.options.json) return;
371
+ console.log();
372
+ console.log(pc.bold(pc.underline(text)));
373
+ console.log();
374
+ }
375
+ // Subheading
376
+ subheading(text) {
377
+ if (this.options.json) return;
378
+ console.log(pc.bold(text));
379
+ }
380
+ // Key-value pair
381
+ keyValue(key, value) {
382
+ if (this.options.json) return;
383
+ console.log(`${pc.dim(key + ":")} ${value ?? pc.dim("(not set)")}`);
384
+ }
385
+ // List item
386
+ listItem(text, indent = 0) {
387
+ if (this.options.json) return;
388
+ const prefix = " ".repeat(indent) + "\u2022";
389
+ console.log(`${prefix} ${text}`);
390
+ }
391
+ // Spinner
392
+ spinner(message) {
393
+ return ora({
394
+ text: message,
395
+ isSilent: this.options.json
396
+ }).start();
397
+ }
398
+ // Blank line
399
+ newLine() {
400
+ if (this.options.json) return;
401
+ console.log();
402
+ }
403
+ // Horizontal rule
404
+ hr() {
405
+ if (this.options.json) return;
406
+ console.log(pc.dim("\u2500".repeat(50)));
407
+ }
408
+ // Alias for hr
409
+ divider() {
410
+ this.hr();
411
+ }
412
+ // Code block
413
+ code(text, language) {
414
+ if (this.options.json) {
415
+ this.json({ code: text, language });
416
+ return;
417
+ }
418
+ console.log(pc.dim("```" + (language ?? "")));
419
+ console.log(text);
420
+ console.log(pc.dim("```"));
421
+ }
422
+ // Highlight text
423
+ highlight(text) {
424
+ return pc.cyan(text);
425
+ }
426
+ // Dim text
427
+ dim(text) {
428
+ return pc.dim(text);
429
+ }
430
+ // Bold text
431
+ bold(text) {
432
+ return pc.bold(text);
433
+ }
434
+ // Link (just returns text in terminal)
435
+ link(text, url) {
436
+ return `\x1B]8;;${url}\x07${pc.underline(pc.blue(text))}\x1B]8;;\x07`;
437
+ }
438
+ };
439
+ function createOutput(flags) {
440
+ return new OutputFormatter({
441
+ json: flags.json,
442
+ verbose: flags.verbose
443
+ });
444
+ }
445
+
446
+ // src/commands/auth/login.ts
447
+ var Login = class _Login extends Command {
448
+ static description = "Authenticate with TPMJS";
449
+ static examples = [
450
+ "<%= config.bin %> <%= command.id %> --api-key tpm_xxxxx",
451
+ "<%= config.bin %> <%= command.id %> --browser"
452
+ ];
453
+ static flags = {
454
+ "api-key": Flags.string({
455
+ char: "k",
456
+ description: "API key (or set TPMJS_API_KEY environment variable)"
457
+ }),
458
+ browser: Flags.boolean({
459
+ char: "b",
460
+ description: "Open browser for OAuth authentication",
461
+ default: false
462
+ }),
463
+ json: Flags.boolean({
464
+ description: "Output in JSON format",
465
+ default: false
466
+ }),
467
+ verbose: Flags.boolean({
468
+ char: "v",
469
+ description: "Show verbose output",
470
+ default: false
471
+ })
472
+ };
473
+ static args = {
474
+ key: Args.string({
475
+ description: "API key (alternative to --api-key flag)",
476
+ required: false
477
+ })
478
+ };
479
+ async run() {
480
+ const { args, flags } = await this.parse(_Login);
481
+ const output = createOutput(flags);
482
+ const apiKey = flags["api-key"] ?? args.key;
483
+ if (apiKey) {
484
+ await this.loginWithApiKey(apiKey, output, flags);
485
+ } else if (flags.browser) {
486
+ await this.loginWithBrowser(output, flags);
487
+ } else {
488
+ output.info("No API key provided. Use --api-key or --browser flag.");
489
+ output.newLine();
490
+ output.text("Options:");
491
+ output.listItem("tpm auth login --api-key <your-api-key>");
492
+ output.listItem("tpm auth login --browser (opens browser for OAuth)");
493
+ output.newLine();
494
+ output.text(`Get your API key at: ${output.link("tpmjs.com/dashboard/settings/tpmjs-api-keys", "https://tpmjs.com/dashboard/settings/tpmjs-api-keys")}`);
495
+ }
496
+ }
497
+ async loginWithApiKey(apiKey, output, flags) {
498
+ const spinner = output.spinner("Validating API key...");
499
+ try {
500
+ const client = new TpmClient({ apiKey });
501
+ const response = await client.whoami();
502
+ if (!response.success || !response.data) {
503
+ spinner.fail("Invalid API key");
504
+ return;
505
+ }
506
+ saveCredentials({ apiKey });
507
+ spinner.succeed("Logged in successfully");
508
+ if (flags.json) {
509
+ output.json({
510
+ success: true,
511
+ user: response.data
512
+ });
513
+ } else {
514
+ output.newLine();
515
+ output.keyValue("Email", response.data.email);
516
+ if (response.data.username) {
517
+ output.keyValue("Username", response.data.username);
518
+ }
519
+ if (response.data.name) {
520
+ output.keyValue("Name", response.data.name);
521
+ }
522
+ }
523
+ } catch (error) {
524
+ spinner.fail("Authentication failed");
525
+ output.error(
526
+ error instanceof Error ? error.message : "Unknown error",
527
+ flags.verbose ? String(error) : void 0
528
+ );
529
+ }
530
+ }
531
+ async loginWithBrowser(output, flags) {
532
+ const port = 9876;
533
+ const callbackUrl = `http://localhost:${port}/callback`;
534
+ const state = crypto.randomUUID();
535
+ output.info("Opening browser for authentication...");
536
+ return new Promise((resolve) => {
537
+ const server = createServer(async (req, res) => {
538
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
539
+ if (url.pathname === "/callback") {
540
+ const receivedState = url.searchParams.get("state");
541
+ const apiKey = url.searchParams.get("key");
542
+ const error = url.searchParams.get("error");
543
+ if (error) {
544
+ res.writeHead(200, { "Content-Type": "text/html" });
545
+ res.end("<html><body><h1>Authentication Failed</h1><p>You can close this window.</p></body></html>");
546
+ server.close();
547
+ output.error(`Authentication failed: ${error}`);
548
+ resolve();
549
+ return;
550
+ }
551
+ if (receivedState !== state) {
552
+ res.writeHead(200, { "Content-Type": "text/html" });
553
+ res.end("<html><body><h1>Invalid State</h1><p>Authentication failed due to invalid state.</p></body></html>");
554
+ server.close();
555
+ output.error("Authentication failed: Invalid state parameter");
556
+ resolve();
557
+ return;
558
+ }
559
+ if (apiKey) {
560
+ saveCredentials({ apiKey });
561
+ res.writeHead(200, { "Content-Type": "text/html" });
562
+ res.end("<html><body><h1>Success!</h1><p>You are now logged in. You can close this window.</p></body></html>");
563
+ server.close();
564
+ output.success("Logged in successfully via browser");
565
+ if (flags.json) {
566
+ output.json({ success: true });
567
+ }
568
+ resolve();
569
+ } else {
570
+ res.writeHead(200, { "Content-Type": "text/html" });
571
+ res.end("<html><body><h1>Error</h1><p>No API key received.</p></body></html>");
572
+ server.close();
573
+ output.error("No API key received from authentication");
574
+ resolve();
575
+ }
576
+ } else {
577
+ res.writeHead(404);
578
+ res.end("Not found");
579
+ }
580
+ });
581
+ server.listen(port, async () => {
582
+ const authUrl = `${getApiUrl().replace("/api", "")}/cli/auth?state=${state}&callback=${encodeURIComponent(callbackUrl)}`;
583
+ output.debug(`Auth URL: ${authUrl}`);
584
+ output.text("Waiting for authentication...");
585
+ try {
586
+ await open(authUrl);
587
+ } catch {
588
+ output.warning("Could not open browser automatically.");
589
+ output.text(`Please open this URL manually: ${authUrl}`);
590
+ }
591
+ });
592
+ setTimeout(() => {
593
+ server.close();
594
+ output.error("Authentication timed out");
595
+ resolve();
596
+ }, 5 * 60 * 1e3);
597
+ });
598
+ }
599
+ };
600
+
601
+ export { Login as default };
602
+ //# sourceMappingURL=login.js.map
603
+ //# sourceMappingURL=login.js.map