@fabrika/cli 0.9.0-dev.2 → 0.9.0-dev.20

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/db.ts CHANGED
@@ -1,48 +1,33 @@
1
- import {
2
- type Finding,
3
- formatFinding,
4
- GENERATED_TEST_HEADER,
5
- type GeneratedTest,
6
- generatedTests,
7
- missingEndpointFixtures,
8
- readApplicationTree,
9
- scaffoldInputs,
10
- } from '@fabrika/check'
11
- import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
1
+ import { applicationMigrations as sqliteApplicationMigrations } from '@fabrika/app/build'
2
+ import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
3
+ import { CodegenError, type GeneratedModule, generateSchema, leftOutText, SCHEMA_FILE } from '@fabrika/db/codegen'
4
+ import { generateSqliteSchema } from '@fabrika/db/codegen-sqlite'
12
5
  import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
6
+ import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
13
7
  import {
14
- CONNECTION_CAPACITY_MESSAGE,
8
+ APPLICATION_MIGRATION_BUNDLE,
15
9
  ConnectionCapacityError,
16
- createTestProvisioner,
17
10
  DEFAULT_MIGRATION_LOCK_TIMEOUT_MS,
18
11
  DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS,
19
12
  definePostgresApplicationMigrations,
20
13
  type PostgresApplicationMigrations,
21
14
  PostgresMigrationError,
22
15
  postgresMigrationResultMessage,
23
- type TestProvisioner,
24
- TOO_MANY_CONNECTIONS,
25
- withConnectionCapacity,
26
16
  } from '@fabrika/platform-node'
27
17
  import { SQL } from 'bun'
28
- import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
29
- import { tmpdir } from 'node:os'
18
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
30
19
  import { dirname, join } from 'node:path'
31
- import { fileURLToPath } from 'node:url'
32
- import { readJunitCases } from './junit'
33
20
 
34
21
  /** The checker's `migration-name` contract (`@fabrika/check`, `db/migrations/`). */
35
22
  const MIGRATIONS_DIR = 'db/migrations'
36
23
  const SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
37
24
 
38
- export const DB_USAGE = `fabrika db — an application's Postgres schema
25
+ export const DB_USAGE = `fabrika db — an application's database schema: Postgres, or SQLite on Cloudflare
39
26
 
40
27
  Usage:
41
28
  fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
42
29
  fabrika db migrate Apply the framework's tables, then ${MIGRATIONS_DIR}, to the application's schema app_<id>.
43
30
  fabrika db codegen [--verify] Write ${SCHEMA_FILE} from the migrated schema; --verify only fails when it is stale.
44
- fabrika db test-scaffold Write the generated tests: a policy isolation test per table a store reaches, the endpoint access test.
45
- fabrika db test-isolation [--verbose] Run the generated tests on a throwaway schema; fail unless every case the scaffold wrote passed.
46
31
 
47
32
  Run from the application root. \`migrate\` and \`codegen\` read FABRIKA_APP_ID and FABRIKA_APP_DATABASE_URL from
48
33
  the environment only. FABRIKA_APP_DATABASE_URL is the provisioning credential: \`migrate\` uses it only to create
@@ -50,15 +35,10 @@ the application's roles (app_<id> owns the schema, run_<id> gets DML on its tabl
50
35
  roles. It applies the files as app_<id>, holds a lock derived from the application id, runs each file in one
51
36
  transaction with lock_timeout ${DEFAULT_MIGRATION_LOCK_TIMEOUT_MS} ms and statement_timeout ${DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS} ms, and fails when a
52
37
  file that already ran has changed: an applied migration is immutable, so a change is a new file.
53
- \`test-scaffold\` reads fabrika.contract.ts and src/db/tables.ts as the checker does, rewrites every generated test and
54
- deletes a generated one the scaffold no longer writes, printing each path, or that it wrote none; @fabrika/check refuses
55
- one that is missing, edited or stale.
56
- \`test-isolation\` is the platform's run of them: with FABRIKA_APP_DATABASE_URL it creates a throwaway provisioner
57
- (CREATEROLE, CREATE on the database, nothing of any application) that the tests get instead, ignores the application's
58
- bunfig.toml, and checks the JUnit report against the case names the scaffold wrote. It first drops the provisioners
59
- that killed runs left behind: expired, and without a session of their own or of a role they created. A database at its
60
- connection limit (SQLSTATE ${TOO_MANY_CONNECTIONS}) is waited for; one that never frees a slot fails the run saying so,
61
- never as failed cases.
38
+
39
+ An application whose ${CONFIG_FILE} default-exports @fabrika/provider-cloudflare's defineApp runs on SQLite in its
40
+ Durable Object, which applies the migrations itself when it boots: \`migrate\` refuses, \`codegen\` applies them to an
41
+ in-memory database; neither needs a database URL.
62
42
  `
