ezhst 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ import { log } from "../lib/ui.js";
5
5
  export const listApps = async () => {
6
6
  const { apps } = await request("/apps");
7
7
  if (!apps.length) {
8
- log.info("No apps yet. Run `easyhost deploy` inside a Next.js project.");
8
+ log.info("No apps yet. Run `ezhst deploy` inside a Next.js project.");
9
9
  return;
10
10
  }
11
11
  for (const app of apps) {
@@ -34,7 +34,7 @@ export const listEnv = async (options) => {
34
34
  };
35
35
  const saveEnv = async (app, env) => {
36
36
  await request(`/apps/${app.id}/env`, { method: "PUT", body: JSON.stringify({ env }) });
37
- log.success("Environment saved. Run `easyhost redeploy` to apply it.");
37
+ log.success("Environment saved. Run `ezhst redeploy` to apply it.");
38
38
  };
39
39
  export const setEnv = async (pairs, options) => {
40
40
  const app = await resolveApp(options.app);
@@ -1,26 +1,57 @@
1
1
  import { input, password } from "@inquirer/prompts";
2
- import { request } from "../lib/api.js";
2
+ import { json, request } from "../lib/api.js";
3
3
  import { clearConfig, readConfig, writeConfig } from "../lib/config.js";
4
- import { log } from "../lib/ui.js";
4
+ import { log, output, required } from "../lib/ui.js";
5
+ const apiUrlFrom = (api) => (api ?? readConfig().apiUrl).replace(/\/$/, "");
6
+ const askEmail = () => input({ message: "Email" });
7
+ const askPassword = () => password({ message: "Password", mask: "*" });
8
+ const saveSession = (apiUrl, token, user, message) => {
9
+ writeConfig({ apiUrl, token });
10
+ output({ user, token }, () => {
11
+ log.success(`${message} ${user.name} <${user.email}>`);
12
+ if (!user.verified) {
13
+ log.warn("Verify your email address. Check your inbox, or run `ezhst resend-verification`.");
14
+ }
15
+ });
16
+ };
17
+ export const register = async (options) => {
18
+ const apiUrl = apiUrlFrom(options.api);
19
+ writeConfig({ apiUrl });
20
+ const name = await required(options.name, "--name", () => input({ message: "Name" }));
21
+ const email = await required(options.email, "--email", askEmail);
22
+ const secret = await required(options.password, "--password", askPassword);
23
+ const { token, user } = await request("/auth/register", json("POST", { name, email, password: secret }));
24
+ saveSession(apiUrl, token, user, "Account created for");
25
+ };
5
26
  export const login = async (options) => {
6
- const current = readConfig();
7
- const apiUrl = (options.api ?? current.apiUrl).replace(/\/$/, "");
27
+ const apiUrl = apiUrlFrom(options.api);
8
28
  writeConfig({ apiUrl });
9
- const email = await input({ message: "Email" });
10
- const secret = await password({ message: "Password", mask: "*" });
11
- const { token, user } = await request("/auth/login", {
12
- method: "POST",
13
- body: JSON.stringify({ email, password: secret }),
14
- });
15
- writeConfig({ apiUrl, token });
16
- log.success(`Logged in as ${user.name} <${user.email}>`);
29
+ const email = await required(options.email, "--email", askEmail);
30
+ const secret = await required(options.password, "--password", askPassword);
31
+ const { token, user } = await request("/auth/login", json("POST", { email, password: secret }));
32
+ saveSession(apiUrl, token, user, "Logged in as");
17
33
  };
18
34
  export const logout = () => {
19
35
  clearConfig();
20
- log.success("Logged out");
36
+ output({ loggedOut: true }, () => log.success("Logged out"));
21
37
  };
22
38
  export const whoami = async () => {
23
39
  const { user } = await request("/auth/me");
24
- log.info(`${user.name} <${user.email}>`);
25
- log.dim(readConfig().apiUrl);
40
+ const { apiUrl } = readConfig();
41
+ output({ user, apiUrl }, () => {
42
+ log.info(`${user.name} <${user.email}>`);
43
+ if (!user.verified) {
44
+ log.warn("Email not verified");
45
+ }
46
+ log.dim(apiUrl);
47
+ });
48
+ };
49
+ export const resendVerification = async () => {
50
+ const result = await request("/auth/resend-verification", { method: "POST" });
51
+ output(result, () => log.success(result.message));
52
+ };
53
+ export const forgotPassword = async (options) => {
54
+ const email = await required(options.email, "--email", askEmail);
55
+ const result = await request("/auth/forgot-password", json("POST", { email }));
56
+ output(result, () => log.success(result.message));
26
57
  };
@@ -0,0 +1,57 @@
1
+ import { json, request } from "../lib/api.js";
2
+ import { resolveProject } from "../lib/project.js";
3
+ import { log, output } from "../lib/ui.js";
4
+ const settingsOf = (project) => ({
5
+ nodeVersion: project.nodeVersion,
6
+ rootDir: project.rootDir,
7
+ installCommand: project.installCommand,
8
+ buildCommand: project.buildCommand,
9
+ startCommand: project.startCommand,
10
+ });
11
+ const printSettings = (project) => {
12
+ const rows = [
13
+ ["Node.js version", project.nodeVersion],
14
+ ["Root directory", project.rootDir],
15
+ ["Install command", project.installCommand],
16
+ ["Build command", project.buildCommand],
17
+ ["Start command", project.startCommand],
18
+ ];
19
+ for (const [label, value] of rows) {
20
+ log.info(`${label.padEnd(17)} ${value ?? "auto"}`);
21
+ }
22
+ };
23
+ const pick = (value, current) => {
24
+ if (value === undefined) {
25
+ return current ?? "";
26
+ }
27
+ return value;
28
+ };
29
+ const saveSettings = async (project, settings) => {
30
+ const { app } = await request(`/apps/${project.id}/build`, json("PUT", settings));
31
+ output({ build: settingsOf(app) }, () => {
32
+ printSettings(app);
33
+ log.success("Build settings saved. Run `ezhst redeploy` to apply them.");
34
+ });
35
+ };
36
+ export const showBuild = async (options) => {
37
+ const project = await resolveProject(options);
38
+ output({ build: settingsOf(project) }, () => printSettings(project));
39
+ };
40
+ export const setBuild = async (options) => {
41
+ const project = await resolveProject(options);
42
+ let nodeVersion = pick(options.node, project.nodeVersion);
43
+ if (!nodeVersion) {
44
+ nodeVersion = null;
45
+ }
46
+ await saveSettings(project, {
47
+ nodeVersion,
48
+ rootDir: pick(options.rootDir, project.rootDir),
49
+ installCommand: pick(options.install, project.installCommand),
50
+ buildCommand: pick(options.build, project.buildCommand),
51
+ startCommand: pick(options.start, project.startCommand),
52
+ });
53
+ };
54
+ export const resetBuild = async (options) => {
55
+ const project = await resolveProject(options);
56
+ await saveSettings(project, { nodeVersion: null, rootDir: "", installCommand: "", buildCommand: "", startCommand: "" });
57
+ };
@@ -0,0 +1,76 @@
1
+ import { readFileSync } from "node:fs";
2
+ import pc from "picocolors";
3
+ import { json, request } from "../lib/api.js";
4
+ import { resolveProject } from "../lib/project.js";
5
+ import { confirmed, fail, formatBytes, log, output, table } from "../lib/ui.js";
6
+ const findDatabase = async (options) => {
7
+ const project = await resolveProject(options);
8
+ const { databases } = await request("/databases", {}, project.id);
9
+ const database = databases[0];
10
+ if (!database) {
11
+ return fail("This project has no database yet. Create it with `ezhst db create <name>`.");
12
+ }
13
+ return { project, database };
14
+ };
15
+ export const databaseInfo = async (options) => {
16
+ const { project, database } = await findDatabase(options);
17
+ const detail = await request(`/databases/${database.id}`, {}, project.id);
18
+ output(detail, () => {
19
+ const info = detail.database;
20
+ log.info(`${pc.bold(info.name)} ${pc.dim(`(${info.dbName}, ${formatBytes(info.sizeBytes)})`)}`);
21
+ log.info(`DATABASE_URL: ${info.connectionString}`);
22
+ log.info(`SHADOW_DATABASE_URL: ${info.shadowConnectionString}`);
23
+ log.info(`Tables: ${detail.tables.length}`);
24
+ for (const item of detail.tables) {
25
+ log.info(` ${item.name}`);
26
+ }
27
+ });
28
+ };
29
+ export const createDatabase = async (name, options) => {
30
+ const project = await resolveProject(options);
31
+ const { database } = await request("/databases", json("POST", { name }), project.id);
32
+ output({ database }, () => log.success(`Database ${database.name} created. Run \`ezhst db info\` for the connection string.`));
33
+ };
34
+ export const queryDatabase = async (sql, options) => {
35
+ let text = sql;
36
+ if (options.file) {
37
+ text = readFileSync(options.file, "utf8");
38
+ }
39
+ if (!text) {
40
+ return fail("Pass the SQL as an argument or with --file <file.sql>.");
41
+ }
42
+ const { project, database } = await findDatabase(options);
43
+ const { result } = await request(`/databases/${database.id}/query`, json("POST", { sql: text }), project.id);
44
+ output({ result }, () => {
45
+ if (result.columns.length) {
46
+ table(result.rows);
47
+ }
48
+ log.dim(`${result.command} ${result.rowCount ?? 0}`);
49
+ if (result.truncated) {
50
+ log.warn("Output truncated.");
51
+ }
52
+ });
53
+ };
54
+ export const tableRows = async (tableName, options) => {
55
+ const { project, database } = await findDatabase(options);
56
+ const query = new URLSearchParams({ page: options.page ?? "1" });
57
+ const data = await request(`/databases/${database.id}/tables/${encodeURIComponent(tableName)}/rows?${query}`, {}, project.id);
58
+ output(data, () => {
59
+ table(data.rows);
60
+ log.dim(`Page ${data.page}, ${data.total} rows total`);
61
+ });
62
+ };
63
+ export const resetDatabasePassword = async (options) => {
64
+ const { project, database } = await findDatabase(options);
65
+ const result = await request(`/databases/${database.id}/reset-password`, { method: "POST" }, project.id);
66
+ output(result, () => {
67
+ log.success("Password rotated. Update DATABASE_URL in your env and redeploy.");
68
+ log.info(result.connectionString);
69
+ });
70
+ };
71
+ export const deleteDatabase = async (options) => {
72
+ const { project, database } = await findDatabase(options);
73
+ confirmed(options.yes, `Deleting database ${database.name} removes all of its data.`);
74
+ const result = await request(`/databases/${database.id}`, { method: "DELETE" }, project.id);
75
+ output(result, () => log.success("Database deleted"));
76
+ };
@@ -5,8 +5,8 @@ import * as tar from "tar";
5
5
  import pc from "picocolors";
6
6
  import ora from "ora";
7
7
  import { request } from "../lib/api.js";
8
- import { resolveApp } from "../lib/resolve-app.js";
9
- import { fail, log } from "../lib/ui.js";
8
+ import { resolveProject, resolveProjectDetail } from "../lib/project.js";
9
+ import { fail, isJsonMode, log, output } from "../lib/ui.js";
10
10
  const IGNORED_DIRS = new Set(["node_modules", ".next", ".git", ".vercel", ".turbo", ".swc"]);
11
11
  const IGNORED_FILES = new Set([".DS_Store", ".easyhost.json"]);
12
12
  const isIgnored = (entry) => {
@@ -41,7 +41,7 @@ const packSource = async (cwd) => {
41
41
  };
42
42
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
43
  const STEP_LABELS = {
44
- QUEUED: { active: "Waiting in queue", done: "Started" },
44
+ QUEUED: { active: "Waiting in queue", done: "Waited in queue" },
45
45
  PREPARING: { active: "Preparing environment", done: "Prepared environment" },
46
46
  INSTALLING: { active: "Installing dependencies", done: "Installed dependencies" },
47
47
  BUILDING: { active: "Building app", done: "Built app" },
@@ -71,7 +71,13 @@ const withSpinner = async (text, done, task) => {
71
71
  throw error;
72
72
  }
73
73
  };
74
- const followDeployment = async (app, deploymentId, verbose) => {
74
+ const queueLabel = (position) => {
75
+ if (!position) {
76
+ return STEP_LABELS.QUEUED.active;
77
+ }
78
+ return `${STEP_LABELS.QUEUED.active} (${position} ahead)`;
79
+ };
80
+ const followDeployment = async (project, deploymentId, verbose) => {
75
81
  let printed = 0;
76
82
  let step = null;
77
83
  let stepStartedAt = Date.now();
@@ -82,20 +88,30 @@ const followDeployment = async (app, deploymentId, verbose) => {
82
88
  }
83
89
  };
84
90
  while (true) {
85
- const { deployment } = await request(`/apps/${app.id}/deployments/${deploymentId}`);
91
+ const { deployment } = await request(`/apps/${project.id}/deployments/${deploymentId}`);
86
92
  const text = deployment.log ?? "";
87
93
  if (verbose && text.length > printed) {
88
- process.stdout.write(pc.dim(text.slice(printed)));
94
+ let stream = process.stdout;
95
+ if (isJsonMode()) {
96
+ stream = process.stderr;
97
+ }
98
+ stream.write(pc.dim(text.slice(printed)));
89
99
  printed = text.length;
90
100
  }
101
+ if (deployment.status === "SUPERSEDED") {
102
+ if (spinner) {
103
+ spinner.warn("Replaced by a newer deploy");
104
+ }
105
+ return "superseded";
106
+ }
91
107
  if (deployment.status === "FAILED") {
92
108
  if (spinner && step && step !== "DONE") {
93
109
  spinner.fail(STEP_LABELS[step].active);
94
110
  }
95
111
  if (!verbose) {
96
- console.log(`\n${pc.dim(errorTail(text))}\n`);
112
+ log.info(`\n${pc.dim(errorTail(text))}\n`);
97
113
  }
98
- return false;
114
+ return "failed";
99
115
  }
100
116
  if (!verbose && deployment.step !== step) {
101
117
  finishStep();
@@ -114,53 +130,86 @@ const followDeployment = async (app, deploymentId, verbose) => {
114
130
  spinner = ora(STEP_LABELS[step].active).start();
115
131
  }
116
132
  }
133
+ if (spinner && deployment.status === "QUEUED") {
134
+ spinner.text = queueLabel(deployment.queuePosition);
135
+ }
117
136
  if (deployment.status === "RUNNING") {
118
137
  finishStep();
119
- return true;
138
+ return "live";
120
139
  }
121
140
  await sleep(1500);
122
141
  }
123
142
  };
124
- const warnMissingEnv = (app, cwd) => {
125
- if (!Object.keys(app.env ?? {}).length && existsSync(path.join(cwd, ".env"))) {
126
- log.warn(".env files are not uploaded. Set variables with `easyhost env set KEY=VALUE` and redeploy.");
143
+ const warnMissingEnv = (project, cwd) => {
144
+ if (!Object.keys(project.env).length && existsSync(path.join(cwd, ".env"))) {
145
+ log.warn(".env files are not uploaded. Set variables with `ezhst env set KEY=VALUE` and redeploy.");
127
146
  }
128
147
  };
148
+ const finish = (project, deploymentId, url, result, cwd) => {
149
+ if (result === "superseded") {
150
+ output({ deploymentId, status: "SUPERSEDED" }, () => log.warn("A newer deploy for this project was queued, so this one was skipped."));
151
+ return;
152
+ }
153
+ if (result === "failed") {
154
+ if (cwd) {
155
+ warnMissingEnv(project, cwd);
156
+ }
157
+ fail(`Deployment ${deploymentId} failed. See the full build log with \`ezhst deployments log ${deploymentId}\`.`);
158
+ }
159
+ output({ deploymentId, status: "RUNNING", url }, () => log.success(`\nLive at ${pc.bold(url)}`));
160
+ };
129
161
  export const deploy = async (options) => {
130
162
  const cwd = process.cwd();
131
163
  assertNextProject(cwd);
132
- const app = await resolveApp(options.app);
133
- log.info(`\nDeploying ${pc.bold(app.name)}\n`);
164
+ const project = await resolveProject(options);
165
+ log.info(`\nDeploying ${pc.bold(project.name)}\n`);
134
166
  const { stage, archive } = await withSpinner("Packaging source", () => "Packaged source", () => packSource(cwd));
135
167
  try {
136
168
  const { deployment, url } = await withSpinner("Uploading", (result) => `Uploaded ${result.size}`, async () => {
137
169
  const blob = await openAsBlob(archive);
138
170
  const form = new FormData();
139
171
  form.append("file", blob, "app.tgz");
140
- const result = await request(`/apps/${app.id}/deploy`, {
172
+ const result = await request(`/apps/${project.id}/deploy`, {
141
173
  method: "POST",
142
174
  body: form,
143
175
  });
144
176
  return { ...result, size: `${(blob.size / 1024 / 1024).toFixed(1)} MB` };
145
177
  });
146
- const ok = await followDeployment(app, deployment.id, !!options.verbose);
147
- if (!ok) {
148
- warnMissingEnv(app, cwd);
149
- fail("Deployment failed. Run with --verbose or open the app in the dashboard for the full log.");
150
- }
151
- log.success(`\nLive at ${pc.bold(url)}`);
178
+ const result = await followDeployment(project, deployment.id, !!options.verbose);
179
+ finish(project, deployment.id, url, result, cwd);
152
180
  }
153
181
  finally {
154
182
  rmSync(stage, { recursive: true, force: true });
155
183
  }
156
184
  };
157
185
  export const redeploy = async (options) => {
158
- const app = await resolveApp(options.app);
159
- log.info(`\nRedeploying ${pc.bold(app.name)}\n`);
160
- const { deployment, url } = await withSpinner("Queueing redeploy", () => "Queued redeploy", () => request(`/apps/${app.id}/redeploy`, { method: "POST" }));
161
- const ok = await followDeployment(app, deployment.id, !!options.verbose);
162
- if (!ok) {
163
- fail("Redeploy failed. Run with --verbose or open the app in the dashboard for the full log.");
186
+ const project = await resolveProject(options);
187
+ log.info(`\nRedeploying ${pc.bold(project.name)}\n`);
188
+ const { deployment, url } = await withSpinner("Queueing redeploy", () => "Queued redeploy", () => request(`/apps/${project.id}/redeploy`, { method: "POST" }));
189
+ const result = await followDeployment(project, deployment.id, !!options.verbose);
190
+ finish(project, deployment.id, url, result);
191
+ };
192
+ export const listDeployments = async (options) => {
193
+ const { deployments } = await resolveProjectDetail(options);
194
+ output({ deployments }, () => {
195
+ if (!deployments.length) {
196
+ log.info("No deployments yet. Run `ezhst deploy`.");
197
+ return;
198
+ }
199
+ for (const deployment of deployments) {
200
+ log.info(`${deployment.id} ${deployment.status.padEnd(10)} ${pc.dim(deployment.createdAt)}`);
201
+ }
202
+ });
203
+ };
204
+ export const deploymentLog = async (deploymentId, options) => {
205
+ const { app, deployments } = await resolveProjectDetail(options);
206
+ const id = deploymentId ?? deployments[0]?.id;
207
+ if (!id) {
208
+ fail("No deployments yet. Run `ezhst deploy`.");
164
209
  }
165
- log.success(`\nLive at ${pc.bold(url)}`);
210
+ const { deployment } = await request(`/apps/${app.id}/deployments/${id}`);
211
+ output({ deployment }, () => {
212
+ log.dim(`${deployment.id} ${deployment.status}`);
213
+ process.stdout.write(deployment.log || "No build log yet.\n");
214
+ });
166
215
  };
@@ -0,0 +1,47 @@
1
+ import pc from "picocolors";
2
+ import { json, request } from "../lib/api.js";
3
+ import { resolveProjectDetail } from "../lib/project.js";
4
+ import { fail, log, output } from "../lib/ui.js";
5
+ const findDomain = (domains, hostname) => {
6
+ const domain = domains.find((item) => item.hostname === hostname.toLowerCase());
7
+ if (!domain) {
8
+ return fail(`${hostname} is not connected to this project. See \`ezhst domains list\`.`);
9
+ }
10
+ return domain;
11
+ };
12
+ export const listDomains = async (options) => {
13
+ const { domains, dnsTarget } = await resolveProjectDetail(options);
14
+ output({ domains, dnsTarget }, () => {
15
+ if (!domains.length) {
16
+ log.info("No custom domains yet. Add one with `ezhst domains add <hostname>`.");
17
+ }
18
+ for (const domain of domains) {
19
+ log.info(`${pc.bold(domain.hostname.padEnd(32))} ${domain.status}`);
20
+ if (domain.error) {
21
+ log.warn(` ${domain.error}`);
22
+ }
23
+ }
24
+ log.dim(`\nDNS: CNAME to ${dnsTarget.cname}, or for a root domain an A record to ${dnsTarget.ip}.`);
25
+ });
26
+ };
27
+ export const addDomain = async (hostname, options) => {
28
+ const { app, dnsTarget } = await resolveProjectDetail(options);
29
+ const { domain } = await request(`/apps/${app.id}/domains`, json("POST", { hostname }));
30
+ output({ domain, dnsTarget }, () => {
31
+ log.success(`Added ${domain.hostname}.`);
32
+ log.info(`Create a CNAME record for ${domain.hostname} pointing to ${dnsTarget.cname}`);
33
+ log.info(`(for a root domain, an A record pointing to ${dnsTarget.ip}), then run \`ezhst domains verify ${domain.hostname}\`.`);
34
+ });
35
+ };
36
+ export const verifyDomain = async (hostname, options) => {
37
+ const { app, domains } = await resolveProjectDetail(options);
38
+ const domain = findDomain(domains, hostname);
39
+ const result = await request(`/apps/${app.id}/domains/${domain.id}/verify`, { method: "POST" });
40
+ output(result, () => log.success(`${result.domain.hostname} is ${result.domain.status.toLowerCase()}`));
41
+ };
42
+ export const removeDomain = async (hostname, options) => {
43
+ const { app, domains } = await resolveProjectDetail(options);
44
+ const domain = findDomain(domains, hostname);
45
+ const result = await request(`/apps/${app.id}/domains/${domain.id}`, { method: "DELETE" });
46
+ output(result, () => log.success(`Removed ${domain.hostname}`));
47
+ };
@@ -0,0 +1,75 @@
1
+ import pc from "picocolors";
2
+ import { json, request } from "../lib/api.js";
3
+ import { resolveProject } from "../lib/project.js";
4
+ import { fail, log, output } from "../lib/ui.js";
5
+ const overview = async (options, page = "1") => {
6
+ const project = await resolveProject(options);
7
+ const query = new URLSearchParams({ page });
8
+ const data = await request(`/emails?${query}`, {}, project.id);
9
+ return { project, data };
10
+ };
11
+ export const emailInfo = async (options) => {
12
+ const { data } = await overview(options);
13
+ output({ senders: data.senders, sentToday: data.sentToday, dailyLimit: data.dailyLimit }, () => {
14
+ const sender = data.senders[0];
15
+ if (sender) {
16
+ log.info(`Sender: ${pc.bold(sender.address)}`);
17
+ }
18
+ else {
19
+ log.info(`No sender yet. Create one with \`ezhst email sender create <username>\` (<username>@${data.domain}).`);
20
+ }
21
+ log.info(`Sent in the last 24h: ${data.sentToday}/${data.dailyLimit}`);
22
+ });
23
+ };
24
+ export const createSender = async (username, options) => {
25
+ const project = await resolveProject(options);
26
+ const { senders } = await request("/emails/senders", json("POST", { username }), project.id);
27
+ output({ senders }, () => log.success(`Sender ${senders[0]?.address} created`));
28
+ };
29
+ export const deleteSender = async (options) => {
30
+ const { project, data } = await overview(options);
31
+ const sender = data.senders[0];
32
+ if (!sender) {
33
+ return fail("This project has no sender address.");
34
+ }
35
+ await request(`/emails/senders/${sender.id}`, { method: "DELETE" }, project.id);
36
+ output({ deleted: sender.address }, () => log.success(`Deleted ${sender.address}`));
37
+ };
38
+ export const sendEmail = async (options) => {
39
+ const project = await resolveProject(options);
40
+ const { from, subject } = options;
41
+ if (!from) {
42
+ return fail("Missing --from.");
43
+ }
44
+ if (!subject) {
45
+ return fail("Missing --subject.");
46
+ }
47
+ if (!options.to?.length) {
48
+ return fail("Missing --to.");
49
+ }
50
+ if (!options.text && !options.html) {
51
+ return fail("Pass --text or --html.");
52
+ }
53
+ let to = options.to;
54
+ if (options.to.length === 1) {
55
+ to = options.to[0];
56
+ }
57
+ const result = await request("/emails/send", json("POST", { from, to, subject, text: options.text, html: options.html }), project.id);
58
+ output(result, () => log.success(`Sent from ${result.from}`));
59
+ };
60
+ export const emailLogs = async (options) => {
61
+ const { data } = await overview(options, options.page);
62
+ output({ logs: data.logs, total: data.total, page: data.page }, () => {
63
+ if (!data.logs.length) {
64
+ log.info("No emails sent yet.");
65
+ return;
66
+ }
67
+ for (const entry of data.logs) {
68
+ log.info(`${pc.dim(entry.createdAt)} ${entry.status.padEnd(7)} ${entry.from} to ${entry.to.join(", ")}: ${entry.subject}`);
69
+ if (entry.error) {
70
+ log.warn(` ${entry.error}`);
71
+ }
72
+ }
73
+ log.dim(`Page ${data.page}, ${data.total} emails total`);
74
+ });
75
+ };
@@ -0,0 +1,69 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { json, request } from "../lib/api.js";
3
+ import { resolveProject } from "../lib/project.js";
4
+ import { fail, log, output } from "../lib/ui.js";
5
+ const saveEnv = async (project, env) => {
6
+ await request(`/apps/${project.id}/env`, json("PUT", { env }));
7
+ output({ env }, () => log.success("Environment saved. Run `ezhst redeploy` to apply it."));
8
+ };
9
+ const parseDotenv = (text) => {
10
+ const entries = {};
11
+ for (const raw of text.split(/\r?\n/)) {
12
+ const line = raw.trim().replace(/^export\s+/, "");
13
+ if (!line || line.startsWith("#")) {
14
+ continue;
15
+ }
16
+ const index = line.indexOf("=");
17
+ if (index < 1) {
18
+ continue;
19
+ }
20
+ let value = line.slice(index + 1).trim();
21
+ const quoted = value.length > 1 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0]);
22
+ if (quoted) {
23
+ value = value.slice(1, -1);
24
+ }
25
+ entries[line.slice(0, index).trim()] = value;
26
+ }
27
+ return entries;
28
+ };
29
+ export const listEnv = async (options) => {
30
+ const project = await resolveProject(options);
31
+ output({ env: project.env }, () => {
32
+ const entries = Object.entries(project.env);
33
+ if (!entries.length) {
34
+ log.info("No environment variables set.");
35
+ return;
36
+ }
37
+ for (const [key, value] of entries) {
38
+ log.info(`${key}=${value}`);
39
+ }
40
+ });
41
+ };
42
+ export const setEnv = async (pairs, options) => {
43
+ const project = await resolveProject(options);
44
+ const env = { ...project.env };
45
+ for (const pair of pairs) {
46
+ const index = pair.indexOf("=");
47
+ if (index < 1) {
48
+ fail(`Invalid pair "${pair}". Use KEY=VALUE.`);
49
+ }
50
+ env[pair.slice(0, index)] = pair.slice(index + 1);
51
+ }
52
+ await saveEnv(project, env);
53
+ };
54
+ export const unsetEnv = async (keys, options) => {
55
+ const project = await resolveProject(options);
56
+ const env = { ...project.env };
57
+ for (const key of keys) {
58
+ delete env[key];
59
+ }
60
+ await saveEnv(project, env);
61
+ };
62
+ export const importEnv = async (file, options) => {
63
+ const project = await resolveProject(options);
64
+ const imported = parseDotenv(readFileSync(file, "utf8"));
65
+ if (!Object.keys(imported).length) {
66
+ fail(`No variables found in ${file}.`);
67
+ }
68
+ await saveEnv(project, { ...project.env, ...imported });
69
+ };
@@ -0,0 +1,30 @@
1
+ import pc from "picocolors";
2
+ import { json, request } from "../lib/api.js";
3
+ import { resolveProject } from "../lib/project.js";
4
+ import { log, output } from "../lib/ui.js";
5
+ export const listKeys = async (options) => {
6
+ const project = await resolveProject(options);
7
+ const { apiKeys } = await request("/api-keys", {}, project.id);
8
+ output({ apiKeys }, () => {
9
+ if (!apiKeys.length) {
10
+ log.info("No API keys yet. Create one with `ezhst keys create <name>`.");
11
+ return;
12
+ }
13
+ for (const key of apiKeys) {
14
+ log.info(`${key.id} ${pc.bold(key.name.padEnd(24))} ${key.prefix}... ${pc.dim(`last used ${key.lastUsedAt ?? "never"}`)}`);
15
+ }
16
+ });
17
+ };
18
+ export const createKey = async (name, options) => {
19
+ const project = await resolveProject(options);
20
+ const result = await request("/api-keys", json("POST", { name }), project.id);
21
+ output(result, () => {
22
+ log.success(`Created ${result.apiKey.name}. Copy it now, it is shown only once:`);
23
+ log.info(result.key);
24
+ });
25
+ };
26
+ export const revokeKey = async (id, options) => {
27
+ const project = await resolveProject(options);
28
+ const result = await request(`/api-keys/${id}`, { method: "DELETE" }, project.id);
29
+ output(result, () => log.success(result.message));
30
+ };