sagacloud 0.3.0 → 0.3.2

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 (2) hide show
  1. package/dist/index.js +405 -110
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -6,7 +6,6 @@ import pc8 from "picocolors";
6
6
 
7
7
  // src/commands/auth.ts
8
8
  import crypto from "crypto";
9
- import { execFile } from "child_process";
10
9
  import http from "http";
11
10
  import os2 from "os";
12
11
  import * as p from "@clack/prompts";
@@ -34,7 +33,7 @@ var SagaCloudJsoncSchema = z.object({
34
33
  app_name: z.string().min(1).optional(),
35
34
  name: z.string().min(1).optional(),
36
35
  site_id: z.string().optional(),
37
- type: z.enum(["static", "spa", "php", "node", "nextjs"]).optional(),
36
+ type: z.enum(["static", "html", "spa", "php", "node", "nextjs"]).optional(),
38
37
  base_directory: z.string().optional(),
39
38
  install_command: z.string().optional(),
40
39
  build_command: z.string().optional(),
@@ -285,12 +284,102 @@ async function exchangeCliCode(apiUrl, code) {
285
284
  return parsed.message || parsed;
286
285
  }
287
286
 
288
- // src/commands/auth.ts
289
- function openBrowser(url) {
287
+ // src/lib/browser.ts
288
+ import { execFile } from "child_process";
289
+ async function openBrowser(url) {
290
290
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
291
291
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
292
- execFile(cmd, args, () => {
292
+ return await new Promise((resolve) => {
293
+ let settled = false;
294
+ const finish = (ok) => {
295
+ if (settled) return;
296
+ settled = true;
297
+ resolve(ok);
298
+ };
299
+ try {
300
+ const child = execFile(cmd, args, (err) => {
301
+ finish(!err);
302
+ });
303
+ child.once("error", () => finish(false));
304
+ setTimeout(() => {
305
+ if (child.exitCode === null) {
306
+ child.unref();
307
+ finish(true);
308
+ }
309
+ }, 400);
310
+ } catch {
311
+ finish(false);
312
+ }
313
+ });
314
+ }
315
+ function isHeadlessOrRemoteShell() {
316
+ if (!process.stdin.isTTY) return true;
317
+ if (process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT) return true;
318
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
319
+ return true;
320
+ }
321
+ return false;
322
+ }
323
+
324
+ // src/commands/auth.ts
325
+ async function authenticateWithToken(rawToken, apiUrl, panelUrl) {
326
+ const spin = p.spinner();
327
+ spin.start("Verifying SagaCloud API token...");
328
+ const client = new SagaCloudClient({ token: rawToken.trim(), apiUrl });
329
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
330
+ writeAuthProfile({
331
+ token: rawToken.trim(),
332
+ apiUrl,
333
+ panelUrl,
334
+ user: info.user,
335
+ tenant: info.tenant,
336
+ tenantName: info.tenant_name,
337
+ tokenName: info.token_name
338
+ });
339
+ spin.stop(`Authenticated as ${pc.green(info.user)} (Workspace: ${pc.cyan(info.tenant_name)})`);
340
+ }
341
+ async function promptManualLogin(apiUrl, panelBase, tryOpenBrowser) {
342
+ const manualUrl = new URL(`${panelBase}/hosting/cli-auth`);
343
+ manualUrl.searchParams.set("mode", "manual");
344
+ manualUrl.searchParams.set("device", os2.hostname());
345
+ console.log(pc.bold("Manual CLI authorization (SSH / headless / container):"));
346
+ console.log(`1. Open this URL in any browser:
347
+ ${pc.cyan(manualUrl.toString())}`);
348
+ console.log(`2. Click ${pc.bold("Authorize CLI Access")} and copy the one-time code (or an ${pc.dim("sc_live_...")} API token).
349
+ `);
350
+ if (tryOpenBrowser) {
351
+ await openBrowser(manualUrl.toString());
352
+ }
353
+ const pasted = await p.password({
354
+ message: "Paste authorization code or sc_live_... token",
355
+ validate(val) {
356
+ if (!val || !val.trim()) return "Authorization code or token is required.";
357
+ }
358
+ });
359
+ if (p.isCancel(pasted)) {
360
+ p.cancel("Login cancelled.");
361
+ process.exit(1);
362
+ }
363
+ const secret = String(pasted).trim();
364
+ if (secret.startsWith("sc_live_")) {
365
+ await authenticateWithToken(secret, apiUrl, panelBase);
366
+ return;
367
+ }
368
+ const spin = p.spinner();
369
+ spin.start("Exchanging one-time authorization code...");
370
+ const exchanged = await exchangeCliCode(apiUrl, secret);
371
+ writeAuthProfile({
372
+ token: exchanged.token,
373
+ apiUrl,
374
+ panelUrl: panelBase,
375
+ user: exchanged.user,
376
+ tenant: exchanged.tenant,
377
+ tenantName: exchanged.tenant_name,
378
+ tokenName: exchanged.token_name
293
379
  });
380
+ spin.stop(
381
+ `Logged in as ${pc.green(exchanged.user)} \xB7 Workspace: ${pc.cyan(exchanged.tenant_name)} (${pc.dim(exchanged.token_prefix)}...)`
382
+ );
294
383
  }
295
384
  function escapeHtml(value) {
296
385
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
@@ -423,23 +512,15 @@ function renderCallbackHtml(opts) {
423
512
  </html>`;
424
513
  }
425
514
  function registerAuthCommands(program2) {
426
- 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) => {
515
+ program2.command("login").description("Authenticate CLI via browser approval, manual code paste, or --token").option("--token <token>", "Store an existing sc_live_... API token directly").option("--manual", "Prompt to paste an authorization code or token instead of waiting for 127.0.0.1 callback", false).option("--no-browser", "Do not launch a local browser automatically").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) => {
427
516
  const apiUrl = (opts.url || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
517
+ const panelBase = (opts.panelUrl || DEFAULT_PANEL_BASE_URL).replace(/\/+$/, "");
428
518
  if (opts.token) {
429
- const spin2 = p.spinner();
430
- spin2.start("Verifying SagaCloud API token...");
431
- const client = new SagaCloudClient({ token: opts.token.trim(), apiUrl });
432
- const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
433
- writeAuthProfile({
434
- token: opts.token.trim(),
435
- apiUrl,
436
- panelUrl: opts.panelUrl,
437
- user: info.user,
438
- tenant: info.tenant,
439
- tenantName: info.tenant_name,
440
- tokenName: info.token_name
441
- });
442
- spin2.stop(`Authenticated as ${pc.green(info.user)} (Workspace: ${pc.cyan(info.tenant_name)})`);
519
+ await authenticateWithToken(opts.token, apiUrl, opts.panelUrl);
520
+ return;
521
+ }
522
+ if (opts.manual || opts.browser === false || isHeadlessOrRemoteShell()) {
523
+ await promptManualLogin(apiUrl, panelBase, Boolean(opts.browser !== false && !isHeadlessOrRemoteShell()));
443
524
  return;
444
525
  }
445
526
  const state = crypto.randomBytes(24).toString("hex");
@@ -450,7 +531,6 @@ function registerAuthCommands(program2) {
450
531
  throw new Error("Could not bind local loopback port for login.");
451
532
  }
452
533
  const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
453
- const panelBase = (opts.panelUrl || DEFAULT_PANEL_BASE_URL).replace(/\/+$/, "");
454
534
  const authUrl = new URL(`${panelBase}/hosting/cli-auth`);
455
535
  authUrl.searchParams.set("callback", callbackUrl);
456
536
  authUrl.searchParams.set("state", state);
@@ -459,7 +539,13 @@ function registerAuthCommands(program2) {
459
539
  console.log(`If your browser doesn't open, visit:
460
540
  ${pc.cyan(authUrl.toString())}
461
541
  `);
462
- openBrowser(authUrl.toString());
542
+ const opened = await openBrowser(authUrl.toString());
543
+ if (!opened) {
544
+ server.close();
545
+ console.log(pc.yellow("No working local browser opener detected; switching to manual authorization mode.\n"));
546
+ await promptManualLogin(apiUrl, panelBase, false);
547
+ return;
548
+ }
463
549
  const code = await new Promise((resolve, reject) => {
464
550
  const timeout = setTimeout(() => {
465
551
  server.close();
@@ -530,6 +616,7 @@ function registerAuthCommands(program2) {
530
616
  );
531
617
  });
532
618
  program2.command("logout").description("Revoke active CLI token on server and remove local credentials").action(async () => {
619
+ const envToken = process.env.SAGACLOUD_TOKEN?.trim();
533
620
  const profile = readAuthProfile();
534
621
  if (!profile) {
535
622
  console.log(pc.yellow("No local CLI credentials found."));
@@ -543,6 +630,13 @@ function registerAuthCommands(program2) {
543
630
  }
544
631
  clearAuthProfile();
545
632
  console.log(pc.green(`Logged out and removed ${getAuthFilePath()}`));
633
+ if (envToken) {
634
+ console.log(
635
+ pc.yellow(
636
+ "Warning: SAGACLOUD_TOKEN is set in your shell environment and its token was just revoked. Run `unset SAGACLOUD_TOKEN` in your terminal."
637
+ )
638
+ );
639
+ }
546
640
  });
547
641
  program2.command("whoami").description("Display active CLI user, workspace, and token scopes").action(async () => {
548
642
  const client = new SagaCloudClient();
@@ -799,28 +893,32 @@ async function streamRuntimeLogs(client, siteId, lines = 100, follow = false) {
799
893
  void stop().then(() => process.exit(0));
800
894
  });
801
895
  let ticks = 0;
802
- while (running) {
803
- const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
804
- query: { site_id: siteId, lines }
805
- });
806
- const current = (res.logs || "").split(/\r?\n/).filter(Boolean);
807
- if (previousLines.length === 0) {
808
- for (const ln of current) console.log(ln);
809
- } else {
810
- const lastPrev = previousLines[previousLines.length - 1];
811
- const matchIdx = current.lastIndexOf(lastPrev);
812
- const added = matchIdx >= 0 ? current.slice(matchIdx + 1) : current;
813
- for (const ln of added) console.log(ln);
814
- }
815
- previousLines = current;
816
- ticks += 1;
817
- if (ticks % 5 === 0) {
818
- await client.rpc("saga_cloud.api.hosting.heartbeat_site_log_stream", {
819
- method: "POST",
820
- body: { site_id: siteId }
896
+ try {
897
+ while (running) {
898
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
899
+ query: { site_id: siteId, lines }
821
900
  });
901
+ const current = (res.logs || "").split(/\r?\n/).filter(Boolean);
902
+ if (previousLines.length === 0) {
903
+ for (const ln of current) console.log(ln);
904
+ } else {
905
+ const lastPrev = previousLines[previousLines.length - 1];
906
+ const matchIdx = current.lastIndexOf(lastPrev);
907
+ const added = matchIdx >= 0 ? current.slice(matchIdx + 1) : current;
908
+ for (const ln of added) console.log(ln);
909
+ }
910
+ previousLines = current;
911
+ ticks += 1;
912
+ if (ticks % 5 === 0) {
913
+ await client.rpc("saga_cloud.api.hosting.heartbeat_site_log_stream", {
914
+ method: "POST",
915
+ body: { site_id: siteId }
916
+ });
917
+ }
918
+ await new Promise((r) => setTimeout(r, 2500));
822
919
  }
823
- await new Promise((r) => setTimeout(r, 2500));
920
+ } finally {
921
+ await stop();
824
922
  }
825
923
  }
826
924
 
@@ -843,22 +941,56 @@ var ALWAYS_IGNORED = [
843
941
  ".env",
844
942
  ".env.*",
845
943
  "sagacloud.jsonc",
846
- "sagacloud.json"
944
+ "sagacloud.json",
945
+ ".sagacloudignore"
946
+ ];
947
+ var STATIC_NON_WEB_IGNORES = [
948
+ "**/*.d.ts",
949
+ "**/*.d.mts",
950
+ "**/*.d.cts",
951
+ "*.d.ts",
952
+ "*.d.mts",
953
+ "*.d.cts",
954
+ ".editorconfig",
955
+ ".gitignore",
956
+ ".gitattributes",
957
+ ".gitkeep",
958
+ "**/.gitkeep",
959
+ ".keep",
960
+ "**/.keep",
961
+ ".browserslistrc",
962
+ ".npmrc",
963
+ ".prettierrc",
964
+ ".prettierignore",
965
+ ".eslintrc",
966
+ ".eslintignore",
967
+ ".stylelintrc"
847
968
  ];
848
- async function createArchiveFromDirectory(targetDir, extraIgnorePatterns = [], includeGitignore = false) {
969
+ async function createArchiveFromDirectory(targetDir, extraOrOptions = [], includeGitignoreArg = false) {
849
970
  if (!fs3.existsSync(targetDir) || !fs3.statSync(targetDir).isDirectory()) {
850
971
  throw new Error(`Directory not found: ${targetDir}`);
851
972
  }
973
+ const opts = Array.isArray(extraOrOptions) ? { extraIgnorePatterns: extraOrOptions, includeGitignore: includeGitignoreArg } : extraOrOptions;
852
974
  const ig = ignore().add(ALWAYS_IGNORED);
853
- if (extraIgnorePatterns.length > 0) {
854
- ig.add(extraIgnorePatterns);
975
+ if (opts.staticSiteFilter) {
976
+ ig.add(STATIC_NON_WEB_IGNORES);
855
977
  }
856
- if (includeGitignore) {
857
- for (const ignoreFile of [".gitignore", ".sagacloudignore"]) {
858
- const fp = path3.join(targetDir, ignoreFile);
859
- if (fs3.existsSync(fp)) {
860
- ig.add(fs3.readFileSync(fp, "utf8"));
861
- }
978
+ if (opts.extraIgnorePatterns && opts.extraIgnorePatterns.length > 0) {
979
+ ig.add(opts.extraIgnorePatterns);
980
+ }
981
+ const searchDirs = Array.from(
982
+ /* @__PURE__ */ new Set([targetDir, ...opts.projectRootDir ? [opts.projectRootDir] : []])
983
+ );
984
+ for (const baseDir of searchDirs) {
985
+ const sagaIgnore = path3.join(baseDir, ".sagacloudignore");
986
+ if (fs3.existsSync(sagaIgnore)) {
987
+ ig.add(fs3.readFileSync(sagaIgnore, "utf8"));
988
+ }
989
+ }
990
+ if (opts.includeGitignore) {
991
+ const gitIgnore = path3.join(targetDir, ".gitignore");
992
+ if (fs3.existsSync(gitIgnore)) {
993
+ ig.add(fs3.readFileSync(gitIgnore, "utf8"));
862
994
  }
863
995
  }
864
996
  return await new Promise((resolve, reject) => {
@@ -911,16 +1043,57 @@ async function resolveWranglerStyleTargetSite(client, optsSite, configuredName,
911
1043
  return link?.site_id || "";
912
1044
  }
913
1045
  function parseDotEnvText(raw) {
1046
+ const trimmed = raw.trim();
1047
+ if (trimmed.startsWith("[")) {
1048
+ const parsed = JSON.parse(trimmed);
1049
+ return parsed.filter((r) => Boolean(r?.key)).map((r) => ({
1050
+ key: String(r.key).trim(),
1051
+ value: String(r.value ?? ""),
1052
+ isBuildTime: r.is_build_time
1053
+ }));
1054
+ }
914
1055
  const rows = [];
915
- for (const line of raw.split(/\r?\n/)) {
916
- const trimmed = line.trim();
917
- if (!trimmed || trimmed.startsWith("#")) continue;
918
- const eq = trimmed.indexOf("=");
1056
+ const lines = raw.split(/\r?\n/);
1057
+ for (let i = 0; i < lines.length; i += 1) {
1058
+ let line = lines[i].trim();
1059
+ if (!line || line.startsWith("#")) continue;
1060
+ if (/^export\s+/i.test(line)) {
1061
+ line = line.replace(/^export\s+/i, "").trim();
1062
+ }
1063
+ const eq = line.indexOf("=");
919
1064
  if (eq <= 0) continue;
920
- const key = trimmed.slice(0, eq).trim();
921
- let val = trimmed.slice(eq + 1).trim();
922
- if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
923
- val = val.slice(1, -1);
1065
+ const key = line.slice(0, eq).trim();
1066
+ const rawVal = line.slice(eq + 1).trimStart();
1067
+ let val = "";
1068
+ if (rawVal.startsWith('"') || rawVal.startsWith("'")) {
1069
+ const quote = rawVal[0];
1070
+ let buf = rawVal.slice(1);
1071
+ while (true) {
1072
+ let closeIdx = -1;
1073
+ for (let j = 0; j < buf.length; j += 1) {
1074
+ if (buf[j] === "\\" && quote === '"' && j + 1 < buf.length) {
1075
+ j += 1;
1076
+ continue;
1077
+ }
1078
+ if (buf[j] === quote) {
1079
+ closeIdx = j;
1080
+ break;
1081
+ }
1082
+ }
1083
+ if (closeIdx !== -1 || i + 1 >= lines.length) {
1084
+ val = closeIdx !== -1 ? buf.slice(0, closeIdx) : buf;
1085
+ if (quote === '"') {
1086
+ val = val.replaceAll("\\n", "\n").replaceAll('\\"', '"').replaceAll("\\\\", "\\");
1087
+ }
1088
+ break;
1089
+ }
1090
+ i += 1;
1091
+ buf += `
1092
+ ${lines[i]}`;
1093
+ }
1094
+ } else {
1095
+ const hashIdx = rawVal.indexOf(" #");
1096
+ val = (hashIdx !== -1 ? rawVal.slice(0, hashIdx) : rawVal).trim();
924
1097
  }
925
1098
  if (key) rows.push({ key, value: val });
926
1099
  }
@@ -977,7 +1150,7 @@ async function reconcileConfiguredDomains(client, site, specs) {
977
1150
  return latestSite;
978
1151
  }
979
1152
  function registerDeployCommands(program2) {
980
- 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(
1153
+ 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").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(
981
1154
  async (opts) => {
982
1155
  const cwd = process.cwd();
983
1156
  const client = new SagaCloudClient();
@@ -1027,7 +1200,7 @@ function registerDeployCommands(program2) {
1027
1200
  runtimeVariant = jsonc.type;
1028
1201
  } else {
1029
1202
  siteType = "static";
1030
- runtimeVariant = jsonc.type === "static" || jsonc.type === "spa" && jsonc.spa_fallback === false ? "html" : jsonc.type;
1203
+ runtimeVariant = jsonc.type === "static" || jsonc.type === "html" || jsonc.type === "spa" && jsonc.spa_fallback === false ? "html" : jsonc.type;
1031
1204
  }
1032
1205
  } else if (link?.site_type) {
1033
1206
  siteType = link.site_type;
@@ -1048,23 +1221,35 @@ function registerDeployCommands(program2) {
1048
1221
  }
1049
1222
  const spin = p2.spinner();
1050
1223
  spin.start(`Packaging ${siteType === "node" ? "Node.js source" : outputRel}...`);
1051
- const archive = await createArchiveFromDirectory(
1052
- uploadDir,
1053
- jsonc?.ignore || [],
1054
- siteType === "node"
1055
- );
1224
+ const archive = await createArchiveFromDirectory(uploadDir, {
1225
+ extraIgnorePatterns: jsonc?.ignore || [],
1226
+ includeGitignore: siteType === "node" || path4.resolve(uploadDir) === path4.resolve(cwd),
1227
+ staticSiteFilter: siteType === "static",
1228
+ projectRootDir: cwd
1229
+ });
1056
1230
  spin.stop(
1057
1231
  `Packaged ${archive.fileCount} files (${(archive.sizeBytes / 1024).toFixed(1)} KB)`
1058
1232
  );
1233
+ if (archive.fileCount === 0) {
1234
+ throw new Error(
1235
+ `No deployable files found in '${outputRel}'. Check your output directory or ignore patterns.`
1236
+ );
1237
+ }
1059
1238
  const uploadSpin = p2.spinner();
1060
1239
  uploadSpin.start("Uploading bundle to SagaCloud...");
1061
1240
  const zipName = `${(jsonc?.app_name || jsonc?.name || path4.basename(cwd) || "bundle").replace(/[^a-z0-9-]+/gi, "-")}.zip`;
1062
- const uploaded = await client.uploadBundle(archive.buffer, zipName, siteType);
1241
+ let uploaded;
1242
+ try {
1243
+ uploaded = await client.uploadBundle(archive.buffer, zipName, siteType);
1244
+ } catch (err) {
1245
+ uploadSpin.stop("Upload failed");
1246
+ throw err;
1247
+ }
1063
1248
  uploadSpin.stop(`Uploaded (${uploaded.detected_entry})`);
1064
1249
  const mergedVars = /* @__PURE__ */ new Map();
1065
1250
  if (jsonc?.vars) {
1066
1251
  for (const [k, v] of Object.entries(jsonc.vars)) {
1067
- mergedVars.set(k, String(v));
1252
+ mergedVars.set(k, { value: String(v) });
1068
1253
  }
1069
1254
  }
1070
1255
  const envFilesToLoad = [jsonc?.env_file, opts.withEnv].filter((f) => Boolean(f));
@@ -1072,13 +1257,13 @@ function registerDeployCommands(program2) {
1072
1257
  const envPath = path4.resolve(cwd, relEnv);
1073
1258
  if (!fs4.existsSync(envPath)) throw new Error(`Env file not found: ${envPath}`);
1074
1259
  for (const item of parseDotEnvText(fs4.readFileSync(envPath, "utf8"))) {
1075
- mergedVars.set(item.key, item.value);
1260
+ mergedVars.set(item.key, { value: item.value, isBuildTime: item.isBuildTime });
1076
1261
  }
1077
1262
  }
1078
- const envPayload = Array.from(mergedVars.entries()).map(([key, value]) => ({
1263
+ const envPayload = Array.from(mergedVars.entries()).map(([key, item]) => ({
1079
1264
  key,
1080
- value,
1081
- is_build_time: siteType === "static"
1265
+ value: item.value,
1266
+ is_build_time: item.isBuildTime ?? siteType === "static"
1082
1267
  }));
1083
1268
  const forceRebuild = opts.force || Boolean(jsonc?.deploy?.force_rebuild);
1084
1269
  const detachMode = opts.detach || Boolean(jsonc?.deploy?.detach);
@@ -1086,6 +1271,61 @@ function registerDeployCommands(program2) {
1086
1271
  let targetSite;
1087
1272
  let dep;
1088
1273
  if (existingSiteId) {
1274
+ const settingsPatch = {
1275
+ site_id: existingSiteId
1276
+ };
1277
+ let hasSettingsUpdate = false;
1278
+ if (siteType === "node") {
1279
+ const nextPort = opts.port || (jsonc?.port !== void 0 ? String(jsonc.port) : "");
1280
+ if (nextPort) {
1281
+ settingsPatch.ports_exposes = nextPort;
1282
+ hasSettingsUpdate = true;
1283
+ }
1284
+ const nextStart = opts.start || jsonc?.start_command;
1285
+ if (nextStart) {
1286
+ settingsPatch.start_command = nextStart;
1287
+ hasSettingsUpdate = true;
1288
+ }
1289
+ if (jsonc?.install_command !== void 0) {
1290
+ settingsPatch.install_command = jsonc.install_command;
1291
+ hasSettingsUpdate = true;
1292
+ }
1293
+ if (jsonc?.build_command !== void 0) {
1294
+ settingsPatch.build_command = jsonc.build_command;
1295
+ hasSettingsUpdate = true;
1296
+ }
1297
+ } else {
1298
+ if (opts.spa || opts.static || jsonc?.spa_fallback !== void 0) {
1299
+ settingsPatch.is_spa = runtimeVariant === "spa" ? 1 : 0;
1300
+ hasSettingsUpdate = true;
1301
+ }
1302
+ if (opts.dir || jsonc?.output_dir) {
1303
+ settingsPatch.publish_directory = outputRel;
1304
+ hasSettingsUpdate = true;
1305
+ }
1306
+ }
1307
+ if (jsonc?.base_directory !== void 0) {
1308
+ settingsPatch.base_directory = jsonc.base_directory;
1309
+ hasSettingsUpdate = true;
1310
+ }
1311
+ if (jsonc?.healthcheck_path !== void 0) {
1312
+ settingsPatch.healthcheck_path = jsonc.healthcheck_path;
1313
+ hasSettingsUpdate = true;
1314
+ }
1315
+ if (jsonc?.resources?.memory !== void 0) {
1316
+ settingsPatch.limits_memory = String(jsonc.resources.memory);
1317
+ hasSettingsUpdate = true;
1318
+ }
1319
+ if (jsonc?.resources?.cpus !== void 0) {
1320
+ settingsPatch.limits_cpus = String(jsonc.resources.cpus);
1321
+ hasSettingsUpdate = true;
1322
+ }
1323
+ if (hasSettingsUpdate) {
1324
+ await client.rpc("saga_cloud.api.hosting.update_site_settings", {
1325
+ method: "POST",
1326
+ body: settingsPatch
1327
+ });
1328
+ }
1089
1329
  if (envPayload.length > 0) {
1090
1330
  await client.rpc("saga_cloud.api.hosting.save_site_envs", {
1091
1331
  method: "POST",
@@ -1258,21 +1498,55 @@ function registerEnvCommands(program2) {
1258
1498
  );
1259
1499
  console.log(pc4.green(`Synced ${res.envs?.length || 0} variables from ${filePath}. Redeploy to apply changes.`));
1260
1500
  });
1261
- env.command("pull [filePath]").description("Download remote environment variables to a local file").option("--site <siteId>", "Site ID").action(async (filePath = ".env.local", opts) => {
1501
+ env.command("pull [filePath]").description("Download remote environment variables to a local file").option("--site <siteId>", "Site ID").option("--json", "Write JSON including is_build_time metadata", false).action(async (filePath = ".env.local", opts) => {
1262
1502
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1263
1503
  const client = new SagaCloudClient();
1264
1504
  const res = await client.rpc("saga_cloud.api.hosting.get_site_envs", {
1265
1505
  query: { site_id: siteId }
1266
1506
  });
1507
+ const envs = res.envs || [];
1267
1508
  const outPath = path5.resolve(process.cwd(), filePath);
1268
- const lines = (res.envs || []).map((item) => {
1509
+ if (opts.json) {
1510
+ fs5.writeFileSync(
1511
+ outPath,
1512
+ `${JSON.stringify(
1513
+ envs.map((e) => ({
1514
+ key: e.key,
1515
+ value: e.value ?? "",
1516
+ is_build_time: Boolean(e.is_build_time)
1517
+ })),
1518
+ null,
1519
+ 2
1520
+ )}
1521
+ `,
1522
+ { mode: 384 }
1523
+ );
1524
+ console.log(pc4.green(`Wrote ${envs.length} variables (JSON with metadata) to ${filePath}`));
1525
+ return;
1526
+ }
1527
+ const buildTimeKeys = [];
1528
+ const lines = [];
1529
+ for (const item of envs) {
1269
1530
  const val = String(item.value ?? "");
1270
- const needsQuotes = /[\s#'"]/.test(val);
1271
- return `${item.key}=${needsQuotes ? JSON.stringify(val) : val}`;
1272
- });
1531
+ const needsQuotes = /[\s#'"\\]/.test(val);
1532
+ const formatted = `${item.key}=${needsQuotes ? JSON.stringify(val) : val}`;
1533
+ if (item.is_build_time) {
1534
+ buildTimeKeys.push(item.key);
1535
+ lines.push(`# build-time`, formatted);
1536
+ } else {
1537
+ lines.push(formatted);
1538
+ }
1539
+ }
1273
1540
  fs5.writeFileSync(outPath, `${lines.join("\n")}
1274
1541
  `, { mode: 384 });
1275
- console.log(pc4.green(`Wrote ${lines.length} variables to ${filePath}`));
1542
+ console.log(pc4.green(`Wrote ${envs.length} variables to ${filePath}`));
1543
+ if (buildTimeKeys.length > 0) {
1544
+ console.log(
1545
+ pc4.dim(
1546
+ `Note: ${buildTimeKeys.length} build-time variable(s) (${buildTimeKeys.join(", ")}); use \`env pull --json\` to preserve flags cleanly.`
1547
+ )
1548
+ );
1549
+ }
1276
1550
  });
1277
1551
  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) => {
1278
1552
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
@@ -1337,7 +1611,10 @@ function registerOpsCommands(program2) {
1337
1611
  console.log(pc5.yellow("No deployments found for this site."));
1338
1612
  return;
1339
1613
  }
1340
- await streamBuildUntilDone(client, siteId, targetDep);
1614
+ const finalStatus = await streamBuildUntilDone(client, siteId, targetDep);
1615
+ if (finalStatus !== "finished") {
1616
+ process.exit(1);
1617
+ }
1341
1618
  }
1342
1619
  );