63
43
 
64
44
  export interface DbCommandDependencies {
@@ -79,6 +59,12 @@ const refuseArguments = (command: string, argv: readonly string[]): void => {
79
59
  if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
80
60
  }
81
61
 
62
+ /** The dialect `fabrika.config.ts` names, read as the checker reads it; Postgres without a config. */
63
+ const dialectAt = async (cwd: string): Promise<ApplicationDialect> => {
64
+ const config = await readFile(join(cwd, CONFIG_FILE), 'utf8').catch(() => undefined)
65
+ return applicationDialect(new Map(config === undefined ? [] : [[CONFIG_FILE, config]]))
66
+ }
67
+
82
68
  const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
83
69
 
84
70
  const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
@@ -126,6 +112,11 @@ const applicationMigrations = (appId: string, cwd: string): PostgresApplicationM
126
112
 
127
113
  const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
128
114
  refuseArguments('migrate', argv)
115
+ if ((await dialectAt(deps.cwd)) === 'sqlite') {
116
+ throw new Error(
117
+ 'db migrate: an application on Cloudflare migrates its own SQLite database when its Durable Object boots (ADR-0065); there is nothing to run',
118
+ )
119
+ }
129
120
  const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
130
121
  const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
131
122
  const files = migrations.read()
@@ -137,19 +128,32 @@ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Pr
137
128
  }
138
129
  }
139
130
 
