@basaltkit/deploy 0.2.1 → 0.3.1

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/config.d.ts CHANGED
@@ -5,21 +5,57 @@
5
5
  * its own module. A config can therefore be printed, diffed and validated
6
6
  * without running anything.
7
7
  */
8
- export interface DeployConfig {
9
- /** Owner label: names every process, container, volume, vhost and backup. `[a-z][a-z0-9-]{1,30}`. */
8
+ /**
9
+ * The app's environment, as `defineEnv` returns it: `defineDeploy<typeof env>`
10
+ * with `import type { env } from './src/env.js'` types every `.env` key the
11
+ * config names (RFC 0007 §2.1). Type-only — the app is never loaded.
12
+ */
13
+ export type EnvShape = Record<string, unknown>;
14
+ /** A key of the app's `.env`: any string until `defineDeploy<typeof env>` narrows it. */
15
+ export type EnvKey<E extends object = EnvShape> = Extract<keyof E, string>;
16
+ /**
17
+ * What a `.env` line may hold for a value of type `T`: an enum's members, a
18
+ * number's digits, `true`/`false` — else any string.
19
+ */
20
+ export type EnvValue<T> = ValueOf<T & {}>;
21
+ type ValueOf<N> = [
22
+ N
23
+ ] extends [never] ? string : N extends string ? (string extends N ? string : N) : N extends number ? `${number}` : N extends boolean ? 'true' | 'false' : string;
24
+ export interface DeployConfig<E extends object = EnvShape> {
25
+ /**
26
+ * Owner label: names every process, container, volume, vhost and backup.
27
+ * `[a-z][a-z0-9-]{1,30}`.
28
+ * @example 'acme'
29
+ */
10
30
  app: string;
11
- /** The apex the app answers on, e.g. `lexfirma.aipro.ao`. */
31
+ /**
32
+ * The apex the app answers on.
33
+ * @example 'acme.example.com'
34
+ */
12
35
  domain: string;
13
- /** `subdomain` → tenants live on `<id>.<domain>`: the wildcard certificate is checked too. */
36
+ /**
37
+ * `subdomain` → tenants live on `<id>.<domain>`: the wildcard certificate is checked too.
38
+ * @default 'none'
39
+ */
14
40
  tenants?: 'subdomain' | 'none';
41
+ /**
42
+ * The branch a deploy fetches and fast-forwards to.
43
+ * @default 'main'
44
+ */
15
45
  branch?: string;
46
+ /** @default 'origin' */
16
47
  remote?: string;
17
- env: EnvConfig;
18
- infra?: InfraConfig;
48
+ /** The `.env`: where it lives and what the deploy keeps in it. */
49
+ env: EnvConfig<E>;
50
+ /** Databases, caches and object storage: `dockerInfra(app)` or `external()`. */
51
+ infra?: InfraConfig<E>;
19
52
  build?: BuildConfig;
20
- migrate?: MigrateConfig;
21
- backup?: BackupConfig;
53
+ migrate?: MigrateConfig<E>;
54
+ /** The `pg_dump` before migrating (RFC 0006 §8). */
55
+ backup?: BackupConfig<E>;
56
+ /** How the app runs: `pm2({ … })` or `compose({ … })`. */
22
57
  runtime: RuntimeConfig;
58
+ /** What sits in front: `apache({ … })` or `none()`. Default: none. */
23
59
  proxy?: ProxyConfig;
24
60
  health?: HealthConfig;
25
61
  /**
@@ -35,6 +71,31 @@ export interface DeployConfig {
35
71
  * `DEPLOY_APP` in their environment. Idempotent — they run on every deploy.
36
72
  */
37
73
  hooks?: HooksConfig;
74
+ /** Declarative checks after the health check; a failure is a failed release, rolled back (RFC 0007 §6). */
75
+ verify?: VerifyConfig;
76
+ /** What `basalt-deploy bootstrap` sets up on a fresh server (RFC 0007 §7). */
77
+ bootstrap?: {
78
+ /** Swap created when RAM is under 6 GB and there is none; 0 = never. @default 4 */
79
+ swapGb?: number;
80
+ /** ufw: SSH (+ 80/443 behind a proxy), turned on only when nothing else listens. @default true */
81
+ firewall?: boolean;
82
+ };
83
+ }
84
+ export interface VerifyConfig {
85
+ /**
86
+ * Per compose service, text that must not appear in its logs since the
87
+ * release started — a worker that cannot reach its queue logs, it does not crash.
88
+ * @example { 'ingest-worker': ['EAI_AGAIN', 'ECONNREFUSED'] }
89
+ */
90
+ logs?: Record<string, string[]>;
91
+ /**
92
+ * More URLs on the API than `health.path`, each answering `expect` (default 200).
93
+ * @example [{ path: '/readyz' }]
94
+ */
95
+ http?: Array<{
96
+ path: `/${string}`;
97
+ expect?: number;
98
+ }>;
38
99
  }
39
100
  export interface HooksConfig {
40
101
  /** After the `.env` and the infra, before the build. Failing stops the deploy (code put back). */
@@ -42,25 +103,51 @@ export interface HooksConfig {
42
103
  /** After the health check. Failing is a failed release (rolled back). */
43
104
  verify?: string[][];
44
105
  }
45
- export interface EnvConfig {
106
+ export interface EnvConfig<E extends object = EnvShape> {
46
107
  /**
47
- * Relative to the app directory, or absolute (e.g. `/etc/mukanda/api.env`).
48
- * Written 0600, backed up before every change, in its own directory.
108
+ * Relative to the app directory, or absolute. Written 0600, backed up
109
+ * before every change, in its own directory.
110
+ * @default '.env'
111
+ * @example '/etc/globex/api.env'
49
112
  */
50
113
  file?: string;
51
114
  /** Exact copies of the file (0600), rewritten with it; one that differs is a C10 error. */
52
115
  mirror?: string[];
53
- /** The module whose import runs the app's `defineEnv(...)`, e.g. `src/env.ts`. */
116
+ /**
117
+ * The module whose import runs the app's `defineEnv(...)`; the new `.env`
118
+ * is validated against it before migrating.
119
+ * @example 'src/env.ts'
120
+ */
54
121
  schema?: string;
55
- /** Always these values — a different one in the file is corrected. */
56
- fixed?: Record<string, string>;
57
- /** Generated once when absent, then kept. */
58
- generate?: Record<string, SecretSpec>;
59
- /** Asked once when absent or empty, then kept. */
60
- ask?: Record<string, Question>;
122
+ /**
123
+ * Always these values — a different one in the file is corrected.
124
+ * @example { NODE_ENV: 'production' }
125
+ */
126
+ fixed?: {
127
+ [K in EnvKey<E>]?: EnvValue<E[K]>;
128
+ };
129
+ /**
130
+ * Generated once when absent, then kept.
131
+ * @example { APP_SECRET: secret(32) }
132
+ */
133
+ generate?: {
134
+ [K in EnvKey<E>]?: SecretSpec;
135
+ };
136
+ /**
137
+ * Asked once when absent or empty, then kept.
138
+ * @example { SMTP_URL: ask('SMTP URL', { secret: true }) }
139
+ */
140
+ ask?: {
141
+ [K in EnvKey<E>]?: Question;
142
+ };
61
143
  /** Computed from the deploy's own values on every run. */
62
- derive?: (context: DeriveContext) => Record<string, string>;
63
- /** Must not exist in the file at all (e.g. a flag whose "0" would read as true). */
144
+ derive?: (context: DeriveContext) => {
145
+ [K in EnvKey<E>]?: string;
146
+ };
147
+ /**
148
+ * Must not exist in the file at all (e.g. a flag whose "0" would read as
149
+ * true). Usually keys the schema no longer has, so any string.
150
+ */
64
151
  forbid?: string[];
65
152
  }
66
153
  export interface DeriveContext {
@@ -81,52 +168,114 @@ export interface Question {
81
168
  optional: boolean;
82
169
  default?: string;
83
170
  }
84
- export type InfraConfig = ExternalInfra | DockerInfra;
85
- export interface ExternalInfra {
171
+ export type InfraConfig<E extends object = EnvShape> = ExternalInfra<E> | DockerInfra<E>;
172
+ /**
173
+ * Containers this deploy does not create (their data outlives any release),
174
+ * but keeps: checked running in the preflight, the app's database role and the
175
+ * buckets maintained on every deploy, the database dumped before migrating
176
+ * (RFC 0007 §4.5). Without services, `external()` means "nothing to do".
177
+ */
178
+ export interface ExternalInfra<E extends object = EnvShape> {
86
179
  kind: 'external';
180
+ postgres?: ExternalPostgres<E>;
181
+ redis?: {
182
+ container: string;
183
+ };
184
+ minio?: {
185
+ container: string;
186
+ buckets?: Bucket[];
187
+ };
87
188
  }
88
- export interface DockerInfra {
189
+ export interface ExternalPostgres<E extends object = EnvShape> {
190
+ container: string;
191
+ /**
192
+ * The `.env` key with the OWNER's URL (user, password, database): what the
193
+ * role, the grants and the dump run as.
194
+ * @default 'DATABASE_URL'
195
+ */
196
+ urlKey?: EnvKey<E>;
197
+ appRole?: AppRole<E>;
198
+ }
199
+ /**
200
+ * The role the app connects as: no DDL, no superuser (RFC 0007 §4.1). Created
201
+ * when missing, its password kept equal to the URL at `urlKey` (generated
202
+ * there when absent), and granted DML through the owner's default privileges.
203
+ */
204
+ export interface AppRole<E extends object = EnvShape> {
205
+ /** @example 'globex_app' */
206
+ name: string;
207
+ /** The `.env` key with the app's URL. */
208
+ urlKey: EnvKey<E>;
209
+ }
210
+ /**
211
+ * A bucket name, or one with its policy: `versioned` turns versioning on,
212
+ * `expireDays` adds an expiry rule — once (RFC 0007 §4.2).
213
+ */
214
+ export type Bucket = string | {
215
+ name: string;
216
+ versioned?: boolean;
217
+ expireDays?: number;
218
+ };
219
+ export interface DockerInfra<E extends object = EnvShape> {
89
220
  kind: 'docker';
90
- postgres?: PostgresService;
91
- redis?: RedisService;
221
+ postgres?: PostgresService<E>;
222
+ redis?: RedisService<E>;
92
223
  minio?: MinioService;
93
224
  }
94
- export interface PostgresService {
225
+ export interface PostgresService<E extends object = EnvShape> {
95
226
  image: string;
96
227
  /** Host port on 127.0.0.1; `auto` keeps the running container's, else the `.env` URL's, else the first free from 5433. */
97
228
  port: number | 'auto';
98
229
  user: string;
99
230
  database: string;
100
- /** The `.env` key that receives the connection URL. */
101
- urlKey: string;
231
+ /**
232
+ * The `.env` key that receives the connection URL.
233
+ * @default 'DATABASE_URL'
234
+ */
235
+ urlKey: EnvKey<E>;
102
236
  /** Query parameters appended to the URL (e.g. `{ schema: 'public' }` for Prisma). */
103
237
  urlParams: Record<string, string>;
238
+ /** Adopt a container under another name. Default `<app>-pg`. */
239
+ container?: string;
240
+ appRole?: AppRole<E>;
104
241
  }
105
- export interface RedisService {
242
+ export interface RedisService<E extends object = EnvShape> {
106
243
  image: string;
107
244
  port: number | 'auto';
108
- urlKey: string;
245
+ /** @default 'REDIS_URL' */
246
+ urlKey: EnvKey<E>;
247
+ /** Adopt a container under another name. Default `<app>-redis`. */
248
+ container?: string;
109
249
  }
110
250
  export interface MinioService {
111
251
  image: string;
112
252
  port: number | 'auto';
113
253
  consolePort: number | 'auto';
114
254
  user: string;
115
- buckets: string[];
255
+ buckets: Bucket[];
116
256
  /** The `.env` keys that receive the endpoint and the credentials. */
117
257
  keys: {
118
258
  endpoint: string;
119
259
  accessKey: string;
120
260
  secretKey: string;
121
261
  };
262
+ /** Adopt a container under another name. Default `<app>-minio`. */
263
+ container?: string;
122
264
  }
123
265
  export interface BuildConfig {
124
266
  /** Prisma config files, each generated with `prisma generate --config <file>`. */
125
267
  prisma?: string[];
268
+ /**
269
+ * The package.json script that compiles the app, run after `prisma
270
+ * generate` — needed when `start` runs the compiled output (`node dist/…`),
271
+ * as a create-basalt app's does.
272
+ * @example 'build'
273
+ */
274
+ script?: string;
126
275
  /** Frontend directory built with `<pm> --dir <web> build`. */
127
276
  web?: string;
128
277
  }
129
- export interface MigrateConfig {
278
+ export interface MigrateConfig<E extends object = EnvShape> {
130
279
  /** `prisma migrate deploy` with the root Prisma config. */
131
280
  central?: boolean;
132
281
  /** `<pm> basalt tenant:migrate` (or the given package.json script arguments). */
@@ -138,18 +287,34 @@ export interface MigrateConfig {
138
287
  command?: string[];
139
288
  /**
140
289
  * Values that override the `.env` for the migration and the pre-migration
141
- * dump — e.g. URLs that name a container (`@mukanda-postgres:`) rewritten to
290
+ * dump — e.g. URLs that name a container (`@globex-postgres:`) rewritten to
142
291
  * reach it from the host (`@127.0.0.1:`).
143
292
  */
144
- env?: (values: ReadonlyMap<string, string>) => Record<string, string>;
293
+ env?: (values: ReadonlyMap<EnvKey<E>, string>) => {
294
+ [K in EnvKey<E>]?: string;
295
+ };
145
296
  }
146
- export interface BackupConfig {
297
+ export interface BackupConfig<E extends object = EnvShape> {
298
+ /**
299
+ * Unsaid: the dump runs when something is migrated and there is a Postgres
300
+ * to dump. `true`/`false` force it either way.
301
+ */
147
302
  beforeMigrate?: boolean;
303
+ /**
304
+ * Dumps kept; older ones are removed.
305
+ * @default 10
306
+ */
148
307
  keep?: number;
149
- /** Relative to the app directory. Default `backups/predeploy`. */
308
+ /**
309
+ * Relative to the app directory.
310
+ * @default 'backups/predeploy'
311
+ */
150
312
  dir?: string;
151
- /** With external infra: the `.env` key holding the database URL. Default `DATABASE_URL`. */
152
- urlKey?: string;
313
+ /**
314
+ * With external infra: the `.env` key holding the database URL.
315
+ * @default 'DATABASE_URL'
316
+ */
317
+ urlKey?: EnvKey<E>;
153
318
  /**
154
319
  * With external infra: the Postgres container to dump INSIDE (`docker exec`)
155
320
  * — the server's own pg_dump major, and no pg_dump needed on the host. The
@@ -174,6 +339,29 @@ export interface ComposeRuntime {
174
339
  env: Record<string, string>;
175
340
  /** Releases whose images are kept for a rollback without a rebuild. */
176
341
  keepImages: number;
342
+ /**
343
+ * Containers this project does not own, connected to its networks before
344
+ * `up` — creating the project first on a fresh server, so the first release
345
+ * is healthy, not the second (RFC 0007 §4.3).
346
+ * @example { 'myapp-postgres': ['data'], 'myapp-redis': ['data', 'sandbox'] }
347
+ */
348
+ attach?: Record<string, string[]>;
349
+ /** One-off commands before `up`, with this commit's images (RFC 0007 §4.4). */
350
+ jobs?: ComposeJob[];
351
+ }
352
+ export interface ComposeJob {
353
+ /** A service of the compose file; the job runs `docker compose run --rm --no-deps <service> …`. */
354
+ service: string;
355
+ /** The command; default the service's own. */
356
+ command?: string[];
357
+ /**
358
+ * Skip the job when this path (a glob, inside the service's container)
359
+ * already exists — e.g. signatures already in a volume.
360
+ * @example { exists: '/var/lib/clamav/main.c?d' }
361
+ */
362
+ once?: {
363
+ exists: string;
364
+ };
177
365
  }
178
366
  export interface ComposeImage {
179
367
  tag: string;
@@ -193,7 +381,36 @@ export interface Pm2Runtime {
193
381
  /** Ports never picked by `auto` (e.g. a port the proxy itself listens on). */
194
382
  avoid: number[];
195
383
  }
196
- export type ProxyConfig = ApacheProxy | NoProxy;
384
+ export type ProxyConfig = ApacheProxy | CaddyProxy | NoProxy;
385
+ /**
386
+ * Caddy on the host (RFC 0007 §8): `install` writes `/etc/caddy/sites/<app>.caddy`
387
+ * (imported by the main Caddyfile) and reloads after `caddy validate`; deploys
388
+ * diff it and never rewrite it. TLS is Caddy's own: one certificate per host,
389
+ * issued on first visit — for tenants, only once the app says the host is
390
+ * theirs (`onDemandTls.ask`).
391
+ */
392
+ export interface CaddyProxy {
393
+ kind: 'caddy';
394
+ /** Directory served at `/`, relative to the app directory. @default 'web/dist' */
395
+ webRoot: string;
396
+ /** Path prefix proxied to the API (stripped). @default '/api' */
397
+ apiPrefix: string;
398
+ /**
399
+ * Issue certificates on demand, after asking the app (`GET <ask>?domain=<host>`
400
+ * answering 200) — required for `tenants: 'subdomain'` and customer domains.
401
+ * Caddy has one such endpoint per server: it lives in the main Caddyfile.
402
+ * @example { ask: '/tls/allowed' }
403
+ */
404
+ onDemandTls?: {
405
+ ask: `/${string}`;
406
+ };
407
+ /** More Caddyfile appended to the site file, as is (another host of the app, special routes). */
408
+ extra?: string;
409
+ /** `false`: the site file is the app's own — checked (imported, C1), never written. */
410
+ managed?: boolean;
411
+ /** @default '/etc/caddy' */
412
+ root?: string;
413
+ }
197
414
  export interface ApacheProxy {
198
415
  kind: 'apache';
199
416
  /**
@@ -220,13 +437,37 @@ export interface NoProxy {
220
437
  kind: 'none';
221
438
  }
222
439
  export interface HealthConfig {
223
- /** Path on the API itself (without the proxy prefix). */
224
- path?: string;
440
+ /**
441
+ * Path on the API itself (without the proxy prefix).
442
+ * @default '/health'
443
+ * @example '/readyz'
444
+ */
445
+ path?: `/${string}`;
446
+ /**
447
+ * How long the release may take to answer before it is rolled back.
448
+ * @default 60
449
+ */
225
450
  timeoutSeconds?: number;
226
- /** Also check `https://<domain><apiPrefix><path>` — what users reach. */
451
+ /**
452
+ * Also check `https://<domain><apiPrefix><path>` — what users reach.
453
+ * @default true with a proxy
454
+ */
227
455
  public?: boolean;
228
456
  }
229
- export declare function defineDeploy(config: DeployConfig): DeployConfig;
457
+ /** The entries of an env record, without the keys a mapped type left `undefined`. */
458
+ export declare function definedEntries<T>(record: {
459
+ readonly [key: string]: T | undefined;
460
+ } | undefined): [string, T][];
461
+ /**
462
+ * Types `deploy.config.ts`. With the app's env, every `.env` key the config
463
+ * names is completed and checked (RFC 0007 §2.1):
464
+ *
465
+ * ```ts
466
+ * import type { env } from './src/env.js'
467
+ * export default defineDeploy<typeof env>({ … })
468
+ * ```
469
+ */
470
+ export declare function defineDeploy<E extends object = EnvShape>(config: NoInfer<DeployConfig<E>>): DeployConfig<E>;
230
471
  export declare const secret: (bytes?: number) => SecretSpec;
231
472
  export declare const ask: {
232
473
  secret: (prompt: string, options?: {
@@ -243,6 +484,16 @@ export declare const pm2: (options?: {
243
484
  port?: number | 'auto';
244
485
  avoid?: number[];
245
486
  }) => Pm2Runtime;
487
+ export declare const caddy: (options?: {
488
+ webRoot?: string;
489
+ apiPrefix?: string;
490
+ onDemandTls?: {
491
+ ask: `/${string}`;
492
+ };
493
+ extra?: string;
494
+ managed?: boolean;
495
+ root?: string;
496
+ }) => CaddyProxy;
246
497
  export declare const apache: (options?: {
247
498
  vhost?: string;
248
499
  webRoot?: string;
@@ -261,13 +512,17 @@ export declare const compose: (options: {
261
512
  };
262
513
  env?: Record<string, string>;
263
514
  keepImages?: number;
515
+ attach?: Record<string, string[]>;
516
+ jobs?: ComposeJob[];
264
517
  }) => ComposeRuntime;
265
518
  export declare const none: () => NoProxy;
266
- export declare const external: () => ExternalInfra;
519
+ export declare const external: <E extends object = EnvShape>(services?: NoInfer<Omit<ExternalInfra<E>, 'kind'>>) => ExternalInfra<E>;
520
+ /** A bucket's name, whichever form it was given in. */
521
+ export declare const bucketName: (bucket: Bucket) => string;
267
522
  export declare const MINIO_IMAGE = "minio/minio:RELEASE.2025-03-12T18-04-18Z";
268
- export interface DockerInfraOptions {
269
- postgres?: Partial<PostgresService> | false;
270
- redis?: Partial<RedisService> | false;
523
+ export interface DockerInfraOptions<E extends object = EnvShape> {
524
+ postgres?: Partial<PostgresService<E>> | false;
525
+ redis?: Partial<RedisService<E>> | false;
271
526
  minio?: Partial<MinioService> | false;
272
527
  }
273
528
  /**
@@ -276,7 +531,7 @@ export interface DockerInfraOptions {
276
531
  * already runs them (created by hand or by an older script) is adopted, not
277
532
  * duplicated.
278
533
  */
279
- export declare function dockerInfra(app: string, options?: DockerInfraOptions): DockerInfra;
534
+ export declare function dockerInfra<E extends object = EnvShape>(app: string, options?: NoInfer<DockerInfraOptions<E>>): DockerInfra<E>;
280
535
  export declare const APP_NAME: RegExp;
281
536
  export declare class DeployConfigError extends Error {
282
537
  readonly problems: string[];
@@ -285,7 +540,7 @@ export declare class DeployConfigError extends Error {
285
540
  /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
286
541
  export declare const processName: (config: DeployConfig) => string;
287
542
  export declare const vhostName: (config: DeployConfig) => string | undefined;
288
- export declare function validateConfig(config: DeployConfig): DeployConfig;
543
+ export declare function validateConfig<E extends object = EnvShape>(typed: DeployConfig<E>): DeployConfig<E>;
289
544
  /**
290
545
  * `/etc/basalt/<app>.json` — what is true of ONE server and so cannot be
291
546
  * committed: a port taken there by something else, a branch it tracks. Data
@@ -310,3 +565,4 @@ export interface ServerOverrides {
310
565
  }
311
566
  export declare function applyOverrides(config: DeployConfig, overrides: ServerOverrides): DeployConfig;
312
567
  export declare function parseOverrides(text: string, path: string): ServerOverrides;
568
+ export {};
package/dist/config.js CHANGED
@@ -5,7 +5,20 @@
5
5
  * its own module. A config can therefore be printed, diffed and validated
6
6
  * without running anything.
7
7
  */
8
+ /** The entries of an env record, without the keys a mapped type left `undefined`. */
9
+ export function definedEntries(record) {
10
+ return Object.entries(record ?? {}).filter((entry) => entry[1] !== undefined);
11
+ }
8
12
  // ── helpers used in deploy.config.ts ───────────────────────────────────────
13
+ /**
14
+ * Types `deploy.config.ts`. With the app's env, every `.env` key the config
15
+ * names is completed and checked (RFC 0007 §2.1):
16
+ *
17
+ * ```ts
18
+ * import type { env } from './src/env.js'
19
+ * export default defineDeploy<typeof env>({ … })
20
+ * ```
21
+ */
9
22
  export function defineDeploy(config) {
10
23
  return config;
11
24
  }
@@ -26,6 +39,15 @@ export const pm2 = (options = {}) => ({
26
39
  port: options.port ?? 'auto',
27
40
  avoid: options.avoid ?? [],
28
41
  });
42
+ export const caddy = (options = {}) => ({
43
+ kind: 'caddy',
44
+ webRoot: options.webRoot ?? 'web/dist',
45
+ apiPrefix: options.apiPrefix ?? '/api',
46
+ ...(options.onDemandTls ? { onDemandTls: options.onDemandTls } : {}),
47
+ ...(options.extra === undefined ? {} : { extra: options.extra }),
48
+ ...(options.managed === undefined ? {} : { managed: options.managed }),
49
+ ...(options.root === undefined ? {} : { root: options.root }),
50
+ });
29
51
  export const apache = (options = {}) => ({
30
52
  kind: 'apache',
31
53
  ...(options.managed === undefined ? {} : { managed: options.managed }),
@@ -43,9 +65,13 @@ export const compose = (options) => ({
43
65
  upstream: options.upstream,
44
66
  env: options.env ?? {},
45
67
  keepImages: options.keepImages ?? 3,
68
+ ...(options.attach ? { attach: options.attach } : {}),
69
+ ...(options.jobs ? { jobs: options.jobs } : {}),
46
70
  });
47
71
  export const none = () => ({ kind: 'none' });
48
- export const external = () => ({ kind: 'external' });
72
+ export const external = (services = {}) => ({ kind: 'external', ...services });
73
+ /** A bucket's name, whichever form it was given in. */
74
+ export const bucketName = (bucket) => (typeof bucket === 'string' ? bucket : bucket.name);
49
75
  export const MINIO_IMAGE = 'minio/minio:RELEASE.2025-03-12T18-04-18Z';
50
76
  /**
51
77
  * Dedicated containers on 127.0.0.1 for this app only. Names are fixed by the
@@ -87,7 +113,9 @@ export class DeployConfigError extends Error {
87
113
  /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
88
114
  export const processName = (config) => config.runtime.kind === 'pm2' ? (config.runtime.name ?? `${config.app}-api`) : config.app;
89
115
  export const vhostName = (config) => config.proxy?.kind === 'apache' ? (config.proxy.vhost ?? `${config.app}.conf`) : undefined;
90
- export function validateConfig(config) {
116
+ export function validateConfig(typed) {
117
+ // The checks read keys as plain strings; the app's key types are for the editor.
118
+ const config = typed;
91
119
  const problems = [];
92
120
  if (!APP_NAME.test(config.app))
93
121
  problems.push(`app "${config.app}" must match ${APP_NAME}`);
@@ -159,19 +187,43 @@ export function validateConfig(config) {
159
187
  if (config.infra?.kind === 'docker') {
160
188
  const minio = config.infra.minio;
161
189
  for (const bucket of minio?.buckets ?? []) {
162
- if (!/^[a-z0-9][a-z0-9.-]{2,62}$/.test(bucket))
163
- problems.push(`bucket "${bucket}" is not a valid S3 bucket name`);
190
+ if (!/^[a-z0-9][a-z0-9.-]{2,62}$/.test(bucketName(bucket)))
191
+ problems.push(`bucket "${bucketName(bucket)}" is not a valid S3 bucket name`);
192
+ }
193
+ }
194
+ const services = config.infra?.kind === 'external' ? config.infra : undefined;
195
+ for (const bucket of services?.minio?.buckets ?? []) {
196
+ if (!/^[a-z0-9][a-z0-9.-]{2,62}$/.test(bucketName(bucket)))
197
+ problems.push(`bucket "${bucketName(bucket)}" is not a valid S3 bucket name`);
198
+ }
199
+ for (const bucket of [...(services?.minio?.buckets ?? []), ...(config.infra?.kind === 'docker' ? config.infra.minio?.buckets ?? [] : [])]) {
200
+ if (typeof bucket === 'object' && bucket.expireDays !== undefined && (!Number.isInteger(bucket.expireDays) || bucket.expireDays < 1)) {
201
+ problems.push(`bucket "${bucket.name}": expireDays must be a whole number ≥ 1`);
164
202
  }
165
203
  }
204
+ const containers = [
205
+ services?.postgres?.container, services?.redis?.container, services?.minio?.container,
206
+ ...(config.infra?.kind === 'docker' ? [config.infra.postgres?.container, config.infra.redis?.container, config.infra.minio?.container] : []),
207
+ ];
208
+ for (const container of containers) {
209
+ if (container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(container))
210
+ problems.push(`container "${container}" is not a container name`);
211
+ }
212
+ const role = services?.postgres?.appRole ?? (config.infra?.kind === 'docker' ? config.infra.postgres?.appRole : undefined);
213
+ if (role && !/^[a-z_][a-z0-9_]{0,62}$/.test(role.name))
214
+ problems.push(`appRole "${role.name}" must be a lowercase Postgres identifier`);
166
215
  if (config.backup?.keep !== undefined && (!Number.isInteger(config.backup.keep) || config.backup.keep < 1)) {
167
216
  problems.push('backup.keep must be a whole number ≥ 1');
168
217
  }
169
218
  if (config.backup?.container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(config.backup.container)) {
170
219
  problems.push(`backup.container "${config.backup.container}" is not a container name`);
171
220
  }
221
+ if (config.proxy?.kind === 'caddy' && config.tenants === 'subdomain' && !config.proxy.onDemandTls) {
222
+ problems.push(`tenants: 'subdomain' behind caddy() needs onDemandTls: { ask: '/…' } — a certificate per tenant host, issued only for hosts the app vouches for`);
223
+ }
172
224
  if (problems.length > 0)
173
225
  throw new DeployConfigError(problems);
174
- return config;
226
+ return typed;
175
227
  }
176
228
  export function applyOverrides(config, overrides) {
177
229
  const next = { ...config };
@@ -8,7 +8,7 @@ export declare function checkSchema(ctx: DeployContext, values: Map<string, stri
8
8
  /**
9
9
  * C6 — a value written to turn something OFF that the schema reads as ON.
10
10
  * `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
11
- * "0" and "false" included. `PROXYPAY_FAKE="0"` switched the fake payment
11
+ * "0" and "false" included. `PAYCO_FAKE="0"` switched the fake payment
12
12
  * gateway on in production. Generic on purpose: it needs no list of boolean
13
13
  * keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
14
14
  * are matched too).
package/dist/env-check.js CHANGED
@@ -59,7 +59,7 @@ const FALSY = new Set(['0', 'false', 'no', 'off']);
59
59
  /**
60
60
  * C6 — a value written to turn something OFF that the schema reads as ON.
61
61
  * `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
62
- * "0" and "false" included. `PROXYPAY_FAKE="0"` switched the fake payment
62
+ * "0" and "false" included. `PAYCO_FAKE="0"` switched the fake payment
63
63
  * gateway on in production. Generic on purpose: it needs no list of boolean
64
64
  * keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
65
65
  * are matched too).
package/dist/env-step.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { basename, dirname, join, resolve } from 'node:path';
2
+ import { definedEntries } from './config.js';
2
3
  import { applyEnvChanges, envValues, formatValue, parseEnv, UnwritableValueError } from './dotenv.js';
3
4
  /** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
4
5
  export const envFile = (ctx) => resolve(ctx.dir, ctx.config.env.file ?? '.env');
@@ -33,20 +34,20 @@ export function planEnv(ctx, document, port, infra) {
33
34
  // port inside the container is the compose file's business, not the .env's.
34
35
  if (config.runtime.kind === 'pm2')
35
36
  set('PORT', String(port), 'the port the process listens on');
36
- for (const [key, value] of Object.entries(config.env.fixed ?? {}))
37
+ for (const [key, value] of definedEntries(config.env.fixed))
37
38
  set(key, value, 'fixed in deploy.config.ts');
38
- for (const [key, spec] of Object.entries(config.env.generate ?? {})) {
39
+ for (const [key, spec] of definedEntries(config.env.generate)) {
39
40
  if (!pending.get(key))
40
41
  set(key, ctx.host.randomHex(spec.bytes), 'generated');
41
42
  }
42
43
  const derived = config.env.derive?.({ app: config.app, domain: config.domain, port }) ?? {};
43
- for (const [key, value] of Object.entries(derived))
44
+ for (const [key, value] of definedEntries(derived))
44
45
  set(key, value, 'derived from the domain/port');
45
46
  for (const change of infra)
46
47
  if (change.kind === 'set')
47
48
  set(change.key, change.value, change.reason);
48
49
  const questions = [];
49
- for (const [key, question] of Object.entries(config.env.ask ?? {})) {
50
+ for (const [key, question] of definedEntries(config.env.ask)) {
50
51
  const current = pending.get(key);
51
52
  if (current === undefined || (current === '' && !question.optional))
52
53
  questions.push(key);
package/dist/host.d.ts CHANGED
@@ -60,6 +60,8 @@ export interface ExecOptions {
60
60
  stdoutFile?: string;
61
61
  /** stdout/stderr go to the terminal (long steps), nothing is captured. */
62
62
  stream?: boolean;
63
+ /** Written to the child's stdin, then closed — SQL that carries a password, never an argument. */
64
+ stdin?: string;
63
65
  }
64
66
  export interface ExecResult {
65
67
  code: number;