ezhst 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ import pc from "picocolors";
2
+ import { request } from "../lib/api.js";
3
+ import { linkApp, resolveApp } from "../lib/resolve-app.js";
4
+ import { log } from "../lib/ui.js";
5
+ export const listApps = async () => {
6
+ const { apps } = await request("/apps");
7
+ if (!apps.length) {
8
+ log.info("No apps yet. Run `easyhost deploy` inside a Next.js project.");
9
+ return;
10
+ }
11
+ for (const app of apps) {
12
+ log.info(`${pc.bold(app.name.padEnd(24))} ${app.status.padEnd(10)} ${pc.dim(app.url)}`);
13
+ }
14
+ };
15
+ export const init = async () => {
16
+ const app = await linkApp();
17
+ log.success(`Linked to ${app.name}`);
18
+ };
19
+ export const logs = async (options) => {
20
+ const app = await resolveApp(options.app);
21
+ const { logs: output } = await request(`/apps/${app.id}/logs?tail=${options.tail ?? "200"}`);
22
+ process.stdout.write(output || "No logs yet.\n");
23
+ };
24
+ export const listEnv = async (options) => {
25
+ const app = await resolveApp(options.app);
26
+ const entries = Object.entries(app.env ?? {});
27
+ if (!entries.length) {
28
+ log.info("No environment variables set.");
29
+ return;
30
+ }
31
+ for (const [key, value] of entries) {
32
+ log.info(`${key}=${value}`);
33
+ }
34
+ };
35
+ const saveEnv = async (app, env) => {
36
+ await request(`/apps/${app.id}/env`, { method: "PUT", body: JSON.stringify({ env }) });
37
+ log.success("Environment saved. Run `easyhost redeploy` to apply it.");
38
+ };
39
+ export const setEnv = async (pairs, options) => {
40
+ const app = await resolveApp(options.app);
41
+ const env = { ...(app.env ?? {}) };
42
+ for (const pair of pairs) {
43
+ const index = pair.indexOf("=");
44
+ if (index < 1) {
45
+ log.error(`Invalid pair "${pair}". Use KEY=VALUE.`);
46
+ process.exit(1);
47
+ }
48
+ env[pair.slice(0, index)] = pair.slice(index + 1);
49
+ }
50
+ await saveEnv(app, env);
51
+ };
52
+ export const unsetEnv = async (keys, options) => {
53
+ const app = await resolveApp(options.app);
54
+ const env = { ...(app.env ?? {}) };
55
+ for (const key of keys) {
56
+ delete env[key];
57
+ }
58
+ await saveEnv(app, env);
59
+ };
@@ -0,0 +1,26 @@
1
+ import { input, password } from "@inquirer/prompts";
2
+ import { request } from "../lib/api.js";
3
+ import { clearConfig, readConfig, writeConfig } from "../lib/config.js";
4
+ import { log } from "../lib/ui.js";
5
+ export const login = async (options) => {
6
+ const current = readConfig();
7
+ const apiUrl = (options.api ?? current.apiUrl).replace(/\/$/, "");
8
+ 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}>`);
17
+ };
18
+ export const logout = () => {
19
+ clearConfig();
20
+ log.success("Logged out");
21
+ };
22
+ export const whoami = async () => {
23
+ const { user } = await request("/auth/me");
24
+ log.info(`${user.name} <${user.email}>`);
25
+ log.dim(readConfig().apiUrl);
26
+ };
@@ -0,0 +1,166 @@
1
+ import { existsSync, mkdtempSync, openAsBlob, readFileSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import * as tar from "tar";
5
+ import pc from "picocolors";
6
+ import ora from "ora";
7
+ import { request } from "../lib/api.js";
8
+ import { resolveApp } from "../lib/resolve-app.js";
9
+ import { fail, log } from "../lib/ui.js";
10
+ const IGNORED_DIRS = new Set(["node_modules", ".next", ".git", ".vercel", ".turbo", ".swc"]);
11
+ const IGNORED_FILES = new Set([".DS_Store", ".easyhost.json"]);
12
+ const isIgnored = (entry) => {
13
+ const parts = entry.replace(/^\.\//, "").split("/");
14
+ if (parts.some((part) => IGNORED_DIRS.has(part))) {
15
+ return true;
16
+ }
17
+ const name = parts[parts.length - 1];
18
+ if (IGNORED_FILES.has(name) || name.endsWith(".tsbuildinfo")) {
19
+ return true;
20
+ }
21
+ return name.startsWith(".env") && name !== ".env.example";
22
+ };
23
+ const assertNextProject = (cwd) => {
24
+ const pkgFile = path.join(cwd, "package.json");
25
+ if (!existsSync(pkgFile)) {
26
+ fail("No package.json found. Run this inside your Next.js project.");
27
+ }
28
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
29
+ if (!pkg.dependencies?.next && !pkg.devDependencies?.next) {
30
+ fail("This does not look like a Next.js project. Only Next.js apps are supported right now.");
31
+ }
32
+ if (!pkg.scripts?.build) {
33
+ fail("No build script found in package.json.");
34
+ }
35
+ };
36
+ const packSource = async (cwd) => {
37
+ const stage = mkdtempSync(path.join(tmpdir(), "easyhost-"));
38
+ const archive = path.join(stage, "app.tgz");
39
+ await tar.create({ gzip: true, cwd, file: archive, portable: true, filter: (entry) => !isIgnored(entry) }, ["."]);
40
+ return { stage, archive };
41
+ };
42
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ const STEP_LABELS = {
44
+ QUEUED: { active: "Waiting in queue", done: "Started" },
45
+ PREPARING: { active: "Preparing environment", done: "Prepared environment" },
46
+ INSTALLING: { active: "Installing dependencies", done: "Installed dependencies" },
47
+ BUILDING: { active: "Building app", done: "Built app" },
48
+ STARTING: { active: "Starting app", done: "Started app" },
49
+ ROUTING: { active: "Going live", done: "Routed traffic" },
50
+ };
51
+ const STEP_ORDER = ["QUEUED", "PREPARING", "INSTALLING", "BUILDING", "STARTING", "ROUTING", "DONE"];
52
+ const NOISE = [/^ ---> /, /^Step \d+\/\d+ : /, /^Removed intermediate/, /^npm (notice|warn)/, /returned a non-zero code/];
53
+ const errorTail = (text, lines = 25) => {
54
+ return text
55
+ .split("\n")
56
+ .filter((line) => line.trim() && !NOISE.some((pattern) => pattern.test(line)))
57
+ .slice(-lines)
58
+ .join("\n");
59
+ };
60
+ const seconds = (since) => `${Math.round((Date.now() - since) / 1000)}s`;
61
+ const withSpinner = async (text, done, task) => {
62
+ const spinner = ora(text).start();
63
+ const startedAt = Date.now();
64
+ try {
65
+ const result = await task();
66
+ spinner.succeed(`${done(result)} ${pc.dim(seconds(startedAt))}`);
67
+ return result;
68
+ }
69
+ catch (error) {
70
+ spinner.fail(text);
71
+ throw error;
72
+ }
73
+ };
74
+ const followDeployment = async (app, deploymentId, verbose) => {
75
+ let printed = 0;
76
+ let step = null;
77
+ let stepStartedAt = Date.now();
78
+ let spinner = null;
79
+ const finishStep = () => {
80
+ if (spinner && step && step !== "DONE") {
81
+ spinner.succeed(`${STEP_LABELS[step].done} ${pc.dim(seconds(stepStartedAt))}`);
82
+ }
83
+ };
84
+ while (true) {
85
+ const { deployment } = await request(`/apps/${app.id}/deployments/${deploymentId}`);
86
+ const text = deployment.log ?? "";
87
+ if (verbose && text.length > printed) {
88
+ process.stdout.write(pc.dim(text.slice(printed)));
89
+ printed = text.length;
90
+ }
91
+ if (deployment.status === "FAILED") {
92
+ if (spinner && step && step !== "DONE") {
93
+ spinner.fail(STEP_LABELS[step].active);
94
+ }
95
+ if (!verbose) {
96
+ console.log(`\n${pc.dim(errorTail(text))}\n`);
97
+ }
98
+ return false;
99
+ }
100
+ if (!verbose && deployment.step !== step) {
101
+ finishStep();
102
+ if (step) {
103
+ const skipped = STEP_ORDER.slice(STEP_ORDER.indexOf(step) + 1, STEP_ORDER.indexOf(deployment.step));
104
+ for (const item of skipped) {
105
+ if (item !== "DONE") {
106
+ ora().succeed(STEP_LABELS[item].done);
107
+ }
108
+ }
109
+ }
110
+ step = deployment.step;
111
+ stepStartedAt = Date.now();
112
+ spinner = null;
113
+ if (step !== "DONE") {
114
+ spinner = ora(STEP_LABELS[step].active).start();
115
+ }
116
+ }
117
+ if (deployment.status === "RUNNING") {
118
+ finishStep();
119
+ return true;
120
+ }
121
+ await sleep(1500);
122
+ }
123
+ };
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.");
127
+ }
128
+ };
129
+ export const deploy = async (options) => {
130
+ const cwd = process.cwd();
131
+ assertNextProject(cwd);
132
+ const app = await resolveApp(options.app);
133
+ log.info(`\nDeploying ${pc.bold(app.name)}\n`);
134
+ const { stage, archive } = await withSpinner("Packaging source", () => "Packaged source", () => packSource(cwd));
135
+ try {
136
+ const { deployment, url } = await withSpinner("Uploading", (result) => `Uploaded ${result.size}`, async () => {
137
+ const blob = await openAsBlob(archive);
138
+ const form = new FormData();
139
+ form.append("file", blob, "app.tgz");
140
+ const result = await request(`/apps/${app.id}/deploy`, {
141
+ method: "POST",
142
+ body: form,
143
+ });
144
+ return { ...result, size: `${(blob.size / 1024 / 1024).toFixed(1)} MB` };
145
+ });
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)}`);
152
+ }
153
+ finally {
154
+ rmSync(stage, { recursive: true, force: true });
155
+ }
156
+ };
157
+ 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.");
164
+ }
165
+ log.success(`\nLive at ${pc.bold(url)}`);
166
+ };
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { login, logout, whoami } from "./commands/auth.js";
4
+ import { init, listApps, listEnv, logs, setEnv, unsetEnv } from "./commands/apps.js";
5
+ import { deploy, redeploy } from "./commands/deploy.js";
6
+ import { log } from "./lib/ui.js";
7
+ const program = new Command();
8
+ program.name("easyhost").description("Deploy Next.js apps to EasyHost").version("0.1.0");
9
+ program.command("login").description("Log in to EasyHost").option("--api <url>", "API URL").action(login);
10
+ program.command("logout").description("Log out").action(logout);
11
+ program.command("whoami").description("Show the logged in user").action(whoami);
12
+ program.command("apps").description("List your apps").action(listApps);
13
+ program.command("init").description("Link this folder to an app").action(init);
14
+ program
15
+ .command("deploy")
16
+ .description("Upload and deploy the Next.js app in this folder")
17
+ .option("--app <slug>", "App to deploy to")
18
+ .option("--verbose", "Stream the full build log")
19
+ .action(deploy);
20
+ program
21
+ .command("redeploy")
22
+ .description("Rebuild and redeploy the latest upload")
23
+ .option("--app <slug>", "App slug")
24
+ .option("--verbose", "Stream the full build log")
25
+ .action(redeploy);
26
+ program
27
+ .command("logs")
28
+ .description("Show runtime logs")
29
+ .option("--app <slug>", "App slug")
30
+ .option("--tail <lines>", "Number of lines", "200")
31
+ .action(logs);
32
+ const env = program.command("env").description("Manage environment variables");
33
+ env.command("list").option("--app <slug>", "App slug").action(listEnv);
34
+ env.command("set").argument("<pairs...>", "KEY=VALUE pairs").option("--app <slug>", "App slug").action(setEnv);
35
+ env.command("unset").argument("<keys...>", "Keys to remove").option("--app <slug>", "App slug").action(unsetEnv);
36
+ program.parseAsync().catch((error) => {
37
+ if (error?.name === "ExitPromptError") {
38
+ process.exit(130);
39
+ }
40
+ log.error(error instanceof Error ? error.message : String(error));
41
+ process.exit(1);
42
+ });
@@ -0,0 +1,27 @@
1
+ import { readConfig } from "./config.js";
2
+ export class ApiError extends Error {
3
+ status;
4
+ constructor(message, status) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ }
9
+ export const request = async (pathname, init = {}) => {
10
+ const { apiUrl, token } = readConfig();
11
+ const headers = new Headers(init.headers);
12
+ if (token) {
13
+ headers.set("Authorization", `Bearer ${token}`);
14
+ }
15
+ if (init.body && typeof init.body === "string") {
16
+ headers.set("Content-Type", "application/json");
17
+ }
18
+ const res = await fetch(`${apiUrl}/api${pathname}`, { ...init, headers });
19
+ const data = await res.json().catch(() => ({}));
20
+ if (!res.ok) {
21
+ if (res.status === 401) {
22
+ throw new ApiError("Not logged in. Run `easyhost login` first.", 401);
23
+ }
24
+ throw new ApiError(data.error ?? `Request failed with status ${res.status}`, res.status);
25
+ }
26
+ return data;
27
+ };
@@ -0,0 +1,30 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ const CONFIG_DIR = path.join(homedir(), ".easyhost");
5
+ const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
6
+ const PROJECT_FILE = ".easyhost.json";
7
+ export const DEFAULT_API_URL = process.env.EASYHOST_API_URL || "http://localhost:4000";
8
+ export const readConfig = () => {
9
+ if (!existsSync(CONFIG_FILE)) {
10
+ return { apiUrl: DEFAULT_API_URL };
11
+ }
12
+ return { apiUrl: DEFAULT_API_URL, ...JSON.parse(readFileSync(CONFIG_FILE, "utf8")) };
13
+ };
14
+ export const writeConfig = (config) => {
15
+ mkdirSync(CONFIG_DIR, { recursive: true });
16
+ writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
17
+ };
18
+ export const clearConfig = () => {
19
+ rmSync(CONFIG_FILE, { force: true });
20
+ };
21
+ export const readProject = (cwd = process.cwd()) => {
22
+ const file = path.join(cwd, PROJECT_FILE);
23
+ if (!existsSync(file)) {
24
+ return null;
25
+ }
26
+ return JSON.parse(readFileSync(file, "utf8"));
27
+ };
28
+ export const writeProject = (project, cwd = process.cwd()) => {
29
+ writeFileSync(path.join(cwd, PROJECT_FILE), `${JSON.stringify(project, null, 2)}\n`);
30
+ };
@@ -0,0 +1,51 @@
1
+ import { input, select } from "@inquirer/prompts";
2
+ import path from "node:path";
3
+ import { request } from "./api.js";
4
+ import { readProject, writeProject } from "./config.js";
5
+ import { log } from "./ui.js";
6
+ const slugify = (value) => {
7
+ return value
8
+ .toLowerCase()
9
+ .replace(/[^a-z0-9]+/g, "-")
10
+ .replace(/(^-|-$)/g, "");
11
+ };
12
+ export const linkApp = async () => {
13
+ const { apps } = await request("/apps");
14
+ const NEW_APP = "__new__";
15
+ let choice = NEW_APP;
16
+ if (apps.length) {
17
+ choice = await select({
18
+ message: "Which app should this folder deploy to?",
19
+ choices: [
20
+ { name: "Create a new app", value: NEW_APP },
21
+ ...apps.map((app) => ({ name: `${app.name} (${app.url})`, value: app.id })),
22
+ ],
23
+ });
24
+ }
25
+ let app = apps.find((item) => item.id === choice);
26
+ if (!app) {
27
+ const name = await input({
28
+ message: "App name (used as subdomain)",
29
+ default: slugify(path.basename(process.cwd())),
30
+ validate: (value) => /^[a-z0-9]+(-[a-z0-9]+)*$/.test(value) || "Use lowercase letters, numbers and single dashes",
31
+ });
32
+ const result = await request("/apps", { method: "POST", body: JSON.stringify({ name }) });
33
+ app = result.app;
34
+ log.success(`Created app ${app.name}`);
35
+ }
36
+ writeProject({ appId: app.id, slug: app.slug });
37
+ log.dim("Saved link in .easyhost.json");
38
+ return app;
39
+ };
40
+ export const resolveApp = async (slug) => {
41
+ if (slug) {
42
+ const { app } = await request(`/apps/${slug}`);
43
+ return app;
44
+ }
45
+ const project = readProject();
46
+ if (project) {
47
+ const { app } = await request(`/apps/${project.appId}`);
48
+ return app;
49
+ }
50
+ return linkApp();
51
+ };
package/dist/lib/ui.js ADDED
@@ -0,0 +1,13 @@
1
+ import pc from "picocolors";
2
+ export const log = {
3
+ info: (message) => console.log(message),
4
+ step: (message) => console.log(pc.cyan(message)),
5
+ success: (message) => console.log(pc.green(message)),
6
+ warn: (message) => console.log(pc.yellow(message)),
7
+ error: (message) => console.error(pc.red(message)),
8
+ dim: (message) => console.log(pc.dim(message)),
9
+ };
10
+ export const fail = (message) => {
11
+ log.error(message);
12
+ process.exit(1);
13
+ };
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "ezhst",
3
+ "version": "0.1.0",
4
+ "description": "Deploy Next.js apps to EasyHost",
5
+ "type": "module",
6
+ "bin": {
7
+ "ezhst": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "dev": "tsx src/index.ts",
14
+ "build": "tsc",
15
+ "typecheck": "tsc --noEmit"
16
+ },
17
+ "dependencies": {
18
+ "@inquirer/prompts": "^8.7.2",
19
+ "commander": "^15.0.0",
20
+ "ora": "^9.4.1",
21
+ "picocolors": "^1.1.1",
22
+ "tar": "^7.5.22"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^26.6.2",
26
+ "tsx": "^4.23.15",
27
+ "typescript": "^7.0.2"
28
+ }
29
+ }