@temps-sdk/cli 0.1.8 → 0.1.9

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 +1968 -30
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -48792,7 +48792,8 @@ var configStore = new Conf({
48792
48792
  var SECRET_KEYS = {
48793
48793
  apiKey: "temps_api_key",
48794
48794
  userId: "temps_user_id",
48795
- email: "temps_email"
48795
+ email: "temps_email",
48796
+ cloudApiKey: "temps_cloud_api_key"
48796
48797
  };
48797
48798
  async function setSecret(key, value) {
48798
48799
  const secrets = await loadSecrets();
@@ -48897,7 +48898,8 @@ var credentials = {
48897
48898
  return {
48898
48899
  apiKey: secrets[SECRET_KEYS.apiKey],
48899
48900
  userId: userIdStr ? parseInt(userIdStr, 10) : undefined,
48900
- email: secrets[SECRET_KEYS.email]
48901
+ email: secrets[SECRET_KEYS.email],
48902
+ cloudApiKey: secrets[SECRET_KEYS.cloudApiKey]
48901
48903
  };
48902
48904
  },
48903
48905
  async setAll(values) {
@@ -48923,6 +48925,13 @@ var credentials = {
48923
48925
  delete secrets[SECRET_KEYS.email];
48924
48926
  }
48925
48927
  }
48928
+ if (values.cloudApiKey !== undefined) {
48929
+ if (values.cloudApiKey) {
48930
+ secrets[SECRET_KEYS.cloudApiKey] = values.cloudApiKey;
48931
+ } else {
48932
+ delete secrets[SECRET_KEYS.cloudApiKey];
48933
+ }
48934
+ }
48926
48935
  await saveSecrets(secrets);
48927
48936
  },
48928
48937
  async clear() {
@@ -56154,6 +56163,16 @@ async function promptUrl(message, defaultValue) {
56154
56163
  }
56155
56164
  });
56156
56165
  }
