@fabrika/cli 0.0.26 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/cli",
3
- "version": "0.0.26",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,14 +29,13 @@
29
29
  "test": "bun test"
30
30
  },
31
31
  "dependencies": {
32
- "@fabrika/app": "^0.0.26",
33
- "@fabrika/auth-core": "^0.0.26",
34
- "@fabrika/control-contract": "^0.0.26",
35
- "@fabrika/installation-cloudflare": "^0.0.26",
36
- "@fabrika/installation-contract": "^0.0.26",
37
- "@fabrika/installation-zerops": "^0.0.26",
38
- "@fabrika/provider-cloudflare": "^0.0.26",
39
- "@fabrika/provider-contract": "^0.0.26",
40
- "@fabrika/provider-zerops": "^0.0.26"
32
+ "zod": "^3.25.76",
33
+ "@fabrika/app": "^0.3.1",
34
+ "@fabrika/auth-core": "^0.3.1",
35
+ "@fabrika/builder": "^0.3.1",
36
+ "@fabrika/control-contract": "^0.3.1",
37
+ "@fabrika/provider-cloudflare": "^0.3.1",
38
+ "@fabrika/provider-contract": "^0.3.1",
39
+ "@fabrika/provider-zerops": "^0.3.1"
41
40
  }
42
41
  }
package/src/control.ts CHANGED
@@ -23,6 +23,24 @@ import type {
23
23
  RegisterAppRequest,
24
24
  RunDto,
25
25
  } from '@fabrika/control-contract'
26
+ import { z } from 'zod'
27
+
28
+ const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
29
+ z.union([z.null(), z.string(), z.number(), z.boolean(), z.array(jsonValueSchema), z.record(jsonValueSchema)])
30
+ )
31
+ const manifestHeaderSchema = z.object({ manifestVersion: z.number().int().safe().positive() })
32
+ const issueKeyResultSchema = z.union([
33
+ z.object({
34
+ ok: z.literal(false),
35
+ reason: z.enum(['missing_token', 'invalid_token', 'unknown_principal', 'disabled', 'not_allowed']).catch('not_allowed'),
36
+ }),
37
+ z.object({
38
+ ok: z.literal(true),
39
+ token: z.string(),
40
+ id: z.string(),
41
+ principalId: z.string().optional().catch(undefined),
42
+ }).transform(({ principalId, ...result }) => ({ ...result, ...(principalId === undefined ? {} : { principalId }) })),
43
+ ])
26
44
 
27
45
  const USAGE = `fabrika control — operate the Delivery control plane
28
46
 
@@ -105,7 +123,7 @@ control service. It is NOT the private hostname the services use between themsel
105
123
  resolves inside the provider's project and nowhere else, so from here it only ever fails to connect.
106
124
 
107
125
  Connecting a GitHub source is NOT here and will not be: App creation is a browser flow whose
108
- authorization requires a human principal (ADR-0031). Use Settings → Source in the console.
126
+ authorization requires a human principal (ADR-0029). Use Settings → Source in the console.
109
127
  `
110
128
 
111
129
  const DEFAULT_CONTROL_APP_ID = 'vozka'
@@ -208,43 +226,25 @@ const readJsonFile = async (path: string): Promise<JsonValue> => {
208
226
  const text = await file.text()
209
227
  try {
210
228
  const parsed: unknown = JSON.parse(text)
211
- return asJsonValue(parsed, path)
229
+ const result = jsonValueSchema.safeParse(parsed)
230
+ if (!result.success) throw new Error(`${path} contains a value JSON cannot carry`)
231
+ return result.data
212
232
  } catch (error) {
213
233
  throw error instanceof SyntaxError ? new Error(`${path} is not valid JSON`) : error
214
234
  }
215
235
  }
216
236
 
217
- /** `JSON.parse` returns `unknown`; narrow it to the contract's own JSON type without a cast. */
218
- const asJsonValue = (value: unknown, path: string): JsonValue => {
219
- if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
220
- return value
221
- }
222
- if (Array.isArray(value)) {
223
- return value.map((entry) => asJsonValue(entry, path))
224
- }
225
- if (typeof value === 'object') {
226
- const out: Record<string, JsonValue> = {}
227
- for (const [key, entry] of Object.entries(value)) {
228
- out[key] = asJsonValue(entry, path)
229
- }
230
- return out
231
- }
232
- throw new Error(`${path} contains a value JSON cannot carry`)
233
- }
234
-
235
237
  const emit = (flags: Flags, result: unknown, render: () => string): void => {
236
238
  console.info(flags.json ? JSON.stringify(result, null, 2) : render())
237
239
  }
