@fabrika/cli 0.3.3 → 0.4.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 +25 -8
- package/src/app-dev-outside.ts +120 -0
- package/src/app-dev-seed.ts +119 -0
- package/src/app-dev-ui.ts +586 -0
- package/src/app-dev.ts +589 -0
- package/src/connect.ts +249 -0
- package/src/control.ts +106 -22
- package/src/db.ts +296 -0
- package/src/index.ts +140 -11
- package/src/job.ts +81 -0
- package/src/junit.ts +37 -0
package/src/connect.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { CONNECT_LIMITS, ContractError, parseExportDescription, snapshotNames, snapshotSource } from '@fabrika/app/contract'
|
|
2
|
+
import { isJsonMediaType, readBoundedBytes } from '@fabrika/app/implement'
|
|
3
|
+
import { API_KEY_PREFIX, type ExportDescription } from '@fabrika/auth-core'
|
|
4
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const KEY_VARIABLE = 'FABRIKA_CONTROL_KEY'
|
|
8
|
+
const URL_VARIABLE = 'FABRIKA_CONTROL_URL'
|
|
9
|
+
const TARGET = /^([a-z0-9][a-z0-9-]*)\/([A-Za-z][A-Za-z0-9_]*)@([1-9][0-9]*)$/
|
|
10
|
+
const APP_ID = /^[a-z0-9][a-z0-9-]*$/
|
|
11
|
+
const ENV_NAME = /^[a-z0-9][a-z0-9-]*$/
|
|
12
|
+
const TIMEOUT_MS = 10_000
|
|
13
|
+
|
|
14
|
+
export const CONNECT_USAGE = `fabrika connect — vendor another application's export
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
fabrika connect add <app>/<export>@<version> --consumer=<this app's id> --env=<env> [--url=<control origin>]
|
|
18
|
+
Write fabrika/connect/<app>.<export>.v<version>.ts.
|
|
19
|
+
fabrika connect pull <app>/<export>@<version> --consumer=<this app's id> --env=<env> [--url=<control origin>]
|
|
20
|
+
Rewrite that snapshot from what the owner's environment approved now.
|
|
21
|
+
|
|
22
|
+
Run from the application root. Both read the export the owner's environment <env> approved for the consumer from
|
|
23
|
+
Control (${URL_VARIABLE} or --url), with a machine key that holds deploy.read on the consumer, read from
|
|
24
|
+
${KEY_VARIABLE} in the environment only. The origin is https; plain http only for localhost. \`add\` refuses an
|
|
25
|
+
existing snapshot and prints what to add to src/app-kit.ts and to the endpoints that call it; \`pull\` refuses a missing one
|
|
26
|
+
and says whether the digest changed. The platform writes each import's address and key when it deploys the consumer.
|
|
27
|
+
`
|
|
28
|
+
|
|
29
|
+
export interface ConnectCommandDependencies {
|
|
30
|
+
/** The application root. */
|
|
31
|
+
readonly cwd: string
|
|
32
|
+
readonly source: Readonly<Record<string, string | undefined>>
|
|
33
|
+
readonly fetch: (request: Request) => Promise<Response>
|
|
34
|
+
/** Data: the snapshot's path. */
|
|
35
|
+
readonly write: (line: string) => void
|
|
36
|
+
/** Guidance for the person running it. */
|
|
37
|
+
readonly note: (line: string) => void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Target {
|
|
41
|
+
readonly app: string
|
|
42
|
+
readonly export: string
|
|
43
|
+
readonly version: number
|
|
44
|
+
readonly consumer: string
|
|
45
|
+
readonly env: string
|
|
46
|
+
/** Control's origin. */
|
|
47
|
+
readonly control: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const LOCAL_HOST = /^(?:localhost|127\.0\.0\.1|.+\.localhost)$/
|
|
51
|
+
const OPTIONS = ['--consumer=', '--env=', '--url=']
|
|
52
|
+
|
|
53
|
+
const option = (options: readonly string[], name: string): string | undefined =>
|
|
54
|
+
options.find((candidate) => candidate.startsWith(`--${name}=`))?.slice(`--${name}=`.length)
|
|
55
|
+
|
|
56
|
+
function parseTarget(command: string, argv: readonly string[], source: ConnectCommandDependencies['source']): Target {
|
|
57
|
+
const positional = argv.filter((arg) => !arg.startsWith('--'))
|
|
58
|
+
const options = argv.filter((arg) => arg.startsWith('--'))
|
|
59
|
+
const [target, ...extra] = positional
|
|
60
|
+
const matched = target === undefined ? null : TARGET.exec(target)
|
|
61
|
+
if (matched === null || extra.length > 0) {
|
|
62
|
+
throw new Error(`connect ${command} needs one <app>/<export>@<version>\n\n${CONNECT_USAGE}`)
|
|
63
|
+
}
|
|
64
|
+
const unknown = options.find((candidate) => !OPTIONS.some((known) => candidate.startsWith(known)))
|
|
65
|
+
if (unknown !== undefined) {
|
|
66
|
+
throw new Error(`connect ${command} takes no option ${unknown.split('=')[0]}\n\n${CONNECT_USAGE}`)
|
|
67
|
+
}
|
|
68
|
+
const consumer = option(options, 'consumer') ?? ''
|
|
69
|
+
const env = option(options, 'env') ?? ''
|
|
70
|
+
if (!APP_ID.test(consumer) || !ENV_NAME.test(env)) {
|
|
71
|
+
throw new Error(`connect ${command} needs --consumer=<this application's id> and --env=<environment>`)
|
|
72
|
+
}
|
|
73
|
+
const raw = option(options, 'url') ?? source[URL_VARIABLE]?.trim() ?? ''
|
|
74
|
+
let url: URL
|
|
75
|
+
try {
|
|
76
|
+
url = new URL(raw)
|
|
77
|
+
} catch {
|
|
78
|
+
throw new Error(`connect ${command} needs Control's origin: pass --url=<origin> or set ${URL_VARIABLE}`)
|
|
79
|
+
}
|
|
80
|
+
const secure = url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOST.test(url.hostname))
|
|
81
|
+
if (!secure || url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '') {
|
|
82
|
+
throw new Error(`connect ${command}: Control's origin must be an https origin without a path or credentials (plain http only for localhost)`)
|
|
83
|
+
}
|
|
84
|
+
const [, app = '', name = '', version = ''] = matched
|
|
85
|
+
return { app, export: name, version: Number(version), consumer, env, control: url.origin }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function controlKey(source: ConnectCommandDependencies['source']): string {
|
|
89
|
+
const key = source[KEY_VARIABLE]?.trim() ?? ''
|
|
90
|
+
if (!key.startsWith(API_KEY_PREFIX)) {
|
|
91
|
+
throw new Error(`${KEY_VARIABLE} must hold a ${API_KEY_PREFIX} machine key that holds deploy.read on the consumer`)
|
|
92
|
+
}
|
|
93
|
+
return key
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The description the owner's environment approved, as Control answers `connectors.describe`. Every failure is a fixed
|
|
98
|
+
* diagnostic: a redirect is never followed, a body is read under `CONNECT_LIMITS.maxDescriptionBytes` and only as
|
|
99
|
+
* `application/json`, and nothing of the answer is quoted, because the owner's contract wrote it.
|
|
100
|
+
*/
|
|
101
|
+
async function fetchDescription(target: Target, key: string, deps: ConnectCommandDependencies): Promise<ExportDescription> {
|
|
102
|
+
const named = `${target.app}/${target.export}@${target.version}`
|
|
103
|
+
const origin = target.control
|
|
104
|
+
const signal = AbortSignal.timeout(TIMEOUT_MS)
|
|
105
|
+
const input = { consumer: target.consumer, env: target.env, app: target.app, export: target.export, version: target.version }
|
|
106
|
+
let response: Response
|
|
107
|
+
try {
|
|
108
|
+
response = await deps.fetch(
|
|
109
|
+
new Request(new URL('/api/rpc', origin), {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
|
|
112
|
+
body: JSON.stringify({ method: 'connectors.describe', input }),
|
|
113
|
+
signal,
|
|
114
|
+
redirect: 'manual',
|
|
115
|
+
}),
|
|
116
|
+
)
|
|
117
|
+
} catch {
|
|
118
|
+
throw new Error(`${origin} could not be reached for ${named}`)
|
|
119
|
+
}
|
|
120
|
+
if (response.status >= 300 && response.status < 400) {
|
|
121
|
+
await response.body?.cancel().catch(() => {})
|
|
122
|
+
throw new Error(`${origin} answered ${response.status} for ${named}, a redirect, which fabrika connect never follows; pass Control's own origin`)
|
|
123
|
+
}
|
|
124
|
+
if (response.status === 401 || response.status === 403) {
|
|
125
|
+
await response.body?.cancel().catch(() => {})
|
|
126
|
+
throw new Error(`${origin} refused ${KEY_VARIABLE} for ${named} (${response.status}); the key must hold deploy.read on ${target.consumer}`)
|
|
127
|
+
}
|
|
128
|
+
if (response.status === 404) {
|
|
129
|
+
await response.body?.cancel().catch(() => {})
|
|
130
|
+
throw new Error(`${target.app}@${target.env} has approved no export ${target.export}@${target.version} for ${target.consumer}`)
|
|
131
|
+
}
|
|
132
|
+
if (response.status !== 200) {
|
|
133
|
+
await response.body?.cancel().catch(() => {})
|
|
134
|
+
throw new Error(`${origin} answered ${response.status} for ${named}`)
|
|
135
|
+
}
|
|
136
|
+
if (!isJsonMediaType(response.headers.get('Content-Type'))) {
|
|
137
|
+
await response.body?.cancel().catch(() => {})
|
|
138
|
+
throw new Error(`${origin} answered ${named} with no application/json body`)
|
|
139
|
+
}
|
|
140
|
+
let bytes: Uint8Array | null
|
|
141
|
+
try {
|
|
142
|
+
bytes = await readBoundedBytes(response.body, {
|
|
143
|
+
maxBytes: CONNECT_LIMITS.maxDescriptionBytes,
|
|
144
|
+
declaredLength: response.headers.get('Content-Length'),
|
|
145
|
+
signal,
|
|
146
|
+
})
|
|
147
|
+
} catch {
|
|
148
|
+
throw new Error(`${origin} did not finish its description of ${named} in time`)
|
|
149
|
+
}
|
|
150
|
+
if (bytes === null) {
|
|
151
|
+
throw new Error(`${origin} answered ${named} with a description larger than ${CONNECT_LIMITS.maxDescriptionBytes} bytes`)
|
|
152
|
+
}
|
|
153
|
+
const text = new TextDecoder().decode(bytes)
|
|
154
|
+
// A description that quotes the key would write the credential into a committed file.
|
|
155
|
+
if (text.includes(key)) {
|
|
156
|
+
throw new Error(`${origin} answered ${named} with a description that contains ${KEY_VARIABLE}; nothing was written`)
|
|
157
|
+
}
|
|
158
|
+
let body: unknown
|
|
159
|
+
try {
|
|
160
|
+
body = JSON.parse(text)
|
|
161
|
+
} catch {
|
|
162
|
+
throw new Error(`${origin} answered ${named} with no JSON`)
|
|
163
|
+
}
|
|
164
|
+
let description: ExportDescription
|
|
165
|
+
try {
|
|
166
|
+
description = parseExportDescription(typeof body === 'object' && body !== null && 'result' in body ? body.result : undefined)
|
|
167
|
+
} catch (error) {
|
|
168
|
+
throw new Error(`${origin} served no valid description of ${named}${error instanceof ContractError ? `: ${error.problems.join('; ')}` : ''}`)
|
|
169
|
+
}
|
|
170
|
+
if (description.app !== target.app || description.export !== target.export || description.version !== target.version) {
|
|
171
|
+
throw new Error(`${origin} described another export than ${named}`)
|
|
172
|
+
}
|
|
173
|
+
return description
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function contractHint(description: ExportDescription): string[] {
|
|
177
|
+
const names = snapshotNames(description.app, description.export, description.version)
|
|
178
|
+
const module = `./${names.file.replace(/\.ts$/, '')}`
|
|
179
|
+
const procedures = Object.keys(description.procedures).map((path) => `'${path}'`).join(', ')
|
|
180
|
+
return [
|
|
181
|
+
`Add to defineApp in src/app-kit.ts:`,
|
|
182
|
+
` import { ${names.snapshot} } from '.${module}'`,
|
|
183
|
+
` defineApp(vocabulary, tables, { imports: { <name>: { snapshot: ${names.snapshot}, procedures: [${procedures}] } } })`,
|
|
184
|
+
`and to each endpoint that calls it: connect: ['<name>'], then ctx.connect.<name>.<procedure>(input) in its handler.`,
|
|
185
|
+
`The platform writes the owner's address and the key when it deploys this application; nothing is set by hand.`,
|
|
186
|
+
]
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function add(argv: readonly string[], deps: ConnectCommandDependencies): Promise<void> {
|
|
190
|
+
const target = parseTarget('add', argv, deps.source)
|
|
191
|
+
const description = await fetchDescription(target, controlKey(deps.source), deps)
|
|
192
|
+
const { file } = snapshotNames(target.app, target.export, target.version)
|
|
193
|
+
const path = join(deps.cwd, file)
|
|
194
|
+
await mkdir(dirname(path), { recursive: true })
|
|
195
|
+
try {
|
|
196
|
+
await writeFile(path, snapshotSource(description), { flag: 'wx' })
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error(`connect add: ${file} exists; run fabrika connect pull to rewrite it`)
|
|
199
|
+
}
|
|
200
|
+
deps.write(`${file}\n`)
|
|
201
|
+
for (const line of contractHint(description)) {
|
|
202
|
+
deps.note(`${line}\n`)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function pull(argv: readonly string[], deps: ConnectCommandDependencies): Promise<void> {
|
|
207
|
+
const target = parseTarget('pull', argv, deps.source)
|
|
208
|
+
const { file } = snapshotNames(target.app, target.export, target.version)
|
|
209
|
+
const path = join(deps.cwd, file)
|
|
210
|
+
const previous = await readFile(path, 'utf8').catch(() => null)
|
|
211
|
+
if (previous === null) {
|
|
212
|
+
throw new Error(`connect pull: ${file} does not exist; run fabrika connect add first`)
|
|
213
|
+
}
|
|
214
|
+
const description = await fetchDescription(target, controlKey(deps.source), deps)
|
|
215
|
+
const source = snapshotSource(description)
|
|
216
|
+
await writeFile(path, source)
|
|
217
|
+
deps.write(`${file}\n`)
|
|
218
|
+
deps.note(
|
|
219
|
+
previous.includes(description.digest)
|
|
220
|
+
? `the export is unchanged (${description.digest})\n`
|
|
221
|
+
: `the export changed; its digest is now ${description.digest}, which the contract's import reads from the snapshot\n`,
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Every line and error leaves with the Control key cut out. No diagnostic quotes the answer; this is defence in depth
|
|
227
|
+
* against an owner contract that names a procedure after a key.
|
|
228
|
+
*/
|
|
229
|
+
export const runConnectCommand = async (command: string | undefined, argv: readonly string[], deps: ConnectCommandDependencies): Promise<void> => {
|
|
230
|
+
const key = deps.source[KEY_VARIABLE]?.trim() ?? ''
|
|
231
|
+
const redact = (text: string): string => (key === '' ? text : text.replaceAll(key, '[control key]'))
|
|
232
|
+
const redacted: ConnectCommandDependencies = { ...deps, write: (line) => deps.write(redact(line)), note: (line) => deps.note(redact(line)) }
|
|
233
|
+
try {
|
|
234
|
+
if (command === 'add') return await add(argv, redacted)
|
|
235
|
+
if (command === 'pull') return await pull(argv, redacted)
|
|
236
|
+
} catch (error) {
|
|
237
|
+
throw new Error(redact(error instanceof Error ? error.message : 'fabrika connect failed'))
|
|
238
|
+
}
|
|
239
|
+
throw new Error(`Unknown connect command: ${command ?? '(missing)'}\n\n${CONNECT_USAGE}`)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export const runConnectCli = (command: string | undefined, argv: readonly string[]): Promise<void> =>
|
|
243
|
+
runConnectCommand(command, argv, {
|
|
244
|
+
cwd: process.cwd(),
|
|
245
|
+
source: process.env,
|
|
246
|
+
fetch: (request) => fetch(request),
|
|
247
|
+
write: (line) => process.stdout.write(line),
|
|
248
|
+
note: (line) => process.stderr.write(line),
|
|
249
|
+
})
|
package/src/control.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// `--json` prints the procedure's result verbatim so a caller never parses a table.
|
|
11
11
|
|
|
12
12
|
import { createRpcClient, RpcError } from '@fabrika/app'
|
|
13
|
-
import type
|
|
13
|
+
import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
|
|
14
14
|
import type {
|
|
15
15
|
AppDto,
|
|
16
16
|
ControlRpcContract,
|
|
@@ -22,6 +22,7 @@ import type {
|
|
|
22
22
|
PutAppEnvRequest,
|
|
23
23
|
PutAppVarRequest,
|
|
24
24
|
RegisterAppRequest,
|
|
25
|
+
RegisterAppResponse,
|
|
25
26
|
RunDto,
|
|
26
27
|
} from '@fabrika/control-contract'
|
|
27
28
|
import { z } from 'zod'
|
|
@@ -46,7 +47,7 @@ const issueKeyResultSchema = z.union([
|
|
|
46
47
|
const USAGE = `fabrika control — operate the Delivery control plane
|
|
47
48
|
|
|
48
49
|
Usage:
|
|
49
|
-
fabrika control key issue --label=<name> --permissions=<a,b,c>
|
|
50
|
+
fabrika control key issue --label=<name> --permissions=<a,b,c> --expires-in=<seconds> [--iam-url=<origin>]
|
|
50
51
|
fabrika control apps list
|
|
51
52
|
fabrika control apps get --app=<id>
|
|
52
53
|
fabrika control apps environments list --app=<id>
|
|
@@ -113,7 +114,8 @@ process listing:
|
|
|
113
114
|
|
|
114
115
|
\`key issue\` mints that credential and therefore authenticates differently — it presents the
|
|
115
116
|
installation's IAM RPC key as transport authentication and its provisioning key as the ISSUING
|
|
116
|
-
credential.
|
|
117
|
+
credential. Every key expires: \`--expires-in\` is required and at most 2592000 (30 days). Both
|
|
118
|
+
credentials are read from the environment only:
|
|
117
119
|
|
|
118
120
|
FABRIKA_IAM_RPC_URL required IAM's PUBLIC origin, or --iam-url
|
|
119
121
|
FABRIKA_IAM_RPC_KEY required the installation's IAM RPC key
|
|
@@ -226,14 +228,18 @@ const readJsonFile = async (path: string): Promise<JsonValue> => {
|
|
|
226
228
|
if (!(await file.exists())) {
|
|
227
229
|
throw new Error(`No such file: ${path}`)
|
|
228
230
|
}
|
|
229
|
-
|
|
231
|
+
return parseJsonText(await file.text(), path)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** `label` names the source in errors: a file path, or what produced an in-memory manifest. */
|
|
235
|
+
const parseJsonText = (text: string, label: string): JsonValue => {
|
|
230
236
|
try {
|
|
231
237
|
const parsed: unknown = JSON.parse(text)
|
|
232
238
|
const result = jsonValueSchema.safeParse(parsed)
|
|
233
|
-
if (!result.success) throw new Error(`${
|
|
239
|
+
if (!result.success) throw new Error(`${label} contains a value JSON cannot carry`)
|
|
234
240
|
return result.data
|
|
235
241
|
} catch (error) {
|
|
236
|
-
throw error instanceof SyntaxError ? new Error(`${
|
|
242
|
+
throw error instanceof SyntaxError ? new Error(`${label} is not valid JSON`) : error
|
|
237
243
|
}
|
|
238
244
|
}
|
|
239
245
|
|
|
@@ -287,14 +293,17 @@ const runKeyIssue = async (flags: Flags, env: Readonly<Record<string, string | u
|
|
|
287
293
|
if (permissions.length === 0) {
|
|
288
294
|
throw new Error('--permissions needs at least one action')
|
|
289
295
|
}
|
|
290
|
-
const expiresIn =
|
|
296
|
+
const expiresIn = positiveInteger(required(flags, 'expires-in'), 'expires-in')
|
|
297
|
+
if (expiresIn > MAX_KEY_LIFETIME_SECONDS) {
|
|
298
|
+
throw new Error(`--expires-in must be at most ${MAX_KEY_LIFETIME_SECONDS} seconds (30 days): IAM issues no longer-lived key`)
|
|
299
|
+
}
|
|
291
300
|
const body: IssueKeyInput = {
|
|
292
301
|
app: env['FABRIKA_CONTROL_APP_ID']?.trim() || DEFAULT_CONTROL_APP_ID,
|
|
293
302
|
credential: secret('FABRIKA_IAM_PROVISIONING_KEY', env),
|
|
294
303
|
requestId: crypto.randomUUID(),
|
|
295
304
|
service: { label: required(flags, 'label'), permissions },
|
|
296
305
|
label: required(flags, 'label'),
|
|
297
|
-
|
|
306
|
+
expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
|
|
298
307
|
}
|
|
299
308
|
const base = origin(flags, 'iam-url', 'FABRIKA_IAM_RPC_URL', env, 'IAM')
|
|
300
309
|
const response = await fetch(`${base}/rpc/issueKey`, {
|
|
@@ -327,15 +336,12 @@ const decodeIssueKeyResult = (value: unknown): IssueKeyResult => {
|
|
|
327
336
|
return result.data
|
|
328
337
|
}
|
|
329
338
|
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
// The envelope's version is the manifest's own, never a literal: `fabrika app build` writes the
|
|
337
|
-
// version its provider's codec accepts, and a hardcoded one goes stale the moment that codec moves.
|
|
338
|
-
const version = manifestVersion(manifest, manifestPath)
|
|
339
|
+
const registrationLine = (result: RegisterAppResponse): string => `${result.app.id}\t${result.env.env}\t${result.env.provider}`
|
|
340
|
+
|
|
341
|
+
/** Everything a registration carries except the manifest, read from flags before any manifest exists. */
|
|
342
|
+
type RegistrationInputs = Omit<RegisterAppRequest, 'target' | 'artifact'>
|
|
343
|
+
|
|
344
|
+
const registrationInputs = (flags: Flags): RegistrationInputs => {
|
|
339
345
|
const installationId = optional(flags, 'installation-id')
|
|
340
346
|
// Three states, because the registry has three: absent resolves from the connected GitHub App,
|
|
341
347
|
// `none` is the anonymous public-repository path, and a number names one installation outright.
|
|
@@ -344,13 +350,10 @@ const runRegister = async (flags: Flags, provider: string | undefined, env: Read
|
|
|
344
350
|
const publicOrigin = optional(flags, 'public-origin')
|
|
345
351
|
const triggerRef = optional(flags, 'trigger-ref')
|
|
346
352
|
const namespaceId = optional(flags, 'namespace')
|
|
347
|
-
|
|
353
|
+
return {
|
|
348
354
|
id: required(flags, 'app'),
|
|
349
355
|
repoUrl: required(flags, 'repo'),
|
|
350
356
|
env: required(flags, 'env'),
|
|
351
|
-
// An empty placeholder: registration DISCOVERS the real target from the manifest and replaces this.
|
|
352
|
-
target: { provider, version, payload: {} },
|
|
353
|
-
artifact: { provider, version, payload: manifest },
|
|
354
357
|
...(installationId === undefined
|
|
355
358
|
// Blank → resolve from the installed GitHub App, which is what the console's empty field means.
|
|
356
359
|
? { resolveInstallationId: true }
|
|
@@ -362,8 +365,89 @@ const runRegister = async (flags: Flags, provider: string | undefined, env: Read
|
|
|
362
365
|
...(triggerRef === undefined ? {} : { triggerRef }),
|
|
363
366
|
...(namespaceId === undefined ? {} : { namespaceId }),
|
|
364
367
|
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The one request both `control register` and `app register` send, so the two cannot differ on the wire. */
|
|
371
|
+
const registrationRequest = (inputs: RegistrationInputs, provider: string, manifest: JsonValue, label: string): RegisterAppRequest => {
|
|
372
|
+
// The envelope's version is the manifest's own, never a literal: `fabrika app build` writes the
|
|
373
|
+
// version its provider's codec accepts, and a hardcoded one goes stale the moment that codec moves.
|
|
374
|
+
const version = manifestVersion(manifest, label)
|
|
375
|
+
const { id, repoUrl, env, ...placement } = inputs
|
|
376
|
+
return {
|
|
377
|
+
id,
|
|
378
|
+
repoUrl,
|
|
379
|
+
env,
|
|
380
|
+
// An empty placeholder: registration DISCOVERS the real target from the manifest and replaces this.
|
|
381
|
+
target: { provider, version, payload: {} },
|
|
382
|
+
artifact: { provider, version, payload: manifest },
|
|
383
|
+
...placement,
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const runRegister = async (flags: Flags, provider: string | undefined, env: Readonly<Record<string, string | undefined>>): Promise<void> => {
|
|
388
|
+
if (provider === undefined || provider === '') {
|
|
389
|
+
throw new Error('--provider=<name> is required: it labels the envelope this registration carries.')
|
|
390
|
+
}
|
|
391
|
+
const manifestPath = required(flags, 'manifest')
|
|
392
|
+
const manifest = await readJsonFile(manifestPath)
|
|
393
|
+
const body = registrationRequest(registrationInputs(flags), provider, manifest, manifestPath)
|
|
365
394
|
const result = await controlClient(flags, env).register(body)
|
|
366
|
-
emit(flags, result, () =>
|
|
395
|
+
emit(flags, result, () => registrationLine(result))
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** The exact text `app build` would write, and the provider whose envelope carries it. */
|
|
399
|
+
export interface CompiledManifest {
|
|
400
|
+
readonly provider: string
|
|
401
|
+
readonly text: string
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Resolves the app's provider and compiles its manifest for one environment; both run the app's own code. */
|
|
405
|
+
export type ManifestTextCompiler = (environment: string) => Promise<CompiledManifest>
|
|
406
|
+
|
|
407
|
+
const IN_MEMORY_MANIFEST = 'the compiled manifest'
|
|
408
|
+
|
|
409
|
+
/** The compile runs repository code that can read the environment, so its message may quote the key. */
|
|
410
|
+
const failureMessage = (error: unknown, controlKey: string): string => {
|
|
411
|
+
const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
|
|
412
|
+
return message.replaceAll(controlKey, '[FABRIKA_CONTROL_KEY]')
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* `fabrika app register`: compile in memory, then send the SAME request `control register` sends for
|
|
417
|
+
* that manifest read from disk. Inputs, the control origin and the credential are checked before the
|
|
418
|
+
* compile; nothing is written locally in either phase.
|
|
419
|
+
*/
|
|
420
|
+
export const registerCompiledManifest = async (
|
|
421
|
+
argv: readonly string[],
|
|
422
|
+
compile: ManifestTextCompiler,
|
|
423
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
424
|
+
): Promise<void> => {
|
|
425
|
+
const flags = parseControlFlags(argv)
|
|
426
|
+
for (const refused of ['manifest', 'output']) {
|
|
427
|
+
if (flags.values.has(refused)) {
|
|
428
|
+
throw new Error(
|
|
429
|
+
`\`app register\` compiles the manifest in memory and takes no --${refused}; use \`control register --manifest=<path>\` for a built file.`,
|
|
430
|
+
)
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const inputs = registrationInputs(flags)
|
|
434
|
+
const client = controlClient(flags, env)
|
|
435
|
+
const controlKey = secret('FABRIKA_CONTROL_KEY', env)
|
|
436
|
+
let body: RegisterAppRequest
|
|
437
|
+
try {
|
|
438
|
+
const compiled = await compile(inputs.env)
|
|
439
|
+
const manifest = parseJsonText(compiled.text, IN_MEMORY_MANIFEST)
|
|
440
|
+
body = registrationRequest(inputs, compiled.provider, manifest, IN_MEMORY_MANIFEST)
|
|
441
|
+
} catch (error) {
|
|
442
|
+
throw new Error(`Compile phase failed; nothing was registered. ${failureMessage(error, controlKey)}`)
|
|
443
|
+
}
|
|
444
|
+
let result: RegisterAppResponse
|
|
445
|
+
try {
|
|
446
|
+
result = await client.register(body)
|
|
447
|
+
} catch (error) {
|
|
448
|
+
throw new Error(`Register phase failed after a successful compile; no manifest file was written. ${failureMessage(error, controlKey)}`)
|
|
449
|
+
}
|
|
450
|
+
emit(flags, result, () => registrationLine(result))
|
|
367
451
|
}
|
|
368
452
|
|
|
369
453
|
/**
|