1343
1620
  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) => {
@@ -1366,25 +1643,20 @@ function registerOpsCommands(program2) {
1366
1643
  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) => {
1367
1644
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1368
1645
  const client = new SagaCloudClient();
1369
- let depId = versionOrId.trim();
1370
- const vMatch = depId.match(/^v?(\d+)$/i);
1371
- if (vMatch) {
1372
- const ver = Number(vMatch[1]);
1373
- const list = await client.rpc(
1374
- "saga_cloud.api.hosting.list_deployments",
1375
- { query: { site_id: siteId, limit: 50 } }
1376
- );
1377
- const found = (list.deployments || []).find((d) => d.version_number === ver);
1378
- if (!found) throw new Error(`Version v${ver} not found.`);
1379
- depId = found.name;
1380
- }
1646
+ const raw = versionOrId.trim();
1647
+ const vMatch = raw.match(/^v?(\d+)$/i);
1648
+ const rollbackBody = vMatch ? { site_id: siteId, target_version: Number(vMatch[1]) } : { site_id: siteId, target_deployment_id: raw };
1381
1649
  const res = await client.rpc(
1382
1650
  "saga_cloud.api.hosting.rollback_site",
1383
- { method: "POST", body: { site_id: siteId, target_deployment_id: depId } }
1651
+ { method: "POST", body: rollbackBody }
1384
1652
  );
1385
1653
  console.log(pc5.green(`Queued rollback v${res.deployment.version_number} (${res.rollback_mode || "instant"})`));
1386
1654
  if (res.deployment.deployment_uuid) {
1387
- await streamBuildUntilDone(client, siteId, res.deployment.deployment_uuid);
1655
+ const finalStatus = await streamBuildUntilDone(client, siteId, res.deployment.deployment_uuid);
1656
+ if (finalStatus !== "finished") {
1657
+ console.log(pc5.red(`\u2717 Rollback v${res.deployment.version_number} ${finalStatus}`));
1658
+ process.exit(1);
1659
+ }
1388
1660
  }
1389
1661
  });
