@hyphacommerce/cli 0.0.0-stage → 0.1.0-beta.3

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/dist/main.mjs ADDED
@@ -0,0 +1,3960 @@
1
+ #!/usr/bin/env node
2
+ import { defineCommand, runMain } from "citty";
3
+ import * as p from "@clack/prompts";
4
+ import { lookup } from "node:dns";
5
+ import { Resolver, resolve4, resolve6 } from "node:dns/promises";
6
+ import { request } from "node:http";
7
+ import { request as request$1 } from "node:https";
8
+ import { isIP } from "node:net";
9
+ import { createHash, randomBytes, randomInt } from "node:crypto";
10
+ import { chmod, cp, mkdir, mkdtemp, readFile, readdir, readlink, rm, stat, symlink, writeFile } from "node:fs/promises";
11
+ import { basename, join, relative, resolve, sep } from "node:path";
12
+ import { existsSync, readdirSync } from "node:fs";
13
+ import { spawn } from "node:child_process";
14
+ import { tmpdir } from "node:os";
15
+ //#region src/api.ts
16
+ var ApiError = class extends Error {
17
+ status;
18
+ code;
19
+ constructor(method, path, status, body) {
20
+ const parsed = body ?? {};
21
+ super(`${method} ${path}: ${status} ${parsed.code ?? ""} ${parsed.error ?? ""}`.trim());
22
+ this.status = status;
23
+ this.code = parsed.code;
24
+ }
25
+ };
26
+ /** Every name to 127.0.0.1: this machine's deployment, whatever its `*.localhost`. */
27
+ const loopback = (_host, options, callback) => options.all ? callback(null, [{
28
+ address: "127.0.0.1",
29
+ family: 4
30
+ }]) : callback(null, "127.0.0.1", 4);
31
+ /** A lookup through `resolve4`/`resolve6` (IPv4 first), falling back to `fallback` for
32
+ * IP literals and for names they don't know (a split-horizon or private name). */
33
+ function lookupVia(resolve4, resolve6, fallback) {
34
+ return (host, options, callback) => {
35
+ if (isIP(host)) return fallback(host, options, callback);
36
+ const family = options.family === 4 || options.family === "IPv4" ? 4 : options.family === 6 || options.family === "IPv6" ? 6 : 0;
37
+ (async () => {
38
+ const found = await addressesOf(host, family, resolve4, resolve6);
39
+ if (found.length === 0) fallback(host, options, callback);
40
+ else if (options.all) callback(null, found);
41
+ else callback(null, found[0].address, found[0].family);
42
+ })();
43
+ };
44
+ }
45
+ /** `host`'s addresses in `family` (0 for both, IPv4 first); none when a resolver fails. */
46
+ async function addressesOf(host, family, resolve4, resolve6) {
47
+ const [v4, v6] = await Promise.all([family === 6 ? [] : resolve4(host).catch(() => []), family === 4 ? [] : resolve6(host).catch(() => [])]);
48
+ return [...v4.map((address) => ({
49
+ address,
50
+ family: 4
51
+ })), ...v6.map((address) => ({
52
+ address,
53
+ family: 6
54
+ }))];
55
+ }
56
+ const resolver = new Resolver({
57
+ timeout: 3e3,
58
+ tries: 2
59
+ });
60
+ resolver.setServers(["1.1.1.1", "8.8.8.8"]);
61
+ /** Public resolvers first, then this machine's. */
62
+ const freshLookup = lookupVia((host) => resolver.resolve4(host), (host) => resolver.resolve6(host), lookup);
63
+ function send(d, method, path, body, token) {
64
+ const target = new URL(path, `${d.scheme}://${d.domains.api}`);
65
+ const request$2 = target.protocol === "https:" ? request$1 : request;
66
+ const payload = body === void 0 ? void 0 : JSON.stringify(body);
67
+ return new Promise((resolve, reject) => {
68
+ const req = request$2(target, {
69
+ method,
70
+ timeout: 15e3,
71
+ headers: {
72
+ accept: "application/json",
73
+ ...payload ? { "content-type": "application/json" } : {},
74
+ ...token ? { authorization: `Bearer ${token}` } : {}
75
+ },
76
+ lookup: d.target === "local" ? loopback : freshLookup
77
+ }, (res) => {
78
+ let text = "";
79
+ res.setEncoding("utf8");
80
+ res.on("data", (chunk) => text += chunk);
81
+ res.on("end", () => {
82
+ let parsed;
83
+ try {
84
+ parsed = text ? JSON.parse(text) : void 0;
85
+ } catch {
86
+ parsed = text;
87
+ }
88
+ resolve({
89
+ status: res.statusCode ?? 0,
90
+ body: parsed
91
+ });
92
+ });
93
+ });
94
+ req.on("timeout", () => req.destroy(/* @__PURE__ */ new Error("timed out")));
95
+ req.on("error", reject);
96
+ req.end(payload);
97
+ });
98
+ }
99
+ /** Whether `GET /health` answers 200 through Caddy. */
100
+ async function healthy(d) {
101
+ try {
102
+ return (await send(d, "GET", "/health")).status === 200;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+ /** Polls the API's health until it answers or `seconds` pass. The first time, Caddy is
108
+ * also getting the certificates, which can take a minute. */
109
+ async function waitForHealth(d, seconds) {
110
+ const until = Date.now() + seconds * 1e3;
111
+ while (Date.now() < until) {
112
+ if (await healthy(d)) return true;
113
+ await new Promise((r) => setTimeout(r, 3e3));
114
+ }
115
+ return false;
116
+ }
117
+ /** Polls `target` until it answers anything but a server error, or `seconds` pass: a new
118
+ * app's custom domain (its DNS record and certificate) can take a minute or two. With
119
+ * a deployment on this machine, through 127.0.0.1. */
120
+ async function waitForAnswer(target, seconds, d) {
121
+ const until = Date.now() + seconds * 1e3;
122
+ const parsed = new URL(target);
123
+ const request$3 = parsed.protocol === "https:" ? request$1 : request;
124
+ while (Date.now() < until) {
125
+ const status = await new Promise((resolve) => {
126
+ const req = request$3(parsed, {
127
+ method: "GET",
128
+ timeout: 15e3,
129
+ lookup: d?.target === "local" ? loopback : freshLookup
130
+ }, (res) => {
131
+ res.resume();
132
+ resolve(res.statusCode ?? 0);
133
+ });
134
+ req.on("timeout", () => req.destroy(/* @__PURE__ */ new Error("timed out")));
135
+ req.on("error", () => resolve(0));
136
+ req.end();
137
+ });
138
+ if (status > 0 && status < 500) return true;
139
+ await new Promise((r) => setTimeout(r, 3e3));
140
+ }
141
+ return false;
142
+ }
143
+ /** A staff session: the API's admin routes, as the owner. */
144
+ var Staff = class Staff {
145
+ d;
146
+ token;
147
+ constructor(d, token) {
148
+ this.d = d;
149
+ this.token = token;
150
+ }
151
+ /** An API key's or an existing session's token (`hypha_sk_…`, `hypha_sess_…`). */
152
+ static withToken(d, token) {
153
+ return new Staff(d, token);
154
+ }
155
+ static async login(d, email, password) {
156
+ const { status, body } = await send(d, "POST", "/admin/auth/login", {
157
+ email,
158
+ password
159
+ });
160
+ if (status !== 200) throw new ApiError("POST", "/admin/auth/login", status, body);
161
+ const answer = body;
162
+ if (answer.status !== "authenticated" || !answer.session) throw new Error(`logging in needs ${answer.status} (the owner has two-factor on): set the storefront up in the admin`);
163
+ return new Staff(d, answer.session.token);
164
+ }
165
+ async call(method, path, body) {
166
+ const { status, body: answer } = await send(this.d, method, path, body, this.token);
167
+ if (status < 200 || status >= 300) throw new ApiError(method, path, status, answer);
168
+ return answer;
169
+ }
170
+ };
171
+ /** `GET target` as JSON (an app's manifest): its body, or `undefined` when it doesn't
172
+ * answer 200 with JSON. On this machine, through 127.0.0.1 like the API's calls. */
173
+ async function getJson(d, target) {
174
+ const parsed = new URL(target);
175
+ const request$4 = parsed.protocol === "https:" ? request$1 : request;
176
+ return new Promise((resolve) => {
177
+ const req = request$4(parsed, {
178
+ method: "GET",
179
+ timeout: 15e3,
180
+ headers: { accept: "application/json" },
181
+ lookup: d.target === "local" ? loopback : freshLookup
182
+ }, (res) => {
183
+ let text = "";
184
+ res.setEncoding("utf8");
185
+ res.on("data", (chunk) => text += chunk);
186
+ res.on("end", () => {
187
+ if (res.statusCode !== 200) return resolve(void 0);
188
+ try {
189
+ resolve(JSON.parse(text));
190
+ } catch {
191
+ resolve(void 0);
192
+ }
193
+ });
194
+ });
195
+ req.on("timeout", () => req.destroy(/* @__PURE__ */ new Error("timed out")));
196
+ req.on("error", () => resolve(void 0));
197
+ req.end();
198
+ });
199
+ }
200
+ //#endregion
201
+ //#region src/templates.ts
202
+ const TEMPLATES = join(import.meta.dirname, "..", "templates");
203
+ /** Where a checkout of Hypha would be around this CLI: the repository when it runs from
204
+ * one (`pnpm hypha …`, or the package built in it), `node_modules` when installed. */
205
+ const REPO = join(import.meta.dirname, "..", "..", "..");
206
+ /** Whether the CLI runs from a checkout of Hypha, which building anything needs: the
207
+ * images from source, a deployment's host crate for its spores, the Workers. */
208
+ function inCheckout() {
209
+ return existsSync(join(REPO, "Cargo.toml")) && existsSync(join(REPO, "crates", "hypha-host-axum"));
210
+ }
211
+ /** The checkout, or a clear refusal: the installed CLI deploys the published images and
212
+ * can't build. */
213
+ function requireRepo(what) {
214
+ if (inCheckout()) return REPO;
215
+ throw new Error(`${what} needs a checkout of Hypha (github.com/hyphacommerce/hypha): clone it and run \`pnpm hypha\` from there`);
216
+ }
217
+ function composeFile() {
218
+ return readFile(join(TEMPLATES, "vps", "compose.yaml"), "utf8");
219
+ }
220
+ /** The settings file's JSON Schema, for editors: the copy the package ships (made by its
221
+ * build), or the checkout's. */
222
+ async function configSchema() {
223
+ const shipped = join(TEMPLATES, "hypha.config.schema.json");
224
+ if (existsSync(shipped)) return readFile(shipped, "utf8");
225
+ return readFile(join(requireRepo("The settings schema"), "hypha.config.schema.json"), "utf8");
226
+ }
227
+ /** Caddy's configuration: one site per domain, to its service. Over `https`, Caddy gets
228
+ * and renews the certificates itself (Let's Encrypt), once the domains point at the
229
+ * server. */
230
+ function caddyfile(d, acmeEmail) {
231
+ const site = (host, upstream, compress) => caddySite(d, host, upstream, compress);
232
+ const global = d.scheme === "https" ? acmeEmail ? [
233
+ "{",
234
+ `\temail ${acmeEmail}`,
235
+ "}"
236
+ ] : [] : [
237
+ "{",
238
+ " auto_https off",
239
+ "}"
240
+ ];
241
+ const sites = [
242
+ site(d.domains.api, "api:3000", true),
243
+ site(d.domains.media, "s3:8333", false),
244
+ ...d.domains.admin ? [site(d.domains.admin, "admin:3000", true)] : [],
245
+ ...d.domains.storefront ? [site(d.domains.storefront, "storefront:3000", true)] : []
246
+ ];
247
+ return [
248
+ "# Written by `hypha init`; `hypha init --force` writes it again.",
249
+ "",
250
+ ...global,
251
+ "",
252
+ sites.join("\n\n"),
253
+ "",
254
+ "# The co-located apps' sites, written by `hypha deploy`.",
255
+ CADDY_IMPORT,
256
+ ""
257
+ ].join("\n");
258
+ }
259
+ /** One Caddy site: `host` to `upstream`, compressed or not. */
260
+ function caddySite(d, host, upstream, compress = true) {
261
+ return [
262
+ `${url(d, host)} {`,
263
+ ...compress ? [" encode zstd gzip"] : [],
264
+ `\treverse_proxy ${upstream}`,
265
+ "}"
266
+ ].join("\n");
267
+ }
268
+ /** The apps' Caddy sites, each to its container's port. */
269
+ function appsCaddy(d, coLocated) {
270
+ return [
271
+ "# Written by `hypha deploy` from hypha.json's apps.",
272
+ ...coLocated.map(({ entry, profile }) => ["", caddySite(d, appDomain(d, entry), `${service(entry)}:${profile.port}`)].join("\n")),
273
+ ""
274
+ ].join("\n");
275
+ }
276
+ /** SeaweedFS's S3 users: the API's key, and anonymous reads of the media bucket (public
277
+ * files are served by plain URL, so static pages can keep them). */
278
+ function seaweedConfig(accessKey, secretKey) {
279
+ return `${JSON.stringify({ identities: [{
280
+ name: "hypha",
281
+ credentials: [{
282
+ accessKey,
283
+ secretKey
284
+ }],
285
+ actions: [
286
+ "Admin",
287
+ "Read",
288
+ "List",
289
+ "Tagging",
290
+ "Write"
291
+ ]
292
+ }, {
293
+ name: "anonymous",
294
+ actions: ["Read:hypha-media"]
295
+ }] }, null, 2)}\n`;
296
+ }
297
+ /** A TOML string: a JSON string is a valid TOML basic string. */
298
+ function str$2(value) {
299
+ return JSON.stringify(value);
300
+ }
301
+ /** `[email]` as TOML: the sender and the from address (the secrets stay in `.env`). */
302
+ function emailToml(email) {
303
+ if (email.sender === "log") return [
304
+ "# Emails are only written to the API's log until a sender is set:",
305
+ "# [email] sender = \"resend\" (HYPHA_RESEND_API_KEY in .env) or \"smtp\" ([email.smtp],",
306
+ "# HYPHA_SMTP_PASSWORD in .env), and the from address. `hypha init --force` asks again.",
307
+ "# [email]"
308
+ ];
309
+ const lines = [
310
+ "[email]",
311
+ `sender = ${str$2(email.sender)}`,
312
+ `from = ${str$2(email.from)}`
313
+ ];
314
+ if (email.sender === "smtp") lines.push("", "[email.smtp]", `host = ${str$2(email.host)}`, `port = ${email.port}`, `tls = ${str$2(email.tls)}`, ...email.username ? [`username = ${str$2(email.username)}`] : []);
315
+ return lines;
316
+ }
317
+ /** The API's settings file, mostly empty: every key has a default, and the environment
318
+ * in compose.yaml sets the deployment's own. */
319
+ function configToml(target = "vps", email = { sender: "log" }) {
320
+ return [
321
+ "#:schema ./hypha.config.schema.json",
322
+ ...target === "cloudflare" ? [
323
+ "# The API's settings. Every key has a default; the Worker reads",
324
+ "# this file as its HYPHA_CONFIG variable, under the addresses and storage that",
325
+ "# `hypha deploy` sets. After a change: `hypha deploy` (it also resizes the rate",
326
+ "# limiters to [rate_limits])."
327
+ ] : [
328
+ "# The API's settings. Every key has a default; `compose.yaml`",
329
+ "# sets the addresses, storage and proxies through the environment, which wins.",
330
+ "# After a change: `hypha deploy` (or `docker compose up -d api` on the server)."
331
+ ],
332
+ "",
333
+ ...emailToml(email),
334
+ "",
335
+ "# [rate_limits]",
336
+ "# [dispatch]",
337
+ ""
338
+ ].join("\n");
339
+ }
340
+ /** The email provider's secret in `.env`, which `deploy` passes to the API. */
341
+ function setEmailSecret(env, email) {
342
+ if (email.sender === "resend") {
343
+ env.comment("").comment("Resend's API key, for sending emails.");
344
+ env.set("HYPHA_RESEND_API_KEY", email.apiKey);
345
+ } else if (email.sender === "smtp" && email.password) {
346
+ env.comment("").comment("The SMTP server's password, for sending emails.");
347
+ env.set("HYPHA_SMTP_PASSWORD", email.password);
348
+ }
349
+ return env;
350
+ }
351
+ function secret(bytes = 32) {
352
+ return randomBytes(bytes).toString("hex");
353
+ }
354
+ /** A password to type once and change: 24 characters, no lookalikes to misread. */
355
+ function password() {
356
+ const alphabet = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
357
+ return Array.from(randomBytes(24), (b) => alphabet[b % 54]).join("");
358
+ }
359
+ /** A new deployment's `.env`: the secrets made here, the addresses from the domains. */
360
+ function newEnv(d, owner) {
361
+ const env = new EnvFile();
362
+ env.comment("Written by `hypha init`. Secrets: keep this file private, and\nkeep it (HYPHA_SECRET_KEY seals two-factor secrets; losing it locks staff out).").set("POSTGRES_PASSWORD", secret()).set("HYPHA_SECRET_KEY", secret()).set("S3_ACCESS_KEY", secret(10)).set("S3_SECRET_KEY", secret()).comment("").comment("The first owner, created on the first start (change the password after logging in).").set("HYPHA_OWNER_EMAIL", owner.email).set("HYPHA_OWNER_PASSWORD", password()).set("HYPHA_STORE_NAME", owner.storeName).comment("").comment("Addresses (from hypha.json's domains).").set("API_URL", url(d, d.domains.api)).set("MEDIA_URL", url(d, d.domains.media)).set("MEDIA_HOST", d.domains.media).set("ADMIN_URL", d.domains.admin ? url(d, d.domains.admin) : "").set("COMPOSE_PROFILES", apps$1(d).join(","));
363
+ if (d.domains.storefront) env.comment("").comment("The storefront's public address, for canonical links and link previews.").set("STOREFRONT_URL", url(d, d.domains.storefront)).comment("The storefront's publishable key and webhook secret: `hypha deploy` creates them.").set("STOREFRONT_KEY", "").set("HYPHA_WEBHOOK_SECRET", "");
364
+ return env;
365
+ }
366
+ /** A Cloudflare deployment's `.env`: kept here, never uploaded as a file. `hypha deploy`
367
+ * passes the token to wrangler and `cf`, the database URL to setup and Hyperdrive, and the
368
+ * rest to the Workers as secrets. */
369
+ function newCloudflareEnv(owner, databaseUrl, options) {
370
+ const env = new EnvFile().comment("Written by `hypha init --target cloudflare`. Secrets: keep this file\nprivate, and keep it (HYPHA_SECRET_KEY seals two-factor secrets; losing it locks staff out).").set("HYPHA_SECRET_KEY", secret()).comment("").comment("The Cloudflare API token everything deploys with (revoke it in the dashboard to stop that).").set("CLOUDFLARE_API_TOKEN", options.token).comment("").comment("The database's direct URL: `hypha deploy` sets it up and points Hyperdrive at it.").set("DATABASE_URL", databaseUrl).comment("").comment("R2's S3 keys for files (derived from an R2-capable token: its ID, the SHA-256 of its value); empty: off.").set("R2_ACCESS_KEY_ID", options.r2.id).set("R2_SECRET_ACCESS_KEY", options.r2.secret).comment("").comment("The first owner, created by the first deploy (change the password after logging in).").set("HYPHA_OWNER_EMAIL", owner.email).set("HYPHA_OWNER_PASSWORD", password()).set("HYPHA_STORE_NAME", owner.storeName);
371
+ if (options.storefront) env.comment("").comment("The storefront's publishable key and webhook secret: `hypha deploy` creates them.").set("STOREFRONT_KEY", "").set("HYPHA_WEBHOOK_SECRET", "");
372
+ return env;
373
+ }
374
+ //#endregion
375
+ //#region src/spores.ts
376
+ /** Hypha's repository, as spores outside it name it in their git dependencies. */
377
+ const HYPHA_GIT = "https://github.com/hyphacommerce/hypha";
378
+ /** The first-party spores, by name: each in its own repository. */
379
+ const FIRST_PARTY_SPORES = { stripe: {
380
+ crate: "hypha-spore-stripe",
381
+ git: "git@github.com:hyphacommerce/spore-stripe.git",
382
+ spore: "hypha_spore_stripe::Stripe",
383
+ routes: "hypha_spore_stripe::stripe_routes"
384
+ } };
385
+ const NAME$2 = /^[a-z][a-z0-9_]*$/;
386
+ const REV$1 = /^[0-9a-f]{40}$/;
387
+ const RUST_PATH = /^[a-z_][a-z0-9_]*(::[A-Za-z_][A-Za-z0-9_]*)+$/;
388
+ /** The spore's name. */
389
+ function sporeName(entry) {
390
+ return entry.name;
391
+ }
392
+ /** `hypha.json`'s `spores`, checked: every problem a message naming `where`. A
393
+ * first-party name alone is filled in from its repository. The names may not extend one
394
+ * another (`stripe`, `stripe_link`), as the hosts check. */
395
+ function normalizeSpores(raw, where) {
396
+ if (!Array.isArray(raw)) throw new Error(`${where}: \`spores\` is a list`);
397
+ const out = [];
398
+ const known = Object.keys(FIRST_PARTY_SPORES).join(", ");
399
+ for (const item of raw) {
400
+ let o;
401
+ if (typeof item === "string") {
402
+ const first = FIRST_PARTY_SPORES[item];
403
+ if (!first) throw new Error(`${where}: ${JSON.stringify(item)} isn't a first-party spore (${known}): give {name, crate, spore, and git, version or path}`);
404
+ o = {
405
+ name: item,
406
+ ...first
407
+ };
408
+ } else if (item && typeof item === "object") {
409
+ const given = item;
410
+ const first = given.name ? FIRST_PARTY_SPORES[given.name] : void 0;
411
+ o = first && given.crate === void 0 ? {
412
+ ...first,
413
+ ...given
414
+ } : given;
415
+ } else throw new Error(`${where}: a spore is a first-party name or {name, crate, spore, …}`);
416
+ const name = o.name;
417
+ if (typeof name !== "string" || typeof o.crate !== "string" || typeof o.spore !== "string") throw new Error(`${where}: a spore needs \`name\`, \`crate\` and \`spore\``);
418
+ if ([
419
+ o.git,
420
+ o.version,
421
+ o.path
422
+ ].filter((s) => s !== void 0).length !== 1) throw new Error(`${where}: spore ${name}: give one of \`git\`, \`version\` or \`path\``);
423
+ if (o.rev !== void 0 && (o.git === void 0 || !REV$1.test(o.rev))) throw new Error(`${where}: spore ${name}: \`rev\` is a full commit ID (40 hex digits), with \`git\``);
424
+ if (!RUST_PATH.test(o.spore)) throw new Error(`${where}: spore ${name}: \`spore\` is a Rust path (crate_name::Type)`);
425
+ if (o.routes !== void 0 && !RUST_PATH.test(o.routes)) throw new Error(`${where}: spore ${name}: \`routes\` is a Rust path (crate_name::name_routes)`);
426
+ const entry = {
427
+ name,
428
+ crate: o.crate,
429
+ spore: o.spore,
430
+ ...o.git !== void 0 ? { git: o.git } : {},
431
+ ...o.rev !== void 0 ? { rev: o.rev } : {},
432
+ ...o.version !== void 0 ? { version: o.version } : {},
433
+ ...o.path !== void 0 ? { path: o.path } : {},
434
+ ...o.routes !== void 0 ? { routes: o.routes } : {}
435
+ };
436
+ if (!NAME$2.test(name)) throw new Error(`${where}: spore ${JSON.stringify(name)}: lowercase letters, digits and _, starting with a letter`);
437
+ for (const other of out.map(sporeName)) {
438
+ if (other === name) throw new Error(`${where}: spore ${name} is listed twice`);
439
+ const [shorter, longer] = other.length < name.length ? [other, name] : [name, other];
440
+ if (longer.startsWith(`${shorter}_`)) throw new Error(`${where}: spore ${longer}'s name extends ${shorter}'s: their tables and provider keys (spore_${shorter}_…) would overlap`);
441
+ }
442
+ out.push(entry);
443
+ }
444
+ return out;
445
+ }
446
+ /** The deployment's generated crates, in this checkout: git-ignored, named after the
447
+ * deployment's folder. */
448
+ function buildDir(deploymentDir) {
449
+ return join(requireRepo("A deployment with spores"), ".hypha-build", basename(resolve(deploymentDir)));
450
+ }
451
+ /** Where a deployment's host crate goes. */
452
+ function hostCrateDir(deploymentDir) {
453
+ return join(buildDir(deploymentDir), "host");
454
+ }
455
+ /** Where a git spore is cloned, beside the host crate (in Docker's build context). */
456
+ function sporeCloneDir(deploymentDir, name) {
457
+ return join(buildDir(deploymentDir), "spores", name);
458
+ }
459
+ /** Each git spore cloned at its commit: its name → the clone. A spore not pinned yet is
460
+ * refused (`hypha deploy` pins them first). */
461
+ async function fetchSpores(deploymentDir, spores, runner) {
462
+ const local = {};
463
+ for (const s of spores) {
464
+ if (!s.git) continue;
465
+ if (!s.rev) throw new Error(`spore ${s.name} isn't pinned to a commit (\`rev\`)`);
466
+ const clone = sporeCloneDir(deploymentDir, s.name);
467
+ await cloneAt(s.git, s.rev, clone, runner);
468
+ local[s.name] = clone;
469
+ }
470
+ return local;
471
+ }
472
+ /** The host crate's `Cargo.toml`: the native host and every spore, its own workspace.
473
+ * `local` is where each git spore's crate is on this machine (`fetchSpores`). */
474
+ function hostCargoToml(dir, spores, deploymentDir = ".", local = {}) {
475
+ const repo = (path) => JSON.stringify(relative(dir, join(REPO, path)));
476
+ const lines = [
477
+ "# Written by `hypha deploy` from hypha.json's `spores`: change",
478
+ "# those, not this file.",
479
+ "[package]",
480
+ "name = \"hypha-deployment\"",
481
+ "version = \"0.1.0\"",
482
+ "edition = \"2024\"",
483
+ "publish = false",
484
+ "",
485
+ "# Its own workspace: not one of the checkout's crates.",
486
+ "[workspace]",
487
+ "",
488
+ "[dependencies]",
489
+ `hypha-host-axum = { path = ${repo("crates/hypha-host-axum")} }`
490
+ ];
491
+ lines.push(...sporeDependencies(dir, spores, deploymentDir, local));
492
+ lines.push(...hyphaPatch(dir));
493
+ lines.push("", "[profile.release]", "debug = \"line-tables-only\"", "");
494
+ return lines.join("\n");
495
+ }
496
+ /** Spores depend on Hypha through git: this points that source at this checkout, so the
497
+ * spores and the host share one copy of each crate (two would be two `Spore` traits), and
498
+ * the build fetches nothing. Cargo warns about the crates no spore uses. */
499
+ function hyphaPatch(dir) {
500
+ const crates = readdirSync(join(REPO, "crates"), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).toSorted();
501
+ return [
502
+ "",
503
+ `[patch.${JSON.stringify(HYPHA_GIT)}]`,
504
+ ...crates.map((c) => `${c} = { path = ${JSON.stringify(relative(dir, join(REPO, "crates", c)))} }`)
505
+ ];
506
+ }
507
+ /** A path spore's folder: resolved against the deployment's folder, and inside this
508
+ * checkout's `spores/`, the one folder of it besides the crates and `.hypha-build/` that
509
+ * goes into Docker's build context (`docker/api.Dockerfile.dockerignore`). */
510
+ function sporePath(name, deploymentDir, path) {
511
+ const full = resolve(deploymentDir, path);
512
+ const spores = join(REPO, "spores");
513
+ if (!full.startsWith(`${spores}${sep}`)) throw new Error(`spore ${name}: \`path\` ${full} is outside ${spores}, which the API is built from: put the crate there, or give \`git\` or \`version\``);
514
+ return full;
515
+ }
516
+ /** The host crate's `main.rs`: `host! { spores: [...], routes: [...] }`. */
517
+ function hostMain(spores) {
518
+ return crateEntry("hypha_host_axum::host!", "`hypha deploy`", spores);
519
+ }
520
+ /** A generated crate's entry: `<macro> { spores: [...], routes: [...] }`. */
521
+ function crateEntry(macro, writer, spores) {
522
+ const types = spores.map((s) => s.spore);
523
+ const routes = spores.flatMap((s) => s.routes ? [s.routes] : []);
524
+ return [
525
+ `//! Written by ${writer} from hypha.json's \`spores\`.`,
526
+ "",
527
+ `${macro} {`,
528
+ ` spores: [${types.join(", ")}],`,
529
+ ` routes: [${routes.join(", ")}],`,
530
+ "}",
531
+ ""
532
+ ].join("\n");
533
+ }
534
+ /** Where a deployment's Worker crate goes, beside its host crate. */
535
+ function workerCrateDir(deploymentDir) {
536
+ return join(buildDir(deploymentDir), "worker");
537
+ }
538
+ /** The spores' dependency lines for a crate in `dir`. */
539
+ function sporeDependencies(dir, spores, deploymentDir, local) {
540
+ return spores.map((s) => {
541
+ let source;
542
+ if (s.git) {
543
+ const clone = local[s.name];
544
+ if (!clone) throw new Error(`spore ${s.name} hasn't been fetched (\`fetchSpores\`)`);
545
+ source = `path = ${JSON.stringify(relative(dir, clone))}`;
546
+ } else if (s.version) source = `version = ${JSON.stringify(s.version)}`;
547
+ else source = `path = ${JSON.stringify(relative(dir, sporePath(s.name, deploymentDir, s.path ?? ".")))}`;
548
+ return `${s.crate} = { ${source} }`;
549
+ });
550
+ }
551
+ /** The Worker crate's `Cargo.toml`: `hypha-host-workers` without its stock Worker, `worker`
552
+ * (its `#[event]`s expand to `::worker`), every spore. */
553
+ function workerCargoToml(dir, spores, worker, deploymentDir = ".", local = {}) {
554
+ return [
555
+ "# Written by `hypha deploy` from hypha.json's `spores`: change",
556
+ "# those, not this file.",
557
+ "[package]",
558
+ "name = \"hypha-deployment-worker\"",
559
+ "version = \"0.1.0\"",
560
+ "edition = \"2024\"",
561
+ "publish = false",
562
+ "",
563
+ "[lib]",
564
+ "crate-type = [\"cdylib\"]",
565
+ "",
566
+ "# Its own workspace: not one of the checkout's crates.",
567
+ "[workspace]",
568
+ "",
569
+ "[dependencies]",
570
+ `hypha-host-workers = { path = ${JSON.stringify(relative(dir, join(REPO, "crates", "hypha-host-workers")))}, default-features = false }`,
571
+ worker,
572
+ ...sporeDependencies(dir, spores, deploymentDir, local),
573
+ ...hyphaPatch(dir),
574
+ ""
575
+ ].join("\n");
576
+ }
577
+ /** The Worker crate's `lib.rs`: `worker! { spores: [...], routes: [...] }`. */
578
+ function workerLib(spores) {
579
+ return crateEntry("hypha_host_workers::worker!", "`hypha deploy` (the Worker)", spores);
580
+ }
581
+ /** `hypha-host-workers`' own `worker = …` line: the Worker crate needs the very same
582
+ * `worker` (its `#[event]`s expand to `::worker`), pinned exactly as the host is. */
583
+ async function workerDependency() {
584
+ const line = (await readFile(join(REPO, "crates", "hypha-host-workers", "Cargo.toml"), "utf8")).split("\n").find((l) => /^worker\s*=/.test(l));
585
+ if (!line) throw new Error("crates/hypha-host-workers/Cargo.toml names no `worker` dependency");
586
+ return line.trim();
587
+ }
588
+ /** Writes the deployment's Worker crate and returns its folder (absolute: wrangler
589
+ * builds there). */
590
+ async function writeWorkerCrate(deploymentDir, spores, local = {}) {
591
+ const dir = workerCrateDir(deploymentDir);
592
+ await writeCrate(dir, {
593
+ "Cargo.toml": workerCargoToml(dir, spores, await workerDependency(), deploymentDir, local),
594
+ "src/lib.rs": workerLib(spores)
595
+ });
596
+ return dir;
597
+ }
598
+ /** Writes the deployment's host crate and returns its folder relative to the checkout
599
+ * (what the API's Dockerfile builds: `HOST_CRATE`). */
600
+ async function writeHostCrate(deploymentDir, spores, local = {}) {
601
+ const dir = hostCrateDir(deploymentDir);
602
+ await writeCrate(dir, {
603
+ "Cargo.toml": hostCargoToml(dir, spores, deploymentDir, local),
604
+ "src/main.rs": hostMain(spores)
605
+ });
606
+ return relative(REPO, dir);
607
+ }
608
+ /** Writes a generated crate's files, and its `Cargo.lock` from the checkout's, so
609
+ * Hypha's own dependencies resolve as they're tested. The lock is written again only
610
+ * when the checkout's changed since (`Cargo.lock.seed` holds its hash): until then the
611
+ * crate keeps its own, with what Cargo resolved for the spores. */
612
+ async function writeCrate(dir, files) {
613
+ await mkdir(join(dir, "src"), { recursive: true });
614
+ for (const [path, text] of Object.entries(files)) await writeFile(join(dir, path), text);
615
+ const checkout = await readFile(join(REPO, "Cargo.lock"), "utf8");
616
+ const hash = createHash("sha256").update(checkout).digest("hex");
617
+ const seed = join(dir, "Cargo.lock.seed");
618
+ if (await readFile(seed, "utf8").catch(() => void 0) === hash) return;
619
+ await writeFile(join(dir, "Cargo.lock"), checkout);
620
+ await writeFile(seed, hash);
621
+ }
622
+ //#endregion
623
+ //#region src/deployment.ts
624
+ const STATE_FILE = "hypha.json";
625
+ const ENV_FILE = ".env";
626
+ function apps$1(d) {
627
+ return ["admin", "storefront"].filter((app) => d.domains[app]);
628
+ }
629
+ function url(d, host) {
630
+ return `${d.scheme}://${host}`;
631
+ }
632
+ async function loadDeployment(dir) {
633
+ let text;
634
+ try {
635
+ text = await readFile(join(dir, STATE_FILE), "utf8");
636
+ } catch {
637
+ throw new Error(`no deployment in ${dir}: run \`hypha init\` first (or pass --dir)`);
638
+ }
639
+ const d = JSON.parse(text);
640
+ if (d.version !== 1) throw new Error(`${join(dir, STATE_FILE)}: version ${JSON.stringify(d.version)} is newer than this CLI`);
641
+ if (d.apps !== void 0) d.apps = normalizeApps(d.apps, join(dir, STATE_FILE));
642
+ if (d.spores !== void 0) d.spores = normalizeSpores(d.spores, join(dir, STATE_FILE));
643
+ return d;
644
+ }
645
+ async function saveDeployment(dir, d) {
646
+ await writeFile(join(dir, STATE_FILE), `${JSON.stringify(d, null, 2)}\n`);
647
+ }
648
+ function isBlank(line) {
649
+ return line !== void 0 && "text" in line && line.text === "";
650
+ }
651
+ /** A `.env` file as Docker Compose reads it, kept in order with its comments. */
652
+ var EnvFile = class EnvFile {
653
+ lines;
654
+ constructor(lines = []) {
655
+ this.lines = lines;
656
+ }
657
+ static parse(text) {
658
+ const lines = [];
659
+ for (const raw of text.split("\n")) {
660
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(raw);
661
+ if (!match) {
662
+ lines.push({ text: raw });
663
+ continue;
664
+ }
665
+ let value = match[2];
666
+ if (value.startsWith("\"") && value.endsWith("\"") && value.length >= 2) value = value.slice(1, -1).replace(/\\(["\\])/g, "$1");
667
+ else if (value.startsWith("'") && value.endsWith("'") && value.length >= 2) value = value.slice(1, -1);
668
+ lines.push({
669
+ key: match[1],
670
+ value
671
+ });
672
+ }
673
+ while (isBlank(lines.at(-1))) lines.pop();
674
+ return new EnvFile(lines);
675
+ }
676
+ /** The variables' names, in order. */
677
+ keys() {
678
+ return this.lines.flatMap((l) => "key" in l ? [l.key] : []);
679
+ }
680
+ get(key) {
681
+ for (const line of this.lines) if ("key" in line && line.key === key) return line.value;
682
+ }
683
+ /** Removes `key`, if it's there. */
684
+ delete(key) {
685
+ this.lines = this.lines.filter((l) => !("key" in l && l.key === key));
686
+ return this;
687
+ }
688
+ /** Sets `key`, in place if it's there, else at the end. */
689
+ set(key, value) {
690
+ const line = this.lines.find((l) => "key" in l && l.key === key);
691
+ if (line && "key" in line) line.value = value;
692
+ else this.lines.push({
693
+ key,
694
+ value
695
+ });
696
+ return this;
697
+ }
698
+ comment(text) {
699
+ this.lines.push(...text.split("\n").map((t) => ({ text: t ? `# ${t}` : "" })));
700
+ return this;
701
+ }
702
+ toString() {
703
+ return `${this.lines.map((l) => "key" in l ? `${l.key}=${formatValue(l.value)}` : l.text).join("\n")}\n`;
704
+ }
705
+ };
706
+ /** Plain when it's safe, else double-quoted (Compose unescapes `\"` and `\\`). */
707
+ function formatValue(value) {
708
+ return /^[A-Za-z0-9_./:@,+-]*$/.test(value) ? value : `"${value.replace(/(["\\])/g, "\\$1")}"`;
709
+ }
710
+ async function loadEnv(dir) {
711
+ return EnvFile.parse(await readFile(join(dir, ENV_FILE), "utf8"));
712
+ }
713
+ /** Writes `.env` readable by its owner only: it holds the deployment's secrets. */
714
+ async function saveEnv(dir, env) {
715
+ const path = join(dir, ENV_FILE);
716
+ await writeFile(path, env.toString(), { mode: 384 });
717
+ await chmod(path, 384);
718
+ }
719
+ //#endregion
720
+ //#region src/shell.ts
721
+ var CommandFailed = class extends Error {
722
+ command;
723
+ code;
724
+ output;
725
+ constructor(command, code, output) {
726
+ const tail = output.trim().split("\n").slice(-15).join("\n");
727
+ super(`\`${command}\` failed${code === null ? "" : ` (exit ${code})`}${tail ? `:\n${tail}` : ""}`);
728
+ this.command = command;
729
+ this.code = code;
730
+ this.output = output;
731
+ }
732
+ };
733
+ /** The variables a program needs from the system, whoever runs it. */
734
+ const SYSTEM = [
735
+ "PATH",
736
+ "HOME",
737
+ "SystemRoot",
738
+ "windir",
739
+ "SystemDrive",
740
+ "ComSpec",
741
+ "PATHEXT",
742
+ "TEMP",
743
+ "TMP",
744
+ "USERPROFILE",
745
+ "APPDATA",
746
+ "LOCALAPPDATA",
747
+ "ProgramData"
748
+ ];
749
+ /** The system's own variables from `from` (this process's environment). */
750
+ function systemEnv(from = process.env) {
751
+ const out = {};
752
+ for (const key of SYSTEM) {
753
+ const value = from[key];
754
+ if (value !== void 0) out[key] = value;
755
+ }
756
+ return out;
757
+ }
758
+ /** Runs `program` and resolves with its output when `capture` is set; rejects on a
759
+ * non-zero exit with the output's last lines. */
760
+ function run(program, args, options = {}) {
761
+ const { capture = false, input, cwd, env, bareEnv = false } = options;
762
+ const base = bareEnv ? systemEnv() : process.env;
763
+ return new Promise((resolve, reject) => {
764
+ const child = spawn(program, args, {
765
+ cwd,
766
+ env: env ? {
767
+ ...base,
768
+ ...env
769
+ } : base,
770
+ stdio: [
771
+ input === void 0 ? "inherit" : "pipe",
772
+ capture ? "pipe" : "inherit",
773
+ capture ? "pipe" : "inherit"
774
+ ]
775
+ });
776
+ let out = "";
777
+ let err = "";
778
+ child.stdout?.on("data", (chunk) => out += chunk);
779
+ child.stderr?.on("data", (chunk) => err += chunk);
780
+ if (input !== void 0) child.stdin?.end(input);
781
+ child.on("error", (e) => reject(new CommandFailed(`${program} ${args.join(" ")}`, null, e.message)));
782
+ child.on("close", (code) => {
783
+ if (code === 0) resolve(out);
784
+ else reject(new CommandFailed(`${program} ${args.join(" ")}`, code, `${out}\n${err}`));
785
+ });
786
+ });
787
+ }
788
+ /** `a | b`: the first program's output is the second's input. */
789
+ function pipe(a, b, options = {}) {
790
+ return new Promise((resolve, reject) => {
791
+ const first = spawn(a[0], a[1], {
792
+ cwd: options.cwd,
793
+ env: options.env ? {
794
+ ...process.env,
795
+ ...options.env
796
+ } : process.env,
797
+ stdio: [
798
+ "ignore",
799
+ "pipe",
800
+ "inherit"
801
+ ]
802
+ });
803
+ const second = spawn(b[0], b[1], { stdio: [
804
+ "pipe",
805
+ "inherit",
806
+ "inherit"
807
+ ] });
808
+ first.stdout.pipe(second.stdin);
809
+ let failed = false;
810
+ const fail = (name, code) => {
811
+ if (failed) return;
812
+ failed = true;
813
+ reject(new CommandFailed(name, code, ""));
814
+ };
815
+ first.on("error", () => fail(a[0], null));
816
+ second.on("error", () => fail(b[0], null));
817
+ first.on("close", (code) => code !== 0 && fail(`${a[0]} ${a[1].join(" ")}`, code));
818
+ second.on("close", (code) => code === 0 ? !failed && resolve() : fail(`${b[0]} ${b[1].join(" ")}`, code));
819
+ });
820
+ }
821
+ /** `value` quoted for a POSIX shell. */
822
+ function quote(value) {
823
+ return /^[A-Za-z0-9_./:@=+-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
824
+ }
825
+ /** A server, over SSH. `BatchMode` makes a missing key an error instead of a prompt. */
826
+ function server(ssh, dir) {
827
+ const options = [
828
+ "-o",
829
+ "BatchMode=yes",
830
+ "-o",
831
+ "ConnectTimeout=15"
832
+ ];
833
+ return {
834
+ label: ssh,
835
+ ssh,
836
+ sh(command, { capture, input } = {}) {
837
+ return run("ssh", [
838
+ ...options,
839
+ ssh,
840
+ `export LC_ALL=C.UTF-8; mkdir -p ${quote(dir)} && cd ${quote(dir)} && ${command}`
841
+ ], {
842
+ capture,
843
+ input
844
+ });
845
+ },
846
+ upload(from, files) {
847
+ return pipe(["tar", [
848
+ "--no-xattrs",
849
+ "-C",
850
+ from,
851
+ "-czf",
852
+ "-",
853
+ ...files
854
+ ]], ["ssh", [
855
+ ...options,
856
+ ssh,
857
+ `mkdir -p ${quote(dir)} && tar -C ${quote(dir)} --no-same-owner -xzf -`
858
+ ]], { env: { COPYFILE_DISABLE: "1" } });
859
+ }
860
+ };
861
+ }
862
+ /** This machine: the deployment's folder is where the files already are. */
863
+ function here(dir) {
864
+ return {
865
+ label: "this machine",
866
+ sh(command, { capture, input } = {}) {
867
+ return run("sh", ["-c", command], {
868
+ cwd: dir,
869
+ capture,
870
+ input
871
+ });
872
+ },
873
+ async upload() {}
874
+ };
875
+ }
876
+ //#endregion
877
+ //#region src/apps.ts
878
+ /** The first-party apps, by name. */
879
+ const FIRST_PARTY = {
880
+ stripe: "git@github.com:hyphacommerce/app-stripe.git",
881
+ meilisearch: "git@github.com:hyphacommerce/app-meilisearch.git"
882
+ };
883
+ /** An app's name: a DNS label and part of resource names. `hypha` is the SDK's link. */
884
+ const NAME$1 = /^[a-z][a-z0-9-]{0,30}[a-z0-9]$/;
885
+ function checkAppName(name) {
886
+ if (!NAME$1.test(name)) return "lowercase letters, digits and dashes (2 to 32)";
887
+ if (name === "hypha") return "`hypha` is taken by the link to this checkout";
888
+ }
889
+ /** A full commit ID. */
890
+ const REV = /^[0-9a-f]{40}$/;
891
+ /** A domain name, lowercase (the API Worker's `HYPHA_APP_BINDINGS` takes no other). */
892
+ const DOMAIN$1 = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/;
893
+ /** `domain` as an app's domain: trimmed and lowercased, or `undefined` if it isn't one. */
894
+ function appDomainOf(domain) {
895
+ const lower = domain.trim().toLowerCase();
896
+ return DOMAIN$1.test(lower) ? lower : void 0;
897
+ }
898
+ /** `hypha.json`'s `apps`, each a name (a first-party app) or an entry, checked. */
899
+ function normalizeApps(raw, where) {
900
+ if (!Array.isArray(raw)) throw new Error(`${where}: \`apps\` is a list`);
901
+ const out = [];
902
+ for (const item of raw) {
903
+ let entry;
904
+ if (typeof item === "string") {
905
+ const git = FIRST_PARTY[item];
906
+ if (!git) throw new Error(`${where}: ${JSON.stringify(item)} isn't a first-party app (${Object.keys(FIRST_PARTY).join(", ")}): give {name, git, rev}`);
907
+ entry = {
908
+ name: item,
909
+ git
910
+ };
911
+ } else if (item && typeof item === "object") {
912
+ const o = item;
913
+ const git = o.git ?? (o.name ? FIRST_PARTY[o.name] : void 0);
914
+ if (typeof o.name !== "string" || typeof git !== "string") throw new Error(`${where}: an app needs \`name\` and \`git\``);
915
+ entry = {
916
+ ...o,
917
+ name: o.name,
918
+ git
919
+ };
920
+ } else throw new Error(`${where}: an app is a name or {name, git, rev}`);
921
+ const wrong = checkAppName(entry.name);
922
+ if (wrong) throw new Error(`${where}: app ${JSON.stringify(entry.name)}: ${wrong}`);
923
+ if (entry.domain !== void 0) {
924
+ const domain = typeof entry.domain === "string" ? appDomainOf(entry.domain) : void 0;
925
+ if (!domain) throw new Error(`${where}: app ${entry.name}: \`domain\` ${JSON.stringify(entry.domain)} isn't a domain name (like stripe.example.com: no scheme, port or path)`);
926
+ entry.domain = domain;
927
+ }
928
+ if (entry.rev !== void 0 && !REV.test(entry.rev)) throw new Error(`${where}: app ${entry.name}: \`rev\` is a full commit ID (40 hex digits)`);
929
+ if (out.some((a) => a.name === entry.name)) throw new Error(`${where}: app ${entry.name} is listed twice`);
930
+ out.push(entry);
931
+ }
932
+ return out;
933
+ }
934
+ /** What `hypha apps add` takes: a first-party name, or a repository (its name from the
935
+ * repository's, without an `app-` or `hypha-app-` prefix, unless `name` is given). */
936
+ function entryFor(spec, name) {
937
+ const git = FIRST_PARTY[spec] ?? spec;
938
+ if (git === spec && !/^(git@|https:\/\/|ssh:\/\/|file:\/\/|\/)/.test(spec)) throw new Error(`${spec} isn't a first-party app (${Object.keys(FIRST_PARTY).join(", ")}) or a git URL`);
939
+ const derived = name ?? (FIRST_PARTY[spec] ? spec : spec.replace(/\/+$/, "").split(/[/:]/).pop()?.replace(/\.git$/, "").replace(/^(hypha-)?app-/, "").toLowerCase() ?? "");
940
+ const wrong = checkAppName(derived);
941
+ if (wrong) throw new Error(`the app's name, ${JSON.stringify(derived)}: ${wrong} (pass --name)`);
942
+ return {
943
+ name: derived,
944
+ git
945
+ };
946
+ }
947
+ /** The domain the deployment's others go under. */
948
+ function apex(d) {
949
+ if (d.domain) return d.domain;
950
+ const labels = d.domains.api.split(".");
951
+ return labels.length > 2 ? labels.slice(1).join(".") : d.domains.api;
952
+ }
953
+ const appDomain = (d, a) => a.domain ?? `${a.name}.${apex(d)}`;
954
+ const appUrl = (d, a) => url(d, appDomain(d, a));
955
+ /** `stripe-payments` → `STRIPE_PAYMENTS`. */
956
+ const upper = (name) => name.toUpperCase().replaceAll("-", "_");
957
+ /** Its `APP_ENCRYPTION_KEY`, in the deployment's `.env`. */
958
+ const encryptionKeyVar = (a) => `APP_${upper(a.name)}_ENCRYPTION_KEY`;
959
+ /** Matches every app's key, for `init --force` to keep. */
960
+ const ENCRYPTION_KEY_VAR = /^APP_[A-Z0-9_]+_ENCRYPTION_KEY$/;
961
+ /** The API Worker's binding to its Worker. */
962
+ const bindingName = (a) => `APP_${upper(a.name)}`;
963
+ /** Its Worker and D1 database on Cloudflare. */
964
+ const appWorkerName = (d, a) => `${d.cloudflare.name}-app-${a.name}`;
965
+ /** Its container and image on a server. */
966
+ const service = (a) => `app-${a.name}`;
967
+ const imageTag = (a) => `hypha-app-${a.name}:current`;
968
+ /** A new `APP_ENCRYPTION_KEY`: 64 hex characters. Lost, the app loses what it sealed. */
969
+ function newEncryptionKey() {
970
+ return randomBytes(32).toString("hex");
971
+ }
972
+ /** The variables apps take the allowed APIs' origins in, as the first-party apps name it. */
973
+ const ALLOWLIST_VARS = ["HYPHA_API_ALLOWLIST", "HYPHA_API_URLS"];
974
+ function profileOf(files) {
975
+ const expose = /^\s*EXPOSE\s+(\d+)/m.exec(files.dockerfile ?? "")?.[1];
976
+ const volume = /^\s*VOLUME\s+(?:\[\s*"([^"]+)"|(\S+))/m.exec(files.dockerfile ?? "");
977
+ const scripts = files.packageJson ? JSON.parse(files.packageJson) : {};
978
+ const wrangler = files.wrangler;
979
+ return {
980
+ port: expose ? Number(expose) : 3e3,
981
+ ...volume ? { dataDir: volume[1] ?? volume[2] } : {},
982
+ ...wrangler ? { wrangler } : {},
983
+ apiBinding: Boolean(wrangler && /binding\s*=\s*"HYPHA_API"/.test(wrangler)),
984
+ ...(() => {
985
+ const found = ALLOWLIST_VARS.find((v) => new RegExp(`^\\s*${v}\\s*=`, "m").test(wrangler ?? ""));
986
+ return found ? { allowlistVar: found } : {};
987
+ })(),
988
+ ...scripts.scripts?.["build:node"] ? { nodeBuild: "build:node" } : {}
989
+ };
990
+ }
991
+ const read = (path) => readFile(path, "utf8").catch(() => void 0);
992
+ async function readProfile(clone) {
993
+ return profileOf({
994
+ dockerfile: await read(join(clone, "Dockerfile")),
995
+ wrangler: await read(join(clone, "wrangler.example.toml")) ?? await read(join(clone, "wrangler.toml.example")),
996
+ packageJson: await read(join(clone, "package.json"))
997
+ });
998
+ }
999
+ /** A TOML string: JSON's escapes are TOML's. */
1000
+ const str$1 = (value) => JSON.stringify(value);
1001
+ /**
1002
+ * The app's `wrangler.toml`, from its own template (which keeps its entry point, flags,
1003
+ * crons and other variables): its name, account and custom domain, `APP_URL`, the
1004
+ * allowed API, the D1 database, and the binding to the API when it supports one.
1005
+ */
1006
+ function appWranglerToml(template, o) {
1007
+ const lines = template.split("\n");
1008
+ const set = (pattern, line, what) => {
1009
+ const i = lines.findIndex((l) => pattern.test(l));
1010
+ if (i < 0) throw new Error(`the app's wrangler template has no ${what}`);
1011
+ lines[i] = line;
1012
+ return i;
1013
+ };
1014
+ set(/^name\s*=/, `name = ${str$1(o.worker)}`, "`name`");
1015
+ if (lines.findIndex((l) => /^main\s*=/.test(l)) < 0) throw new Error("the app's wrangler template has no `main`");
1016
+ const firstTable = lines.findIndex((l) => l.startsWith("["));
1017
+ lines.splice(firstTable < 0 ? lines.length : firstTable, 0, `account_id = ${str$1(o.accountId)}`, "workers_dev = false", `routes = [{ pattern = ${str$1(o.domain)}, custom_domain = true }]`, "");
1018
+ let vars = lines.findIndex((l) => /^\[vars\]\s*$/.test(l));
1019
+ if (vars < 0) {
1020
+ lines.push("", "[vars]");
1021
+ vars = lines.length - 1;
1022
+ }
1023
+ const setVar = (key, value) => {
1024
+ const i = lines.findIndex((l) => new RegExp(`^${key}\\s*=`).test(l));
1025
+ if (i >= 0) lines[i] = `${key} = ${str$1(value)}`;
1026
+ else lines.splice(vars + 1, 0, `${key} = ${str$1(value)}`);
1027
+ };
1028
+ setVar("APP_URL", o.appUrl);
1029
+ if (o.allowlistVar) setVar(o.allowlistVar, new URL(o.apiUrl).origin);
1030
+ if (o.apiWorker) setVar("HYPHA_API_URL", o.apiUrl);
1031
+ const d1 = lines.findIndex((l) => l.startsWith("[[d1_databases]]"));
1032
+ if (d1 < 0) throw new Error("the app's wrangler template has no `[[d1_databases]]`");
1033
+ const inD1 = (pattern, line) => {
1034
+ const end = lines.findIndex((l, i) => i > d1 && l.startsWith("["));
1035
+ const i = lines.findIndex((l, j) => j > d1 && (end < 0 || j < end) && pattern.test(l));
1036
+ if (i < 0) throw new Error("the app's wrangler template's D1 database lacks a key");
1037
+ lines[i] = line;
1038
+ };
1039
+ inD1(/^database_name\s*=/, `database_name = ${str$1(o.d1.name)}`);
1040
+ inD1(/^database_id\s*=/, `database_id = ${str$1(o.d1.id)}`);
1041
+ while (lines.at(-1) === "") lines.pop();
1042
+ if (o.apiWorker) lines.push("", "# Calls to HYPHA_API_URL go through this Service Binding.", "[[services]]", "binding = \"HYPHA_API\"", `service = ${str$1(o.apiWorker)}`);
1043
+ return [
1044
+ "# Written by `hypha deploy` from the app's wrangler template and hypha.json on every",
1045
+ "# deploy: change those, not this file.",
1046
+ ...lines,
1047
+ ""
1048
+ ].join("\n");
1049
+ }
1050
+ /** The file it's written to, in the app's clone (`main` is relative to it). */
1051
+ const APP_WRANGLER_FILE = ".hypha-wrangler.toml";
1052
+ /** The co-located apps on a server: each a container on the deployment's network. */
1053
+ function composeApps(d, apps) {
1054
+ const out = [
1055
+ "# Written by `hypha deploy` from hypha.json's apps on every",
1056
+ "# deploy: change those, not this file. Compose reads it after compose.yaml",
1057
+ "# (COMPOSE_FILE in .env).",
1058
+ "",
1059
+ "services:"
1060
+ ];
1061
+ const volumes = [];
1062
+ for (const { entry, profile } of apps) {
1063
+ const name = service(entry);
1064
+ out.push(` ${name}:`, ` image: ${imageTag(entry)}`, " restart: unless-stopped", " environment:", ` APP_URL: ${appUrl(d, entry)}`, ` APP_ENCRYPTION_KEY: \${${encryptionKeyVar(entry)}:?}`, ` PORT: "${profile.port}"`, ...profile.allowlistVar ? [` ${profile.allowlistVar}: ${url(d, d.domains.api)}`] : []);
1065
+ if (profile.dataDir) {
1066
+ volumes.push(`${name}-data`);
1067
+ out.push(" volumes:", ` - ${name}-data:${profile.dataDir}`);
1068
+ }
1069
+ out.push(" networks: [hypha]");
1070
+ }
1071
+ out.push(" caddy:", " volumes:", " - ./apps.caddy:/etc/caddy/apps.caddy:ro");
1072
+ if (d.target === "local") out.push(" networks:", " hypha:", " aliases:", " - ${MEDIA_HOST:?}", ` - ${d.domains.api}`, ...apps.map(({ entry }) => ` - ${appDomain(d, entry)}`));
1073
+ if (volumes.length > 0) out.push("", "volumes:", ...volumes.map((v) => ` ${v}:`));
1074
+ return `${out.join("\n")}\n`;
1075
+ }
1076
+ /** The file Compose reads after `compose.yaml`, and Caddy's sites for the apps. */
1077
+ const COMPOSE_APPS_FILE = "compose.apps.yaml";
1078
+ const APPS_CADDY_FILE = "apps.caddy";
1079
+ /** The Caddyfile's line that reads `apps.caddy`. */
1080
+ const CADDY_IMPORT = "import /etc/caddy/apps.caddy";
1081
+ /** The SDK's link next to the clones, and each clone's folder. */
1082
+ const buildRoot = (dir) => join(dir, ".build", "apps");
1083
+ const cloneDir = (dir, a) => join(buildRoot(dir), a.name);
1084
+ const runHere = (program, args, options = {}) => run(program, args, options);
1085
+ /** The commit `git`'s default branch (or `ref`) is at, asked of the remote. */
1086
+ async function remoteHead(git, ref = "HEAD", runner = runHere) {
1087
+ const out = await runner("git", [
1088
+ "ls-remote",
1089
+ git,
1090
+ ref
1091
+ ], { capture: true });
1092
+ const rev = /^([0-9a-f]{40})\s/m.exec(out)?.[1];
1093
+ if (!rev) throw new Error(`${git} has no ${ref}`);
1094
+ return rev;
1095
+ }
1096
+ /** `git` at commit `rev` in `clone`: cloned the first time, fetched when the commit is new
1097
+ * to it, and left as it is when it's there already. With this machine's git credentials. */
1098
+ async function cloneAt(git, rev, clone, runner = runHere) {
1099
+ if (!await exists$2(join(clone, ".git"))) await runner("git", [
1100
+ "clone",
1101
+ "--quiet",
1102
+ git,
1103
+ clone
1104
+ ], { capture: true });
1105
+ if (!await runner("git", [
1106
+ "cat-file",
1107
+ "-e",
1108
+ `${rev}^{commit}`
1109
+ ], {
1110
+ cwd: clone,
1111
+ capture: true
1112
+ }).then(() => true, () => false)) await runner("git", [
1113
+ "fetch",
1114
+ "--quiet",
1115
+ "origin",
1116
+ rev
1117
+ ], {
1118
+ cwd: clone,
1119
+ capture: true
1120
+ });
1121
+ await runner("git", [
1122
+ "-c",
1123
+ "advice.detachedHead=false",
1124
+ "checkout",
1125
+ "--quiet",
1126
+ "--force",
1127
+ rev
1128
+ ], {
1129
+ cwd: clone,
1130
+ capture: true
1131
+ });
1132
+ }
1133
+ async function exists$2(path) {
1134
+ return stat(path).then(() => true, () => false);
1135
+ }
1136
+ /** Links `<build root>/hypha` to this checkout, so the apps' `../hypha/packages/*`
1137
+ * resolve to it. */
1138
+ async function linkHypha(dir, repo = REPO) {
1139
+ const root = buildRoot(dir);
1140
+ await mkdir(root, { recursive: true });
1141
+ const link = join(root, "hypha");
1142
+ if (await readlink(link).catch(() => void 0) === repo) return;
1143
+ await rm(link, {
1144
+ recursive: false,
1145
+ force: true
1146
+ });
1147
+ await symlink(repo, link, process.platform === "win32" ? "junction" : "dir");
1148
+ }
1149
+ /**
1150
+ * The app's clone at its commit, its dependencies installed: cloned the first time,
1151
+ * fetched when the commit is new to it, and left as it is when it's there already.
1152
+ */
1153
+ async function checkout(dir, a, runner = runHere) {
1154
+ if (!a.rev) throw new Error(`app ${a.name} isn't pinned: \`hypha apps update ${a.name}\``);
1155
+ requireRepo(`Building the ${a.name} app`);
1156
+ await linkHypha(dir);
1157
+ const clone = cloneDir(dir, a);
1158
+ await cloneAt(a.git, a.rev, clone, runner);
1159
+ if (!await exists$2(join(REPO, "node_modules"))) await runner("pnpm", ["install", "--frozen-lockfile"], {
1160
+ cwd: REPO,
1161
+ capture: true
1162
+ });
1163
+ await runner("pnpm", ["install", "--frozen-lockfile"], {
1164
+ cwd: clone,
1165
+ capture: true
1166
+ });
1167
+ return clone;
1168
+ }
1169
+ //#endregion
1170
+ //#region src/app-install.ts
1171
+ /** The link that starts installing `entry` into this deployment's store. */
1172
+ function installLink(d, entry) {
1173
+ return `${appUrl(d, entry)}/install?api=${encodeURIComponent(url(d, d.domains.api))}`;
1174
+ }
1175
+ /** The key the app's manifest gives it (`app_stripe`); `app_<name>` when it can't be read. */
1176
+ async function appKey(d, entry, fetchJson = (target) => getJson(d, target)) {
1177
+ const manifest = await fetchJson(`${appUrl(d, entry)}/manifest.json`);
1178
+ return typeof manifest?.key === "string" ? {
1179
+ key: manifest.key,
1180
+ reachable: true
1181
+ } : {
1182
+ key: `app_${entry.name.replaceAll("-", "_")}`,
1183
+ reachable: false
1184
+ };
1185
+ }
1186
+ /** Every app in the store, by key (all pages of `GET /admin/apps`). */
1187
+ async function storeApps(staff) {
1188
+ const out = /* @__PURE__ */ new Map();
1189
+ let cursor = null;
1190
+ do {
1191
+ const query = cursor ? `&cursor=${encodeURIComponent(cursor)}` : "";
1192
+ const page = await staff.call("GET", `/admin/apps?limit=100${query}`);
1193
+ for (const app of page.items) out.set(app.key, app);
1194
+ cursor = page.next_cursor;
1195
+ } while (cursor);
1196
+ return out;
1197
+ }
1198
+ /** Each co-located app: where it is, whether it answers, whether the store has it. */
1199
+ async function appStatuses(d, staff, fetchJson) {
1200
+ const installed = staff ? await storeApps(staff) : void 0;
1201
+ const out = [];
1202
+ for (const entry of d.apps ?? []) {
1203
+ const { key, reachable } = await appKey(d, entry, fetchJson);
1204
+ out.push({
1205
+ entry,
1206
+ key,
1207
+ url: appUrl(d, entry),
1208
+ reachable,
1209
+ ...installed ? { installed: installed.get(key)?.installed ?? false } : {},
1210
+ link: installLink(d, entry)
1211
+ });
1212
+ }
1213
+ return out;
1214
+ }
1215
+ /**
1216
+ * A staff session for reading the store's apps: `HYPHA_ADMIN_KEY` (a secret key with
1217
+ * `apps:read`, from this shell or `.env`), else the owner's login from `.env`. None when
1218
+ * neither is there, or the login doesn't go through (two-factor on, a changed password).
1219
+ */
1220
+ async function staffFor(d, env) {
1221
+ const key = process.env.HYPHA_ADMIN_KEY || env?.get("HYPHA_ADMIN_KEY");
1222
+ if (key) return Staff.withToken(d, key);
1223
+ const email = env?.get("HYPHA_OWNER_EMAIL");
1224
+ const password = env?.get("HYPHA_OWNER_PASSWORD");
1225
+ if (!email || !password) return void 0;
1226
+ return Staff.login(d, email, password).catch(() => void 0);
1227
+ }
1228
+ //#endregion
1229
+ //#region src/commands/shared.ts
1230
+ const dirArg = {
1231
+ type: "string",
1232
+ default: "hypha-deploy",
1233
+ description: "The deployment's folder"
1234
+ };
1235
+ let unattended = false;
1236
+ /** `--yes`: take defaults instead of asking. */
1237
+ function setUnattended(value) {
1238
+ unattended = value;
1239
+ }
1240
+ /**
1241
+ * A value from its flag, else `fallback` when not asking (`--yes`, or no terminal),
1242
+ * else the prompt's answer. Cancelling a prompt (Ctrl+C) ends the command.
1243
+ */
1244
+ async function ask(flag, fallback, prompt) {
1245
+ if (flag !== void 0 && flag !== "") return flag;
1246
+ if (fallback !== void 0 && (unattended || !process.stdin.isTTY)) return fallback;
1247
+ if (!process.stdin.isTTY) throw new Error("a value is missing and there's no terminal to ask in: pass its flag");
1248
+ const answer = await prompt();
1249
+ if (p.isCancel(answer) || typeof answer !== "string") {
1250
+ p.cancel("Cancelled.");
1251
+ process.exit(1);
1252
+ }
1253
+ return answer;
1254
+ }
1255
+ async function open(dir) {
1256
+ const d = await loadDeployment(dir);
1257
+ if (d.target === "vps") {
1258
+ if (!d.ssh) throw new Error("hypha.json: a vps deployment needs `ssh`");
1259
+ return {
1260
+ d,
1261
+ machine: server(d.ssh, d.remoteDir)
1262
+ };
1263
+ }
1264
+ return {
1265
+ d,
1266
+ machine: here(dir)
1267
+ };
1268
+ }
1269
+ /** Runs `work`, printing a failure as a message instead of a stack trace. */
1270
+ async function guarded(work) {
1271
+ try {
1272
+ await work();
1273
+ } catch (e) {
1274
+ p.log.error(e instanceof Error ? e.message : String(e));
1275
+ p.outro("Stopped.");
1276
+ process.exit(1);
1277
+ }
1278
+ }
1279
+ //#endregion
1280
+ //#region src/cloudflare-token.ts
1281
+ /** Why an R2 key pair can't be R2's S3 credentials, if it can't: R2 shows a token's
1282
+ * Access Key ID (32 hex characters) and Secret Access Key (64) apart from the token's
1283
+ * value (`cfat_…`), which is what wrangler-style tools take, not the S3 API. */
1284
+ function checkR2Keys(id, secret) {
1285
+ if (/^cf[a-z]*_/.test(id) || /^cf[a-z]*_/.test(secret)) return "that's the token's value; R2 shows the token's Access Key ID and Secret Access Key below it";
1286
+ if (!/^[0-9a-f]{32}$/i.test(id)) return "the Access Key ID is 32 hexadecimal characters";
1287
+ if (!/^[0-9a-f]{64}$/i.test(secret)) return "the Secret Access Key is 64 hexadecimal characters";
1288
+ }
1289
+ /**
1290
+ * R2's S3 credentials from an API token with R2 permission (developers.cloudflare.com/r2/
1291
+ * api/tokens): the Access Key ID is the token's ID, the Secret Access Key the SHA-256 of
1292
+ * its value. So the deploy token can give the media's keys, and a pasted token value is
1293
+ * turned into them.
1294
+ */
1295
+ async function r2KeysOf(token, accountId, get = fetch) {
1296
+ const verified = await call(get, token, "/user/tokens/verify") ?? await call(get, token, `/accounts/${accountId}/tokens/verify`);
1297
+ if (!verified?.id) throw new Error("that R2 token isn't valid (or has expired)");
1298
+ const secret = createHash("sha256").update(token).digest("hex");
1299
+ return {
1300
+ id: verified.id,
1301
+ secret
1302
+ };
1303
+ }
1304
+ /** Whether `value` is a Cloudflare API token's value rather than an S3 key. */
1305
+ function isTokenValue(value) {
1306
+ return /^cf[a-z]*_/.test(value) || value.length >= 40 && !/^[0-9a-f]+$/i.test(value);
1307
+ }
1308
+ /** What the token must allow, as the dashboard's template keys
1309
+ * (developers.cloudflare.com/fundamentals/api/how-to/account-owned-token-template). */
1310
+ const PERMISSIONS = [
1311
+ {
1312
+ key: "account_settings",
1313
+ type: "read",
1314
+ why: "finding the account"
1315
+ },
1316
+ {
1317
+ key: "workers_scripts",
1318
+ type: "edit",
1319
+ why: "deploying the three Workers"
1320
+ },
1321
+ {
1322
+ key: "workers_tail",
1323
+ type: "read",
1324
+ why: "`hypha logs`"
1325
+ },
1326
+ {
1327
+ key: "workers_kv_storage",
1328
+ type: "edit",
1329
+ why: "the jobs' marks and the storefront's cache"
1330
+ },
1331
+ {
1332
+ key: "workers_r2",
1333
+ type: "edit",
1334
+ why: "the media bucket"
1335
+ },
1336
+ {
1337
+ key: "query_cache",
1338
+ type: "edit",
1339
+ why: "the database connection"
1340
+ },
1341
+ {
1342
+ key: "zone",
1343
+ type: "read",
1344
+ why: "finding the domain"
1345
+ },
1346
+ {
1347
+ key: "workers_routes",
1348
+ type: "edit",
1349
+ why: "the Workers' custom domains"
1350
+ },
1351
+ {
1352
+ key: "dns",
1353
+ type: "edit",
1354
+ why: "the custom domains' records"
1355
+ },
1356
+ {
1357
+ key: "d1",
1358
+ type: "edit",
1359
+ why: "the co-located apps' databases"
1360
+ }
1361
+ ];
1362
+ /** The permissions as the form names them, for telling the person what to add. */
1363
+ const NAMES = {
1364
+ account_settings: "Account Settings",
1365
+ workers_scripts: "Workers Scripts",
1366
+ workers_tail: "Workers Tail",
1367
+ workers_kv_storage: "Workers KV Storage",
1368
+ workers_r2: "Workers R2 Storage",
1369
+ query_cache: "Hyperdrive",
1370
+ zone: "Zone",
1371
+ workers_routes: "Workers Routes",
1372
+ dns: "DNS",
1373
+ d1: "D1"
1374
+ };
1375
+ /** The dashboard's create-token page, filled in with `PERMISSIONS`. */
1376
+ function templateUrl(name = "Hypha deploy") {
1377
+ return `https://dash.cloudflare.com/profile/api-tokens?permissionGroupKeys=${encodeURIComponent(JSON.stringify(PERMISSIONS.map(({ key, type }) => ({
1378
+ key,
1379
+ type
1380
+ }))))}&accountId=*&zoneId=all&name=${encodeURIComponent(name)}`;
1381
+ }
1382
+ const API = "https://api.cloudflare.com/client/v4";
1383
+ /** A call to Cloudflare's API with `token`: its result, or `null` when it's refused. */
1384
+ async function call(get, token, path) {
1385
+ const response = await get(`${API}${path}`, { headers: { authorization: `Bearer ${token}` } });
1386
+ if (response.status === 401 || response.status === 403) return null;
1387
+ const body = await response.json().catch(() => null);
1388
+ if (!body) throw new Error(`Cloudflare's API answered ${path} with ${response.status}`);
1389
+ if (!body.success) return null;
1390
+ return body.result;
1391
+ }
1392
+ /** The permission `key` names, as the form shows it, with why deploying needs it. */
1393
+ function lacking(key) {
1394
+ const permission = PERMISSIONS.find((p) => p.key === key);
1395
+ return `${NAMES[key] ?? key} (${permission.type}): ${permission.why}`;
1396
+ }
1397
+ /**
1398
+ * Checks `token`: that it's valid, which account it reaches (`accountId` when given, else
1399
+ * the only one), that the account holds `domain`'s zone, and that each permission
1400
+ * deploying needs answers (a read of each kind of resource; `media` adds R2).
1401
+ */
1402
+ async function checkToken(token, domain, options, get = fetch) {
1403
+ const verified = await call(get, token, "/user/tokens/verify");
1404
+ if (!verified || verified.status !== "active") throw new Error("the API token isn't valid (or has expired): create one with the link, then paste it");
1405
+ const accounts = await call(get, token, "/accounts") ?? [];
1406
+ let accountId = options.accountId;
1407
+ if (!accountId) {
1408
+ if (accounts.length !== 1) throw new Error(`the token reaches ${accounts.length} accounts: pass --account-id` + (accounts.length ? `\n${accounts.map((a) => `${a.id} ${a.name}`).join("\n")}` : ""));
1409
+ accountId = accounts[0].id;
1410
+ } else if (accounts.length > 0 && !accounts.some((a) => a.id === accountId)) throw new Error(`the token doesn't reach account ${accountId}`);
1411
+ const labels = domain.split(".");
1412
+ let zoneId = options.zoneId;
1413
+ for (let i = 0; i < labels.length - 1 && !zoneId; i++) {
1414
+ const name = labels.slice(i).join(".");
1415
+ zoneId = (await call(get, token, `/zones?name=${encodeURIComponent(name)}&account.id=${accountId}`))?.[0]?.id;
1416
+ }
1417
+ if (!zoneId) throw new Error(`no zone for ${domain} in that account (or the token can't read zones): add the domain to Cloudflare first`);
1418
+ const probes = [
1419
+ [`/accounts/${accountId}/workers/scripts`, "workers_scripts"],
1420
+ [`/accounts/${accountId}/storage/kv/namespaces?per_page=5`, "workers_kv_storage"],
1421
+ [`/accounts/${accountId}/hyperdrive/configs`, "query_cache"],
1422
+ [`/zones/${zoneId}/workers/routes`, "workers_routes"],
1423
+ [`/zones/${zoneId}/dns_records?per_page=1`, "dns"]
1424
+ ];
1425
+ const missing = [];
1426
+ for (const [path, key] of probes) if (await call(get, token, path) === null) missing.push(lacking(key));
1427
+ if (options.apps && await call(get, token, `/accounts/${accountId}/d1/database?per_page=1`) === null) missing.push(lacking("d1"));
1428
+ const r2 = await call(get, token, `/accounts/${accountId}/r2/buckets`) !== null;
1429
+ if (options.media && !r2) missing.push(lacking("workers_r2"));
1430
+ return {
1431
+ accountId,
1432
+ zoneId,
1433
+ missing,
1434
+ r2
1435
+ };
1436
+ }
1437
+ //#endregion
1438
+ //#region src/commands/token.ts
1439
+ async function obtainToken(o) {
1440
+ if (!o.given && !o.known) {
1441
+ const link = templateUrl(`Hypha ${o.name}`);
1442
+ p.log.step(`Hypha deploys with a Cloudflare API token. Create one with this link (the permissions are
1443
+ filled in; pick the account and ${o.domain}'s zone), then paste it here:\n${link}`);
1444
+ if (process.stdin.isTTY && !o.quiet) openInBrowser(link);
1445
+ }
1446
+ const token = (await ask(o.given, o.known, () => p.password({
1447
+ message: "The API token",
1448
+ validate: (v) => v?.trim() ? void 0 : "paste the token"
1449
+ }))).trim();
1450
+ for (;;) {
1451
+ const spin = p.spinner();
1452
+ spin.start("Checking the token");
1453
+ let checked;
1454
+ try {
1455
+ checked = await checkToken(token, o.domain, {
1456
+ accountId: o.accountId,
1457
+ zoneId: o.zoneId,
1458
+ media: false,
1459
+ apps: o.apps
1460
+ });
1461
+ } catch (e) {
1462
+ spin.error("The token won't do");
1463
+ throw e;
1464
+ }
1465
+ if (checked.missing.length === 0) {
1466
+ spin.stop(`The token reaches the account and ${o.domain}`);
1467
+ return {
1468
+ token,
1469
+ checked
1470
+ };
1471
+ }
1472
+ spin.error("The token lacks permissions");
1473
+ const missing = checked.missing.map((m) => ` ${m}`).join("\n");
1474
+ const where = "dash.cloudflare.com/profile/api-tokens → the token's ⋯ → Edit";
1475
+ if (!process.stdin.isTTY || o.quiet) throw new Error(`add these to the token (${where}), then run this again:\n${missing}`);
1476
+ const again = await p.confirm({ message: `Add these to the token (${where}), then check again:\n${missing}` });
1477
+ if (p.isCancel(again) || !again) throw new Error("the token lacks permissions");
1478
+ }
1479
+ }
1480
+ /** Opens `link` in the browser, if this machine has a way; the link is printed anyway. */
1481
+ function openInBrowser(link) {
1482
+ const [program, ...args] = process.platform === "darwin" ? ["open"] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler"] : ["xdg-open"];
1483
+ run(program, [...args, link], { capture: true }).catch(() => {});
1484
+ }
1485
+ //#endregion
1486
+ //#region src/commands/apps.ts
1487
+ /** `rev` as a commit: a full commit ID as given, else a branch or tag asked of the remote. */
1488
+ async function resolveRev(git, rev) {
1489
+ if (rev && /^[0-9a-f]{40}$/.test(rev)) return rev;
1490
+ if (rev && /^[0-9a-f]{7,39}$/.test(rev)) throw new Error(`--rev ${rev}: give the full commit ID (40 hex digits), or a branch or tag`);
1491
+ return remoteHead(git, rev ? rev : "HEAD");
1492
+ }
1493
+ /** Pins every app and git spore listed without a commit (a first-party name alone in
1494
+ * `hypha.json`) to its repository's head, and saves it. */
1495
+ async function pinUnpinned(dir, d) {
1496
+ let changed = false;
1497
+ for (const entry of d.apps ?? []) {
1498
+ if (entry.rev) continue;
1499
+ entry.rev = await remoteHead(entry.git);
1500
+ p.log.step(`Pinned the ${entry.name} app to ${entry.rev.slice(0, 12)} (its head)`);
1501
+ changed = true;
1502
+ }
1503
+ for (const entry of d.spores ?? []) {
1504
+ if (!entry.git || entry.rev) continue;
1505
+ entry.rev = await remoteHead(entry.git);
1506
+ p.log.step(`Pinned the ${entry.name} spore to ${entry.rev.slice(0, 12)} (its head)`);
1507
+ changed = true;
1508
+ }
1509
+ if (changed) await saveDeployment(dir, d);
1510
+ }
1511
+ /** Makes each app's `APP_ENCRYPTION_KEY` that `.env` lacks; whether it made one. */
1512
+ function ensureEncryptionKeys(d, env) {
1513
+ let made = false;
1514
+ for (const entry of d.apps ?? []) {
1515
+ if (env.get(encryptionKeyVar(entry))) continue;
1516
+ env.comment("").comment(`The ${entry.name} app's APP_ENCRYPTION_KEY: it seals the app's secrets. Keep it.`).set(encryptionKeyVar(entry), newEncryptionKey());
1517
+ made = true;
1518
+ }
1519
+ return made;
1520
+ }
1521
+ /**
1522
+ * For each co-located app the store hasn't installed: its install link, printed and
1523
+ * (in a terminal, unless `quiet`) opened. A staff member approves it on the consent
1524
+ * page; nothing installs silently.
1525
+ */
1526
+ async function offerInstalls(d, env, options = {}) {
1527
+ const apps = (d.apps ?? []).filter((a) => !options.only || a.name === options.only);
1528
+ if (apps.length === 0) return;
1529
+ const staff = await staffFor(d, env);
1530
+ const statuses = await appStatuses({
1531
+ ...d,
1532
+ apps
1533
+ }, staff);
1534
+ const pending = statuses.filter((s) => s.installed !== true);
1535
+ for (const done of statuses.filter((s) => s.installed === true)) p.log.step(`The ${done.entry.name} app is installed (${done.key})`);
1536
+ if (pending.length === 0) return;
1537
+ p.note(pending.map((s) => `${s.entry.name.padEnd(12)} ${s.link}`).join("\n"), staff ? "Install these apps: open each link and approve it as a staff member" : "Install these apps (if the store hasn't): open each link and approve it");
1538
+ if (process.stdin.isTTY && !options.quiet) for (const s of pending) openInBrowser(s.link);
1539
+ }
1540
+ const apps = defineCommand({
1541
+ meta: {
1542
+ name: "apps",
1543
+ description: "Apps deployed alongside Hypha (Stripe, Meilisearch, or any app's repository)"
1544
+ },
1545
+ subCommands: {
1546
+ add: defineCommand({
1547
+ meta: {
1548
+ name: "add",
1549
+ description: "List an app in hypha.json, pinned to its repository's head (then deploy)"
1550
+ },
1551
+ args: {
1552
+ dir: dirArg,
1553
+ app: {
1554
+ type: "positional",
1555
+ required: true,
1556
+ description: "stripe, meilisearch, or a git URL"
1557
+ },
1558
+ rev: {
1559
+ type: "string",
1560
+ description: "A commit, branch or tag (default: the head)"
1561
+ },
1562
+ name: {
1563
+ type: "string",
1564
+ description: "Its name (default: from the repository's)"
1565
+ },
1566
+ domain: {
1567
+ type: "string",
1568
+ description: "Its domain (default <name>.<your domain>)"
1569
+ }
1570
+ },
1571
+ run: ({ args }) => guarded(async () => {
1572
+ const d = await loadDeployment(args.dir);
1573
+ p.intro("hypha apps add");
1574
+ const entry = entryFor(args.app, args.name);
1575
+ if ((d.apps ?? []).some((a) => a.name === entry.name)) throw new Error(`the ${entry.name} app is listed already: \`hypha apps update ${entry.name}\` moves its commit`);
1576
+ if (args.domain) {
1577
+ const domain = appDomainOf(args.domain);
1578
+ if (!domain) throw new Error(`--domain: ${args.domain} isn't a domain`);
1579
+ entry.domain = domain;
1580
+ }
1581
+ entry.rev = await resolveRev(entry.git, args.rev);
1582
+ d.apps = [...d.apps ?? [], entry];
1583
+ if (Object.values(d.domains).includes(appDomain(d, entry))) throw new Error(`${appDomain(d, entry)} is taken by the deployment: pass --domain`);
1584
+ await saveDeployment(args.dir, d);
1585
+ const env = await loadEnv(args.dir).catch(() => void 0);
1586
+ if (env && ensureEncryptionKeys(d, env)) await saveEnv(args.dir, env);
1587
+ p.note([
1588
+ `Repository ${entry.git}`,
1589
+ `Commit ${entry.rev}`,
1590
+ `URL ${appUrl(d, entry)}`,
1591
+ d.target === "cloudflare" ? `Worker ${appWorkerName(d, entry)} (with its D1 database)` : `Container ${service(entry)}`
1592
+ ].join("\n"), `Added the ${entry.name} app`);
1593
+ if (d.target === "vps") p.log.step(`Point ${appDomain(d, entry)} at the server before deploying.`);
1594
+ if (d.target === "cloudflare") p.log.step("The deploy token needs D1 (edit) for the app's database.");
1595
+ p.outro("Next: hypha deploy (then approve the app's install)");
1596
+ })
1597
+ }),
1598
+ update: defineCommand({
1599
+ meta: {
1600
+ name: "update",
1601
+ description: "Move an app (or every app) to its head, or --rev"
1602
+ },
1603
+ args: {
1604
+ dir: dirArg,
1605
+ app: {
1606
+ type: "positional",
1607
+ required: false,
1608
+ description: "One app; all without"
1609
+ },
1610
+ rev: {
1611
+ type: "string",
1612
+ description: "A commit, branch or tag (with one app)"
1613
+ }
1614
+ },
1615
+ run: ({ args }) => guarded(async () => {
1616
+ const d = await loadDeployment(args.dir);
1617
+ p.intro("hypha apps update");
1618
+ const listed = d.apps ?? [];
1619
+ if (args.rev && !args.app) throw new Error("--rev needs the app's name");
1620
+ const chosen = args.app ? listed.filter((a) => a.name === args.app) : listed;
1621
+ if (args.app && chosen.length === 0) throw new Error(`no ${args.app} app in hypha.json: \`hypha apps add ${args.app}\``);
1622
+ if (chosen.length === 0) throw new Error("no apps in hypha.json: `hypha apps add`");
1623
+ for (const entry of chosen) {
1624
+ const rev = await resolveRev(entry.git, args.rev);
1625
+ p.log.step(entry.rev === rev ? `${entry.name}: at ${rev.slice(0, 12)} already` : `${entry.name}: ${entry.rev?.slice(0, 12) ?? "unpinned"} → ${rev.slice(0, 12)}`);
1626
+ entry.rev = rev;
1627
+ }
1628
+ await saveDeployment(args.dir, d);
1629
+ p.outro("Next: hypha deploy");
1630
+ })
1631
+ }),
1632
+ remove: defineCommand({
1633
+ meta: {
1634
+ name: "remove",
1635
+ description: "Take an app out of hypha.json"
1636
+ },
1637
+ args: {
1638
+ dir: dirArg,
1639
+ app: {
1640
+ type: "positional",
1641
+ required: true,
1642
+ description: "The app's name"
1643
+ }
1644
+ },
1645
+ run: ({ args }) => guarded(async () => {
1646
+ const wrong = checkAppName(args.app);
1647
+ if (wrong) throw new Error(`${args.app}: ${wrong}`);
1648
+ const d = await loadDeployment(args.dir);
1649
+ p.intro("hypha apps remove");
1650
+ const entry = (d.apps ?? []).find((a) => a.name === args.app);
1651
+ if (!entry) throw new Error(`no ${args.app} app in hypha.json`);
1652
+ d.apps = (d.apps ?? []).filter((a) => a !== entry);
1653
+ await saveDeployment(args.dir, d);
1654
+ p.log.step(d.target === "cloudflare" ? `The next deploy unbinds it; its Worker ${appWorkerName(d, entry)} and D1 database stay until you delete them (wrangler delete, wrangler d1 delete).` : `The next deploy stops its container; its data volume stays (docker volume rm).`);
1655
+ p.log.step("The store keeps its installation: uninstall it in the admin (Settings → Apps).");
1656
+ p.outro(`Removed. Keep ${encryptionKeyVar(entry)} in .env if you might bring it back.`);
1657
+ })
1658
+ }),
1659
+ status: defineCommand({
1660
+ meta: {
1661
+ name: "status",
1662
+ description: "Whether each app answers and is installed in the store"
1663
+ },
1664
+ args: { dir: dirArg },
1665
+ run: ({ args }) => guarded(async () => {
1666
+ const d = await loadDeployment(args.dir);
1667
+ p.intro("hypha apps status");
1668
+ if (!d.apps?.length) {
1669
+ p.outro("No apps: `hypha apps add stripe`, say");
1670
+ return;
1671
+ }
1672
+ const staff = await staffFor(d, await loadEnv(args.dir).catch(() => void 0));
1673
+ if (!staff) p.log.warn("Can't read the store's apps: set HYPHA_ADMIN_KEY (a secret key with apps:read), or the owner's login in .env");
1674
+ const statuses = await appStatuses(d, staff);
1675
+ for (const s of statuses) {
1676
+ const installed = s.installed === void 0 ? "?" : s.installed ? "installed" : "not installed";
1677
+ p.log.step([
1678
+ `${s.entry.name.padEnd(12)} ${s.entry.rev?.slice(0, 12) ?? "unpinned".padEnd(12)} ${s.url}`,
1679
+ `${"".padEnd(12)} ${s.reachable ? "answers" : "doesn't answer"}, ${installed} (${s.key})`,
1680
+ ...s.installed === false ? [`${"".padEnd(12)} install: ${s.link}`] : []
1681
+ ].join("\n"));
1682
+ }
1683
+ const bad = statuses.some((s) => !s.reachable || s.installed === false);
1684
+ p.outro(bad ? "Not all ready" : "Every app answers and is installed");
1685
+ if (bad) process.exitCode = 1;
1686
+ })
1687
+ }),
1688
+ install: defineCommand({
1689
+ meta: {
1690
+ name: "install",
1691
+ description: "Open the install link of each app the store hasn't installed"
1692
+ },
1693
+ args: {
1694
+ dir: dirArg,
1695
+ app: {
1696
+ type: "positional",
1697
+ required: false,
1698
+ description: "One app; all without"
1699
+ },
1700
+ yes: {
1701
+ type: "boolean",
1702
+ alias: "y",
1703
+ description: "Print the links, don't open them"
1704
+ }
1705
+ },
1706
+ run: ({ args }) => guarded(async () => {
1707
+ const d = await loadDeployment(args.dir);
1708
+ p.intro("hypha apps install");
1709
+ if (args.app && !(d.apps ?? []).some((a) => a.name === args.app)) throw new Error(`no ${args.app} app in hypha.json`);
1710
+ await offerInstalls(d, await loadEnv(args.dir).catch(() => void 0), {
1711
+ quiet: Boolean(args.yes),
1712
+ only: args.app
1713
+ });
1714
+ p.outro(`Then: hypha apps status${args.dir === "hypha-deploy" ? "" : ` --dir ${args.dir}`}`);
1715
+ })
1716
+ })
1717
+ }
1718
+ });
1719
+ //#endregion
1720
+ //#region src/version.ts
1721
+ const VERSION = "0.1.0-beta.3";
1722
+ //#endregion
1723
+ //#region src/create.ts
1724
+ /** The repository the starters are downloaded from. */
1725
+ const REPOSITORY = "hyphacommerce/hypha";
1726
+ const STARTERS = {
1727
+ storefront: {
1728
+ path: "apps/storefront",
1729
+ title: "Hypha's storefront: a server-rendered shop on Next.js, vinext and Astryx",
1730
+ next: [
1731
+ "cp .env.example .dev.vars # then fill in HYPHA_API_URL and a publishable key",
1732
+ "pnpm install",
1733
+ "pnpm dev # http://localhost:3002"
1734
+ ]
1735
+ },
1736
+ app: {
1737
+ path: "starters/app",
1738
+ title: "An app for Hypha's apps platform: installed over OAuth, answering webhooks and an extension point",
1739
+ next: [
1740
+ "pnpm install",
1741
+ "pnpm test",
1742
+ "APP_URL=http://localhost:8787 pnpm dev # then install it from your admin: Apps → Install app"
1743
+ ]
1744
+ }
1745
+ };
1746
+ function isStarter(name) {
1747
+ return Object.hasOwn(STARTERS, name);
1748
+ }
1749
+ /** What a copy leaves behind: a workspace's builds, caches and local secrets. */
1750
+ const SKIPPED = /* @__PURE__ */ new Set([
1751
+ "node_modules",
1752
+ "dist",
1753
+ ".next",
1754
+ ".vinext",
1755
+ ".cloudflare",
1756
+ ".wrangler",
1757
+ ".dev.vars",
1758
+ "next-env.d.ts",
1759
+ ".DS_Store"
1760
+ ]);
1761
+ function skipped(name) {
1762
+ return SKIPPED.has(name) || name.endsWith(".tsbuildinfo") || /^\.env.*\.local$/.test(name);
1763
+ }
1764
+ /** The tag a version was released as. */
1765
+ function tagOf(version) {
1766
+ return `v${version}`;
1767
+ }
1768
+ /** The release's source archive, and the folder inside it. */
1769
+ function archiveOf(ref) {
1770
+ const tag = ref.startsWith("v") || !/^\d/.test(ref) ? ref : tagOf(ref);
1771
+ return {
1772
+ url: `https://codeload.github.com/${REPOSITORY}/tar.gz/${encodeURIComponent(tag)}`,
1773
+ root: `hypha-${tag.replace(/^v/, "").replaceAll("/", "-")}`
1774
+ };
1775
+ }
1776
+ /** The starter's `.gitignore`: what the workspace's covered for it. */
1777
+ const GITIGNORE = `node_modules/
1778
+ dist/
1779
+ .next/
1780
+ .cloudflare/
1781
+ .wrangler/
1782
+ .vinext/
1783
+ *.tsbuildinfo
1784
+ .env*.local
1785
+ .dev.vars
1786
+ wrangler.toml
1787
+ next-env.d.ts
1788
+ .DS_Store
1789
+ `;
1790
+ /** pnpm's settings for the project (pnpm reads them from this file, not package.json). */
1791
+ function workspaceYaml() {
1792
+ return "# pnpm's settings for this project.\n# Hypha's packages are released together with this starter: never hold them back as too new.\nminimumReleaseAgeExclude:\n - \"@hyphacommerce/*\"\n# Dependency install scripts run only when listed here (pnpm refuses an install with one\n# it wasn't told about). workerd is the Workers runtime the dev server runs in; esbuild and\n# sharp find their binaries without their scripts; Astryx's script only prints a hint.\nallowBuilds:\n workerd: true\n esbuild: false\n sharp: false\n \"@astryxdesign/core\": false\n \"@astryxdesign/cli\": false\n";
1793
+ }
1794
+ function isRecord(value) {
1795
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1796
+ }
1797
+ /** A record of strings from a JSON value, or none. */
1798
+ function strings(value) {
1799
+ if (!isRecord(value)) return void 0;
1800
+ const out = {};
1801
+ for (const [key, item] of Object.entries(value)) if (typeof item === "string") out[key] = item;
1802
+ return out;
1803
+ }
1804
+ /** A JSON object from `text`; anything else is refused with `what`. */
1805
+ function parseObject(text, what) {
1806
+ const value = JSON.parse(text);
1807
+ if (!isRecord(value)) throw new Error(`${what} isn't a JSON object`);
1808
+ return value;
1809
+ }
1810
+ /**
1811
+ * The project's `package.json` from the starter's: named after its folder, its
1812
+ * `workspace:*` dependencies at `version` (Hypha's packages on npm), and the workspace's
1813
+ * `packageManager` and `engines`, which pnpm and Node read from the project.
1814
+ */
1815
+ function adaptManifest(source, name, version, root) {
1816
+ const swap = (deps) => deps && Object.fromEntries(Object.entries(deps).map(([dep, spec]) => [dep, spec.startsWith("workspace:") ? version : spec]));
1817
+ const { version: _version, ...rest } = source;
1818
+ return {
1819
+ ...rest,
1820
+ name,
1821
+ private: true,
1822
+ ...root.packageManager ? { packageManager: root.packageManager } : {},
1823
+ ...root.engines ? { engines: root.engines } : {},
1824
+ dependencies: swap(source.dependencies),
1825
+ devDependencies: swap(source.devDependencies)
1826
+ };
1827
+ }
1828
+ /** A project name from the folder: lowercase, what npm allows. */
1829
+ function projectName(dir) {
1830
+ return basename(resolve(dir)).toLowerCase().replaceAll(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "") || "hypha-project";
1831
+ }
1832
+ /** Copies `from` into `to`, leaving builds, caches and local secrets behind. */
1833
+ async function copyStarter(from, to) {
1834
+ await cp(from, to, {
1835
+ recursive: true,
1836
+ filter: (path) => !skipped(basename(path))
1837
+ });
1838
+ }
1839
+ /** Downloads the release's archive and extracts the starter's folder from it. */
1840
+ async function downloadStarter(ref, path, to) {
1841
+ const { url, root } = archiveOf(ref);
1842
+ const work = await mkdtemp(join(tmpdir(), "hypha-create-"));
1843
+ try {
1844
+ const response = await fetch(url);
1845
+ if (!response.ok) throw new Error(response.status === 404 ? `no release ${ref} of ${REPOSITORY} (${url}): pass --ref to create from another tag or branch` : `downloading ${url}: HTTP ${response.status}`);
1846
+ const archive = join(work, "source.tar.gz");
1847
+ await writeFile(archive, new Uint8Array(await response.arrayBuffer()));
1848
+ await run("tar", [
1849
+ "-xzf",
1850
+ archive,
1851
+ "-C",
1852
+ to,
1853
+ `--strip-components=${path.split("/").length + 1}`,
1854
+ `${root}/${path}`
1855
+ ], { capture: true });
1856
+ } finally {
1857
+ await rm(work, {
1858
+ recursive: true,
1859
+ force: true
1860
+ });
1861
+ }
1862
+ }
1863
+ /** Makes `dir` from the starter `kind`; refuses a folder that isn't empty. */
1864
+ async function create(kind, dir, options = {}) {
1865
+ const starter = STARTERS[kind];
1866
+ const target = resolve(dir);
1867
+ if (await exists$1(target)) {
1868
+ if ((await readdir(target)).length > 0) throw new Error(`${dir} exists and isn't empty`);
1869
+ }
1870
+ const checkout = options.from ?? (options.ref === void 0 && inCheckout() ? REPO : void 0);
1871
+ let source;
1872
+ let root = {};
1873
+ if (checkout) {
1874
+ await copyStarter(join(checkout, starter.path), target);
1875
+ root = pick$1(parseObject(await readFile(join(checkout, "package.json"), "utf8"), "package.json"));
1876
+ source = `the checkout at ${checkout}`;
1877
+ } else {
1878
+ const ref = options.ref ?? tagOf(VERSION);
1879
+ await mkdir(target, { recursive: true });
1880
+ await downloadStarter(ref, starter.path, target);
1881
+ root = {
1882
+ packageManager: ROOT_PACKAGE_MANAGER,
1883
+ engines: ROOT_ENGINES
1884
+ };
1885
+ source = `${REPOSITORY} at ${ref}`;
1886
+ }
1887
+ const name = projectName(target);
1888
+ const manifestPath = join(target, "package.json");
1889
+ const raw = parseObject(await readFile(manifestPath, "utf8"), `${starter.path}/package.json`);
1890
+ const manifest = {
1891
+ ...raw,
1892
+ dependencies: strings(raw.dependencies),
1893
+ devDependencies: strings(raw.devDependencies)
1894
+ };
1895
+ await writeFile(manifestPath, JSON.stringify(adaptManifest(manifest, name, VERSION, root), null, 2) + "\n");
1896
+ await writeFile(join(target, ".gitignore"), GITIGNORE);
1897
+ await writeFile(join(target, "pnpm-workspace.yaml"), workspaceYaml());
1898
+ return {
1899
+ dir: target,
1900
+ name,
1901
+ source
1902
+ };
1903
+ }
1904
+ /** What the workspace's root package.json pins, read when creating from a checkout. */
1905
+ function pick$1(root) {
1906
+ const engines = strings(root.engines);
1907
+ return {
1908
+ ...typeof root.packageManager === "string" ? { packageManager: root.packageManager } : {},
1909
+ ...engines ? { engines } : {}
1910
+ };
1911
+ }
1912
+ const ROOT_PACKAGE_MANAGER = "pnpm@12.6.0";
1913
+ const ROOT_ENGINES = { node: ">=24" };
1914
+ async function exists$1(path) {
1915
+ return stat(path).then(() => true, () => false);
1916
+ }
1917
+ //#endregion
1918
+ //#region src/commands/create.ts
1919
+ const createCommand = defineCommand({
1920
+ meta: {
1921
+ name: "create",
1922
+ description: "A project of your own from a starter: the storefront, or an app"
1923
+ },
1924
+ args: {
1925
+ starter: {
1926
+ type: "positional",
1927
+ required: false,
1928
+ description: `One of ${Object.keys(STARTERS).join(", ")}`
1929
+ },
1930
+ dir: {
1931
+ type: "positional",
1932
+ required: false,
1933
+ description: "The new project's folder"
1934
+ },
1935
+ ref: {
1936
+ type: "string",
1937
+ description: `A tag or branch of hyphacommerce/hypha to take the starter from (default v${VERSION}, this CLI's release)`
1938
+ },
1939
+ yes: {
1940
+ type: "boolean",
1941
+ default: false,
1942
+ description: "Take defaults instead of asking"
1943
+ }
1944
+ },
1945
+ run: ({ args }) => guarded(async () => {
1946
+ setUnattended(args.yes);
1947
+ p.intro(`hypha create (v${VERSION})`);
1948
+ const starter = await ask(args.starter, void 0, () => p.select({
1949
+ message: "What are you starting?",
1950
+ options: Object.entries(STARTERS).map(([value, s]) => ({
1951
+ value,
1952
+ label: value,
1953
+ hint: s.title
1954
+ }))
1955
+ }));
1956
+ if (!isStarter(starter)) throw new Error(`no starter ${JSON.stringify(starter)}: one of ${Object.keys(STARTERS).join(", ")}`);
1957
+ const dir = await ask(args.dir, `my-${starter}`, () => p.text({
1958
+ message: "Its folder",
1959
+ placeholder: `my-${starter}`,
1960
+ defaultValue: `my-${starter}`
1961
+ }));
1962
+ const made = await create(starter, dir, { ref: args.ref });
1963
+ p.log.success(`${made.name} in ${made.dir}, from ${made.source}; Hypha's packages at ${VERSION}`);
1964
+ p.note([`cd ${dir}`, ...STARTERS[starter].next].join("\n"), "Next");
1965
+ p.outro(`${STARTERS[starter].title}.`);
1966
+ })
1967
+ });
1968
+ //#endregion
1969
+ //#region src/storefront.ts
1970
+ /** The events that change what a static page shows. */
1971
+ const EVENTS = [
1972
+ "product.*",
1973
+ "inventory_item.*",
1974
+ "price_list.*",
1975
+ "catalog.*",
1976
+ "channel.*",
1977
+ "category.*",
1978
+ "market.*",
1979
+ "custom_field_definition.*",
1980
+ "discount.created",
1981
+ "discount.updated",
1982
+ "discount.deleted",
1983
+ "discount.started",
1984
+ "discount.ended"
1985
+ ];
1986
+ /**
1987
+ * The storefront's order link for emails (`order_url`): `app/order/[id]/route.ts` keeps
1988
+ * the token in the buyer's cookie and opens the confirmation in the order's country, in
1989
+ * either routing mode.
1990
+ */
1991
+ function orderUrl(d) {
1992
+ return `${url(d, d.domains.storefront)}/order/{order}?token={token}`;
1993
+ }
1994
+ /** Points the emails' order links at the storefront unless the store has its own;
1995
+ * answers the pattern it set, `null` when it kept the store's. */
1996
+ async function linkOrders(d, staff) {
1997
+ if ((await staff.call("GET", "/admin/notification-settings")).order_url) return null;
1998
+ const pattern = orderUrl(d);
1999
+ await staff.call("PATCH", "/admin/notification-settings", { order_url: pattern });
2000
+ return pattern;
2001
+ }
2002
+ /** Where the API should deliver the storefront's events. */
2003
+ function webhookUrl(d) {
2004
+ return `${url(d, d.domains.storefront)}/api/revalidate`;
2005
+ }
2006
+ /** Points the storefront's webhook at its current domain and adds the events it has
2007
+ * come to need since it was connected (keeping any the merchant added); answers the new
2008
+ * URL when it moved, `null` when it was already right. */
2009
+ async function syncWebhook(d, staff) {
2010
+ const app = await staff.call("GET", "/admin/apps/app_storefront");
2011
+ const target = webhookUrl(d);
2012
+ const moved = app.webhook?.url !== target;
2013
+ const missing = EVENTS.filter((e) => !app.subscriptions.includes(e));
2014
+ if (!moved && missing.length === 0) return null;
2015
+ await staff.call("PATCH", "/admin/apps/app_storefront", {
2016
+ ...moved ? { webhook: { url: target } } : {},
2017
+ ...missing.length > 0 ? { subscriptions: [...app.subscriptions, ...missing] } : {}
2018
+ });
2019
+ return moved ? target : null;
2020
+ }
2021
+ /**
2022
+ * The order links first, then the app: a second run after a failure finds the links set
2023
+ * and keeps them, and the app is the call that can be refused (a webhook URL the API
2024
+ * won't call), which leaves nothing behind (on a server or on Cloudflare alike). On this
2025
+ * machine there's no webhook: the API
2026
+ * calls only https URLs (or localhost), and the storefront is reachable from its
2027
+ * container only as `http://storefront:3000`. Its static pages then refresh within
2028
+ * their five minutes.
2029
+ */
2030
+ async function connectStorefront(d, staff) {
2031
+ const channel = (await staff.call("GET", "/admin/channels")).items.find((c) => c.kind === "online_store");
2032
+ if (!channel) throw new Error("the store has no Online Store channel to sell through");
2033
+ const linked = await linkOrders(d, staff);
2034
+ let webhookSecret = null;
2035
+ if (d.target !== "local") webhookSecret = (await staff.call("POST", "/admin/apps", {
2036
+ key: "app_storefront",
2037
+ name: "Storefront",
2038
+ subscriptions: EVENTS,
2039
+ webhook: { url: webhookUrl(d) }
2040
+ })).secret;
2041
+ return {
2042
+ key: (await staff.call("POST", "/admin/api-keys", {
2043
+ kind: "publishable",
2044
+ name: "Storefront",
2045
+ channel: channel.id
2046
+ })).token,
2047
+ webhookSecret,
2048
+ orderUrl: linked
2049
+ };
2050
+ }
2051
+ //#endregion
2052
+ //#region src/cloudflare.ts
2053
+ /** The generated configuration, next to `hypha.json`. */
2054
+ const WRANGLER_FILE = "wrangler.toml";
2055
+ const SECRETS_FILE = ".secrets.json";
2056
+ const WORKER_CRATE = join(REPO, "crates", "hypha-host-workers");
2057
+ /** The database's `host:port`, which the Worker is placed next to. */
2058
+ function databaseHost(databaseUrl) {
2059
+ const parsed = new URL(databaseUrl);
2060
+ return `${parsed.hostname}:${parsed.port || "5432"}`;
2061
+ }
2062
+ /** Why `databaseUrl` can't be a Worker's database, if it can't. */
2063
+ function checkDatabaseUrl(databaseUrl) {
2064
+ let parsed;
2065
+ try {
2066
+ parsed = new URL(databaseUrl ?? "");
2067
+ } catch {
2068
+ return "a Postgres URL like postgres://user:password@host:5432/database";
2069
+ }
2070
+ if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") return "a postgres:// URL";
2071
+ if (!parsed.username || !parsed.password) return "a URL with the user and password";
2072
+ if (/^(localhost|127\.|\[?::1\]?$|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(parsed.hostname)) return "a database Cloudflare can reach: Hyperdrive connects from Cloudflare's network, not from here";
2073
+ }
2074
+ /** The R2 bucket's S3 endpoint. */
2075
+ function r2Endpoint(accountId) {
2076
+ return `https://${accountId}.r2.cloudflarestorage.com`;
2077
+ }
2078
+ /** A TOML string: JSON's escapes are TOML's. */
2079
+ const str = (value) => JSON.stringify(value);
2080
+ /** The Worker's `wrangler.toml`, written on every deploy from `hypha.json`. */
2081
+ function wranglerToml(d, input) {
2082
+ const cf = d.cloudflare;
2083
+ const workerCrate = input.workerCrate ?? WORKER_CRATE;
2084
+ const crate = relative(input.dir, workerCrate) || ".";
2085
+ const vars = [["HYPHA_CONFIG", input.config]];
2086
+ if (input.media) {
2087
+ vars.push(["HYPHA_S3_ENDPOINT", r2Endpoint(input.accountId)], ["HYPHA_S3_REGION", "auto"], ["HYPHA_S3_BUCKET", bucket(d)]);
2088
+ if (cf.zoneId) vars.push(["HYPHA_MEDIA_URL", url(d, d.domains.media)]);
2089
+ }
2090
+ if (d.domains.admin) vars.push(["HYPHA_ADMIN_URL", url(d, d.domains.admin)]);
2091
+ vars.push(["HYPHA_PUBLIC_URL", url(d, d.domains.api)]);
2092
+ const bound = input.apps ?? [];
2093
+ if (bound.length > 0) vars.push(["HYPHA_APP_BINDINGS", bound.map((a) => `${a.host}=${a.binding}`).join(",")]);
2094
+ const services = bound.flatMap((a) => [
2095
+ "[[services]]",
2096
+ `binding = ${str(a.binding)}`,
2097
+ `service = ${str(a.worker)}`,
2098
+ ""
2099
+ ]);
2100
+ const placement = cf.region ? [
2101
+ "[placement]",
2102
+ "mode = \"targeted\"",
2103
+ `region = ${str(cf.region)}`
2104
+ ] : [
2105
+ "[placement]",
2106
+ "mode = \"targeted\"",
2107
+ `host = ${str(databaseHost(input.databaseUrl))}`
2108
+ ];
2109
+ const limits = input.bindings.flatMap((b) => {
2110
+ if (!Number.isInteger(b.slot) || b.slot < 0 || b.slot >= 100) throw new Error(`${b.binding}: slot ${b.slot} is outside a deployment's block of 100`);
2111
+ return [
2112
+ "[[ratelimits]]",
2113
+ `name = ${str(b.binding)}`,
2114
+ `namespace_id = ${str(String(cf.rateLimitBase + b.slot))}`,
2115
+ `simple = { limit = ${b.limit}, period = ${b.period} }`,
2116
+ ""
2117
+ ];
2118
+ });
2119
+ return [
2120
+ "# Written by `hypha deploy` from hypha.json and hypha.config.toml on every deploy",
2121
+ "#: change those, not this file.",
2122
+ `name = ${str(workerName(d))}`,
2123
+ `main = ${str(`${crate}/build/worker/shim.mjs`)}`,
2124
+ `compatibility_date = ${str(input.compatibilityDate)}`,
2125
+ `account_id = ${str(input.accountId)}`,
2126
+ "workers_dev = false",
2127
+ `routes = [{ pattern = ${str(d.domains.api)}, custom_domain = true }]`,
2128
+ "",
2129
+ "[build]",
2130
+ `command = ${str("worker-build --release")}`,
2131
+ `cwd = ${str(workerCrate)}`,
2132
+ "",
2133
+ "# Next to the database: its round trips are most of a request (W12).",
2134
+ ...placement,
2135
+ "",
2136
+ "# Query cache off: the API's reads outside transactions (sessions, keys) must be fresh.",
2137
+ "[[hyperdrive]]",
2138
+ "binding = \"HYPERDRIVE\"",
2139
+ `id = ${str(input.hyperdriveId)}`,
2140
+ "",
2141
+ "[[kv_namespaces]]",
2142
+ "binding = \"JOBS\"",
2143
+ `id = ${str(input.kvId)}`,
2144
+ "",
2145
+ "# Per rule: the most its [rate_limits] quota allows in a minute (W8).",
2146
+ ...limits,
2147
+ ...services.length > 0 ? ["# Co-located apps: calls to their domains stay on Cloudflare.", ...services] : [],
2148
+ "[triggers]",
2149
+ "crons = [\"* * * * *\"]",
2150
+ "",
2151
+ "[observability]",
2152
+ "enabled = true",
2153
+ "",
2154
+ "[vars]",
2155
+ ...vars.map(([key, value]) => `${key} = ${str(value)}`),
2156
+ ""
2157
+ ].join("\n");
2158
+ }
2159
+ const workerName = (d) => `${d.cloudflare.name}-api`;
2160
+ const bucket = (d) => `${d.cloudflare.name}-media`;
2161
+ const kvTitle = (d) => `${d.cloudflare.name}-jobs`;
2162
+ const hyperdriveName = (d) => d.cloudflare.name;
2163
+ /** The first 32-hex-digit ID in wrangler's output (what `create` commands print). */
2164
+ function idIn(output) {
2165
+ return /\b[0-9a-f]{32}\b/.exec(output)?.[0];
2166
+ }
2167
+ /** R2's CORS rule: the admin uploads files straight to the bucket with signed URLs. */
2168
+ function corsRules(adminOrigin) {
2169
+ return `${JSON.stringify({ rules: [{
2170
+ allowed: {
2171
+ origins: [adminOrigin],
2172
+ methods: [
2173
+ "GET",
2174
+ "HEAD",
2175
+ "PUT"
2176
+ ],
2177
+ headers: ["content-type"]
2178
+ },
2179
+ exposeHeaders: ["ETag"],
2180
+ maxAgeSeconds: 3600
2181
+ }] }, null, 2)}\n`;
2182
+ }
2183
+ const appWorker = (d, app) => `${d.cloudflare.name}-${app}`;
2184
+ const cacheTitle = (d) => `${d.cloudflare.name}-cache`;
2185
+ /** Hyperdrive's origin flags: the URL without its query (TLS is `--sslmode`, which
2186
+ * Hyperdrive takes for `require` and stricter), and the query cache always off. */
2187
+ function hyperdriveOrigin(databaseUrl) {
2188
+ const parsed = new URL(databaseUrl);
2189
+ const sslmode = parsed.searchParams.get("sslmode");
2190
+ parsed.search = "";
2191
+ return [
2192
+ "--connection-string",
2193
+ parsed.toString(),
2194
+ ...sslmode && [
2195
+ "require",
2196
+ "verify-ca",
2197
+ "verify-full"
2198
+ ].includes(sslmode) ? ["--sslmode", sslmode] : [],
2199
+ "--caching-disabled"
2200
+ ];
2201
+ }
2202
+ /** `work`, with the database password left out of its error (the command line). */
2203
+ async function redacted(work, password) {
2204
+ try {
2205
+ return await work;
2206
+ } catch (e) {
2207
+ const message = e instanceof Error ? e.message : String(e);
2208
+ throw new Error(password ? message.replaceAll(password, "***").replaceAll(encodeURIComponent(password), "***") : message);
2209
+ }
2210
+ }
2211
+ /** What's already there is fine: wrangler says so in its error. */
2212
+ async function tolerate(work, already) {
2213
+ try {
2214
+ await work;
2215
+ } catch (e) {
2216
+ if (!already.test(e instanceof Error ? e.message : String(e))) throw e;
2217
+ }
2218
+ }
2219
+ async function deployCloudflare(dir, d, env, tools) {
2220
+ const cf = d.cloudflare;
2221
+ if (!cf) throw new Error("hypha.json: a cloudflare deployment needs `cloudflare`");
2222
+ const databaseUrl = env.get("DATABASE_URL");
2223
+ const problem = checkDatabaseUrl(databaseUrl);
2224
+ if (!databaseUrl || problem) throw new Error(`.env: DATABASE_URL should be ${problem}`);
2225
+ const secretKey = env.get("HYPHA_SECRET_KEY");
2226
+ if (!secretKey) throw new Error(".env: HYPHA_SECRET_KEY is missing");
2227
+ const spores = d.spores ?? [];
2228
+ const local = spores.length ? await fetchSpores(dir, spores) : {};
2229
+ const hostCrate = spores.length ? await writeHostCrate(dir, spores, local) : void 0;
2230
+ const workerCrate = spores.length ? await writeWorkerCrate(dir, spores, local) : void 0;
2231
+ const keyId = env.get("R2_ACCESS_KEY_ID");
2232
+ const keySecret = env.get("R2_SECRET_ACCESS_KEY");
2233
+ const media = Boolean(keyId && keySecret);
2234
+ const wrongKeys = media ? checkR2Keys(keyId, keySecret) : void 0;
2235
+ if (wrongKeys) throw new Error(`.env: R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY: ${wrongKeys}`);
2236
+ const token = env.get("CLOUDFLARE_API_TOKEN");
2237
+ const deployed = apps$1(d);
2238
+ if (!token && deployed.length > 0) throw new Error(".env has no CLOUDFLARE_API_TOKEN, which the admin and storefront deploy with: run `hypha deploy` in a terminal (it asks for one), or set it in .env");
2239
+ if (!cf.accountId) {
2240
+ const accounts = JSON.parse(await tools.wrangler(["whoami", "--json"], { capture: true }).catch(() => {
2241
+ throw new Error("wrangler isn't logged in: run `wrangler login` (or set CLOUDFLARE_API_TOKEN)");
2242
+ })).accounts ?? [];
2243
+ if (accounts.length !== 1) throw new Error(`wrangler can reach ${accounts.length} accounts: pick one with \`hypha init --force --account-id …\`` + (accounts.length ? `\n${accounts.map((a) => `${a.id} ${a.name}`).join("\n")}` : ""));
2244
+ cf.accountId = accounts[0].id;
2245
+ await saveDeployment(dir, d);
2246
+ }
2247
+ const accountId = cf.accountId;
2248
+ let callerKey = env.get("HYPHA_CALLER_KEY");
2249
+ if (deployed.length > 0 && !callerKey) {
2250
+ callerKey = randomBytes(32).toString("hex");
2251
+ env.set("HYPHA_CALLER_KEY", callerKey);
2252
+ await saveEnv(dir, env);
2253
+ }
2254
+ await tools.checkToolchain();
2255
+ const coLocated = [];
2256
+ for (const entry of d.apps ?? []) {
2257
+ p.log.step(`Preparing the ${entry.name} app (${entry.rev?.slice(0, 12) ?? "unpinned"})…`);
2258
+ const prepared = await tools.prepareApp(entry);
2259
+ if (!prepared.profile.wrangler) throw new Error(`the ${entry.name} app has no wrangler template (wrangler.example.toml): it can't run on Workers`);
2260
+ coLocated.push({
2261
+ entry,
2262
+ ...prepared
2263
+ });
2264
+ if (!env.get(encryptionKeyVar(entry))) {
2265
+ env.set(encryptionKeyVar(entry), newEncryptionKey());
2266
+ await saveEnv(dir, env);
2267
+ }
2268
+ }
2269
+ const appBindings = () => coLocated.filter(({ entry }) => entry.deployed).map(({ entry }) => ({
2270
+ host: appDomain(d, entry),
2271
+ binding: bindingName(entry),
2272
+ worker: appWorkerName(d, entry)
2273
+ }));
2274
+ const spin = p.spinner();
2275
+ let spinning = false;
2276
+ const start = (message) => {
2277
+ spin.start(message);
2278
+ spinning = true;
2279
+ };
2280
+ const stop = (message, failed = false) => {
2281
+ if (failed) spin.error(message);
2282
+ else spin.stop(message);
2283
+ spinning = false;
2284
+ };
2285
+ try {
2286
+ start("Building the setup tool (hypha-host-axum)");
2287
+ const binary = await tools.buildHost(hostCrate);
2288
+ const hostEnv = {
2289
+ DATABASE_URL: databaseUrl,
2290
+ HYPHA_SECRET_KEY: secretKey,
2291
+ HYPHA_CONFIG: join(dir, "hypha.config.toml"),
2292
+ ...pick(env, [
2293
+ "HYPHA_OWNER_EMAIL",
2294
+ "HYPHA_OWNER_PASSWORD",
2295
+ "HYPHA_OWNER_NAME",
2296
+ "HYPHA_STORE_NAME",
2297
+ "HYPHA_RESEND_API_KEY"
2298
+ ])
2299
+ };
2300
+ spin.message("Setting the database up");
2301
+ await tools.host(binary, ["setup"], hostEnv);
2302
+ const { bindings } = JSON.parse(await tools.host(binary, ["config", "rate-limits"], hostEnv));
2303
+ stop("Database ready");
2304
+ start("Creating Hyperdrive, KV and R2 where missing");
2305
+ const origin = hyperdriveOrigin(databaseUrl);
2306
+ const password = decodeURIComponent(new URL(databaseUrl).password);
2307
+ if (cf.hyperdriveId) await redacted(tools.wrangler([
2308
+ "hyperdrive",
2309
+ "update",
2310
+ cf.hyperdriveId,
2311
+ ...origin
2312
+ ], { capture: true }), password);
2313
+ else {
2314
+ const out = await redacted(tools.wrangler([
2315
+ "hyperdrive",
2316
+ "create",
2317
+ hyperdriveName(d),
2318
+ ...origin
2319
+ ], { capture: true }), password);
2320
+ cf.hyperdriveId = idIn(out);
2321
+ if (!cf.hyperdriveId) throw new Error(`no Hyperdrive ID in wrangler's answer:\n${out}`);
2322
+ await saveDeployment(dir, d);
2323
+ }
2324
+ if (!cf.kvId) {
2325
+ cf.kvId = await namespace(tools, kvTitle(d));
2326
+ await saveDeployment(dir, d);
2327
+ }
2328
+ if (media) {
2329
+ await tolerate(tools.wrangler([
2330
+ "r2",
2331
+ "bucket",
2332
+ "create",
2333
+ bucket(d)
2334
+ ], { capture: true }), /already exists|10004/i);
2335
+ if (d.domains.admin) {
2336
+ const rules = join(dir, ".cors.json");
2337
+ await writeFile(rules, corsRules(url(d, d.domains.admin)));
2338
+ try {
2339
+ await tools.wrangler([
2340
+ "r2",
2341
+ "bucket",
2342
+ "cors",
2343
+ "set",
2344
+ bucket(d),
2345
+ "--file",
2346
+ rules,
2347
+ "--force"
2348
+ ], { capture: true });
2349
+ } finally {
2350
+ await rm(rules, { force: true });
2351
+ }
2352
+ }
2353
+ if (cf.zoneId) await tolerate(tools.wrangler([
2354
+ "r2",
2355
+ "bucket",
2356
+ "domain",
2357
+ "add",
2358
+ bucket(d),
2359
+ "--domain",
2360
+ d.domains.media,
2361
+ "--zone-id",
2362
+ cf.zoneId,
2363
+ "--force"
2364
+ ], { capture: true }), /already|exists/i);
2365
+ }
2366
+ stop("Resources ready");
2367
+ const compatibilityDate = /^compatibility_date\s*=\s*"([^"]+)"/m.exec(await readFile(join(WORKER_CRATE, "wrangler.toml"), "utf8"))?.[1] ?? "2026-10-01";
2368
+ const config = await readFile(join(dir, "hypha.config.toml"), "utf8");
2369
+ const writeApiToml = (bound) => writeFile(join(dir, WRANGLER_FILE), wranglerToml(d, {
2370
+ dir,
2371
+ workerCrate,
2372
+ accountId,
2373
+ databaseUrl,
2374
+ hyperdriveId: cf.hyperdriveId,
2375
+ kvId: cf.kvId,
2376
+ config,
2377
+ bindings,
2378
+ compatibilityDate,
2379
+ media,
2380
+ apps: bound
2381
+ }));
2382
+ await writeApiToml(appBindings());
2383
+ const secrets = { HYPHA_SECRET_KEY: secretKey };
2384
+ if (callerKey) secrets.HYPHA_CALLER_KEY = callerKey;
2385
+ const resendKey = env.get("HYPHA_RESEND_API_KEY");
2386
+ if (resendKey) secrets.HYPHA_RESEND_API_KEY = resendKey;
2387
+ if (media) Object.assign(secrets, {
2388
+ HYPHA_S3_ACCESS_KEY_ID: keyId,
2389
+ HYPHA_S3_SECRET_ACCESS_KEY: keySecret
2390
+ });
2391
+ const secretsPath = join(dir, SECRETS_FILE);
2392
+ const deployApi = async () => {
2393
+ await writeFile(secretsPath, JSON.stringify(secrets), { mode: 384 });
2394
+ try {
2395
+ await tools.wrangler([
2396
+ "deploy",
2397
+ "--config",
2398
+ join(dir, WRANGLER_FILE),
2399
+ "--secrets-file",
2400
+ secretsPath
2401
+ ]);
2402
+ } finally {
2403
+ await rm(secretsPath, { force: true });
2404
+ }
2405
+ };
2406
+ p.log.step("Building and deploying the Worker (worker-build --release)…");
2407
+ await deployApi();
2408
+ await tools.wrangler([
2409
+ "kv",
2410
+ "key",
2411
+ "put",
2412
+ "jobs:written",
2413
+ String(tools.now()),
2414
+ "--namespace-id",
2415
+ cf.kvId,
2416
+ "--remote"
2417
+ ], { capture: true });
2418
+ start("Waiting for the API (a new custom domain can take a minute)");
2419
+ if (!await tools.answers(d)) {
2420
+ stop("The API didn't answer", true);
2421
+ throw new Error(`${url(d, d.domains.api)}/health didn't answer in 5 minutes: see \`hypha logs\``);
2422
+ }
2423
+ stop("The API is running");
2424
+ let added = false;
2425
+ for (const { entry, clone, profile } of coLocated) {
2426
+ const worker = appWorkerName(d, entry);
2427
+ if (!entry.d1Id) {
2428
+ entry.d1Id = await d1Database(tools, worker);
2429
+ await saveDeployment(dir, d);
2430
+ }
2431
+ await writeFile(join(clone, APP_WRANGLER_FILE), appWranglerToml(profile.wrangler, {
2432
+ worker,
2433
+ accountId,
2434
+ domain: appDomain(d, entry),
2435
+ appUrl: appUrl(d, entry),
2436
+ apiUrl: url(d, d.domains.api),
2437
+ ...profile.apiBinding ? { apiWorker: workerName(d) } : {},
2438
+ d1: {
2439
+ name: worker,
2440
+ id: entry.d1Id
2441
+ },
2442
+ ...profile.allowlistVar ? { allowlistVar: profile.allowlistVar } : {}
2443
+ }));
2444
+ const file = join(dir, `.secrets-app-${entry.name}.json`);
2445
+ await writeFile(file, JSON.stringify({ APP_ENCRYPTION_KEY: env.get(encryptionKeyVar(entry)) }), { mode: 384 });
2446
+ p.log.step(`Deploying the ${entry.name} app (${worker})…`);
2447
+ try {
2448
+ await tools.wrangler([
2449
+ "deploy",
2450
+ "--config",
2451
+ join(clone, APP_WRANGLER_FILE),
2452
+ "--secrets-file",
2453
+ file
2454
+ ]);
2455
+ } finally {
2456
+ await rm(file, { force: true });
2457
+ }
2458
+ if (!entry.deployed) {
2459
+ entry.deployed = true;
2460
+ added = true;
2461
+ await saveDeployment(dir, d);
2462
+ }
2463
+ }
2464
+ if (added) {
2465
+ p.log.step("Binding the API to the new apps' Workers…");
2466
+ await writeApiToml(appBindings());
2467
+ await deployApi();
2468
+ }
2469
+ if (d.domains.storefront) {
2470
+ const email = env.get("HYPHA_OWNER_EMAIL");
2471
+ const ownerPassword = env.get("HYPHA_OWNER_PASSWORD");
2472
+ if (!email || !ownerPassword) {
2473
+ if (!env.get("STOREFRONT_KEY")) throw new Error("no owner credentials in .env to connect the storefront: set STOREFRONT_KEY and HYPHA_WEBHOOK_SECRET there");
2474
+ } else if (!env.get("STOREFRONT_KEY")) {
2475
+ start("Connecting the storefront: a publishable key and its webhook");
2476
+ const keys = await tools.connectStorefront(d, email, ownerPassword);
2477
+ env.set("STOREFRONT_KEY", keys.key).set("HYPHA_WEBHOOK_SECRET", keys.webhookSecret ?? "");
2478
+ await saveEnv(dir, env);
2479
+ stop("Storefront connected");
2480
+ if (keys.orderUrl) p.log.step(`Order links in emails go to ${keys.orderUrl}`);
2481
+ } else {
2482
+ const moved = await tools.syncWebhook(d, email, ownerPassword).catch((e) => {
2483
+ p.log.warn(`Couldn't check the storefront's webhook: ${e instanceof Error ? e.message : String(e)}`);
2484
+ return null;
2485
+ });
2486
+ if (moved) p.log.step(`The storefront's webhook now goes to ${moved}`);
2487
+ }
2488
+ if (!cf.cacheKvId) {
2489
+ cf.cacheKvId = await namespace(tools, cacheTitle(d));
2490
+ await saveDeployment(dir, d);
2491
+ }
2492
+ }
2493
+ for (const app of deployed) {
2494
+ const domain = d.domains[app];
2495
+ const appEnv = {
2496
+ CLOUDFLARE_API_TOKEN: token,
2497
+ CLOUDFLARE_ACCOUNT_ID: accountId,
2498
+ HYPHA_CF_ACCOUNT_ID: accountId,
2499
+ HYPHA_CF_WORKER: appWorker(d, app),
2500
+ HYPHA_CF_DOMAIN: domain,
2501
+ HYPHA_CF_API_WORKER: workerName(d),
2502
+ ...app === "storefront" ? { HYPHA_CF_CACHE_KV: cf.cacheKvId } : {}
2503
+ };
2504
+ const appSecrets = {
2505
+ HYPHA_API_URL: url(d, d.domains.api),
2506
+ HYPHA_CALLER_KEY: callerKey
2507
+ };
2508
+ if (app === "storefront") {
2509
+ appSecrets.STOREFRONT_KEY = env.get("STOREFRONT_KEY") ?? "";
2510
+ appSecrets.HYPHA_WEBHOOK_SECRET = env.get("HYPHA_WEBHOOK_SECRET") ?? "";
2511
+ }
2512
+ const file = join(dir, `.secrets-${app}.json`);
2513
+ await writeFile(file, JSON.stringify(appSecrets), { mode: 384 });
2514
+ p.log.step(`Building and deploying the ${app} (${appWorker(d, app)})…`);
2515
+ try {
2516
+ await tools.deployApp(app, appEnv, file);
2517
+ } finally {
2518
+ await rm(file, { force: true });
2519
+ }
2520
+ }
2521
+ for (const { entry } of coLocated) {
2522
+ start(`Waiting for the ${entry.name} app at ${appUrl(d, entry)}`);
2523
+ if (!await tools.reachable(`${appUrl(d, entry)}/health`)) {
2524
+ stop(`The ${entry.name} app didn't answer`, true);
2525
+ throw new Error(`${appUrl(d, entry)}/health didn't answer in 5 minutes: see \`wrangler tail ${appWorkerName(d, entry)}\``);
2526
+ }
2527
+ stop(`The ${entry.name} app is running`);
2528
+ }
2529
+ for (const app of deployed) {
2530
+ start(`Waiting for the ${app} at ${url(d, d.domains[app])}`);
2531
+ if (!await tools.reachable(url(d, d.domains[app]))) {
2532
+ stop(`The ${app} didn't answer`, true);
2533
+ throw new Error(`${url(d, d.domains[app])} didn't answer in 5 minutes: see \`hypha logs ${app}\``);
2534
+ }
2535
+ stop(`The ${app} is running`);
2536
+ }
2537
+ if (!media) p.log.warn("Media is off: add an R2 API token's keys to .env (R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY), then deploy.");
2538
+ else if (!cf.zoneId) p.log.warn("Files are served by signed URLs: pass --zone-id to `hypha init --force` for the media domain.");
2539
+ } catch (e) {
2540
+ if (spinning) stop("Stopped", true);
2541
+ throw e;
2542
+ }
2543
+ }
2544
+ /** The D1 database named `name`: the one already there, or a new one. */
2545
+ async function d1Database(tools, name) {
2546
+ const id = JSON.parse(await tools.wrangler([
2547
+ "d1",
2548
+ "list",
2549
+ "--json"
2550
+ ], { capture: true }) || "[]").find((db) => db.name === name)?.uuid ?? uuidIn(await tools.wrangler([
2551
+ "d1",
2552
+ "create",
2553
+ name
2554
+ ], { capture: true }));
2555
+ if (!id) throw new Error(`no ID for the D1 database ${name} in wrangler's answer`);
2556
+ return id;
2557
+ }
2558
+ /** The first UUID in wrangler's output (what `d1 create` prints). */
2559
+ function uuidIn(output) {
2560
+ return /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/.exec(output)?.[0];
2561
+ }
2562
+ /** The KV namespace titled `title`: the one already there, or a new one. */
2563
+ async function namespace(tools, title) {
2564
+ const id = JSON.parse(await tools.wrangler([
2565
+ "kv",
2566
+ "namespace",
2567
+ "list"
2568
+ ], { capture: true })).find((n) => n.title === title)?.id ?? idIn(await tools.wrangler([
2569
+ "kv",
2570
+ "namespace",
2571
+ "create",
2572
+ title
2573
+ ], { capture: true }));
2574
+ if (!id) throw new Error(`no ID for the KV namespace ${title} in wrangler's answer`);
2575
+ return id;
2576
+ }
2577
+ function pick(env, keys) {
2578
+ const out = {};
2579
+ for (const key of keys) {
2580
+ const value = env.get(key);
2581
+ if (value) out[key] = value;
2582
+ }
2583
+ return out;
2584
+ }
2585
+ /** The tools on this machine: wrangler (logged in, or `CLOUDFLARE_API_TOKEN`), cargo,
2586
+ * and `worker-build` with the wasm target. */
2587
+ function hereTools(dir, d, env) {
2588
+ const auth = () => {
2589
+ const out = {};
2590
+ const token = env.get("CLOUDFLARE_API_TOKEN");
2591
+ if (token) out.CLOUDFLARE_API_TOKEN = token;
2592
+ if (d.cloudflare?.accountId) out.CLOUDFLARE_ACCOUNT_ID = d.cloudflare.accountId;
2593
+ return out;
2594
+ };
2595
+ return {
2596
+ wrangler(args, { capture } = {}) {
2597
+ return run("wrangler", args, {
2598
+ capture,
2599
+ cwd: REPO,
2600
+ env: auth()
2601
+ });
2602
+ },
2603
+ async buildHost(hostCrate) {
2604
+ const target = process.env.CARGO_TARGET_DIR ?? join(REPO, "target");
2605
+ if (hostCrate) {
2606
+ await run("cargo", [
2607
+ "build",
2608
+ "--release",
2609
+ "--manifest-path",
2610
+ join(REPO, hostCrate, "Cargo.toml")
2611
+ ], {
2612
+ cwd: REPO,
2613
+ capture: true,
2614
+ env: { CARGO_TARGET_DIR: target }
2615
+ });
2616
+ return join(target, "release", "hypha-deployment");
2617
+ }
2618
+ await run("cargo", [
2619
+ "build",
2620
+ "--release",
2621
+ "-p",
2622
+ "hypha-host-axum"
2623
+ ], {
2624
+ cwd: REPO,
2625
+ capture: true
2626
+ });
2627
+ return join(process.env.CARGO_TARGET_DIR ?? join(REPO, "target"), "release", "hypha-host-axum");
2628
+ },
2629
+ host: (binary, args, hostEnv) => run(binary, args, {
2630
+ cwd: REPO,
2631
+ env: {
2632
+ RUST_LOG: "info",
2633
+ ...hostEnv
2634
+ },
2635
+ bareEnv: true,
2636
+ capture: true
2637
+ }),
2638
+ async checkToolchain() {
2639
+ await run("worker-build", ["--version"], { capture: true }).catch(() => {
2640
+ throw new Error("worker-build is missing: `cargo install worker-build`");
2641
+ });
2642
+ if (!(await run("rustup", [
2643
+ "target",
2644
+ "list",
2645
+ "--installed"
2646
+ ], { capture: true }).catch(() => "")).includes("wasm32-unknown-unknown")) throw new Error("the wasm target is missing: `rustup target add wasm32-unknown-unknown`");
2647
+ },
2648
+ now: () => Date.now(),
2649
+ answers: (deployed) => waitForHealth(deployed, 300),
2650
+ reachable: (target) => waitForAnswer(target, 300),
2651
+ connectStorefront: async (deployed, email, password) => connectStorefront(deployed, await Staff.login(deployed, email, password)),
2652
+ syncWebhook: async (deployed, email, password) => syncWebhook(deployed, await Staff.login(deployed, email, password)),
2653
+ async deployApp(app, appEnv, secretsFile) {
2654
+ const cwd = join(REPO, "apps", app);
2655
+ const buildEnv = {
2656
+ ...appEnv,
2657
+ ...auth(),
2658
+ HYPHA_TARGET: "",
2659
+ NODE_ENV: "production"
2660
+ };
2661
+ await run("pnpm", [
2662
+ "exec",
2663
+ "vite",
2664
+ "build"
2665
+ ], {
2666
+ cwd,
2667
+ env: buildEnv,
2668
+ capture: true
2669
+ });
2670
+ await run("pnpm", [
2671
+ "exec",
2672
+ "cf",
2673
+ "deploy",
2674
+ "--prebuilt",
2675
+ "--secrets-file",
2676
+ secretsFile
2677
+ ], {
2678
+ cwd,
2679
+ env: buildEnv
2680
+ });
2681
+ },
2682
+ async prepareApp(entry) {
2683
+ const clone = await checkout(dir, entry);
2684
+ return {
2685
+ clone,
2686
+ profile: await readProfile(clone)
2687
+ };
2688
+ }
2689
+ };
2690
+ }
2691
+ //#endregion
2692
+ //#region src/images.ts
2693
+ /** Where the release workflow publishes the images. */
2694
+ const REGISTRY = "ghcr.io/hyphacommerce";
2695
+ /** `.env`'s image references, read by `compose.yaml`; without them it runs the
2696
+ * `:current` images a source build leaves in Docker. */
2697
+ const IMAGE_VARS = {
2698
+ api: "HYPHA_API_IMAGE",
2699
+ admin: "HYPHA_ADMIN_IMAGE",
2700
+ storefront: "HYPHA_STOREFRONT_IMAGE"
2701
+ };
2702
+ /** The published image for a service at a version: `ghcr.io/hyphacommerce/hypha-api:0.1.0`. */
2703
+ function publishedImage(name, version = VERSION) {
2704
+ return `${REGISTRY}/hypha-${name}:${version}`;
2705
+ }
2706
+ /** Points `.env` at the published images at `version` (every service, so a profile
2707
+ * turned on later gets its image too), or at the source build's. */
2708
+ function setImageRefs(env, source, version = VERSION) {
2709
+ for (const name of [
2710
+ "api",
2711
+ "admin",
2712
+ "storefront"
2713
+ ]) if (source) env.delete(IMAGE_VARS[name]);
2714
+ else env.set(IMAGE_VARS[name], publishedImage(name, version));
2715
+ }
2716
+ /** The images: the API (from `hostCrate`, the deployment's own host crate, when it has
2717
+ * spores), and the apps. */
2718
+ function images(apps, hostCrate) {
2719
+ const repo = requireRepo("Building the images from source");
2720
+ return [{
2721
+ name: "api",
2722
+ tag: "hypha-api:current",
2723
+ dockerfile: join(repo, "docker/api.Dockerfile"),
2724
+ context: repo,
2725
+ args: hostCrate ? [`HOST_CRATE=${hostCrate}`] : []
2726
+ }, ...apps.map((app) => ({
2727
+ name: app,
2728
+ tag: `hypha-${app}:current`,
2729
+ dockerfile: join(repo, "docker/app.Dockerfile"),
2730
+ context: repo,
2731
+ app
2732
+ }))];
2733
+ }
2734
+ /** A co-located app's image: its own Dockerfile, in its clone, which holds the Node bundle
2735
+ * built here (`apps.ts`). */
2736
+ function appImage(entry, clone) {
2737
+ return {
2738
+ name: service(entry),
2739
+ tag: imageTag(entry),
2740
+ dockerfile: join(clone, "Dockerfile"),
2741
+ context: clone
2742
+ };
2743
+ }
2744
+ function buildArgs(image) {
2745
+ return [
2746
+ "build",
2747
+ "-f",
2748
+ image.dockerfile,
2749
+ "-t",
2750
+ image.tag,
2751
+ ...image.app ? ["--build-arg", `APP=${image.app}`] : [],
2752
+ ...(image.args ?? []).flatMap((arg) => ["--build-arg", arg]),
2753
+ image.context
2754
+ ];
2755
+ }
2756
+ /** The server's platform for `docker build --platform`, from `uname -m`. */
2757
+ async function platform(machine) {
2758
+ const arch = (await machine.sh("uname -m", { capture: true })).trim();
2759
+ if (arch === "x86_64" || arch === "amd64") return "linux/amd64";
2760
+ if (arch === "aarch64" || arch === "arm64") return "linux/arm64";
2761
+ throw new Error(`the server's architecture, ${arch}, has no build here`);
2762
+ }
2763
+ /** Builds `image` where the deployment says, leaving it in the machine's Docker. */
2764
+ async function build(d, machine, image) {
2765
+ if (!machine.ssh) await run("docker", buildArgs(image));
2766
+ else if (d.buildOn === "server") await run("docker", [
2767
+ "--host",
2768
+ `ssh://${machine.ssh}`,
2769
+ ...buildArgs(image)
2770
+ ]);
2771
+ else {
2772
+ const [, ...rest] = buildArgs(image);
2773
+ await run("docker", [
2774
+ "buildx",
2775
+ "build",
2776
+ "--platform",
2777
+ await platform(machine),
2778
+ "--load",
2779
+ ...rest
2780
+ ]);
2781
+ await pipe(["docker", ["save", image.tag]], ["ssh", [
2782
+ "-o",
2783
+ "BatchMode=yes",
2784
+ machine.ssh,
2785
+ "docker load"
2786
+ ]]);
2787
+ }
2788
+ }
2789
+ //#endregion
2790
+ //#region src/commands/deploy.ts
2791
+ /** What the server runs: copied on every deploy. */
2792
+ const FILES = [
2793
+ ENV_FILE,
2794
+ "compose.yaml",
2795
+ COMPOSE_APPS_FILE,
2796
+ "Caddyfile",
2797
+ APPS_CADDY_FILE,
2798
+ "hypha.config.toml",
2799
+ "hypha.config.schema.json",
2800
+ "seaweedfs/s3.json"
2801
+ ];
2802
+ const deploy = defineCommand({
2803
+ meta: {
2804
+ name: "deploy",
2805
+ description: "Build, copy and start the deployment (again after any change)"
2806
+ },
2807
+ args: {
2808
+ dir: dirArg,
2809
+ "build-from-source": {
2810
+ type: "boolean",
2811
+ description: "Build the images from this checkout instead of pulling the published ones"
2812
+ },
2813
+ "skip-build": {
2814
+ type: "boolean",
2815
+ description: "When building from source: use the images already there"
2816
+ },
2817
+ images: {
2818
+ type: "string",
2819
+ description: `Pull the published images at this version instead of ${VERSION}`
2820
+ },
2821
+ yes: {
2822
+ type: "boolean",
2823
+ alias: "y",
2824
+ description: "Don't ask (installing Docker, DNS warnings)"
2825
+ }
2826
+ },
2827
+ run: ({ args }) => guarded(async () => {
2828
+ const dir = args.dir;
2829
+ const deployment = await loadDeployment(dir);
2830
+ await pinUnpinned(dir, deployment);
2831
+ if (deployment.target === "cloudflare") {
2832
+ p.intro("hypha deploy → Cloudflare");
2833
+ requireRepo("Deploying to Cloudflare");
2834
+ const env = await loadEnv(dir);
2835
+ const cf = deployment.cloudflare;
2836
+ const known = env.get("CLOUDFLARE_API_TOKEN");
2837
+ const colocated = Boolean(deployment.apps?.length);
2838
+ if (cf && (!known && apps$1(deployment).length > 0 || colocated)) {
2839
+ const { token, checked } = await obtainToken({
2840
+ name: cf.name,
2841
+ domain: deployment.domains.api,
2842
+ given: known,
2843
+ accountId: cf.accountId,
2844
+ zoneId: cf.zoneId,
2845
+ quiet: args.yes,
2846
+ apps: colocated
2847
+ });
2848
+ env.set("CLOUDFLARE_API_TOKEN", token);
2849
+ await saveEnv(dir, env);
2850
+ if (!cf.accountId || !cf.zoneId) {
2851
+ Object.assign(cf, {
2852
+ accountId: checked.accountId,
2853
+ zoneId: checked.zoneId
2854
+ });
2855
+ await saveDeployment(dir, deployment);
2856
+ }
2857
+ }
2858
+ await deployCloudflare(resolve(dir), deployment, env, hereTools(resolve(dir), deployment, env));
2859
+ const password = env.get("HYPHA_OWNER_PASSWORD");
2860
+ const lines = [
2861
+ `API ${url(deployment, deployment.domains.api)}`,
2862
+ ...deployment.domains.admin ? [`Admin ${url(deployment, deployment.domains.admin)}`] : [],
2863
+ ...deployment.domains.storefront ? [`Storefront ${url(deployment, deployment.domains.storefront)}`] : []
2864
+ ];
2865
+ if (password) lines.push("", `Log in as ${env.get("HYPHA_OWNER_EMAIL")} with ${password}`, "(then change it)");
2866
+ for (const entry of deployment.apps ?? []) lines.splice(lines.length, 0, `${entry.name.padEnd(10)} ${appUrl(deployment, entry)}`);
2867
+ p.note(lines.join("\n"), "Deployed");
2868
+ await offerInstalls(deployment, env, { quiet: args.yes });
2869
+ p.outro("Done.");
2870
+ return;
2871
+ }
2872
+ const { d, machine } = await open(dir);
2873
+ p.intro(`hypha deploy → ${machine.label}`);
2874
+ const spores = d.spores ?? [];
2875
+ const source = Boolean(args["build-from-source"] || d.source || spores.length);
2876
+ const building = source && !args["skip-build"];
2877
+ await preflight(d, machine, Boolean(args.yes), building);
2878
+ const coLocated = [];
2879
+ for (const entry of d.apps ?? []) {
2880
+ const clone = cloneDir(resolve(dir), entry);
2881
+ if (!args["skip-build"]) {
2882
+ p.log.step(`Preparing the ${entry.name} app (${entry.rev.slice(0, 12)})…`);
2883
+ await checkout(resolve(dir), entry);
2884
+ }
2885
+ const profile = await readProfile(clone);
2886
+ if (!profile.nodeBuild && !args["skip-build"]) throw new Error(`the ${entry.name} app has no \`build:node\` script: it can't be built for a container`);
2887
+ coLocated.push({
2888
+ entry,
2889
+ clone,
2890
+ profile
2891
+ });
2892
+ }
2893
+ if (building) {
2894
+ const hostCrate = spores.length ? await writeHostCrate(dir, spores, await fetchSpores(dir, spores)) : void 0;
2895
+ for (const image of images(apps$1(d), hostCrate)) {
2896
+ p.log.step(`Building ${image.tag}${machine.ssh ? d.buildOn === "server" ? " on the server" : " here" : ""}…`);
2897
+ await build(d, machine, image);
2898
+ }
2899
+ for (const { entry, clone } of coLocated) {
2900
+ await run("pnpm", ["run", "build:node"], {
2901
+ cwd: clone,
2902
+ capture: true
2903
+ });
2904
+ const image = appImage(entry, clone);
2905
+ p.log.step(`Building ${image.tag}${machine.ssh ? d.buildOn === "server" ? " on the server" : " here" : ""}…`);
2906
+ await build(d, machine, image);
2907
+ }
2908
+ }
2909
+ await writeServerApps(resolve(dir), d, coLocated);
2910
+ {
2911
+ const env = await loadEnv(dir);
2912
+ const before = env.toString();
2913
+ setImageRefs(env, source, args.images);
2914
+ if (env.toString() !== before) await saveEnv(dir, env);
2915
+ if (!source) p.log.step(`Using the published images: ${publishedImage("api", args.images)}, …`);
2916
+ }
2917
+ const spin = p.spinner();
2918
+ spin.start("Copying the deployment and starting it");
2919
+ await machine.upload(dir, FILES);
2920
+ if (machine.ssh) await machine.sh(`chmod 700 . && chmod 600 ${ENV_FILE} && chmod 644 seaweedfs/s3.json`);
2921
+ await machine.sh("docker compose up -d --remove-orphans", { capture: true });
2922
+ spin.message("Waiting for the API (the first time, Caddy is also getting certificates)");
2923
+ if (!await waitForHealth(d, 300)) {
2924
+ spin.error("The API didn't answer");
2925
+ throw new Error(`${url(d, d.domains.api)}/health didn't answer in 5 minutes: see \`hypha logs api\` and \`hypha logs caddy\``);
2926
+ }
2927
+ spin.stop("Running");
2928
+ const env = await loadEnv(dir);
2929
+ if (d.domains.storefront && env.get("STOREFRONT_KEY") && d.target === "vps") {
2930
+ const email = env.get("HYPHA_OWNER_EMAIL");
2931
+ const password = env.get("HYPHA_OWNER_PASSWORD");
2932
+ if (email && password) await Staff.login(d, email, password).then((staff) => syncWebhook(d, staff)).then((moved) => moved && p.log.step(`The storefront's webhook now goes to ${moved}`)).catch((e) => p.log.warn(`Couldn't check the storefront's webhook: ${e instanceof Error ? e.message : e}`));
2933
+ } else if (d.domains.storefront && !env.get("STOREFRONT_KEY")) {
2934
+ spin.start("Connecting the storefront: a publishable key and its webhook");
2935
+ const email = env.get("HYPHA_OWNER_EMAIL");
2936
+ const password = env.get("HYPHA_OWNER_PASSWORD");
2937
+ if (!email || !password) {
2938
+ spin.error("Skipped");
2939
+ p.log.warn("No owner credentials in .env: set STOREFRONT_KEY and HYPHA_WEBHOOK_SECRET there, then deploy.");
2940
+ } else {
2941
+ const keys = await connectStorefront(d, await Staff.login(d, email, password));
2942
+ env.set("STOREFRONT_KEY", keys.key).set("HYPHA_WEBHOOK_SECRET", keys.webhookSecret ?? "");
2943
+ await saveEnv(dir, env);
2944
+ await machine.upload(dir, [ENV_FILE]);
2945
+ await machine.sh("docker compose up -d storefront", { capture: true });
2946
+ spin.stop("Storefront connected");
2947
+ if (keys.orderUrl) p.log.step(`Order links in emails go to ${keys.orderUrl}`);
2948
+ }
2949
+ }
2950
+ for (const { entry } of coLocated) {
2951
+ const target = `${appUrl(d, entry)}/health`;
2952
+ if (!await waitForAnswer(target, 120, d)) p.log.warn(`The ${entry.name} app doesn't answer at ${target}: see \`hypha logs ${service(entry)}\``);
2953
+ }
2954
+ const lines = [
2955
+ `API ${url(d, d.domains.api)}`,
2956
+ ...d.domains.admin ? [`Admin ${url(d, d.domains.admin)}`] : [],
2957
+ ...d.domains.storefront ? [`Storefront ${url(d, d.domains.storefront)}`] : [],
2958
+ ...coLocated.map(({ entry }) => `${entry.name.padEnd(10)} ${appUrl(d, entry)}`)
2959
+ ];
2960
+ const password = env.get("HYPHA_OWNER_PASSWORD");
2961
+ if (password) lines.push("", `Log in as ${env.get("HYPHA_OWNER_EMAIL")} with ${password}`, "(then change it)");
2962
+ p.note(lines.join("\n"), "Deployed");
2963
+ await offerInstalls(d, env, { quiet: args.yes });
2964
+ p.outro("Done.");
2965
+ })
2966
+ });
2967
+ /**
2968
+ * The co-located apps' part of a server's files: `compose.apps.yaml` (their containers,
2969
+ * read after `compose.yaml` through `.env`'s COMPOSE_FILE), `apps.caddy` (their sites,
2970
+ * which the Caddyfile imports), their encryption keys in `.env`, and on this machine
2971
+ * calls to private addresses allowed (the apps are other containers). Written on every
2972
+ * deploy, with no apps too, so a removed app's container goes (`--remove-orphans`).
2973
+ */
2974
+ async function writeServerApps(dir, d, coLocated) {
2975
+ await writeFile(join(dir, COMPOSE_APPS_FILE), composeApps(d, coLocated));
2976
+ await writeFile(join(dir, APPS_CADDY_FILE), appsCaddy(d, coLocated));
2977
+ const caddyfile = await readFile(join(dir, "Caddyfile"), "utf8");
2978
+ if (!caddyfile.split("\n").includes("import /etc/caddy/apps.caddy")) await writeFile(join(dir, "Caddyfile"), `${caddyfile.trimEnd()}\n\n# The co-located apps' sites, written by \`hypha deploy\`.\n${CADDY_IMPORT}\n`);
2979
+ const env = await loadEnv(dir);
2980
+ const before = env.toString();
2981
+ env.set("COMPOSE_FILE", `compose.yaml:${COMPOSE_APPS_FILE}`).set("COMPOSE_PATH_SEPARATOR", ":");
2982
+ env.set("API_URL", url(d, d.domains.api));
2983
+ ensureEncryptionKeys(d, env);
2984
+ if (d.target === "local" && coLocated.length > 0) env.set("HYPHA_ALLOW_PRIVATE_CALLBACKS", "true");
2985
+ if (env.toString() !== before) await saveEnv(dir, env);
2986
+ }
2987
+ /** Checks the server before anything is built: SSH, Docker (offering to install it),
2988
+ * and that the domains point at it. */
2989
+ async function preflight(d, machine, yes, building) {
2990
+ if (!machine.ssh) {
2991
+ await machine.sh("docker compose version", { capture: true }).catch(() => {
2992
+ throw new Error("Docker with Compose isn't running here: start Docker Desktop");
2993
+ });
2994
+ const bytes = Number((await machine.sh("docker info --format '{{.MemTotal}}'", { capture: true })).trim());
2995
+ if (building && bytes < BUILD_MEMORY_MB * 1024 * 1024) throw new Error(`Docker has ${(bytes / 2 ** 30).toFixed(1)} GiB of memory; compiling the API needs about 5: raise it in Docker Desktop (Settings → Resources → Memory), then deploy again`);
2996
+ return;
2997
+ }
2998
+ try {
2999
+ await machine.sh("true", { capture: true });
3000
+ } catch (e) {
3001
+ throw new Error(`can't reach ${machine.ssh} over SSH without a password (key-based login is needed):\n` + (e instanceof CommandFailed ? e.output.trim() : String(e)), { cause: e });
3002
+ }
3003
+ if (!await machine.sh("docker compose version", { capture: true }).then(() => true, () => false)) {
3004
+ if (!(yes || process.stdin.isTTY && await p.confirm({ message: `Docker isn't installed on ${machine.ssh}. Install it with Docker's script (get.docker.com)?` }) === true)) throw new Error("Docker with Compose is needed on the server: install it, then deploy again");
3005
+ p.log.step("Installing Docker…");
3006
+ await machine.sh("curl -fsSL https://get.docker.com | sh");
3007
+ }
3008
+ if (building && d.buildOn === "server") await ensureBuildMemory(machine, yes);
3009
+ const host = machine.ssh.split("@").pop();
3010
+ const serverIps = isIP(host) ? [host] : await addresses(host);
3011
+ const wrong = [];
3012
+ for (const domain of [...Object.values(d.domains), ...(d.apps ?? []).map((a) => appDomain(d, a))]) {
3013
+ if (!domain) continue;
3014
+ const ips = await addresses(domain);
3015
+ if (!ips.some((ip) => serverIps.includes(ip))) wrong.push(`${domain} → ${ips.join(", ") || "nothing"}`);
3016
+ }
3017
+ if (wrong.length > 0) {
3018
+ p.log.warn(`These domains don't point at ${serverIps.join(", ")} (yet?):\n${wrong.join("\n")}`);
3019
+ if (!(yes || process.stdin.isTTY && await p.confirm({
3020
+ message: "Deploy anyway?",
3021
+ initialValue: false
3022
+ }) === true)) throw new Error("fix the DNS records (or wait for them to spread), then deploy again");
3023
+ }
3024
+ }
3025
+ /** Memory and swap the API's compile needs: its last crate peaks near 3 GB, on top of
3026
+ * Docker and the system. A "4 GB" server reports about 3.8, so it gets swap. */
3027
+ const BUILD_MEMORY_MB = 5120;
3028
+ /** On a server with less memory than compiling needs, offers a swap file (slower, but
3029
+ * it finishes) or building here instead. */
3030
+ async function ensureBuildMemory(machine, yes) {
3031
+ const meminfo = await machine.sh("cat /proc/meminfo", { capture: true });
3032
+ const kb = (name) => Number(new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(meminfo)?.[1] ?? 0);
3033
+ const totalMb = Math.floor((kb("MemTotal") + kb("SwapTotal")) / 1024);
3034
+ if (totalMb >= BUILD_MEMORY_MB) return;
3035
+ const swapMb = Math.ceil((BUILD_MEMORY_MB - totalMb) / 1024) * 1024 + 1024;
3036
+ p.log.warn(`The server has ${totalMb} MB of memory and swap; compiling the API needs about ${BUILD_MEMORY_MB}.`);
3037
+ if (!(yes || process.stdin.isTTY && await p.confirm({ message: `Add a ${swapMb / 1024} GB swap file (/swapfile, kept across reboots)?` }) === true)) throw new Error("not enough memory to compile there: add swap, or `--build-on here` in `hypha init`");
3038
+ await machine.sh([
3039
+ `fallocate -l ${swapMb}M /swapfile`,
3040
+ "chmod 600 /swapfile",
3041
+ "mkswap /swapfile",
3042
+ "swapon /swapfile",
3043
+ "grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"
3044
+ ].join(" && "), { capture: true });
3045
+ }
3046
+ async function addresses(host) {
3047
+ const [v4, v6] = await Promise.all([resolve4(host).catch(() => []), resolve6(host).catch(() => [])]);
3048
+ return [...v4, ...v6];
3049
+ }
3050
+ //#endregion
3051
+ //#region src/commands/init.ts
3052
+ /** What `--force` keeps from the deployment's `.env`. */
3053
+ const KEPT = [
3054
+ "POSTGRES_PASSWORD",
3055
+ "HYPHA_SECRET_KEY",
3056
+ "S3_ACCESS_KEY",
3057
+ "S3_SECRET_KEY",
3058
+ "HYPHA_OWNER_EMAIL",
3059
+ "HYPHA_OWNER_PASSWORD",
3060
+ "STOREFRONT_KEY",
3061
+ "HYPHA_WEBHOOK_SECRET",
3062
+ "DATABASE_URL",
3063
+ "R2_ACCESS_KEY_ID",
3064
+ "R2_SECRET_ACCESS_KEY",
3065
+ "CLOUDFLARE_API_TOKEN",
3066
+ "HYPHA_RESEND_API_KEY",
3067
+ "HYPHA_SMTP_PASSWORD"
3068
+ ];
3069
+ /** A Cloudflare deployment's name: its resources' prefix. */
3070
+ const NAME = /^[a-z][a-z0-9-]{0,40}[a-z0-9]$/;
3071
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/i;
3072
+ function checkDomain(value) {
3073
+ return value && DOMAIN.test(value.trim()) ? void 0 : "a domain like shop.example.com";
3074
+ }
3075
+ function checkEmail(value) {
3076
+ return value && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()) ? void 0 : "an email address";
3077
+ }
3078
+ const init = defineCommand({
3079
+ meta: {
3080
+ name: "init",
3081
+ description: "Write a deployment: where Hypha runs, its domains, its secrets"
3082
+ },
3083
+ args: {
3084
+ dir: dirArg,
3085
+ target: {
3086
+ type: "string",
3087
+ description: "vps (a server over SSH), cloudflare (the API on Workers) or local (this machine, to try it)"
3088
+ },
3089
+ ssh: {
3090
+ type: "string",
3091
+ description: "The server's SSH destination, e.g. root@203.0.113.7"
3092
+ },
3093
+ domain: {
3094
+ type: "string",
3095
+ description: "Your domain: api., admin. and media. go under it, the shop on it"
3096
+ },
3097
+ "api-domain": {
3098
+ type: "string",
3099
+ description: "The API's domain (default api.<domain>)"
3100
+ },
3101
+ "admin-domain": {
3102
+ type: "string",
3103
+ description: "The admin's domain (default admin.<domain>)"
3104
+ },
3105
+ "media-domain": {
3106
+ type: "string",
3107
+ description: "Uploaded files' domain (default media.<domain>)"
3108
+ },
3109
+ "storefront-domain": {
3110
+ type: "string",
3111
+ description: "The shop's domain (default <domain>)"
3112
+ },
3113
+ admin: {
3114
+ type: "boolean",
3115
+ default: true,
3116
+ description: "Include the admin (--no-admin to host your own)"
3117
+ },
3118
+ storefront: {
3119
+ type: "boolean",
3120
+ default: true,
3121
+ description: "Include the storefront (--no-storefront for your own)"
3122
+ },
3123
+ "owner-email": {
3124
+ type: "string",
3125
+ description: "The first staff user, the store's owner"
3126
+ },
3127
+ "store-name": {
3128
+ type: "string",
3129
+ description: "The store's name"
3130
+ },
3131
+ "acme-email": {
3132
+ type: "string",
3133
+ description: "For Let's Encrypt's expiry notices (default the owner's; none for none)"
3134
+ },
3135
+ "from-source": {
3136
+ type: "boolean",
3137
+ description: "Build the images from this checkout rather than pull the published ones"
3138
+ },
3139
+ "build-on": {
3140
+ type: "string",
3141
+ description: "With --from-source: server (default) or here, where the images are built"
3142
+ },
3143
+ "remote-dir": {
3144
+ type: "string",
3145
+ default: "/opt/hypha",
3146
+ description: "The deployment's folder on the server"
3147
+ },
3148
+ "database-url": {
3149
+ type: "string",
3150
+ description: "cloudflare: the Postgres database's direct URL (any provider; not a pooler's)"
3151
+ },
3152
+ name: {
3153
+ type: "string",
3154
+ description: "cloudflare: its resources' prefix (default hypha: hypha-api, hypha-media, …)"
3155
+ },
3156
+ "account-id": {
3157
+ type: "string",
3158
+ description: "cloudflare: the account, when wrangler reaches more than one"
3159
+ },
3160
+ "api-token": {
3161
+ type: "string",
3162
+ description: "cloudflare: the API token to deploy with (else CLOUDFLARE_API_TOKEN, else init links to a filled-in form)"
3163
+ },
3164
+ "zone-id": {
3165
+ type: "string",
3166
+ description: "cloudflare: the domain's zone (found from the token otherwise)"
3167
+ },
3168
+ region: {
3169
+ type: "string",
3170
+ description: "cloudflare: a placement region (aws:eu-central-1) instead of measuring the database's host"
3171
+ },
3172
+ "r2-access-key-id": {
3173
+ type: "string",
3174
+ description: "cloudflare: R2's Access Key ID, or an R2 token's value (default: derived from the API token)"
3175
+ },
3176
+ "r2-secret-access-key": {
3177
+ type: "string",
3178
+ description: "cloudflare: R2's Secret Access Key, with an Access Key ID"
3179
+ },
3180
+ media: {
3181
+ type: "boolean",
3182
+ default: true,
3183
+ description: "cloudflare: files on R2 (--no-media for none)"
3184
+ },
3185
+ "email-sender": {
3186
+ type: "string",
3187
+ description: "How emails go out: log (written to the API's log, the default), resend, or smtp (not on cloudflare)"
3188
+ },
3189
+ "email-from": {
3190
+ type: "string",
3191
+ description: "The address emails come from, on a domain your provider verified"
3192
+ },
3193
+ "resend-api-key": {
3194
+ type: "string",
3195
+ description: "resend: the API key (re_…)"
3196
+ },
3197
+ "smtp-host": {
3198
+ type: "string",
3199
+ description: "smtp: the server's host name"
3200
+ },
3201
+ "smtp-port": {
3202
+ type: "string",
3203
+ description: "smtp: its port (default 587)"
3204
+ },
3205
+ "smtp-tls": {
3206
+ type: "string",
3207
+ description: "smtp: starttls (default), tls (port 465) or none"
3208
+ },
3209
+ "smtp-username": {
3210
+ type: "string",
3211
+ description: "smtp: the login, if it needs one"
3212
+ },
3213
+ "smtp-password": {
3214
+ type: "string",
3215
+ description: "smtp: the login's password"
3216
+ },
3217
+ apps: {
3218
+ type: "string",
3219
+ description: "Apps deployed alongside, comma-separated: stripe, meilisearch (none for none; more with `hypha apps add`)"
3220
+ },
3221
+ spores: {
3222
+ type: "string",
3223
+ description: "Spores compiled into the API, comma-separated: stripe (none for none; more with `hypha spores add`)"
3224
+ },
3225
+ yes: {
3226
+ type: "boolean",
3227
+ alias: "y",
3228
+ description: "Don't ask: defaults for what isn't given"
3229
+ },
3230
+ force: {
3231
+ type: "boolean",
3232
+ description: "Write an existing deployment again (keeps its secrets, owner and keys)"
3233
+ }
3234
+ },
3235
+ run: ({ args }) => guarded(async () => {
3236
+ const dir = resolve(args.dir);
3237
+ setUnattended(Boolean(args.yes));
3238
+ p.intro("hypha init");
3239
+ if (!args.force && await exists(join(dir, "hypha.json"))) {
3240
+ p.cancel(`${dir} already holds a deployment: \`hypha deploy\` it, or --force to write it again (keeps its secrets)`);
3241
+ process.exit(1);
3242
+ }
3243
+ const target = await ask(args.target, "vps", () => p.select({
3244
+ message: "Where should Hypha run?",
3245
+ options: [
3246
+ {
3247
+ value: "vps",
3248
+ label: "A server",
3249
+ hint: "a VPS you reach over SSH (Hetzner, DigitalOcean, …)"
3250
+ },
3251
+ {
3252
+ value: "cloudflare",
3253
+ label: "Cloudflare",
3254
+ hint: "the API on Workers, with your Postgres (Neon, Supabase, …)"
3255
+ },
3256
+ {
3257
+ value: "local",
3258
+ label: "This machine",
3259
+ hint: "to try the production setup locally"
3260
+ }
3261
+ ]
3262
+ }));
3263
+ if (target !== "vps" && target !== "local" && target !== "cloudflare") throw new Error(`--target is vps, cloudflare or local, not ${target}`);
3264
+ if (target === "cloudflare") return initCloudflare(dir, args);
3265
+ let ssh;
3266
+ let domains;
3267
+ let apex = "hypha.localhost";
3268
+ let buildOn = "server";
3269
+ if (target === "vps") {
3270
+ ssh = await ask(args.ssh, void 0, () => p.text({
3271
+ message: "The server's SSH destination",
3272
+ placeholder: "root@203.0.113.7",
3273
+ validate: (v) => v?.trim() ? void 0 : "user@host, as you'd pass it to ssh"
3274
+ }));
3275
+ const domain = (await ask(args.domain, void 0, () => p.text({
3276
+ message: "Your domain",
3277
+ placeholder: "example.com",
3278
+ validate: checkDomain
3279
+ }))).toLowerCase();
3280
+ if (checkDomain(domain)) throw new Error(`--domain: ${domain} isn't a domain`);
3281
+ apex = domain;
3282
+ const sub = async (flag, label, fallback) => {
3283
+ const value = await ask(flag, fallback, () => p.text({
3284
+ message: label,
3285
+ initialValue: fallback,
3286
+ validate: checkDomain
3287
+ }));
3288
+ if (checkDomain(value)) throw new Error(`${label}: ${value} isn't a domain`);
3289
+ return value.toLowerCase();
3290
+ };
3291
+ domains = {
3292
+ api: await sub(args["api-domain"], "The API's address", `api.${domain}`),
3293
+ media: await sub(args["media-domain"], "Uploaded files' address", `media.${domain}`),
3294
+ ...args.admin ? { admin: await sub(args["admin-domain"], "The admin's address", `admin.${domain}`) } : {},
3295
+ ...args.storefront ? { storefront: await sub(args["storefront-domain"], "The shop's address", domain) } : {}
3296
+ };
3297
+ if (args["from-source"] || args["build-on"]) {
3298
+ const buildAnswer = await ask(args["build-on"], "server", () => p.select({
3299
+ message: "Where should the images be built?",
3300
+ options: [{
3301
+ value: "server",
3302
+ label: "On the server",
3303
+ hint: "nothing to copy; compiling needs ~4 GB of memory"
3304
+ }, {
3305
+ value: "here",
3306
+ label: "Here",
3307
+ hint: "then copied over; for small servers"
3308
+ }]
3309
+ }));
3310
+ if (buildAnswer !== "server" && buildAnswer !== "here") throw new Error(`--build-on is server or here, not ${buildAnswer}`);
3311
+ buildOn = buildAnswer;
3312
+ }
3313
+ } else domains = {
3314
+ api: "api.hypha.localhost",
3315
+ media: "media.hypha.localhost",
3316
+ ...args.admin ? { admin: "admin.hypha.localhost" } : {},
3317
+ ...args.storefront ? { storefront: "shop.hypha.localhost" } : {}
3318
+ };
3319
+ const email = (await ask(args["owner-email"], void 0, () => p.text({
3320
+ message: "The owner's email (the first staff user)",
3321
+ validate: checkEmail
3322
+ }))).trim();
3323
+ if (checkEmail(email)) throw new Error(`--owner-email: ${email} isn't an email address`);
3324
+ const storeName = await ask(args["store-name"], "My store", () => p.text({
3325
+ message: "The store's name",
3326
+ initialValue: "My store"
3327
+ }));
3328
+ const emailSettings = await askEmail(args, target, domains.storefront ?? domains.api);
3329
+ const acme = args["acme-email"] === "none" ? void 0 : args["acme-email"] || email;
3330
+ const earlierState = args.force ? await loadDeployment(dir).catch(() => void 0) : void 0;
3331
+ const d = {
3332
+ version: 1,
3333
+ target,
3334
+ ...ssh ? { ssh: ssh.trim() } : {},
3335
+ remoteDir: args["remote-dir"],
3336
+ buildOn,
3337
+ ...args["from-source"] ? { source: true } : {},
3338
+ scheme: target === "vps" ? "https" : "http",
3339
+ domains,
3340
+ domain: apex,
3341
+ ...acme ? { acmeEmail: acme } : {}
3342
+ };
3343
+ const chosenApps = await askApps(args, d, earlierState?.apps);
3344
+ if (chosenApps) d.apps = chosenApps;
3345
+ const chosenSpores = chooseSpores(args, earlierState?.spores);
3346
+ if (chosenSpores) d.spores = chosenSpores;
3347
+ const env = setEmailSecret(newEnv(d, {
3348
+ email,
3349
+ storeName
3350
+ }), emailSettings);
3351
+ const earlier = args.force ? await loadEnv(dir).catch(() => void 0) : void 0;
3352
+ if (earlier) for (const key of KEPT) {
3353
+ const value = earlier.get(key);
3354
+ if (value !== void 0 && value !== "" && env.get(key) !== void 0) env.set(key, value);
3355
+ }
3356
+ keepAppKeys(earlier, env);
3357
+ ensureEncryptionKeys(d, env);
3358
+ await mkdir(join(dir, "seaweedfs"), {
3359
+ recursive: true,
3360
+ mode: 448
3361
+ });
3362
+ await chmod(dir, 448);
3363
+ await saveDeployment(dir, d);
3364
+ await saveEnv(dir, env);
3365
+ await writeFile(join(dir, "compose.yaml"), await composeFile());
3366
+ await writeFile(join(dir, "Caddyfile"), caddyfile(d, acme));
3367
+ await writeFile(join(dir, "hypha.config.toml"), configToml(target, emailSettings));
3368
+ await writeFile(join(dir, "hypha.config.schema.json"), await configSchema());
3369
+ await writeFile(join(dir, "seaweedfs", "s3.json"), seaweedConfig(env.get("S3_ACCESS_KEY"), env.get("S3_SECRET_KEY")));
3370
+ await chmod(join(dir, "seaweedfs", "s3.json"), 420);
3371
+ await writeFile(join(dir, ".gitignore"), `# Secrets: never commit these.\n${ENV_FILE}\nseaweedfs/\n# The co-located apps' clones (hypha deploy makes them again).\n.build/\n`);
3372
+ const lines = [
3373
+ `API ${url(d, domains.api)}`,
3374
+ ...domains.admin ? [`Admin ${url(d, domains.admin)}`] : [],
3375
+ ...domains.storefront ? [`Storefront ${url(d, domains.storefront)}`] : [],
3376
+ `Files ${url(d, domains.media)}`,
3377
+ `Emails ${emailLine(emailSettings)}`,
3378
+ ...appLines(d)
3379
+ ];
3380
+ p.note(lines.join("\n"), `Written to ${dir}`);
3381
+ if (target === "vps") {
3382
+ const host = ssh.split("@").pop();
3383
+ p.log.step(`Point these domains at the server (A/AAAA records to ${host}) before deploying,\nso Caddy can get their certificates.`);
3384
+ }
3385
+ p.outro(`Next: hypha deploy${args.dir === "hypha-deploy" ? "" : ` --dir ${args.dir}`}`);
3386
+ })
3387
+ });
3388
+ async function exists(path) {
3389
+ try {
3390
+ await stat(path);
3391
+ return true;
3392
+ } catch {
3393
+ return false;
3394
+ }
3395
+ }
3396
+ /**
3397
+ * `--target cloudflare`: the API, the admin and the storefront as Workers on your
3398
+ * account, the API over Hyperdrive to the Postgres you give (any provider), all deployed
3399
+ * with one API token.
3400
+ */
3401
+ async function initCloudflare(dir, args) {
3402
+ const databaseUrl = (await ask(args["database-url"], void 0, () => p.text({
3403
+ message: "The Postgres database's direct URL (Neon, Supabase, RDS, your own; not a pooler's)",
3404
+ placeholder: "postgres://user:password@host:5432/hypha?sslmode=require",
3405
+ validate: checkDatabaseUrl
3406
+ }))).trim();
3407
+ const problem = checkDatabaseUrl(databaseUrl);
3408
+ if (problem) throw new Error(`--database-url: ${problem}`);
3409
+ const domain = (await ask(args.domain, void 0, () => p.text({
3410
+ message: "Your domain, on Cloudflare",
3411
+ placeholder: "example.com",
3412
+ validate: checkDomain
3413
+ }))).toLowerCase();
3414
+ if (checkDomain(domain)) throw new Error(`--domain: ${domain} isn't a domain`);
3415
+ const sub = async (flag, label, fallback) => {
3416
+ const value = await ask(flag, fallback, () => p.text({
3417
+ message: label,
3418
+ initialValue: fallback,
3419
+ validate: checkDomain
3420
+ }));
3421
+ if (checkDomain(value)) throw new Error(`${label}: ${value} isn't a domain`);
3422
+ return value.toLowerCase();
3423
+ };
3424
+ const domains = {
3425
+ api: await sub(args["api-domain"], "The API's address", `api.${domain}`),
3426
+ media: await sub(args["media-domain"], "Uploaded files' address", `media.${domain}`),
3427
+ ...args.admin ? { admin: await sub(args["admin-domain"], "The admin's address", `admin.${domain}`) } : {},
3428
+ ...args.storefront ? { storefront: await sub(args["storefront-domain"], "The shop's address", `shop.${domain}`) } : {}
3429
+ };
3430
+ const name = await ask(args.name, "hypha", () => p.text({
3431
+ message: "A name for its resources (the Workers <name>-api, -admin, -storefront, …)",
3432
+ initialValue: "hypha",
3433
+ validate: (v) => v && NAME.test(v) ? void 0 : "lowercase letters, digits and dashes"
3434
+ }));
3435
+ if (!NAME.test(name)) throw new Error(`--name: ${name} should be lowercase letters, digits and dashes`);
3436
+ const r2Flag = (args["r2-access-key-id"] ?? "").trim();
3437
+ const earlierEnv = args.force ? await loadEnv(dir).catch(() => void 0) : void 0;
3438
+ const earlierState = args.force ? await loadDeployment(dir).catch(() => void 0) : void 0;
3439
+ const keptR2 = earlierEnv?.get("R2_ACCESS_KEY_ID") ? earlierEnv : void 0;
3440
+ const wantsMedia = args.media !== false;
3441
+ const { token, checked } = await obtainToken({
3442
+ name,
3443
+ domain,
3444
+ given: args["api-token"],
3445
+ known: earlierEnv?.get("CLOUDFLARE_API_TOKEN") || process.env.CLOUDFLARE_API_TOKEN || void 0,
3446
+ accountId: args["account-id"],
3447
+ zoneId: args["zone-id"],
3448
+ quiet: args.yes,
3449
+ apps: Boolean(args.apps && args.apps !== "none") || Boolean(earlierState?.apps?.length)
3450
+ });
3451
+ let r2 = {
3452
+ id: "",
3453
+ secret: ""
3454
+ };
3455
+ if (!wantsMedia) {} else if (r2Flag) {
3456
+ r2 = isTokenValue(r2Flag) ? await r2KeysOf(r2Flag, checked.accountId) : {
3457
+ id: r2Flag,
3458
+ secret: (args["r2-secret-access-key"] ?? "").trim()
3459
+ };
3460
+ const wrong = checkR2Keys(r2.id, r2.secret);
3461
+ if (wrong) throw new Error(`the R2 keys: ${wrong}`);
3462
+ } else if (keptR2) r2 = {
3463
+ id: keptR2.get("R2_ACCESS_KEY_ID"),
3464
+ secret: keptR2.get("R2_SECRET_ACCESS_KEY") ?? ""
3465
+ };
3466
+ else if (checked.r2) r2 = await r2KeysOf(token, checked.accountId);
3467
+ else p.log.warn("The token can't use R2, so uploads are off: add R2 (edit) to it, then run init --force.");
3468
+ const media = Boolean(r2.id);
3469
+ const email = (await ask(args["owner-email"], void 0, () => p.text({
3470
+ message: "The owner's email (the first staff user)",
3471
+ validate: checkEmail
3472
+ }))).trim();
3473
+ if (checkEmail(email)) throw new Error(`--owner-email: ${email} isn't an email address`);
3474
+ const storeName = await ask(args["store-name"], "My store", () => p.text({
3475
+ message: "The store's name",
3476
+ initialValue: "My store"
3477
+ }));
3478
+ const emailSettings = await askEmail(args, "cloudflare", domains.storefront ?? domains.api);
3479
+ const earlier = earlierState?.cloudflare?.name === name ? earlierState.cloudflare : void 0;
3480
+ const d = {
3481
+ version: 1,
3482
+ target: "cloudflare",
3483
+ remoteDir: "",
3484
+ buildOn: "here",
3485
+ scheme: "https",
3486
+ domains,
3487
+ domain,
3488
+ cloudflare: {
3489
+ name,
3490
+ accountId: checked.accountId,
3491
+ zoneId: checked.zoneId,
3492
+ ...args.region ? { region: args.region } : {},
3493
+ rateLimitBase: earlier?.rateLimitBase ?? (1 + randomInt(9e4)) * 100,
3494
+ ...earlier?.hyperdriveId ? { hyperdriveId: earlier.hyperdriveId } : {},
3495
+ ...earlier?.kvId ? { kvId: earlier.kvId } : {},
3496
+ ...earlier?.cacheKvId ? { cacheKvId: earlier.cacheKvId } : {}
3497
+ }
3498
+ };
3499
+ const chosenApps = await askApps(args, d, earlier ? earlierState?.apps : earlierState?.apps?.map(({ d1Id: _d1, deployed: _deployed, ...rest }) => rest));
3500
+ if (chosenApps) d.apps = chosenApps;
3501
+ const chosenSpores = chooseSpores(args, earlierState?.spores);
3502
+ if (chosenSpores) d.spores = chosenSpores;
3503
+ const env = setEmailSecret(newCloudflareEnv({
3504
+ email,
3505
+ storeName
3506
+ }, databaseUrl, {
3507
+ token,
3508
+ r2,
3509
+ storefront: Boolean(domains.storefront)
3510
+ }), emailSettings);
3511
+ const given = /* @__PURE__ */ new Set([
3512
+ "DATABASE_URL",
3513
+ "CLOUDFLARE_API_TOKEN",
3514
+ "R2_ACCESS_KEY_ID",
3515
+ "R2_SECRET_ACCESS_KEY",
3516
+ "HYPHA_RESEND_API_KEY"
3517
+ ]);
3518
+ if (earlierEnv) for (const key of KEPT) {
3519
+ const value = earlierEnv.get(key);
3520
+ if (!given.has(key) && value !== void 0 && value !== "" && env.get(key) !== void 0) env.set(key, value);
3521
+ }
3522
+ keepAppKeys(earlierEnv, env);
3523
+ ensureEncryptionKeys(d, env);
3524
+ await mkdir(dir, {
3525
+ recursive: true,
3526
+ mode: 448
3527
+ });
3528
+ await chmod(dir, 448);
3529
+ await saveDeployment(dir, d);
3530
+ await saveEnv(dir, env);
3531
+ await writeFile(join(dir, "hypha.config.toml"), configToml("cloudflare", emailSettings));
3532
+ await writeFile(join(dir, "hypha.config.schema.json"), await configSchema());
3533
+ await writeFile(join(dir, ".gitignore"), `# Secrets: never commit these.\n${ENV_FILE}\n.secrets*.json\n.cors.json\n# The co-located apps' clones (hypha deploy makes them again).\n.build/\n`);
3534
+ p.note([
3535
+ `API ${url(d, domains.api)}`,
3536
+ ...domains.admin ? [`Admin ${url(d, domains.admin)}`] : [],
3537
+ ...domains.storefront ? [`Storefront ${url(d, domains.storefront)}`] : [],
3538
+ `Files ${media ? url(d, domains.media) : "off (no R2 keys)"}`,
3539
+ `Emails ${emailLine(emailSettings)}`,
3540
+ `Database ${new URL(databaseUrl).host}`,
3541
+ ...appLines(d)
3542
+ ].join("\n"), `Written to ${dir}`);
3543
+ p.log.step("hypha deploy needs Rust with `rustup target add wasm32-unknown-unknown` and `cargo install worker-build`.");
3544
+ p.outro(`Next: hypha deploy${args.dir === "hypha-deploy" ? "" : ` --dir ${args.dir}`}`);
3545
+ }
3546
+ /** Every value answered or flagged, else an error naming the flag. */
3547
+ function required(value, flag, why) {
3548
+ const trimmed = value.trim();
3549
+ if (!trimmed) throw new Error(`--${flag} is required ${why}`);
3550
+ return trimmed;
3551
+ }
3552
+ /**
3553
+ * How the API sends email: the log (nothing is sent; the default), Resend with its API
3554
+ * key, or an SMTP server (a server's own, not Workers'). `domain` suggests the from
3555
+ * address.
3556
+ */
3557
+ async function askEmail(args, target, domain) {
3558
+ const sender = await ask(args["email-sender"], "log", () => p.select({
3559
+ message: "How should emails (order confirmations, invites) go out?",
3560
+ options: [
3561
+ {
3562
+ value: "resend",
3563
+ label: "Resend",
3564
+ hint: "an API key from resend.com"
3565
+ },
3566
+ ...target === "cloudflare" ? [] : [{
3567
+ value: "smtp",
3568
+ label: "SMTP",
3569
+ hint: "any provider's server"
3570
+ }],
3571
+ {
3572
+ value: "log",
3573
+ label: "Not yet",
3574
+ hint: "written to the API's log; set it up later"
3575
+ }
3576
+ ]
3577
+ }));
3578
+ if (sender !== "log" && sender !== "resend" && sender !== "smtp") throw new Error(`--email-sender is log, resend or smtp, not ${sender}`);
3579
+ if (sender === "smtp" && target === "cloudflare") throw new Error("--email-sender smtp isn't available on Cloudflare Workers: use resend");
3580
+ if (sender === "log") return { sender };
3581
+ const why = `with --email-sender ${sender}`;
3582
+ const from = required(await ask(args["email-from"], "", () => p.text({
3583
+ message: "The address emails come from (on a domain your provider verified)",
3584
+ placeholder: `shop@mail.${domain}`,
3585
+ validate: checkEmail
3586
+ })), "email-from", why);
3587
+ if (checkEmail(from)) throw new Error(`--email-from: ${from} isn't an email address`);
3588
+ if (sender === "resend") return {
3589
+ sender,
3590
+ from,
3591
+ apiKey: required(await ask(args["resend-api-key"], "", () => p.password({
3592
+ message: "Resend's API key (resend.com/api-keys, with sending access)",
3593
+ validate: (v) => v?.trim().startsWith("re_") ? void 0 : "a key starting re_"
3594
+ })), "resend-api-key", why)
3595
+ };
3596
+ const host = required(await ask(args["smtp-host"], "", () => p.text({
3597
+ message: "The SMTP server",
3598
+ placeholder: "smtp.example.com",
3599
+ validate: (v) => v?.trim() ? void 0 : "a host name"
3600
+ })), "smtp-host", why);
3601
+ const tlsAnswer = await ask(args["smtp-tls"], "starttls", () => p.select({
3602
+ message: "How is the connection encrypted?",
3603
+ options: [
3604
+ {
3605
+ value: "starttls",
3606
+ label: "STARTTLS",
3607
+ hint: "usually port 587"
3608
+ },
3609
+ {
3610
+ value: "tls",
3611
+ label: "TLS",
3612
+ hint: "usually port 465"
3613
+ },
3614
+ {
3615
+ value: "none",
3616
+ label: "None",
3617
+ hint: "a server on the same network only"
3618
+ }
3619
+ ]
3620
+ }));
3621
+ if (tlsAnswer !== "starttls" && tlsAnswer !== "tls" && tlsAnswer !== "none") throw new Error(`--smtp-tls is starttls, tls or none, not ${tlsAnswer}`);
3622
+ const tls = tlsAnswer;
3623
+ const defaultPort = tls === "tls" ? "465" : "587";
3624
+ const portAnswer = await ask(args["smtp-port"], defaultPort, () => p.text({
3625
+ message: "Its port",
3626
+ initialValue: defaultPort
3627
+ }));
3628
+ const port = Number(portAnswer);
3629
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`--smtp-port: ${portAnswer} isn't a port (1 to 65535)`);
3630
+ const username = (await ask(args["smtp-username"], "", () => p.text({
3631
+ message: "The login (empty for none)",
3632
+ placeholder: "apikey"
3633
+ }))).trim();
3634
+ if (!username) return {
3635
+ sender,
3636
+ from,
3637
+ host,
3638
+ port,
3639
+ tls
3640
+ };
3641
+ return {
3642
+ sender,
3643
+ from,
3644
+ host,
3645
+ port,
3646
+ tls,
3647
+ username,
3648
+ password: required(await ask(args["smtp-password"], "", () => p.password({
3649
+ message: "Its password",
3650
+ validate: (v) => v ? void 0 : "the login's password"
3651
+ })), "smtp-password", "with --smtp-username")
3652
+ };
3653
+ }
3654
+ function emailLine(email) {
3655
+ switch (email.sender) {
3656
+ case "log": return "logged, not sent (set [email] in hypha.config.toml)";
3657
+ case "resend": return `Resend, from ${email.from}`;
3658
+ case "smtp": return `SMTP ${email.host}:${email.port}, from ${email.from}`;
3659
+ }
3660
+ }
3661
+ /** The spores to compile into the API: `--spores` (`none` for none), else the earlier list
3662
+ * with `--force`, else none. Not asked: `hypha spores add` adds one later. */
3663
+ function chooseSpores(args, earlier) {
3664
+ if (args.spores === void 0) return earlier;
3665
+ if (args.spores.trim() === "none") return void 0;
3666
+ return normalizeSpores(args.spores.split(",").map((s) => s.trim()).filter(Boolean), "--spores");
3667
+ }
3668
+ /** The co-located apps in the summary. */
3669
+ function appLines(d) {
3670
+ return (d.apps ?? []).map((a) => `${a.name.padEnd(10)} ${appUrl(d, a)}`);
3671
+ }
3672
+ /** Keeps every app's encryption key from the earlier `.env` (`--force`): without it the
3673
+ * app loses what it sealed. */
3674
+ function keepAppKeys(earlier, env) {
3675
+ if (!earlier) return;
3676
+ for (const key of earlier.keys().filter((k) => ENCRYPTION_KEY_VAR.test(k))) {
3677
+ const value = earlier.get(key);
3678
+ if (value && !env.get(key)) env.set(key, value);
3679
+ }
3680
+ }
3681
+ /**
3682
+ * The first-party apps to deploy alongside: `--apps`, else asked (none by default), each
3683
+ * pinned to its repository's head and on `<name>.<domain>` unless another domain is
3684
+ * given. With `--force`, the earlier list stays unless `--apps` replaces it (an app kept
3685
+ * keeps its commit, domain and resources). `undefined`: none.
3686
+ */
3687
+ async function askApps(args, d, earlier) {
3688
+ if (args.apps === void 0 && earlier) return earlier;
3689
+ let names;
3690
+ if (args.apps !== void 0) names = args.apps === "none" ? [] : args.apps.split(",").map((n) => n.trim()).filter(Boolean);
3691
+ else if (args.yes || !process.stdin.isTTY) names = [];
3692
+ else {
3693
+ const answer = await p.multiselect({
3694
+ message: "Deploy apps alongside? (each installed afterwards on its consent page)",
3695
+ options: Object.keys(FIRST_PARTY).map((name) => ({
3696
+ value: name,
3697
+ label: name,
3698
+ hint: name === "stripe" ? "card payments" : "search through Meilisearch"
3699
+ })),
3700
+ required: false
3701
+ });
3702
+ if (p.isCancel(answer)) {
3703
+ p.cancel("Cancelled.");
3704
+ process.exit(1);
3705
+ }
3706
+ names = answer;
3707
+ }
3708
+ if (names.length === 0) return void 0;
3709
+ const out = [];
3710
+ for (const name of names) {
3711
+ if (!FIRST_PARTY[name]) throw new Error(`--apps: ${name} isn't a first-party app (${Object.keys(FIRST_PARTY).join(", ")}); add others with \`hypha apps add <git url>\``);
3712
+ const kept = earlier?.find((a) => a.name === name);
3713
+ if (kept) {
3714
+ out.push(kept);
3715
+ continue;
3716
+ }
3717
+ const entry = entryFor(name);
3718
+ const fallback = `${name}.${d.domain}`;
3719
+ const domain = d.target === "local" ? fallback : (await ask(void 0, fallback, () => p.text({
3720
+ message: `The ${name} app's address`,
3721
+ initialValue: fallback,
3722
+ validate: checkDomain
3723
+ }))).toLowerCase();
3724
+ if (checkDomain(domain)) throw new Error(`the ${name} app's address: ${domain} isn't a domain`);
3725
+ if (domain !== fallback) entry.domain = domain;
3726
+ try {
3727
+ entry.rev = await remoteHead(entry.git);
3728
+ } catch (e) {
3729
+ p.log.warn(`Couldn't read ${entry.git}'s head (${e instanceof Error ? e.message.split("\n")[0] : String(e)}): \`hypha deploy\` pins it`);
3730
+ }
3731
+ out.push(entry);
3732
+ }
3733
+ return out;
3734
+ }
3735
+ //#endregion
3736
+ //#region src/commands/ops.ts
3737
+ const status = defineCommand({
3738
+ meta: {
3739
+ name: "status",
3740
+ description: "What's running, and whether the API answers"
3741
+ },
3742
+ args: { dir: dirArg },
3743
+ run: ({ args }) => guarded(async () => {
3744
+ const deployment = await loadDeployment(args.dir);
3745
+ if (deployment.target === "cloudflare") {
3746
+ p.intro("hypha status → Cloudflare");
3747
+ let ok = await healthy(deployment);
3748
+ p.log.step(`${workerName(deployment)} ${url(deployment, deployment.domains.api)}/health ${ok ? "answers" : "doesn't answer"}`);
3749
+ for (const app of apps$1(deployment)) {
3750
+ const target = url(deployment, deployment.domains[app]);
3751
+ const answers = await waitForAnswer(target, 1);
3752
+ ok &&= answers;
3753
+ p.log.step(`${appWorker(deployment, app)} ${target} ${answers ? "answers" : "doesn't answer"}`);
3754
+ }
3755
+ for (const entry of deployment.apps ?? []) {
3756
+ const answers = await waitForAnswer(`${appUrl(deployment, entry)}/health`, 1);
3757
+ ok &&= answers;
3758
+ p.log.step(`${appWorkerName(deployment, entry)} ${appUrl(deployment, entry)} ${answers ? "answers" : "doesn't answer"}`);
3759
+ }
3760
+ p.outro(ok ? "Everything answers (whether the apps are installed: `hypha apps status`)" : "Something doesn't answer: see `hypha logs <api|admin|storefront|app>`");
3761
+ if (!ok) process.exitCode = 1;
3762
+ return;
3763
+ }
3764
+ const { d, machine } = await open(args.dir);
3765
+ p.intro(`hypha status → ${machine.label}`);
3766
+ await machine.sh("docker compose ps --format 'table {{.Service}}\\t{{.Status}}'");
3767
+ const ok = await healthy(d);
3768
+ p.outro(`${url(d, d.domains.api)}/health ${ok ? "answers" : "doesn't answer"}`);
3769
+ if (!ok) process.exitCode = 1;
3770
+ })
3771
+ });
3772
+ const logs = defineCommand({
3773
+ meta: {
3774
+ name: "logs",
3775
+ description: "A service's logs (api, admin, storefront, caddy, postgres, s3, app-<name>), or all"
3776
+ },
3777
+ args: {
3778
+ dir: dirArg,
3779
+ service: {
3780
+ type: "positional",
3781
+ required: false,
3782
+ description: "One service; all without"
3783
+ },
3784
+ follow: {
3785
+ type: "boolean",
3786
+ alias: "f",
3787
+ description: "Keep printing new lines"
3788
+ },
3789
+ tail: {
3790
+ type: "string",
3791
+ default: "200",
3792
+ description: "Lines to start with"
3793
+ }
3794
+ },
3795
+ run: ({ args }) => guarded(async () => {
3796
+ const deployment = await loadDeployment(args.dir);
3797
+ if (deployment.target === "cloudflare") {
3798
+ const worker = cloudflareWorker(deployment, args.service);
3799
+ const env = {};
3800
+ const token = (await loadEnv(args.dir).catch(() => void 0))?.get("CLOUDFLARE_API_TOKEN");
3801
+ if (token) env.CLOUDFLARE_API_TOKEN = token;
3802
+ if (deployment.cloudflare?.accountId) env.CLOUDFLARE_ACCOUNT_ID = deployment.cloudflare.accountId;
3803
+ await run("wrangler", [
3804
+ "tail",
3805
+ worker,
3806
+ "--format",
3807
+ "pretty"
3808
+ ], { env });
3809
+ return;
3810
+ }
3811
+ const { machine } = await open(args.dir);
3812
+ const service = args.service ? ` ${quote(args.service)}` : "";
3813
+ await machine.sh(`docker compose logs --tail ${quote(args.tail)}${args.follow ? " -f" : ""}${service}`);
3814
+ })
3815
+ });
3816
+ /** The Worker `service` names (api by default) in a Cloudflare deployment. */
3817
+ function cloudflareWorker(d, service) {
3818
+ if (!service || service === "api") return workerName(d);
3819
+ if (service === "admin" || service === "storefront") {
3820
+ if (!d.domains[service]) throw new Error(`this deployment has no ${service}`);
3821
+ return appWorker(d, service);
3822
+ }
3823
+ const app = (d.apps ?? []).find((a) => service === a.name || service === `app-${a.name}`);
3824
+ if (app) return appWorkerName(d, app);
3825
+ throw new Error(`on Cloudflare, logs are per Worker: api, admin, storefront${(d.apps ?? []).map((a) => `, ${a.name}`).join("")} (not ${service})`);
3826
+ }
3827
+ //#endregion
3828
+ //#region src/commands/spores.ts
3829
+ /** What `list` shows for a spore. */
3830
+ function describeSpore(entry) {
3831
+ const source = entry.git ? `${entry.git} @ ${entry.rev?.slice(0, 12) ?? "unpinned"}` : entry.version ? `crates.io ${entry.version}` : `path ${entry.path}`;
3832
+ return `${entry.name.padEnd(12)} ${entry.crate} (${source})`;
3833
+ }
3834
+ const spores = defineCommand({
3835
+ meta: {
3836
+ name: "spores",
3837
+ description: "Spores compiled into the API (Stripe, or any spore crate)"
3838
+ },
3839
+ subCommands: {
3840
+ list: defineCommand({
3841
+ meta: {
3842
+ name: "list",
3843
+ description: "The spores hypha.json lists"
3844
+ },
3845
+ args: { dir: dirArg },
3846
+ run: ({ args }) => guarded(async () => {
3847
+ const listed = (await loadDeployment(args.dir)).spores ?? [];
3848
+ if (listed.length === 0) {
3849
+ p.log.info(`No spores: \`hypha spores add ${Object.keys(FIRST_PARTY_SPORES)[0]}\` adds the first-party one.`);
3850
+ return;
3851
+ }
3852
+ p.log.message(listed.map(describeSpore).join("\n"));
3853
+ })
3854
+ }),
3855
+ add: defineCommand({
3856
+ meta: {
3857
+ name: "add",
3858
+ description: "List a spore in hypha.json (then `hypha deploy` builds the API with it)"
3859
+ },
3860
+ args: {
3861
+ dir: dirArg,
3862
+ spore: {
3863
+ type: "positional",
3864
+ required: true,
3865
+ description: `A first-party spore (${Object.keys(FIRST_PARTY_SPORES).join(", ")}), or a name with --crate`
3866
+ },
3867
+ crate: {
3868
+ type: "string",
3869
+ description: "Its crate (a spore from outside)"
3870
+ },
3871
+ type: {
3872
+ type: "string",
3873
+ description: "Its Spore type (crate_name::Type)"
3874
+ },
3875
+ routes: {
3876
+ type: "string",
3877
+ description: "Its route macro (crate_name::name_routes), if it has routes"
3878
+ },
3879
+ git: {
3880
+ type: "string",
3881
+ description: "Its repository (with --rev)"
3882
+ },
3883
+ rev: {
3884
+ type: "string",
3885
+ description: "The commit (40 hex digits); without it, the next deploy pins the head"
3886
+ },
3887
+ version: {
3888
+ type: "string",
3889
+ description: "Its crates.io version"
3890
+ },
3891
+ path: {
3892
+ type: "string",
3893
+ description: "A local path (relative to the deployment)"
3894
+ }
3895
+ },
3896
+ run: ({ args }) => guarded(async () => {
3897
+ const d = await loadDeployment(args.dir);
3898
+ const raw = args.crate ? {
3899
+ name: args.spore,
3900
+ crate: args.crate,
3901
+ spore: args.type,
3902
+ ...args.routes ? { routes: args.routes } : {},
3903
+ ...args.git ? {
3904
+ git: args.git,
3905
+ rev: args.rev
3906
+ } : {},
3907
+ ...args.version ? { version: args.version } : {},
3908
+ ...args.path ? { path: args.path } : {}
3909
+ } : args.spore;
3910
+ d.spores = normalizeSpores([...d.spores ?? [], raw], "--");
3911
+ await saveDeployment(args.dir, d);
3912
+ p.log.success(`Listed the ${args.spore} spore: \`hypha deploy\` builds the API with it, and it registers at the API's start.`);
3913
+ })
3914
+ }),
3915
+ remove: defineCommand({
3916
+ meta: {
3917
+ name: "remove",
3918
+ description: "Take a spore out of hypha.json (its tables and app stay, shown as missing, until dropped)"
3919
+ },
3920
+ args: {
3921
+ dir: dirArg,
3922
+ spore: {
3923
+ type: "positional",
3924
+ required: true,
3925
+ description: "Its name"
3926
+ }
3927
+ },
3928
+ run: ({ args }) => guarded(async () => {
3929
+ const d = await loadDeployment(args.dir);
3930
+ const before = d.spores ?? [];
3931
+ const after = before.filter((s) => sporeName(s) !== args.spore);
3932
+ if (after.length === before.length) throw new Error(`no spore ${args.spore} in hypha.json`);
3933
+ d.spores = after;
3934
+ await saveDeployment(args.dir, d);
3935
+ p.log.success(`Took the ${args.spore} spore out: the next \`hypha deploy\` builds the API without it.`);
3936
+ })
3937
+ })
3938
+ }
3939
+ });
3940
+ //#endregion
3941
+ //#region src/main.ts
3942
+ const main = defineCommand({
3943
+ meta: {
3944
+ name: "hypha",
3945
+ version: VERSION,
3946
+ description: "Host Hypha: the API, the admin, the storefront and the apps beside them; start your own"
3947
+ },
3948
+ subCommands: {
3949
+ init,
3950
+ deploy,
3951
+ status,
3952
+ logs,
3953
+ apps,
3954
+ spores,
3955
+ create: createCommand
3956
+ }
3957
+ });
3958
+ await runMain(main);
3959
+ //#endregion
3960
+ export {};