140
- const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
141
- const verify = argv.includes('--verify')
142
- refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
131
+ /** The schema module of the migrated application schema, read with the provisioning credential. */
132
+ const postgresSchema = async (deps: DbCommandDependencies): Promise<GeneratedModule> => {
143
133
  const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
144
134
  const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
145
- let source: string
146
135
  try {
147
136
  // The migrations' manifest: the start check refuses any database object no migration declares.
148
- source = await generateSchema(url, migrations.schema, migrations.objects())
137
+ return await generateSchema(url, migrations.schema, migrations.objects())
149
138
  } catch (error) {
150
139
  throw reportable(error)
151
140
  }
141
+ }
142
+
143
+ /** The schema module of the bundles the Durable Object applies, in its order, run in an in-memory database. */
144
+ const sqliteSchema = async (cwd: string): Promise<GeneratedModule> =>
145
+ generateSqliteSchema([
146
+ { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
147
+ { bundle: APPLICATION_MIGRATION_BUNDLE, migrations: await sqliteApplicationMigrations(cwd) },
148
+ ])
149
+
150
+ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
151
+ const verify = argv.includes('--verify')
152
+ refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
153
+ const { source, leftOut } = (await dialectAt(deps.cwd)) === 'sqlite' ? await sqliteSchema(deps.cwd) : await postgresSchema(deps)
152
154
  const path = join(deps.cwd, SCHEMA_FILE)
155
+ // Named on every run, --verify's too, so a column the module leaves out is never silent.
156
+ for (const column of leftOut) deps.write(`${leftOutText(`${column.table}.${column.column}`, column.type, column.of)}\n`)
153
157
  if (verify) {
154
158
  const committed = await readFile(path, 'utf8').catch(() => undefined)
155
159
  if (committed !== source) throw new Error(`${SCHEMA_FILE} is stale; run fabrika db codegen and commit the result`)
@@ -161,153 +165,16 @@ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Pr
161
165
  deps.write(`${SCHEMA_FILE}\n`)
162
166
  }
163
167
 
164
- const expectedTests = async (
165
- cwd: string,
166
- ): Promise<
167
- { readonly files: ReadonlyMap<string, string>; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
168
- > => {
169
- const { files } = await readApplicationTree(cwd)
170
- const inputs = scaffoldInputs(files)
171
- return { files, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
172
- }
173
-
174
- const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
175
- refuseArguments('test-scaffold', argv)
176
- const { files, tests, missing } = await expectedTests(deps.cwd)
177
- for (const [path, text] of files) {
178
- if (text.startsWith(GENERATED_TEST_HEADER) && !tests.has(path)) {
179
- await rm(join(deps.cwd, path))
180
- deps.write(`removed ${path}\n`)
181
- }
182
- }
183
- for (const [path, { text }] of tests) {
184
- await mkdir(dirname(join(deps.cwd, path)), { recursive: true })
185
- await writeFile(join(deps.cwd, path), text)
186
- deps.write(`${path}\n`)
187
- }
188
- if (missing.length > 0) {
189
- throw new Error(`db test-scaffold: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
190
- }
191
- if (tests.size === 0) {
192
- deps.write('no generated tests: they start with the first table a store reaches, and the application has none; write the first test yourself\n')
193
- }
194
- }
195
-
196
- /**
197
- * Only what Bun needs to run; the URL arrives as the kit's own variable, and no framework variable is passed on. It is
198
- * a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code.
199
- */
200
- const testEnvironment = (source: DbCommandDependencies['source'], url: string): Record<string, string> => {
201
- const environment: Record<string, string> = { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
202
- for (const name of ['PATH', 'HOME', 'TMPDIR']) {
203
- const value = source[name]
204
- if (value !== undefined) environment[name] = value
205
- }
206
- return environment
207
- }
208
-
209
- /**
210
- * The server's own words for a refused connection (SQLSTATE 53300) and the test kit's report of one it gave up on. A
211
- * run whose tests met one says so instead of counting cases: a case that could not connect proved nothing.
212
- */
213
- const EXHAUSTED_CONNECTIONS = [
214
- CONNECTION_CAPACITY_MESSAGE,
215
- 'remaining connection slots are reserved',
216
- 'too many clients already',
217
- 'too many connections for role',
218
- 'too many connections for database',
219
- ]
220
-
221
- /** Whether the tests' output reports a connection the database refused for lack of a free slot. */
222
- export const reportsExhaustedConnections = (output: string): boolean => EXHAUSTED_CONNECTIONS.some((text) => output.includes(text))
223
-
224
- /**
225
- * Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
226
- * application applies, and the platform's preload, which captures Bun's test functions before the application loads.
227
- * Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
228
- * printed, because a dependency may write a credential into it; `--verbose`, which the platform never passes, prints it.
229
- */
230
- const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
231
- const verbose = argv.includes('--verbose')
232
- refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
233
- const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
234
- const { files, tests, missing } = await expectedTests(deps.cwd)
235
- if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
236
- for (const [path, { text }] of tests) {
237
- if (files.get(path) !== text) throw new Error(`db test-isolation: ${path} is not the test fabrika db test-scaffold writes; run it`)
238
- }
239
- if (tests.size === 0) {
240
- deps.write('no generated tests\n')
241
- return
242
- }
243
- let provisioner: TestProvisioner
244
- try {
245
- provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
246
- } catch (error) {
247
- throw reportable(error)
248
- }
249
- if (provisioner.swept.length > 0) deps.write(`dropped the test provisioners earlier runs left behind: ${provisioner.swept.join(', ')}\n`)
250
- const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
251
- try {
252
- await writeFile(join(scratch, 'bunfig.toml'), '')
253
- const report = join(scratch, 'junit.xml')
254
- const child = Bun.spawn(
255
- [
256
- process.execPath,
257
- `--config=${join(scratch, 'bunfig.toml')}`,
258
- 'test',
259
- `--preload=${fileURLToPath(import.meta.resolve('@fabrika/app/testing/preload'))}`,
260
- ...[...tests.keys()].map((path) => `./${path}`),
261
- '--reporter=junit',
262
- `--reporter-outfile=${report}`,
263
- ],
264
- { cwd: deps.cwd, env: testEnvironment(deps.source, provisioner.url), stdout: 'pipe', stderr: 'pipe' },
265
- )
266
- const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
267
- if (verbose) deps.write(`${stdout}${stderr}\n`)
268
- const reported = readJunitCases(await readFile(report, 'utf8').catch(() => ''))
269
- const failed: string[] = []
270
- let total = 0
271
- for (const [path, { cases }] of tests) {
272
- for (const name of cases) {
273
- total++
274
- const reportedCase = reported.find((item) => item.file === path && item.name === name)
275
- const outcome = reportedCase === undefined
276
- ? 'not run'
277
- : reportedCase.outcome === 'passed' && reportedCase.assertions === 0
278
- ? 'no assertion'
279
- : reportedCase.outcome
280
- if (outcome !== 'passed') failed.push(`${path}: ${name} (${outcome})`)
281
- }
282
- }
283
- if ((code !== 0 || failed.length > 0) && reportsExhaustedConnections(`${stdout}${stderr}`)) {
284
- throw new Error(
285
- `db test-isolation: ${CONNECTION_CAPACITY_MESSAGE} for the generated tests (SQLSTATE ${TOO_MANY_CONNECTIONS}), so they reached no verdict; other processes hold the database's connections: free them or give the database more, then run it again`,
286
- )
287
- }
288
- if (code !== 0 || failed.length > 0) {
289
- const rerun = verbose ? '' : '; rerun with --verbose locally to see the test output'
290
- throw new Error(
291
- `db test-isolation: ${total - failed.length} of ${total} generated cases passed (exit ${code})${rerun}${
292
- failed.map((line) => `\n- ${line}`).join('')
293
- }`,
294
- )
295
- }
296
- deps.write(`${total} generated cases passed\n`)
297
- } finally {
298
- await rm(scratch, { recursive: true, force: true })
299
- await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
300
- throw reportable(error)
301
- })
302
- }
303
- }
304
-
305
168
  export const runDbCommand = async (command: string | undefined, argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
306
169
  if (command === 'new') return newMigration(argv, deps)
307
170
  if (command === 'migrate') return migrate(argv, deps)
308
171
  if (command === 'codegen') return codegen(argv, deps)
309
- if (command === 'test-scaffold') return testScaffold(argv, deps)
310
- if (command === 'test-isolation') return testIsolation(argv, deps)
172
+ // A platform release up to 0.9.0-dev.18 still runs this init command against the application's own CLI, and its
173
+ // reader admits a newer prerelease of the same version (ADR-0062): the command stays, and runs nothing.
174
+ if (command === 'test-isolation') {
175
+ deps.write('db test-isolation: nothing to run; this release generates no tests\n')
176
+ return
177
+ }
311
178
  throw new Error(`Unknown db command: ${command ?? '(missing)'}\n\n${DB_USAGE}`)
312
179
  }
