@hakopod/cli 0.1.0-alpha.2 → 0.1.0-alpha.36

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.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Hakopod
2
+ Copyright 2026 Hakopod contributors
3
+
4
+ Hakopod original code is licensed under Apache-2.0.
5
+ Third-party dependencies retain their own licenses. See docs/licenses.md.
6
+ No Railway, Render, Vercel, Coolify, Dokploy, Kubernetes, or HAProxy branding
7
+ assets are redistributed as Hakopod branding. References informed behavior
8
+ and interface principles only. No ownership of hakopod.com is asserted.
package/README.md CHANGED
@@ -1,67 +1,54 @@
1
- # Hakopod CLI
2
-
3
- Deploy a committed Git repository to Hakopod Cloud or your own Hakopod installation.
4
- Requires Node.js 22.12+ and Git. This package uses the shared engine API; it does not
5
- download or execute another binary during npm installation.
1
+ # @hakopod/cli-binary
2
+
3
+ Source for the npm distribution of the Go `hakopod` CLI (`cmd/hakopod/`),
4
+ using the optionalDependencies-per-platform pattern (as used by esbuild,
5
+ swc, etc.).
6
+
7
+ ## Layout
8
+
9
+ - `bin/hakopod.mjs` — the wrapper's bin entry. Resolves the platform
10
+ package for the current `process.platform`/`process.arch`, execs its
11
+ binary with `stdio: 'inherit'`, and forwards the exit code. No
12
+ postinstall/download step — npm's optionalDependencies resolution does
13
+ the fetching.
14
+ - `wrapper-package.json` — template for the `@hakopod/cli` wrapper
15
+ package.json (`__VERSION__` is substituted by the generator).
16
+ - `generate.mjs` — generator script. Produces seven publishable package
17
+ directories: the wrapper (`cli/`) and six platform packages
18
+ (`cli-<os>-<arch>/`), one per supported platform.
19
+
20
+ Platform packages (name / os / cpu):
21
+
22
+ | npm package | os | cpu |
23
+ |---------------------------------|---------|-------|
24
+ | `@hakopod/cli-darwin-arm64` | darwin | arm64 |
25
+ | `@hakopod/cli-darwin-x64` | darwin | x64 |
26
+ | `@hakopod/cli-linux-x64` | linux | x64 |
27
+ | `@hakopod/cli-linux-arm64` | linux | arm64 |
28
+ | `@hakopod/cli-win32-x64` | win32 | x64 |
29
+ | `@hakopod/cli-win32-arm64` | win32 | arm64 |
30
+
31
+ ## Generator invocation
32
+
33
+ Input is a directory containing one extracted release archive per
34
+ platform, named `<system>_<arch>` (release-asset naming: `darwin`,
35
+ `linux`, `windows` / `amd64`, `arm64`), each holding the `hakopod`
36
+ binary (`hakopod.exe` on windows), `LICENSE`, and `NOTICE` — i.e. the
37
+ contents of `hakopod-cli_<version>_<system>_<arch>.tar.gz` extracted.
6
38
 
7
39
  ```sh
8
- npx @hakopod/cli deploy
9
- # Or point it at your own dashboard:
10
- npx @hakopod/cli deploy --url https://hakopod.example.com
40
+ node packages/cli-binary/generate.mjs <version> <extracted-archives-dir> <out-dir>
11
41
  ```
12
42
 
13
- The first run opens browser sign-in. Create an account if needed, compare the
14
- terminal code, and choose one project/environment or ready Cloud workspace.
15
- If no destination is ready, open dashboard setup from the consent page, finish
16
- setup, return, and refresh destinations. Codes expire after ten minutes; repeat
17
- login if setup takes longer. Cloud admission, email verification, membership and
18
- MFA requirements still apply. A project administrator or Cloud workspace owner
19
- must connect Git and authorize a new application source.
20
-
21
- The deploy command checks that your working tree is clean and the current branch
22
- is pushed to `origin`, detects the framework remotely, and lets you review or edit
23
- its commands, service port and public access. GitHub.com and GitLab.com are supported.
24
- It shows the exact generated workflow and requirements before writing it, then
25
- writes to the repository default branch. When deploying that branch, it also
26
- fast-forwards your local checkout to the reviewed workflow commit. Concurrent remote
27
- or local edits stop this step for review. Builds run in your Git provider's CI.
28
-
29
- You review the deployment plan before its digest-pinned image is deployed. The CLI
30
- waits for the deployment's terminal status. Failed builds, failed deployments and
31
- Cloud Team approvals do not report success. Approval must be completed in Cloud.
32
- Run the same command after interruption to resume an accepted build/deployment.
43
+ Example:
33
44
 
34
45
  ```sh
35
- npx @hakopod/cli login --url https://cloud.hakopod.com
36
- npx @hakopod/cli deploy --name my-app --context apps/web
37
- npx @hakopod/cli deploy --build BUILD_ID # link an existing build for this exact source/scope
38
- npx @hakopod/cli status
39
- npx @hakopod/cli logout
46
+ node packages/cli-binary/generate.mjs 0.1.0-alpha.34 /tmp/hakopod-release-assets /tmp/hakopod-npm-out
40
47
  ```
