@basaltkit/deploy 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/init.js ADDED
@@ -0,0 +1,501 @@
1
+ import { relative } from 'node:path';
2
+ import { APP_NAME } from './config.js';
3
+ const COMPOSE_FILES = ['docker/compose.prod.yml', 'docker/compose.prod.yaml', 'compose.prod.yml', 'compose.prod.yaml', 'docker-compose.prod.yml'];
4
+ const PRISMA_CENTRAL = 'prisma.config.ts';
5
+ const PRISMA_TENANTS = 'prisma/tenants/prisma.config.ts';
6
+ const SENSITIVE = /SECRET|TOKEN|PASSWORD|PASS\b|_KEY\b|^KEY_|CREDENTIAL|_URL$|_DSN$/;
7
+ /**
8
+ * A `secret()` the app can mint for itself (signing, encryption): generated on
9
+ * the server. One a provider issues (S3, an API, SMTP) is asked instead — a
10
+ * random value would only fail at the first call.
11
+ */
12
+ const ISSUED = /S3|AWS|ACCESS_KEY|API_?KEY|TOKEN|SMTP|MAIL|OAUTH|CLIENT|STRIPE|PROXYPAY|TWILIO|SENDGRID|PASSWORD/;
13
+ // ── detection ──────────────────────────────────────────────────────────────
14
+ export async function detectProject(host, dir, options = {}) {
15
+ const pkg = parseJson(await host.readFile(`${dir}/package.json`));
16
+ const scripts = pkg?.scripts ?? {};
17
+ const app = appName(pkg?.name ?? dir.split('/').pop() ?? 'app');
18
+ const prisma = [];
19
+ if (await host.stat(`${dir}/${PRISMA_CENTRAL}`))
20
+ prisma.push(PRISMA_CENTRAL);
21
+ const tenants = Boolean(await host.stat(`${dir}/${PRISMA_TENANTS}`));
22
+ if (tenants)
23
+ prisma.push(PRISMA_TENANTS);
24
+ const dbDeploy = scripts['db:deploy'];
25
+ const migrateScript = dbDeploy !== undefined && dbDeploy.trim() !== 'prisma migrate deploy' ? 'db:deploy' : undefined;
26
+ const buildScript = scripts['build'] !== undefined && /\bnode\b[^&|;]*\bdist\//.test(scripts['start'] ?? '') ? 'build' : undefined;
27
+ const web = (await host.stat(`${dir}/web/package.json`)) ? 'web' : undefined;
28
+ const envSource = await host.readFile(`${dir}/src/env.ts`);
29
+ const env = envSource === undefined ? undefined : parseEnvSchema(envSource);
30
+ let compose;
31
+ for (const file of COMPOSE_FILES) {
32
+ if (!(await host.stat(`${dir}/${file}`)))
33
+ continue;
34
+ compose = await detectCompose(host, dir, file, app);
35
+ if (compose)
36
+ break;
37
+ }
38
+ const server = options.server === undefined ? undefined : await detectServer(host, options.server);
39
+ const grep = await host.exec('grep', ['-rlE', `['"\`]/readyz['"\`]`, 'src'], { cwd: dir });
40
+ return {
41
+ health: grep.code === 0 && grep.stdout.trim() !== '' ? '/readyz' : '/health',
42
+ app,
43
+ env: env && { schema: 'src/env.ts', ...env },
44
+ prisma,
45
+ tenants,
46
+ migrateScript,
47
+ buildScript,
48
+ web,
49
+ compose,
50
+ server,
51
+ };
52
+ }
53
+ /** `@acme/My App` → `my-app`, within C4's `[a-z][a-z0-9-]{1,30}`. */
54
+ export function appName(name) {
55
+ const base = slugOf(name);
56
+ return APP_NAME.test(base) ? base : 'app';
57
+ }
58
+ /** Lowercase, hyphens for the rest, starting with a letter, no trailing hyphen, at most 31 characters — trimmed in linear time (an anchored `-+$` regex backtracks on long runs of '-'). */
59
+ function slugOf(name) {
60
+ const base = name.replace(/^@[^/]+\//, '').toLowerCase().replace(/[^a-z0-9]+/g, '-');
61
+ let start = 0;
62
+ while (start < base.length && !(base[start] >= 'a' && base[start] <= 'z'))
63
+ start++;
64
+ let end = Math.min(base.length, start + 31);
65
+ while (end > start && base[end - 1] === '-')
66
+ end--;
67
+ return base.slice(start, end);
68
+ }
69
+ /** The keys of the first `defineEnv({ … })` in `source`, read as text. */
70
+ export function parseEnvSchema(source) {
71
+ const call = /export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*defineEnv\s*\(\s*\{/.exec(source);
72
+ if (!call)
73
+ return undefined;
74
+ const body = objectBody(source, call.index + call[0].length - 1);
75
+ const keys = [];
76
+ // Top-level entries only: depth 0 inside the object literal.
77
+ let depth = 0;
78
+ let start = 0;
79
+ const entries = [];
80
+ for (let i = 0; i < body.length; i++) {
81
+ const c = body[i];
82
+ if (c === '"' || c === "'" || c === '`') {
83
+ i = skipString(body, i);
84
+ continue;
85
+ }
86
+ if (c === '/' && body[i + 1] === '/') {
87
+ const end = body.indexOf('\n', i);
88
+ i = end === -1 ? body.length : end;
89
+ continue;
90
+ }
91
+ if (c === '/' && body[i + 1] === '*') {
92
+ const end = body.indexOf('*/', i + 2);
93
+ i = end === -1 ? body.length : end + 1;
94
+ continue;
95
+ }
96
+ if (c === '(' || c === '[' || c === '{')
97
+ depth++;
98
+ else if (c === ')' || c === ']' || c === '}')
99
+ depth--;
100
+ else if (c === ',' && depth === 0) {
101
+ entries.push(body.slice(start, i));
102
+ start = i + 1;
103
+ }
104
+ }
105
+ entries.push(body.slice(start));
106
+ for (const raw of entries) {
107
+ const entry = raw.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g, '').trim();
108
+ const match = /^([A-Z][A-Z0-9_]*)\s*:\s*([\s\S]+)$/.exec(entry);
109
+ if (!match)
110
+ continue;
111
+ const expression = match[2];
112
+ keys.push({
113
+ name: match[1],
114
+ secret: /\bsecret\s*\(/.test(expression),
115
+ optional: /\.(default|optional|catch)\s*\(/.test(expression),
116
+ });
117
+ }
118
+ return { exportName: call[1], keys };
119
+ }
120
+ function objectBody(source, open) {
121
+ let depth = 0;
122
+ for (let i = open; i < source.length; i++) {
123
+ const c = source[i];
124
+ if (c === '"' || c === "'" || c === '`') {
125
+ i = skipString(source, i);
126
+ continue;
127
+ }
128
+ if (c === '/' && source[i + 1] === '/') {
129
+ const end = source.indexOf('\n', i);
130
+ i = end === -1 ? source.length : end;
131
+ continue;
132
+ }
133
+ if (c === '{')
134
+ depth++;
135
+ else if (c === '}') {
136
+ depth--;
137
+ if (depth === 0)
138
+ return source.slice(open + 1, i);
139
+ }
140
+ }
141
+ return source.slice(open + 1);
142
+ }
143
+ function skipString(text, at) {
144
+ const quote = text[at];
145
+ for (let i = at + 1; i < text.length; i++) {
146
+ if (text[i] === '\\') {
147
+ i++;
148
+ continue;
149
+ }
150
+ if (text[i] === quote)
151
+ return i;
152
+ }
153
+ return text.length;
154
+ }
155
+ /**
156
+ * The compose file as `docker compose config` reads it, interpolation off. It
157
+ * is the app's runtime only when it runs images of this app — services whose
158
+ * `image:` is a variable (`${APP_IMAGE}`), which the deploy sets to
159
+ * `<tag>:<sha>`; a file of infra only (postgres:16, redis) is not. Each
160
+ * variable is one image: its Dockerfile from `build:`, else by convention
161
+ * (`docker/<name>/Dockerfile`, `Dockerfile`). The service that publishes on
162
+ * 127.0.0.1 is the upstream.
163
+ */
164
+ async function detectCompose(host, dir, file, app) {
165
+ const result = await host.exec('docker', ['compose', '-f', file, 'config', '--no-interpolate', '--format', 'json'], { cwd: dir });
166
+ if (result.code !== 0) {
167
+ throw new Error(`${file} found, but docker compose cannot read it: ${result.stderr.trim().split('\n')[0] ?? ''} — init reads the compose file with docker compose`);
168
+ }
169
+ const config = parseJson(result.stdout);
170
+ const services = Object.entries(config?.services ?? {});
171
+ const variables = new Map();
172
+ for (const [service, spec] of services) {
173
+ const variable = /^\$\{([A-Za-z_][A-Za-z0-9_]*)/.exec(spec.image ?? '')?.[1];
174
+ if (!variable)
175
+ continue;
176
+ const seen = variables.get(variable) ?? { services: [], build: undefined };
177
+ seen.services.push(service);
178
+ seen.build ??= spec.build ?? undefined;
179
+ variables.set(variable, seen);
180
+ }
181
+ if (variables.size === 0)
182
+ return undefined;
183
+ const dockerDirs = (await host.list(`${dir}/docker`).catch(() => [])).filter((d) => !d.includes('.'));
184
+ // ACME_IMAGE, ACME_SCANNER_IMAGE → the shared ACME_ is the app's prefix,
185
+ // whatever the package is called; what is left names the image.
186
+ const stems = [...variables.keys()].map((v) => v.replace(/_IMAGE$/, '').split('_'));
187
+ let shared = 0;
188
+ if (stems.length === 1)
189
+ shared = stems[0].length;
190
+ else
191
+ while (stems.every((t) => t[shared] !== undefined && t[shared] === stems[0][shared]))
192
+ shared++;
193
+ const images = [];
194
+ const unresolved = [];
195
+ for (const [variable, { services: users, build }] of variables) {
196
+ const stem = variable.replace(/_IMAGE$/, '').split('_').slice(shared).join('-').toLowerCase();
197
+ const tag = stem ? `${app}-${stem}` : app;
198
+ let dockerfile;
199
+ let context;
200
+ if (build) {
201
+ context = relative(dir, build.context ?? dir) || '.';
202
+ dockerfile = context === '.' ? build.dockerfile ?? 'Dockerfile' : `${context}/${build.dockerfile ?? 'Dockerfile'}`;
203
+ }
204
+ else {
205
+ const names = stem ? [stem, ...users] : ['app', 'api', ...users];
206
+ const near = (d) => names.some((n) => d === n || (n.length >= 4 && d.startsWith(n.slice(0, 4))));
207
+ const found = [...dockerDirs.filter((d) => names.includes(d)), ...dockerDirs.filter(near)];
208
+ for (const d of found)
209
+ if (!dockerfile && (await host.stat(`${dir}/docker/${d}/Dockerfile`)))
210
+ dockerfile = `docker/${d}/Dockerfile`;
211
+ if (!dockerfile && !stem && (await host.stat(`${dir}/Dockerfile`)))
212
+ dockerfile = 'Dockerfile';
213
+ if (dockerfile) {
214
+ // A Dockerfile that copies the app's own files builds from the root;
215
+ // one that copies only what sits next to it, from its directory.
216
+ const text = (await host.readFile(`${dir}/${dockerfile}`)) ?? '';
217
+ const own = dockerfile.replace(/\/?Dockerfile$/, '') || '.';
218
+ context = /^\s*COPY\s+(?:--\S+\s+)*(?:package\.json|pnpm-lock\.yaml|src\b|\.\s)/m.test(text) ? '.' : own;
219
+ }
220
+ }
221
+ if (!dockerfile || !context) {
222
+ unresolved.push(`${variable} (${users.join(', ')})`);
223
+ continue;
224
+ }
225
+ images.push({ tag, dockerfile, context, env: variable });
226
+ }
227
+ if (unresolved.length) {
228
+ throw new Error(`${file}: no Dockerfile found for ${unresolved.join(', ')} — add build: { context, dockerfile } to the service, or put it in docker/<name>/Dockerfile`);
229
+ }
230
+ // The app's own image first: it is the one named after the app.
231
+ images.sort((a, b) => (a.tag === app ? -1 : b.tag === app ? 1 : 0));
232
+ const env = {};
233
+ let upstream;
234
+ for (const [service, spec] of services) {
235
+ for (const port of spec.ports ?? []) {
236
+ if (upstream)
237
+ break;
238
+ let published;
239
+ if (typeof port === 'string') {
240
+ const short = /^127\.0\.0\.1:(.+):\d+(?:\/tcp)?$/.exec(port);
241
+ if (!short)
242
+ continue;
243
+ published = short[1];
244
+ }
245
+ else {
246
+ if (port.host_ip !== '127.0.0.1')
247
+ continue;
248
+ published = String(port.published ?? '');
249
+ }
250
+ const interpolated = /^\$\{([A-Za-z_][A-Za-z0-9_]*):?-(\d+)\}$/.exec(published);
251
+ const number = Number(interpolated ? interpolated[2] : published);
252
+ if (!Number.isInteger(number) || number <= 0)
253
+ continue;
254
+ upstream = { service, port: number };
255
+ if (interpolated)
256
+ env[interpolated[1]] = interpolated[2];
257
+ }
258
+ }
259
+ return { file, images, upstream, env };
260
+ }
261
+ async function detectServer(host, domain) {
262
+ const vhosts = [];
263
+ for (const name of (await host.list('/etc/apache2/sites-available').catch(() => [])).sort()) {
264
+ if (!name.endsWith('.conf'))
265
+ continue;
266
+ const text = await host.readFile(`/etc/apache2/sites-available/${name}`);
267
+ const served = [...(text ?? '').matchAll(/^\s*Server(?:Name|Alias)\s+(.+)$/gim)].flatMap((m) => m[1].trim().split(/\s+/));
268
+ if (served.some((h) => h === domain || h === `*.${domain}`))
269
+ vhosts.push(name);
270
+ }
271
+ const ss = await host.exec('ss', ['-ltnH'], {});
272
+ const busyPorts = [...new Set([...ss.stdout.matchAll(/:(\d+)\s/g)].map((m) => Number(m[1])).filter((p) => p >= 3000 && p < 3100))].sort((a, b) => a - b);
273
+ return { vhosts, busyPorts };
274
+ }
275
+ function parseJson(text) {
276
+ if (text === undefined)
277
+ return undefined;
278
+ try {
279
+ return JSON.parse(text);
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ }
285
+ // ── the file ───────────────────────────────────────────────────────────────
286
+ /** Keys the deploy writes itself, never generated or asked. */
287
+ function managedKeys(facts) {
288
+ const keys = new Set(['NODE_ENV']);
289
+ if (!facts.compose) {
290
+ for (const key of ['PORT', 'HOST', 'DATABASE_URL', 'REDIS_URL'])
291
+ keys.add(key);
292
+ if (hasMinio(facts))
293
+ for (const key of MINIO_KEYS)
294
+ keys.add(key);
295
+ }
296
+ return keys;
297
+ }
298
+ /** What `dockerInfra`'s MinIO writes (`minio.keys`); all three in the schema → a dedicated MinIO. */
299
+ const MINIO_KEYS = ['S3_ENDPOINT', 'S3_ACCESS_KEY', 'S3_SECRET_KEY'];
300
+ const hasMinio = (facts) => MINIO_KEYS.every((k) => facts.env?.keys.some((e) => e.name === k));
301
+ export function renderConfig(facts, answers) {
302
+ const helpers = new Set(['defineDeploy']);
303
+ const lines = [];
304
+ const typed = facts.env !== undefined;
305
+ const keys = facts.env?.keys ?? [];
306
+ const has = (name) => keys.some((k) => k.name === name);
307
+ const managed = managedKeys(facts);
308
+ const fixed = [];
309
+ if (has('NODE_ENV') || !typed)
310
+ fixed.push(`NODE_ENV: 'production'`);
311
+ if (!facts.compose && has('HOST'))
312
+ fixed.push(`HOST: '127.0.0.1'`);
313
+ const minted = (k) => k.secret && !ISSUED.test(k.name);
314
+ const generate = keys.filter((k) => minted(k) && !managed.has(k.name)).map((k) => `${k.name}: secret(32)`);
315
+ const ask = keys.filter((k) => !minted(k) && (k.secret || !k.optional) && !managed.has(k.name))
316
+ .map((k) => `${k.name}: ask.${k.secret || SENSITIVE.test(k.name) ? 'secret' : 'text'}(${quote(label(k.name, facts.app))})`);
317
+ if (generate.length)
318
+ helpers.add('secret');
319
+ if (ask.length)
320
+ helpers.add('ask');
321
+ lines.push(` app: ${quote(facts.app)},`);
322
+ lines.push(` domain: ${quote(answers.domain)},`);
323
+ if (answers.tenants === 'subdomain')
324
+ lines.push(` tenants: 'subdomain',`);
325
+ if (answers.branch !== 'main')
326
+ lines.push(` branch: ${quote(answers.branch)},`);
327
+ lines.push('');
328
+ lines.push(' env: {');
329
+ if (facts.env)
330
+ lines.push(` schema: ${quote(facts.env.schema)},`);
331
+ lines.push(` fixed: { ${fixed.join(', ')} },`);
332
+ if (generate.length)
333
+ lines.push(...block('generate', generate));
334
+ if (ask.length)
335
+ lines.push(...block('ask', ask));
336
+ lines.push(' },');
337
+ if (!facts.compose && (has('DATABASE_URL') || has('REDIS_URL') || hasMinio(facts) || !typed)) {
338
+ helpers.add('dockerInfra');
339
+ const options = [];
340
+ if (typed && !has('DATABASE_URL'))
341
+ options.push('postgres: false');
342
+ if (typed && !has('REDIS_URL'))
343
+ options.push('redis: false');
344
+ if (hasMinio(facts))
345
+ options.push('minio: {}');
346
+ lines.push(` infra: dockerInfra(${quote(facts.app)}${options.length ? `, { ${options.join(', ')} }` : ''}),`);
347
+ }
348
+ const build = [];
349
+ if (facts.prisma.length)
350
+ build.push(`prisma: [${facts.prisma.map(quote).join(', ')}]`);
351
+ if (facts.buildScript && !facts.compose)
352
+ build.push(`script: ${quote(facts.buildScript)}`);
353
+ if (facts.web)
354
+ build.push(`web: ${quote(facts.web)}`);
355
+ if (build.length)
356
+ lines.push(` build: { ${build.join(', ')} },`);
357
+ if (facts.migrateScript)
358
+ lines.push(` migrate: { command: ['pnpm', ${quote(facts.migrateScript)}] },`);
359
+ else if (facts.prisma.length)
360
+ lines.push(` migrate: { central: true${facts.tenants ? ', tenants: true' : ''} },`);
361
+ lines.push('');
362
+ if (facts.compose) {
363
+ helpers.add('compose');
364
+ const c = facts.compose;
365
+ if (!c.upstream)
366
+ throw new Error(`${c.file}: no service publishes a port on 127.0.0.1 — the proxy needs one (ports: ["127.0.0.1:3001:3000"])`);
367
+ if (!c.images.length)
368
+ throw new Error(`${c.file}: no service is built here with image: \${VAR} — the deploy tags each image per commit through that variable`);
369
+ lines.push(' runtime: compose({');
370
+ lines.push(` file: ${quote(c.file)},`);
371
+ lines.push(' images: [');
372
+ for (const i of c.images) {
373
+ lines.push(` { tag: ${quote(i.tag)}, dockerfile: ${quote(i.dockerfile)}${i.context === '.' ? '' : `, context: ${quote(i.context)}`}, env: ${quote(i.env)} },`);
374
+ }
375
+ lines.push(' ],');
376
+ lines.push(` upstream: { service: ${quote(c.upstream.service)}, port: ${c.upstream.port} },`);
377
+ if (Object.keys(c.env).length)
378
+ lines.push(` env: { ${Object.entries(c.env).map(([k, v]) => `${k}: ${quote(v)}`).join(', ')} },`);
379
+ lines.push(' }),');
380
+ }
381
+ else {
382
+ helpers.add('pm2');
383
+ const avoid = facts.server?.busyPorts ?? [];
384
+ lines.push(` runtime: pm2(${avoid.length ? `{ avoid: [${avoid.join(', ')}] }` : ''}),${avoid.length ? ' // ports already taken on this server' : ''}`);
385
+ }
386
+ if (answers.proxy === 'caddy') {
387
+ helpers.add('caddy');
388
+ // One certificate per tenant host, issued only for hosts the app vouches for.
389
+ lines.push(answers.tenants === 'subdomain'
390
+ ? ` proxy: caddy({ onDemandTls: { ask: '/tls/allowed' } }), // GET /tls/allowed?domain=<host> must answer 200 for the app's hosts only`
391
+ : ' proxy: caddy(),');
392
+ }
393
+ if (answers.proxy === 'apache') {
394
+ helpers.add('apache');
395
+ const vhosts = facts.server?.vhosts ?? [];
396
+ if (vhosts.length)
397
+ lines.push(` proxy: apache({ managed: false, vhosts: [${vhosts.map(quote).join(', ')}] }), // the vhosts this server already has`);
398
+ else
399
+ lines.push(' proxy: apache(),');
400
+ }
401
+ lines.push(` health: { path: ${quote(facts.health)} },`);
402
+ const header = [
403
+ '/**',
404
+ ` * Deploy of ${facts.app} with @basaltkit/deploy — written by \`basalt-deploy init\`.`,
405
+ ' * Holds no secrets. What is true of one server only goes in /etc/basalt/<app>.json.',
406
+ ' *',
407
+ ' * node node_modules/@basaltkit/deploy/dist/bin.js check # this file, without a server',
408
+ ' * node node_modules/@basaltkit/deploy/dist/bin.js plan # on the server: what run would do',
409
+ ' * node node_modules/@basaltkit/deploy/dist/bin.js run',
410
+ ' */',
411
+ ];
412
+ const order = ['apache', 'ask', 'caddy', 'compose', 'defineDeploy', 'dockerInfra', 'pm2', 'secret'];
413
+ const imports = order.filter((h) => helpers.has(h));
414
+ return [
415
+ ...header,
416
+ ...(facts.env ? [`import type { ${facts.env.exportName} } from './${facts.env.schema.replace(/\.ts$/, '.js')}'`] : []),
417
+ `import { ${imports.join(', ')} } from '@basaltkit/deploy'`,
418
+ '',
419
+ `export default defineDeploy${facts.env ? `<typeof ${facts.env.exportName}>` : ''}({`,
420
+ ...lines,
421
+ '})',
422
+ '',
423
+ ].join('\n');
424
+ }
425
+ function block(name, entries) {
426
+ if (entries.join(', ').length < 70)
427
+ return [` ${name}: { ${entries.join(', ')} },`];
428
+ return [` ${name}: {`, ...entries.map((e) => ` ${e},`), ' },'];
429
+ }
430
+ /** `MUKANDA_SMTP_URL` → `SMTP URL`: the prompt the operator sees once. */
431
+ function label(key, app) {
432
+ const prefix = `${app.toUpperCase().replace(/-/g, '_')}_`;
433
+ return (key.startsWith(prefix) ? key.slice(prefix.length) : key).replace(/_/g, ' ');
434
+ }
435
+ function quote(value) {
436
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
437
+ }
438
+ // ── the command ────────────────────────────────────────────────────────────
439
+ export async function init(host, dir, flags, switches) {
440
+ const file = flags.get('config') ?? 'deploy.config.ts';
441
+ const path = `${dir}/${file}`;
442
+ if ((await host.stat(path)) && !switches.has('force')) {
443
+ host.out.error(`${file} already exists — init never overwrites it (--force to replace it)`);
444
+ return 1;
445
+ }
446
+ const answer = async (key, question, fallback) => {
447
+ const given = flags.get(key);
448
+ if (given !== undefined)
449
+ return given;
450
+ if (!host.interactive())
451
+ return fallback;
452
+ const typed = (await host.prompt(`${question}${fallback ? ` [${fallback}]` : ''}: `, { secret: false }))?.trim();
453
+ return typed || fallback;
454
+ };
455
+ const domain = await answer('domain', 'Domain the app answers on (e.g. acme.example.ao)');
456
+ if (!domain || !/^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)) {
457
+ host.out.error(`--domain=<host> is required${domain ? `: "${domain}" is not a host name` : ''}`);
458
+ return 1;
459
+ }
460
+ const tenants = await answer('tenants', 'Tenants on subdomains (<id>.domain)? subdomain | none', 'none');
461
+ if (tenants !== 'subdomain' && tenants !== 'none') {
462
+ host.out.error('--tenants is subdomain or none');
463
+ return 1;
464
+ }
465
+ const branch = (await answer('branch', 'Branch deployed', 'main')) ?? 'main';
466
+ const proxy = (await answer('proxy', 'Proxy on this server: apache | caddy | none', 'apache')) ?? 'apache';
467
+ if (proxy !== 'apache' && proxy !== 'caddy' && proxy !== 'none') {
468
+ host.out.error('--proxy is apache, caddy or none');
469
+ return 1;
470
+ }
471
+ host.out.step('init');
472
+ const facts = await detectProject(host, dir, { server: switches.has('server') ? domain : undefined });
473
+ for (const line of describeFacts(facts))
474
+ host.out.info(line);
475
+ const source = renderConfig(facts, { domain, tenants, branch, proxy });
476
+ await host.writeFile(path, source, 0o644);
477
+ host.out.ok(`${file} written — commit it`);
478
+ return 0;
479
+ }
480
+ export function describeFacts(facts) {
481
+ const lines = [`app: ${facts.app}`];
482
+ if (facts.env) {
483
+ const secrets = facts.env.keys.filter((k) => k.secret).length;
484
+ lines.push(`env: ${facts.env.schema} — ${facts.env.keys.length} key(s), ${secrets} secret(s)`);
485
+ }
486
+ else
487
+ lines.push('env: no src/env.ts — the config is not typed by the app\'s env');
488
+ if (facts.prisma.length)
489
+ lines.push(`prisma: ${facts.prisma.join(', ')}${facts.tenants ? ' (schema per tenant)' : ''}`);
490
+ if (facts.migrateScript)
491
+ lines.push(`migrate: pnpm ${facts.migrateScript}`);
492
+ if (facts.web)
493
+ lines.push(`web: ${facts.web}/`);
494
+ if (facts.compose)
495
+ lines.push(`runtime: compose (${facts.compose.file}: ${facts.compose.images.map((i) => i.tag).join(', ')})`);
496
+ else
497
+ lines.push('runtime: pm2 (no production compose file)');
498
+ if (facts.server)
499
+ lines.push(`server: ${facts.server.vhosts.length ? `vhosts ${facts.server.vhosts.join(', ')}` : 'no vhost for this domain'}; ports taken: ${facts.server.busyPorts.join(', ') || 'none'}`);
500
+ return lines;
501
+ }