313
180
 
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { CONTRACT_FILE, type EntryRuntime, writeGeneratedEntry } from '@fabrika/app/build'
4
4
  import { authoredAppProvider } from '@fabrika/provider-contract'
5
+ import { type AppCli, appCliFromModule, type NamespaceCli } from '@fabrika/provider-contract/app-cli'
5
6
  import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/provider-contract/installation'
6
7
  import { dirname, join, relative, resolve } from 'node:path'
7
8
  import { CONTROL_USAGE, registerCompiledManifest, runControlCli } from './control.js'
@@ -25,8 +26,10 @@ Usage:
25
26
  [--namespace=<id>] [--installation-id=<n|none>] [--url=<origin>] [--json]
26
27
  fabrika namespace <plan|create|adopt|reconcile> --provider=zerops [provider options]
27
28
  fabrika control <key|apps|namespaces|register|deploy|runs> [options]
29
+ fabrika env <inspect|maintenance|operations|recover|backups|restore> <app> <env> [arguments] [--json]
30
+ fabrika operations <issues|issue|releases|health> [options] [--json]
28
31
  fabrika builder <init|next|advance|gate|ensure-daemon|induce|build> [options]
29
- fabrika db <new|migrate|codegen|test-scaffold|test-isolation> [options]
32
+ fabrika db <new|migrate|codegen> [options]
30
33
  fabrika job run <name>
31
34
  fabrika connect <add|pull> <app>/<export>@<version> --consumer=<app> --env=<env> [--url=<control origin>]
32
35
 