41
48
 
42
- `--no-browser` prints the sign-in URL without opening it. `--yes` accepts the
43
- printed configuration, workflow and deployment reviews; it does not bypass browser
44
- consent or server policy. Noninteractive defaults use Cloud, a small private web
45
- service and the detected commands. Advanced runtime variables, secret bindings,
46
- multiple services, architecture and resource settings remain editable in the
47
- shared dashboard; linked builds preserve those settings.
48
-
49
- Credentials and resumable deployment state live outside the source repository in
50
- `~/.config/hakopod/npm`, separately for each exact installation origin. Set
51
- `HAKOPOD_CLI_HOME` to use another protected directory. Files are written atomically
52
- with owner-only permissions; Windows uses the account profile's directory ACLs.
53
- Sessions expire after twelve hours and can be revoked in account security. Logout
54
- attempts server revocation and always removes local credentials. Account login happens in the browser. Before deployment, missing application
55
- secrets can be entered with hidden terminal input or explicitly generated.
56
- Generation creates a random password, not a provider-issued API credential.
57
- Noninteractive runs stop with the missing names, including when using `--yes`.
58
- Secret values are sent directly to scoped storage and never saved in CLI state.
59
- Never commit CLI state to Git.
60
-
61
- Use an engine/Cloud server release containing npm CLI device-scope support. Older
62
- servers may expose only the image-based Go CLI API. That CLI remains available for
63
- TOML, machine API keys, logs and infrastructure administration.
49
+ This writes `<out-dir>/cli/` (the wrapper) and
50
+ `<out-dir>/cli-<os>-<arch>/` (the six platform packages), each a
51
+ complete, publishable package directory.
64
52
 
