@sssb/kit 0.0.0-stage → 0.2.0

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.
Files changed (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -3
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,295 @@
1
+ import { afterAll, beforeAll, expect, vi } from 'vitest'
2
+ import { dataRoot, setDataRoot } from '../../adapters/fake/data-dir'
3
+ import type { MessageTree } from '../../i18n/messages'
4
+ import { keepTestTmpDir, makeTestTmpDir, removeTestTmpDir } from '../tmp-dir'
5
+ import type { CheckImpl } from './types'
6
+
7
+ /**
8
+ * `demo-presets`: SEAM CONFORMANCE for demo presets (@sssb/kit/core/presets.ts). A preset replays on two hosts that
9
+ * share no code path, so a preset naming a person, team, handler or flag the world does not have would fail
10
+ * differently on each — or, worse, quietly do nothing on one. This holds every registered preset to the seed and
11
+ * the registries it will replay against, and its copy to both catalogs, at build time.
12
+ *
13
+ * The world is DERIVED (seed people, seed orgs, the composed inbound registry, KNOWN_FLAGS, the registered actors),
14
+ * never listed here, so the check cannot drift from what the replays actually consult. So is the operation registry:
15
+ * SSSB's kinds composed with the app's (`composePresetOperations(appPresetOperations)`), and held both ways to the
16
+ * server halves the replay dispatches to — a kind with a definition and no server half would pass the static check
17
+ * and then throw on the first replay. (The STATIC halves are supplied by each app's static composition root at
18
+ * runtime, where no unit test can see them; the static demo's e2e loads every registered preset instead.)
19
+ *
20
+ * The static check is not the whole proof: the last test REPLAYS every registered preset through the server path
21
+ * (@sssb/kit/server-lib/demo-presets.ts) against this app's real seed, migrations and handlers, so a preset that
22
+ * only an e2e would have caught throwing fails here. Same harness as demo-presets.test.ts: a throwaway data dir, a
23
+ * cookie jar, a stub translator, and the fake adapters standing in for the `server-only` registry.
24
+ *
25
+ * THE DATA DIR. The fake adapters keep their world under APP_DATA_DIR, else the working directory's `.data`, which is
26
+ * the developer's own dev world: a replay there would reset and reseed it. So `setup` ASSIGNS APP_DATA_DIR for the
27
+ * check's tests (`setDataRoot`), never `vi.stubEnv`, which an adopter's `unstubEnvs: true` undoes before every test,
28
+ * and every test that reaches the adapters first proves the scratch dir is still in effect (`inScratchWorld`),
29
+ * failing rather than replaying anywhere else. Its teardown closes the fake database the replay opened there before
30
+ * deleting the dir, so a file run after it without isolation opens its own, and before any of that waits for a replay
31
+ * that outlived its test's timeout to stop (see `demoPresets`), so it never runs on into the developer's world.
32
+ *
33
+ * THE MOCKS. A test file's `vi.mock` is hoisted above its imports; a library's is not, so `setup` registers them
34
+ * with `vi.doMock` while the suite is collected, before any test runs, and every module that reaches them (the
35
+ * adapter registry, `next/headers`, `next-intl/server`) is imported only afterwards, inside a test. Nothing the
36
+ * suite imports statically loads `../../adapters/index`. A mock that silently failed to apply would leave the replay
37
+ * on the REAL registry, so the tests that rely on it first prove it applied (`mockedRegistry`).
38
+ */
39
+
40
+ const cookieStore = new Map<string, { value: string }>()
41
+
42
+ /** Set on the mocked adapter registry, so a test can tell the mock from the real module. */
43
+ const MOCK_MARK = '__sssbConformanceMock'
44
+
45
+ function mockServerOnlyWorld(): void {
46
+ vi.doMock('next/headers', () => ({
47
+ cookies: async () => ({
48
+ get: (name: string) => cookieStore.get(name),
49
+ set: (name: string, value: string) => cookieStore.set(name, { value }),
50
+ delete: (name: string) => cookieStore.delete(name),
51
+ }),
52
+ }))
53
+ vi.doMock('../../adapters/index', async () => ({
54
+ [MOCK_MARK]: true,
55
+ isSimulated: true,
56
+ auth: (await import('../../adapters/fake/auth')).fakeAuth,
57
+ db: (await import('../../adapters/fake/db')).fakeDb,
58
+ email: (await import('../../adapters/fake/email')).fakeEmail,
59
+ analytics: (await import('../../adapters/fake/analytics')).fakeAnalytics,
60
+ }))
61
+ vi.doMock('next-intl/server', () => ({
62
+ getTranslations: async () => (key: string) => key,
63
+ }))
64
+ }
65
+
66
+ /** Fails loudly when the adapter registry the replay will reach is not the mock `setup` registered. */
67
+ async function mockedRegistry(): Promise<void> {
68
+ const notMocked = (detail: string) =>
69
+ new Error(
70
+ "demo-presets: the adapter registry is not the conformance suite's mock (registered with vi.doMock while " +
71
+ 'the file was collected), so the replay would run on the real adapters. Vitest hands the REAL module to ' +
72
+ "an import made while a mock's factory is still running, so another test of this file importing " +
73
+ '@sssb/kit/adapters/index (or a module that does) at the same moment does this (`it.concurrent`, ' +
74
+ '`describe.concurrent`: the suite runs its own tests one at a time); so does a `vi.doUnmock` or ' +
75
+ `\`vi.unmock\` of it. ${detail}`,
76
+ )
77
+ let registry: Record<string, unknown>
78
+ try {
79
+ registry = await import('../../adapters/index')
80
+ } catch (error) {
81
+ // The real registry refuses to load outside a server (`server-only`), which is how this usually shows.
82
+ throw notMocked(`Loading the real one failed: ${error instanceof Error ? error.message : String(error)}`)
83
+ }
84
+ if (registry[MOCK_MARK] !== true) throw notMocked('The real one loaded.')
85
+ }
86
+
87
+ function resolve(tree: MessageTree, key: string): unknown {
88
+ return key.split('.').reduce<unknown>((node, part) => (node as MessageTree | undefined)?.[part], tree)
89
+ }
90
+
91
+ async function registries() {
92
+ const { appPresetOperations, presets } = await import('@sssb/app-config/presets')
93
+ const { composePresetOperations } = await import('../../core/presets')
94
+ return { presets, definitions: composePresetOperations(appPresetOperations) }
95
+ }
96
+
97
+ /** One file's scratch world: the dir, the APP_DATA_DIR it replaced, and the replay running in it, if one is. */
98
+ interface ScratchWorld {
99
+ dir: string
100
+ previous: string | undefined
101
+ /** Set when the file's teardown begins: a replay still running stops before its next preset. */
102
+ stopping: boolean
103
+ /** The replay test's body, settled or not, which runs on past a timeout of its test (Vitest cannot stop it). */
104
+ replay?: Promise<void>
105
+ }
106
+
107
+ /** The check's scratch world while its tests run; undefined outside them. */
108
+ let world: ScratchWorld | undefined
109
+
110
+ /** The scratch world; fails loudly, before any adapter is touched, when the fake adapters would not write into it. */
111
+ function inScratchWorld(): ScratchWorld {
112
+ const root = dataRoot()
113
+ if (world === undefined || root !== world.dir) {
114
+ throw new Error(
115
+ `demo-presets: the fake adapters' data dir is ${root}, not the check's scratch dir (${world?.dir ?? 'not made'}), ` +
116
+ 'so a replay would reset and reseed that world. Something reassigned APP_DATA_DIR after the check set it.',
117
+ )
118
+ }
119
+ return world
120
+ }
121
+
122
+ const REPLAY_TEST =
123
+ 'replay on the server host: every operation performed, every invite pending, every hold set, the viewpoint signed in'
124
+
125
+ /** Whether `promise` settles within `ms`. */
126
+ async function settlesWithin(promise: Promise<void>, ms: number): Promise<boolean> {
127
+ let timer: ReturnType<typeof setTimeout> | undefined
128
+ const timedOut = new Promise<false>((resolve) => (timer = setTimeout(() => resolve(false), ms)))
129
+ try {
130
+ return await Promise.race([promise.then(() => true), timedOut])
131
+ } finally {
132
+ clearTimeout(timer)
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Leaves `own`: closes the database the replay opened there, points the adapters back, then deletes the dir. In this
138
+ * order, in one function: without isolation the next file shares this one's globals, and a client left cached on
139
+ * `globalThis` would serve it this world; and the check removes its directory itself, because a teardown deferred
140
+ * past the file (`keepTestTmpDir`) outlives the file's cleanup. `onlyIfStillOurs` (that deferred teardown) closes the
141
+ * database only while the adapters still point here: by then a later file may have opened its own.
142
+ */
143
+ async function leaveWorld(own: ScratchWorld, onlyIfStillOurs: boolean): Promise<void> {
144
+ try {
145
+ if (!onlyIfStillOurs || dataRoot() === own.dir) await (await import('../../adapters/fake/db')).closeFakeDb()
146
+ } finally {
147
+ if (dataRoot() === own.dir) setDataRoot(own.previous)
148
+ removeTestTmpDir(own.dir)
149
+ if (world === own) world = undefined
150
+ }
151
+ }
152
+
153
+ /**
154
+ * THE REPLAY OUTLIVING ITS TEST. A test that times out fails, but its body runs on: Vitest cannot stop a promise. A
155
+ * replay still running when the file tears down would, once APP_DATA_DIR is restored, reopen the database and write
156
+ * its files under the working directory's `.data`, the developer's world. So the teardown first marks the world as
157
+ * stopping (the replay goes no further than the preset it is in) and waits for the replay to settle, up to
158
+ * `replayStopWaitMs`. If it still has not, the teardown fails, saying so, and leaves APP_DATA_DIR on the scratch dir
159
+ * for the replay to finish in; the dir is closed and removed once it settles. Tests of the check set the wait (and
160
+ * the replay's timeout, in `timeouts`) before registering the suite; nothing an adopter configures reaches either.
161
+ */
162
+ export const demoPresets: CheckImpl & { replayStopWaitMs: number } = {
163
+ replayStopWaitMs: 30_000,
164
+ setup: () => {
165
+ mockServerOnlyWorld()
166
+ const stopWaitMs = demoPresets.replayStopWaitMs
167
+ beforeAll(() => {
168
+ const dir = makeTestTmpDir('app-demo-presets-seam-')
169
+ world = { dir, previous: setDataRoot(dir), stopping: false }
170
+ })
171
+ // ONE hook, so the order holds whatever `sequence.hooks` says (see `leaveWorld`).
172
+ afterAll(async () => {
173
+ const own = world
174
+ if (own === undefined) return
175
+ own.stopping = true
176
+ if (own.replay !== undefined && !(await settlesWithin(own.replay, stopWaitMs))) {
177
+ // The file's own cleanup still runs after this teardown fails (Vitest runs every afterAll), and would
178
+ // delete the dir under the running replay: it is the replay's now, removed when the replay stops.
179
+ keepTestTmpDir(own.dir)
180
+ // Its failure has nowhere to be reported by then; the error below has already said what is left behind.
181
+ void own.replay.then(() => leaveWorld(own, true)).catch(() => undefined)
182
+ throw new Error(
183
+ `demo-presets: the replay was still running ${stopWaitMs / 1000} s after its test ended (it ` +
184
+ `times out at ${(demoPresets.timeouts?.[REPLAY_TEST] ?? 0) / 1000} s), so APP_DATA_DIR ` +
185
+ `stays on the check's scratch dir (${own.dir}) until it stops, and the dir is removed ` +
186
+ 'then: pointing the adapters back now would let it write into the developer world.',
187
+ )
188
+ }
189
+ await leaveWorld(own, false)
190
+ }, stopWaitMs + 30_000)
191
+ },
192
+ timeouts: { [REPLAY_TEST]: 60_000 },
193
+ tests: {
194
+ 'describe only worlds the product could reach': async () => {
195
+ const { presets, definitions } = await registries()
196
+ const { presetProblems } = await import('../../core/presets')
197
+ const { actors } = await import('@sssb/app-config/actors')
198
+ const { organizations, people } = await import('@sssb/app-config/seed')
199
+ const { KNOWN_FLAGS } = await import('../../adapters/fake/analytics')
200
+ const { inboundHandlers } = await import('../../inbound-email/handlers')
201
+ const problems = presetProblems(
202
+ presets,
203
+ {
204
+ people: people.map((person) => ({
205
+ id: person.id,
206
+ email: person.email,
207
+ memberships: person.memberships,
208
+ restricted: person.restricted,
209
+ })),
210
+ orgSlugs: organizations.map((org) => org.slug),
211
+ handlers: Object.keys(inboundHandlers),
212
+ flags: KNOWN_FLAGS,
213
+ actors: actors.map((actor) => actor.id),
214
+ },
215
+ definitions,
216
+ )
217
+ expect(problems).toEqual([])
218
+ },
219
+ 'use only operation kinds the registry defines': async () => {
220
+ const { presets, definitions } = await registries()
221
+ const used = new Set(
222
+ presets.flatMap((preset) => (preset.operations ?? []).map((operation) => operation.op)),
223
+ )
224
+ expect([...used].filter((kind) => !Object.hasOwn(definitions, kind))).toEqual([])
225
+ },
226
+ 'have a server half for every defined operation kind, and no server half without a definition': async () => {
227
+ inScratchWorld()
228
+ await mockedRegistry()
229
+ const { definitions } = await registries()
230
+ const { presetOperationHandlers } = await import('../../server-lib/demo-presets')
231
+ expect(Object.keys(presetOperationHandlers).sort()).toEqual(Object.keys(definitions).sort())
232
+ },
233
+ 'resolve their title and summary in BOTH catalogs': async () => {
234
+ const { presets } = await registries()
235
+ const { loadAppMessages } = await import('@sssb/app-config/messages')
236
+ const missing: string[] = []
237
+ for (const locale of ['en', 'es']) {
238
+ const catalog = await loadAppMessages(locale)
239
+ for (const preset of presets) {
240
+ for (const key of [preset.titleKey, preset.summaryKey]) {
241
+ if (typeof resolve(catalog, key) !== 'string') missing.push(`${locale} is missing ${key}`)
242
+ }
243
+ }
244
+ }
245
+ expect(missing).toEqual([])
246
+ },
247
+ [REPLAY_TEST]: async () => {
248
+ const own = inScratchWorld()
249
+ const replay = replayEveryPreset(own)
250
+ own.replay = replay.then(
251
+ () => undefined,
252
+ () => undefined,
253
+ )
254
+ await replay
255
+ },
256
+ },
257
+ }
258
+
259
+ /** The replay test's body: every registered preset, replayed in `own` and held to its expanded script. */
260
+ async function replayEveryPreset(own: ScratchWorld): Promise<void> {
261
+ await mockedRegistry()
262
+ const { presets } = await registries()
263
+ const { expandPreset } = await import('../../core/presets')
264
+ const { applyDemoPreset } = await import('../../server-lib/demo-presets')
265
+ const { fakeAuth } = await import('../../adapters/fake/auth')
266
+ const { readActorHolds } = await import('../../adapters/fake/simulator')
267
+ for (const preset of presets) {
268
+ // What replays is the EXPANDED preset (`extends` chain flattened): a child's inherited invites
269
+ // and viewpoint are as much its world as its own.
270
+ const expanded = expandPreset(preset.id, presets)
271
+ if (!expanded) throw new Error(`${preset.id} does not expand (unknown base or a cycle)`)
272
+ if (own.stopping)
273
+ throw new Error(`demo-presets: the file is tearing down, so the replay stops before ${preset.id}`)
274
+ inScratchWorld()
275
+ const result = await applyDemoPreset(preset.id, { baseUrl: 'http://localhost:3000/' })
276
+ expect(result, preset.id).toEqual({ signedIn: expanded.viewpoint !== undefined })
277
+ // The replay reset the world first, so the hold file is exactly the script's last word per actor.
278
+ const expectedHolds: Record<string, boolean> = {}
279
+ for (const operation of expanded.operations) {
280
+ if (operation.op === 'actor.hold') expectedHolds[operation.actor] = operation.held
281
+ }
282
+ expect(readActorHolds(), `${preset.id}: actor holds`).toEqual(expectedHolds)
283
+ for (const operation of expanded.operations) {
284
+ if (operation.op !== 'invite') continue
285
+ const members = await fakeAuth.listMembers(operation.org)
286
+ expect(
287
+ members.some((member) => member.status === 'invited' && member.email === operation.email),
288
+ `${preset.id}: invite to ${operation.email}`,
289
+ ).toBe(true)
290
+ }
291
+ if (expanded.viewpoint !== undefined) {
292
+ expect((await fakeAuth.getCurrentUser())?.id, preset.id).toBe(expanded.viewpoint)
293
+ }
294
+ }
295
+ }
@@ -0,0 +1,80 @@
1
+ import { expect } from 'vitest'
2
+ import enFramework from '../../i18n/messages/en.json'
3
+ import esFramework from '../../i18n/messages/es.json'
4
+ import { mergeMessages, type MessageTree } from '../../i18n/messages'
5
+ import { FRAMEWORK_NAMESPACES } from '../../i18n/namespaces'
6
+ import type { CheckImpl } from './types'
7
+
8
+ // The app's half of the catalog arrives through the seam, imported when a test runs rather than when the suite is
9
+ // collected, so a seam that fails to load fails its checks by name instead of the whole file.
10
+ const seamMessages = () => import('@sssb/app-config/messages')
11
+
12
+ /**
13
+ * `i18n-partition`: the framework/app namespace partition (ADR-0012), and it is PHYSICAL: each side's catalog must
14
+ * hold exactly its own namespaces, the two lists must be DISJOINT, and the merged catalog's top-level keys must be
15
+ * exactly their union — so no namespace is orphaned or served twice. (en/es parity is `i18n-parity`.)
16
+ */
17
+ export const i18nPartition: CheckImpl = {
18
+ tests: {
19
+ 'FRAMEWORK and APP namespaces are disjoint': async () => {
20
+ const { APP_NAMESPACES } = await seamMessages()
21
+ const app: readonly string[] = APP_NAMESPACES
22
+ expect(FRAMEWORK_NAMESPACES.filter((ns) => app.includes(ns))).toEqual([])
23
+ },
24
+ "the framework catalog's top-level keys are exactly FRAMEWORK_NAMESPACES": () => {
25
+ expect(Object.keys(enFramework).sort()).toEqual([...FRAMEWORK_NAMESPACES].sort())
26
+ },
27
+ "the app catalog's top-level keys are exactly APP_NAMESPACES": async () => {
28
+ const { APP_NAMESPACES, loadAppMessages } = await seamMessages()
29
+ expect(Object.keys(await loadAppMessages('en')).sort()).toEqual([...APP_NAMESPACES].sort())
30
+ },
31
+ "the MERGED catalog's top-level keys are exactly FRAMEWORK ∪ APP": async () => {
32
+ const { APP_NAMESPACES, loadAppMessages } = await seamMessages()
33
+ const union = [...FRAMEWORK_NAMESPACES, ...APP_NAMESPACES].sort()
34
+ expect(Object.keys(mergeMessages(enFramework, await loadAppMessages('en'))).sort()).toEqual(union)
35
+ },
36
+ },
37
+ }
38
+
39
+ function flatten(tree: MessageTree, prefix = ''): Map<string, string> {
40
+ const out = new Map<string, string>()
41
+ for (const [key, value] of Object.entries(tree)) {
42
+ const at = prefix ? `${prefix}.${key}` : key
43
+ if (typeof value === 'string') out.set(at, value)
44
+ else for (const [k, v] of flatten(value, at)) out.set(k, v)
45
+ }
46
+ return out
47
+ }
48
+
49
+ const icuArgs = (msg: string) => [...msg.matchAll(/\{(\w+)/g)].map((m) => m[1]).sort()
50
+
51
+ function expectParity(en: MessageTree, es: MessageTree): void {
52
+ const enFlat = flatten(en)
53
+ const esFlat = flatten(es)
54
+ expect([...esFlat.keys()].sort()).toEqual([...enFlat.keys()].sort())
55
+ for (const [key, enMsg] of enFlat) {
56
+ const esMsg = esFlat.get(key)
57
+ if (esMsg !== undefined) expect.soft(icuArgs(esMsg), key).toEqual(icuArgs(enMsg))
58
+ }
59
+ }
60
+
61
+ /**
62
+ * `i18n-parity`: en/es parity over the MERGED catalog (the framework half + the app half, which arrives through the
63
+ * ADR-0012 seam). The catalogs are physically split, but what ships to the user is the merge — so that is what must
64
+ * stay key- and placeholder-identical. The framework half is checked on its own too, so the package carries a
65
+ * truthful guarantee independent of whatever app consumes it.
66
+ */
67
+ export const i18nParity: CheckImpl = {
68
+ tests: {
69
+ 'the framework catalog has identical key sets and ICU placeholders': () => {
70
+ expectParity(enFramework, esFramework)
71
+ },
72
+ 'the MERGED catalog (framework + app) has identical key sets and ICU placeholders': async () => {
73
+ const { loadAppMessages } = await seamMessages()
74
+ expectParity(
75
+ mergeMessages(enFramework, await loadAppMessages('en')),
76
+ mergeMessages(esFramework, await loadAppMessages('es')),
77
+ )
78
+ },
79
+ },
80
+ }
@@ -0,0 +1,200 @@
1
+ import { aroundAll, describe, it, type RunnerTask } from 'vitest'
2
+ import registry from '../checks.json'
3
+ import type { CheckImpl } from './types'
4
+
5
+ /**
6
+ * THE REGISTRATION BOTH RUNNERS SHARE: the unit suite (`conformanceSuite`, ./suite.ts) and the contract runner
7
+ * (`contractSuite`, ../contract.ts) register their checks, opt-outs and skip guard here, so the two cannot differ in
8
+ * what `sssb doctor` reads back from `vitest list --json`.
9
+ *
10
+ * WHAT IT REGISTERS is fixed by `../checks.json` (exported as `@sssb/kit/testing/checks.json`): per check of the
11
+ * runner, `describe('[sssb:<id>] <title>')` holding exactly the named `it`s, never a dynamic name, so every expected
12
+ * full name `[sssb:<id>] <title> > <test>` is computable from the data.
13
+ *
14
+ * OPT-OUTS are the only way to leave a check out: `optOut: { '<id>': '<why>' }`. An unknown id (another runner's
15
+ * included) or an empty reason throws while the file is collected, so a typo is a red run, never a silent skip, and
16
+ * an opted-out check registers ONE passing test `[sssb:opt-out:<id>] <why>` in its place, so `vitest list` shows the
17
+ * decision.
18
+ *
19
+ * THE SKIP GUARD fails the run if any registered test (opt-outs aside) did not run. It is a file-level `aroundAll`
20
+ * that checks once the file's whole run, its `afterAll` hooks included, has returned: an `afterAll` would be one of
21
+ * the file's own, which Vitest runs in turn and abandons at the first that throws, so a guard that fired there could
22
+ * leave the contract server running and the file's scratch directories on disk, under every `sequence.hooks` order.
23
+ * It runs whenever at least one test in the file runs, so an `it.only` beside the suite, or a `-t` filter that
24
+ * matches part of it, fails the run instead of skipping checks quietly. Its message names the cause it can tell: a
25
+ * check skipped because a setup hook failed (a `beforeAll` of the file or of the check, a `beforeEach`) is reported as
26
+ * that; one that was still to run when the file started and was stopped during it (`--bail`, an interrupted run) as a
27
+ * cancelled run; only the rest, skipped before the file ran, as a filter, an `.only` or a `.skip`. Each check's
28
+ * tests run in order (`describe.sequential`), under `sequence.concurrent` too. When EVERY test in the
29
+ * file is skipped no hook runs, and Vitest exits 0: that half is `sssb doctor`'s, which asks `vitest list --json`
30
+ * whether every check would run.
31
+ */
32
+
33
+ /** A check, as `checks.json` names it. */
34
+ interface RegisteredCheck {
35
+ id: string
36
+ runner: string
37
+ title: string
38
+ tests: string[]
39
+ }
40
+
41
+ export type Runner = 'unit' | 'contract'
42
+
43
+ const CHECKS: readonly RegisteredCheck[] = registry.checks
44
+
45
+ /** The checks one runner registers, in `checks.json`'s order (which is the order they run in). */
46
+ const checksOf = (runner: Runner): readonly RegisteredCheck[] => CHECKS.filter((check) => check.runner === runner)
47
+
48
+ /**
49
+ * Refuses, while the file is collected, an opt-out that names no check of this runner or gives no reason.
50
+ * `caller` names the function in the message (`conformanceSuite`, `contractSuite`).
51
+ */
52
+ export function checkOptOut(caller: string, runner: Runner, optOut: Readonly<Record<string, string>>): void {
53
+ const checks = checksOf(runner)
54
+ for (const [id, reason] of Object.entries(optOut)) {
55
+ if (!checks.some((check) => check.id === id)) {
56
+ throw new Error(
57
+ `${caller}: optOut names "${id}", which is not a check this suite registers ` +
58
+ `(${checks.map((check) => check.id).join(', ')})`,
59
+ )
60
+ }
61
+ if (typeof reason !== 'string' || reason.trim() === '') {
62
+ throw new Error(`${caller}: optOut "${id}" needs a reason`)
63
+ }
64
+ }
65
+ }
66
+
67
+ /** True when this runner has at least one check `optOut` leaves in: the ones that need setting up. */
68
+ export const runsAny = (runner: Runner, optOut: Readonly<Record<string, string>>): boolean =>
69
+ checksOf(runner).some((check) => optOut[check.id] === undefined)
70
+
71
+ /**
72
+ * Registers one runner's checks in the calling test file, with its opt-outs and the skip guard. Call it once, at the
73
+ * file's top level, after `checkOptOut`.
74
+ */
75
+ export function registerChecks<C>(options: {
76
+ caller: string
77
+ runner: Runner
78
+ implementations: Readonly<Record<string, CheckImpl<C>>>
79
+ optOut: Readonly<Record<string, string>>
80
+ context: C
81
+ }): void {
82
+ const { caller, runner, implementations, optOut, context } = options
83
+ const expected: string[] = []
84
+ const ran = new Set<string>()
85
+ for (const check of checksOf(runner)) {
86
+ const reason = optOut[check.id]
87
+ if (reason !== undefined) {
88
+ it(`[sssb:opt-out:${check.id}] ${reason}`, () => {})
89
+ continue
90
+ }
91
+ const impl = implementations[check.id]
92
+ const names = impl ? Object.keys(impl.tests) : []
93
+ if (!impl || names.join('\n') !== check.tests.join('\n')) {
94
+ throw new Error(
95
+ `${caller}: the implementation of "${check.id}" does not register exactly the tests checks.json ` +
96
+ `names for it (${check.tests.join('; ')})`,
97
+ )
98
+ }
99
+ const describeName = `[sssb:${check.id}] ${check.title}`
100
+ // SEQUENTIAL whatever the adopter's config says: under `sequence.concurrent` two of a check's tests would run
101
+ // at once, and Vitest's mocker hands an import made while a `vi.doMock` factory is still running the REAL
102
+ // module (demo-presets' registry mock), besides the checks' shared state (the data root, the fake world).
103
+ // `describe.sequential` changes no name, so `sssb doctor` reads the same list.
104
+ describe.sequential(describeName, () => {
105
+ impl.setup?.(context)
106
+ for (const test of check.tests) {
107
+ const name = `${describeName} > ${test}`
108
+ expected.push(name)
109
+ const body = impl.tests[test]!
110
+ it(
111
+ test,
112
+ async () => {
113
+ ran.add(name)
114
+ await body(context)
115
+ },
116
+ impl.timeouts?.[test],
117
+ )
118
+ }
119
+ })
120
+ }
121
+
122
+ // eslint-disable-next-line no-empty-pattern -- Vitest reads this parameter as the hook's fixtures and refuses anything but a destructuring pattern; the guard uses none, only the file (the third)
123
+ aroundAll(async (runSuite, {}, file) => {
124
+ // Which tests were still to run once the file was collected: a filter, an `.only` or a `.skip` has already
125
+ // marked the rest skipped by now, so a test that was to run and did not was stopped DURING the run.
126
+ const toRun = new Set<string>()
127
+ visitTests(file, (name, test) => {
128
+ if (test.mode === 'run') toRun.add(name)
129
+ })
130
+ await runSuite()
131
+ const skipped = expected.filter((name) => !ran.has(name))
132
+ if (skipped.length === 0) return
133
+ const underFailedHook = testsUnderAFailedSetup(file)
134
+ const blocked = skipped.filter((name) => underFailedHook.has(name))
135
+ const cancelled = skipped.filter((name) => !underFailedHook.has(name) && toRun.has(name))
136
+ const dropped = skipped.filter((name) => !underFailedHook.has(name) && !toRun.has(name))
137
+ const suite = runner === 'unit' ? 'conformance suite' : 'contract suite'
138
+ const parts: string[] = []
139
+ if (blocked.length > 0) {
140
+ parts.push(
141
+ `the SSSB ${suite} did not run ${blocked.length} of its checks because a hook failed (its error is ` +
142
+ `reported above; fix that and they run):\n ${blocked.join('\n ')}`,
143
+ )
144
+ }
145
+ if (cancelled.length > 0) {
146
+ parts.push(
147
+ `the SSSB ${suite} did not run ${cancelled.length} of its checks because the run was cancelled ` +
148
+ 'while this file ran (`--bail` stops the run after a failure, reported above; an interrupted run, or a ' +
149
+ `hook that called \`skip()\`, does the same):\n ${cancelled.join('\n ')}`,
150
+ )
151
+ }
152
+ if (dropped.length > 0) {
153
+ parts.push(
154
+ `the SSSB ${suite} did not run ${dropped.length} of its checks, and none of them is opted out:\n ` +
155
+ `${dropped.join('\n ')}\nA check is left out only by naming it in ${caller}({ optOut: { <id>: ` +
156
+ '<reason> } }); an `.only`, a `.skip` or a test-name filter that drops one fails the run.',
157
+ )
158
+ }
159
+ throw new Error(parts.join('\n'))
160
+ })
161
+ }
162
+
163
+ /** Calls `visit` on every test under `file`, named `<describe> > <test>` as `expected` names them. */
164
+ function visitTests(file: RunnerTask, visit: (name: string, test: RunnerTask) => void): void {
165
+ const walk = (task: RunnerTask, parent: string | undefined) => {
166
+ if (task.type === 'suite') {
167
+ for (const child of task.tasks) walk(child, task === file ? undefined : task.name)
168
+ } else if (parent !== undefined) {
169
+ visit(`${parent} > ${task.name}`, task)
170
+ }
171
+ }
172
+ walk(file, undefined)
173
+ }
174
+
175
+ /** True when a test under `task` (itself, if it is one) began: it has a pass or fail result of its own. */
176
+ function anyTestStarted(task: RunnerTask): boolean {
177
+ if (task.type === 'suite') return task.tasks.some(anyTestStarted)
178
+ return task.result?.state === 'pass' || task.result?.state === 'fail'
179
+ }
180
+
181
+ /**
182
+ * The tests (`<describe> > <test>`, as `expected` names them) that a SETUP hook which failed kept from running: one
183
+ * whose own result carries an error (its `beforeEach` threw), or one under a suite whose result carries an error
184
+ * while no test under that suite began (its `beforeAll` threw, which skips every test below it). An error on a suite
185
+ * where tests did begin came after them (an `afterAll`), and it skipped nothing.
186
+ */
187
+ function testsUnderAFailedSetup(file: RunnerTask): Set<string> {
188
+ const names = new Set<string>()
189
+ const visit = (task: RunnerTask, failed: boolean, parent: string | undefined) => {
190
+ const errored = (task.result?.errors?.length ?? 0) > 0
191
+ if (task.type === 'suite') {
192
+ const here = failed || (errored && !anyTestStarted(task))
193
+ for (const child of task.tasks) visit(child, here, task === file ? undefined : task.name)
194
+ } else if ((failed || errored) && parent !== undefined) {
195
+ names.add(`${parent} > ${task.name}`)
196
+ }
197
+ }
198
+ visit(file, false, undefined)
199
+ return names
200
+ }