238
240
 
239
241
  /** `fabrika app build` writes `manifestVersion`; it is the version the provider's artifact codec accepts. */
240
242
  const manifestVersion = (manifest: JsonValue, path: string): number => {
241
- const version = typeof manifest === 'object' && manifest !== null && !Array.isArray(manifest)
242
- ? Reflect.get(manifest, 'manifestVersion')
243
- : undefined
244
- if (typeof version !== 'number' || !Number.isSafeInteger(version) || version <= 0) {
243
+ const result = manifestHeaderSchema.safeParse(manifest)
244
+ if (!result.success) {
245
245
  throw new Error(`${path} declares no manifestVersion — run \`fabrika app build\` to produce one`)
246
246
  }
247
- return version
247
+ return result.data.manifestVersion
248
248
  }
249
249
 
250
250
  const appLine = (app: AppDto): string => `${app.id}\t${app.repoUrl}\t${app.defaultBranch}`
@@ -317,28 +317,13 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
317
317
  }
318
318
 
319
319
  const decodeIssueKeyResult = (value: unknown): IssueKeyResult => {
320
- if (typeof value !== 'object' || value === null) {
320
+ const result = issueKeyResultSchema.safeParse(value)
321
+ if (!result.success) {
321
322
  throw new Error('IAM returned an unreadable issueKey result')
322
323
  }
323
- const ok = Reflect.get(value, 'ok')
324
- if (ok === false) {
325
- const reason = Reflect.get(value, 'reason')
326
- return { ok: false, reason: isIssueKeyDenial(reason) ? reason : 'not_allowed' }
327
- }
328
- const token = Reflect.get(value, 'token')
329
- const id = Reflect.get(value, 'id')
330
- const principalId = Reflect.get(value, 'principalId')
331
- if (ok !== true || typeof token !== 'string' || typeof id !== 'string') {
332
- throw new Error('IAM returned an unreadable issueKey result')
333
- }
334
- return { ok: true, token, id, ...(typeof principalId === 'string' ? { principalId } : {}) }
324
+ return result.data
335
325
  }
336
326
 
337
- const ISSUE_KEY_DENIALS = ['missing_token', 'invalid_token', 'unknown_principal', 'disabled', 'not_allowed'] as const
338
-
339
- const isIssueKeyDenial = (value: unknown): value is (typeof ISSUE_KEY_DENIALS)[number] =>
340
- typeof value === 'string' && ISSUE_KEY_DENIALS.some((denial) => denial === value)
341
-
342
327
  const runRegister = async (flags: Flags, provider: string | undefined, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
343
328
  if (provider === undefined || provider === '') {
344
329
  throw new Error('--provider=<name> is required: it labels the envelope this registration carries.')
package/src/index.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/installation-contract'
3
+ import { BUILDER_USAGE, runBuilderCli } from '@fabrika/builder'
4
4
  import { authoredAppProvider } from '@fabrika/provider-contract'
5
+ import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/provider-contract/installation'
5
6
  import { resolve } from 'node:path'
6
7
  import { CONTROL_USAGE, runControlCli } from './control.js'
7
8
 
@@ -18,6 +19,7 @@ Usage:
18
19
  fabrika app build [--provider=zerops] --env=<env> [--config=<path>] [--output=<path>]
19
20
  fabrika namespace <plan|create|adopt|reconcile> --provider=zerops [provider options]
20
21
  fabrika control <key|apps|namespaces|register|deploy|runs> [options]
22
+ fabrika builder <init|next|advance|gate|ensure-daemon|induce|build> [options]
21
23
 
22
24
  For app commands, the provider is read from the config returned by the selected provider's defineApp().
23
25
  An explicit --provider is required only when no app config is available.
@@ -104,9 +106,9 @@ const selectedAppProvider = async (parsed: ParsedCommand): Promise<string> => {
104
106
 
105
107
  const installationModule = async (provider: string): Promise<unknown> => {
106
108
  const packageName = provider === 'cloudflare'
107
- ? '@fabrika/installation-cloudflare'
109
+ ? '@fabrika/provider-cloudflare/installation'
108
110
  : provider === 'zerops'
109
- ? '@fabrika/installation-zerops'
111
+ ? '@fabrika/provider-zerops/installation'
110
112
  : provider
111
113
  return import(packageName)
112
114
  }
@@ -171,8 +173,8 @@ const runNamespace = async (parsed: ParsedCommand): Promise<void> => {
171
173
  if (parsed.command === undefined) {
172
174
  throw new Error('Namespace command is required')
173
175
  }
174
- const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli')
175
- await runZeropsCli(['namespace', parsed.command, ...parsed.rest])
176
+ const { runZeropsNamespaceCli } = await import('./namespace.js')
177
+ await runZeropsNamespaceCli(parsed.command, parsed.rest)
176
178
  }
177
179
 
178
180
  export const runCli = async (argv: readonly string[]): Promise<void> => {
@@ -187,6 +189,15 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
187
189
  console.info(CONTROL_USAGE)
188
190
  return
189
191
  }
192
+ if (parsed.help && parsed.area === 'namespace') {
193
+ const { NAMESPACE_USAGE } = await import('./namespace.js')
194
+ console.info(NAMESPACE_USAGE)
195
+ return
196
+ }
197
+ if (parsed.help && parsed.area === 'builder') {
198
+ console.info(BUILDER_USAGE)
199
+ return
200
+ }
190
201
  if (parsed.help || parsed.area === undefined) {
191
202
  console.info(USAGE)
192
203
  return
@@ -207,6 +218,11 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
207
218
  await runControlCli(parsed.command, parsed.rest, parsed.provider)
208
219
  return
209
220
  }
221
+ if (parsed.area === 'builder') {
222
+ const exitCode = await runBuilderCli(parsed.command === undefined ? [] : [parsed.command, ...parsed.rest])
223
+ if (exitCode !== 0) process.exitCode = exitCode
224
+ return
225
+ }
210
226
  throw new Error(`Unknown command area: ${parsed.area}\n\n${USAGE}`)
211
227
  }
212
228
 
@@ -0,0 +1,221 @@
1
+ import { createRpcClient } from '@fabrika/app'
2
+ import type { AdoptDeploymentNamespaceRequest, ControlRpcContract, CreateDeploymentNamespaceRequest } from '@fabrika/control-contract'
3
+ import type { JsonValue, ProviderDeploymentNamespace, ProviderNamespacePlan } from '@fabrika/provider-contract'
4
+ import {
5
+ createZeropsNamespaceOperator,
6
+ decodeZeropsNamespaceProxySource,
7
+ parseZeropsCliArgs,
8
+ verifyZeropsNamespaceProxySource,
9
+ type ZeropsCliArgs,
10
+ type ZeropsNamespacePostgres,
11
+ zeropsNamespacePostgresSchema,
12
+ zeropsNamespaceTargetCodec,
13
+ } from '@fabrika/provider-zerops'
14
+ import { z } from 'zod'
15
+
16
+ export const NAMESPACE_USAGE = `fabrika namespace — Zerops deployment namespaces
17
+
18
+ Usage:
19
+ fabrika namespace plan --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options]
20
+ fabrika namespace create --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> [namespace options] [--control-url=<url>]
21
+ fabrika namespace adopt --provider=zerops --id=<id> --env=<env> --preset=<cheap|mid|full> --project-id=<id> [namespace options] [--control-url=<url>]
22
+ fabrika namespace reconcile --provider=zerops --id=<id> [--control-url=<url>]
23
+
24
+ Options:
25
+ --id=<id> Namespace id.
26
+ --env=<env> Environment.
27
+ --preset=<cheap|mid|full> Provider-owned namespace preset.
28
+ --exclusive-app=<id> App reserved by a full namespace.
29
+ --project-id=<id> Existing Zerops project id for adoption.
30
+ --project-name=<name> Zerops project name (default: namespace id).
31
+ --core-package=<tier> LIGHT or SERIOUS.
32
+ --public-access=<mode> custom-domain or zerops-subdomain.
33
+ --postgres-type=<type> Cheap-tier PostgreSQL type.
34
+ --postgres-profile=<profile> Cheap-tier PostgreSQL profile.
35
+ --control-url=<url> Control origin; or FABRIKA_CONTROL_URL.
36
+ -h, --help Show this help.
37
+
38
+ Mutating namespace commands read the Bearer credential from FABRIKA_CONTROL_TOKEN.
39
+ Plan/create/adopt require FABRIKA_ZEROPS_PROXY_SOURCE_JSON:
40
+ {"repository":{"owner":"...","name":"..."},"commitSha":"...","descriptor":{"path":"zerops.yaml","contents":"...","sha256":"..."}}
41
+ Reconcile uses the persisted namespace source.
42
+ `
43
+
44
+ export interface ZeropsNamespaceCommandDependencies {
45
+ readonly source: Readonly<Record<string, string | undefined>>
46
+ readonly fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>
47
+ readonly write: (value: string) => void
48
+ }
49
+
50
+ const required = (value: string | undefined, label: string): string => {
51
+ if (value === undefined || value.trim() === '') {
52
+ throw new Error(`${label} is required`)
53
+ }
54
+ return value.trim()
55
+ }
56
+
57
+ const postgres = (args: ZeropsCliArgs): ZeropsNamespacePostgres | undefined => {
58
+ const type = args.postgresType
59
+ const profile = args.postgresProfile
60
+ if (type === undefined && profile === undefined) return undefined
61
+ if (type === undefined) {
62
+ throw new Error('--postgres-type is required with --postgres-profile')
63
+ }
64
+ const result = zeropsNamespacePostgresSchema.safeParse({ type, profile })
65
+ if (result.success) return result.data
66
+ if (result.error.issues[0]?.path[0] === 'type') throw new Error('--postgres-type must be postgresql:ha@18 or postgresql:single@18')
67
+ throw new Error(`--postgres-profile ${profile} is not supported by ${type}`)
68
+ }
69
+
70
+ const planOptions = (args: ZeropsCliArgs): { [key: string]: JsonValue } | undefined => {
71
+ const values: { [key: string]: JsonValue } = {}
72
+ if (args.projectName !== undefined) values['projectName'] = required(args.projectName, '--project-name')
73
+ if (args.corePackage !== undefined) values['corePackage'] = required(args.corePackage, '--core-package')
74
+ if (args.publicAccess !== undefined) values['publicAccess'] = required(args.publicAccess, '--public-access')
75
+ const database = postgres(args)
76
+ if (database !== undefined) {
77
+ values['postgres'] = database.profile === undefined ? { type: database.type } : { type: database.type, profile: database.profile }
78
+ }
79
+ return Object.keys(values).length === 0 ? undefined : values
80
+ }
81
+
82
+ const namespacePlan = async (
83
+ args: ZeropsCliArgs,
84
+ source: Readonly<Record<string, string | undefined>>,
85
+ ): Promise<ProviderNamespacePlan> => {
86
+ // `FABRIKA_ZEROPS_*` because Zerops reserves the bare `ZEROPS_` prefix and refuses to store a custom
87
+ // variable using it (`userDataZeropsPrefixForbidden`).
88
+ const serialized = required(source['FABRIKA_ZEROPS_PROXY_SOURCE_JSON'], 'FABRIKA_ZEROPS_PROXY_SOURCE_JSON')
89
+ let value: unknown
90
+ try {
91
+ value = JSON.parse(serialized)
92
+ } catch {
93
+ throw new Error('FABRIKA_ZEROPS_PROXY_SOURCE_JSON must contain valid JSON')
94
+ }
95
+ const proxySource = decodeZeropsNamespaceProxySource(value)
96
+ await verifyZeropsNamespaceProxySource(proxySource)
97
+ const operator = createZeropsNamespaceOperator({ proxySource })
98
+ const options = planOptions(args)
99
+ return operator.plan({
100
+ id: required(args.namespaceId, '--id'),
101
+ env: required(args.env, '--env'),
102
+ preset: required(args.preset, '--preset'),
103
+ ...(args.exclusiveAppId === undefined ? {} : { exclusiveAppId: required(args.exclusiveAppId, '--exclusive-app') }),
104
+ ...(options === undefined ? {} : { options }),
105
+ })
106
+ }
107
+
108
+ const outputJson = (value: unknown): string => `${JSON.stringify(value, null, '\t')}\n`
109
+
110
+ const controlCoordinates = (
111
+ args: ZeropsCliArgs,
112
+ source: Readonly<Record<string, string | undefined>>,
113
+ ): { baseUrl: URL; token: string } => {
114
+ const value = required(args.controlUrl ?? source['FABRIKA_CONTROL_URL'], '--control-url or FABRIKA_CONTROL_URL')
115
+ const token = required(source['FABRIKA_CONTROL_TOKEN'], 'FABRIKA_CONTROL_TOKEN')
116
+ let baseUrl: URL
117
+ try {
118
+ baseUrl = new URL(value)
119
+ } catch {
120
+ throw new Error('--control-url or FABRIKA_CONTROL_URL must be an absolute URL')
121
+ }
122
+ if (baseUrl.protocol !== 'https:' && baseUrl.protocol !== 'http:') {
123
+ throw new Error('--control-url or FABRIKA_CONTROL_URL must use http or https')
124
+ }
125
+ return { baseUrl, token }
126
+ }
127
+
128
+ const controlClient = (
129
+ deps: ZeropsNamespaceCommandDependencies,
130
+ coordinates: { baseUrl: URL; token: string },
131
+ ) =>
132
+ createRpcClient<ControlRpcContract>({
133
+ baseUrl: new URL('/api/rpc', coordinates.baseUrl).href,
134
+ fetch: async (input, init) => {
135
+ const headers = new Headers(init?.headers)
136
+ headers.set('authorization', `Bearer ${coordinates.token}`)
137
+ const response = await deps.fetch(input, { ...init, headers, redirect: 'manual' })
138
+ if (!response.ok) {
139
+ const body: unknown = await response.clone().json().catch(() => null)
140
+ if (typeof body !== 'object' || body === null || !('error' in body)) {
141
+ return Response.json({ error: { type: 'transport', message: `Control API request failed (${response.status})` } }, { status: response.status })
142
+ }
143
+ }
144
+ return response
145
+ },
146
+ })
147
+
148
+ // Passthrough on purpose: the operator sees the whole namespace detail, this only checks it is one.
149
+ const namespaceResponseSchema = z.object({ id: z.string(), state: z.enum(['pending', 'provisioning', 'ready', 'failed']) }).passthrough()
150
+ const writeNamespace = (deps: ZeropsNamespaceCommandDependencies, result: unknown): void => {
151
+ const parsed = namespaceResponseSchema.safeParse(result)
152
+ if (!parsed.success) {
153
+ throw new Error('Control API returned an invalid namespace')
154
+ }
155
+ deps.write(outputJson(parsed.data))
156
+ }
157
+
158
+ const createBody = (namespace: ProviderDeploymentNamespace): CreateDeploymentNamespaceRequest => ({
159
+ id: namespace.id,
160
+ env: namespace.env,
161
+ ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
162
+ target: namespace.target,
163
+ })
164
+
165
+ const adoptBody = (namespace: ProviderDeploymentNamespace): AdoptDeploymentNamespaceRequest => ({
166
+ env: namespace.env,
167
+ ...(namespace.exclusiveAppId === undefined ? {} : { exclusiveAppId: namespace.exclusiveAppId }),
168
+ target: namespace.target,
169
+ })
170
+
171
+ /** Execute one namespace command. All command inputs are validated before the first fetch. */
172
+ export const runZeropsNamespaceCommand = async (
173
+ args: ZeropsCliArgs,
174
+ deps: ZeropsNamespaceCommandDependencies,
175
+ ): Promise<void> => {
176
+ const subcommand = required(args.subcommand, 'namespace command')
177
+ if (subcommand === 'plan') {
178
+ deps.write(outputJson(await namespacePlan(args, deps.source)))
179
+ return
180
+ }
181
+ if (subcommand === 'reconcile') {
182
+ const id = required(args.namespaceId, '--id')
183
+ const control = controlCoordinates(args, deps.source)
184
+ writeNamespace(deps, await controlClient(deps, control).namespaces.reconcile({ namespaceId: id }))
185
+ return
186
+ }
187
+ if (subcommand !== 'create' && subcommand !== 'adopt') {
188
+ throw new Error(`Unknown namespace command: ${subcommand}`)
189
+ }
190
+
191
+ const planned = await namespacePlan(args, deps.source)
192
+ const control = controlCoordinates(args, deps.source)
193
+ if (subcommand === 'create') {
194
+ writeNamespace(deps, await controlClient(deps, control).namespaces.create(createBody(planned.namespace)))
195
+ return
196
+ }
197
+
198
+ const projectId = required(args.projectId, '--project-id')
199
+ const decoded = zeropsNamespaceTargetCodec.decode(planned.namespace.target.payload)
200
+ const namespace: ProviderDeploymentNamespace = {
201
+ ...planned.namespace,
202
+ target: {
203
+ provider: 'zerops',
204
+ version: zeropsNamespaceTargetCodec.version,
205
+ payload: zeropsNamespaceTargetCodec.encode({
206
+ ...decoded,
207
+ managed: false,
208
+ projectId,
209
+ ready: false,
210
+ }),
211
+ },
212
+ }
213
+ writeNamespace(deps, await controlClient(deps, control).namespaces.adopt({ namespaceId: namespace.id, namespace: adoptBody(namespace) }))
214
+ }
215
+
216
+ export const runZeropsNamespaceCli = (subcommand: string, argv: readonly string[]): Promise<void> =>
217
+ runZeropsNamespaceCommand(parseZeropsCliArgs(['namespace', subcommand, ...argv]), {
218
+ source: process.env,
219
+ fetch: globalThis.fetch,
220
+ write: (value) => console.info(value.trimEnd()),
221
+ })