@otwdesign/cli 0.0.0-stage → 1.0.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/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /* The CLI's pieces, for scripts and for create-otw-cms. */
2
+ export {
3
+ generate,
4
+ managedFiles,
5
+ MARKER,
6
+ parseConfig,
7
+ readConfig,
8
+ siteModulePath,
9
+ } from './generate.ts'
10
+ export type { CmsConfig, FileStatus, GenerateResult, ManagedFile, SiteLayout } from './generate.ts'
11
+ export { migrate, type MigrateOptions, type MigrateResult } from './migrate.ts'
12
+ export { loadEnv, loadSite } from './site.ts'
13
+ export {
14
+ CORE_PACKAGES,
15
+ detectPackageManager,
16
+ nextSpec,
17
+ planSite,
18
+ planUpdate,
19
+ readSitePackages,
20
+ npmView,
21
+ resolveTargets,
22
+ updateCommitMessage,
23
+ writeChanges,
24
+ type Packument,
25
+ type PluginReport,
26
+ type SitePackages,
27
+ type Unreachable,
28
+ type UpdatePlan,
29
+ type UpdateScope,
30
+ } from './update.ts'
package/src/main.ts ADDED
@@ -0,0 +1,219 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { join, relative, resolve } from 'node:path'
3
+ import { parseArgs, promisify } from 'node:util'
4
+ import { consoleLogger, DEFAULT_BRAND, type Brand } from '@otwdesign/core'
5
+ import { migrationModeFromEnv } from '@otwdesign/next/server'
6
+ import { displayPath, generate, readConfig } from './generate.ts'
7
+ import { migrate } from './migrate.ts'
8
+ import { serve } from './serve/index.ts'
9
+ import { loadEnv, loadSite } from './site.ts'
10
+ import {
11
+ commitUpdate,
12
+ detectPackageManager,
13
+ install,
14
+ planSite,
15
+ updateCommitMessage,
16
+ writeChanges,
17
+ type UpdatePlan,
18
+ } from './update.ts'
19
+
20
+ const USAGE = `Usage: cms <command> [options]
21
+
22
+ Commands:
23
+ generate Write the site module and the CMS's route files from cms.config.json
24
+ migrate Back up the database, then run pending migrations
25
+ --dry-run list them and change nothing
26
+ --no-backup when your host takes backups (most managed Postgres does)
27
+ serve Run the site from built releases, with updates from the admin (instead of next start)
28
+ --port <n> public port (default: PORT, or 3000)
29
+ --hostname <h> address to listen on (default: 0.0.0.0)
30
+ --no-backup with Postgres, when your host takes backups
31
+ update [packages...]
32
+ Update core and plugins to the newest compatible versions; name plugins (or
33
+ "core") to update only those
34
+ --check report what would change, and change nothing
35
+ --plugins-only leave core where it is
36
+ --major allow a new major version of core
37
+ --force update even if a plugin would be switched off
38
+ --commit put the update on a new git branch, for hosts that build from git
39
+
40
+ Options:
41
+ --root <dir> The site's directory (default: the current directory)`
42
+
43
+ const { positionals, values } = parseArgs({
44
+ allowPositionals: true,
45
+ options: {
46
+ root: { type: 'string', default: '.' },
47
+ help: { type: 'boolean', short: 'h' },
48
+ 'dry-run': { type: 'boolean', default: false },
49
+ 'no-backup': { type: 'boolean', default: false },
50
+ check: { type: 'boolean', default: false },
51
+ major: { type: 'boolean', default: false },
52
+ 'plugins-only': { type: 'boolean', default: false },
53
+ force: { type: 'boolean', default: false },
54
+ commit: { type: 'boolean', default: false },
55
+ port: { type: 'string' },
56
+ hostname: { type: 'string', default: '0.0.0.0' },
57
+ },
58
+ })
59
+
60
+ const run = promisify(execFile)
61
+
62
+ async function runGenerate(root: string): Promise<void> {
63
+ const { files } = await generate({ root })
64
+ for (const { path, status } of files) {
65
+ if (status === 'written') console.log(`cms: wrote ${displayPath(root, path)}`)
66
+ if (status === 'removed') console.log(`cms: removed ${displayPath(root, path)}`)
67
+ if (status === 'kept') {
68
+ console.warn(
69
+ `cms: kept ${displayPath(root, path)}: it has no "@generated" line, so it is yours. Compare it with a new site from create-otw-cms after updating.`,
70
+ )
71
+ }
72
+ }
73
+ if (files.every(({ status }) => status === 'unchanged' || status === 'own')) {
74
+ console.log('cms: up to date')
75
+ }
76
+ }
77
+
78
+ async function runMigrate(root: string): Promise<void> {
79
+ const env = loadEnv(root)
80
+ const site = await loadSite(root)
81
+ const result = await migrate({
82
+ root,
83
+ env,
84
+ site,
85
+ logger: { ...consoleLogger, info: () => {} },
86
+ dryRun: values['dry-run'],
87
+ backup: !values['no-backup'],
88
+ })
89
+ if ('pending' in result) {
90
+ console.log(
91
+ result.pending.length === 0
92
+ ? 'cms: no pending migrations'
93
+ : `cms: pending migrations:\n${result.pending.map((key) => ` ${key}`).join('\n')}`,
94
+ )
95
+ return
96
+ }
97
+ if (result.backup) {
98
+ console.log(
99
+ `cms: backed up the database to ${displayPath(root, relative(root, result.backup))}`,
100
+ )
101
+ }
102
+ console.log(
103
+ result.applied.length === 0
104
+ ? 'cms: the database is up to date'
105
+ : `cms: applied ${result.applied.length} migration(s):\n${result.applied.map((key) => ` ${key}`).join('\n')}`,
106
+ )
107
+ }
108
+
109
+ const COMPATIBILITY: Record<UpdatePlan['plugins'][number]['compatible'], string> = {
110
+ yes: 'works with this core',
111
+ unknown: 'compatibility unknown: it does not say which core it supports',
112
+ no: 'does not support this core',
113
+ }
114
+
115
+ function report(plan: UpdatePlan, brand: Brand): void {
116
+ console.log(
117
+ plan.core
118
+ ? `${brand.name} ${plan.core.from} → ${plan.core.to}`
119
+ : `${brand.name} stays where it is`,
120
+ )
121
+ if (plan.plugins.length > 0) {
122
+ console.log('Plugins:')
123
+ for (const plugin of plan.plugins) {
124
+ const versions = plugin.to ? `${plugin.from} → ${plugin.to}` : plugin.from
125
+ console.log(` ${plugin.name} ${versions}: ${COMPATIBILITY[plugin.compatible]}`)
126
+ if (plugin.note) console.log(` ${plugin.latest} is out, but ${plugin.note}`)
127
+ }
128
+ }
129
+ if (plan.linked.length > 0) {
130
+ console.log(`Linked, so updated with your workspace instead: ${plan.linked.join(', ')}`)
131
+ }
132
+ for (const warning of plan.warnings) console.warn(`cms: ${warning}`)
133
+ for (const blocker of plan.blockers) console.warn(`cms: ${blocker}`)
134
+ }
135
+
136
+ /** Runs the newly installed CLI, so its route files and migrations are the new version's. */
137
+ async function runInstalledCli(root: string, args: string[]): Promise<void> {
138
+ const bin = join(root, 'node_modules', '@otwdesign', 'cli', 'bin', 'cms.js')
139
+ const { stdout } = await run(process.execPath, [bin, ...args, '--root', root], { cwd: root })
140
+ process.stdout.write(stdout)
141
+ }
142
+
143
+ async function runUpdate(root: string, names: readonly string[]): Promise<void> {
144
+ const plan = await planSite(root, {
145
+ major: values.major,
146
+ pluginsOnly: values['plugins-only'],
147
+ packages: names,
148
+ })
149
+ const brand = (await readConfig(join(root, 'cms.config.json'))).brand ?? DEFAULT_BRAND
150
+ report(plan, brand)
151
+ if (values.check) return
152
+ if (plan.changes.length === 0) {
153
+ console.log('cms: nothing to update')
154
+ return
155
+ }
156
+ if (plan.blockers.length > 0 && !values.force) {
157
+ throw new Error('Not updating; see above. Run with --force to update anyway.')
158
+ }
159
+ if (values.commit) {
160
+ const { stdout } = await run('git', ['status', '--porcelain'], { cwd: root })
161
+ if (stdout.trim())
162
+ throw new Error('Commit or stash your changes first, so the update is a commit of its own')
163
+ }
164
+
165
+ await writeChanges(root, plan.changes)
166
+ const manager = await detectPackageManager(root)
167
+ console.log(`cms: installing with ${manager}`)
168
+ await install(root, manager)
169
+ await runInstalledCli(root, ['generate'])
170
+
171
+ const target = plan.core?.to
172
+ if (values.commit) {
173
+ const branch = `cms-update-${target ?? 'plugins'}-${Date.now().toString(36)}`
174
+ await commitUpdate(root, branch, updateCommitMessage(brand, target))
175
+ console.log(
176
+ `cms: committed on ${branch}. Push it and open a pull request; your host builds it, and runs \`cms migrate\` if you deploy with CMS_MIGRATIONS=deploy.`,
177
+ )
178
+ return
179
+ }
180
+ const env = loadEnv(root)
181
+ console.log(
182
+ migrationModeFromEnv(env) === 'deploy'
183
+ ? `cms: updated. Run \`cms migrate\` when you deploy, then \`${manager} run build\` and restart.`
184
+ : `cms: updated. Stop the site, run \`cms migrate\` (it backs up first), then \`${manager} run build\` and start it again. Without cms migrate, migrations run when the site starts, with no backup.`,
185
+ )
186
+ }
187
+
188
+ async function main(): Promise<void> {
189
+ const [command] = positionals
190
+ if (values.help || !command) {
191
+ console.log(USAGE)
192
+ return
193
+ }
194
+ const root = resolve(values.root)
195
+ // Relative paths in the environment (CMS_DATA_DIR) mean the site's directory, as under Next.js.
196
+ process.chdir(root)
197
+ if (command === 'generate') return runGenerate(root)
198
+ if (command === 'migrate') return runMigrate(root)
199
+ if (command === 'update') return runUpdate(root, positionals.slice(1))
200
+ if (command === 'serve') {
201
+ const port = Number(values.port ?? process.env.PORT ?? 3000)
202
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
203
+ throw new Error('--port must be a port number')
204
+ return serve({
205
+ root,
206
+ port,
207
+ hostname: values.hostname,
208
+ backup: !values['no-backup'],
209
+ // For tests; twelve hours otherwise, as WordPress checks twice a day.
210
+ checkEveryMs: Number(process.env.CMS_UPDATE_CHECK_EVERY_MS) || undefined,
211
+ })
212
+ }
213
+ throw new Error(`Unknown command "${command}"\n\n${USAGE}`)
214
+ }
215
+
216
+ main().catch((error: unknown) => {
217
+ console.error(`cms: ${error instanceof Error ? error.message : String(error)}`)
218
+ process.exit(1)
219
+ })
package/src/migrate.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { access, cp, mkdir } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+ import { migrateSite, type Env } from '@otwdesign/core'
6
+ import type { Site } from '@otwdesign/next'
7
+ import { activePluginsFromEnv, dataDir, openDatabase } from '@otwdesign/next/server'
8
+ import type { Logger } from '@otwdesign/sdk'
9
+
10
+ const run = promisify(execFile)
11
+
12
+ export interface MigrateOptions {
13
+ /** The site's directory. Postgres backups go in its `.data/backups`. */
14
+ root: string
15
+ env: Env
16
+ site: Site
17
+ logger: Logger
18
+ /** List pending migrations and change nothing. */
19
+ dryRun?: boolean
20
+ /** Skip the backup, for hosts that take their own (most managed Postgres does). */
21
+ backup?: boolean
22
+ now?: () => Date
23
+ /** Whether `pg_dump` can run; replaced in tests. */
24
+ hasPgDump?: () => Promise<boolean>
25
+ }
26
+
27
+ export type MigrateResult = { pending: string[] } | { applied: string[]; backup: string | null }
28
+
29
+ async function pgDumpAvailable(): Promise<boolean> {
30
+ return run('pg_dump', ['--version']).then(
31
+ () => true,
32
+ () => false,
33
+ )
34
+ }
35
+
36
+ /**
37
+ * Copies the embedded database's directory, or dumps Postgres with `pg_dump`. The password goes
38
+ * through the environment, not the command line, where other users could read it.
39
+ */
40
+ async function backUp(options: MigrateOptions): Promise<string | null> {
41
+ const { env, root } = options
42
+ const stamp = (options.now ?? (() => new Date()))().toISOString().replace(/[:.]/g, '-')
43
+ if (env.DATABASE_URL) {
44
+ const dir = join(root, '.data', 'backups')
45
+ if (!(await (options.hasPgDump ?? pgDumpAvailable)())) {
46
+ throw new Error(
47
+ 'pg_dump is not installed, so the database cannot be backed up first. Take a backup (many hosts do this for you), then run `cms migrate --no-backup`.',
48
+ )
49
+ }
50
+ const url = new URL(env.DATABASE_URL)
51
+ const password = decodeURIComponent(url.password)
52
+ url.password = ''
53
+ const file = join(dir, `postgres-${stamp}.dump`)
54
+ await mkdir(dir, { recursive: true })
55
+ await run('pg_dump', ['--format=custom', `--file=${file}`, url.toString()], {
56
+ env: { ...process.env, ...(password ? { PGPASSWORD: password } : {}) },
57
+ })
58
+ return file
59
+ }
60
+ const source = dataDir(env)
61
+ const exists = await access(source).then(
62
+ () => true,
63
+ () => false,
64
+ )
65
+ // A site that never started has nothing to lose.
66
+ if (!exists) return null
67
+ // Beside the database, so it shares its disk (the volume, in a container).
68
+ const target = join(dirname(source), 'backups', `pglite-${stamp}`)
69
+ await cp(source, target, { recursive: true, errorOnExist: true, force: false })
70
+ return target
71
+ }
72
+
73
+ /** `cms migrate`: back up, then run core's and the active plugins' pending migrations. */
74
+ export async function migrate(options: MigrateOptions): Promise<MigrateResult> {
75
+ const backup = options.dryRun || options.backup === false ? null : await backUp(options)
76
+ const handle = openDatabase(options.env, { create: !options.dryRun })
77
+ try {
78
+ const result = await migrateSite({
79
+ db: handle.db,
80
+ plugins: options.site.plugins,
81
+ active: activePluginsFromEnv(options.env),
82
+ logger: options.logger,
83
+ dryRun: options.dryRun,
84
+ })
85
+ return 'pending' in result ? result : { applied: result.applied, backup }
86
+ } finally {
87
+ await handle.close()
88
+ }
89
+ }
@@ -0,0 +1,67 @@
1
+ import { timingSafeEqual } from 'node:crypto'
2
+ import { createServer, type IncomingMessage, type Server } from 'node:http'
3
+
4
+ /** A request the supervisor can't take now, such as a second update while one runs. */
5
+ export class ControlError extends Error {
6
+ readonly status: number
7
+
8
+ constructor(status: number, message: string) {
9
+ super(message)
10
+ this.name = 'ControlError'
11
+ this.status = status
12
+ }
13
+ }
14
+
15
+ export type ControlHandler = (body: unknown) => unknown | Promise<unknown>
16
+
17
+ /** `GET /status` and the like: method and path to handler. */
18
+ export type ControlRoutes = Readonly<Record<string, ControlHandler>>
19
+
20
+ const MAX_BODY = 64 * 1024
21
+
22
+ function authorized(header: string | undefined, token: string): boolean {
23
+ const expected = Buffer.from(`Bearer ${token}`)
24
+ const given = Buffer.from(header ?? '')
25
+ return given.length === expected.length && timingSafeEqual(given, expected)
26
+ }
27
+
28
+ async function readJson(incoming: IncomingMessage): Promise<unknown> {
29
+ let size = 0
30
+ const chunks: Buffer[] = []
31
+ for await (const chunk of incoming as AsyncIterable<Buffer>) {
32
+ size += chunk.length
33
+ if (size > MAX_BODY) throw new ControlError(413, 'Request body too large')
34
+ chunks.push(chunk)
35
+ }
36
+ if (size === 0) return {}
37
+ try {
38
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
39
+ } catch {
40
+ throw new ControlError(400, 'Request body is not JSON')
41
+ }
42
+ }
43
+
44
+ /**
45
+ * How the admin reaches the supervisor: JSON over HTTP on a loopback port, with a random token
46
+ * the supervisor hands only to the release it starts. Nothing else on the machine can call it
47
+ * without the token, and nothing off the machine can reach it.
48
+ */
49
+ export function createControlServer(token: string, routes: ControlRoutes): Server {
50
+ return createServer(async (incoming, outgoing) => {
51
+ const reply = (status: number, body: unknown) =>
52
+ outgoing
53
+ .writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
54
+ .end(JSON.stringify(body))
55
+ if (!authorized(incoming.headers.authorization, token))
56
+ return reply(401, { error: 'Unauthorized' })
57
+ const handler =
58
+ routes[`${incoming.method} ${new URL(incoming.url ?? '/', 'http://x').pathname}`]
59
+ if (!handler) return reply(404, { error: 'Not found' })
60
+ try {
61
+ reply(200, (await handler(await readJson(incoming))) ?? {})
62
+ } catch (error) {
63
+ if (error instanceof ControlError) return reply(error.status, { error: error.message })
64
+ reply(500, { error: error instanceof Error ? error.message : String(error) })
65
+ }
66
+ })
67
+ }
@@ -0,0 +1,168 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { once } from 'node:events'
3
+ import { access } from 'node:fs/promises'
4
+ import type { AddressInfo } from 'node:net'
5
+ import { join, resolve } from 'node:path'
6
+ import type { UpdateRequest } from '@otwdesign/core'
7
+ import { loadEnv } from '../site.ts'
8
+ import { detectPackageManager, planSite } from '../update.ts'
9
+ import { ControlError, createControlServer } from './control.ts'
10
+ import { startRelease } from './processes.ts'
11
+ import { createProxy } from './proxy.ts'
12
+ import { buildRelease, removeRelease, step, writeBack } from './releases.ts'
13
+ import { backupDatabase, loadState, restoreDatabase, saveState } from './state.ts'
14
+ import { Supervisor, type Log } from './supervisor.ts'
15
+
16
+ const TWELVE_HOURS = 12 * 60 * 60 * 1000
17
+ const MAX_PACKAGES = 100
18
+
19
+ export interface ServeOptions {
20
+ root: string
21
+ port: number
22
+ hostname: string
23
+ /** For Postgres hosts that take their own backups; the embedded database is always copied. */
24
+ backup: boolean
25
+ checkEveryMs?: number
26
+ }
27
+
28
+ function parseUpdateRequest(body: unknown): UpdateRequest {
29
+ const { packages, pluginsOnly } = (body ?? {}) as { packages?: unknown; pluginsOnly?: unknown }
30
+ if (
31
+ packages !== undefined &&
32
+ (!Array.isArray(packages) ||
33
+ packages.length > MAX_PACKAGES ||
34
+ !packages.every((name) => typeof name === 'string' && name.length <= 214))
35
+ ) {
36
+ throw new ControlError(400, '"packages" must be a list of package names')
37
+ }
38
+ return { packages: packages as string[] | undefined, pluginsOnly: pluginsOnly === true }
39
+ }
40
+
41
+ async function standaloneSite(root: string): Promise<void> {
42
+ const lockfiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb']
43
+ for (const file of lockfiles) {
44
+ if (
45
+ await access(join(root, file)).then(
46
+ () => true,
47
+ () => false,
48
+ )
49
+ )
50
+ return
51
+ }
52
+ throw new Error(
53
+ 'cms serve runs a site with its own lockfile (as create-otw-cms makes them). Run it in the site’s directory, after installing.',
54
+ )
55
+ }
56
+
57
+ /**
58
+ * `cms serve`: runs the site from built releases behind a proxy on the public port, and applies
59
+ * updates from the admin. Resolves once it is serving; stops on SIGINT or SIGTERM.
60
+ */
61
+ export async function serve(options: ServeOptions): Promise<void> {
62
+ const root = resolve(options.root)
63
+ await standaloneSite(root)
64
+ const env = loadEnv(root)
65
+ const database = env.DATABASE_URL ? 'postgres' : 'embedded'
66
+ const dataDir = resolve(root, env.CMS_DATA_DIR || '.data/pglite')
67
+ const stateFile = join(root, '.cms', 'state.json')
68
+ const manager = await detectPackageManager(root)
69
+ const builder = { site: root, manager, releasesDir: join(root, '.cms', 'releases') }
70
+ const token = randomBytes(32).toString('hex')
71
+ const output: Log = (line) => console.log(line)
72
+
73
+ // Bound first, so releases can be told where it is.
74
+ const routes: Record<string, (body: unknown) => unknown> = {}
75
+ const control = createControlServer(token, routes)
76
+ control.listen(0, '127.0.0.1')
77
+ await once(control, 'listening')
78
+ const controlUrl = `http://127.0.0.1:${(control.address() as AddressInfo).port}`
79
+ const releaseEnv = {
80
+ CMS_SUPERVISOR_URL: controlUrl,
81
+ CMS_SUPERVISOR_TOKEN: token,
82
+ // The proxy in front is ours: the visitor's origin comes from its X-Forwarded headers.
83
+ CMS_TRUST_PROXY: '1',
84
+ // Every release uses the site's database and uploads, wherever its own copy of the code is.
85
+ ...(database === 'embedded' ? { CMS_DATA_DIR: dataDir } : {}),
86
+ CMS_UPLOADS_DIR: resolve(root, env.CMS_UPLOADS_DIR || '.data/uploads'),
87
+ }
88
+
89
+ const supervisor = new Supervisor(
90
+ await loadState(stateFile),
91
+ {
92
+ plan: (release, scope) => planSite(release.dir, scope),
93
+ build: (id, changes, log) => buildRelease(builder, id, changes, log),
94
+ migrate: (release, log) =>
95
+ step(
96
+ process.execPath,
97
+ [
98
+ join(release.dir, 'node_modules', '@otwdesign', 'cli', 'bin', 'cms.js'),
99
+ 'migrate',
100
+ '--root',
101
+ release.dir,
102
+ // The supervisor copies the embedded database itself, and puts it back on failure.
103
+ ...(database === 'embedded' || !options.backup ? ['--no-backup'] : []),
104
+ ],
105
+ release.dir,
106
+ log,
107
+ releaseEnv,
108
+ ),
109
+ backup: async () =>
110
+ database === 'embedded'
111
+ ? backupDatabase(dataDir, join(root, '.cms', 'backups'), new Date())
112
+ : null,
113
+ restore: (backup) => restoreDatabase(backup, dataDir),
114
+ start: (release, log) => startRelease(release, log, { env: releaseEnv, output }),
115
+ writeBack: async (release, changes) => {
116
+ const skipped = await writeBack(builder, release, changes)
117
+ if (skipped.length > 0) {
118
+ output(`cms: not copied back to the site (local package links): ${skipped.join(', ')}`)
119
+ }
120
+ },
121
+ remove: removeRelease,
122
+ save: (state) => saveState(stateFile, state),
123
+ now: () => new Date(),
124
+ },
125
+ { database },
126
+ )
127
+
128
+ Object.assign(routes, {
129
+ 'GET /status': () => supervisor.overview(),
130
+ 'POST /check': async () => ({ notice: await supervisor.check() }),
131
+ 'POST /update': (body: unknown) => ({ notice: supervisor.update(parseUpdateRequest(body)) }),
132
+ 'POST /rollback': (body: unknown) => {
133
+ const release = (body as { release?: unknown } | null)?.release
134
+ if (typeof release !== 'string') throw new ControlError(400, '"release" is required')
135
+ return { notice: supervisor.rollback(release) }
136
+ },
137
+ 'PUT /auto-update': async (body: unknown) => {
138
+ const mode = (body as { mode?: unknown } | null)?.mode
139
+ if (mode !== 'off' && mode !== 'patch') {
140
+ throw new ControlError(400, '"mode" must be "off" or "patch"')
141
+ }
142
+ return { notice: await supervisor.setAutoUpdate(mode) }
143
+ },
144
+ })
145
+
146
+ await supervisor.start(output)
147
+ const proxy = createProxy(() => supervisor.target())
148
+ proxy.listen(options.port, options.hostname)
149
+ await once(proxy, 'listening')
150
+ output(`cms: serving on http://${options.hostname}:${options.port} (${database} database)`)
151
+
152
+ const timer = setInterval(() => {
153
+ supervisor
154
+ .tick()
155
+ .catch((error: unknown) => output(`cms: update check failed: ${String(error)}`))
156
+ }, options.checkEveryMs ?? TWELVE_HOURS)
157
+
158
+ const shutdown = async () => {
159
+ clearInterval(timer)
160
+ output('cms: stopping')
161
+ proxy.close()
162
+ control.close()
163
+ await supervisor.stop()
164
+ process.exit(0)
165
+ }
166
+ process.once('SIGINT', () => void shutdown())
167
+ process.once('SIGTERM', () => void shutdown())
168
+ }
@@ -0,0 +1,99 @@
1
+ import { spawn, type ChildProcess } from 'node:child_process'
2
+ import { once } from 'node:events'
3
+ import { createServer, type AddressInfo } from 'node:net'
4
+ import { join } from 'node:path'
5
+ import type { BuiltRelease, Log, RunningRelease } from './supervisor.ts'
6
+
7
+ /** A port nothing listens on now. Another process could take it first; starting would then fail. */
8
+ export async function freePort(): Promise<number> {
9
+ const server = createServer()
10
+ server.listen(0, '127.0.0.1')
11
+ await once(server, 'listening')
12
+ const { port } = server.address() as AddressInfo
13
+ server.close()
14
+ await once(server, 'close')
15
+ return port
16
+ }
17
+
18
+ /** Signs-in page answers (200, or a redirect to setup) once the app and its database are up. */
19
+ async function answers(port: number): Promise<boolean> {
20
+ try {
21
+ const response = await fetch(`http://127.0.0.1:${port}/admin/login`, {
22
+ redirect: 'manual',
23
+ signal: AbortSignal.timeout(5_000),
24
+ })
25
+ await response.body?.cancel()
26
+ return response.status < 500
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+
32
+ async function stopChild(child: ChildProcess, graceMs: number): Promise<void> {
33
+ if (child.exitCode !== null || child.signalCode !== null) return
34
+ const exited = once(child, 'exit')
35
+ child.kill('SIGTERM')
36
+ const timer = setTimeout(() => child.kill('SIGKILL'), graceMs)
37
+ await exited
38
+ clearTimeout(timer)
39
+ }
40
+
41
+ export interface StartOptions {
42
+ /** Added to the supervisor's own environment. */
43
+ env: NodeJS.ProcessEnv
44
+ /** Where the release's output goes once it serves (the supervisor's own output). */
45
+ output: Log
46
+ timeoutMs?: number
47
+ graceMs?: number
48
+ }
49
+
50
+ /**
51
+ * Starts a release with its own `next start` on a loopback port, and resolves once it answers.
52
+ * If it exits or doesn't answer in time, it is stopped and the promise rejects.
53
+ */
54
+ export async function startRelease(
55
+ release: BuiltRelease,
56
+ log: Log,
57
+ { env, output, timeoutMs = 60_000, graceMs = 10_000 }: StartOptions,
58
+ ): Promise<RunningRelease> {
59
+ const port = await freePort()
60
+ const next = join(release.dir, 'node_modules', 'next', 'dist', 'bin', 'next')
61
+ const child = spawn(
62
+ process.execPath,
63
+ [next, 'start', '--port', String(port), '--hostname', '127.0.0.1'],
64
+ {
65
+ cwd: release.dir,
66
+ env: { ...process.env, ...env, NODE_ENV: 'production', PORT: String(port) },
67
+ stdio: ['ignore', 'pipe', 'pipe'],
68
+ },
69
+ )
70
+ let ready = false
71
+ for (const stream of [child.stdout, child.stderr]) {
72
+ stream?.setEncoding('utf8')
73
+ stream?.on('data', (chunk: string) => {
74
+ for (const line of chunk.split('\n').filter(Boolean)) {
75
+ const tagged = `[${release.id}] ${line}`
76
+ if (ready) output(tagged)
77
+ else log(tagged)
78
+ }
79
+ })
80
+ }
81
+
82
+ const deadline = Date.now() + timeoutMs
83
+ while (Date.now() < deadline) {
84
+ if (child.exitCode !== null) {
85
+ throw new Error(
86
+ `The release ${release.id} exited (code ${child.exitCode}) before it answered.`,
87
+ )
88
+ }
89
+ if (await answers(port)) {
90
+ ready = true
91
+ return { port, stop: () => stopChild(child, graceMs) }
92
+ }
93
+ await new Promise((resolve) => setTimeout(resolve, 250))
94
+ }
95
+ await stopChild(child, graceMs)
96
+ throw new Error(
97
+ `The release ${release.id} did not answer within ${Math.round(timeoutMs / 1000)} seconds.`,
98
+ )
99
+ }