@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.40

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.9.0-dev.4",
3
+ "version": "0.9.0-dev.40",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,24 +26,25 @@
26
26
  }
27
27
  },
28
28
  "scripts": {
29
- "typecheck": "tsc --noEmit",
29
+ "typecheck": "tsrs --build tsconfig.test.json",
30
30
  "test": "bun test"
31
31
  },
32
32
  "dependencies": {
33
33
  "zod": "^3.25.76",
34
- "@fabrika/app": "0.9.0-dev.4",
35
- "@fabrika/auth-core": "0.9.0-dev.4",
36
- "@fabrika/control-contract": "0.9.0-dev.4",
37
- "@fabrika/provider-contract": "0.9.0-dev.4",
38
- "@fabrika/db": "0.9.0-dev.4",
39
- "@fabrika/platform": "0.9.0-dev.4",
40
- "@fabrika/platform-node": "0.9.0-dev.4",
41
- "@fabrika/check": "0.9.0-dev.4"
34
+ "@fabrika/app": "0.9.0-dev.40",
35
+ "@fabrika/auth-core": "0.9.0-dev.40",
36
+ "@fabrika/control-contract": "0.9.0-dev.40",
37
+ "@fabrika/operations-contract": "0.9.0-dev.40",
38
+ "@fabrika/provider-contract": "0.9.0-dev.40",
39
+ "@fabrika/db": "0.9.0-dev.40",
40
+ "@fabrika/platform": "0.9.0-dev.40",
41
+ "@fabrika/platform-node": "0.9.0-dev.40",
42
+ "@fabrika/check": "0.9.0-dev.40"
42
43
  },
43
44
  "peerDependencies": {
44
- "@fabrika/builder": "0.9.0-dev.4",
45
- "@fabrika/provider-cloudflare": "0.9.0-dev.4",
46
- "@fabrika/provider-zerops": "0.9.0-dev.4"
45
+ "@fabrika/builder": "0.9.0-dev.40",
46
+ "@fabrika/provider-cloudflare": "0.9.0-dev.40",
47
+ "@fabrika/provider-zerops": "0.9.0-dev.40"
47
48
  },