@@ -49,7 +52,7 @@ A bare \`--trigger-ref\` is a branch (\`deploy/prod\` deploys on a push to \`ref
49
52
  \`refs/tags/<tag>\` or a glob such as \`refs/tags/v*\`. \`fabrika control --help\` lists every form.
50
53
 
51
54
  \`fabrika db\` manages an application's Postgres schema: migration files, applying them (the template's
52
- \`run.initCommands\`), the generated types and the generated isolation tests. Run \`fabrika db --help\` for its surface.
55
+ \`run.initCommands\`) and the generated types. Run \`fabrika db --help\` for its surface.
53
56
 
54
57
  \`fabrika job run <name>\` runs one c.cron job of a contract application: the command each crontab entry runs. Run
55
58
  \`fabrika job --help\` for its surface.
@@ -61,6 +64,12 @@ environment approved, as Control answers it to FABRIKA_CONTROL_KEY. Run \`fabrik
61
64
  provider-neutral, loads no installation package, and speaks the same typed API the console does. Run
62
65
  \`fabrika control --help\` for its surface.
63
66
 
67
+ \`fabrika env\` shows an application environment's data and backups through the control plane, puts it into
68
+ maintenance, restores its data as of a past time, or recovers a stuck operation. Run \`fabrika env --help\` for its surface.
69
+
70
+ \`fabrika operations\` reads Operations — issues and their events, releases, health — through the console's API, with
71
+ FABRIKA_CONTROL_KEY. It is read-only. Run \`fabrika operations --help\` for its surface.
72
+
64
73
  Which platform commands exist, and how WIDE each one is, is the provider's own answer — Zerops'
65
74
  \`platform deploy\` owns the whole ordered sequence while Cloudflare's is one step of a scaffolded
66
75
  workflow (ADR-0027), and only Zerops offers \`platform install\`, the from-scratch bring-up,
@@ -152,41 +161,33 @@ const requireInstalled = (specifier: string, command: string): void => {
152
161
  }
153
162
  }
154
163
 
164
+ /** A provider id names its package, `@fabrika/provider-<id>`; anything else is a module specifier of its own. */
165
+ const PROVIDER_ID = /^[a-z][a-z0-9-]*$/
166
+
167
+ const installationSpecifier = (provider: string): string => PROVIDER_ID.test(provider) ? `@fabrika/provider-${provider}/installation` : provider
168
+
155
169
  const installationModule = async (provider: string, command: string): Promise<unknown> => {
156
- const specifier = provider === 'cloudflare'
157
- ? '@fabrika/provider-cloudflare/installation'
158
- : provider === 'zerops'
159
- ? '@fabrika/provider-zerops/installation'
160
- : provider
170
+ const specifier = installationSpecifier(provider)
161
171
  requireInstalled(specifier, command)
162
172
  return import(specifier)
163
173
  }
164
174
 
165
- export type AppCliRunner = (argv: readonly string[]) => Promise<void>
166
-
167
- export const appCliRunnerFromModule = (loaded: unknown, packageName: string, exportName: string): AppCliRunner => {
168
- if (typeof loaded !== 'object' || loaded === null || !(exportName in loaded)) {
169
- throw new Error(`${packageName} must export \`${exportName}\``)
170
- }
171
- const runner = Reflect.get(loaded, exportName)
172
- if (typeof runner !== 'function') {
173
- throw new Error(`${packageName} must export \`${exportName}\` as a function`)
174
- }
175
- return runner
175
+ /** App and namespace commands take a provider id only: the module's `appCli` must name the same one. */
176
+ const providerAppCli = async (provider: string, command: string): Promise<AppCli> => {
177
+ if (!PROVIDER_ID.test(provider)) throw new Error(`\`${command}\` takes a provider id ([a-z][a-z0-9-]*), not "${provider}"`)
178
+ const specifier = `@fabrika/provider-${provider}/cli`
179
+ requireInstalled(specifier, command)
180
+ return appCliFromModule(await import(specifier), provider, specifier)
176
181
  }
177
182
 
178
- const appCliRunner = async (packageName: string, exportName: string, command: string): Promise<AppCliRunner> => {
179
- requireInstalled(packageName, command)
180
- const loaded: unknown = await import(packageName)
181
- return appCliRunnerFromModule(loaded, packageName, exportName)
182
- }
183
+ const unsupported = (provider: string, command: string): Error => new Error(`${provider} app tooling does not support \`${command}\``)
183
184
 