65
- For local development: `npm test`, `npm pack`, then `npx --package ./hakopod-cli-*.tgz hakopod --help`.
66
- The package archive contains only public JavaScript, this documentation and the
67
- Apache-2.0 license. CI tests it and inspects its package contents.
53
+ A release workflow calling this script is out of scope here; wiring it
54
+ in is reserved for whoever owns `.github/workflows/`.
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { createRequire } from "node:module";
4
+
5
+ const require = createRequire(import.meta.url);
6
+
7
+ const PLATFORM_PACKAGES = {
8
+ "darwin-arm64": "@hakopod/cli-darwin-arm64",
9
+ "darwin-x64": "@hakopod/cli-darwin-x64",
10
+ "linux-x64": "@hakopod/cli-linux-x64",
11
+ "linux-arm64": "@hakopod/cli-linux-arm64",
12
+ "win32-x64": "@hakopod/cli-win32-x64",
13
+ "win32-arm64": "@hakopod/cli-win32-arm64",
14
+ };
15
+
16
+ const key = `${process.platform}-${process.arch}`;
17
+ const pkgName = PLATFORM_PACKAGES[key];
18
+ const binName = process.platform === "win32" ? "hakopod.exe" : "hakopod";
19
+
20
+ let binPath;
21
+ try {
22
+ if (!pkgName) throw new Error("unsupported");
23
+ binPath = require.resolve(`${pkgName}/${binName}`);
24
+ } catch {
25
+ process.stderr.write(
26
+ `hakopod: no binary available for platform ${key}; install via https://hakopod.com/scripts/cli.sh instead\n`,
27
+ );
28
+ process.exit(1);
29
+ }
30
+
31
+ const result = spawnSync(binPath, process.argv.slice(2), { stdio: "inherit" });
32
+ process.exit(result.status ?? 1);
package/package.json CHANGED
@@ -1,28 +1,33 @@
1
1
  {
2
2
  "name": "@hakopod/cli",
3
- "version": "0.1.0-alpha.2",
4
- "description": "Guided Git deployments to Hakopod Cloud and self-hosted Hakopod",
3
+ "version": "0.1.0-alpha.36",
4
+ "description": "Deploy, manage, and operate Hakopod stacks from the command line",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "bin": {
8
- "hakopod": "src/main.mjs"
8
+ "hakopod": "bin/hakopod.mjs"
9
9
  },
10
10
  "engines": {
11
11
  "node": ">=22.12.0"
12
12
  },
13
13
  "files": [
14
- "src",
14
+ "bin",
15
15
  "README.md",
16
- "LICENSE"
16
+ "LICENSE",
17
+ "NOTICE"
17
18
  ],
18
- "scripts": {
19
- "test": "node --test",
20
- "prepublishOnly": "npm test"
19
+ "optionalDependencies": {
20
+ "@hakopod/cli-darwin-arm64": "0.1.0-alpha.36",
21
+ "@hakopod/cli-darwin-x64": "0.1.0-alpha.36",
22
+ "@hakopod/cli-linux-x64": "0.1.0-alpha.36",
23
+ "@hakopod/cli-linux-arm64": "0.1.0-alpha.36",
24
+ "@hakopod/cli-win32-x64": "0.1.0-alpha.36",
25
+ "@hakopod/cli-win32-arm64": "0.1.0-alpha.36"
21
26
  },
22
27
  "repository": {
23
28
  "type": "git",
24
29
  "url": "git+https://github.com/hakopod/hakopod.git",
25
- "directory": "packages/cli"
30
+ "directory": "packages/cli-binary"
26
31
  },
27
32
  "publishConfig": {
28
33
  "access": "public"
package/src/core.mjs DELETED
@@ -1,297 +0,0 @@
1
- import { mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
2
- import { constants } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
5
- import { createHash, randomUUID } from "node:crypto";
6
- import { execFile } from "node:child_process";
7
- import { promisify } from "node:util";
8
- export const execute = promisify(execFile);
9
- export const cloud = "https://cloud.hakopod.com";
10
- export const clean = (value) =>
11
- String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, "");
12
- export function origin(value) {
13
- const url = new URL(value);
14
- if (
15
- url.username ||
16
- url.password ||
17
- url.search ||
18
- url.hash ||
19
- !["", "/"].includes(url.pathname) ||
20
- !(
21
- url.protocol === "https:" ||
22
- (url.protocol === "http:" &&
23
- ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
24
- )
25
- )
26
- throw new Error(
27
- "Use an exact HTTPS dashboard origin, or HTTP on localhost.",
28
- );
29
- return url.origin;
30
- }
31
- export function remote(value) {
32
- const match =
33
- /^(?:git@(github\.com|gitlab\.com):|https:\/\/(github\.com|gitlab\.com)\/|ssh:\/\/git@(github\.com|gitlab\.com)\/)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+?)(?:\.git)?$/.exec(
34
- value,
35
- );
36
- if (!match)
37
- throw new Error(
38
- "Use a GitHub.com or GitLab.com origin without credentials in its URL.",
39
- );
40
- const host = match[1] || match[2] || match[3];
41
- const repository = match[4].replace(/\.git$/, "");
42
- if (
43
- repository.split("/").some((part) => part === "." || part === "..") ||
44
- (host === "github.com" && repository.split("/").length !== 2)
45
- )
46
- throw new Error("Invalid Git repository path.");
47
- return { provider: host === "github.com" ? "github" : "gitlab", repository };
48
- }
49
- export async function git(args, cwd = process.cwd()) {
50
- try {
51
- return (
52
- await execute("git", args, {
53
- cwd,
54
- timeout: 30000,
55
- maxBuffer: 1024 * 1024,
56
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
57
- })
58
- ).stdout.trim();
59
- } catch {
60
- throw new Error(
61
- "Git could not complete the check. Verify repository access and your local Git credentials.",
62
- );
63
- }
64
- }
65
- export async function repository(cwd = process.cwd(), requirePushed = true) {
66
- const root = await git(["rev-parse", "--show-toplevel"], cwd);
67
- const source = remote(await git(["remote", "get-url", "origin"], root));
68
- const branch = await git(["symbolic-ref", "--short", "HEAD"], root);
69
- const commit = await git(["rev-parse", "HEAD"], root);
70
- if (requirePushed) {
71
- if (await git(["status", "--porcelain"], root))
72
- throw new Error(
73
- "Commit or stash local changes first. This command deploys only committed, pushed Git files.",
74
- );
75
- const published = await git(
76
- ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
77
- root,
78
- );
79
- if (published.split(/\s/)[0] !== commit)
80
- throw new Error(
81
- "Push this branch before deploying. Its remote HEAD must match your local commit.",
82
- );
83
- }
84
- return { root, branch, commit, ...source };
85
- }
86
- export const configRoot = () =>
87
- process.env.HAKOPOD_CLI_HOME || join(homedir(), ".config", "hakopod", "npm");
88
- export const key = (value) => createHash("sha256").update(value).digest("hex");
89
- export async function readPrivate(file) {
90
- let handle;
91
- try {
92
- handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
93
- const info = await handle.stat();
94
- if (
95
- (process.getuid && info.uid !== process.getuid()) ||
96
- !info.isFile() ||
97
- info.size > 1024 * 1024 ||
98
- (process.platform !== "win32" && info.mode & 0o077)
99
- )
100
- throw new Error("CLI state must be a private file (chmod 600).");
101
- return JSON.parse(await handle.readFile("utf8"));
102
- } catch (error) {
103
- if (error.code === "ENOENT") return null;
104
- throw error;
105
- } finally {
106
- await handle?.close();
107
- }
108
- }
109
- export async function writePrivate(file, data) {
110
- await mkdir(dirname(file), { recursive: true, mode: 0o700 });
111
- const temporary = `${file}.${randomUUID()}`;
112
- const handle = await open(temporary, "wx", 0o600);
113
- try {
114
- await handle.writeFile(JSON.stringify(data, null, 2) + "\n");
115
- await handle.sync();
116
- } finally {
117
- await handle.close();
118
- }
119
- try {
120
- await rename(temporary, file);
121
- } finally {
122
- await unlink(temporary).catch(() => {});
123
- }
124
- }
125
- export const profilePath = (target) =>
126
- join(configRoot(), `profile-${key(origin(target))}.json`);
127
- export const statePath = (target, scope, root) =>
128
- join(
129
- configRoot(),
130
- `deploy-${key(JSON.stringify([origin(target), scope, root]))}.json`,
131
- );
132
- export class APIError extends Error {
133
- constructor(status, body) {
134
- super(
135
- clean(
136
- body?.error?.message ||
137
- body?.error ||
138
- `API request failed (${status}).`,
139
- ),
140
- );
141
- this.status = status;
142
- this.code = body?.error?.code || body?.error;
143
- this.details = body?.error;
144
- }
145
- }
146
- export class API {
147
- constructor(target, profile, transport = fetch) {
148
- this.origin = origin(target);
149
- this.profile = profile;
150
- this.transport = transport;
151
- }
152
- async call(
153
- path,
154
- body,
155
- { method = body === undefined ? "GET" : "POST", idempotency } = {},
156
- ) {
157
- if (
158
- !/^\/[A-Za-z0-9/?=&%_.:-]+$/.test(path) ||
159
- path.startsWith("//") ||
160
- path.split("/").includes("..")
161
- )
162
- throw new Error("Invalid API path.");
163
- if (this.profile && this.profile.origin !== this.origin)
164
- throw new Error(
165
- "Credentials belong to a different installation. Sign in again.",
166
- );
167
- const headers = { Accept: "application/json" };
168
- if (body !== undefined) headers["Content-Type"] = "application/json";
169
- if (this.profile) {
170
- headers.Authorization = `Bearer ${this.profile.token}`;
171
- if (this.profile.scope_id)
172
- headers["X-Hakopod-Workspace"] = this.profile.scope_id;
173
- }
174
- if (idempotency) headers["Idempotency-Key"] = idempotency;
175
- let response;
176
- try {
177
- response = await this.transport(`${this.origin}/api/v1${path}`, {
178
- method,
179
- headers,
180
- body: body === undefined ? undefined : JSON.stringify(body),
181
- redirect: "error",
182
- signal: AbortSignal.timeout(35000),
183
- });
184
- } catch {
185
- throw new Error(
186
- "Cannot reach this installation. Any accepted work continues; run the command again to resume.",
187
- );
188
- }
189
- const reader = response.body?.getReader();
190
- const chunks = [];
191
- let length = 0;
192
- if (reader)
193
- for (;;) {
194
- const { done, value } = await reader.read();
195
- if (done) break;
196
- length += value.length;
197
- if (length > 2 * 1024 * 1024) {
198
- await reader.cancel();
199
- throw new Error("API response exceeds the CLI limit.");
200
- }
201
- chunks.push(Buffer.from(value));
202
- }
203
- let result;
204
- try {
205
- result = JSON.parse(Buffer.concat(chunks).toString());
206
- } catch {
207
- throw new Error(
208
- "This installation did not return JSON. Check the dashboard URL and server version.",
209
- );
210
- }
211
- if (!response.ok) throw new APIError(response.status, result);
212
- return result;
213
- }
214
- }
215
- export async function openBrowser(url) {
216
- const command =
217
- process.platform === "darwin"
218
- ? "open"
219
- : process.platform === "win32"
220
- ? "rundll32"
221
- : "xdg-open";
222
- const args =
223
- process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
224
- await execute(command, args, { timeout: 5000 }).catch(() => {});
225
- }
226
- export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
227
- export async function deviceLogin(
228
- api,
229
- { show, launch = openBrowser, wait = sleep, now = Date.now } = {},
230
- ) {
231
- const challenge = await api.call("/auth/device/start", {});
232
- const link = new URL(challenge.verification_uri_complete);
233
- if (
234
- link.origin !== api.origin ||
235
- link.pathname !== "/login/device" ||
236
- link.username ||
237
- link.password ||
238
- link.hash ||
239
- link.searchParams.get("user_code") !== challenge.user_code ||
240
- !/^[A-Z2-7]{4}-[A-Z2-7]{4}$/.test(challenge.user_code) ||
241
- !/^[a-f0-9]{64}$/.test(challenge.device_code)
242
- )
243
- throw new Error(
244
- "The server returned an invalid browser authorization link.",
245
- );
246
- if (
247
- !Number.isInteger(challenge.expires_in) ||
248
- challenge.expires_in < 1 ||
249
- challenge.expires_in > 900 ||
250
- !Number.isInteger(challenge.interval) ||
251
- challenge.interval < 5 ||
252
- challenge.interval > 30
253
- )
254
- throw new Error("The server returned invalid authorization timing.");
255
- show(
256
- `Sign in or create an account, choose a destination, and approve code ${challenge.user_code}.\n${link.href}`,
257
- );
258
- await launch(link.href);
259
- const deadline = now() + challenge.expires_in * 1000;
260
- let interval = challenge.interval;
261
- while (now() < deadline) {
262
- await wait(interval * 1000);
263
- if (now() >= deadline) break;
264
- try {
265
- const result = await api.call("/auth/device/token", {
266
- device_code: challenge.device_code,
267
- });
268
- if (
269
- !/^hs_[a-f0-9]{32}_[a-f0-9]{64}$/.test(result.access_token) ||
270
- result.user?.credential_type !== "cli" ||
271
- !result.user.project ||
272
- !result.user.environment ||
273
- (result.scope_id && !/^[a-f0-9]{32}$/.test(result.scope_id)) ||
274
- !(Date.parse(result.expires_at) > now())
275
- )
276
- throw new Error("The server returned an invalid scoped CLI session.");
277
- return {
278
- origin: api.origin,
279
- token: result.access_token,
280
- expires_at: result.expires_at,
281
- scope_id: result.scope_id || "",
282
- project: result.user.project,
283
- environment: result.user.environment,
284
- };
285
- } catch (error) {
286
- if (error.code === "authorization_pending") continue;
287
- if (error.code === "slow_down") {
288
- interval = Math.min(30, interval + 5);
289
- continue;
290
- }
291
- throw error;
292
- }
293
- }
294
- throw new Error(
295
- "Sign-in expired. Run hakopod login again to get a new code.",
296
- );
297
- }
package/src/main.mjs DELETED
@@ -1,490 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Writable } from "node:stream";
3
- import { parseArgs } from "node:util";
4
- import { createInterface } from "node:readline/promises";
5
- import { stdin, stdout } from "node:process";
6
- import { basename } from "node:path";
7
- import { unlink } from "node:fs/promises";
8
- import { randomUUID } from "node:crypto";
9
- import {
10
- API,
11
- APIError,
12
- cloud,
13
- clean,
14
- origin,
15
- repository,
16
- git,
17
- profilePath,
18
- statePath,
19
- readPrivate,
20
- writePrivate,
21
- deviceLogin,
22
- openBrowser,
23
- sleep,
24
- } from "./core.mjs";
25
-
26
- const help = `Hakopod — deploy committed Git repositories
27
-
28
- npx @hakopod/cli deploy
29
- npx @hakopod/cli login --url https://hakopod.example.com
30
- npx @hakopod/cli status --url https://hakopod.example.com
31
- npx @hakopod/cli logout --url https://hakopod.example.com
32
-
33
- Options: --url <dashboard origin> --name <application> --context <directory>
34
- --build <existing build ID> --yes (accept displayed reviews) --no-browser --help
35
-
36
- Requires Node 22.12+, Git, and a pushed GitHub.com or GitLab.com branch.
37
- Cloud is the default for noninteractive use. Self-hosted uses the same APIs.
38
- Credentials are saved per installation with owner-only file permissions.
39
- `;
40
- let rl;
41
- const say = (value) => stdout.write(`${clean(value)}\n`);
42
- const show = (value) =>
43
- stdout.write(
44
- String(value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, "") + "\n",
45
- );
46
- async function ask(label, fallback = "") {
47
- if (!stdin.isTTY) {
48
- if (fallback) return fallback;
49
- throw new Error(`${label}: run in an interactive terminal.`);
50
- }
51
- rl ||= createInterface({ input: stdin, output: stdout });
52
- return (
53
- (
54
- await rl.question(`${label}${fallback ? ` [${clean(fallback)}]` : ""}: `)
55
- ).trim() || fallback
56
- );
57
- }
58
- async function askSecret(label) {
59
- if (!stdin.isTTY) throw new Error("Secret input requires an interactive terminal.");
60
- rl?.close(); rl = undefined;
61
- let muted = false;
62
- const output = new Writable({ write(chunk, encoding, done) { if (!muted) stdout.write(chunk, encoding); done(); } });
63
- const secretInput = createInterface({ input: stdin, output, terminal: true });
64
- try {
65
- const result = secretInput.question(`${label} (hidden): `);
66
- muted = true;
67
- return await result;
68
- } finally { secretInput.close(); stdout.write("\n"); }
69
- }
70
- async function setupSecrets(api, config, plan) {
71
- const missing = plan.missing_secrets || [];
72
- if (!missing.length) return;
73
- if (!stdin.isTTY) throw new Error(`Missing application secrets: ${missing.map(clean).join(", ")}. Save them in the dashboard or through POST /api/v1/secrets/{name}, then retry. No deployment was submitted.`);
74
- for (const name of missing) {
75
- say(`Missing secret: ${name}`);
76
- const mode = await choose("Secret value", [
77
- { label: "Enter an existing value (hidden)", value: "value" },
78
- { label: "Generate a new random password (not a provider credential)", value: "generate" },
79
- { label: "Cancel deployment", value: "cancel" },
80
- ]);
81
- if (mode === "cancel") throw new Error("Secret setup cancelled. No deployment was submitted.");
82
- const body = mode === "generate" ? { generate: true } : { value: await askSecret(clean(name)) };
83
- const query = new URLSearchParams({ project: config.project, environment: config.environment, application: plan.spec.name });
84
- try { await api.call(`/secrets/${encodeURIComponent(name)}?${query}`, body); }
85
- finally { delete body.value; }
86
- }
87
- }
88
- async function choose(label, items) {
89
- if (!items.length) throw new Error(`No ${label.toLowerCase()} available.`);
90
- items.forEach((item, index) => say(`${index + 1}. ${item.label}`));
91
- for (;;) {
92
- const value = Number(await ask(label, items.length === 1 ? "1" : ""));
93
- if (Number.isInteger(value) && items[value - 1])
94
- return items[value - 1].value;
95
- say("Choose one of the numbers above.");
96
- }
97
- }
98
- async function confirm(label, yes) {
99
- if (yes) {
100
- say(`${label}: accepted with --yes`);
101
- return;
102
- }
103
- if (!/^y(es)?$/i.test(await ask(`${label} (y/N)`, "n")))
104
- throw new Error(
105
- "Stopped. Saved configuration remains available for your next attempt.",
106
- );
107
- }
108
- async function waitFor(read, finished, label, timeout = 30 * 60 * 1000) {
109
- let previous = "";
110
- const until = Date.now() + timeout;
111
- while (Date.now() < until) {
112
- const item = await read();
113
- if (item.status !== previous) {
114
- say(`${label}: ${item.status}`);
115
- previous = item.status;
116
- }
117
- if (finished(item)) return item;
118
- await sleep(5000);
119
- }
120
- throw new Error(
121
- `${label} is still running. Use the same deploy command to resume, or status to inspect it.`,
122
- );
123
- }
124
- async function main() {
125
- const { values: flags, positionals } = parseArgs({
126
- allowPositionals: true,
127
- options: {
128
- url: { type: "string" },
129
- name: { type: "string" },
130
- context: { type: "string" },
131
- build: { type: "string" },
132
- yes: { type: "boolean" },
133
- "no-browser": { type: "boolean" },
134
- help: { type: "boolean" },
135
- },
136
- });
137
- if (flags.help) {
138
- show(help);
139
- return;
140
- }
141
- const command = positionals[0] || "deploy";
142
- if (
143
- positionals.length > 1 ||
144
- !["deploy", "login", "logout", "status"].includes(command)
145
- )
146
- throw new Error(help);
147
- let target = flags.url;
148
- if (!target && stdin.isTTY) {
149
- const kind = await choose("Deployment target", [
150
- { label: "Hakopod Cloud", value: "cloud" },
151
- { label: "Self-hosted Hakopod", value: "self" },
152
- ]);
153
- target = kind === "cloud" ? cloud : await ask("Self-hosted dashboard URL");
154
- }
155
- target = origin(target || cloud);
156
- const file = profilePath(target);
157
- let profile = await readPrivate(file);
158
- if (command === "logout") {
159
- if (profile) {
160
- try {
161
- await new API(target, profile).call("/auth/logout", {});
162
- say("CLI session revoked.");
163
- } catch {
164
- say(
165
- `Server revocation was unavailable. Revoke this session in ${target}/settings/security.`,
166
- );
167
- }
168
- await unlink(file);
169
- say("Removed local credentials.");
170
- } else say("No saved login for this installation.");
171
- return;
172
- }
173
- let api = new API(target, profile);
174
- if (
175
- command === "login" ||
176
- !profile ||
177
- Date.parse(profile.expires_at) <= Date.now()
178
- )
179
- profile = null;
180
- if (profile) {
181
- try {
182
- const me = await api.call("/me");
183
- if (
184
- me.credential_type !== "cli" ||
185
- me.project !== profile.project ||
186
- me.environment !== profile.environment
187
- )
188
- throw new Error(
189
- "The saved CLI destination no longer matches. Run login again.",
190
- );
191
- } catch (error) {
192
- if (error.status === 401) profile = null;
193
- else throw error;
194
- }
195
- }
196
- if (!profile) {
197
- profile = await deviceLogin(new API(target), {
198
- show,
199
- launch: flags["no-browser"] ? async () => {} : openBrowser,
200
- });
201
- await writePrivate(file, profile);
202
- api = new API(target, profile);
203
- }
204
- say(`Destination: ${target} · ${profile.project} / ${profile.environment}`);
205
- if (command === "login") return;
206
- let source = await repository(process.cwd(), command !== "status");
207
- const local = statePath(
208
- target,
209
- [profile.scope_id, profile.project, profile.environment],
210
- source.root,
211
- );
212
- let saved = await readPrivate(local);
213
- if (flags.build) {
214
- if (!/^[a-f0-9]{32}$/.test(flags.build))
215
- throw new Error("Use the build ID shown in the dashboard.");
216
- if (saved?.build && saved.build !== flags.build)
217
- throw new Error(
218
- "This directory already has a linked build for this destination.",
219
- );
220
- const linked = await api.call(`/builds/${flags.build}`);
221
- if (
222
- linked.project !== profile.project ||
223
- linked.environment !== profile.environment ||
224
- linked.repository !== source.repository ||
225
- linked.provider !== source.provider ||
226
- linked.branch !== source.branch
227
- )
228
- throw new Error(
229
- "Build does not match this repository and authorized destination.",
230
- );
231
- saved ||= { build: linked.id };
232
- await writePrivate(local, saved);
233
- }
234
- if (command === "status") {
235
- if (!saved?.build)
236
- throw new Error(
237
- "No saved deployment in this repository for this destination.",
238
- );
239
- const build = await api.call(`/builds/${saved.build}`);
240
- say(`Application: ${build.name}`);
241
- if (saved.run) {
242
- const run = await api.call(`/builds/${saved.build}/runs/${saved.run}`);
243
- say(`Build: ${run.status} ${run.conclusion}`);
244
- if (run.deployment_id) {
245
- const deployment = await api.call(`/deployments/${run.deployment_id}`);
246
- say(`Deployment: ${deployment.status}`);
247
- }
248
- }
249
- return;
250
- }
251
- let config;
252
- if (saved?.build) {
253
- config = await api.call(`/builds/${saved.build}`);
254
- if (
255
- config.repository !== source.repository ||
256
- config.provider !== source.provider ||
257
- config.branch !== source.branch ||
258
- config.project !== profile.project ||
259
- config.environment !== profile.environment
260
- )
261
- throw new Error(
262
- "This directory is linked to another source or destination. Use a separate checkout or restore its original branch.",
263
- );
264
- if (
265
- (flags.name && flags.name !== config.name) ||
266
- (flags.context && flags.context !== config.context_path)
267
- )
268
- throw new Error(
269
- "This deployment is already linked. Edit its build configuration in the dashboard before continuing.",
270
- );
271
- } else {
272
- let connections = (await api.call("/git/connections")).items.filter(
273
- (item) =>
274
- item.provider === source.provider &&
275
- item.enabled &&
276
- item.capabilities.builds,
277
- );
278
- if (!connections.length) {
279
- const url = `${target}/settings/git/connections/new`;
280
- show(
281
- `Connect ${source.provider} in the dashboard for this destination, then return here.\n${url}`,
282
- );
283
- if (!flags["no-browser"]) await openBrowser(url);
284
- await ask("Press Enter after connecting Git", "continue");
285
- connections = (await api.call("/git/connections")).items.filter(
286
- (item) =>
287
- item.provider === source.provider &&
288
- item.enabled &&
289
- item.capabilities.builds,
290
- );
291
- }
292
- const connection_id = await choose(
293
- "Git connection",
294
- connections.map((item) => ({ label: item.name, value: item.id })),
295
- );
296
- const name =
297
- flags.name ||
298
- (await ask(
299
- "Application name",
300
- basename(source.root)
301
- .toLowerCase()
302
- .replace(/[^a-z0-9-]/g, "-")
303
- .slice(0, 40),
304
- ));
305
- const context_path =
306
- flags.context || (await ask("Directory inside repository", "."));
307
- let input = {
308
- project: profile.project,
309
- environment: profile.environment,
310
- name,
311
- provider: source.provider,
312
- repository: source.repository,
313
- branch: source.branch,
314
- connection_id,
315
- context_path,
316
- service: "web",
317
- public: false,
318
- auto_build: false,
319
- auto_deploy: false,
320
- };
321
- const detected = await api.call("/builds/detect", input);
322
- if (detected.commit_sha !== source.commit)
323
- throw new Error(
324
- "The remote branch changed during detection. Pull and review it, then retry.",
325
- );
326
- show(
327
- `Detected ${detected.framework?.framework || "Dockerfile"} at ${source.commit}\n${(detected.warnings || []).join("\n")}`,
328
- );
329
- input = {
330
- ...input,
331
- mode: detected.mode,
332
- framework: detected.framework,
333
- dockerfile: detected.dockerfile,
334
- port: detected.framework?.port || 8080,
335
- size: "small",
336
- };
337
- if (input.framework) {
338
- show(JSON.stringify(input.framework, null, 2));
339
- if (
340
- !flags.yes &&
341
- /^y(es)?$/i.test(await ask("Edit detected commands? (y/N)", "n"))
342
- ) {
343
- for (const field of [
344
- "install_command",
345
- "build_command",
346
- "start_command",
347
- "output_directory",
348
- ]) {
349
- if (input.framework[field] !== undefined)
350
- input.framework[field] = await ask(
351
- field.replaceAll("_", " "),
352
- input.framework[field],
353
- );
354
- }
355
- }
356
- }
357
- input.port = Number(await ask("Service port", String(input.port)));
358
- if (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535)
359
- throw new Error("Choose a service port between 1 and 65535.");
360
- if (input.framework) input.framework.port = input.port;
361
- input.public = /^y(es)?$/i.test(
362
- await ask("Expose this web service publicly? (y/N)", "n"),
363
- );
364
- show(`Review build settings\n${JSON.stringify(input, null, 2)}`);
365
- await confirm("Save these build settings", flags.yes);
366
- // A create response can be lost. Discover the unique saved name before retrying.
367
- const existing = (
368
- await api.call(
369
- `/builds?project=${encodeURIComponent(profile.project)}&environment=${encodeURIComponent(profile.environment)}`,
370
- )
371
- ).items.filter((item) => item.name === name);
372
- if (existing.length)
373
- throw new Error(
374
- "A build with this name already exists. Rerun with --build plus its ID from the dashboard, or choose another application name.",
375
- );
376
- config = await api.call("/builds", input);
377
- saved = { build: config.id };
378
- await writePrivate(local, saved);
379
- }
380
- say(`Application: ${config.name} · ${source.repository} · ${source.branch}`);
381
- if (config.installed_revision !== config.revision) {
382
- const preview = await api.call(`/builds/${config.id}/preview`, {});
383
- show(
384
- `Workflow to write: ${preview.workflow_path}\n${preview.workflow}\nRequirements:\n${preview.requirements.join("\n")}`,
385
- );
386
- await confirm(
387
- "Commit this workflow to the repository default branch (fast-forward locally if selected)",
388
- flags.yes,
389
- );
390
- const installed = await api.call(`/builds/${config.id}/install`, {
391
- expected_config_revision: config.revision,
392
- });
393
- config = installed.config;
394
- if (!/^[a-f0-9]{40,64}$/.test(installed.commit_sha))
395
- throw new Error("The provider returned an invalid workflow commit.");
396
- if (!installed.workflow_branch)
397
- throw new Error(
398
- "The server must report the installed workflow branch. Upgrade this installation before continuing.",
399
- );
400
- if (installed.workflow_branch === source.branch) {
401
- if (await git(["status", "--porcelain"], source.root))
402
- throw new Error(
403
- "Local files changed during review. Commit or stash them, pull the workflow commit, and rerun deploy.",
404
- );
405
- await git(["fetch", "origin", source.branch], source.root);
406
- if (
407
- (await git(["rev-parse", "FETCH_HEAD"], source.root)) !==
408
- installed.commit_sha
409
- )
410
- throw new Error(
411
- "The remote branch changed after workflow installation. Pull and review it before retrying.",
412
- );
413
- await git(["merge", "--ff-only", installed.commit_sha], source.root);
414
- source = await repository(source.root);
415
- }
416
- say(
417
- `Workflow installed on ${installed.workflow_branch}. Source remains ${source.branch}.`,
418
- );
419
- say(`Workflow ready at ${source.commit}.`);
420
- }
421
- if (saved.commit !== source.commit || saved.revision !== config.revision) {
422
- saved = {
423
- build: config.id,
424
- commit: source.commit,
425
- revision: config.revision,
426
- idempotency: `cli-${randomUUID()}`,
427
- };
428
- await writePrivate(local, saved);
429
- }
430
- if (!saved.run) {
431
- await confirm(
432
- `Build committed source ${source.commit} using your Git provider`,
433
- flags.yes,
434
- );
435
- const run = await api.call(
436
- `/builds/${config.id}/run`,
437
- { expected_config_revision: config.revision, commit: source.commit },
438
- { idempotency: saved.idempotency },
439
- );
440
- saved.run = run.id;
441
- await writePrivate(local, saved);
442
- }
443
- const base = `/builds/${config.id}/runs/${saved.run}`;
444
- const run = await waitFor(
445
- () => api.call(base),
446
- (item) => ["completed", "failed", "cancelled"].includes(item.status),
447
- "Build",
448
- );
449
- if (run.status !== "completed" || run.conclusion !== "success" || !run.image)
450
- throw new Error(
451
- `Build did not succeed. Inspect ${target}/builds/${config.id}. Fix it and push a new commit to start another build.`,
452
- );
453
- let deploymentID = run.deployment_id;
454
- if (!deploymentID) {
455
- const plan = await api.call(`${base}/plan`, {});
456
- show(
457
- `Review deployment\n${JSON.stringify({ image: run.image, changes: plan.changes, warnings: plan.warnings }, null, 2)}`,
458
- );
459
- await setupSecrets(api, config, plan);
460
- await confirm("Deploy this built image", flags.yes);
461
- const deployment = await api.call(`${base}/deploy`, {
462
- expected_revision: plan.expected_revision,
463
- expected_config_revision: plan.expected_config_revision,
464
- });
465
- deploymentID = deployment.id;
466
- }
467
- const deployment = await waitFor(
468
- () => api.call(`/deployments/${deploymentID}`),
469
- (item) =>
470
- ["succeeded", "failed", "cancelled", "superseded"].includes(item.status),
471
- "Deployment",
472
- );
473
- if (deployment.status !== "succeeded")
474
- throw new Error(
475
- `Deployment ${deployment.status}. Inspect ${target}/applications/${deployment.application_id} for diagnostics.`,
476
- );
477
- say(
478
- `Deployment succeeded. ${target}/applications/${deployment.application_id}`,
479
- );
480
- }
481
- main()
482
- .catch((error) => {
483
- if (error instanceof APIError && error.code === "approval_required") {
484
- say(
485
- "Deployment awaits a Cloud Team review. Open the workspace approvals in the dashboard; rerun deploy after approval.",
486
- );
487
- } else show(error.message || "The command could not finish.");
488
- process.exitCode = 1;
489
- })
490
- .finally(() => rl?.close());