48
49
  "peerDependenciesMeta": {
49
50
  "@fabrika/builder": {
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { AnyContract } from '@fabrika/app/contract'
5
5
  import type { DevKit, PersonTestCaller } from '@fabrika/app/testing'
6
+ import { sameOriginTarget } from '@fabrika/auth-core'
6
7
  import { existsSync } from 'node:fs'
7
8
  import { isAbsolute, join } from 'node:path'
8
9
  import { pathToFileURL } from 'node:url'
@@ -53,11 +54,6 @@ const SeedResult = z.strictObject({
53
54
  scopes: z.record(z.string(), z.array(z.strictObject({ value: Text(MAX_SCOPE_VALUE), label: Text(MAX_NAME) })).max(MAX_ENTRIES)).optional(),
54
55
  }).optional()
55
56
 
56
- /** A path of this origin; a link the application issued is one (`/s/#px_…`). */
57
- export function isLocalPath(path: string): boolean {
58
- return path.startsWith('/') && !path.startsWith('//') && !path.startsWith('/\\')
59
- }
60
-
61
57
  /** The seed module's path: `--seed`, relative to the root, or `dev/seed.ts` when it exists; `null` for none. */
62
58
  export function seedPath(root: string, given: string | null): string | null {
63
59
  if (given !== null) {
@@ -102,7 +98,7 @@ export function parseSeeded<C extends AnyContract>(dev: DevKit<C>, answer: unkno
102
98
  return { name: persona.name, description: persona.description ?? null, caller }
103
99
  })
104
100
  const links = (result.links ?? []).map((link, index): SeedLink => {
105
- if (!isLocalPath(link.url)) {
101
+ if (sameOriginTarget(dev.kit.origin, link.url) === null) {
106
102
  throw new SeedProblem(`app dev: link ${index + 1} of the seed is not a path of the application, as ctx.links answers it`)
107
103
  }
108
104
  return { title: link.title, description: link.description ?? null, url: link.url }
package/src/app-dev-ui.ts CHANGED
@@ -1,10 +1,10 @@
1
- // What `fabrika app dev` shows a person: the caller picker page, one mail a job sent, and the toolbar script it injects
1
+ // What `fabrika app dev` shows a person: the caller picker page, one mail a job or the stand-in IAM sent, and the toolbar script it injects
2
2
  // into every SPA page. All are self-contained (no font, no CDN) and take their colors from `--fd-*` custom properties, light and dark.
3
3
  // Every value here comes from the seed, the vocabulary or the request, so the page escapes it and the script only ever
4
4
  // sets `textContent` and `href`.
5
5
 
6
6
  import type { DevMail, SentInvitation } from '@fabrika/app/testing'
7
- import type { Locale } from '@fabrika/auth-core'
7
+ import type { Locale, RenderedMessage } from '@fabrika/auth-core'
8
8
 
9
9
  /** A label beside a caller: a role it holds (with the scope value it holds it in), or that it is external. */
10
10
  export interface Badge {
@@ -52,9 +52,20 @@ export interface LinkView {
52
52
  /** An invitation's state, or how a job's message ended: `sent` when the transport accepted it. */
53
53
  export type MailStatus = SentInvitation['status'] | 'sent' | 'not_sent' | 'unknown'
54
54
 
55
+ /** A link a row offers: accept an invitation, continue as its invitee, open a message. */
56
+ export interface MailAction {
57
+ readonly label: string
58
+ readonly href: string
59
+ }
60
+
55
61
  export interface MailView {
56
62
  readonly to: string
63
+ /** The subject the addressee reads: an invitation's in the language IAM writes it in. */
57
64
  readonly subject: string
65
+ /** The language the subject is written in when it is not the page's (an invitation's `mailLocale`); otherwise `null`. */
66
+ readonly subjectLocale: Locale | null
67
+ /** One more line of what it is: an invitation's role, scope value and language; `null` for a job's message. */
68
+ readonly note: string | null
58
69
  /** When it was sent, in ms: an invitation's latest send, or a job's handoff. */
59
70
  readonly at: number
60
71
  /** The key the job passed; `null` for an invitation. */
@@ -62,7 +73,8 @@ export interface MailView {
62
73
  readonly status: MailStatus
63
74
  /** The transport's refusal code (`provider_rejected`) when it did not accept; otherwise `null`. */
64
75
  readonly answer: string | null
65
- readonly action: { readonly label: string; readonly href: string } | null
76
+ /** The row's links, the main one first: the toolbar offers that one only. */
77
+ readonly actions: readonly MailAction[]
66
78
  }
67
79
 
68
80
  /** A request the application sent to the dev outbox. */
@@ -129,6 +141,8 @@ interface Strings {
129
141
  readonly key: string
130
142
  readonly transportKey: string
131
143
  readonly sentAt: string
144
+ readonly language: string
145
+ readonly state: string
132
146
  readonly answer: string
133
147
  readonly fromName: string
134
148
  readonly replyTo: string
@@ -185,6 +199,8 @@ const STRINGS: Readonly<Record<Locale, Strings>> = {
185
199
  key: 'Key',
186
200
  transportKey: 'Transport key',
187
201
  sentAt: 'Sent',
202
+ language: 'Language',
203
+ state: 'State',
188
204
  answer: 'Transport answer',
189
205
  fromName: 'From name',
190
206
  replyTo: 'Reply to',
@@ -239,6 +255,8 @@ const STRINGS: Readonly<Record<Locale, Strings>> = {
239
255
  key: 'Klíč',
240
256
  transportKey: 'Klíč transportu',
241
257
  sentAt: 'Odesláno',
258
+ language: 'Jazyk',
259
+ state: 'Stav',
242
260
  answer: 'Odpověď transportu',
243
261
  fromName: 'Jméno odesílatele',
244
262
  replyTo: 'Odpovědět na',
@@ -252,6 +270,63 @@ const STRINGS: Readonly<Record<Locale, Strings>> = {
252
270
  close: 'Zavřít',
253
271
  back: 'Zpět na výběr',
254
272
  },
273
+ uk: {
274
+ preview: 'Попередній перегляд для розробки',
275
+ choose: 'Виберіть, ким ви є',
276
+ lede:
277
+ 'Кожен варіант визначає, від чийого імені ви звертаєтеся до тестового IAM. Дані зберігаються в тимчасовій схемі й зникають, коли app dev завершується.',
278
+ now: 'Ви',
279
+ nobody: 'Ніхто (анонімно)',
280
+ personas: 'Персони',
281
+ noPersonas: 'Seed не створив жодної персони. Поверніть їх із dev/seed.ts.',
282
+ another: 'Інша роль',
283
+ appWide: 'у всьому застосунку',
284
+ inScope: (dimension) => `в одному значенні ${dimension}`,
285
+ external: 'зовнішній',
286
+ use: 'Використати',
287
+ scopePlaceholder: (dimension) => `значення ${dimension}`,
288
+ anonymous: 'Анонімно',
289
+ anonymousText: 'Сторінка, що потребує входу, поверне вас сюди.',
290
+ anonymousButton: 'Продовжити анонімно',
291
+ links: 'Сторінки за посиланням',
292
+ linksText: 'Кожна відкривається від імені власника посилання, яке видав застосунок.',
293
+ openLink: 'Відкрити як власник посилання',
294
+ mail: 'Пошта',
295
+ mailText: 'Запрошення, які тестовий IAM надіслав би електронною поштою, і листи, які надіслали завдання застосунку.',
296
+ noMail: 'Ще нічого не надіслано.',
297
+ invitation: (role, scope) => `Запрошення: ${role} у ${scope}`,
298
+ accept: 'Прийняти запрошення',
299
+ continueAs: 'Продовжити як ця особа',
300
+ openMessage: 'Відкрити лист',
301
+ status: {
302
+ open: 'очікує',
303
+ accepted: 'прийнято',
304
+ cancelled: 'скасовано',
305
+ expired: 'термін минув',
306
+ sent: 'надіслано',
307
+ not_sent: 'не надіслано',
308
+ unknown: 'можливо, надіслано',
309
+ },
310
+ to: 'Кому',
311
+ subject: 'Тема',
312
+ key: 'Ключ',
313
+ transportKey: 'Ключ транспорту',
314
+ sentAt: 'Надіслано',
315
+ language: 'Мова',
316
+ state: 'Стан',
317
+ answer: 'Відповідь транспорту',
318
+ fromName: 'Ім’я відправника',
319
+ replyTo: 'Адреса для відповіді',
320
+ text: 'Текст',
321
+ html: 'HTML',
322
+ noHtml: 'Лист не має частини HTML.',
323
+ outbox: 'Скринька розробки',
324
+ outboxText: 'Запити, які застосунок надіслав до скриньки розробки, від найновішого.',
325
+ noOutbox: 'До скриньки розробки ще нічого не надійшло.',
326
+ picker: 'Вибрати інший варіант',
327
+ close: 'Закрити',
328
+ back: 'Назад до вибору',
329
+ },
255
330
  }
256
331
 
257
332
  export const stringsOf = (locale: Locale): Strings => STRINGS[locale]
@@ -338,7 +413,7 @@ h2 + .grid, h2 + .rows { margin-top: 14px; }
338
413
  .row .meta .grants { font-family: var(--fd-mono); font-size: 12px; overflow-wrap: anywhere; }
339
414
  .row .control { display: flex; gap: 8px; align-items: center; }
340
415
  .row .meta.stack { flex-direction: column; align-items: flex-start; gap: 2px; }
341
- .actions { margin-top: 24px; }
416
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 24px; }
342
417
  .subject { font-weight: 600; color: var(--fd-text); font-size: 15px; }
343
418
  .to { font-size: 13px; color: var(--fd-muted); overflow-wrap: anywhere; }
344
419
  input { font: inherit; font-size: 14px; height: 34px; padding: 0 10px; width: 200px; border: 1px solid var(--fd-border-strong); border-radius: 8px; background: var(--fd-bg); color: var(--fd-text); }
@@ -371,7 +446,10 @@ const badges = (list: readonly Badge[]): string =>
371
446
  ? ''
372
447
  : `<div class="badges">${list.map((badge) => `<span class="badge ${badge.tone}">${escapeHtml(badge.text)}</span>`).join('')}</div>`
373
448
 
374
- function page(view: Pick<DevView, 'locale' | 'title' | 'current'>, heading: string, body: string): string {
449
+ /** The `lang` attribute of text written in `locale` on a page in another language; none when they agree. */
450
+ const langOf = (page: Locale, locale: Locale | null): string => (locale === null || locale === page ? '' : ` lang="${locale}"`)
451
+
452
+ function page(view: Pick<DevView, 'locale' | 'title' | 'current'>, heading: string, body: string, headingLocale: Locale | null = null): string {
375
453
  const text = stringsOf(view.locale)
376
454
  const now = view.current === null
377
455
  ? `<span>${escapeHtml(text.now)}:</span> <strong>${escapeHtml(text.nobody)}</strong>`
@@ -391,7 +469,7 @@ function page(view: Pick<DevView, 'locale' | 'title' | 'current'>, heading: stri
391
469
  escapeHtml(text.preview)
392
470
  }</span></span><span class="now">${now}</span></div></header>
393
471
  <main>
394
- <h1>${escapeHtml(heading)}</h1>
472
+ <h1${langOf(view.locale, headingLocale)}>${escapeHtml(heading)}</h1>
395
473
  ${body}
396
474
  </main>
397
475
  </body>
@@ -433,7 +511,7 @@ function roleRow(role: RoleView, text: Strings): string {
433
511
  }"><datalist id="${list}">${options}</datalist><button class="button quiet" type="submit">${escapeHtml(text.use)}</button></span></form>`
434
512
  }
435
513
 
436
- const actionButton = (action: { readonly label: string; readonly href: string } | null): string =>
514
+ const actionButton = (action: MailAction | null): string =>
437
515
  action === null ? '' : `<span class="control"><a class="button quiet" href="${escapeHtml(action.href)}">${escapeHtml(action.label)}</a></span>`
438
516
 
439
517
  function mailRows(mail: readonly MailView[], text: Strings, locale: Locale): string {
@@ -441,11 +519,11 @@ function mailRows(mail: readonly MailView[], text: Strings, locale: Locale): str
441
519
  return `<div class="rows">${
442
520
  mail.map((item) => {
443
521
  const when = [...(item.key === null ? [] : [item.key]), timeOf(locale, item.at)].join(' · ')
444
- return `<div class="row"><span class="meta stack"><span class="subject">${escapeHtml(item.subject)}</span><span class="to">${
445
- escapeHtml(text.to)
446
- }: ${escapeHtml(item.to)}</span><span class="to">${escapeHtml(when)}</span></span><span class="badge">${
522
+ return `<div class="row"><span class="meta stack"><span class="subject"${langOf(locale, item.subjectLocale)}>${escapeHtml(item.subject)}</span>${
523
+ item.note === null ? '' : `<span class="to">${escapeHtml(item.note)}</span>`
524
+ }<span class="to">${escapeHtml(text.to)}: ${escapeHtml(item.to)}</span><span class="to">${escapeHtml(when)}</span></span><span class="badge">${
447
525
  escapeHtml(text.status[item.status])
448
- }</span>${item.answer === null ? '' : `<span class="mono">${escapeHtml(item.answer)}</span>`}${actionButton(item.action)}</div>`
526
+ }</span>${item.answer === null ? '' : `<span class="mono">${escapeHtml(item.answer)}</span>`}${item.actions.map(actionButton).join('')}</div>`
449
527
  }).join('')
450
528
  }</div>`
451
529
  }
@@ -511,13 +589,44 @@ export function noticePage(view: Pick<DevView, 'locale' | 'title' | 'current' |
511
589
  }
512
590
 
513
591
  /**
514
- * One message a job handed to the mail stand-in: its fields, its text, and its HTML in a frame that runs no script, has no
515
- * origin and submits nothing. The frame's document inherits the page's policy (`default-src 'none'`), so it loads nothing.
592
+ * One message: its fields, its text, and its HTML in a frame that runs no script, has no origin and submits nothing. The
593
+ * frame's document inherits the page's policy (`default-src 'none'`), so it loads nothing, and a link in it opens
594
+ * nothing, so what the message offers is a button beside the way back. `messageLocale` is the message's language when it
595
+ * is not the page's.
516
596
  */
597
+ function messagePage(
598
+ view: Pick<DevView, 'locale' | 'title' | 'current' | 'pickerHref'>,
599
+ subject: string,
600
+ fields: readonly (readonly [string, string | null])[],
601
+ message: { readonly text: string; readonly html: string | null },
602
+ actions: readonly MailAction[] = [],
603
+ messageLocale: Locale | null = null,
604
+ ): string {
605
+ const text = stringsOf(view.locale)
606
+ const lang = langOf(view.locale, messageLocale)
607
+ const html = message.html === null
608
+ ? `<div class="empty">${escapeHtml(text.noHtml)}</div>`
609
+ : `<iframe class="mail-html" sandbox="" referrerpolicy="no-referrer" title="${escapeHtml(text.html)}" srcdoc="${
610
+ escapeHtml(message.html)
611
+ }"></iframe>`
612
+ return page(
613
+ view,
614
+ subject,
615
+ `<p class="actions"><a class="button quiet" href="${escapeHtml(view.pickerHref)}">${escapeHtml(text.back)}</a>${
616
+ actions.map((action) => `<a class="button quiet" href="${escapeHtml(action.href)}">${escapeHtml(action.label)}</a>`).join('')
617
+ }</p>
618
+ <dl class="fields">${fields.map(([name, value]) => (value === null ? '' : `<dt>${escapeHtml(name)}</dt><dd>${escapeHtml(value)}</dd>`)).join('')}</dl>
619
+ <section aria-labelledby="text"><h2 id="text">${escapeHtml(text.text)}</h2><pre class="text"${lang}>${escapeHtml(message.text)}</pre></section>
620
+ <section aria-labelledby="html"><h2 id="html">${escapeHtml(text.html)}</h2>${html}</section>`,
621
+ messageLocale,
622
+ )
623
+ }
624
+
625
+ /** One message a job handed to the mail stand-in. */
517
626
  export function mailPage(view: Pick<DevView, 'locale' | 'title' | 'current' | 'pickerHref'>, mail: DevMail): string {
518
627
  const text = stringsOf(view.locale)
519
628
  const status = mail.outcome === 'accepted' ? text.status.sent : text.status[mail.outcome]
520
- const fields: readonly (readonly [string, string | null])[] = [
629
+ return messagePage(view, mail.subject, [
521
630
  [text.to, mail.to],
522
631
  [text.subject, mail.subject],
523
632
  [text.fromName, mail.fromName],
@@ -526,17 +635,35 @@ export function mailPage(view: Pick<DevView, 'locale' | 'title' | 'current' | 'p
526
635
  [text.transportKey, mail.transportKey],
527
636
  [text.answer, mail.answer === 'accepted' ? status : `${status} · ${mail.answer}`],
528
637
  [text.sentAt, timeOf(view.locale, Date.parse(mail.at))],
529
- ]
530
- const html = mail.html === null
531
- ? `<div class="empty">${escapeHtml(text.noHtml)}</div>`
532
- : `<iframe class="mail-html" sandbox="" referrerpolicy="no-referrer" title="${escapeHtml(text.html)}" srcdoc="${escapeHtml(mail.html)}"></iframe>`
533
- return page(
638
+ ], mail)
639
+ }
640
+
641
+ /**
642
+ * The e-mail the stand-in IAM would have sent for an invitation, as IAM writes it: in the language it chose
643
+ * (`mailLocale`), from the application's template of that language or IAM's own wording. The page around it speaks the
644
+ * application's language; only the message is the invitee's. `actions` are what its row offers (accept it, continue as
645
+ * its invitee).
646
+ */
647
+ export function invitationMailPage(
648
+ view: Pick<DevView, 'locale' | 'title' | 'current' | 'pickerHref'>,
649
+ invitation: SentInvitation,
650
+ mail: RenderedMessage,
651
+ actions: readonly MailAction[] = [],
652
+ ): string {
653
+ const text = stringsOf(view.locale)
654
+ return messagePage(
534
655
  view,
535
656
  mail.subject,
536
- `<p class="actions"><a class="button quiet" href="${escapeHtml(view.pickerHref)}">${escapeHtml(text.back)}</a></p>
537
- <dl class="fields">${fields.map(([name, value]) => (value === null ? '' : `<dt>${escapeHtml(name)}</dt><dd>${escapeHtml(value)}</dd>`)).join('')}</dl>
538
- <section aria-labelledby="text"><h2 id="text">${escapeHtml(text.text)}</h2><pre class="text">${escapeHtml(mail.text)}</pre></section>
539
- <section aria-labelledby="html"><h2 id="html">${escapeHtml(text.html)}</h2>${html}</section>`,
657
+ [
658
+ [text.to, invitation.email],
659
+ [text.subject, mail.subject],
660
+ [text.language, invitation.mailLocale],
661
+ [text.state, text.status[invitation.status]],
662
+ [text.sentAt, timeOf(view.locale, invitation.sentAt * 1000)],
663
+ ],
664
+ mail,
665
+ actions,
666
+ invitation.mailLocale,
540
667
  )
541
668
  }
542
669
 
@@ -560,7 +687,11 @@ export function toolbarState(view: DevView): unknown {
560
687
  current: view.current === null ? { name: text.nobody, detail: '' } : { name: view.current.name, detail: detail(view.current.badges) },
561
688
  personas: view.personas.map((persona) => ({ name: persona.name, detail: detail(persona.badges), href: persona.href, current: persona.current })),
562
689
  links: view.links.map((link) => ({ title: link.title, detail: link.description ?? '', href: link.href })),
563
- mail: view.mail.map((item) => ({ subject: item.subject, detail: `${text.to}: ${item.to} · ${text.status[item.status]}`, action: item.action })),
690
+ mail: view.mail.map((item) => ({
691
+ subject: item.subject,
692
+ detail: [...(item.note === null ? [] : [item.note]), `${text.to}: ${item.to}`, text.status[item.status]].join(' · '),
693
+ action: item.actions[0] ?? null,
694
+ })),
564
695
  outbox: view.outbox.map((item) => ({
565
696
  subject: item.subject,
566
697
  detail: `${text.to}: ${item.to}`,
package/src/app-dev.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `fabrika app dev`: a contract application served through its test kit on a loopback port, to click through its
2
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
3
+ // their build directories; Postgres is a throwaway schema of the tests' database, SQLite (Cloudflare) an in-memory
4
+ // database. A seed module fills it through the
4
5
  // endpoints first. A caller picker chooses who the browser is; a cookie keeps the choice, and the kit's own session
5
6
  // never leaves the process. Every SPA page gets the dev toolbar, which switches the caller without leaving the page.
6
7
 
@@ -8,19 +9,32 @@ import { CONTRACT_FILE, IMPLEMENTATION_FILE } from '@fabrika/app/build'
8
9
  import { implementationAt } from '@fabrika/app/bun'
9
10
  import type { AnyContract } from '@fabrika/app/contract'
10
11
  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 {
13
+ DEV_OUTBOX_ORIGIN,
14
+ type DevKit,
15
+ devKit,
16
+ type DevOutside,
17
+ type LabelledTestCaller,
18
+ type SentInvitation,
19
+ type TestCaller,
20
+ } from '@fabrika/app/testing'
21
+ import { sameOriginTarget } from '@fabrika/auth-core'
22
+ import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
23
+ import { SqliteMigrationError } from '@fabrika/db/sqlite-migrate'
12
24
  import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
13
25
  import { PostgresMigrationError } from '@fabrika/platform-node'
14
26
  import { MemoryFileObjects } from '@fabrika/platform/testing'
15
- import { existsSync } from 'node:fs'
27
+ import { existsSync, readFileSync } from 'node:fs'
16
28
  import { join } from 'node:path'
17
29
  import { z } from 'zod/v4'
18
30
  import { DEV_ENV_FILE, DevEnvProblem, type DevOutbox, 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'
31
+ import { DEFAULT_SEED, importSeed, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
20
32
  import {
21
33
  type Badge,
22
34
  type CurrentView,
23
35
  type DevView,
36
+ invitationMailPage,
37
+ type MailAction,
24
38
  mailPage,
25
39
  type MailView,
26
40
  newestMail,
@@ -41,7 +55,8 @@ Usage:
41
55
 
42
56
  Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
43
57
  the kit's stand-in IAM, each SPA from its built directory (run the SPA build first; an unbuilt one is an empty page),
44
- and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit.
58
+ and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit; an
59
+ application on Cloudflare (its ${CONFIG_FILE} is @fabrika/provider-cloudflare's) gets an in-memory SQLite database instead.
45
60
  The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
46
61
  receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
47
62
  Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
@@ -87,7 +102,7 @@ export class AppDevError extends Error {
87
102
  export function startupFailure(error: unknown): Error {
88
103
  if (
89
104
  error instanceof AppDevError || error instanceof SeedProblem || error instanceof DevEnvProblem || error instanceof BootError
90
- || error instanceof PostgresMigrationError
105
+ || error instanceof PostgresMigrationError || error instanceof SqliteMigrationError
91
106
  ) {
92
107
  return new Error(error.message)
93
108
  }
@@ -190,21 +205,31 @@ function addressedHere(request: Request, port: number): boolean {
190
205
  const plain = (status: number, text: string): Response =>
191
206
  new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
192
207
 
208
+ /** The dialect the application's `fabrika.config.ts` names, as the checker reads it. */
209
+ function dialectAt(root: string): ApplicationDialect {
210
+ const path = join(root, CONFIG_FILE)
211
+ return applicationDialect(new Map(existsSync(path) ? [[CONFIG_FILE, readFileSync(path, 'utf8')]] : []))
212
+ }
213
+
193
214
  /** Serves `app` through its test kit on a loopback port until `stop`. */
194
215
  export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
195
216
  if (!LOOPBACK.has(options.host)) throw new AppDevError(`app dev serves this machine only, not ${options.host}`)
196
- let postgres: TestDatabase | null = null
197
- if (app.database !== null) {
217
+ let testDb: TestDatabase | null = null
218
+ if (app.database !== null && dialectAt(options.root) === 'sqlite') {
219
+ // The SQLite twin of the kit opens an in-memory database: no URL, and nothing left behind to drop.
220
+ const sqlite = await import('@fabrika/db/testing-sqlite')
221
+ testDb = await sqlite.testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
222
+ } else if (app.database !== null) {
198
223
  if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
199
224
  throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
200
225
  }
201
- postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
226
+ testDb = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
202
227
  }
203
228
  try {
204
- return await serveThroughKit(app, options, postgres)
229
+ return await serveThroughKit(app, options, testDb)
205
230
  } catch (error) {
206
231
  // The schema and its roles exist from here on: a failed start drops them as a stop does.
207
- await postgres?.close()
232
+ await testDb?.close()
208
233
  throw error
209
234
  }
210
235
  }
@@ -226,24 +251,24 @@ async function runSeed(dev: DevKit<AnyContract>, outside: DevOutside, path: stri
226
251
  return parseSeeded(dev, answer)
227
252
  }
228
253
 
229
- /** What a job's handler threw, printed whole on the developer's terminal. */
254
+ /** What a request's 5xx or a job attempt threw, printed whole on the developer's terminal. */
230
255
  const printHandlerError = (where: string, error: unknown): void => {
231
256
  console.error(`fabrika app dev: ${where} threw\n${Bun.inspect(error)}`)
232
257
  }
233
258
 
234
259
  /**
235
- * The server over the kit of `app`, on `postgres` when it has a data layer; its `stop` also drops the schema. The dev
260
+ * The server over the kit of `app`, on `testDb` when it has a data layer; its `stop` also drops a Postgres schema. The dev
236
261
  * outbox captures the process's `fetch` from before the seed runs until `stop`, or until a failed start.
237
262
  */
238
263
  async function serveThroughKit(
239
264
  app: ContractImplementation<AnyContract>,
240
265
  options: AppDevOptions,
241
- postgres: TestDatabase | null,
266
+ testDb: TestDatabase | null,
242
267
  ): Promise<AppDevServer> {
243
268
  const outbox = devOutbox()
244
269
  const restoreFetch = outbox.install()
245
270
  try {
246
- return await serveDevKit(app, options, postgres, outbox, restoreFetch)
271
+ return await serveDevKit(app, options, testDb, outbox, restoreFetch)
247
272
  } catch (error) {
248
273
  restoreFetch()
249
274
  throw error
@@ -253,7 +278,7 @@ async function serveThroughKit(
253
278
  async function serveDevKit(
254
279
  app: ContractImplementation<AnyContract>,
255
280
  options: AppDevOptions,
256
- postgres: TestDatabase | null,
281
+ testDb: TestDatabase | null,
257
282
  outbox: DevOutbox,
258
283
  restoreFetch: () => void,
259
284
  ): Promise<AppDevServer> {
@@ -263,7 +288,7 @@ async function serveDevKit(
263
288
  const dev = devKit(app, {
264
289
  root: options.root,
265
290
  env: { ...applicationVariables(options.env), ...readDevEnv(options.root) },
266
- ...(postgres === null ? {} : { database: postgres.database }),
291
+ ...(testDb === null ? {} : { database: testDb.database }),
267
292
  ...(hasFiles ? { files: new MemoryFileObjects() } : {}),
268
293
  revealHandlerErrors: printHandlerError,
269
294
  })
@@ -278,9 +303,11 @@ async function serveDevKit(
278
303
  const callers = new Map<string, LabelledTestCaller>()
279
304
  const invitees = new Map<string, LabelledTestCaller>()
280
305
  const toolbar = toolbarScript(STATE_PATH)
306
+ const urlHost = options.host.includes(':') ? `[${options.host}]` : options.host
307
+ let port = options.port
281
308
 
282
309
  /** A path of this origin to go on to; anything else is the first SPA. */
283
- const nextOf = (next: string | null): string => (next !== null && isLocalPath(next) ? next : firstSpa)
310
+ const nextOf = (next: string | null): string => (next !== null && sameOriginTarget(kit.origin, next) !== null ? next : firstSpa)
284
311
 
285
312
  /** The caller a role choice names, made once and kept, so its membership changes last; `null` when it is no grant. */
286
313
  const roleCaller = (role: string, value: string | null): LabelledTestCaller | null => {
@@ -331,6 +358,25 @@ async function serveDevKit(
331
358
  }
332
359
 
333
360
  const chooseHref = (params: Record<string, string>, next: string): string => `${CHOOSE_PATH}?${new URLSearchParams({ ...params, next }).toString()}`
361
+ const acceptHref = (invitation: string, next: string): string => `${ACCEPT_PATH}?${new URLSearchParams({ invitation, next }).toString()}`
362
+
363
+ /**
364
+ * The e-mail the stand-in IAM would have sent for an invitation, in the language IAM chooses for it: its link is this
365
+ * server's accept route, where IAM's would be its own accept page, and `{{appUrl}}` is this server, where the
366
+ * application's registered return origin would be.
367
+ */
368
+ const invitationMailOf = (invitation: SentInvitation) => {
369
+ const origin = `http://${urlHost}:${port}`
370
+ return dev.invitationMail(invitation.id, new URL(acceptHref(invitation.id, firstSpa), origin).toString(), `${origin}/`)
371
+ }
372
+
373
+ /** What an invitation offers: accept it while it is open, or continue as the invitee who accepted it here. */
374
+ const invitationActions = (invitation: SentInvitation, next: string): MailAction[] =>
375
+ invitation.status === 'open'
376
+ ? [{ label: text.accept, href: acceptHref(invitation.id, next) }]
377
+ : invitation.status === 'accepted' && invitees.has(invitation.id)
378
+ ? [{ label: text.continueAs, href: chooseHref({ invitation: invitation.id }, next) }]
379
+ : []
334
380
 
335
381
  /** The values a membership role is offered in: the seed's, then those its personas hold. */
336
382
  const valuesOf = (dimension: string): { readonly value: string; readonly label: string }[] => {
@@ -368,27 +414,31 @@ async function serveDevKit(
368
414
  anonymousHref: chooseHref({ anonymous: '1' }, next),
369
415
  links: seeded.links.map((link) => ({ title: link.title, description: link.description, href: link.url })),
370
416
  mail: newestMail([
371
- ...dev.invitations().map((invitation): MailView => ({
372
- to: invitation.email,
373
- subject: text.invitation(invitation.role, scopeLabel(invitation.scope.type, invitation.scope.value)),
374
- at: invitation.sentAt * 1000,
375
- key: null,
376
- status: invitation.status,
377
- answer: null,
378
- action: invitation.status === 'open'
379
- ? { label: text.accept, href: `${ACCEPT_PATH}?${new URLSearchParams({ invitation: invitation.id, next }).toString()}` }
380
- : invitation.status === 'accepted' && invitees.has(invitation.id)
381
- ? { label: text.continueAs, href: chooseHref({ invitation: invitation.id }, next) }
382
- : null,
383
- })),
417
+ ...dev.invitations().map((invitation): MailView => {
418
+ const label = text.invitation(invitation.role, scopeLabel(invitation.scope.type, invitation.scope.value))
419
+ const mail = invitationMailOf(invitation)
420
+ return {
421
+ to: invitation.email,
422
+ subject: mail?.subject ?? label,
423
+ subjectLocale: mail === undefined ? null : invitation.mailLocale,
424
+ note: `${label} · ${invitation.mailLocale}`,
425
+ at: invitation.sentAt * 1000,
426
+ key: null,
427
+ status: invitation.status,
428
+ answer: null,
429
+ actions: [...invitationActions(invitation, next), { label: text.openMessage, href: `${MAIL_PATH}${invitation.id}` }],
430
+ }
431
+ }),
384
432
  ...dev.mails().map((sent): MailView => ({
385
433
  to: sent.to,
386
434
  subject: sent.subject,
435
+ subjectLocale: null,
387
436
  at: Date.parse(sent.at),
388
437
  key: sent.key,
389
438
  status: sent.outcome === 'accepted' ? 'sent' : sent.outcome,
390
439
  answer: sent.answer === 'accepted' ? null : sent.answer,
391
- action: { label: text.openMessage, href: `${MAIL_PATH}${sent.id}` },
440
+ note: null,
441
+ actions: [{ label: text.openMessage, href: `${MAIL_PATH}${sent.id}` }],
392
442
  })),
393
443
  ]),
394
444
  outbox: [...outbox.outbox()].reverse().map((message): OutboxView => ({ ...mailHeadOf(message), href: `${OUTBOX_PATH}${message.id}` })),
@@ -503,11 +553,18 @@ async function serveDevKit(
503
553
  })
504
554
  }
505
555
 
506
- /** A message a job handed to the mail stand-in: its fields, its text, and its HTML in a sandboxed frame. */
556
+ /**
557
+ * A message a job handed to the mail stand-in, or the e-mail of an invitation the stand-in IAM sent: its fields, its
558
+ * text, and its HTML in a sandboxed frame.
559
+ */
507
560
  const mailMessage = (request: Request, path: string): Response => {
561
+ const view = viewOf(choiceOf(request), firstSpa)
508
562
  const sent = dev.mails().find((candidate) => `${MAIL_PATH}${candidate.id}` === path)
509
- if (sent === undefined) return plain(404, 'no such mail in app dev')
510
- return new Response(mailPage(viewOf(choiceOf(request), firstSpa), sent), { headers: PAGE_HEADERS })
563
+ if (sent !== undefined) return new Response(mailPage(view, sent), { headers: PAGE_HEADERS })
564
+ const invitation = dev.invitations().find((candidate) => `${MAIL_PATH}${candidate.id}` === path)
565
+ const mail = invitation === undefined ? undefined : invitationMailOf(invitation)
566
+ if (invitation === undefined || mail === undefined) return plain(404, 'no such mail in app dev')
567
+ return new Response(invitationMailPage(view, invitation, mail, invitationActions(invitation, firstSpa)), { headers: PAGE_HEADERS })
511
568
  }
512
569
 
513
570
  const devRoute = (request: Request, url: URL): Response | null => {
@@ -534,7 +591,6 @@ async function serveDevKit(
534
591
  }
535
592
  }
536
593
 
537
- let port = options.port
538
594
  const server = listen({
539
595
  hostname: options.host,
540
596
  port: options.port,
@@ -552,16 +608,15 @@ async function serveDevKit(
552
608
  error: () => plain(500, 'app dev could not serve the request'),
553
609
  })
554
610
  port = server.port ?? options.port
555
- const host = options.host.includes(':') ? `[${options.host}]` : options.host
556
611
  return {
557
- url: `http://${host}:${port}/`,
612
+ url: `http://${urlHost}:${port}/`,
558
613
  seeded: { personas: seeded.personas.length, links: seeded.links.length },
559
614
  async stop() {
560
615
  try {
561
616
  await server.stop(true)
562
617
  } finally {
563
618
  restoreFetch()
564
- await postgres?.close()
619
+ await testDb?.close()
565
620
  }
566
621
  },
567
622
  }