184
185
  const runPlatform = async (parsed: ParsedCommand): Promise<void> => {
185
186
  if (!isInstallationCommand(parsed.command)) {
186
187
  throw new Error(`Unknown platform command: ${parsed.command ?? '(missing)'}`)
187
188
  }
188
189
  const provider = requireExplicitProvider(parsed)
189
- const expectedProvider = provider === 'cloudflare' || provider === 'zerops' ? provider : undefined
190
+ const expectedProvider = PROVIDER_ID.test(provider) ? provider : undefined
190
191
  const installation = installationCliFromModule(
191
192
  await installationModule(provider, `fabrika platform ${parsed.command} --provider=${provider}`),
192
193
  expectedProvider,
@@ -202,17 +203,12 @@ const runAppRegister = async (parsed: ParsedCommand): Promise<void> => {
202
203
  const config = configPath(parsed.rest)
203
204
  await registerCompiledManifest(parsed.rest, async (env) => {
204
205
  const provider = await selectedAppProvider(parsed)
205
- if (provider !== 'zerops') {
206
- throw new Error(`${provider} app tooling does not support \`app register\``)
207
- }
208
- requireInstalled('@fabrika/provider-zerops/cli', 'fabrika app register')
209
- const { buildZeropsManifestText } = await import('@fabrika/provider-zerops/cli')
210
- return { provider, text: await buildZeropsManifestText({ config, env }) }
206
+ const cli = await providerAppCli(provider, 'fabrika app register')
207
+ if (cli.registrationManifest === undefined) throw unsupported(provider, 'app register')
208
+ return { provider, text: await cli.registrationManifest({ config, env }) }
211
209
  })
212
210
  }
213
211
 
214
- const ENTRY_RUNTIMES: Readonly<Record<string, EntryRuntime>> = { cloudflare: 'cloudflare', zerops: 'bun' }
215
-
216
212
  /** A contract application gets its generated entrypoint before the provider builds it. False when it is none. */
217
213
  const writeContractEntry = async (argv: readonly string[], runtime: EntryRuntime): Promise<boolean> => {
218
214
  const root = dirname(resolve(process.cwd(), configPath(argv)))
@@ -235,41 +231,37 @@ const runApp = async (parsed: ParsedCommand): Promise<void> => {
235
231
  return
236
232
  }
237
233
  const provider = await selectedAppProvider(parsed)
238
- const runtime = ENTRY_RUNTIMES[provider]
239
- const contract = parsed.command === 'build' && runtime !== undefined && (await writeContractEntry(parsed.rest, runtime))
240
- if (provider === 'cloudflare') {
241
- if (contract) {
242
- return
243
- }
244
- if (parsed.command !== 'deploy') {
245
- throw new Error(`Cloudflare app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
246
- }
247
- const runCloudflareCli = await appCliRunner('@fabrika/provider-cloudflare/cli', 'runCloudflareCli', 'fabrika app deploy')
248
- await runCloudflareCli(['deploy', ...parsed.rest])
234
+ const command = `app ${parsed.command ?? '(missing)'}`
235
+ const cli = await providerAppCli(provider, `fabrika ${command}`)
236
+ if (parsed.command === 'build' && cli.build !== undefined) {
237
+ await cli.build(parsed.rest, { contract: await writeContractEntry(parsed.rest, cli.entryRuntime) })
249
238
  return
250
239
  }
251
- if (provider === 'zerops') {
252
- if (parsed.command !== 'build') {
253
- throw new Error(`Zerops app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
254
- }
255
- const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli', 'fabrika app build')
256
- await runZeropsCli(['build', ...parsed.rest])
240
+ if (parsed.command === 'deploy' && cli.deploy !== undefined) {
241
+ await cli.deploy(parsed.rest)
257
242
  return
258
243
  }
259
- throw new Error(`Provider ${provider} does not expose app CLI commands`)
244
+ throw unsupported(provider, command)
245
+ }
246
+
247
+ const namespaceCli = async (provider: string): Promise<NamespaceCli> => {
248
+ const cli = await providerAppCli(provider, 'fabrika namespace')
249
+ if (cli.namespaces === undefined) throw new Error(`Provider ${provider} does not expose deployment namespaces`)
250
+ return cli.namespaces
260
251
  }
261
252
 
262
253
  const runNamespace = async (parsed: ParsedCommand): Promise<void> => {
263
254
  const provider = requireExplicitProvider(parsed)
264
- if (provider !== 'zerops') {
265
- throw new Error(`Provider ${provider} does not expose deployment namespaces`)
266
- }
255
+ const cli = await namespaceCli(provider)
267
256
  if (parsed.command === undefined) {
268
257
  throw new Error('Namespace command is required')
269
258
  }
270
- requireInstalled('@fabrika/provider-zerops', 'fabrika namespace')
271
- const { runZeropsNamespaceCli } = await import('./namespace.js')
272
- await runZeropsNamespaceCli(parsed.command, parsed.rest)
259
+ const { runNamespaceCommand } = await import('./namespace.js')
260
+ await runNamespaceCommand(cli, parsed.command, parsed.rest, {
261
+ source: process.env,
262
+ fetch: (input, init) => fetch(input, init),
263
+ write: (value) => console.info(value.trimEnd()),
264
+ })
273
265
  }
274
266
 
275
267
  export const runCli = async (argv: readonly string[]): Promise<void> => {
@@ -284,8 +276,21 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
284
276
  console.info(CONTROL_USAGE)
285
277
  return
286
278
  }
279
+ if (parsed.help && parsed.area === 'env') {
280
+ const { ENV_USAGE } = await import('./data.js')
281
+ console.info(ENV_USAGE)
282
+ return
283
+ }
284
+ if (parsed.help && parsed.area === 'operations') {
285
+ const { OPERATIONS_USAGE } = await import('./operations.js')
286
+ console.info(OPERATIONS_USAGE)
287
+ return
288
+ }
287
289
  if (parsed.help && parsed.area === 'namespace') {
288
- requireInstalled('@fabrika/provider-zerops', 'fabrika namespace')
290
+ if (parsed.provider !== undefined && parsed.provider !== '') {
291
+ console.info((await namespaceCli(parsed.provider)).usage)
292
+ return
293
+ }
289
294
  const { NAMESPACE_USAGE } = await import('./namespace.js')
290
295
  console.info(NAMESPACE_USAGE)
291
296
  return
@@ -336,6 +341,17 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
336
341
  await runControlCli(parsed.command, parsed.rest, parsed.provider)
337
342
  return
338
343
  }
344
+ if (parsed.area === 'env') {
345
+ const { runEnvCli } = await import('./data.js')
346
+ await runEnvCli(parsed.command, parsed.rest)
347
+ return
348
+ }
349
+ if (parsed.area === 'operations') {
350
+ const { runOperationsCli } = await import('./operations.js')
351
+ const exitCode = await runOperationsCli(parsed.command, parsed.rest)
352
+ if (exitCode !== 0) process.exitCode = exitCode
353
+ return
354
+ }
339
355
  if (parsed.area === 'db') {
340
356
  const { runDbCli } = await import('./db.js')
341
357
  await runDbCli(parsed.command, parsed.rest)
package/src/job.ts CHANGED
@@ -16,8 +16,8 @@ come from the environment only and leave the process before ${IMPLEMENTATION_FIL
16
16
  process started again with the runtime role's credential in place of FABRIKA_APP_DATABASE_URL. A run takes the job's lease
17
17
  or does not start. It exits 1 when the job failed, and 0 when it succeeded or a previous run still holds the lease.
18
18
  A failure is named by a fixed code (timeout, lease_lost, handler_failed, query_refused, capability_refused,
19
- driver_failed, crashed, unauthorized, iam_unavailable, boot_failed), never by the application's error; a refusal adds
20
- its catalog reason (query_refused: undeclared_reach).
19
+ framework_fault, unavailable, driver_failed, crashed, unauthorized, iam_unavailable, boot_failed), never by the
20
+ application's error; a framework failure adds its catalog reason (query_refused: undeclared_reach).
21
21
  `
22
22
 
23
23
  export interface JobCommandDependencies {