56166
+ async function promptEmail(message, defaultValue) {
56167
+ return promptText({
56168
+ message,
56169
+ default: defaultValue,
56170
+ validate: (value) => {
56171
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
56172
+ return emailRegex.test(value) || "Please enter a valid email address";
56173
+ }
56174
+ });
56175
+ }
56157
56176
  async function promptNumber(message, options) {
56158
56177
  const result = await promptText({
56159
56178
  message,
@@ -59500,8 +59519,15 @@ var createClient = (config2 = {}) => {
59500
59519
  var client = createClient(createConfig({ baseUrl: "/api" }));
59501
59520
 
59502
59521
  // src/lib/api-client.ts
59522
+ function normalizeApiUrl(url) {
59523
+ let normalized = url.replace(/\/+$/, "");
59524
+ if (!normalized.endsWith("/api")) {
59525
+ normalized += "/api";
59526
+ }
59527
+ return normalized;
59528
+ }
59503
59529
  async function setupClient() {
59504
- const apiUrl = config.get("apiUrl");
59530
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
59505
59531
  client.setConfig({
59506
59532
  baseUrl: apiUrl
59507
59533
  });
@@ -60712,7 +60738,40 @@ async function login(options) {
60712
60738
  info('Run "temps logout" first to switch accounts');
60713
60739
  return;
60714
60740
  }
60715
- const apiKey = options.apiKey ?? await promptPassword({
60741
+ if (options.magic) {
60742
+ await loginWithMagicLink(typeof options.magic === "string" ? options.magic : undefined);
60743
+ return;
60744
+ }
60745
+ if (options.email) {
60746
+ await loginWithEmail(typeof options.email === "string" ? options.email : undefined);
60747
+ return;
60748
+ }
60749
+ if (options.apiKey) {
60750
+ await loginWithApiKey(options.apiKey);
60751
+ return;
60752
+ }
60753
+ const method = await promptSelect({
60754
+ message: "How would you like to log in?",
60755
+ choices: [
60756
+ { name: "API Key", value: "api-key", description: "Paste an API key from the dashboard" },
60757
+ { name: "Email & Password", value: "email", description: "Log in with email and password" },
60758
+ { name: "Magic Link", value: "magic", description: "Receive a login link via email" }
60759
+ ]
60760
+ });
60761
+ switch (method) {
60762
+ case "api-key":
60763
+ await loginWithApiKey();
60764
+ break;
60765
+ case "email":
60766
+ await loginWithEmail();
60767
+ break;
60768
+ case "magic":
60769
+ await loginWithMagicLink();
60770
+ break;
60771
+ }
60772
+ }
60773
+ async function loginWithApiKey(apiKey) {
60774
+ const key = apiKey ?? await promptPassword({
60716
60775
  message: "API Key",
60717
60776
  validate: (value) => {
60718
60777
  if (!value || value.trim().length === 0) {
@@ -60721,10 +60780,7 @@ async function login(options) {
60721
60780
  return true;
60722
60781
  }
60723
60782
  });
60724
- await loginWithApiKey(apiKey);
60725
- }
60726
- async function loginWithApiKey(apiKey) {
60727
- await credentials.set("apiKey", apiKey);
60783
+ await credentials.set("apiKey", key);
60728
60784
  await setupClient();
60729
60785
  try {
60730
60786
  const result = await withSpinner("Validating API key...", async () => {
@@ -60738,23 +60794,246 @@ async function loginWithApiKey(apiKey) {
60738
60794
  throw new AuthenticationError("Invalid API key");
60739
60795
  }
60740
60796
  await credentials.setAll({
60741
- apiKey,
60797
+ apiKey: key,
60742
60798
  userId: result.id,
60743
60799
  email: result.email ?? undefined
60744
60800
  });
60745
- newline();
60746
- const lines = [
60747
- result.email ? `Logged in as ${colors.bold(result.email)}` : null,
60748
- `API: ${colors.muted(config.get("apiUrl"))}`,
60749
- `Credentials stored in: ${colors.muted(credentials.path)}`
60750
- ].filter(Boolean).join(`
60751
- `);
60752
- box(lines, `${icons.sparkles} Welcome to Temps!`);
60801
+ displayWelcome(result.email);
60753
60802
  } catch (err) {
60754
60803
  await credentials.clear();
60755
60804
  throw new AuthenticationError("Invalid API key");
60756
60805
  }
60757
60806
  }
60807
+ async function loginWithEmail(emailArg) {
60808
+ const email = emailArg ?? await promptEmail("Email");
60809
+ const password = await promptPassword({
60810
+ message: "Password",
60811
+ validate: (value) => {
60812
+ if (!value || value.trim().length === 0) {
60813
+ return "Password is required";
60814
+ }
60815
+ return true;
60816
+ }
60817
+ });
60818
+ const apiUrl = config.get("apiUrl");
60819
+ const authResponse = await withSpinner("Logging in...", async () => {
60820
+ const response = await fetch(`${apiUrl}/auth/login`, {
60821
+ method: "POST",
60822
+ headers: { "Content-Type": "application/json" },
60823
+ body: JSON.stringify({ email, password })
60824
+ });
60825
+ if (!response.ok) {
60826
+ if (response.status === 401) {
60827
+ throw new AuthenticationError("Invalid email or password");
60828
+ }
60829
+ throw new AuthenticationError(`Login failed (status ${response.status})`);
60830
+ }
60831
+ const data = await response.json();
60832
+ const setCookie = response.headers.get("set-cookie");
60833
+ return { data, setCookie };
60834
+ }, { successText: "Authenticated" });
60835
+ if (authResponse.data.mfa_required) {
60836
+ const mfaCode = await promptText({
60837
+ message: "MFA Code",
60838
+ required: true,
60839
+ validate: (value) => /^\d{6}$/.test(value) || "Enter a 6-digit code"
60840
+ });
60841
+ const sessionCookie2 = extractCookieValue(authResponse.setCookie, "session_token") ?? extractCookieValue(authResponse.setCookie, "id");
60842
+ await withSpinner("Verifying MFA...", async () => {
60843
+ const response = await fetch(`${apiUrl}/auth/verify-mfa`, {
60844
+ method: "POST",
60845
+ headers: {
60846
+ "Content-Type": "application/json",
60847
+ ...sessionCookie2 ? { Cookie: sessionCookie2 } : {}
60848
+ },
60849
+ body: JSON.stringify({ code: mfaCode })
60850
+ });
60851
+ if (!response.ok) {
60852
+ throw new AuthenticationError("Invalid MFA code");
60853
+ }
60854
+ const newSetCookie = response.headers.get("set-cookie");
60855
+ if (newSetCookie) {
60856
+ authResponse.setCookie = newSetCookie;
60857
+ }
60858
+ }, { successText: "MFA verified" });
60859
+ }
60860
+ const sessionCookie = extractSessionCookie(authResponse.setCookie);
60861
+ if (!sessionCookie) {
60862
+ warning("Could not extract session. Please create an API key from the dashboard.");
60863
+ info(`Dashboard: ${colors.primary(`${apiUrl}/dashboard/settings/api-keys`)}`);
60864
+ newline();
60865
+ info("Then run: temps login --api-key <your-key>");
60866
+ return;
60867
+ }
60868
+ const apiKey = await withSpinner("Creating API token...", async () => {
60869
+ const response = await fetch(`${apiUrl}/api/tokens`, {
60870
+ method: "POST",
60871
+ headers: {
60872
+ "Content-Type": "application/json",
60873
+ Cookie: sessionCookie
60874
+ },
60875
+ body: JSON.stringify({
60876
+ name: `temps-cli-${new Date().toISOString().split("T")[0]}`,
60877
+ permissions: ["*"]
60878
+ })
60879
+ });
60880
+ if (!response.ok) {
60881
+ throw new Error("Could not create API token from session");
60882
+ }
60883
+ const tokenData = await response.json();
60884
+ return tokenData.token ?? tokenData.api_key;
60885
+ }, { successText: "API token created" });
60886
+ if (!apiKey) {
60887
+ warning("Could not create API token. Please generate one from the dashboard.");
60888
+ info(`Dashboard: ${colors.primary(`${apiUrl}/dashboard/settings/api-keys`)}`);
60889
+ return;
60890
+ }
60891
+ await credentials.set("apiKey", apiKey);
60892
+ await setupClient();
60893
+ const user = await withSpinner("Validating...", async () => {
60894
+ const { data, error: error3 } = await getCurrentUser({ client });
60895
+ if (error3 || !data) {
60896
+ throw new AuthenticationError("Token validation failed");
60897
+ }
60898
+ return data;
60899
+ }, { successText: "Validated" });
60900
+ await credentials.setAll({
60901
+ apiKey,
60902
+ userId: user.id,
60903
+ email: user.email ?? undefined
60904
+ });
60905
+ displayWelcome(user.email);
60906
+ }
60907
+ async function loginWithMagicLink(emailArg) {
60908
+ const email = emailArg ?? await promptEmail("Email");
60909
+ const apiUrl = config.get("apiUrl");
60910
+ await withSpinner("Sending magic link...", async () => {
60911
+ const response = await fetch(`${apiUrl}/auth/magic-link/request`, {
60912
+ method: "POST",
60913
+ headers: { "Content-Type": "application/json" },
60914
+ body: JSON.stringify({ email })
60915
+ });
60916
+ if (!response.ok && response.status !== 200) {
60917
+ if (response.status === 503) {
60918
+ throw new Error("Email service is not configured on this server");
60919
+ }
60920
+ throw new Error("Failed to send magic link");
60921
+ }
60922
+ }, { successText: "Magic link sent" });
60923
+ newline();
60924
+ info("Check your email for a magic link.");
60925
+ info("After clicking the link, paste the token from the URL below.");
60926
+ newline();
60927
+ const tokenInput = await promptText({
60928
+ message: "Magic link token (from URL or email)",
60929
+ required: true
60930
+ });
60931
+ const token = extractTokenFromInput(tokenInput);
60932
+ const verifyResult = await withSpinner("Verifying token...", async () => {
60933
+ const response = await fetch(`${apiUrl}/auth/magic-link/verify?token=${encodeURIComponent(token)}`, {
60934
+ method: "GET",
60935
+ headers: { "Content-Type": "application/json" }
60936
+ });
60937
+ if (!response.ok) {
60938
+ if (response.status === 400) {
60939
+ throw new AuthenticationError("Invalid or expired token");
60940
+ }
60941
+ throw new AuthenticationError("Verification failed");
60942
+ }
60943
+ const data = await response.json();
60944
+ const setCookie = response.headers.get("set-cookie");
60945
+ return { data, setCookie };
60946
+ }, { successText: "Token verified" });
60947
+ const sessionCookie = extractSessionCookie(verifyResult.setCookie);
60948
+ if (!sessionCookie) {
60949
+ warning("Could not extract session. Please create an API key from the dashboard.");
60950
+ info(`Dashboard: ${colors.primary(`${apiUrl}/dashboard/settings/api-keys`)}`);
60951
+ newline();
60952
+ info("Then run: temps login --api-key <your-key>");
60953
+ return;
60954
+ }
60955
+ const apiKey = await withSpinner("Creating API token...", async () => {
60956
+ const response = await fetch(`${apiUrl}/api/tokens`, {
60957
+ method: "POST",
60958
+ headers: {
60959
+ "Content-Type": "application/json",
60960
+ Cookie: sessionCookie
60961
+ },
60962
+ body: JSON.stringify({
60963
+ name: `temps-cli-${new Date().toISOString().split("T")[0]}`,
60964
+ permissions: ["*"]
60965
+ })
60966
+ });
60967
+ if (!response.ok) {
60968
+ throw new Error("Could not create API token from session");
60969
+ }
60970
+ const tokenData = await response.json();
60971
+ return tokenData.token ?? tokenData.api_key;
60972
+ }, { successText: "API token created" });
60973
+ if (!apiKey) {
60974
+ warning("Could not create API token. Please generate one from the dashboard.");
60975
+ return;
60976
+ }
60977
+ await credentials.set("apiKey", apiKey);
60978
+ await setupClient();
60979
+ const user = await withSpinner("Validating...", async () => {
60980
+ const { data, error: error3 } = await getCurrentUser({ client });
60981
+ if (error3 || !data)
60982
+ throw new AuthenticationError("Token validation failed");
60983
+ return data;
60984
+ }, { successText: "Validated" });
60985
+ await credentials.setAll({
60986
+ apiKey,
60987
+ userId: user.id,
60988
+ email: user.email ?? undefined
60989
+ });
60990
+ displayWelcome(user.email);
60991
+ }
60992
+ function extractCookieValue(setCookie, name) {
60993
+ if (!setCookie)
60994
+ return null;
60995
+ const cookies = setCookie.split(/,(?=\s*\w+=)/);
60996
+ for (const cookie of cookies) {
60997
+ const match = cookie.match(new RegExp(`${name}=([^;]+)`));
60998
+ if (match)
60999
+ return `${name}=${match[1]}`;
61000
+ }
61001
+ return null;
61002
+ }
61003
+ function extractSessionCookie(setCookie) {
61004
+ if (!setCookie)
61005
+ return null;
61006
+ const cookieNames = ["session_token", "session", "id", "sid"];
61007
+ for (const name of cookieNames) {
61008
+ const cookie = extractCookieValue(setCookie, name);
61009
+ if (cookie)
61010
+ return cookie;
61011
+ }
61012
+ const match = setCookie.match(/^([^=]+=[^;]+)/);
61013
+ if (match?.[1])
61014
+ return match[1];
61015
+ return null;
61016
+ }
61017
+ function extractTokenFromInput(input) {
61018
+ const trimmed = input.trim();
61019
+ try {
61020
+ const url = new URL(trimmed);
61021
+ const token = url.searchParams.get("token");
61022
+ if (token)
61023
+ return token;
61024
+ } catch {}
61025
+ return trimmed;
61026
+ }
61027
+ function displayWelcome(email) {
61028
+ newline();
61029
+ const lines = [
61030
+ email ? `Logged in as ${colors.bold(email)}` : null,
61031
+ `API: ${colors.muted(config.get("apiUrl"))}`,
61032
+ `Credentials stored in: ${colors.muted(credentials.path)}`
61033
+ ].filter(Boolean).join(`
61034
+ `);
61035
+ box(lines, `${icons.sparkles} Welcome to Temps!`);
61036
+ }
60758
61037
 
60759
61038
  // src/commands/auth/logout.ts
60760
61039
  async function logout() {
@@ -60804,7 +61083,7 @@ async function whoami(options) {
60804
61083
 
60805
61084
  // src/commands/auth/index.ts
60806
61085
  function registerAuthCommands(program2) {
60807
- program2.command("login").description("Authenticate with Temps using an API key").option("-k, --api-key <key>", "API key (will prompt if not provided)").action(login);
61086
+ program2.command("login").description("Authenticate with the current Temps instance").option("-k, --api-key <key>", "API key (will prompt if not provided)").option("--email [email]", "Login with email and password").option("--magic [email]", "Login via magic link (email-based)").action(login);
60808
61087
  program2.command("logout").description("Log out and clear credentials").action(logout);
60809
61088
  program2.command("whoami").description("Display current authenticated user").option("--json", "Output as JSON").action(whoami);
60810
61089
  }
@@ -81260,6 +81539,1629 @@ async function resetPreferencesAction(options) {
81260
81539
  success("Notification preferences reset to defaults");
81261
81540
  }
81262
81541
 
81542
+ // src/config/project-config.ts
81543
+ import { readFile as readFile3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
81544
+ import { existsSync as existsSync6 } from "node:fs";
81545
+ import { join as join2, dirname as dirname2 } from "node:path";
81546
+ var CONFIG_DIR = ".temps";
81547
+ var CONFIG_FILE = "config.json";
81548
+ var GITIGNORE_FILE = ".gitignore";
81549
+ function findProjectConfigDir(startDir) {
81550
+ let dir = startDir ?? process.cwd();
81551
+ while (true) {
81552
+ const configPath = join2(dir, CONFIG_DIR, CONFIG_FILE);
81553
+ if (existsSync6(configPath)) {
81554
+ return join2(dir, CONFIG_DIR);
81555
+ }
81556
+ const parent = dirname2(dir);
81557
+ if (parent === dir)
81558
+ break;
81559
+ dir = parent;
81560
+ }
81561
+ return null;
81562
+ }
81563
+ async function readProjectConfig() {
81564
+ const configDir = findProjectConfigDir();
81565
+ if (!configDir)
81566
+ return null;
81567
+ try {
81568
+ const configPath = join2(configDir, CONFIG_FILE);
81569
+ const content = await readFile3(configPath, "utf-8");
81570
+ return JSON.parse(content);
81571
+ } catch {
81572
+ return null;
81573
+ }
81574
+ }
81575
+ async function writeProjectConfig(config2) {
81576
+ const configDir = join2(process.cwd(), CONFIG_DIR);
81577
+ await mkdir2(configDir, { recursive: true });
81578
+ const configPath = join2(configDir, CONFIG_FILE);
81579
+ await writeFile2(configPath, JSON.stringify(config2, null, 2) + `
81580
+ `, "utf-8");
81581
+ const gitignorePath = join2(configDir, GITIGNORE_FILE);
81582
+ if (!existsSync6(gitignorePath)) {
81583
+ await writeFile2(gitignorePath, `*
81584
+ `, "utf-8");
81585
+ }
81586
+ return configPath;
81587
+ }
81588
+ function hasProjectConfig() {
81589
+ return findProjectConfigDir() !== null;
81590
+ }
81591
+
81592
+ // src/commands/init/index.ts
81593
+ async function init(projectSlug, options) {
81594
+ await requireAuth();
81595
+ await setupClient();
81596
+ newline();
81597
+ if (hasProjectConfig()) {
81598
+ const existing = await readProjectConfig();
81599
+ if (existing) {
81600
+ warning(`This directory is already linked to ${colors.bold(existing.projectSlug)}`);
81601
+ if (!options.yes) {
81602
+ const overwrite = await promptConfirm({
81603
+ message: "Reinitialize?",
81604
+ default: false
81605
+ });
81606
+ if (!overwrite) {
81607
+ info("Cancelled");
81608
+ return;
81609
+ }
81610
+ }
81611
+ }
81612
+ }
81613
+ let slug;
81614
+ if (projectSlug) {
81615
+ const project = await withSpinner("Verifying project...", async () => {
81616
+ const { data, error: error3 } = await getProjectBySlug({
81617
+ client,
81618
+ path: { slug: projectSlug }
81619
+ });
81620
+ if (error3 || !data) {
81621
+ throw new Error(`Project "${projectSlug}" not found`);
81622
+ }
81623
+ return data;
81624
+ });
81625
+ slug = projectSlug;
81626
+ info(`Found project: ${colors.bold(project.name)}`);
81627
+ } else if (options.yes) {
81628
+ throw new Error("Project slug is required with --yes flag. Use: temps init <project-slug> --yes");
81629
+ } else {
81630
+ const action = await promptSelect({
81631
+ message: "What would you like to do?",
81632
+ choices: [
81633
+ {
81634
+ name: "Link existing project",
81635
+ value: "link",
81636
+ description: "Connect this directory to an existing Temps project"
81637
+ },
81638
+ {
81639
+ name: "Create new project",
81640
+ value: "create",
81641
+ description: "Create a new project and link it here"
81642
+ }
81643
+ ]
81644
+ });
81645
+ if (action === "create") {
81646
+ info("Starting project creation wizard...");
81647
+ info(`Run: ${colors.bold("temps projects create")}`);
81648
+ info("Then link with: temps link <project-slug>");
81649
+ return;
81650
+ }
81651
+ const projects = await withSpinner("Fetching projects...", async () => {
81652
+ const { data, error: error3 } = await getProjects({
81653
+ client,
81654
+ query: { per_page: 100 }
81655
+ });
81656
+ if (error3 || !data) {
81657
+ throw new Error(getErrorMessage(error3));
81658
+ }
81659
+ return data.projects ?? [];
81660
+ });
81661
+ if (projects.length === 0) {
81662
+ warning("No projects found");
81663
+ info("Create one with: temps projects create");
81664
+ return;
81665
+ }
81666
+ slug = await promptSearch({
81667
+ message: "Select a project",
81668
+ choices: projects.map((p) => ({
81669
+ name: `${p.name} (${p.slug})`,
81670
+ value: p.slug,
81671
+ description: p.main_branch ? `Branch: ${p.main_branch}` : undefined
81672
+ }))
81673
+ });
81674
+ }
81675
+ const configPath = await writeProjectConfig({
81676
+ projectSlug: slug
81677
+ });
81678
+ newline();
81679
+ box([
81680
+ `Project: ${colors.bold(slug)}`,
81681
+ `Config: ${colors.muted(configPath)}`
81682
+ ].join(`
81683
+ `), `${icons.sparkles} Project Initialized`);
81684
+ newline();
81685
+ info("Next steps:");
81686
+ info(` ${colors.muted("temps up")} ${colors.muted("# Deploy this project")}`);
81687
+ info(` ${colors.muted("temps status")} ${colors.muted("# View project status")}`);
81688
+ info(` ${colors.muted("temps env:pull")} ${colors.muted("# Pull environment variables")}`);
81689
+ }
81690
+ function registerInitCommand(program2) {
81691
+ program2.command("init [project-slug]").description("Initialize a Temps project in the current directory").option("-n, --name <name>", "Project name (for new projects)").option("-y, --yes", "Skip confirmation prompts").action(init);
81692
+ }
81693
+
81694
+ // src/commands/link/index.ts
81695
+ async function link2(projectSlug, options) {
81696
+ await requireAuth();
81697
+ await setupClient();
81698
+ newline();
81699
+ if (hasProjectConfig()) {
81700
+ const existing = await readProjectConfig();
81701
+ if (existing) {
81702
+ warning(`This directory is already linked to ${colors.bold(existing.projectSlug)}`);
81703
+ const overwrite = await promptConfirm({
81704
+ message: "Overwrite existing link?",
81705
+ default: false
81706
+ });
81707
+ if (!overwrite) {
81708
+ info("Cancelled");
81709
+ return;
81710
+ }
81711
+ }
81712
+ }
81713
+ let slug;
81714
+ if (projectSlug) {
81715
+ const project = await withSpinner("Verifying project...", async () => {
81716
+ const { data, error: error3 } = await getProjectBySlug({
81717
+ client,
81718
+ path: { slug: projectSlug }
81719
+ });
81720
+ if (error3 || !data) {
81721
+ throw new Error(`Project "${projectSlug}" not found`);
81722
+ }
81723
+ return data;
81724
+ });
81725
+ slug = projectSlug;
81726
+ info(`Found project: ${colors.bold(project.name)}`);
81727
+ } else {
81728
+ const projects = await withSpinner("Fetching projects...", async () => {
81729
+ const { data, error: error3 } = await getProjects({
81730
+ client,
81731
+ query: { per_page: 100 }
81732
+ });
81733
+ if (error3 || !data) {
81734
+ throw new Error(getErrorMessage(error3));
81735
+ }
81736
+ return data.projects ?? [];
81737
+ });
81738
+ if (projects.length === 0) {
81739
+ warning("No projects found. Create one first with: temps projects create");
81740
+ return;
81741
+ }
81742
+ slug = await promptSearch({
81743
+ message: "Select a project to link",
81744
+ choices: projects.map((p) => ({
81745
+ name: `${p.name} (${p.slug})`,
81746
+ value: p.slug,
81747
+ description: p.main_branch ? `Branch: ${p.main_branch}` : undefined
81748
+ }))
81749
+ });
81750
+ }
81751
+ let environmentName = options.environment;
81752
+ if (!environmentName) {
81753
+ try {
81754
+ const { data: projectData } = await getProjectBySlug({
81755
+ client,
81756
+ path: { slug }
81757
+ });
81758
+ if (projectData) {
81759
+ const { data: envs } = await getEnvironments({
81760
+ client,
81761
+ path: { project_id: projectData.id }
81762
+ });
81763
+ if (envs && envs.length > 1) {
81764
+ const setDefault = await promptConfirm({
81765
+ message: "Set a default environment?",
81766
+ default: false
81767
+ });
81768
+ if (setDefault) {
81769
+ environmentName = await promptSelect({
81770
+ message: "Default environment",
81771
+ choices: envs.map((e) => ({
81772
+ name: e.name,
81773
+ value: e.name,
81774
+ description: e.is_preview ? "Preview" : undefined
81775
+ }))
81776
+ });
81777
+ }
81778
+ }
81779
+ }
81780
+ } catch {}
81781
+ }
81782
+ const configPath = await writeProjectConfig({
81783
+ projectSlug: slug,
81784
+ environmentName
81785
+ });
81786
+ newline();
81787
+ box([
81788
+ `Project: ${colors.bold(slug)}`,
81789
+ environmentName ? `Environment: ${colors.bold(environmentName)}` : null,
81790
+ `Config: ${colors.muted(configPath)}`
81791
+ ].filter(Boolean).join(`
81792
+ `), `${icons.check} Directory Linked`);
81793
+ newline();
81794
+ info("You can now run commands without specifying --project:");
81795
+ info(` ${colors.muted("temps up")} ${colors.muted("# Deploy this project")}`);
81796
+ info(` ${colors.muted("temps status")} ${colors.muted("# View project status")}`);
81797
+ info(` ${colors.muted("temps env:pull")} ${colors.muted("# Pull environment variables")}`);
81798
+ }
81799
+ function registerLinkCommand(program2) {
81800
+ program2.command("link [project-slug]").description("Link current directory to a Temps project").option("-e, --environment <name>", "Set default environment").action(link2);
81801
+ }
81802
+
81803
+ // src/commands/up/index.ts
81804
+ import { execSync } from "node:child_process";
81805
+
81806
+ // src/config/resolve-project.ts
81807
+ async function resolveProjectSlug(flagValue) {
81808
+ if (flagValue) {
81809
+ return { slug: flagValue, source: "flag" };
81810
+ }
81811
+ const localConfig = await readProjectConfig();
81812
+ if (localConfig?.projectSlug) {
81813
+ return { slug: localConfig.projectSlug, source: "local-config" };
81814
+ }
81815
+ const envProject = process.env.TEMPS_PROJECT;
81816
+ if (envProject) {
81817
+ return { slug: envProject, source: "env-var" };
81818
+ }
81819
+ const defaultProject = config.get("defaultProject");
81820
+ if (defaultProject) {
81821
+ return { slug: defaultProject, source: "global-config" };
81822
+ }
81823
+ return null;
81824
+ }
81825
+ async function requireProjectSlug(flagValue) {
81826
+ const resolved = await resolveProjectSlug(flagValue);
81827
+ if (resolved)
81828
+ return resolved;
81829
+ throw new Error(`No project specified. You can:
81830
+ ` + ` • Pass --project <slug> flag
81831
+ ` + ` • Run "temps link" to link this directory to a project
81832
+ ` + ` • Set TEMPS_PROJECT environment variable
81833
+ ` + ' • Run "temps configure" to set a default project');
81834
+ }
81835
+
81836
+ // src/commands/up/index.ts
81837
+ function detectGitBranch() {
81838
+ try {
81839
+ return execSync("git rev-parse --abbrev-ref HEAD", {
81840
+ encoding: "utf-8",
81841
+ stdio: ["pipe", "pipe", "pipe"]
81842
+ }).trim();
81843
+ } catch {
81844
+ return null;
81845
+ }
81846
+ }
81847
+ async function up(projectArg, options) {
81848
+ await requireAuth();
81849
+ await setupClient();
81850
+ const resolved = await resolveProjectSlug(projectArg ?? options.project);
81851
+ if (!resolved) {
81852
+ newline();
81853
+ warning("No project linked to this directory");
81854
+ info('Run "temps init" or "temps link" to connect a project');
81855
+ return;
81856
+ }
81857
+ let branch = options.branch;
81858
+ if (!branch) {
81859
+ const detectedBranch = detectGitBranch();
81860
+ if (detectedBranch && detectedBranch !== "HEAD") {
81861
+ branch = detectedBranch;
81862
+ }
81863
+ }
81864
+ if (resolved.source !== "flag") {
81865
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
81866
+ }
81867
+ await deploy({
81868
+ project: resolved.slug,
81869
+ environment: options.environment,
81870
+ branch,
81871
+ wait: options.wait,
81872
+ yes: options.yes
81873
+ });
81874
+ if (!hasProjectConfig() && !options.yes) {
81875
+ newline();
81876
+ const save = await promptConfirm({
81877
+ message: "Save this project link for future use?",
81878
+ default: true
81879
+ });
81880
+ if (save) {
81881
+ await writeProjectConfig({ projectSlug: resolved.slug });
81882
+ info("Saved to .temps/config.json");
81883
+ }
81884
+ }
81885
+ }
81886
+ function registerUpCommand(program2) {
81887
+ program2.command("up [project]").description("Deploy the current project (shortcut for deploy)").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Target environment name").option("-b, --branch <branch>", "Git branch to deploy (auto-detected from cwd)").option("--no-wait", "Do not wait for deployment to complete").option("-y, --yes", "Skip confirmation prompts").action((projectArg, opts) => {
81888
+ if (projectArg && !opts.project) {
81889
+ opts.project = projectArg;
81890
+ }
81891
+ return up(projectArg, opts);
81892
+ });
81893
+ }
81894
+
81895
+ // src/commands/status/index.ts
81896
+ async function status2(projectArg, options) {
81897
+ await requireAuth();
81898
+ await setupClient();
81899
+ const resolved = await requireProjectSlug(projectArg ?? options.project);
81900
+ const projectData = await withSpinner("Fetching project status...", async () => {
81901
+ const { data, error: error3 } = await getProjectBySlug({
81902
+ client,
81903
+ path: { slug: resolved.slug }
81904
+ });
81905
+ if (error3 || !data) {
81906
+ throw new Error(`Project "${resolved.slug}" not found`);
81907
+ }
81908
+ return data;
81909
+ });
81910
+ const { data: environments } = await getEnvironments({
81911
+ client,
81912
+ path: { project_id: projectData.id }
81913
+ });
81914
+ const envList = environments ?? [];
81915
+ const targetEnvs = options.environment ? envList.filter((e) => e.name.toLowerCase() === options.environment.toLowerCase() || e.slug === options.environment) : envList;
81916
+ if (options.json) {
81917
+ const data = {
81918
+ project: {
81919
+ id: projectData.id,
81920
+ name: projectData.name,
81921
+ slug: projectData.slug,
81922
+ main_branch: projectData.main_branch
81923
+ },
81924
+ environments: targetEnvs.map((e) => ({
81925
+ id: e.id,
81926
+ name: e.name,
81927
+ slug: e.slug,
81928
+ url: e.main_url,
81929
+ is_preview: e.is_preview
81930
+ }))
81931
+ };
81932
+ json(data);
81933
+ return;
81934
+ }
81935
+ newline();
81936
+ header(`${icons.folder} ${projectData.name}`);
81937
+ keyValue("Slug", projectData.slug);
81938
+ keyValue("Branch", projectData.main_branch ?? "main");
81939
+ if (resolved.source !== "flag") {
81940
+ keyValue("Source", colors.muted(resolved.source));
81941
+ }
81942
+ if (targetEnvs.length === 0) {
81943
+ newline();
81944
+ if (options.environment) {
81945
+ console.log(colors.warning(` Environment "${options.environment}" not found`));
81946
+ } else {
81947
+ console.log(colors.muted(" No environments configured"));
81948
+ }
81949
+ newline();
81950
+ return;
81951
+ }
81952
+ for (const env4 of targetEnvs) {
81953
+ newline();
81954
+ console.log(colors.muted("─".repeat(50)));
81955
+ console.log(` ${colors.bold(env4.name)} ${env4.is_preview ? colors.muted("(preview)") : ""}`);
81956
+ console.log(colors.muted("─".repeat(50)));
81957
+ try {
81958
+ const { data: deployment } = await getLastDeployment({
81959
+ client,
81960
+ path: { id: projectData.id }
81961
+ });
81962
+ if (deployment && deployment.environment_id === env4.id) {
81963
+ keyValue(" Status", statusBadge(deployment.status));
81964
+ keyValue(" Last Deploy", `#${deployment.id} - ${deployment.commit_hash?.substring(0, 7) ?? "-"} - ${formatRelativeTime(new Date(deployment.created_at * 1000).toISOString())}`);
81965
+ } else {
81966
+ keyValue(" Status", colors.muted("no deployments"));
81967
+ }
81968
+ } catch {
81969
+ keyValue(" Status", colors.muted("unable to fetch"));
81970
+ }
81971
+ if (env4.main_url) {
81972
+ keyValue(" URL", colors.primary(env4.main_url));
81973
+ }
81974
+ try {
81975
+ const { data: containerData } = await listContainers({
81976
+ client,
81977
+ path: { project_id: projectData.id, environment_id: env4.id }
81978
+ });
81979
+ if (containerData && containerData.containers.length > 0) {
81980
+ const running = containerData.containers.filter((c) => c.status?.toLowerCase() === "running").length;
81981
+ keyValue(" Containers", `${running}/${containerData.containers.length} running`);
81982
+ }
81983
+ } catch {}
81984
+ }
81985
+ newline();
81986
+ }
81987
+ function registerStatusCommand(program2) {
81988
+ program2.command("status [project]").description("Show project deployment status").option("-p, --project <project>", "Project slug").option("-e, --environment <env>", "Filter by environment").option("--json", "Output in JSON format").action((projectArg, opts) => {
81989
+ if (projectArg && !opts.project) {
81990
+ opts.project = projectArg;
81991
+ }
81992
+ return status2(projectArg, opts);
81993
+ });
81994
+ }
81995
+
81996
+ // src/config/instances.ts
81997
+ import { readFile as readFile4, writeFile as writeFile3, mkdir as mkdir3 } from "node:fs/promises";
81998
+ import { existsSync as existsSync7 } from "node:fs";
81999
+ import { dirname as dirname3 } from "node:path";
82000
+ function getInstancesPath() {
82001
+ const home = process.env.HOME || process.env.USERPROFILE || "~";
82002
+ return `${home}/.temps/.instances.json`;
82003
+ }
82004
+ async function loadInstances() {
82005
+ const path6 = getInstancesPath();
82006
+ try {
82007
+ if (existsSync7(path6)) {
82008
+ const content = await readFile4(path6, "utf-8");
82009
+ return JSON.parse(content);
82010
+ }
82011
+ } catch {}
82012
+ return [];
82013
+ }
82014
+ async function saveInstances(instances2) {
82015
+ const path6 = getInstancesPath();
82016
+ const dir = dirname3(path6);
82017
+ await mkdir3(dir, { recursive: true });
82018
+ await writeFile3(path6, JSON.stringify(instances2, null, 2) + `
82019
+ `, { mode: 384 });
82020
+ }
82021
+ async function listInstances() {
82022
+ return loadInstances();
82023
+ }
82024
+ async function addInstance(instance) {
82025
+ const instances2 = await loadInstances();
82026
+ const existing = instances2.findIndex((i) => i.name === instance.name);
82027
+ if (existing >= 0) {
82028
+ instances2[existing] = instance;
82029
+ } else {
82030
+ instances2.push(instance);
82031
+ }
82032
+ if (instance.isDefault || instances2.length === 1) {
82033
+ for (const inst of instances2) {
82034
+ inst.isDefault = inst.name === instance.name;
82035
+ }
82036
+ }
82037
+ await saveInstances(instances2);
82038
+ }
82039
+ async function removeInstance(name) {
82040
+ const instances2 = await loadInstances();
82041
+ const filtered = instances2.filter((i) => i.name !== name);
82042
+ if (filtered.length === instances2.length) {
82043
+ return false;
82044
+ }
82045
+ if (!filtered.some((i) => i.isDefault) && filtered.length > 0) {
82046
+ filtered[0].isDefault = true;
82047
+ }
82048
+ await saveInstances(filtered);
82049
+ return true;
82050
+ }
82051
+ async function setDefaultInstance(name) {
82052
+ const instances2 = await loadInstances();
82053
+ const target = instances2.find((i) => i.name === name);
82054
+ if (!target)
82055
+ return false;
82056
+ for (const inst of instances2) {
82057
+ inst.isDefault = inst.name === name;
82058
+ }
82059
+ await saveInstances(instances2);
82060
+ return true;
82061
+ }
82062
+ async function getInstance2(name) {
82063
+ const instances2 = await loadInstances();
82064
+ return instances2.find((i) => i.name === name) ?? null;
82065
+ }
82066
+
82067
+ // src/commands/instances/index.ts
82068
+ async function listAction2(options) {
82069
+ const instances2 = await listInstances();
82070
+ if (instances2.length === 0) {
82071
+ newline();
82072
+ info("No instances configured");
82073
+ info(`Add one with: ${colors.bold("temps login --cloud")}`);
82074
+ newline();
82075
+ return;
82076
+ }
82077
+ if (options.json) {
82078
+ json(instances2.map((i) => ({ name: i.name, url: i.url, email: i.email, isDefault: i.isDefault })));
82079
+ return;
82080
+ }
82081
+ newline();
82082
+ header(`${icons.globe} Temps Instances (${instances2.length})`);
82083
+ const columns = [
82084
+ {
82085
+ header: "",
82086
+ accessor: (i) => i.isDefault ? colors.success("●") : colors.muted("○")
82087
+ },
82088
+ { header: "Name", key: "name", color: (v) => colors.bold(v) },
82089
+ { header: "URL", key: "url", color: (v) => colors.primary(v) },
82090
+ {
82091
+ header: "Email",
82092
+ accessor: (i) => i.email ?? colors.muted("-")
82093
+ }
82094
+ ];
82095
+ printTable(instances2, columns, { style: "minimal" });
82096
+ newline();
82097
+ }
82098
+ async function addAction(options) {
82099
+ const name = options.name ?? await promptText({
82100
+ message: "Instance name",
82101
+ required: true
82102
+ });
82103
+ const url = options.url ?? await promptUrl("Instance URL");
82104
+ await addInstance({ name, url, isDefault: false });
82105
+ success(`Instance "${name}" added`);
82106
+ info(`Login with: ${colors.bold(`temps login --cloud --url ${url}`)}`);
82107
+ }
82108
+ async function removeAction2(name) {
82109
+ const instance = await getInstance2(name);
82110
+ if (!instance) {
82111
+ error(`Instance "${name}" not found`);
82112
+ return;
82113
+ }
82114
+ const confirmed = await promptConfirm({
82115
+ message: `Remove instance "${name}" (${instance.url})?`,
82116
+ default: false
82117
+ });
82118
+ if (!confirmed) {
82119
+ info("Cancelled");
82120
+ return;
82121
+ }
82122
+ const removed = await removeInstance(name);
82123
+ if (removed) {
82124
+ success(`Instance "${name}" removed`);
82125
+ } else {
82126
+ error(`Instance "${name}" not found`);
82127
+ }
82128
+ }
82129
+ async function switchAction(name) {
82130
+ const instance = await getInstance2(name);
82131
+ if (!instance) {
82132
+ error(`Instance "${name}" not found`);
82133
+ const instances2 = await listInstances();
82134
+ if (instances2.length > 0) {
82135
+ info(`Available: ${instances2.map((i) => i.name).join(", ")}`);
82136
+ }
82137
+ return;
82138
+ }
82139
+ await setDefaultInstance(name);
82140
+ config.set("apiUrl", instance.url);
82141
+ if (instance.apiKey) {
82142
+ await credentials.setAll({
82143
+ apiKey: instance.apiKey,
82144
+ email: instance.email
82145
+ });
82146
+ }
82147
+ success(`Switched to instance "${name}"`);
82148
+ keyValue("URL", instance.url);
82149
+ if (instance.email) {
82150
+ keyValue("Email", instance.email);
82151
+ }
82152
+ }
82153
+ async function showAction2(name, options) {
82154
+ if (name) {
82155
+ const instance = await getInstance2(name);
82156
+ if (!instance) {
82157
+ error(`Instance "${name}" not found`);
82158
+ return;
82159
+ }
82160
+ if (options.json) {
82161
+ json({ name: instance.name, url: instance.url, email: instance.email, isDefault: instance.isDefault });
82162
+ return;
82163
+ }
82164
+ newline();
82165
+ header(`${icons.globe} ${instance.name}`);
82166
+ keyValue("URL", instance.url);
82167
+ keyValue("Email", instance.email ?? colors.muted("not set"));
82168
+ keyValue("Default", instance.isDefault ? "Yes" : "No");
82169
+ newline();
82170
+ } else {
82171
+ const apiUrl = config.get("apiUrl");
82172
+ const email = await credentials.get("email");
82173
+ if (options.json) {
82174
+ json({ url: apiUrl, email });
82175
+ return;
82176
+ }
82177
+ newline();
82178
+ header(`${icons.globe} Current Instance`);
82179
+ keyValue("URL", apiUrl);
82180
+ keyValue("Email", email ?? colors.muted("not logged in"));
82181
+ newline();
82182
+ }
82183
+ }
82184
+ function registerInstancesCommands(program2) {
82185
+ const instances2 = program2.command("instances").alias("instance").description("Manage Temps server instances");
82186
+ instances2.command("list").alias("ls").description("List configured instances").option("--json", "Output in JSON format").action(listAction2);
82187
+ instances2.command("add").description("Add a new instance").option("-n, --name <name>", "Instance name").option("-u, --url <url>", "Instance URL").action(addAction);
82188
+ instances2.command("remove <name>").alias("rm").description("Remove an instance").action(removeAction2);
82189
+ instances2.command("switch <name>").alias("use").description("Switch to a different instance").action(switchAction);
82190
+ instances2.command("show [name]").description("Show instance details (or current instance)").option("--json", "Output in JSON format").action(showAction2);
82191
+ }
82192
+
82193
+ // src/commands/env-sync/index.ts
82194
+ import * as fs5 from "node:fs";
82195
+ import * as path6 from "node:path";
82196
+ async function resolveProjectId2(slug) {
82197
+ const { data, error: error3 } = await getProjectBySlug({
82198
+ client,
82199
+ path: { slug }
82200
+ });
82201
+ if (error3 || !data) {
82202
+ throw new Error(`Project "${slug}" not found`);
82203
+ }
82204
+ return data.id;
82205
+ }
82206
+ async function pull(file, options) {
82207
+ await requireAuth();
82208
+ await setupClient();
82209
+ const resolved = await requireProjectSlug(options.project);
82210
+ const outputFile = file ?? ".env";
82211
+ const result = await withSpinner("Fetching environment variables...", async () => {
82212
+ const projectId = await resolveProjectId2(resolved.slug);
82213
+ const [varsResult, envsResult] = await Promise.all([
82214
+ getEnvironmentVariables({ client, path: { project_id: projectId } }),
82215
+ getEnvironments({ client, path: { project_id: projectId } })
82216
+ ]);
82217
+ if (varsResult.error)
82218
+ throw new Error(getErrorMessage(varsResult.error));
82219
+ if (envsResult.error)
82220
+ throw new Error(getErrorMessage(envsResult.error));
82221
+ return {
82222
+ vars: varsResult.data ?? [],
82223
+ envs: envsResult.data ?? []
82224
+ };
82225
+ });
82226
+ let filteredVars = result.vars;
82227
+ if (options.environment) {
82228
+ const targetEnv = result.envs.find((e) => e.name.toLowerCase() === options.environment.toLowerCase() || e.slug === options.environment);
82229
+ if (!targetEnv) {
82230
+ error(`Environment "${options.environment}" not found`);
82231
+ info(`Available: ${result.envs.map((e) => e.name).join(", ")}`);
82232
+ return;
82233
+ }
82234
+ filteredVars = result.vars.filter((v) => v.environments.some((e) => e.id === targetEnv.id));
82235
+ } else if (result.envs.length > 1) {
82236
+ const envName = await promptSelect({
82237
+ message: "Pull from which environment?",
82238
+ choices: result.envs.map((e) => ({
82239
+ name: e.name,
82240
+ value: e.name,
82241
+ description: e.is_preview ? "Preview" : undefined
82242
+ }))
82243
+ });
82244
+ const targetEnv = result.envs.find((e) => e.name === envName);
82245
+ if (targetEnv) {
82246
+ filteredVars = result.vars.filter((v) => v.environments.some((e) => e.id === targetEnv.id));
82247
+ }
82248
+ }
82249
+ if (filteredVars.length === 0) {
82250
+ warning("No environment variables to pull");
82251
+ return;
82252
+ }
82253
+ const envContent = filteredVars.map((v) => {
82254
+ const escapedValue = v.value.includes(`
82255
+ `) || v.value.includes('"') ? `"${v.value.replace(/"/g, "\\\"").replace(/\n/g, "\\n")}"` : v.value.includes(" ") || v.value.includes("#") ? `"${v.value}"` : v.value;
82256
+ return `${v.key}=${escapedValue}`;
82257
+ }).join(`
82258
+ `);
82259
+ const outputPath = path6.isAbsolute(outputFile) ? outputFile : path6.resolve(process.cwd(), outputFile);
82260
+ if (fs5.existsSync(outputPath)) {
82261
+ const overwrite = await promptConfirm({
82262
+ message: `${outputFile} already exists. Overwrite?`,
82263
+ default: false
82264
+ });
82265
+ if (!overwrite) {
82266
+ info("Cancelled");
82267
+ return;
82268
+ }
82269
+ }
82270
+ fs5.writeFileSync(outputPath, envContent + `
82271
+ `);
82272
+ success(`Pulled ${filteredVars.length} variables to ${outputFile}`);
82273
+ }
82274
+ async function push(file, options) {
82275
+ await requireAuth();
82276
+ await setupClient();
82277
+ const resolved = await requireProjectSlug(options.project);
82278
+ const inputFile = file ?? ".env";
82279
+ const inputPath = path6.isAbsolute(inputFile) ? inputFile : path6.resolve(process.cwd(), inputFile);
82280
+ if (!fs5.existsSync(inputPath)) {
82281
+ error(`File not found: ${inputFile}`);
82282
+ return;
82283
+ }
82284
+ const content = fs5.readFileSync(inputPath, "utf-8");
82285
+ const variables = parseEnvFile2(content);
82286
+ if (Object.keys(variables).length === 0) {
82287
+ warning("No variables found in file");
82288
+ return;
82289
+ }
82290
+ info(`Found ${Object.keys(variables).length} variables in ${inputFile}`);
82291
+ const result = await withSpinner("Fetching environments...", async () => {
82292
+ const projectId = await resolveProjectId2(resolved.slug);
82293
+ const [varsResult, envsResult] = await Promise.all([
82294
+ getEnvironmentVariables({ client, path: { project_id: projectId } }),
82295
+ getEnvironments({ client, path: { project_id: projectId } })
82296
+ ]);
82297
+ if (varsResult.error)
82298
+ throw new Error(getErrorMessage(varsResult.error));
82299
+ if (envsResult.error)
82300
+ throw new Error(getErrorMessage(envsResult.error));
82301
+ return {
82302
+ projectId,
82303
+ vars: varsResult.data ?? [],
82304
+ envs: envsResult.data ?? []
82305
+ };
82306
+ });
82307
+ if (result.envs.length === 0) {
82308
+ error("No environments found. Create an environment first.");
82309
+ return;
82310
+ }
82311
+ let environmentIds;
82312
+ if (options.environment) {
82313
+ const envNames = options.environment.split(",").map((n) => n.trim().toLowerCase());
82314
+ environmentIds = [];
82315
+ for (const name of envNames) {
82316
+ const env4 = result.envs.find((e) => e.name.toLowerCase() === name || e.slug === name);
82317
+ if (!env4) {
82318
+ error(`Environment "${name}" not found`);
82319
+ info(`Available: ${result.envs.map((e) => e.name).join(", ")}`);
82320
+ return;
82321
+ }
82322
+ environmentIds.push(env4.id);
82323
+ }
82324
+ } else {
82325
+ const selected = await promptCheckbox({
82326
+ message: "Push to which environments?",
82327
+ choices: result.envs.map((e) => ({
82328
+ name: `${e.name} ${e.is_preview ? "(preview)" : ""}`,
82329
+ value: e.id
82330
+ }))
82331
+ });
82332
+ environmentIds = selected;
82333
+ }
82334
+ let created = 0;
82335
+ let updated = 0;
82336
+ let skipped = 0;
82337
+ for (const [key, value] of Object.entries(variables)) {
82338
+ const existing = result.vars.find((v) => v.key === key);
82339
+ if (existing) {
82340
+ if (options.overwrite) {
82341
+ try {
82342
+ await updateEnvironmentVariable({
82343
+ client,
82344
+ path: { project_id: result.projectId, var_id: existing.id },
82345
+ body: { key, value, environment_ids: environmentIds, include_in_preview: true }
82346
+ });
82347
+ updated++;
82348
+ } catch (e) {
82349
+ warning(`Failed to update ${key}: ${getErrorMessage(e)}`);
82350
+ }
82351
+ } else {
82352
+ skipped++;
82353
+ }
82354
+ } else {
82355
+ try {
82356
+ await createEnvironmentVariable({
82357
+ client,
82358
+ path: { project_id: result.projectId },
82359
+ body: { key, value, environment_ids: environmentIds, include_in_preview: true }
82360
+ });
82361
+ created++;
82362
+ } catch (e) {
82363
+ warning(`Failed to create ${key}: ${getErrorMessage(e)}`);
82364
+ }
82365
+ }
82366
+ }
82367
+ newline();
82368
+ success(`Push complete: ${created} created, ${updated} updated, ${skipped} skipped`);
82369
+ if (skipped > 0 && !options.overwrite) {
82370
+ info(`Use ${colors.bold("--overwrite")} to update existing variables`);
82371
+ }
82372
+ }
82373
+ function parseEnvFile2(content) {
82374
+ const variables = {};
82375
+ for (const line of content.split(`
82376
+ `)) {
82377
+ const trimmed = line.trim();
82378
+ if (!trimmed || trimmed.startsWith("#"))
82379
+ continue;
82380
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
82381
+ if (!match)
82382
+ continue;
82383
+ const [, key, rawValue] = match;
82384
+ if (!key || rawValue === undefined)
82385
+ continue;
82386
+ let value = rawValue.trim();
82387
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
82388
+ value = value.slice(1, -1).replace(/\\n/g, `
82389
+ `).replace(/\\"/g, '"').replace(/\\'/g, "'");
82390
+ }
82391
+ variables[key.trim()] = value;
82392
+ }
82393
+ return variables;
82394
+ }
82395
+ function registerEnvSyncCommands(program2) {
82396
+ program2.command("env:pull [file]").description("Pull environment variables to a .env file").option("-e, --environment <name>", "Pull from specific environment").option("-p, --project <project>", "Project slug").action(pull);
82397
+ program2.command("env:push [file]").description("Push environment variables from a .env file").option("-e, --environment <names>", "Comma-separated environment names").option("-p, --project <project>", "Project slug").option("--overwrite", "Overwrite existing variables").action(push);
82398
+ }
82399
+
82400
+ // src/commands/rollback/index.ts
82401
+ async function rollback2(projectArg, options) {
82402
+ const resolved = await requireProjectSlug(projectArg ?? options.project);
82403
+ if (resolved.source !== "flag") {
82404
+ newline();
82405
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
82406
+ }
82407
+ await rollback({
82408
+ project: resolved.slug,
82409
+ environment: options.environment ?? "production",
82410
+ to: options.to
82411
+ });
82412
+ }
82413
+ function registerRollbackCommand(program2) {
82414
+ program2.command("rollback [project]").description("Rollback to a previous deployment").option("-p, --project <project>", "Project slug").option("-e, --environment <env>", "Target environment", "production").option("--to <id>", "Rollback to specific deployment ID").option("-y, --yes", "Skip confirmation").action((projectArg, opts) => {
82415
+ if (projectArg && !opts.project) {
82416
+ opts.project = projectArg;
82417
+ }
82418
+ return rollback2(projectArg, opts);
82419
+ });
82420
+ }
82421
+
82422
+ // src/commands/open/index.ts
82423
+ import { execSync as execSync2 } from "node:child_process";
82424
+ function openUrl(url) {
82425
+ const platform2 = process.platform;
82426
+ try {
82427
+ if (platform2 === "darwin") {
82428
+ execSync2(`open "${url}"`);
82429
+ } else if (platform2 === "win32") {
82430
+ execSync2(`start "" "${url}"`);
82431
+ } else {
82432
+ execSync2(`xdg-open "${url}"`);
82433
+ }
82434
+ } catch {
82435
+ info(`Open in browser: ${colors.primary(url)}`);
82436
+ }
82437
+ }
82438
+ async function open(projectArg, options) {
82439
+ await requireAuth();
82440
+ await setupClient();
82441
+ const resolved = await requireProjectSlug(projectArg ?? options.project);
82442
+ if (resolved.source !== "flag") {
82443
+ newline();
82444
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
82445
+ }
82446
+ if (options.dashboard) {
82447
+ const apiUrl = config.get("apiUrl");
82448
+ const dashboardUrl = `${apiUrl}/dashboard/projects/${resolved.slug}`;
82449
+ success(`Opening dashboard for ${resolved.slug}`);
82450
+ openUrl(dashboardUrl);
82451
+ return;
82452
+ }
82453
+ const result = await withSpinner("Fetching project info...", async () => {
82454
+ const { data: project, error: projectError } = await getProjectBySlug({
82455
+ client,
82456
+ path: { slug: resolved.slug }
82457
+ });
82458
+ if (projectError || !project) {
82459
+ throw new Error(`Project "${resolved.slug}" not found`);
82460
+ }
82461
+ const { data: environments, error: envsError } = await getEnvironments({
82462
+ client,
82463
+ path: { project_id: project.id }
82464
+ });
82465
+ if (envsError) {
82466
+ throw new Error(getErrorMessage(envsError));
82467
+ }
82468
+ return { project, environments: environments ?? [] };
82469
+ });
82470
+ if (result.environments.length === 0) {
82471
+ error("No environments found for this project");
82472
+ return;
82473
+ }
82474
+ let targetEnv;
82475
+ if (options.environment) {
82476
+ targetEnv = result.environments.find((e) => e.name.toLowerCase() === options.environment.toLowerCase() || e.slug === options.environment);
82477
+ if (!targetEnv) {
82478
+ error(`Environment "${options.environment}" not found`);
82479
+ info(`Available: ${result.environments.map((e) => e.name).join(", ")}`);
82480
+ return;
82481
+ }
82482
+ } else if (result.environments.length > 1) {
82483
+ const envName = await promptSelect({
82484
+ message: "Open which environment?",
82485
+ choices: result.environments.map((e) => ({
82486
+ name: `${e.name} ${e.is_preview ? "(preview)" : ""} - ${e.main_url}`,
82487
+ value: e.name
82488
+ }))
82489
+ });
82490
+ targetEnv = result.environments.find((e) => e.name === envName);
82491
+ } else {
82492
+ targetEnv = result.environments[0];
82493
+ }
82494
+ if (!targetEnv) {
82495
+ error("Could not determine environment");
82496
+ return;
82497
+ }
82498
+ if (!targetEnv.main_url) {
82499
+ error(`No URL configured for environment "${targetEnv.name}"`);
82500
+ info("Deploy the project first to get a URL");
82501
+ return;
82502
+ }
82503
+ const url = targetEnv.main_url.startsWith("http") ? targetEnv.main_url : `https://${targetEnv.main_url}`;
82504
+ success(`Opening ${targetEnv.name}: ${colors.primary(url)}`);
82505
+ openUrl(url);
82506
+ }
82507
+ function registerOpenCommand(program2) {
82508
+ program2.command("open [project]").description("Open project URL in browser").option("-p, --project <project>", "Project slug").option("-e, --environment <env>", "Open specific environment").option("--dashboard", "Open the dashboard instead of the project URL").action((projectArg, opts) => {
82509
+ if (projectArg && !opts.project) {
82510
+ opts.project = projectArg;
82511
+ }
82512
+ return open(projectArg, opts);
82513
+ });
82514
+ }
82515
+
82516
+ // src/commands/exec/index.ts
82517
+ async function exec2(_command, options) {
82518
+ await requireAuth();
82519
+ await setupClient();
82520
+ const resolved = await requireProjectSlug(options.project);
82521
+ if (resolved.source !== "flag") {
82522
+ newline();
82523
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
82524
+ }
82525
+ newline();
82526
+ header(`${icons.warning} Remote Execution Not Yet Available`);
82527
+ newline();
82528
+ info("Remote command execution requires a server-side agent that is not yet implemented.");
82529
+ newline();
82530
+ info(`${colors.bold("Alternatives:")}`);
82531
+ info(` ${colors.muted("1.")} SSH into your server directly`);
82532
+ info(` ${colors.muted("2.")} Use the dashboard to view container details`);
82533
+ info(` ${colors.muted("3.")} Check container logs: ${colors.bold("temps containers logs <id>")}`);
82534
+ try {
82535
+ const containers = await withSpinner("Fetching containers...", async () => {
82536
+ const { data: project, error: projectError } = await getProjectBySlug({
82537
+ client,
82538
+ path: { slug: resolved.slug }
82539
+ });
82540
+ if (projectError || !project) {
82541
+ throw new Error(`Project "${resolved.slug}" not found`);
82542
+ }
82543
+ const { data: environments, error: envsError } = await getEnvironments({
82544
+ client,
82545
+ path: { project_id: project.id }
82546
+ });
82547
+ if (envsError || !environments || environments.length === 0)
82548
+ return [];
82549
+ const targetEnv = options.environment ? environments.find((e) => e.name.toLowerCase() === options.environment.toLowerCase() || e.slug === options.environment) : environments[0];
82550
+ if (!targetEnv)
82551
+ return [];
82552
+ const { data, error: error3 } = await listContainers({
82553
+ client,
82554
+ path: { project_id: project.id, environment_id: targetEnv.id }
82555
+ });
82556
+ if (error3)
82557
+ throw new Error(getErrorMessage(error3));
82558
+ return data?.containers ?? [];
82559
+ });
82560
+ if (containers.length > 0) {
82561
+ newline();
82562
+ info(`${colors.bold("Running containers:")}`);
82563
+ for (const container of containers) {
82564
+ const containerStatus = container.status === "running" ? colors.success("running") : colors.warning(container.status);
82565
+ info(` ${colors.muted("●")} ${container.container_name ?? container.container_id} (${containerStatus})`);
82566
+ }
82567
+ }
82568
+ } catch {}
82569
+ newline();
82570
+ warning("This feature will be available in a future release.");
82571
+ }
82572
+ function registerExecCommands(program2) {
82573
+ program2.command("exec [command]").alias("ssh").description("Execute a command in a running container (coming soon)").option("-p, --project <project>", "Project slug").option("-e, --environment <env>", "Target environment").action(exec2);
82574
+ }
82575
+
82576
+ // src/commands/dev/index.ts
82577
+ async function dev() {
82578
+ newline();
82579
+ header(`${icons.warning} Dev Mode Coming Soon`);
82580
+ newline();
82581
+ info("The dev command will provide a local development tunnel,");
82582
+ info("allowing you to expose your local server to the internet");
82583
+ info("for testing webhooks, OAuth callbacks, and more.");
82584
+ newline();
82585
+ info(`${colors.bold("In the meantime, you can:")}`);
82586
+ info(` ${colors.muted("1.")} Deploy preview environments: ${colors.bold("temps up -e preview")}`);
82587
+ info(` ${colors.muted("2.")} Use environment variables locally: ${colors.bold("temps env:pull")}`);
82588
+ info(` ${colors.muted("3.")} Check project status: ${colors.bold("temps status")}`);
82589
+ newline();
82590
+ warning("This feature will be available in a future release.");
82591
+ }
82592
+ function registerDevCommand(program2) {
82593
+ program2.command("dev").description("Start a local development tunnel (coming soon)").option("-p, --project <project>", "Project slug").option("--port <port>", "Local port to expose", "3000").action(dev);
82594
+ }
82595
+
82596
+ // src/commands/cloud/index.ts
82597
+ import { execSync as execSync4 } from "node:child_process";
82598
+
82599
+ // src/lib/cloud-client.ts
82600
+ var CLOUD_URL = process.env.TEMPS_CLOUD_URL ?? "https://temps.sh";
82601
+ function getCloudUrl() {
82602
+ return CLOUD_URL;
82603
+ }
82604
+ async function requireCloudAuth() {
82605
+ const envToken = process.env.TEMPS_CLOUD_TOKEN || process.env.TEMPS_CLOUD_API_KEY;
82606
+ if (envToken) {
82607
+ return envToken;
82608
+ }
82609
+ const key = await credentials.get("cloudApiKey");
82610
+ if (!key) {
82611
+ console.error(colors.error("Not logged in to Temps Cloud. Run: temps cloud login"));
82612
+ process.exit(1);
82613
+ }
82614
+ return key;
82615
+ }
82616
+ async function isCloudAuthenticated() {
82617
+ const envToken = process.env.TEMPS_CLOUD_TOKEN || process.env.TEMPS_CLOUD_API_KEY;
82618
+ if (envToken)
82619
+ return true;
82620
+ const key = await credentials.get("cloudApiKey");
82621
+ return !!key;
82622
+ }
82623
+ async function cloudFetch(path7, options) {
82624
+ const apiKey = await requireCloudAuth();
82625
+ const response = await fetch(`${CLOUD_URL}${path7}`, {
82626
+ ...options,
82627
+ headers: {
82628
+ Authorization: `Bearer ${apiKey}`,
82629
+ "Content-Type": "application/json",
82630
+ ...options?.headers
82631
+ }
82632
+ });
82633
+ if (!response.ok) {
82634
+ const body = await response.json().catch(() => ({}));
82635
+ const message = body.error || body.error_description || body.detail || body.message || `Request failed (${response.status})`;
82636
+ throw new Error(message);
82637
+ }
82638
+ const text = await response.text();
82639
+ if (!text)
82640
+ return;
82641
+ return JSON.parse(text);
82642
+ }
82643
+ async function cloudFetchPublic(path7) {
82644
+ const response = await fetch(`${CLOUD_URL}${path7}`, {
82645
+ headers: { "Content-Type": "application/json" }
82646
+ });
82647
+ if (!response.ok) {
82648
+ const body = await response.json().catch(() => ({}));
82649
+ const message = body.error || body.detail || `Request failed (${response.status})`;
82650
+ throw new Error(message);
82651
+ }
82652
+ return response.json();
82653
+ }
82654
+
82655
+ // src/commands/cloud/vps.ts
82656
+ function vpsStatusBadge(status3) {
82657
+ const statusMap = {
82658
+ provisioning: source_default.yellow,
82659
+ installing: source_default.yellow,
82660
+ stalling: source_default.yellow,
82661
+ destroying: source_default.yellow,
82662
+ active: source_default.green,
82663
+ error: source_default.red,
82664
+ destroyed: source_default.gray
82665
+ };
82666
+ const colorFn = statusMap[status3.toLowerCase()] ?? source_default.white;
82667
+ return colorFn(`● ${status3}`);
82668
+ }
82669
+ function formatPrice(cents) {
82670
+ if (cents === 0)
82671
+ return colors.success("free");
82672
+ return `€${(cents / 100).toFixed(2)}/mo`;
82673
+ }
82674
+ async function vpsList(options) {
82675
+ const data = await withSpinner("Fetching VPS instances...", () => cloudFetch("/api/vps"));
82676
+ const instances2 = data.instances ?? [];
82677
+ if (options.json) {
82678
+ json(instances2);
82679
+ return;
82680
+ }
82681
+ newline();
82682
+ header(`${icons.rocket} VPS Instances (${instances2.length})`);
82683
+ const columns = [
82684
+ { header: "ID", key: "id" },
82685
+ { header: "Hostname", key: "hostname", color: (v) => colors.bold(v) },
82686
+ { header: "Status", accessor: (i) => i.status, color: (v) => vpsStatusBadge(v) },
82687
+ { header: "IPv4", key: "ipv4" },
82688
+ { header: "Type", key: "serverType" },
82689
+ { header: "Price", accessor: (i) => formatPrice(i.monthlyPriceCents) }
82690
+ ];
82691
+ printTable(instances2, columns, { style: "minimal" });
82692
+ newline();
82693
+ }
82694
+ async function vpsCreate(options) {
82695
+ let imageId = options.image;
82696
+ let locationId = options.location;
82697
+ let serverTypeId = options.type;
82698
+ if (!imageId) {
82699
+ const data = await withSpinner("Fetching available images...", () => cloudFetchPublic("/api/vps/images"));
82700
+ const images = (data.images ?? []).filter((i) => !i.deprecated);
82701
+ imageId = await promptSelect({
82702
+ message: "Select an OS image",
82703
+ choices: images.map((img) => ({
82704
+ name: `${img.name}${img.description ? ` — ${img.description}` : ""}`,
82705
+ value: img.id
82706
+ }))
82707
+ });
82708
+ }
82709
+ if (!locationId) {
82710
+ const data = await withSpinner("Fetching locations...", () => cloudFetchPublic("/api/vps/locations"));
82711
+ const locations = data.locations ?? [];
82712
+ locationId = await promptSelect({
82713
+ message: "Select a datacenter location",
82714
+ choices: locations.map((loc) => ({
82715
+ name: `${loc.name} — ${loc.city}, ${loc.country}`,
82716
+ value: loc.id,
82717
+ description: loc.description
82718
+ }))
82719
+ });
82720
+ }
82721
+ if (!serverTypeId) {
82722
+ const data = await withSpinner("Fetching server types...", () => cloudFetchPublic(`/api/vps/server-types?location=${locationId}`));
82723
+ const types = (data.serverTypes ?? []).filter((t) => t.available);
82724
+ serverTypeId = await promptSelect({
82725
+ message: "Select a server type",
82726
+ choices: types.map((t) => ({
82727
+ name: `${t.name} — ${t.cores} vCPU, ${t.memory}GB RAM, ${t.disk}GB disk — ${formatPrice(t.monthlyPriceCents)}`,
82728
+ value: t.id
82729
+ }))
82730
+ });
82731
+ }
82732
+ const result = await withSpinner("Provisioning VPS...", () => cloudFetch("/api/vps", {
82733
+ method: "POST",
82734
+ body: JSON.stringify({
82735
+ serverType: serverTypeId,
82736
+ image: imageId,
82737
+ location: locationId
82738
+ })
82739
+ }));
82740
+ if (options.json) {
82741
+ json(result);
82742
+ return;
82743
+ }
82744
+ newline();
82745
+ box(`Instance: ${colors.bold(result.instanceId)}
82746
+ ` + `Hostname: ${colors.bold(result.hostname)}
82747
+
82748
+ ` + `${result.message}`, `${icons.rocket} VPS Provisioning Started`);
82749
+ newline();
82750
+ info(`Track progress: ${colors.muted(`temps cloud vps show ${result.instanceId}`)}`);
82751
+ newline();
82752
+ }
82753
+ async function vpsShow(id, options) {
82754
+ const data = await withSpinner("Fetching VPS details...", () => cloudFetch(`/api/vps/${id}`));
82755
+ let creds = null;
82756
+ if (data.instance.status === "active") {
82757
+ try {
82758
+ creds = await withSpinner("Fetching credentials...", () => cloudFetch(`/api/vps/${id}/credentials`));
82759
+ } catch {}
82760
+ }
82761
+ if (options.json) {
82762
+ json({ ...data, credentials: creds });
82763
+ return;
82764
+ }
82765
+ const inst = data.instance;
82766
+ newline();
82767
+ header(`${icons.rocket} VPS: ${inst.hostname}`);
82768
+ keyValue("ID", inst.id);
82769
+ keyValue("Hostname", inst.hostname);
82770
+ keyValue("Status", vpsStatusBadge(inst.status));
82771
+ keyValue("IPv4", inst.ipv4 || "pending");
82772
+ keyValue("Type", inst.serverType);
82773
+ keyValue("Price", formatPrice(inst.monthlyPriceCents));
82774
+ if (inst.webPanelUrl) {
82775
+ keyValue("Panel", inst.webPanelUrl);
82776
+ }
82777
+ if (creds) {
82778
+ newline();
82779
+ header(`${icons.key} Credentials`);
82780
+ keyValue("Panel URL", creds.webPanelUrl);
82781
+ keyValue("Username", creds.credentials.username);
82782
+ keyValue("Password", creds.credentials.password);
82783
+ if (creds.apiKey) {
82784
+ keyValue("API Key", creds.apiKey);
82785
+ }
82786
+ }
82787
+ if (data.serverSpecs) {
82788
+ newline();
82789
+ header("Server Specs");
82790
+ keyValue("vCPU", data.serverSpecs.cores);
82791
+ keyValue("Memory", `${data.serverSpecs.memory} GB`);
82792
+ keyValue("Disk", `${data.serverSpecs.disk} GB`);
82793
+ }
82794
+ if (data.logs && data.logs.length > 0) {
82795
+ newline();
82796
+ header("Provisioning Logs");
82797
+ const logColumns = [
82798
+ { header: "Phase", key: "phase" },
82799
+ { header: "Step", key: "step" },
82800
+ {
82801
+ header: "Status",
82802
+ key: "status",
82803
+ color: (v) => statusBadge(v)
82804
+ },
82805
+ { header: "Message", key: "message" }
82806
+ ];
82807
+ printTable(data.logs, logColumns, { style: "minimal" });
82808
+ }
82809
+ newline();
82810
+ }
82811
+ async function vpsDestroy(id) {
82812
+ const confirmed = await promptConfirm({
82813
+ message: `Are you sure you want to destroy VPS ${colors.bold(id)}? This cannot be undone.`,
82814
+ default: false
82815
+ });
82816
+ if (!confirmed) {
82817
+ info("Cancelled.");
82818
+ return;
82819
+ }
82820
+ await withSpinner("Destroying VPS...", () => cloudFetch(`/api/vps/${id}`, { method: "DELETE" }));
82821
+ newline();
82822
+ info(`VPS ${colors.bold(id)} destruction initiated.`);
82823
+ newline();
82824
+ }
82825
+ async function vpsRetry(id) {
82826
+ const result = await withSpinner("Retrying provisioning...", () => cloudFetch(`/api/vps/${id}/retry`, { method: "POST" }));
82827
+ newline();
82828
+ info(result.message || "Provisioning retry initiated.");
82829
+ newline();
82830
+ }
82831
+ async function vpsCredentials(id, options) {
82832
+ const data = await withSpinner("Fetching credentials...", () => cloudFetch(`/api/vps/${id}/credentials`));
82833
+ if (options.json) {
82834
+ json(data);
82835
+ return;
82836
+ }
82837
+ newline();
82838
+ header(`${icons.key} VPS Credentials`);
82839
+ keyValue("Panel URL", data.webPanelUrl);
82840
+ keyValue("Username", data.credentials.username);
82841
+ keyValue("Password", data.credentials.password);
82842
+ if (data.apiKey) {
82843
+ keyValue("API Key", data.apiKey);
82844
+ }
82845
+ newline();
82846
+ info(colors.warning("Store these credentials securely. They will not be shown again."));
82847
+ newline();
82848
+ }
82849
+ async function vpsImages(options) {
82850
+ const data = await withSpinner("Fetching images...", () => cloudFetchPublic("/api/vps/images"));
82851
+ const images = data.images ?? [];
82852
+ if (options.json) {
82853
+ json(images);
82854
+ return;
82855
+ }
82856
+ newline();
82857
+ header(`${icons.package} Available OS Images (${images.length})`);
82858
+ const columns = [
82859
+ { header: "ID", key: "id" },
82860
+ { header: "Name", key: "name", color: (v) => colors.bold(v) },
82861
+ { header: "Description", key: "description" },
82862
+ {
82863
+ header: "Status",
82864
+ accessor: (i) => i.deprecated ? "deprecated" : "available",
82865
+ color: (v, i) => i.deprecated ? colors.muted(v) : colors.success(v)
82866
+ }
82867
+ ];
82868
+ printTable(images, columns, { style: "minimal" });
82869
+ newline();
82870
+ }
82871
+ async function vpsLocations(options) {
82872
+ const data = await withSpinner("Fetching locations...", () => cloudFetchPublic("/api/vps/locations"));
82873
+ const locations = data.locations ?? [];
82874
+ if (options.json) {
82875
+ json(locations);
82876
+ return;
82877
+ }
82878
+ newline();
82879
+ header(`${icons.globe} Available Locations (${locations.length})`);
82880
+ const columns = [
82881
+ { header: "ID", key: "id" },
82882
+ { header: "Name", key: "name", color: (v) => colors.bold(v) },
82883
+ { header: "City", key: "city" },
82884
+ { header: "Country", key: "country" },
82885
+ { header: "Description", key: "description" }
82886
+ ];
82887
+ printTable(locations, columns, { style: "minimal" });
82888
+ newline();
82889
+ }
82890
+ async function vpsTypes(options) {
82891
+ const query = options.location ? `?location=${options.location}` : "";
82892
+ const data = await withSpinner("Fetching server types...", () => cloudFetchPublic(`/api/vps/server-types${query}`));
82893
+ const types = data.serverTypes ?? [];
82894
+ if (options.json) {
82895
+ json(types);
82896
+ return;
82897
+ }
82898
+ newline();
82899
+ const suffix = options.location ? ` for ${options.location}` : "";
82900
+ header(`Server Types${suffix} (${types.length})`);
82901
+ const columns = [
82902
+ { header: "ID", key: "id" },
82903
+ { header: "Name", key: "name", color: (v) => colors.bold(v) },
82904
+ { header: "vCPU", key: "cores", align: "right" },
82905
+ { header: "Memory (GB)", key: "memory", align: "right" },
82906
+ { header: "Disk (GB)", key: "disk", align: "right" },
82907
+ { header: "Price", accessor: (t) => formatPrice(t.monthlyPriceCents), align: "right" },
82908
+ {
82909
+ header: "Available",
82910
+ accessor: (t) => t.available ? "yes" : "no",
82911
+ color: (v, t) => t.available ? colors.success(v) : colors.muted(v)
82912
+ }
82913
+ ];
82914
+ printTable(types, columns, { style: "minimal" });
82915
+ newline();
82916
+ }
82917
+ function registerCloudVpsCommands(cloud) {
82918
+ const vps = cloud.command("vps").description("Manage cloud VPS instances");
82919
+ vps.command("list").description("List VPS instances").option("--json", "Output as JSON").action(vpsList);
82920
+ vps.command("create").description("Provision a new VPS instance").option("--image <image>", "OS image ID").option("--location <location>", "Datacenter location ID").option("--type <type>", "Server type ID").option("--json", "Output as JSON").action(vpsCreate);
82921
+ vps.command("show <id>").description("Show VPS instance details and provisioning logs").option("--json", "Output as JSON").action(vpsShow);
82922
+ vps.command("destroy <id>").description("Destroy a VPS instance").action(vpsDestroy);
82923
+ vps.command("retry <id>").description("Retry failed VPS provisioning").action(vpsRetry);
82924
+ vps.command("credentials <id>").description("Show VPS panel credentials").option("--json", "Output as JSON").action(vpsCredentials);
82925
+ vps.command("images").description("List available OS images").option("--json", "Output as JSON").action(vpsImages);
82926
+ vps.command("locations").description("List available datacenter locations").option("--json", "Output as JSON").action(vpsLocations);
82927
+ vps.command("types").description("List available server types with pricing").option("--location <location>", "Filter by datacenter location").option("--json", "Output as JSON").action(vpsTypes);
82928
+ }
82929
+
82930
+ // src/commands/cloud/billing.ts
82931
+ import { execSync as execSync3 } from "node:child_process";
82932
+ function openBrowser(url) {
82933
+ try {
82934
+ if (process.platform === "darwin") {
82935
+ execSync3(`open "${url}"`);
82936
+ } else if (process.platform === "win32") {
82937
+ execSync3(`start "" "${url}"`);
82938
+ } else {
82939
+ execSync3(`xdg-open "${url}"`);
82940
+ }
82941
+ } catch {}
82942
+ }
82943
+ function formatPrice2(cents) {
82944
+ if (cents === 0)
82945
+ return colors.success("free");
82946
+ return `€${(cents / 100).toFixed(2)}/mo`;
82947
+ }
82948
+ function usageBar(used, limit) {
82949
+ const pct = limit > 0 ? Math.min(used / limit, 1) : 0;
82950
+ const width = 20;
82951
+ const filled = Math.round(pct * width);
82952
+ const empty = width - filled;
82953
+ const bar = "█".repeat(filled) + "░".repeat(empty);
82954
+ const colorFn = pct >= 0.9 ? colors.error : pct >= 0.7 ? colors.warning : colors.success;
82955
+ return `${colorFn(bar)} ${used}/${limit}`;
82956
+ }
82957
+ async function billingOverview(options) {
82958
+ const data = await withSpinner("Fetching billing info...", () => cloudFetch("/api/billing/overview"));
82959
+ if (options.json) {
82960
+ json(data);
82961
+ return;
82962
+ }
82963
+ newline();
82964
+ header(`${icons.star} Billing Overview`);
82965
+ keyValue("Plan", colors.bold(data.plan));
82966
+ keyValue("Status", data.status);
82967
+ if (data.monthlyPriceCents !== undefined) {
82968
+ keyValue("Price", formatPrice2(data.monthlyPriceCents));
82969
+ }
82970
+ if (data.currentPeriodStart) {
82971
+ keyValue("Period Start", data.currentPeriodStart);
82972
+ }
82973
+ if (data.currentPeriodEnd) {
82974
+ keyValue("Period End", data.currentPeriodEnd);
82975
+ }
82976
+ if (data.hasPaymentMethod !== undefined) {
82977
+ keyValue("Payment Method", data.hasPaymentMethod ? "on file" : "none");
82978
+ }
82979
+ newline();
82980
+ }
82981
+ async function billingUsage(options) {
82982
+ const data = await withSpinner("Fetching usage...", () => cloudFetch("/api/billing/usage"));
82983
+ if (options.json) {
82984
+ json(data);
82985
+ return;
82986
+ }
82987
+ newline();
82988
+ header("Usage");
82989
+ if (data.vpsLimit !== undefined) {
82990
+ keyValue("VPS", usageBar(data.vpsCount ?? 0, data.vpsLimit));
82991
+ }
82992
+ if (data.serversLimit !== undefined) {
82993
+ keyValue("Servers", usageBar(data.serversCount ?? 0, data.serversLimit));
82994
+ }
82995
+ if (data.tunnelsLimit !== undefined) {
82996
+ keyValue("Tunnels", usageBar(data.tunnelsCount ?? 0, data.tunnelsLimit));
82997
+ }
82998
+ newline();
82999
+ }
83000
+ async function billingUpgrade(options) {
83001
+ const billingCycle = options.yearly ? "yearly" : "monthly";
83002
+ const data = await withSpinner("Creating checkout session...", () => cloudFetch("/api/billing/checkout", {
83003
+ method: "POST",
83004
+ body: JSON.stringify({ plan: "app", billingCycle })
83005
+ }));
83006
+ newline();
83007
+ box(`Complete your upgrade at:
83008
+
83009
+ ${colors.primary(data.url)}`, `${icons.star} Upgrade to Pro`);
83010
+ newline();
83011
+ if (!options.noBrowser) {
83012
+ info("Opening browser...");
83013
+ openBrowser(data.url);
83014
+ }
83015
+ }
83016
+ function registerCloudBillingCommands(cloud) {
83017
+ const billing = cloud.command("billing").description("Manage Temps Cloud billing and subscription");
83018
+ billing.command("overview").description("Show billing overview").option("--json", "Output as JSON").action(billingOverview);
83019
+ billing.command("usage").description("Show usage and limits").option("--json", "Output as JSON").action(billingUsage);
83020
+ billing.command("upgrade").description("Upgrade your plan").option("--yearly", "Use yearly billing cycle (default: monthly)").option("--no-browser", "Don't open browser, just show the URL").action(billingUpgrade);
83021
+ }
83022
+
83023
+ // src/commands/cloud/index.ts
83024
+ function openBrowser2(url) {
83025
+ try {
83026
+ if (process.platform === "darwin") {
83027
+ execSync4(`open "${url}"`);
83028
+ } else if (process.platform === "win32") {
83029
+ execSync4(`start "" "${url}"`);
83030
+ } else {
83031
+ execSync4(`xdg-open "${url}"`);
83032
+ }
83033
+ } catch {}
83034
+ }
83035
+ function sleep(ms) {
83036
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
83037
+ }
83038
+ async function cloudLogin() {
83039
+ const cloudUrl = getCloudUrl();
83040
+ newline();
83041
+ info(`Connecting to Temps Cloud at ${colors.primary(cloudUrl)}`);
83042
+ newline();
83043
+ startSpinner("Requesting authorization...");
83044
+ let deviceCode;
83045
+ try {
83046
+ const response = await fetch(`${cloudUrl}/api/auth/device`, {
83047
+ method: "POST",
83048
+ headers: { "Content-Type": "application/json" },
83049
+ body: JSON.stringify({ client_name: "Temps CLI" })
83050
+ });
83051
+ if (!response.ok) {
83052
+ throw new Error(`Failed to start device authorization (${response.status})`);
83053
+ }
83054
+ deviceCode = await response.json();
83055
+ succeedSpinner("Authorization started");
83056
+ } catch (err) {
83057
+ failSpinner("Failed to connect to Temps Cloud");
83058
+ throw err;
83059
+ }
83060
+ newline();
83061
+ box(`Your code: ${colors.bold(deviceCode.user_code)}
83062
+
83063
+ ` + `Opening ${colors.primary(deviceCode.verification_uri_complete)}
83064
+ ` + `in your browser...`, `${icons.globe} Authorize Temps CLI`);
83065
+ newline();
83066
+ openBrowser2(deviceCode.verification_uri_complete);
83067
+ info(`If the browser didn't open, visit: ${colors.primary(deviceCode.verification_uri)}`);
83068
+ info(`and enter code: ${colors.bold(deviceCode.user_code)}`);
83069
+ newline();
83070
+ startSpinner("Waiting for authorization...");
83071
+ const interval = (deviceCode.interval || 5) * 1000;
83072
+ const deadline = Date.now() + deviceCode.expires_in * 1000;
83073
+ let accessToken = null;
83074
+ while (Date.now() < deadline) {
83075
+ await sleep(interval);
83076
+ try {
83077
+ const response = await fetch(`${cloudUrl}/api/auth/device/token`, {
83078
+ method: "POST",
83079
+ headers: { "Content-Type": "application/json" },
83080
+ body: JSON.stringify({ device_code: deviceCode.device_code })
83081
+ });
83082
+ if (response.ok) {
83083
+ const data = await response.json();
83084
+ accessToken = data.access_token;
83085
+ break;
83086
+ }
83087
+ const body = await response.json();
83088
+ if (body.error === "authorization_pending") {
83089
+ updateSpinner("Waiting for authorization...");
83090
+ continue;
83091
+ }
83092
+ if (body.error === "access_denied") {
83093
+ failSpinner("Authorization denied");
83094
+ error("You denied the authorization request.");
83095
+ return;
83096
+ }
83097
+ if (body.error === "expired_token") {
83098
+ failSpinner("Authorization expired");
83099
+ error('The authorization code expired. Run "temps cloud login" again.');
83100
+ return;
83101
+ }
83102
+ continue;
83103
+ } catch {
83104
+ continue;
83105
+ }
83106
+ }
83107
+ if (!accessToken) {
83108
+ failSpinner("Authorization timed out");
83109
+ error('The authorization code expired. Run "temps cloud login" again.');
83110
+ return;
83111
+ }
83112
+ succeedSpinner("Authorized");
83113
+ startSpinner("Fetching account info...");
83114
+ let profile;
83115
+ try {
83116
+ const response = await fetch(`${cloudUrl}/api/user`, {
83117
+ headers: { Authorization: `Bearer ${accessToken}` }
83118
+ });
83119
+ if (!response.ok) {
83120
+ throw new Error(`Failed to fetch user profile (${response.status})`);
83121
+ }
83122
+ profile = await response.json();
83123
+ succeedSpinner(`Logged in as ${profile.email ?? profile.username}`);
83124
+ } catch (err) {
83125
+ failSpinner("Failed to fetch account");
83126
+ throw err;
83127
+ }
83128
+ await credentials.set("cloudApiKey", accessToken);
83129
+ newline();
83130
+ box(`Logged in as ${colors.bold(profile.email ?? profile.username)}
83131
+ ` + `API: ${colors.muted(cloudUrl)}`, `${icons.sparkles} Welcome to Temps Cloud!`);
83132
+ }
83133
+ async function cloudLogout() {
83134
+ const authenticated = await isCloudAuthenticated();
83135
+ if (!authenticated) {
83136
+ info("Not logged in to Temps Cloud.");
83137
+ return;
83138
+ }
83139
+ await credentials.set("cloudApiKey", undefined);
83140
+ newline();
83141
+ info("Logged out of Temps Cloud.");
83142
+ }
83143
+ async function cloudWhoami() {
83144
+ const profile = await cloudFetch("/api/user");
83145
+ newline();
83146
+ header(`${icons.globe} Temps Cloud Account`);
83147
+ keyValue("ID", profile.id);
83148
+ keyValue("Name", profile.name);
83149
+ keyValue("Username", profile.username);
83150
+ keyValue("Email", profile.email ?? "not set");
83151
+ if (profile.plan) {
83152
+ keyValue("Plan", profile.plan);
83153
+ }
83154
+ newline();
83155
+ }
83156
+ function registerCloudCommands(program2) {
83157
+ const cloud = program2.command("cloud").description("Temps Cloud");
83158
+ cloud.command("login").description("Login to Temps Cloud").action(cloudLogin);
83159
+ cloud.command("logout").description("Logout from Temps Cloud").action(cloudLogout);
83160
+ cloud.command("whoami").description("Show current Temps Cloud account").action(cloudWhoami);
83161
+ registerCloudVpsCommands(cloud);
83162
+ registerCloudBillingCommands(cloud);
83163
+ }
83164
+
81263
83165
  // src/cli.ts
81264
83166
  var require2 = createRequire2(import.meta.url);
81265
83167
  var pkg = require2("../package.json");
@@ -81321,16 +83223,34 @@ function createProgram() {
81321
83223
  registerPresetsCommands(program2);
81322
83224
  registerFunnelsCommands(program2);
81323
83225
  registerNotificationPreferencesCommands(program2);
83226
+ registerInitCommand(program2);
83227
+ registerLinkCommand(program2);
83228
+ registerUpCommand(program2);
83229
+ registerStatusCommand(program2);
83230
+ registerInstancesCommands(program2);
83231
+ registerEnvSyncCommands(program2);
83232
+ registerRollbackCommand(program2);
83233
+ registerOpenCommand(program2);
83234
+ registerExecCommands(program2);
83235
+ registerDevCommand(program2);
83236
+ registerCloudCommands(program2);
81324
83237
  registerDocsCommand(program2);
81325
83238
  program2.addHelpText("beforeAll", LOGO);
81326
83239
  program2.addHelpText("after", `
81327
- ${colors.bold("Examples:")}
83240
+ ${colors.bold("Quick Start:")}
81328
83241
  ${colors.muted("$")} temps login ${colors.muted("# Authenticate with Temps")}
81329
- ${colors.muted("$")} temps configure ${colors.muted("# Configure CLI settings")}
81330
- ${colors.muted("$")} temps projects list ${colors.muted("# List all projects")}
81331
- ${colors.muted("$")} temps deploy my-app ${colors.muted("# Deploy a project")}
81332
- ${colors.muted("$")} temps logs my-app --follow ${colors.muted("# Stream deployment logs")}
81333
- ${colors.muted("$")} temps env vars my-app list ${colors.muted("# List environment variables")}
83242
+ ${colors.muted("$")} temps init ${colors.muted("# Initialize project in current directory")}
83243
+ ${colors.muted("$")} temps up ${colors.muted("# Deploy from current directory")}
83244
+ ${colors.muted("$")} temps status ${colors.muted("# View project status")}
83245
+
83246
+ ${colors.bold("Common Commands:")}
83247
+ ${colors.muted("$")} temps link my-app ${colors.muted("# Link directory to a project")}
83248
+ ${colors.muted("$")} temps open ${colors.muted("# Open project URL in browser")}
83249
+ ${colors.muted("$")} temps rollback ${colors.muted("# Rollback to previous deployment")}
83250
+ ${colors.muted("$")} temps env:pull ${colors.muted("# Pull env vars to .env file")}
83251
+ ${colors.muted("$")} temps env:push ${colors.muted("# Push .env file to project")}
83252
+ ${colors.muted("$")} temps cloud login ${colors.muted("# Connect to Temps Cloud")}
83253
+ ${colors.muted("$")} temps instances list ${colors.muted("# Manage server instances")}
81334
83254
 
81335
83255
  ${colors.bold("Documentation:")}
81336
83256
  ${colors.primary("https://temps.dev/docs")}
@@ -81625,16 +83545,34 @@ function createProgram2() {
81625
83545
  registerPresetsCommands(program2);
81626
83546
  registerFunnelsCommands(program2);
81627
83547
  registerNotificationPreferencesCommands(program2);
83548
+ registerInitCommand(program2);
83549
+ registerLinkCommand(program2);
83550
+ registerUpCommand(program2);
83551
+ registerStatusCommand(program2);
83552
+ registerInstancesCommands(program2);
83553
+ registerEnvSyncCommands(program2);
83554
+ registerRollbackCommand(program2);
83555
+ registerOpenCommand(program2);
83556
+ registerExecCommands(program2);
83557
+ registerDevCommand(program2);
83558
+ registerCloudCommands(program2);
81628
83559
  registerDocsCommand(program2);
81629
83560
  program2.addHelpText("beforeAll", LOGO2);
81630
83561
  program2.addHelpText("after", `
81631
- ${colors.bold("Examples:")}
83562
+ ${colors.bold("Quick Start:")}
81632
83563
  ${colors.muted("$")} temps login ${colors.muted("# Authenticate with Temps")}
81633
- ${colors.muted("$")} temps configure ${colors.muted("# Configure CLI settings")}
81634
- ${colors.muted("$")} temps projects list ${colors.muted("# List all projects")}
81635
- ${colors.muted("$")} temps deploy my-app ${colors.muted("# Deploy a project")}
81636
- ${colors.muted("$")} temps logs my-app --follow ${colors.muted("# Stream deployment logs")}
81637
- ${colors.muted("$")} temps env vars my-app list ${colors.muted("# List environment variables")}
83564
+ ${colors.muted("$")} temps init ${colors.muted("# Initialize project in current directory")}
83565
+ ${colors.muted("$")} temps up ${colors.muted("# Deploy from current directory")}
83566
+ ${colors.muted("$")} temps status ${colors.muted("# View project status")}
83567
+
83568
+ ${colors.bold("Common Commands:")}
83569
+ ${colors.muted("$")} temps link my-app ${colors.muted("# Link directory to a project")}
83570
+ ${colors.muted("$")} temps open ${colors.muted("# Open project URL in browser")}
83571
+ ${colors.muted("$")} temps rollback ${colors.muted("# Rollback to previous deployment")}
83572
+ ${colors.muted("$")} temps env:pull ${colors.muted("# Pull env vars to .env file")}
83573
+ ${colors.muted("$")} temps env:push ${colors.muted("# Push .env file to project")}
83574
+ ${colors.muted("$")} temps cloud login ${colors.muted("# Connect to Temps Cloud")}
83575
+ ${colors.muted("$")} temps instances list ${colors.muted("# Manage server instances")}
81638
83576
 
81639
83577
  ${colors.bold("Documentation:")}
81640
83578
  ${colors.primary("https://temps.dev/docs")}