@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/src/app-dev.ts ADDED
@@ -0,0 +1,589 @@
1
+ // `fabrika app dev`: a contract application served through its test kit on a loopback port, to click through its
2
+ // screens. The kit is the whole server: production's proxy decision, the stand-in IAM, the real `boot`, the SPAs from
3
+ // their build directories; Postgres is a throwaway schema of the tests' database. A seed module fills it through the
4
+ // endpoints first. A caller picker chooses who the browser is; a cookie keeps the choice, and the kit's own session
5
+ // never leaves the process. Every SPA page gets the dev toolbar, which switches the caller without leaving the page.
6
+
7
+ import { CONTRACT_FILE, IMPLEMENTATION_FILE } from '@fabrika/app/build'
8
+ import { implementationAt } from '@fabrika/app/bun'
9
+ import type { AnyContract } from '@fabrika/app/contract'
10
+ import { BootError, type ContractImplementation } from '@fabrika/app/implement'
11
+ import { DEV_OUTBOX_ORIGIN, type DevKit, devKit, type DevOutside, type LabelledTestCaller, type TestCaller } from '@fabrika/app/testing'
12
+ import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
13
+ import { PostgresMigrationError } from '@fabrika/platform-node'
14
+ import { MemoryFileObjects } from '@fabrika/platform/testing'
15
+ import { existsSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+ import { z } from 'zod/v4'
18
+ import { DEV_ENV_FILE, DevEnvProblem, devOutbox, mailHeadOf, readDevEnv, shownBody } from './app-dev-outside'
19
+ import { DEFAULT_SEED, importSeed, isLocalPath, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
20
+ import {
21
+ type Badge,
22
+ type CurrentView,
23
+ type DevView,
24
+ type MailView,
25
+ noticePage,
26
+ pickerPage,
27
+ type RoleView,
28
+ stringsOf,
29
+ toolbarScript,
30
+ toolbarState,
31
+ withToolbar,
32
+ } from './app-dev-ui'
33
+
34
+ export const APP_DEV_USAGE = `fabrika app dev — the application on a local port, to click through its screens
35
+
36
+ Usage:
37
+ fabrika app dev [--port=<n>] [--host=<loopback address>] [--seed=<module>]
38
+
39
+ Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
40
+ the kit's stand-in IAM, each SPA from its built directory (run the SPA build first; an unbuilt one is an empty page),
41
+ and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit.
42
+ The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
43
+ receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
44
+ Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
45
+ mail IAM sent and the requests the application sent to ${DEV_OUTBOX_ORIGIN}, the dev outbox. A form's challenge
46
+ passes. The application's own variables come from ${DEV_ENV_FILE} (NAME=value lines) over the environment. What the
47
+ seed or a job's handler throws is printed with its stack. It listens on 127.0.0.1 (or ::1, localhost) only, port
48
+ 3000 unless --port says otherwise (0 picks a free one), and prints the address it serves.
49
+ `
50
+
51
+ const LOOPBACK: ReadonlySet<string> = new Set(['127.0.0.1', '::1', 'localhost'])
52
+ const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(['127.0.0.1', '[::1]', 'localhost'])
53
+ const PICKER_PATH = '/__fabrika/dev'
54
+ const CHOOSE_PATH = '/__fabrika/dev/as'
55
+ const ACCEPT_PATH = '/__fabrika/dev/accept'
56
+ const STATE_PATH = '/__fabrika/dev/state'
57
+ const OUTBOX_PATH = '/__fabrika/dev/outbox/'
58
+ const TOOLBAR_PATH = '/__fabrika/dev/toolbar.js'
59
+ const CHOICE_COOKIE = 'fabrika-dev-as'
60
+ const MAX_SCOPE_VALUE = 200
61
+
62
+ /** What `app dev`'s own pages answer with: nothing runs there but the toolbar, which is a separate response. */
63
+ const PAGE_HEADERS = {
64
+ 'Content-Type': 'text/html; charset=utf-8',
65
+ 'Cache-Control': 'no-store',
66
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
67
+ 'X-Content-Type-Options': 'nosniff',
68
+ 'Referrer-Policy': 'no-referrer',
69
+ }
70
+
71
+ /** A refusal of `app dev` itself, whose message names nothing of the environment. */
72
+ export class AppDevError extends Error {
73
+ override readonly name = 'AppDevError'
74
+ }
75
+
76
+ /**
77
+ * What of a startup failure reaches the terminal: the message of `app dev`'s own refusal (the seed's own throw, with its
78
+ * stack, included), of the seed's answer, of `dev/dev.env`, of the framework's boot and of the migration runner;
79
+ * anything else (an application module, a driver, a dependency `deps` built) may carry a credential, so it is a fixed
80
+ * code.
81
+ */
82
+ export function startupFailure(error: unknown): Error {
83
+ if (
84
+ error instanceof AppDevError || error instanceof SeedProblem || error instanceof DevEnvProblem || error instanceof BootError
85
+ || error instanceof PostgresMigrationError
86
+ ) {
87
+ return new Error(error.message)
88
+ }
89
+ return new Error('app dev could not start: start_failed (the error is withheld: it may contain a credential)')
90
+ }
91
+
92
+ export interface AppDevOptions {
93
+ /** The application root. */
94
+ readonly root: string
95
+ readonly port: number
96
+ readonly host: string
97
+ /** The environment: the test database URL, and the application's own variables. */
98
+ readonly env: Readonly<Record<string, string | undefined>>
99
+ /** The seed module's absolute path, or `null` to serve the empty application. */
100
+ readonly seed: string | null
101
+ }
102
+
103
+ export interface AppDevServer {
104
+ /** The address it serves, `http://<host>:<port>/`. */
105
+ readonly url: string
106
+ /** How many personas and link pages the seed offered. */
107
+ readonly seeded: { readonly personas: number; readonly links: number }
108
+ /** Stops serving and drops the throwaway schema. */
109
+ stop(): Promise<void>
110
+ }
111
+
112
+ /** Who the browser is: a persona of the seed, a role of the vocabulary in a scope value, or who accepted an invitation. */
113
+ const Choice = z.union([
114
+ z.strictObject({ persona: z.string().min(1).max(200) }),
115
+ z.strictObject({ role: z.string().min(1), value: z.string().min(1).max(MAX_SCOPE_VALUE).nullable() }),
116
+ z.strictObject({ invitation: z.string().min(1).max(200) }),
117
+ ])
118
+ type Choice = z.infer<typeof Choice>
119
+
120
+ /** The proxy's sign-in answer to a fetch, whose `loginUrl` names the kit's IAM. */
121
+ const LoginRequired = z.object({ error: z.looseObject({ loginUrl: z.string() }) })
122
+
123
+ export interface AppDevArgs {
124
+ readonly port: number
125
+ readonly host: string
126
+ readonly seed: string | null
127
+ }
128
+
129
+ export function parseAppDevArgs(argv: readonly string[]): AppDevArgs {
130
+ let port = 3000
131
+ let host = '127.0.0.1'
132
+ let seed: string | null = null
133
+ for (let index = 0; index < argv.length; index += 1) {
134
+ const arg = argv[index] ?? ''
135
+ if (arg.startsWith('--port=')) {
136
+ const parsed = Number(arg.slice('--port='.length))
137
+ if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) throw new Error(`app dev: --port is 0 to 65535, not ${arg.slice(7)}`)
138
+ port = parsed
139
+ } else if (arg.startsWith('--host=')) {
140
+ host = arg.slice('--host='.length)
141
+ } else if (arg.startsWith('--seed=') || arg === '--seed') {
142
+ const value = arg === '--seed' ? argv[index += 1] : arg.slice('--seed='.length)
143
+ if (value === undefined || value === '') throw new Error(`app dev: --seed names a module, e.g. --seed=${DEFAULT_SEED}`)
144
+ seed = value
145
+ } else {
146
+ throw new Error(`app dev takes no argument ${arg}\n\n${APP_DEV_USAGE}`)
147
+ }
148
+ }
149
+ if (!LOOPBACK.has(host)) {
150
+ throw new Error(`app dev serves this machine only: --host is 127.0.0.1, ::1 or localhost, not ${host}`)
151
+ }
152
+ return { port, host, seed }
153
+ }
154
+
155
+ /** The application's own variables: the environment without the framework's and the tests' `FABRIKA_*` names. */
156
+ function applicationVariables(env: Readonly<Record<string, string | undefined>>): Record<string, string> {
157
+ return Object.fromEntries(
158
+ Object.entries(env).flatMap(([name, value]) => (name.startsWith('FABRIKA_') || value === undefined ? [] : [[name, value]])),
159
+ )
160
+ }
161
+
162
+ function cookieOf(request: Request, name: string): string | undefined {
163
+ for (const part of (request.headers.get('Cookie') ?? '').split(';')) {
164
+ const [key, ...value] = part.trim().split('=')
165
+ if (key === name) return value.join('=')
166
+ }
167
+ return undefined
168
+ }
169
+
170
+ /** The request's cookies without the picker's own, which the application never sees. */
171
+ function withoutChoice(cookies: string | null): string | null {
172
+ if (cookies === null) return null
173
+ const kept = cookies.split(';').map((part) => part.trim()).filter((part) => part !== '' && !part.startsWith(`${CHOICE_COOKIE}=`))
174
+ return kept.length === 0 ? null : kept.join('; ')
175
+ }
176
+
177
+ /** The request is addressed to this server by a loopback name: a page of another site rebound to 127.0.0.1 is not. */
178
+ function addressedHere(request: Request, port: number): boolean {
179
+ const host = request.headers.get('Host')
180
+ if (host === null) return false
181
+ const at = host.lastIndexOf(':')
182
+ return at > 0 && LOOPBACK_HOSTNAMES.has(host.slice(0, at)) && host.slice(at + 1) === String(port)
183
+ }
184
+
185
+ const plain = (status: number, text: string): Response =>
186
+ new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
187
+
188
+ /** Serves `app` through its test kit on a loopback port until `stop`. */
189
+ export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
190
+ if (!LOOPBACK.has(options.host)) throw new AppDevError(`app dev serves this machine only, not ${options.host}`)
191
+ let postgres: TestDatabase | null = null
192
+ if (app.database !== null) {
193
+ if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
194
+ throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
195
+ }
196
+ postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
197
+ }
198
+ try {
199
+ return await serveThroughKit(app, options, postgres)
200
+ } catch (error) {
201
+ // The schema and its roles exist from here on: a failed start drops them as a stop does.
202
+ await postgres?.close()
203
+ throw error
204
+ }
205
+ }
206
+
207
+ /**
208
+ * The seed's answer, and its answer's problems named. What its own code throws is printed whole, stack included: the
209
+ * developer's code on the developer's machine.
210
+ */
211
+ async function runSeed(dev: DevKit<AnyContract>, outside: DevOutside, path: string | null): Promise<Seeded> {
212
+ if (path === null) return NOTHING_SEEDED
213
+ let answer: unknown
214
+ try {
215
+ const seed = await importSeed(path)
216
+ answer = await seed(dev.kit, outside)
217
+ } catch (error) {
218
+ if (error instanceof SeedProblem) throw error
219
+ throw new AppDevError(`app dev could not seed: the seed threw\n${Bun.inspect(error)}`)
220
+ }
221
+ return parseSeeded(dev, answer)
222
+ }
223
+
224
+ /** What a job's handler threw, printed whole on the developer's terminal. */
225
+ const printHandlerError = (where: string, error: unknown): void => {
226
+ console.error(`fabrika app dev: ${where} threw\n${Bun.inspect(error)}`)
227
+ }
228
+
229
+ /**
230
+ * The server over the kit of `app`, on `postgres` when it has a data layer; its `stop` also drops the schema. The dev
231
+ * outbox captures the process's `fetch` from before the seed runs until `stop`, or until a failed start.
232
+ */
233
+ async function serveThroughKit(
234
+ app: ContractImplementation<AnyContract>,
235
+ options: AppDevOptions,
236
+ postgres: TestDatabase | null,
237
+ ): Promise<AppDevServer> {
238
+ const outbox = devOutbox()
239
+ const restoreFetch = outbox.install()
240
+ try {
241
+ return await serveDevKit(app, options, postgres, outbox, restoreFetch)
242
+ } catch (error) {
243
+ restoreFetch()
244
+ throw error
245
+ }
246
+ }
247
+
248
+ async function serveDevKit(
249
+ app: ContractImplementation<AnyContract>,
250
+ options: AppDevOptions,
251
+ postgres: TestDatabase | null,
252
+ outbox: DevOutside,
253
+ restoreFetch: () => void,
254
+ ): Promise<AppDevServer> {
255
+ const contract = app.contract
256
+ const vocabulary = contract.vocabulary
257
+ const hasFiles = Object.keys(contract.surface.files ?? {}).length > 0
258
+ const dev = devKit(app, {
259
+ root: options.root,
260
+ env: { ...applicationVariables(options.env), ...readDevEnv(options.root) },
261
+ ...(postgres === null ? {} : { database: postgres.database }),
262
+ ...(hasFiles ? { files: new MemoryFileObjects() } : {}),
263
+ revealHandlerErrors: printHandlerError,
264
+ })
265
+ const kit = dev.kit
266
+ const seeded = await runSeed(dev, outbox, options.seed)
267
+ const text = stringsOf(vocabulary.locale ?? 'en')
268
+ const title = vocabulary.displayName ?? vocabulary.app
269
+ const mounts = Object.values(kit.artifact.mounts)
270
+ const firstSpa = mounts.find((mount) => mount.kind === 'spa')?.prefix ?? '/'
271
+ const pagePrefixes = mounts.flatMap((mount) => (mount.kind === 'spa' || mount.kind === 'link' ? [mount.prefix] : []))
272
+ const callers = new Map<string, LabelledTestCaller>()
273
+ const invitees = new Map<string, LabelledTestCaller>()
274
+ const toolbar = toolbarScript(STATE_PATH)
275
+
276
+ /** A path of this origin to go on to; anything else is the first SPA. */
277
+ const nextOf = (next: string | null): string => (next !== null && isLocalPath(next) ? next : firstSpa)
278
+
279
+ /** The caller a role choice names, made once and kept, so its membership changes last; `null` when it is no grant. */
280
+ const roleCaller = (role: string, value: string | null): LabelledTestCaller | null => {
281
+ const declared = Object.hasOwn(vocabulary.roles, role) ? vocabulary.roles[role] : undefined
282
+ if (declared === undefined || (declared.member !== undefined) !== (value !== null)) return null
283
+ const key = JSON.stringify([role, value])
284
+ const known = callers.get(key)
285
+ if (known !== undefined) return known
286
+ const grant = declared.member === undefined || value === null ? { role } : { role, scope: { type: declared.member.scope, value } }
287
+ const made = kit.testCaller([grant], { label: `${role}${value === null ? '' : `@${value}`}` })
288
+ callers.set(key, made)
289
+ return made
290
+ }
291
+
292
+ const callerOf = (choice: Choice): LabelledTestCaller | null => {
293
+ if ('persona' in choice) return seeded.personas.find((persona) => persona.name === choice.persona)?.caller ?? null
294
+ if ('invitation' in choice) return invitees.get(choice.invitation) ?? null
295
+ return roleCaller(choice.role, choice.value)
296
+ }
297
+
298
+ const choiceOf = (request: Request): Choice | null => {
299
+ const raw = cookieOf(request, CHOICE_COOKIE)
300
+ if (raw === undefined) return null
301
+ try {
302
+ const parsed = Choice.safeParse(JSON.parse(decodeURIComponent(raw)))
303
+ return parsed.success ? parsed.data : null
304
+ } catch {
305
+ return null
306
+ }
307
+ }
308
+
309
+ const scopeLabel = (type: string, value: string): string => seeded.scopes.get(type)?.find((known) => known.value === value)?.label ?? value
310
+
311
+ const externalBadge: Badge = { text: text.external, tone: 'external' }
312
+ const badgesOf = (caller: TestCaller): Badge[] => [
313
+ ...dev.membershipsOf(caller).map((held): Badge => ({
314
+ text: held.scope === null ? held.role : `${held.role} · ${scopeLabel(held.scope.type, held.scope.value)}`,
315
+ tone: 'role',
316
+ })),
317
+ ...(caller.affiliation === 'external' ? [externalBadge] : []),
318
+ ]
319
+
320
+ const currentOf = (choice: Choice | null): CurrentView | null => {
321
+ const caller = choice === null ? null : callerOf(choice)
322
+ if (choice === null || caller === null) return null
323
+ if ('persona' in choice) return { name: choice.persona, badges: badgesOf(caller) }
324
+ return { name: caller.email ?? caller.label, badges: badgesOf(caller) }
325
+ }
326
+
327
+ const chooseHref = (params: Record<string, string>, next: string): string => `${CHOOSE_PATH}?${new URLSearchParams({ ...params, next }).toString()}`
328
+
329
+ /** The values a membership role is offered in: the seed's, then those its personas hold. */
330
+ const valuesOf = (dimension: string): { readonly value: string; readonly label: string }[] => {
331
+ const values = [...(seeded.scopes.get(dimension) ?? [])]
332
+ for (const persona of seeded.personas) {
333
+ for (const held of dev.membershipsOf(persona.caller)) {
334
+ if (held.scope?.type === dimension && !values.some((known) => known.value === held.scope?.value)) {
335
+ values.push({ value: held.scope.value, label: held.scope.value })
336
+ }
337
+ }
338
+ }
339
+ return values
340
+ }
341
+
342
+ const viewOf = (choice: Choice | null, next: string): DevView => ({
343
+ locale: vocabulary.locale ?? 'en',
344
+ title,
345
+ current: currentOf(choice),
346
+ personas: seeded.personas.map((persona) => ({
347
+ name: persona.name,
348
+ description: persona.description,
349
+ email: persona.caller.email,
350
+ badges: badgesOf(persona.caller),
351
+ href: chooseHref({ persona: persona.name }, next),
352
+ current: choice !== null && 'persona' in choice && choice.persona === persona.name,
353
+ })),
354
+ roles: Object.entries(vocabulary.roles).map(([role, declared]): RoleView => ({
355
+ role,
356
+ grants: declared.grants,
357
+ external: declared.external === true,
358
+ choose: declared.member === undefined
359
+ ? { kind: 'app', href: chooseHref({ role }, next) }
360
+ : { kind: 'member', action: CHOOSE_PATH, next, dimension: declared.member.scope, values: valuesOf(declared.member.scope) },
361
+ })),
362
+ anonymousHref: chooseHref({ anonymous: '1' }, next),
363
+ links: seeded.links.map((link) => ({ title: link.title, description: link.description, href: link.url })),
364
+ mail: [
365
+ ...dev.invitations().map((invitation): MailView => ({
366
+ to: invitation.email,
367
+ subject: text.invitation(invitation.role, scopeLabel(invitation.scope.type, invitation.scope.value)),
368
+ status: invitation.status,
369
+ action: invitation.status === 'open'
370
+ ? { label: text.accept, href: `${ACCEPT_PATH}?${new URLSearchParams({ invitation: invitation.id, next }).toString()}` }
371
+ : invitation.status === 'accepted' && invitees.has(invitation.id)
372
+ ? { label: text.continueAs, href: chooseHref({ invitation: invitation.id }, next) }
373
+ : null,
374
+ })),
375
+ ...outbox.outbox().map((message): MailView => ({
376
+ ...mailHeadOf(message),
377
+ status: 'sent',
378
+ action: { label: text.openMessage, href: `${OUTBOX_PATH}${message.id}` },
379
+ })),
380
+ ],
381
+ pickerHref: `${PICKER_PATH}?${new URLSearchParams({ next }).toString()}`,
382
+ })
383
+
384
+ const choosing = (choice: Choice | null, next: string): Response => {
385
+ const cookie = choice === null
386
+ ? `${CHOICE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
387
+ : `${CHOICE_COOKIE}=${encodeURIComponent(JSON.stringify(choice))}; Path=/; HttpOnly; SameSite=Lax`
388
+ return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie, 'Cache-Control': 'no-store' } })
389
+ }
390
+
391
+ const choose = (url: URL): Response => {
392
+ const next = nextOf(url.searchParams.get('next'))
393
+ const persona = url.searchParams.get('persona')
394
+ const invitation = url.searchParams.get('invitation')
395
+ if (url.searchParams.has('anonymous')) return choosing(null, next)
396
+ if (persona !== null) {
397
+ const choice = Choice.safeParse({ persona })
398
+ if (!choice.success || callerOf(choice.data) === null) return plain(400, 'no such persona: the seed answered none by that name')
399
+ return choosing(choice.data, next)
400
+ }
401
+ if (invitation !== null) {
402
+ const choice = Choice.safeParse({ invitation })
403
+ if (!choice.success || callerOf(choice.data) === null) return plain(400, 'no such invitee: nobody accepted that invitation here')
404
+ return choosing(choice.data, next)
405
+ }
406
+ const role = url.searchParams.get('role') ?? ''
407
+ const scope = (url.searchParams.get('scope') ?? '').trim()
408
+ const choice = Choice.safeParse({ role, value: scope === '' ? null : scope })
409
+ if (!choice.success || callerOf(choice.data) === null) {
410
+ return plain(400, 'no such caller: a role of the vocabulary, with a scope value exactly when it is a membership role')
411
+ }
412
+ return choosing(choice.data, next)
413
+ }
414
+
415
+ /** The addressee of an open invitation accepts it, as IAM's onboarding does, and the browser is that person from now on. */
416
+ const accept = (request: Request, url: URL): Response => {
417
+ const next = nextOf(url.searchParams.get('next'))
418
+ const id = url.searchParams.get('invitation') ?? ''
419
+ try {
420
+ invitees.set(id, kit.acceptInvitation(id))
421
+ } catch (error) {
422
+ const view = viewOf(choiceOf(request), next)
423
+ // The kit's refusal names the invitation and the role, never a credential.
424
+ return new Response(noticePage(view, text.accept, error instanceof Error ? error.message : 'not_allowed'), { status: 409, headers: PAGE_HEADERS })
425
+ }
426
+ return choosing({ invitation: id }, next)
427
+ }
428
+
429
+ /** The request as it reaches the kit's origin; the page's `Origin` and `Referer` name the kit's origin instead. */
430
+ const toKit = async (request: Request, url: URL): Promise<Request> => {
431
+ const headers = new Headers(request.headers)
432
+ headers.delete('Host')
433
+ headers.delete('Referer')
434
+ const cookies = withoutChoice(headers.get('Cookie'))
435
+ if (cookies === null) headers.delete('Cookie')
436
+ else headers.set('Cookie', cookies)
437
+ if (headers.has('Origin')) headers.set('Origin', kit.origin)
438
+ const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.arrayBuffer()
439
+ return new Request(new URL(`${url.pathname}${url.search}`, kit.origin), { method: request.method, headers, body, redirect: 'manual' })
440
+ }
441
+
442
+ /**
443
+ * A redirect within the kit's origin stays a local path; a sign-in, a redirect to the kit's IAM or a 401's `loginUrl`,
444
+ * goes to the picker instead.
445
+ */
446
+ const fromKit = async (response: Response, url: URL): Promise<Response> => {
447
+ const picker = `${PICKER_PATH}?next=${encodeURIComponent(`${url.pathname}${url.search}`)}`
448
+ const headers = new Headers(response.headers)
449
+ const location = response.headers.get('Location')
450
+ if (location !== null && response.status >= 300 && response.status < 400) {
451
+ const target = new URL(location, kit.origin)
452
+ headers.set('Location', target.origin === kit.origin ? `${target.pathname}${target.search}` : picker)
453
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
454
+ }
455
+ if (response.status === 401 && (response.headers.get('Content-Type') ?? '').startsWith('application/json')) {
456
+ const login = LoginRequired.safeParse(await response.clone().json())
457
+ if (login.success) {
458
+ headers.delete('Content-Length')
459
+ const body = { error: { ...login.data.error, loginUrl: picker } }
460
+ return new Response(JSON.stringify(body), { status: 401, statusText: response.statusText, headers })
461
+ }
462
+ }
463
+ return response
464
+ }
465
+
466
+ const isPage = (path: string): boolean =>
467
+ pagePrefixes.some((prefix) => prefix === '/' || path === prefix || path.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`))
468
+
469
+ /** An SPA page with the toolbar's script tag; the kit's policy (`script-src 'self'`) already admits that script. */
470
+ const withDevToolbar = async (request: Request, response: Response, url: URL): Promise<Response> => {
471
+ if (
472
+ request.method !== 'GET' || response.status !== 200 || !(response.headers.get('Content-Type') ?? '').startsWith('text/html')
473
+ || !isPage(url.pathname)
474
+ ) {
475
+ return response
476
+ }
477
+ const headers = new Headers(response.headers)
478
+ headers.delete('Content-Length')
479
+ headers.delete('ETag')
480
+ return new Response(withToolbar(await response.text(), TOOLBAR_PATH), { status: 200, statusText: response.statusText, headers })
481
+ }
482
+
483
+ /** A message of the dev outbox, its body as it came (JSON indented); its headers, which carry keys, are not kept. */
484
+ const outboxMessage = (path: string): Response => {
485
+ const message = outbox.outbox().find((candidate) => `${OUTBOX_PATH}${candidate.id}` === path)
486
+ if (message === undefined) return plain(404, 'no such message in the dev outbox')
487
+ return new Response(`${message.method} ${DEV_OUTBOX_ORIGIN}${message.path}\n\n${shownBody(message)}\n`, {
488
+ headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
489
+ })
490
+ }
491
+
492
+ const devRoute = (request: Request, url: URL): Response | null => {
493
+ if (request.method !== 'GET') return null
494
+ if (url.pathname.startsWith(OUTBOX_PATH)) return outboxMessage(url.pathname)
495
+ switch (url.pathname) {
496
+ case PICKER_PATH:
497
+ return new Response(pickerPage(viewOf(choiceOf(request), nextOf(url.searchParams.get('next')))), { headers: PAGE_HEADERS })
498
+ case CHOOSE_PATH:
499
+ return choose(url)
500
+ case ACCEPT_PATH:
501
+ return accept(request, url)
502
+ case STATE_PATH:
503
+ return Response.json(toolbarState(viewOf(choiceOf(request), nextOf(url.searchParams.get('next')))), {
504
+ headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
505
+ })
506
+ case TOOLBAR_PATH:
507
+ return new Response(toolbar, {
508
+ headers: { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
509
+ })
510
+ default:
511
+ return null
512
+ }
513
+ }
514
+
515
+ let port = options.port
516
+ const server = listen({
517
+ hostname: options.host,
518
+ port: options.port,
519
+ async fetch(request) {
520
+ if (!addressedHere(request, port)) return plain(421, 'app dev answers only requests addressed to its loopback address')
521
+ const url = new URL(request.url)
522
+ const own = devRoute(request, url)
523
+ if (own !== null) return own
524
+ const choice = choiceOf(request)
525
+ const caller = choice === null ? null : callerOf(choice)
526
+ const fetch = caller === null ? kit.browser() : kit.browser(caller)
527
+ return await withDevToolbar(request, await fromKit(await fetch(await toKit(request, url)), url), url)
528
+ },
529
+ // The kit answers the application's own failures; anything thrown here is answered without its detail.
530
+ error: () => plain(500, 'app dev could not serve the request'),
531
+ })
532
+ port = server.port ?? options.port
533
+ const host = options.host.includes(':') ? `[${options.host}]` : options.host
534
+ return {
535
+ url: `http://${host}:${port}/`,
536
+ seeded: { personas: seeded.personas.length, links: seeded.links.length },
537
+ async stop() {
538
+ try {
539
+ await server.stop(true)
540
+ } finally {
541
+ restoreFetch()
542
+ await postgres?.close()
543
+ }
544
+ },
545
+ }
546
+ }
547
+
548
+ /** `Bun.serve`, with a port another process holds named as such. */
549
+ function listen(serving: Parameters<typeof Bun.serve>[0]): ReturnType<typeof Bun.serve> {
550
+ try {
551
+ return Bun.serve(serving)
552
+ } catch (error) {
553
+ if (error instanceof Error && 'code' in error && error.code === 'EADDRINUSE') {
554
+ throw new AppDevError(
555
+ `app dev: port ${String(serving.port)} on ${String(serving.hostname)} is in use; pass --port=<n>, or --port=0 for a free one`,
556
+ )
557
+ }
558
+ throw error
559
+ }
560
+ }
561
+
562
+ /** `fabrika app dev`: serves until the process is stopped, then drops the throwaway schema. */
563
+ export const runAppDevCli = async (argv: readonly string[]): Promise<void> => {
564
+ const { port, host, seed: given } = parseAppDevArgs(argv)
565
+ const root = process.cwd()
566
+ if (!existsSync(join(root, CONTRACT_FILE))) {
567
+ throw new Error(`app dev: no ${CONTRACT_FILE} in ${root}; run it from the application root`)
568
+ }
569
+ let server: AppDevServer
570
+ try {
571
+ const seed = seedPath(root, given)
572
+ const { default: app } = await implementationAt(join(root, IMPLEMENTATION_FILE))()
573
+ server = await startAppDev(app, { root, port, host, env: process.env, seed })
574
+ } catch (error) {
575
+ throw startupFailure(error)
576
+ }
577
+ console.info(server.url)
578
+ const { personas, links } = server.seeded
579
+ console.error(
580
+ `fabrika app dev: seeded personas: ${personas}, link pages: ${links}; pick a caller at ${server.url}${PICKER_PATH.slice(1)}; stop with Ctrl-C`,
581
+ )
582
+ await new Promise<void>((resolve) => {
583
+ const stop = () => {
584
+ void server.stop().finally(resolve)
585
+ }
586
+ process.once('SIGINT', stop)
587
+ process.once('SIGTERM', stop)
588
+ })
589
+ }