sagacloud 0.0.0-stage → 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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -2
  3. package/dist/index.js +1518 -0
  4. package/package.json +58 -4
package/dist/index.js ADDED
@@ -0,0 +1,1518 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import pc7 from "picocolors";
6
+
7
+ // src/commands/auth.ts
8
+ import crypto from "crypto";
9
+ import { execFile } from "child_process";
10
+ import http from "http";
11
+ import os2 from "os";
12
+ import * as p from "@clack/prompts";
13
+ import Table from "cli-table3";
14
+ import pc from "picocolors";
15
+
16
+ // src/lib/config.ts
17
+ import fs from "fs";
18
+ import os from "os";
19
+ import path from "path";
20
+ import { parse as parseJsonc, printParseErrorCode } from "jsonc-parser";
21
+ import { z } from "zod";
22
+ var DEFAULT_API_BASE_URL = "https://app.sagasoft.xyz";
23
+ var DEFAULT_PANEL_BASE_URL = "https://app.sagasoft.xyz";
24
+ var SagaCloudJsoncSchema = z.object({
25
+ $schema: z.string().optional(),
26
+ name: z.string().min(1).optional(),
27
+ site_id: z.string().optional(),
28
+ type: z.enum(["static", "spa", "php", "node", "nextjs"]).optional(),
29
+ base_directory: z.string().optional(),
30
+ install_command: z.string().optional(),
31
+ build_command: z.string().optional(),
32
+ output_dir: z.string().optional(),
33
+ start_command: z.string().optional(),
34
+ port: z.union([z.number().int().min(1).max(65535), z.string()]).optional(),
35
+ spa_fallback: z.boolean().optional(),
36
+ domains: z.array(z.string()).optional(),
37
+ ignore: z.array(z.string()).optional(),
38
+ vars: z.record(z.union([z.string(), z.number(), z.boolean()])).optional()
39
+ });
40
+ function getAuthDir() {
41
+ return path.join(os.homedir(), ".config", "sagacloud");
42
+ }
43
+ function getAuthFilePath() {
44
+ return path.join(getAuthDir(), "auth.json");
45
+ }
46
+ function readAuthProfile() {
47
+ const envToken = (process.env.SAGACLOUD_TOKEN || "").trim();
48
+ const envUrl = (process.env.SAGACLOUD_API_URL || "").trim().replace(/\/+$/, "");
49
+ let disk = null;
50
+ const fp = getAuthFilePath();
51
+ if (fs.existsSync(fp)) {
52
+ try {
53
+ const parsed = JSON.parse(fs.readFileSync(fp, "utf8"));
54
+ if (parsed?.token) {
55
+ disk = {
56
+ ...parsed,
57
+ apiUrl: (parsed.apiUrl || DEFAULT_API_BASE_URL).replace(/\/+$/, "")
58
+ };
59
+ }
60
+ } catch {
61
+ disk = null;
62
+ }
63
+ }
64
+ if (envToken) {
65
+ return {
66
+ token: envToken,
67
+ apiUrl: envUrl || disk?.apiUrl || DEFAULT_API_BASE_URL,
68
+ panelUrl: disk?.panelUrl || DEFAULT_PANEL_BASE_URL,
69
+ user: disk?.user,
70
+ tenant: disk?.tenant,
71
+ tenantName: disk?.tenantName
72
+ };
73
+ }
74
+ if (disk && envUrl) {
75
+ return { ...disk, apiUrl: envUrl };
76
+ }
77
+ return disk;
78
+ }
79
+ function writeAuthProfile(profile) {
80
+ const dir = getAuthDir();
81
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
82
+ const fp = getAuthFilePath();
83
+ fs.writeFileSync(
84
+ fp,
85
+ JSON.stringify(
86
+ {
87
+ ...profile,
88
+ apiUrl: (profile.apiUrl || DEFAULT_API_BASE_URL).replace(/\/+$/, "")
89
+ },
90
+ null,
91
+ 2
92
+ ),
93
+ { mode: 384 }
94
+ );
95
+ try {
96
+ fs.chmodSync(fp, 384);
97
+ } catch {
98
+ }
99
+ }
100
+ function clearAuthProfile() {
101
+ const fp = getAuthFilePath();
102
+ if (!fs.existsSync(fp)) return false;
103
+ fs.unlinkSync(fp);
104
+ return true;
105
+ }
106
+ function readRepoJsoncConfig(cwd = process.cwd()) {
107
+ for (const fname of ["sagacloud.jsonc", "sagacloud.json"]) {
108
+ const full = path.join(cwd, fname);
109
+ if (!fs.existsSync(full)) continue;
110
+ const raw = fs.readFileSync(full, "utf8");
111
+ const errors = [];
112
+ const parsed = parseJsonc(raw, errors, { allowTrailingComma: true });
113
+ if (errors.length > 0) {
114
+ const first = errors[0];
115
+ throw new Error(
116
+ `Invalid syntax in ${fname} at offset ${first.offset}: ${printParseErrorCode(first.error)}`
117
+ );
118
+ }
119
+ const validated = SagaCloudJsoncSchema.safeParse(parsed);
120
+ if (!validated.success) {
121
+ const issue = validated.error.issues[0];
122
+ throw new Error(
123
+ `Invalid ${fname} field '${issue.path.join(".") || "root"}': ${issue.message}`
124
+ );
125
+ }
126
+ return { filePath: full, config: validated.data };
127
+ }
128
+ return { filePath: null, config: null };
129
+ }
130
+ function readLocalLink(cwd = process.cwd()) {
131
+ const fp = path.join(cwd, ".sagacloud", "project.json");
132
+ if (!fs.existsSync(fp)) return null;
133
+ try {
134
+ return JSON.parse(fs.readFileSync(fp, "utf8"));
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+ function writeLocalLink(data, cwd = process.cwd()) {
140
+ const dir = path.join(cwd, ".sagacloud");
141
+ fs.mkdirSync(dir, { recursive: true });
142
+ const fp = path.join(dir, "project.json");
143
+ fs.writeFileSync(fp, JSON.stringify(data, null, 2));
144
+ const gitignorePath = path.join(cwd, ".gitignore");
145
+ if (fs.existsSync(gitignorePath)) {
146
+ const gi = fs.readFileSync(gitignorePath, "utf8");
147
+ if (!gi.split(/\r?\n/).some((line) => line.trim() === ".sagacloud" || line.trim() === ".sagacloud/")) {
148
+ const suffix = gi.endsWith("\n") ? "" : "\n";
149
+ fs.writeFileSync(gitignorePath, `${gi}${suffix}.sagacloud/
150
+ `);
151
+ }
152
+ }
153
+ return fp;
154
+ }
155
+ function removeLocalLink(cwd = process.cwd()) {
156
+ const fp = path.join(cwd, ".sagacloud", "project.json");
157
+ if (!fs.existsSync(fp)) return false;
158
+ fs.unlinkSync(fp);
159
+ return true;
160
+ }
161
+ function resolveActiveSiteId(cwd = process.cwd(), explicitSiteId) {
162
+ if (explicitSiteId) return explicitSiteId.trim();
163
+ const link = readLocalLink(cwd);
164
+ if (link?.site_id) return link.site_id;
165
+ const { config } = readRepoJsoncConfig(cwd);
166
+ if (config?.site_id) return config.site_id;
167
+ throw new Error(
168
+ "No linked SagaCloud site found in this folder. Run `sagacloud link` or `sagacloud init` first (or pass --site <id>)."
169
+ );
170
+ }
171
+
172
+ // src/lib/api.ts
173
+ function parseFrappeError(rawBody, status) {
174
+ try {
175
+ const parsed = JSON.parse(rawBody);
176
+ if (parsed._server_messages) {
177
+ const msgs = JSON.parse(parsed._server_messages);
178
+ if (Array.isArray(msgs) && msgs.length > 0) {
179
+ const inner = JSON.parse(msgs[0]);
180
+ if (inner?.message) return inner.message.replace(/<[^>]+>/g, "");
181
+ }
182
+ }
183
+ if (parsed.exception) return parsed.exception.replace(/<[^>]+>/g, "");
184
+ if (parsed.message) return parsed.message;
185
+ } catch {
186
+ }
187
+ return `HTTP ${status}: ${rawBody.slice(0, 300)}`;
188
+ }
189
+ var SagaCloudClient = class {
190
+ profile;
191
+ constructor(profile) {
192
+ const active = profile || readAuthProfile();
193
+ if (!active?.token) {
194
+ throw new Error("Not authenticated. Run `sagacloud login` or set SAGACLOUD_TOKEN.");
195
+ }
196
+ this.profile = active;
197
+ }
198
+ get baseUrl() {
199
+ return this.profile.apiUrl;
200
+ }
201
+ async rpc(methodPath, options = {}) {
202
+ const httpMethod = options.method || "GET";
203
+ const url = new URL(`${this.baseUrl}/api/method/${methodPath}`);
204
+ if (options.query) {
205
+ for (const [k, v] of Object.entries(options.query)) {
206
+ if (v !== void 0 && v !== "") url.searchParams.set(k, String(v));
207
+ }
208
+ }
209
+ const headers = {
210
+ Accept: "application/json"
211
+ };
212
+ if (!options.skipAuth) {
213
+ headers["X-SagaCloud-Token"] = this.profile.token;
214
+ }
215
+ let body;
216
+ if (httpMethod === "POST") {
217
+ headers["Content-Type"] = "application/json";
218
+ body = JSON.stringify(options.body || {});
219
+ }
220
+ const resp = await fetch(url.toString(), { method: httpMethod, headers, body });
221
+ const raw = await resp.text();
222
+ if (!resp.ok) {
223
+ throw new Error(parseFrappeError(raw, resp.status));
224
+ }
225
+ const json = raw ? JSON.parse(raw) : {};
226
+ return json.message ?? json;
227
+ }
228
+ async uploadBundle(zipBuffer, fileName, bundleMode = "static") {
229
+ const form = new FormData();
230
+ form.append("file", new Blob([new Uint8Array(zipBuffer)], { type: "application/zip" }), fileName);
231
+ form.append("bundle_mode", bundleMode);
232
+ const resp = await fetch(`${this.baseUrl}/api/method/saga_cloud.api.hosting.upload_static_zip`, {
233
+ method: "POST",
234
+ headers: {
235
+ Accept: "application/json",
236
+ "X-SagaCloud-Token": this.profile.token
237
+ },
238
+ body: form
239
+ });
240
+ const raw = await resp.text();
241
+ if (!resp.ok) {
242
+ throw new Error(parseFrappeError(raw, resp.status));
243
+ }
244
+ const parsed = JSON.parse(raw);
245
+ return parsed.message || parsed;
246
+ }
247
+ };
248
+ async function exchangeCliCode(apiUrl, code) {
249
+ const cleanUrl = apiUrl.replace(/\/+$/, "");
250
+ const resp = await fetch(`${cleanUrl}/api/method/saga_cloud.api.cli_auth.exchange_cli_code`, {
251
+ method: "POST",
252
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
253
+ body: JSON.stringify({ code })
254
+ });
255
+ const raw = await resp.text();
256
+ if (!resp.ok) {
257
+ throw new Error(parseFrappeError(raw, resp.status));
258
+ }
259
+ const parsed = JSON.parse(raw);
260
+ return parsed.message || parsed;
261
+ }
262
+
263
+ // src/commands/auth.ts
264
+ function openBrowser(url) {
265
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
266
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
267
+ execFile(cmd, args, () => {
268
+ });
269
+ }
270
+ function escapeHtml(value) {
271
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
272
+ }
273
+ function renderCallbackHtml(opts) {
274
+ const badgeBg = opts.ok ? "rgba(16, 185, 129, 0.14)" : "rgba(239, 68, 68, 0.14)";
275
+ const badgeBorder = opts.ok ? "rgba(16, 185, 129, 0.35)" : "rgba(239, 68, 68, 0.35)";
276
+ const badgeColor = opts.ok ? "#34d399" : "#f87171";
277
+ const pillText = opts.ok ? "Authentication Complete" : "Authentication Failed";
278
+ const iconSvg = opts.ok ? `<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="${badgeColor}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>` : `<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="${badgeColor}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
279
+ const detailBlock = opts.detail ? `<div class="detail">${escapeHtml(opts.detail)}</div>` : "";
280
+ return `<!doctype html>
281
+ <html lang="en">
282
+ <head>
283
+ <meta charset="utf-8" />
284
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
285
+ <title>${escapeHtml(opts.title)} \u2014 SagaCloud CLI</title>
286
+ <style>
287
+ :root { color-scheme: dark; }
288
+ * { box-sizing: border-box; margin: 0; padding: 0; }
289
+ body {
290
+ min-height: 100vh;
291
+ display: grid;
292
+ place-items: center;
293
+ padding: 24px;
294
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;
295
+ background:
296
+ radial-gradient(60% 50% at 50% 0%, rgba(99, 102, 241, 0.16), transparent 70%),
297
+ #09090b;
298
+ color: #fafafa;
299
+ }
300
+ .card {
301
+ width: 100%;
302
+ max-width: 440px;
303
+ background: rgba(24, 24, 27, 0.88);
304
+ border: 1px solid rgba(255, 255, 255, 0.1);
305
+ border-radius: 16px;
306
+ padding: 32px 28px;
307
+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
308
+ text-align: center;
309
+ }
310
+ .brand {
311
+ display: inline-flex;
312
+ align-items: center;
313
+ gap: 8px;
314
+ font-size: 13px;
315
+ font-weight: 600;
316
+ letter-spacing: 0.04em;
317
+ text-transform: uppercase;
318
+ color: #a1a1aa;
319
+ margin-bottom: 24px;
320
+ }
321
+ .brand-dot {
322
+ width: 8px;
323
+ height: 8px;
324
+ border-radius: 999px;
325
+ background: #6366f1;
326
+ box-shadow: 0 0 12px rgba(99, 102, 241, 0.9);
327
+ }
328
+ .icon-wrap {
329
+ width: 60px;
330
+ height: 60px;
331
+ margin: 0 auto 18px;
332
+ border-radius: 999px;
333
+ display: grid;
334
+ place-items: center;
335
+ background: ${badgeBg};
336
+ border: 1px solid ${badgeBorder};
337
+ }
338
+ .pill {
339
+ display: inline-block;
340
+ font-size: 12px;
341
+ font-weight: 500;
342
+ color: ${badgeColor};
343
+ background: ${badgeBg};
344
+ border: 1px solid ${badgeBorder};
345
+ border-radius: 999px;
346
+ padding: 4px 10px;
347
+ margin-bottom: 14px;
348
+ }
349
+ h1 {
350
+ font-size: 22px;
351
+ font-weight: 650;
352
+ letter-spacing: -0.02em;
353
+ margin-bottom: 10px;
354
+ color: #ffffff;
355
+ }
356
+ p {
357
+ font-size: 14px;
358
+ line-height: 1.6;
359
+ color: #a1a1aa;
360
+ }
361
+ .detail {
362
+ margin-top: 16px;
363
+ padding: 10px 12px;
364
+ border-radius: 10px;
365
+ background: rgba(255, 255, 255, 0.04);
366
+ border: 1px solid rgba(255, 255, 255, 0.08);
367
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
368
+ font-size: 12px;
369
+ color: #d4d4d8;
370
+ word-break: break-word;
371
+ }
372
+ .hint {
373
+ margin-top: 22px;
374
+ padding-top: 18px;
375
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
376
+ font-size: 12px;
377
+ color: #71717a;
378
+ }
379
+ code {
380
+ background: rgba(255, 255, 255, 0.08);
381
+ padding: 2px 6px;
382
+ border-radius: 6px;
383
+ color: #e4e4e7;
384
+ }
385
+ </style>
386
+ </head>
387
+ <body>
388
+ <main class="card">
389
+ <div class="brand"><span class="brand-dot"></span>SagaCloud CLI</div>
390
+ <div class="icon-wrap">${iconSvg}</div>
391
+ <div class="pill">${pillText}</div>
392
+ <h1>${escapeHtml(opts.title)}</h1>
393
+ <p>${escapeHtml(opts.subtitle)}</p>
394
+ ${detailBlock}
395
+ <div class="hint">Return to your terminal to continue using <code>sagacloud</code>. You can safely close this tab.</div>
396
+ </main>
397
+ </body>
398
+ </html>`;
399
+ }
400
+ function registerAuthCommands(program2) {
401
+ program2.command("login").description("Authenticate CLI via browser approval or --token").option("--token <token>", "Store an existing sc_live_... API token directly").option("--url <apiUrl>", "SagaCloud API base URL", DEFAULT_API_BASE_URL).option("--panel-url <panelUrl>", "SagaCloud Dashboard URL for browser login", DEFAULT_PANEL_BASE_URL).action(async (opts) => {
402
+ const apiUrl = (opts.url || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
403
+ if (opts.token) {
404
+ const spin2 = p.spinner();
405
+ spin2.start("Verifying SagaCloud API token...");
406
+ const client = new SagaCloudClient({ token: opts.token.trim(), apiUrl });
407
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
408
+ writeAuthProfile({
409
+ token: opts.token.trim(),
410
+ apiUrl,
411
+ panelUrl: opts.panelUrl,
412
+ user: info.user,
413
+ tenant: info.tenant,
414
+ tenantName: info.tenant_name,
415
+ tokenName: info.token_name
416
+ });
417
+ spin2.stop(`Authenticated as ${pc.green(info.user)} (Workspace: ${pc.cyan(info.tenant_name)})`);
418
+ return;
419
+ }
420
+ const state = crypto.randomBytes(24).toString("hex");
421
+ const server = http.createServer();
422
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
423
+ const addr = server.address();
424
+ if (!addr || typeof addr === "string") {
425
+ throw new Error("Could not bind local loopback port for login.");
426
+ }
427
+ const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
428
+ const panelBase = (opts.panelUrl || DEFAULT_PANEL_BASE_URL).replace(/\/+$/, "");
429
+ const authUrl = new URL(`${panelBase}/hosting/cli-auth`);
430
+ authUrl.searchParams.set("callback", callbackUrl);
431
+ authUrl.searchParams.set("state", state);
432
+ authUrl.searchParams.set("device", os2.hostname());
433
+ console.log(pc.bold("Opening SagaCloud browser login..."));
434
+ console.log(`If your browser doesn't open, visit:
435
+ ${pc.cyan(authUrl.toString())}
436
+ `);
437
+ openBrowser(authUrl.toString());
438
+ const code = await new Promise((resolve, reject) => {
439
+ const timeout = setTimeout(() => {
440
+ server.close();
441
+ reject(new Error("Login timed out after 3 minutes."));
442
+ }, 18e4);
443
+ server.on("request", (req, res) => {
444
+ const reqUrl = new URL(req.url || "/", `http://127.0.0.1:${addr.port}`);
445
+ if (reqUrl.pathname !== "/callback") {
446
+ res.writeHead(404).end("Not found");
447
+ return;
448
+ }
449
+ const recvState = reqUrl.searchParams.get("state") || "";
450
+ const recvCode = reqUrl.searchParams.get("code") || "";
451
+ const err = reqUrl.searchParams.get("error");
452
+ if (err) {
453
+ clearTimeout(timeout);
454
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(
455
+ renderCallbackHtml({
456
+ title: "CLI Login Cancelled",
457
+ subtitle: "Authorization was declined or interrupted in the browser.",
458
+ detail: err,
459
+ ok: false
460
+ })
461
+ );
462
+ server.close();
463
+ reject(new Error(err));
464
+ return;
465
+ }
466
+ if (recvState !== state || !recvCode) {
467
+ clearTimeout(timeout);
468
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(
469
+ renderCallbackHtml({
470
+ title: "Invalid Authorization Callback",
471
+ subtitle: "Missing authorization code or mismatched security state. Re-run `sagacloud login`.",
472
+ ok: false
473
+ })
474
+ );
475
+ server.close();
476
+ reject(new Error("Invalid CLI login state/code."));
477
+ return;
478
+ }
479
+ clearTimeout(timeout);
480
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(
481
+ renderCallbackHtml({
482
+ title: "SagaCloud CLI Authorized",
483
+ subtitle: "Your terminal is now receiving a scoped workspace token and signing you in.",
484
+ ok: true
485
+ })
486
+ );
487
+ server.close();
488
+ resolve(recvCode);
489
+ });
490
+ });
491
+ const spin = p.spinner();
492
+ spin.start("Exchanging one-time authorization code...");
493
+ const exchanged = await exchangeCliCode(apiUrl, code);
494
+ writeAuthProfile({
495
+ token: exchanged.token,
496
+ apiUrl,
497
+ panelUrl: panelBase,
498
+ user: exchanged.user,
499
+ tenant: exchanged.tenant,
500
+ tenantName: exchanged.tenant_name,
501
+ tokenName: exchanged.token_name
502
+ });
503
+ spin.stop(
504
+ `Logged in as ${pc.green(exchanged.user)} \xB7 Workspace: ${pc.cyan(exchanged.tenant_name)} (${pc.dim(exchanged.token_prefix)}...)`
505
+ );
506
+ });
507
+ program2.command("logout").description("Revoke active CLI token on server and remove local credentials").action(async () => {
508
+ const profile = readAuthProfile();
509
+ if (!profile) {
510
+ console.log(pc.yellow("No local CLI credentials found."));
511
+ return;
512
+ }
513
+ try {
514
+ const client = new SagaCloudClient(profile);
515
+ await client.rpc("saga_cloud.api.cli_auth.revoke_current_cli_token", { method: "POST" });
516
+ } catch (err) {
517
+ console.log(pc.yellow(`Server revoke note: ${err.message}`));
518
+ }
519
+ clearAuthProfile();
520
+ console.log(pc.green(`Logged out and removed ${getAuthFilePath()}`));
521
+ });
522
+ program2.command("whoami").description("Display active CLI user, workspace, and token scopes").action(async () => {
523
+ const client = new SagaCloudClient();
524
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
525
+ console.log(`${pc.bold("User:")} ${info.user}`);
526
+ console.log(`${pc.bold("Workspace:")} ${info.tenant_name} (${info.tenant})`);
527
+ console.log(`${pc.bold("Token:")} ${info.token_name || "-"} (${info.token_prefix || "env"}...)`);
528
+ console.log(`${pc.bold("Scopes:")} ${(info.scopes || []).join(", ")}`);
529
+ console.log(`${pc.bold("API URL:")} ${client.baseUrl}`);
530
+ });
531
+ const tokens = program2.command("tokens").description("Manage SagaCloud API & CI/CD tokens");
532
+ tokens.command("ls").description("List API tokens in active workspace").action(async () => {
533
+ const client = new SagaCloudClient();
534
+ const res = await client.rpc("saga_cloud.api.cli_auth.list_cli_tokens");
535
+ const table = new Table({ head: ["ID", "Name", "Prefix", "Status", "Scopes", "Last Used"] });
536
+ for (const t of res.tokens || []) {
537
+ table.push([
538
+ t.token_id,
539
+ t.token_name,
540
+ t.token_prefix,
541
+ t.status === "Active" ? pc.green(t.status) : pc.red(t.status),
542
+ (t.scopes || []).join(","),
543
+ t.last_used_at || "-"
544
+ ]);
545
+ }
546
+ console.log(table.toString());
547
+ });
548
+ tokens.command("create <name>").description("Create a new scoped CI/CD token").option("--scopes <scopes>", "Comma-separated scopes", "read,deploy,env:write").option("--expires-days <days>", "Expiry in days").action(async (name, opts) => {
549
+ const client = new SagaCloudClient();
550
+ const res = await client.rpc(
551
+ "saga_cloud.api.cli_auth.issue_cli_token",
552
+ {
553
+ method: "POST",
554
+ body: {
555
+ token_name: name,
556
+ scopes: opts.scopes,
557
+ expires_days: opts.expiresDays ? Number(opts.expiresDays) : void 0
558
+ }
559
+ }
560
+ );
561
+ console.log(pc.green(`Created token ${res.token_id}:`));
562
+ console.log(pc.bold(res.token));
563
+ console.log(pc.dim("Save this token now \u2014 it will not be shown again."));
564
+ });
565
+ tokens.command("revoke <tokenId>").description("Revoke an API token by ID").action(async (tokenId) => {
566
+ const client = new SagaCloudClient();
567
+ await client.rpc("saga_cloud.api.cli_auth.revoke_cli_token", {
568
+ method: "POST",
569
+ body: { token_id: tokenId }
570
+ });
571
+ console.log(pc.green(`Revoked token ${tokenId}`));
572
+ });
573
+ }
574
+
575
+ // src/commands/deploy.ts
576
+ import { execSync } from "child_process";
577
+ import fs4 from "fs";
578
+ import path4 from "path";
579
+ import * as p2 from "@clack/prompts";
580
+ import pc3 from "picocolors";
581
+
582
+ // src/lib/detect.ts
583
+ import fs2 from "fs";
584
+ import path2 from "path";
585
+ function detectProject(cwd = process.cwd()) {
586
+ const pkgPath = path2.join(cwd, "package.json");
587
+ if (!fs2.existsSync(pkgPath)) {
588
+ if (fs2.existsSync(path2.join(cwd, "index.php"))) {
589
+ return {
590
+ frameworkLabel: "PHP / Static Site",
591
+ siteType: "static",
592
+ runtimeVariant: "php",
593
+ needsLocalBuild: false,
594
+ buildCommand: "",
595
+ outputDir: ".",
596
+ startCommand: "",
597
+ port: "80"
598
+ };
599
+ }
600
+ return {
601
+ frameworkLabel: "Static HTML Site",
602
+ siteType: "static",
603
+ runtimeVariant: "html",
604
+ needsLocalBuild: false,
605
+ buildCommand: "",
606
+ outputDir: ".",
607
+ startCommand: "",
608
+ port: "80"
609
+ };
610
+ }
611
+ const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
612
+ const deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
613
+ const scripts = pkg.scripts || {};
614
+ if (deps.express || deps.fastify || deps["@nestjs/core"] || deps.hono || deps.koa) {
615
+ const label = deps["@nestjs/core"] ? "NestJS Backend" : deps.fastify ? "Fastify Node Server" : deps.hono ? "Hono Node Server" : "Express Node.js Server";
616
+ return {
617
+ frameworkLabel: label,
618
+ siteType: "node",
619
+ runtimeVariant: "node",
620
+ needsLocalBuild: false,
621
+ buildCommand: scripts.build ? "npm run build" : "",
622
+ outputDir: "",
623
+ startCommand: scripts.start ? "npm start" : "node index.js",
624
+ port: "3000"
625
+ };
626
+ }
627
+ if (deps.next) {
628
+ const nextCfg = ["next.config.ts", "next.config.mjs", "next.config.js"].map((f) => path2.join(cwd, f)).find((f) => fs2.existsSync(f));
629
+ const nextCfgTxt = nextCfg ? fs2.readFileSync(nextCfg, "utf8") : "";
630
+ const isStaticExport = /output\s*:\s*['"]export['"]/.test(nextCfgTxt);
631
+ if (isStaticExport) {
632
+ return {
633
+ frameworkLabel: "Next.js Static Export",
634
+ siteType: "static",
635
+ runtimeVariant: "spa",
636
+ needsLocalBuild: Boolean(scripts.build),
637
+ buildCommand: scripts.build ? "npm run build" : "",
638
+ outputDir: "out",
639
+ startCommand: "",
640
+ port: "80"
641
+ };
642
+ }
643
+ return {
644
+ frameworkLabel: "Next.js SSR Web App",
645
+ siteType: "node",
646
+ runtimeVariant: "nextjs",
647
+ needsLocalBuild: false,
648
+ buildCommand: scripts.build ? "npm run build" : "",
649
+ outputDir: "",
650
+ startCommand: scripts.start ? "npm start" : "npx next start",
651
+ port: "3000"
652
+ };
653
+ }
654
+ if (deps["@angular/core"] || fs2.existsSync(path2.join(cwd, "angular.json"))) {
655
+ let angOut = "dist";
656
+ try {
657
+ const angPath = path2.join(cwd, "angular.json");
658
+ if (fs2.existsSync(angPath)) {
659
+ const ang = JSON.parse(fs2.readFileSync(angPath, "utf8"));
660
+ const projects = ang.projects || {};
661
+ const projKey = ang.defaultProject && projects[ang.defaultProject] ? ang.defaultProject : Object.keys(projects)[0];
662
+ const outOpt = projKey ? projects[projKey]?.architect?.build?.options?.outputPath : void 0;
663
+ if (typeof outOpt === "string" && outOpt) {
664
+ angOut = fs2.existsSync(path2.join(cwd, outOpt, "browser")) ? path2.join(outOpt, "browser") : outOpt;
665
+ } else if (outOpt && typeof outOpt === "object" && outOpt.base) {
666
+ const browserSub = outOpt.browser ?? "browser";
667
+ angOut = browserSub ? path2.join(outOpt.base, browserSub) : outOpt.base;
668
+ }
669
+ }
670
+ } catch {
671
+ angOut = "dist";
672
+ }
673
+ return {
674
+ frameworkLabel: "Angular SPA",
675
+ siteType: "static",
676
+ runtimeVariant: "spa",
677
+ needsLocalBuild: Boolean(scripts.build),
678
+ buildCommand: scripts.build ? "npm run build" : "",
679
+ outputDir: angOut,
680
+ startCommand: "",
681
+ port: "80"
682
+ };
683
+ }
684
+ if (deps.vite || deps["react-scripts"] || deps.astro) {
685
+ const frameworkLabel = deps.astro ? "Astro Static Site" : deps.vue ? "Vue / Vite SPA" : deps["react-scripts"] ? "React (CRA) SPA" : "React / Vite SPA";
686
+ return {
687
+ frameworkLabel,
688
+ siteType: "static",
689
+ runtimeVariant: "spa",
690
+ needsLocalBuild: Boolean(scripts.build),
691
+ buildCommand: scripts.build ? "npm run build" : "",
692
+ outputDir: deps["react-scripts"] ? "build" : "dist",
693
+ startCommand: "",
694
+ port: "80"
695
+ };
696
+ }
697
+ if (scripts.start && !scripts.build) {
698
+ return {
699
+ frameworkLabel: "Node.js App",
700
+ siteType: "node",
701
+ runtimeVariant: "node",
702
+ needsLocalBuild: false,
703
+ buildCommand: "",
704
+ outputDir: "",
705
+ startCommand: "npm start",
706
+ port: "3000"
707
+ };
708
+ }
709
+ return {
710
+ frameworkLabel: fs2.existsSync(path2.join(cwd, "dist")) || scripts.build ? "Web SPA / Static Build" : "Static Site",
711
+ siteType: "static",
712
+ runtimeVariant: scripts.build ? "spa" : "html",
713
+ needsLocalBuild: Boolean(scripts.build),
714
+ buildCommand: scripts.build ? "npm run build" : "",
715
+ outputDir: scripts.build ? "dist" : ".",
716
+ startCommand: "",
717
+ port: "80"
718
+ };
719
+ }
720
+
721
+ // src/lib/stream.ts
722
+ import pc2 from "picocolors";
723
+ async function streamBuildUntilDone(client, siteId, deploymentUuid) {
724
+ let printed = 0;
725
+ let lastStatus = "queued";
726
+ while (true) {
727
+ const res = await client.rpc("saga_cloud.api.hosting.get_deployment_status", {
728
+ query: { site_id: siteId, deployment_uuid: deploymentUuid }
729
+ });
730
+ const logs = res.logs || [];
731
+ for (let i = printed; i < logs.length; i += 1) {
732
+ const row = logs[i];
733
+ const msg = (row.output || "").trimEnd();
734
+ if (!msg) continue;
735
+ if (row.type === "stderr" || /ERROR|failed/i.test(msg)) {
736
+ console.log(pc2.red(msg));
737
+ } else {
738
+ console.log(pc2.dim(msg));
739
+ }
740
+ }
741
+ printed = logs.length;
742
+ lastStatus = (res.deployment?.status || res.status || "queued").toLowerCase();
743
+ if (["finished", "failed", "cancelled"].includes(lastStatus)) {
744
+ return lastStatus;
745
+ }
746
+ await new Promise((r) => setTimeout(r, 2500));
747
+ }
748
+ }
749
+ async function streamRuntimeLogs(client, siteId, lines = 100, follow = false) {
750
+ if (!follow) {
751
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
752
+ query: { site_id: siteId, lines }
753
+ });
754
+ console.log(res.logs || pc2.dim("(no logs yet)"));
755
+ return;
756
+ }
757
+ await client.rpc("saga_cloud.api.hosting.start_site_log_stream", {
758
+ method: "POST",
759
+ body: { site_id: siteId, lines }
760
+ });
761
+ let previousLines = [];
762
+ let running = true;
763
+ const stop = async () => {
764
+ running = false;
765
+ try {
766
+ await client.rpc("saga_cloud.api.hosting.stop_site_log_stream", {
767
+ method: "POST",
768
+ body: { site_id: siteId }
769
+ });
770
+ } catch {
771
+ }
772
+ };
773
+ process.once("SIGINT", () => {
774
+ void stop().then(() => process.exit(0));
775
+ });
776
+ let ticks = 0;
777
+ while (running) {
778
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
779
+ query: { site_id: siteId, lines }
780
+ });
781
+ const current = (res.logs || "").split(/\r?\n/).filter(Boolean);
782
+ if (previousLines.length === 0) {
783
+ for (const ln of current) console.log(ln);
784
+ } else {
785
+ const lastPrev = previousLines[previousLines.length - 1];
786
+ const matchIdx = current.lastIndexOf(lastPrev);
787
+ const added = matchIdx >= 0 ? current.slice(matchIdx + 1) : current;
788
+ for (const ln of added) console.log(ln);
789
+ }
790
+ previousLines = current;
791
+ ticks += 1;
792
+ if (ticks % 5 === 0) {
793
+ await client.rpc("saga_cloud.api.hosting.heartbeat_site_log_stream", {
794
+ method: "POST",
795
+ body: { site_id: siteId }
796
+ });
797
+ }
798
+ await new Promise((r) => setTimeout(r, 2500));
799
+ }
800
+ }
801
+
802
+ // src/lib/zip.ts
803
+ import fs3 from "fs";
804
+ import path3 from "path";
805
+ import archiver from "archiver";
806
+ import ignore from "ignore";
807
+ var ALWAYS_IGNORED = [
808
+ ".git",
809
+ ".git/**",
810
+ "node_modules",
811
+ "node_modules/**",
812
+ ".sagacloud",
813
+ ".sagacloud/**",
814
+ ".DS_Store",
815
+ "Thumbs.db",
816
+ "__MACOSX",
817
+ "__MACOSX/**",
818
+ ".env",
819
+ ".env.*",
820
+ "sagacloud.jsonc",
821
+ "sagacloud.json"
822
+ ];
823
+ async function createArchiveFromDirectory(targetDir, extraIgnorePatterns = [], includeGitignore = false) {
824
+ if (!fs3.existsSync(targetDir) || !fs3.statSync(targetDir).isDirectory()) {
825
+ throw new Error(`Directory not found: ${targetDir}`);
826
+ }
827
+ const ig = ignore().add(ALWAYS_IGNORED);
828
+ if (extraIgnorePatterns.length > 0) {
829
+ ig.add(extraIgnorePatterns);
830
+ }
831
+ if (includeGitignore) {
832
+ for (const ignoreFile of [".gitignore", ".sagacloudignore"]) {
833
+ const fp = path3.join(targetDir, ignoreFile);
834
+ if (fs3.existsSync(fp)) {
835
+ ig.add(fs3.readFileSync(fp, "utf8"));
836
+ }
837
+ }
838
+ }
839
+ return await new Promise((resolve, reject) => {
840
+ const chunks = [];
841
+ const archive = archiver("zip", { zlib: { level: 9 } });
842
+ let fileCount = 0;
843
+ archive.on("data", (chunk) => chunks.push(chunk));
844
+ archive.on("error", (err) => reject(err));
845
+ archive.on("end", () => {
846
+ const buffer = Buffer.concat(chunks);
847
+ resolve({ buffer, fileCount, sizeBytes: buffer.length });
848
+ });
849
+ const walk = (dir) => {
850
+ for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
851
+ const fullPath = path3.join(dir, entry.name);
852
+ const rel = path3.relative(targetDir, fullPath).replace(/\\/g, "/");
853
+ if (!rel) continue;
854
+ if (entry.isDirectory()) {
855
+ if (ig.ignores(`${rel}/`) || ig.ignores(rel)) continue;
856
+ walk(fullPath);
857
+ } else if (entry.isFile()) {
858
+ if (ig.ignores(rel)) continue;
859
+ fileCount += 1;
860
+ archive.file(fullPath, { name: rel });
861
+ }
862
+ }
863
+ };
864
+ walk(targetDir);
865
+ archive.finalize().catch(reject);
866
+ });
867
+ }
868
+
869
+ // src/commands/deploy.ts
870
+ function parseDotEnvText(raw) {
871
+ const rows = [];
872
+ for (const line of raw.split(/\r?\n/)) {
873
+ const trimmed = line.trim();
874
+ if (!trimmed || trimmed.startsWith("#")) continue;
875
+ const eq = trimmed.indexOf("=");
876
+ if (eq <= 0) continue;
877
+ const key = trimmed.slice(0, eq).trim();
878
+ let val = trimmed.slice(eq + 1).trim();
879
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
880
+ val = val.slice(1, -1);
881
+ }
882
+ if (key) rows.push({ key, value: val });
883
+ }
884
+ return rows;
885
+ }
886
+ function registerDeployCommands(program2) {
887
+ program2.command("deploy").alias("up").description("Deploy local static/SPA output, Express/Node source, or Git site to SagaCloud").option("--site <siteId>", "Target Site ID (overrides .sagacloud/project.json)").option("--name <siteName>", "Site name when creating a new site").option("--dir <outputDir>", "Pre-built static output directory (e.g. ./dist)").option("--build", "Run local build command before packaging static output").option("--no-build", "Skip running local build command").option("--static", "Deploy as static HTML/PHP site").option("--spa", "Deploy as Single Page App (Nginx try_files /index.html)").option("--node", "Deploy as Node.js / Express / SSR application").option("--port <port>", "Listening HTTP port for Node.js app", "3000").option("--start <cmd>", "Start command for Node.js app").option("--git", "Trigger remote Git redeploy instead of uploading local files").option("--force", "Bypass build cache on remote rebuild", false).option("--with-env <file>", "Load and push .env file variables before building").option("--detach", "Queue deployment and exit without streaming build logs", false).option("--yes", "Skip interactive prompts", false).action(
888
+ async (opts) => {
889
+ const cwd = process.cwd();
890
+ const client = new SagaCloudClient();
891
+ const { config: jsonc } = readRepoJsoncConfig(cwd);
892
+ const link = readLocalLink(cwd);
893
+ const detected = detectProject(cwd);
894
+ const existingSiteId = opts.site || link?.site_id || jsonc?.site_id || "";
895
+ if (opts.git) {
896
+ const targetId = resolveActiveSiteId(cwd, existingSiteId);
897
+ const spin2 = p2.spinner();
898
+ spin2.start("Queueing Git deployment...");
899
+ const res = await client.rpc(
900
+ "saga_cloud.api.hosting.redeploy_site",
901
+ { method: "POST", body: { site_id: targetId, force_rebuild: Boolean(opts.force) } }
902
+ );
903
+ const gitSite = res.site || (await client.rpc("saga_cloud.api.hosting.get_site_details", {
904
+ query: { site_id: targetId, limit: 1 }
905
+ })).site;
906
+ spin2.stop(`Queued v${res.deployment.version_number} for ${gitSite.domain}`);
907
+ if (!opts.detach && res.deployment.deployment_uuid) {
908
+ const finalStatus2 = await streamBuildUntilDone(client, gitSite.name, res.deployment.deployment_uuid);
909
+ console.log(
910
+ finalStatus2 === "finished" ? pc3.green(`\u2713 Live at ${gitSite.live_url || `https://${gitSite.domain}`}`) : pc3.red(`\u2717 Deployment ended with status: ${finalStatus2}`)
911
+ );
912
+ if (finalStatus2 !== "finished") process.exit(1);
913
+ }
914
+ return;
915
+ }
916
+ let siteType = detected.siteType;
917
+ let runtimeVariant = detected.runtimeVariant;
918
+ if (opts.dir || opts.spa || opts.static) {
919
+ siteType = "static";
920
+ runtimeVariant = opts.spa ? "spa" : opts.static ? "html" : detected.runtimeVariant === "php" ? "php" : "spa";
921
+ } else if (opts.node) {
922
+ siteType = "node";
923
+ runtimeVariant = detected.runtimeVariant === "nextjs" ? "nextjs" : "node";
924
+ } else if (jsonc?.type) {
925
+ if (jsonc.type === "node" || jsonc.type === "nextjs") {
926
+ siteType = "node";
927
+ runtimeVariant = jsonc.type;
928
+ } else {
929
+ siteType = "static";
930
+ runtimeVariant = jsonc.type === "static" || jsonc.type === "spa" && jsonc.spa_fallback === false ? "html" : jsonc.type;
931
+ }
932
+ } else if (link?.site_type) {
933
+ siteType = link.site_type;
934
+ if (link.runtime_variant) runtimeVariant = link.runtime_variant;
935
+ }
936
+ const buildCmd = jsonc?.build_command || detected.buildCommand;
937
+ const shouldRunLocalBuild = siteType === "static" && !opts.dir && opts.build !== false && (Boolean(opts.build) || detected.needsLocalBuild || Boolean(jsonc?.build_command));
938
+ if (shouldRunLocalBuild && buildCmd) {
939
+ console.log(pc3.cyan(`Running local build: ${buildCmd}`));
940
+ execSync(buildCmd, { stdio: "inherit", cwd });
941
+ }
942
+ const outputRel = opts.dir || jsonc?.output_dir || link?.output_dir || detected.outputDir || ".";
943
+ const uploadDir = siteType === "node" ? cwd : path4.resolve(cwd, outputRel);
944
+ if (!fs4.existsSync(uploadDir)) {
945
+ throw new Error(
946
+ `Output directory '${outputRel}' not found. Run your build or specify --dir <path>.`
947
+ );
948
+ }
949
+ const spin = p2.spinner();
950
+ spin.start(`Packaging ${siteType === "node" ? "Node.js source" : outputRel}...`);
951
+ const archive = await createArchiveFromDirectory(
952
+ uploadDir,
953
+ jsonc?.ignore || [],
954
+ siteType === "node"
955
+ );
956
+ spin.stop(
957
+ `Packaged ${archive.fileCount} files (${(archive.sizeBytes / 1024).toFixed(1)} KB)`
958
+ );
959
+ const uploadSpin = p2.spinner();
960
+ uploadSpin.start("Uploading bundle to SagaCloud...");
961
+ const zipName = `${(jsonc?.name || path4.basename(cwd) || "bundle").replace(/[^a-z0-9-]+/gi, "-")}.zip`;
962
+ const uploaded = await client.uploadBundle(archive.buffer, zipName, siteType);
963
+ uploadSpin.stop(`Uploaded (${uploaded.detected_entry})`);
964
+ const mergedVars = /* @__PURE__ */ new Map();
965
+ if (jsonc?.vars) {
966
+ for (const [k, v] of Object.entries(jsonc.vars)) {
967
+ mergedVars.set(k, String(v));
968
+ }
969
+ }
970
+ if (opts.withEnv) {
971
+ const envPath = path4.resolve(cwd, opts.withEnv);
972
+ if (!fs4.existsSync(envPath)) throw new Error(`Env file not found: ${envPath}`);
973
+ for (const item of parseDotEnvText(fs4.readFileSync(envPath, "utf8"))) {
974
+ mergedVars.set(item.key, item.value);
975
+ }
976
+ }
977
+ const envPayload = Array.from(mergedVars.entries()).map(([key, value]) => ({
978
+ key,
979
+ value,
980
+ is_build_time: siteType === "static"
981
+ }));
982
+ let targetSite;
983
+ let dep;
984
+ if (existingSiteId) {
985
+ if (envPayload.length > 0) {
986
+ await client.rpc("saga_cloud.api.hosting.save_site_envs", {
987
+ method: "POST",
988
+ body: { site_id: existingSiteId, envs: envPayload }
989
+ });
990
+ }
991
+ const depSpin = p2.spinner();
992
+ depSpin.start(`Deploying update to ${existingSiteId}...`);
993
+ const res = await client.rpc(
994
+ "saga_cloud.api.hosting.redeploy_site",
995
+ {
996
+ method: "POST",
997
+ body: {
998
+ site_id: existingSiteId,
999
+ force_rebuild: true,
1000
+ new_zip_file_url: uploaded.file_url
1001
+ }
1002
+ }
1003
+ );
1004
+ targetSite = res.site || (await client.rpc("saga_cloud.api.hosting.get_site_details", {
1005
+ query: { site_id: existingSiteId, limit: 1 }
1006
+ })).site;
1007
+ dep = res.deployment;
1008
+ depSpin.stop(`Deployment v${dep.version_number} queued for ${targetSite.domain}`);
1009
+ } else {
1010
+ const defaultName = opts.name || jsonc?.name || path4.basename(cwd).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "") || "sagacloud-app";
1011
+ const siteName = opts.yes ? defaultName : String(
1012
+ await p2.text({
1013
+ message: `Create new ${siteType.toUpperCase()} site name`,
1014
+ initialValue: defaultName
1015
+ })
1016
+ );
1017
+ const createSpin = p2.spinner();
1018
+ createSpin.start(`Creating ${siteType} site '${siteName}'...`);
1019
+ const res = await client.rpc(
1020
+ "saga_cloud.api.hosting.create_site",
1021
+ {
1022
+ method: "POST",
1023
+ body: {
1024
+ site_name: siteName,
1025
+ site_type: siteType,
1026
+ runtime_variant: runtimeVariant,
1027
+ source_type: "zip_upload",
1028
+ zip_file_url: uploaded.file_url,
1029
+ is_spa: runtimeVariant === "spa",
1030
+ ports_exposes: siteType === "node" ? String(opts.port || jsonc?.port || detected.port || "3000") : "80",
1031
+ install_command: jsonc?.install_command || "",
1032
+ build_command: siteType === "node" ? jsonc?.build_command || detected.buildCommand || "" : "",
1033
+ start_command: siteType === "node" ? opts.start || jsonc?.start_command || detected.startCommand || "npm start" : "",
1034
+ publish_directory: siteType === "static" ? outputRel : "",
1035
+ env_vars: envPayload.length > 0 ? envPayload : void 0
1036
+ }
1037
+ }
1038
+ );
1039
+ targetSite = res.site;
1040
+ dep = res.deployment;
1041
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
1042
+ writeLocalLink(
1043
+ {
1044
+ site_id: targetSite.name,
1045
+ tenant_id: info.tenant,
1046
+ site_type: siteType,
1047
+ runtime_variant: runtimeVariant,
1048
+ output_dir: siteType === "static" ? outputRel : ""
1049
+ },
1050
+ cwd
1051
+ );
1052
+ createSpin.stop(`Created ${targetSite.name} -> ${pc3.cyan(targetSite.live_url || targetSite.domain)}`);
1053
+ }
1054
+ if (opts.detach || !dep.deployment_uuid) {
1055
+ console.log(pc3.dim(`Deployment ${dep.name} queued. Check progress with: sagacloud logs`));
1056
+ return;
1057
+ }
1058
+ const finalStatus = await streamBuildUntilDone(client, targetSite.name, dep.deployment_uuid);
1059
+ if (finalStatus === "finished") {
1060
+ console.log(pc3.green(`
1061
+ \u2713 Deployment v${dep.version_number} live at ${targetSite.live_url || `https://${targetSite.domain}`}`));
1062
+ } else {
1063
+ console.log(pc3.red(`
1064
+ \u2717 Deployment ${dep.name} ${finalStatus}`));
1065
+ process.exit(1);
1066
+ }
1067
+ }
1068
+ );
1069
+ program2.command("cancel").description("Cancel active queued/running deployment").option("--site <siteId>", "Site ID").option("--deployment <depId>", "Deployment ID").action(async (opts) => {
1070
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1071
+ const client = new SagaCloudClient();
1072
+ let depId = opts.deployment;
1073
+ if (!depId) {
1074
+ const list = await client.rpc(
1075
+ "saga_cloud.api.hosting.list_deployments",
1076
+ { query: { site_id: siteId, limit: 5 } }
1077
+ );
1078
+ const active = (list.deployments || []).find((d) => ["queued", "in_progress"].includes(d.status));
1079
+ if (!active) {
1080
+ console.log(pc3.yellow("No active queued or running deployment found."));
1081
+ return;
1082
+ }
1083
+ depId = active.name;
1084
+ }
1085
+ await client.rpc("saga_cloud.api.hosting.cancel_deployment", {
1086
+ method: "POST",
1087
+ body: { site_id: siteId, deployment_id: depId }
1088
+ });
1089
+ console.log(pc3.green(`Cancelled deployment ${depId}`));
1090
+ });
1091
+ }
1092
+
1093
+ // src/commands/env.ts
1094
+ import fs5 from "fs";
1095
+ import path5 from "path";
1096
+ import Table2 from "cli-table3";
1097
+ import pc4 from "picocolors";
1098
+ function registerEnvCommands(program2) {
1099
+ const env = program2.command("env").description("Manage site environment variables");
1100
+ env.command("ls").description("List environment variables for linked site").option("--site <siteId>", "Site ID").option("--reveal", "Show unmasked values", false).action(async (opts) => {
1101
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1102
+ const client = new SagaCloudClient();
1103
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_envs", {
1104
+ query: { site_id: siteId }
1105
+ });
1106
+ const table = new Table2({ head: ["Key", "Value", "Build-time", "UUID"] });
1107
+ for (const item of res.envs || []) {
1108
+ const shown = opts.reveal ? item.value : item.value ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" : "";
1109
+ table.push([item.key, shown, item.is_build_time ? pc4.green("Yes") : "No", pc4.dim(item.uuid || "-")]);
1110
+ }
1111
+ console.log(table.toString());
1112
+ });
1113
+ env.command("push [filePath]").description("Upload a local .env file to SagaCloud").option("--site <siteId>", "Site ID").option("--replace", "Delete remote variables not present in the uploaded file", false).action(async (filePath = ".env", opts) => {
1114
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1115
+ const target = path5.resolve(process.cwd(), filePath);
1116
+ if (!fs5.existsSync(target)) {
1117
+ throw new Error(`Env file not found: ${target}`);
1118
+ }
1119
+ const raw = fs5.readFileSync(target, "utf8");
1120
+ const client = new SagaCloudClient();
1121
+ const res = await client.rpc(
1122
+ "saga_cloud.api.hosting.save_site_envs",
1123
+ {
1124
+ method: "POST",
1125
+ body: { site_id: siteId, envs: raw, replace_missing: Boolean(opts.replace) }
1126
+ }
1127
+ );
1128
+ console.log(pc4.green(`Synced ${res.envs?.length || 0} variables from ${filePath}. Redeploy to apply changes.`));
1129
+ });
1130
+ env.command("pull [filePath]").description("Download remote environment variables to a local file").option("--site <siteId>", "Site ID").action(async (filePath = ".env.local", opts) => {
1131
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1132
+ const client = new SagaCloudClient();
1133
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_envs", {
1134
+ query: { site_id: siteId }
1135
+ });
1136
+ const outPath = path5.resolve(process.cwd(), filePath);
1137
+ const lines = (res.envs || []).map((item) => {
1138
+ const val = String(item.value ?? "");
1139
+ const needsQuotes = /[\s#'"]/.test(val);
1140
+ return `${item.key}=${needsQuotes ? JSON.stringify(val) : val}`;
1141
+ });
1142
+ fs5.writeFileSync(outPath, `${lines.join("\n")}
1143
+ `, { mode: 384 });
1144
+ console.log(pc4.green(`Wrote ${lines.length} variables to ${filePath}`));
1145
+ });
1146
+ env.command("set <pairs...>").description("Set one or more KEY=VALUE variables").option("--site <siteId>", "Site ID").option("--build-time", "Mark variables as build-time", false).action(async (pairs, opts) => {
1147
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1148
+ const parsed = pairs.map((entry) => {
1149
+ const idx = entry.indexOf("=");
1150
+ if (idx <= 0) throw new Error(`Invalid pair '${entry}'. Expected KEY=VALUE.`);
1151
+ return {
1152
+ key: entry.slice(0, idx).trim(),
1153
+ value: entry.slice(idx + 1),
1154
+ is_build_time: Boolean(opts.buildTime)
1155
+ };
1156
+ });
1157
+ const client = new SagaCloudClient();
1158
+ await client.rpc("saga_cloud.api.hosting.save_site_envs", {
1159
+ method: "POST",
1160
+ body: { site_id: siteId, envs: parsed }
1161
+ });
1162
+ console.log(pc4.green(`Saved ${parsed.length} variable(s). Run \`sagacloud deploy\` to apply.`));
1163
+ });
1164
+ env.command("rm <key>").description("Remove an environment variable by key").option("--site <siteId>", "Site ID").action(async (key, opts) => {
1165
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1166
+ const client = new SagaCloudClient();
1167
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_envs", {
1168
+ query: { site_id: siteId }
1169
+ });
1170
+ const match = (res.envs || []).find((e) => e.key === key);
1171
+ if (!match?.uuid) {
1172
+ throw new Error(`Environment variable '${key}' not found on site ${siteId}.`);
1173
+ }
1174
+ await client.rpc("saga_cloud.api.hosting.delete_site_env", {
1175
+ method: "POST",
1176
+ body: { site_id: siteId, env_uuid: match.uuid }
1177
+ });
1178
+ console.log(pc4.green(`Deleted variable ${key}`));
1179
+ });
1180
+ }
1181
+
1182
+ // src/commands/ops.ts
1183
+ import fs6 from "fs";
1184
+ import path6 from "path";
1185
+ import * as p3 from "@clack/prompts";
1186
+ import Table3 from "cli-table3";
1187
+ import pc5 from "picocolors";
1188
+ function registerOpsCommands(program2) {
1189
+ program2.command("logs [deploymentUuid]").description("View build or live container runtime logs").option("--site <siteId>", "Site ID").option("--runtime", "Fetch runtime container stdout/stderr instead of build logs", false).option("-f, --follow", "Stream runtime logs live", false).option("-n, --lines <lines>", "Lines to retrieve", "100").action(
1190
+ async (deploymentUuid, opts) => {
1191
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1192
+ const client = new SagaCloudClient();
1193
+ if (opts.runtime || opts.follow) {
1194
+ await streamRuntimeLogs(client, siteId, Number(opts.lines || 100), Boolean(opts.follow));
1195
+ return;
1196
+ }
1197
+ let targetDep = deploymentUuid;
1198
+ if (!targetDep) {
1199
+ const deps = await client.rpc(
1200
+ "saga_cloud.api.hosting.list_deployments",
1201
+ { query: { site_id: siteId, limit: 1 } }
1202
+ );
1203
+ targetDep = deps.deployments?.[0]?.deployment_uuid;
1204
+ }
1205
+ if (!targetDep) {
1206
+ console.log(pc5.yellow("No deployments found for this site."));
1207
+ return;
1208
+ }
1209
+ await streamBuildUntilDone(client, siteId, targetDep);
1210
+ }
1211
+ );
1212
+ program2.command("deployments").description("List deployment version history for a site").option("--site <siteId>", "Site ID").option("--limit <limit>", "Rows to fetch", "15").action(async (opts) => {
1213
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1214
+ const client = new SagaCloudClient();
1215
+ const res = await client.rpc(
1216
+ "saga_cloud.api.hosting.list_deployments",
1217
+ { query: { site_id: siteId, limit: Number(opts.limit || 15) } }
1218
+ );
1219
+ const table = new Table3({ head: ["Version", "ID", "Trigger", "Status", "Live", "Rollback", "Created"] });
1220
+ for (const d of res.deployments || []) {
1221
+ table.push([
1222
+ `v${d.version_number}`,
1223
+ d.name,
1224
+ d.trigger_type,
1225
+ d.status === "finished" ? pc5.green(d.status) : d.status === "failed" ? pc5.red(d.status) : d.status,
1226
+ d.is_active ? pc5.green("ACTIVE") : "-",
1227
+ d.can_instant_rollback ? "Yes" : "-",
1228
+ d.created_at
1229
+ ]);
1230
+ }
1231
+ console.log(table.toString());
1232
+ });
1233
+ program2.command("rollback <versionOrId>").description("Roll back site to a previous version (e.g. `v2` or deployment ID)").option("--site <siteId>", "Site ID").action(async (versionOrId, opts) => {
1234
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1235
+ const client = new SagaCloudClient();
1236
+ let depId = versionOrId.trim();
1237
+ const vMatch = depId.match(/^v?(\d+)$/i);
1238
+ if (vMatch) {
1239
+ const ver = Number(vMatch[1]);
1240
+ const list = await client.rpc(
1241
+ "saga_cloud.api.hosting.list_deployments",
1242
+ { query: { site_id: siteId, limit: 50 } }
1243
+ );
1244
+ const found = (list.deployments || []).find((d) => d.version_number === ver);
1245
+ if (!found) throw new Error(`Version v${ver} not found.`);
1246
+ depId = found.name;
1247
+ }
1248
+ const res = await client.rpc(
1249
+ "saga_cloud.api.hosting.rollback_site",
1250
+ { method: "POST", body: { site_id: siteId, target_deployment_id: depId } }
1251
+ );
1252
+ console.log(pc5.green(`Queued rollback v${res.deployment.version_number} (${res.rollback_mode || "instant"})`));
1253
+ if (res.deployment.deployment_uuid) {
1254
+ await streamBuildUntilDone(client, siteId, res.deployment.deployment_uuid);
1255
+ }
1256
+ });
1257
+ const domains = program2.command("domains").description("Manage custom domains & Edge SSL");
1258
+ domains.command("ls").description("List attached domains").option("--site <siteId>", "Site ID").action(async (opts) => {
1259
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1260
+ const client = new SagaCloudClient();
1261
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_details", {
1262
+ query: { site_id: siteId, limit: 1 }
1263
+ });
1264
+ const table = new Table3({ head: ["FQDN", "Mode", "Primary", "SSL", "CNAME Target"] });
1265
+ for (const d of res.site.domains || []) {
1266
+ table.push([
1267
+ d.fqdn,
1268
+ d.domain_mode,
1269
+ d.is_primary ? pc5.green("Yes") : "No",
1270
+ d.ssl_status === "Active" ? pc5.green(d.ssl_status) : pc5.yellow(d.ssl_status),
1271
+ d.cname_target || "-"
1272
+ ]);
1273
+ }
1274
+ console.log(table.toString());
1275
+ });
1276
+ domains.command("add <fqdn>").description("Attach a custom external domain or subdomain").option("--site <siteId>", "Site ID").option("--primary", "Make primary domain", false).action(async (fqdn, opts) => {
1277
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1278
+ const client = new SagaCloudClient();
1279
+ const res = await client.rpc(
1280
+ "saga_cloud.api.hosting.add_site_domain",
1281
+ {
1282
+ method: "POST",
1283
+ body: { site_id: siteId, domain_mode: "custom_external", custom_fqdn: fqdn, make_primary: Boolean(opts.primary) }
1284
+ }
1285
+ );
1286
+ console.log(pc5.green(`Added ${fqdn} to ${res.site.site_name}`));
1287
+ if (res.added_domain?.cname_target) {
1288
+ console.log(`Point DNS CNAME: ${pc5.bold(fqdn)} -> ${pc5.cyan(res.added_domain.cname_target)}`);
1289
+ console.log(pc5.dim(`Then verify SSL with: sagacloud domains verify ${fqdn}`));
1290
+ }
1291
+ });
1292
+ domains.command("verify <fqdn>").description("Verify DNS CNAME and issue Edge SSL").option("--site <siteId>", "Site ID").action(async (fqdn, opts) => {
1293
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1294
+ const client = new SagaCloudClient();
1295
+ const res = await client.rpc(
1296
+ "saga_cloud.api.hosting.verify_site_ssl",
1297
+ { method: "POST", body: { site_id: siteId, fqdn } }
1298
+ );
1299
+ console.log(res.issued ? pc5.green(res.message || "SSL Active") : pc5.yellow(res.message || "Pending"));
1300
+ });
1301
+ domains.command("rm <fqdn>").description("Detach a custom domain").option("--site <siteId>", "Site ID").action(async (fqdn, opts) => {
1302
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1303
+ const client = new SagaCloudClient();
1304
+ await client.rpc("saga_cloud.api.hosting.remove_site_domain", {
1305
+ method: "POST",
1306
+ body: { site_id: siteId, fqdn }
1307
+ });
1308
+ console.log(pc5.green(`Removed ${fqdn}`));
1309
+ });
1310
+ program2.command("purge").description("Purge Edge CDN cache for linked site").option("--site <siteId>", "Site ID").action(async (opts) => {
1311
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1312
+ const client = new SagaCloudClient();
1313
+ await client.rpc("saga_cloud.api.hosting.purge_site_cache", {
1314
+ method: "POST",
1315
+ body: { site_id: siteId }
1316
+ });
1317
+ console.log(pc5.green("Edge CDN cache purged."));
1318
+ });
1319
+ for (const action of ["start", "stop", "restart"]) {
1320
+ program2.command(action).description(`${action[0].toUpperCase()}${action.slice(1)} remote container`).option("--site <siteId>", "Site ID").action(async (opts) => {
1321
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1322
+ const client = new SagaCloudClient();
1323
+ await client.rpc("saga_cloud.api.hosting.execute_site_action", {
1324
+ method: "POST",
1325
+ body: { site_id: siteId, action }
1326
+ });
1327
+ console.log(pc5.green(`Container ${action} requested for ${siteId}.`));
1328
+ });
1329
+ }
1330
+ program2.command("delete").description("Delete a hosted site and unlink local project").option("--site <siteId>", "Site ID").option("--yes", "Skip confirmation", false).option("--keep-dns", "Keep auto-created DNS records", false).action(async (opts) => {
1331
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1332
+ if (!opts.yes) {
1333
+ const ok = await p3.confirm({ message: `Delete site ${siteId} permanently?` });
1334
+ if (p3.isCancel(ok) || !ok) return;
1335
+ }
1336
+ const client = new SagaCloudClient();
1337
+ await client.rpc("saga_cloud.api.hosting.delete_site", {
1338
+ method: "POST",
1339
+ body: { site_id: siteId, remove_dns_record: !opts.keepDns }
1340
+ });
1341
+ removeLocalLink(process.cwd());
1342
+ console.log(pc5.green(`Deleted site ${siteId}.`));
1343
+ });
1344
+ const ci = program2.command("ci").description("CI/CD helpers");
1345
+ ci.command("init").description("Generate .github/workflows/sagacloud.yml").action(() => {
1346
+ const cwd = process.cwd();
1347
+ const wfDir = path6.join(cwd, ".github", "workflows");
1348
+ fs6.mkdirSync(wfDir, { recursive: true });
1349
+ const outPath = path6.join(wfDir, "sagacloud.yml");
1350
+ const yml = [
1351
+ "name: Deploy to SagaCloud",
1352
+ "on:",
1353
+ " push:",
1354
+ " branches: [main]",
1355
+ "jobs:",
1356
+ " deploy:",
1357
+ " runs-on: ubuntu-latest",
1358
+ " steps:",
1359
+ " - uses: actions/checkout@v4",
1360
+ " - uses: actions/setup-node@v4",
1361
+ " with:",
1362
+ " node-version: 22",
1363
+ " - run: npm ci",
1364
+ " - run: npm run build",
1365
+ " - run: npx sagacloud deploy --no-build --yes",
1366
+ " env:",
1367
+ " SAGACLOUD_TOKEN: ${{ secrets.SAGACLOUD_TOKEN }}",
1368
+ ""
1369
+ ].join("\n");
1370
+ fs6.writeFileSync(outPath, yml);
1371
+ console.log(pc5.green(`Created ${outPath}. Add SAGACLOUD_TOKEN in GitHub Repository Secrets.`));
1372
+ });
1373
+ }
1374
+
1375
+ // src/commands/project.ts
1376
+ import fs7 from "fs";
1377
+ import path7 from "path";
1378
+ import { execFile as execFile2 } from "child_process";
1379
+ import * as p4 from "@clack/prompts";
1380
+ import Table4 from "cli-table3";
1381
+ import pc6 from "picocolors";
1382
+ function registerProjectCommands(program2) {
1383
+ program2.command("list").alias("ls").description("List all hosted sites in your workspace").option("--type <siteType>", "Filter by 'static' or 'node'").action(async (opts) => {
1384
+ const client = new SagaCloudClient();
1385
+ const res = await client.rpc("saga_cloud.api.hosting.list_sites", {
1386
+ query: { site_type: opts.type, limit: 100 }
1387
+ });
1388
+ const table = new Table4({ head: ["Site ID", "Name", "Type", "Status", "Live URL", "Server IP"] });
1389
+ for (const s of res.sites || []) {
1390
+ const statusColor = s.status === "Online" ? pc6.green(s.status) : s.status === "Failed" ? pc6.red(s.status) : pc6.yellow(s.status);
1391
+ table.push([s.name, s.site_name, `${s.site_type}/${s.runtime_variant}`, statusColor, s.live_url || s.domain, s.server_public_ip || "-"]);
1392
+ }
1393
+ console.log(table.toString());
1394
+ });
1395
+ program2.command("link").description("Link current directory to an existing SagaCloud site").option("--site <siteId>", "Explicit Site ID").action(async (opts) => {
1396
+ const client = new SagaCloudClient();
1397
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
1398
+ let siteId = opts.site;
1399
+ if (!siteId) {
1400
+ const listRes = await client.rpc("saga_cloud.api.hosting.list_sites", {
1401
+ query: { limit: 100 }
1402
+ });
1403
+ if (!listRes.sites?.length) {
1404
+ throw new Error("No sites found in workspace. Run `sagacloud deploy` to create one.");
1405
+ }
1406
+ const picked = await p4.select({
1407
+ message: "Select site to link to this directory",
1408
+ options: listRes.sites.map((s) => ({
1409
+ value: s.name,
1410
+ label: `${s.site_name} (${s.domain}) [${s.status}]`
1411
+ }))
1412
+ });
1413
+ if (p4.isCancel(picked)) process.exit(1);
1414
+ siteId = String(picked);
1415
+ }
1416
+ const details = await client.rpc("saga_cloud.api.hosting.get_site_details", {
1417
+ query: { site_id: siteId, limit: 1 }
1418
+ });
1419
+ const detected = detectProject(process.cwd());
1420
+ const linkPath = writeLocalLink({
1421
+ site_id: details.site.name,
1422
+ tenant_id: info.tenant,
1423
+ site_type: details.site.site_type,
1424
+ runtime_variant: details.site.runtime_variant,
1425
+ output_dir: details.site.publish_directory || detected.outputDir
1426
+ });
1427
+ console.log(pc6.green(`Linked '${details.site.site_name}' (${details.site.live_url}) -> ${linkPath}`));
1428
+ });
1429
+ program2.command("init").description("Generate sagacloud.jsonc for the current project").option("--yes", "Accept auto-detected settings without prompts").action(async (opts) => {
1430
+ const cwd = process.cwd();
1431
+ const detected = detectProject(cwd);
1432
+ const folderName = path7.basename(cwd).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "") || "my-app";
1433
+ let siteName = folderName;
1434
+ let outDir = detected.outputDir;
1435
+ let startCmd = detected.startCommand;
1436
+ let port = Number(detected.port || 3e3);
1437
+ if (!opts.yes) {
1438
+ p4.intro(pc6.cyan(`Detected ${detected.frameworkLabel}`));
1439
+ const nameRes = await p4.text({ message: "Site name", initialValue: folderName });
1440
+ if (p4.isCancel(nameRes)) process.exit(1);
1441
+ siteName = String(nameRes);
1442
+ if (detected.siteType === "static") {
1443
+ const outRes = await p4.text({ message: "Static output directory", initialValue: detected.outputDir || "dist" });
1444
+ if (p4.isCancel(outRes)) process.exit(1);
1445
+ outDir = String(outRes);
1446
+ } else {
1447
+ const startRes = await p4.text({ message: "Start command", initialValue: detected.startCommand || "npm start" });
1448
+ if (p4.isCancel(startRes)) process.exit(1);
1449
+ startCmd = String(startRes);
1450
+ const portRes = await p4.text({ message: "Listening port", initialValue: detected.port || "3000" });
1451
+ if (p4.isCancel(portRes)) process.exit(1);
1452
+ port = Number(portRes || 3e3);
1453
+ }
1454
+ }
1455
+ const jsoncLines = [
1456
+ "{",
1457
+ ` // Auto-detected: ${detected.frameworkLabel}`,
1458
+ ` "name": ${JSON.stringify(siteName)},`,
1459
+ ` "type": ${JSON.stringify(detected.runtimeVariant)},`,
1460
+ ...detected.buildCommand ? [` "build_command": ${JSON.stringify(detected.buildCommand)},`] : [],
1461
+ ...detected.siteType === "static" ? [
1462
+ ` "output_dir": ${JSON.stringify(outDir || ".")},`,
1463
+ ` "spa_fallback": ${detected.runtimeVariant === "spa"},`
1464
+ ] : [
1465
+ ` "start_command": ${JSON.stringify(startCmd)},`,
1466
+ ` "port": ${port},`
1467
+ ],
1468
+ ` "ignore": ["node_modules", ".git", ".env*", "tests"]`,
1469
+ "}",
1470
+ ""
1471
+ ];
1472
+ const outPath = path7.join(cwd, "sagacloud.jsonc");
1473
+ fs7.writeFileSync(outPath, jsoncLines.join("\n"));
1474
+ console.log(pc6.green(`Created ${outPath}. Run \`sagacloud deploy\` when ready.`));
1475
+ });
1476
+ program2.command("status").description("Show details of linked or specified site").option("--site <siteId>", "Site ID").action(async (opts) => {
1477
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1478
+ const client = new SagaCloudClient();
1479
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_details", {
1480
+ query: { site_id: siteId, limit: 5 }
1481
+ });
1482
+ const s = res.site;
1483
+ console.log(`${pc6.bold("Site:")} ${s.site_name} (${s.name})`);
1484
+ console.log(`${pc6.bold("Type:")} ${s.site_type} / ${s.runtime_variant} (${s.source_type})`);
1485
+ console.log(`${pc6.bold("Status:")} ${s.status}`);
1486
+ console.log(`${pc6.bold("Live URL:")} ${s.live_url || s.domain}`);
1487
+ console.log(`${pc6.bold("SSL / CDN:")} SSL=${s.ssl_status || "-"} \xB7 EdgeCDN=${s.cdn_enabled ? "On" : "Off"} \xB7 Shield=${s.waf_enabled ? "On" : "Off"}`);
1488
+ console.log(`${pc6.bold("Origin IP:")} ${s.server_public_ip || "-"}`);
1489
+ console.log(`${pc6.bold("Deployed:")} ${s.last_deployed_at || "-"}`);
1490
+ });
1491
+ program2.command("open").description("Open site Live URL in browser").option("--site <siteId>", "Site ID").action(async (opts) => {
1492
+ const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1493
+ const client = new SagaCloudClient();
1494
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_details", {
1495
+ query: { site_id: siteId, limit: 1 }
1496
+ });
1497
+ const url = res.site.live_url || `https://${res.site.domain}`;
1498
+ console.log(`Opening ${pc6.cyan(url)}`);
1499
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1500
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1501
+ execFile2(cmd, args, () => {
1502
+ });
1503
+ });
1504
+ }
1505
+
1506
+ // src/index.ts
1507
+ var program = new Command();
1508
+ program.name("sagacloud").description("SagaCloud CLI \u2014 deploy Static, SPA, Express & Node.js apps cleanly").version("0.1.0");
1509
+ registerAuthCommands(program);
1510
+ registerProjectCommands(program);
1511
+ registerDeployCommands(program);
1512
+ registerEnvCommands(program);
1513
+ registerOpsCommands(program);
1514
+ program.parseAsync(process.argv).catch((err) => {
1515
+ const msg = err instanceof Error ? err.message : String(err);
1516
+ console.error(pc7.red(`Error: ${msg}`));
1517
+ process.exit(1);
1518
+ });