1390
1662
  const domains = program2.command("domains").description("Manage custom domains & Edge SSL");
@@ -1481,6 +1753,38 @@ function registerOpsCommands(program2) {
1481
1753
  const ci = program2.command("ci").description("CI/CD helpers");
1482
1754
  ci.command("init").description("Generate .github/workflows/sagacloud.yml").action(() => {
1483
1755
  const cwd = process.cwd();
1756
+ const detected = detectProject(cwd);
1757
+ const { config: jsonc } = readRepoJsoncConfig(cwd);
1758
+ const hasPackageJson = fs6.existsSync(path6.join(cwd, "package.json"));
1759
+ const hasLockfile = fs6.existsSync(path6.join(cwd, "package-lock.json"));
1760
+ const buildCmd = (jsonc?.build_command || detected.buildCommand || "").trim();
1761
+ const siteType = jsonc?.type === "node" || jsonc?.type === "nextjs" ? "node" : jsonc?.type ? "static" : detected.siteType;
1762
+ const outDir = jsonc?.output_dir || detected.outputDir || ".";
1763
+ const steps = [" - uses: actions/checkout@v4"];
1764
+ if (hasPackageJson && (siteType === "static" || Boolean(buildCmd))) {
1765
+ steps.push(
1766
+ " - uses: actions/setup-node@v4",
1767
+ " with:",
1768
+ " node-version: 22",
1769
+ ` - run: ${hasLockfile ? "npm ci" : "npm install"}`
1770
+ );
1771
+ if (buildCmd && siteType === "static") {
1772
+ steps.push(` - run: ${buildCmd}`);
1773
+ }
1774
+ }
1775
+ let deployCmd = "npx sagacloud deploy --yes";
1776
+ if (siteType === "node") {
1777
+ deployCmd = "npx sagacloud deploy --node --yes";
1778
+ } else if (outDir && outDir !== ".") {
1779
+ deployCmd = `npx sagacloud deploy --dir ${outDir} --no-build --yes`;
1780
+ } else {
1781
+ deployCmd = "npx sagacloud deploy --no-build --yes";
1782
+ }
1783
+ steps.push(
1784
+ ` - run: ${deployCmd}`,
1785
+ " env:",
1786
+ " SAGACLOUD_TOKEN: ${{ secrets.SAGACLOUD_TOKEN }}"
1787
+ );
1484
1788
  const wfDir = path6.join(cwd, ".github", "workflows");
1485
1789
  fs6.mkdirSync(wfDir, { recursive: true });
1486
1790
  const outPath = path6.join(wfDir, "sagacloud.yml");
@@ -1493,15 +1797,7 @@ function registerOpsCommands(program2) {
1493
1797
  " deploy:",
1494
1798
  " runs-on: ubuntu-latest",
1495
1799
  " steps:",
1496
- " - uses: actions/checkout@v4",
1497
- " - uses: actions/setup-node@v4",
1498
- " with:",
1499
- " node-version: 22",
1500
- " - run: npm ci",
1501
- " - run: npm run build",
1502
- " - run: npx sagacloud deploy --no-build --yes",
1503
- " env:",
1504
- " SAGACLOUD_TOKEN: ${{ secrets.SAGACLOUD_TOKEN }}",
1800
+ ...steps,
1505
1801
  ""
1506
1802
  ].join("\n");
1507
1803
  fs6.writeFileSync(outPath, yml);
@@ -1512,7 +1808,6 @@ function registerOpsCommands(program2) {
1512
1808
  // src/commands/project.ts
1513
1809
  import fs7 from "fs";
1514
1810
  import path7 from "path";
1515
- import { execFile as execFile2 } from "child_process";
1516
1811
  import * as p4 from "@clack/prompts";
1517
1812
  import Table4 from "cli-table3";
1518
1813
  import pc6 from "picocolors";
@@ -1595,7 +1890,7 @@ function registerProjectCommands(program2) {
1595
1890
  "{",
1596
1891
  ` // Auto-detected: ${detected.frameworkLabel}`,
1597
1892
  ` "app_name": ${JSON.stringify(siteName)},`,
1598
- ` "type": ${JSON.stringify(detected.runtimeVariant)},`,
1893
+ ` "type": ${JSON.stringify(detected.runtimeVariant === "html" ? "static" : detected.runtimeVariant)},`,
1599
1894
  ...detected.buildCommand ? [` "build_command": ${JSON.stringify(detected.buildCommand)},`] : [],
1600
1895
  ...detected.siteType === "static" ? [
1601
1896
  ` "output_dir": ${JSON.stringify(outDir || ".")},`,
@@ -1641,10 +1936,10 @@ function registerProjectCommands(program2) {
1641
1936
  });
1642
1937
  const url = res.site.live_url || `https://${res.site.domain}`;
1643
1938
  console.log(`Opening ${pc6.cyan(url)}`);
1644
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1645
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1646
- execFile2(cmd, args, () => {
1647
- });
1939
+ const opened = await openBrowser(url);
1940
+ if (!opened) {
1941
+ console.log(pc6.yellow("Browser opener is unavailable in this environment; open the URL above manually."));
1942
+ }
1648
1943
  });
1649
1944
  }
1650
1945
 
@@ -1757,7 +2052,7 @@ function registerSkillCommands(program2) {
1757
2052
 
1758
2053
  // src/index.ts
1759
2054
  var program = new Command();
1760
- program.name("sagacloud").description("SagaCloud CLI \u2014 deploy Static, SPA, Express & Node.js apps cleanly").version("0.3.0");
2055
+ program.name("sagacloud").description("SagaCloud CLI \u2014 deploy Static, SPA, Express & Node.js apps cleanly").version("0.3.2");
1761
2056
  registerAuthCommands(program);
1762
2057
  registerProjectCommands(program);
1763
2058
  registerDeployCommands(program);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sagacloud",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Official CLI for SagaCloud Web & App Hosting",
5
5
  "license": "MIT",
6
6
  "author": "SagaSoft",