@sssb/tools 0.2.0 → 0.3.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.
@@ -0,0 +1,218 @@
1
+ diff --git a/src/app-config/db/migrations/1001_items.ts b/src/app-config/db/migrations/1001_items.ts
2
+ deleted file mode 100644
3
+ index e7e9835..0000000
4
+ --- a/src/app-config/db/migrations/1001_items.ts
5
+ +++ /dev/null
6
+ @@ -1,37 +0,0 @@
7
+ -import { Kysely, sql } from 'kysely'
8
+ -
9
+ -/**
10
+ - * The `items` table — this app's only tenant-scoped table, carrying SSSB's RLS pattern (ADR-0004). It runs after every framework migration (name-sorted, 0001–0999
11
+ - * first), so it can reference `tenants` and `organizations` directly.
12
+ - *
13
+ - * Two deliberate differences from SSSB's reference app's `1001_tickets`: `org_id` is NOT NULL (this
14
+ - * app has no legacy rows to keep valid), and DELETE is NOT granted — an item can be listed and created,
15
+ - * never erased, which is the posture most real tables want and is proved in ../rls-proofs.ts.
16
+ - */
17
+ -export async function up(db: Kysely<any>): Promise<void> {
18
+ - await db.schema
19
+ - .createTable('items')
20
+ - .addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
21
+ - .addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
22
+ - .addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
23
+ - .addColumn('title', 'text', (col) => col.notNull())
24
+ - .addColumn('created_by_user_id', 'text', (col) => col.notNull())
25
+ - .addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
26
+ - .execute()
27
+ -
28
+ - await sql`GRANT SELECT, INSERT, UPDATE ON items TO app_user`.execute(db)
29
+ - await sql`ALTER TABLE items ENABLE ROW LEVEL SECURITY`.execute(db)
30
+ - await sql`ALTER TABLE items FORCE ROW LEVEL SECURITY`.execute(db)
31
+ - // NULLIF: unset tenant context must mean zero rows, never a cast error — a session that has
32
+ - // ever SET LOCAL this GUC reports '' (not NULL) afterwards. See ADR-0002 spike findings.
33
+ - await sql`
34
+ - CREATE POLICY tenant_isolation ON items
35
+ - FOR ALL
36
+ - USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
37
+ - WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
38
+ - `.execute(db)
39
+ -}
40
+ -
41
+ -export async function down(db: Kysely<any>): Promise<void> {
42
+ - await db.schema.dropTable('items').execute()
43
+ -}
44
+ diff --git a/src/app-config/db/migrations/1002_items_keyset_index.ts b/src/app-config/db/migrations/1002_items_keyset_index.ts
45
+ deleted file mode 100644
46
+ index 63c03d3..0000000
47
+ --- a/src/app-config/db/migrations/1002_items_keyset_index.ts
48
+ +++ /dev/null
49
+ @@ -1,29 +0,0 @@
50
+ -import { Kysely } from 'kysely'
51
+ -
52
+ -/**
53
+ - * The index that makes the items list pageable (`@sssb/kit/db/keyset`).
54
+ - *
55
+ - * A keyset page reads `WHERE tenant_id = … AND org_id = … AND (created_at, id) < ($1, $2)
56
+ - * ORDER BY created_at DESC, id DESC LIMIT n`. Without a matching index that is a scan of the team's whole
57
+ - * list on EVERY page. The column order mirrors the query: the equality columns first (`tenant_id` is a
58
+ - * predicate RLS adds to every statement, so it belongs in the index), then the ordering pair in the
59
+ - * direction the walk reads it.
60
+ - *
61
+ - * A SEPARATE migration rather than an edit to 1001: an applied migration is a record, not a document to
62
+ - * revise, and an app that already ran 1001 must be able to take this one. A brand-new table meant to be
63
+ - * paged would carry its index in its own create migration instead.
64
+ - *
65
+ - * Not unique: two rows can share `(tenant_id, org_id, created_at)` (one transaction shares one `now()`),
66
+ - * which is why `id` is in the key at all.
67
+ - */
68
+ -export async function up(db: Kysely<unknown>): Promise<void> {
69
+ - await db.schema
70
+ - .createIndex('items_keyset_idx')
71
+ - .on('items')
72
+ - .columns(['tenant_id', 'org_id', 'created_at desc', 'id desc'])
73
+ - .execute()
74
+ -}
75
+ -
76
+ -export async function down(db: Kysely<unknown>): Promise<void> {
77
+ - await db.schema.dropIndex('items_keyset_idx').execute()
78
+ -}
79
+ diff --git a/src/app-config/db/migrations/index.ts b/src/app-config/db/migrations/index.ts
80
+ index 5f35c0f..7edcf7b 100644
81
+ --- a/src/app-config/db/migrations/index.ts
82
+ +++ b/src/app-config/db/migrations/index.ts
83
+ @@ -1,13 +1,8 @@
84
+ import type { Migration } from 'kysely/migration'
85
+ -import * as m1001 from './1001_items'
86
+ -import * as m1002 from './1002_items_keyset_index'
87
+
88
+ /**
89
+ * The APP's migrations (the seam side of @sssb/kit/db/migrations, ADR-0012). Numbering convention: framework
90
+ * 0001–0999, app ≥1001. Composed into the framework registry, which Kysely runs NAME-SORTED — so these
91
+ - * run AFTER every framework table exists. Add new app migrations here in order.
92
+ + * run AFTER every framework table exists. Add new app migrations here in order. None yet: this app owns no table.
93
+ */
94
+ -export const appMigrations: Record<string, Migration> = {
95
+ - '1001_items': m1001,
96
+ - '1002_items_keyset_index': m1002,
97
+ -}
98
+ +export const appMigrations: Record<string, Migration> = {}
99
+ diff --git a/src/app-config/db/rls-proofs.ts b/src/app-config/db/rls-proofs.ts
100
+ index 153b345..df13ef4 100644
101
+ --- a/src/app-config/db/rls-proofs.ts
102
+ +++ b/src/app-config/db/rls-proofs.ts
103
+ @@ -1,6 +1,4 @@
104
+ -import { sql } from 'kysely'
105
+ import type { RlsProofSuite } from '@sssb/kit/db/rls-proofs'
106
+ -import { runWithTenant } from '@sssb/kit/db/with-tenant'
107
+
108
+ /**
109
+ * The APP's tenant-isolation proofs (the seam side of @sssb/kit/db/rls-proofs.ts, ADR-0004 + ADR-0012) —
110
+ @@ -9,73 +7,8 @@ import { runWithTenant } from '@sssb/kit/db/with-tenant'
111
+ * per-table privilege grants.
112
+ *
113
+ * @sssb/kit/db/rls-proof-runner.ts composes this with the framework half and runs the union, so these
114
+ - * assertions execute wherever that runner does. An adopter with no tenant tables leaves the body empty
115
+ - * (ADR-0012, "unused capability = empty registration"). Kept in lockstep with ./migrations.
116
+ + * assertions execute wherever that runner does. This app owns no tenant table yet, so the body is empty
117
+ + * (ADR-0012, "unused capability = empty registration"): `pnpm test:contract` runs only the framework's half.
118
+ + * Kept in lockstep with ./migrations.
119
+ */
120
+ -export const appRlsProofs: RlsProofSuite = async ({
121
+ - db,
122
+ - appDb,
123
+ - expect,
124
+ - alphaTenantId,
125
+ - demoTenantId,
126
+ - alphaOrgId,
127
+ - demoOrgId,
128
+ -}) => {
129
+ - // ---- items: tenant-only RLS (1001), single-org app scoping, SELECT/INSERT/UPDATE (no DELETE) ----
130
+ -
131
+ - await db
132
+ - .insertInto('items')
133
+ - .values([
134
+ - { tenant_id: alphaTenantId, org_id: alphaOrgId, title: 'first item', created_by_user_id: 'proof-user' },
135
+ - { tenant_id: alphaTenantId, org_id: alphaOrgId, title: 'second item', created_by_user_id: 'proof-user' },
136
+ - {
137
+ - tenant_id: demoTenantId,
138
+ - org_id: demoOrgId,
139
+ - title: 'other tenant item',
140
+ - created_by_user_id: 'proof-user',
141
+ - },
142
+ - ])
143
+ - .execute()
144
+ -
145
+ - // read isolation, both directions, via UNFILTERED selects under RLS
146
+ - const ours = await runWithTenant(appDb, alphaTenantId, (trx) => trx.selectFrom('items').selectAll().execute())
147
+ - expect(ours.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
148
+ - expect(ours.filter((r) => r.tenant_id === alphaTenantId).length).toBe(2)
149
+ - const theirs = await runWithTenant(appDb, demoTenantId, (trx) => trx.selectFrom('items').selectAll().execute())
150
+ - expect(theirs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
151
+ - expect(theirs.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
152
+ -
153
+ - // write isolation: an INSERT carrying the OTHER tenant's id is rejected by WITH CHECK, even though
154
+ - // the org id is a real org — the tenant, not the org, is the RLS boundary.
155
+ - let writeRejected = false
156
+ - try {
157
+ - await runWithTenant(appDb, alphaTenantId, (trx) =>
158
+ - trx
159
+ - .insertInto('items')
160
+ - .values({
161
+ - tenant_id: demoTenantId,
162
+ - org_id: demoOrgId,
163
+ - title: 'smuggled',
164
+ - created_by_user_id: 'proof-user',
165
+ - })
166
+ - .execute(),
167
+ - )
168
+ - } catch (error) {
169
+ - writeRejected = /row-level security/.test(String(error))
170
+ - }
171
+ - expect(writeRejected).toBe(true)
172
+ -
173
+ - // DELETE is denied at the PRIVILEGE layer — the 1001 grant is SELECT/INSERT/UPDATE only, so an
174
+ - // item can never be erased even by a correctly-scoped caller.
175
+ - let deleteRejected = false
176
+ - try {
177
+ - await appDb.transaction().execute(async (trx) => {
178
+ - await sql`SET LOCAL ROLE app_user`.execute(trx)
179
+ - await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
180
+ - await sql`DELETE FROM items`.execute(trx)
181
+ - })
182
+ - } catch (error) {
183
+ - deleteRejected = /permission denied/.test(String(error))
184
+ - }
185
+ - expect(deleteRejected).toBe(true)
186
+ -}
187
+ +export const appRlsProofs: RlsProofSuite = async () => {}
188
+ diff --git a/src/app-config/db/schema.ts b/src/app-config/db/schema.ts
189
+ index e9fb0b5..c36b51e 100644
190
+ --- a/src/app-config/db/schema.ts
191
+ +++ b/src/app-config/db/schema.ts
192
+ @@ -1,23 +1,9 @@
193
+ -import type { Generated } from 'kysely'
194
+ -
195
+ /**
196
+ * The APP's tenant-scoped tables (the seam side of @sssb/kit/db/schema.ts, ADR-0012). The framework owns its
197
+ * tables + the `DB` interface, which `extends AppTables` (a type-only seam import). Kept in lockstep
198
+ - * with the migrations in ./migrations (numbered ≥1001).
199
+ + * with the migrations in ./migrations (numbered ≥1001). None yet: this app owns no table, and an empty
200
+ + * `Record<never, never>` is the empty registration.
201
+ */
202
+
203
+ -interface ItemsTable {
204
+ - id: Generated<string>
205
+ - tenant_id: string
206
+ - /** The team that owns the item. NOT NULL — an app-level filter, not an RLS anchor (1001). */
207
+ - org_id: string
208
+ - title: string
209
+ - /** Opaque user id (no users table) — same convention as the framework's jobs / service_keys. */
210
+ - created_by_user_id: string
211
+ - created_at: Generated<string>
212
+ -}
213
+ -
214
+ /** The app's tables, merged into the framework `DB` interface (@sssb/kit/db/schema.ts `extends AppTables`). */
215
+ -export interface AppTables {
216
+ - items: ItemsTable
217
+ -}
218
+ +export type AppTables = Record<never, never>
@@ -0,0 +1,122 @@
1
+ // @ts-check
2
+ // A unified diff applied EXACTLY, for `sssb remove-items`: a hunk applies only where every line it names (context and
3
+ // removed alike) is found, once, in the file as it is. There is no fuzz and no guessing: a file the adopter has
4
+ // edited inside a hunk is refused, never patched around, and a file that is not found, or is found twice, is
5
+ // refused too. A hunk may move (the adopter added lines above it); it may not change.
6
+ //
7
+ // Why this and not `git apply`: it must work where there is no repository (a tarball, a scratch copy), and say what it
8
+ // would refuse before it touches a file.
9
+ //
10
+ // The patches are `git diff --no-renames -U3 --relative=<app>` between the starter and the starter with the Items
11
+ // slice taken out; `tests/tooling/remove-items.test.ts` proves they apply to an app the generator wrote from the
12
+ // starter, and leave no Items behind.
13
+
14
+ /** One line of a hunk: ' ' (context, kept), '-' (removed) or '+' (added). @typedef {{ op: ' ' | '-' | '+', text: string }} HunkLine */
15
+ /** @typedef {{ lines: HunkLine[] }} Hunk */
16
+ /** @typedef {{ path: string, status: 'modify' | 'delete' | 'add', hunks: Hunk[] }} FilePatch */
17
+
18
+ /**
19
+ * @param {string} text a unified diff, as `git diff --no-renames` writes it
20
+ * @returns {FilePatch[]}
21
+ */
22
+ export function parsePatch(text) {
23
+ /** @type {FilePatch[]} */
24
+ const files = []
25
+ /** @type {FilePatch | null} */
26
+ let file = null
27
+ /** @type {Hunk | null} */
28
+ let hunk = null
29
+ for (const line of text.split('\n')) {
30
+ if (line.startsWith('diff --git ')) {
31
+ file = { path: '', status: 'modify', hunks: [] }
32
+ files.push(file)
33
+ hunk = null
34
+ } else if (file === null) {
35
+ continue
36
+ } else if (hunk === null && line.startsWith('new file mode')) {
37
+ file.status = 'add'
38
+ } else if (hunk === null && line.startsWith('deleted file mode')) {
39
+ file.status = 'delete'
40
+ } else if (hunk === null && line.startsWith('--- ')) {
41
+ if (line !== '--- /dev/null') file.path = unprefix(line.slice(4), 'a/')
42
+ } else if (hunk === null && line.startsWith('+++ ')) {
43
+ if (line !== '+++ /dev/null' && file.path === '') file.path = unprefix(line.slice(4), 'b/')
44
+ } else if (line.startsWith('@@ ')) {
45
+ hunk = { lines: [] }
46
+ file.hunks.push(hunk)
47
+ } else if (hunk !== null && (line[0] === ' ' || line[0] === '-' || line[0] === '+')) {
48
+ hunk.lines.push({ op: /** @type {' ' | '-' | '+'} */ (line[0]), text: line.slice(1) })
49
+ }
50
+ }
51
+ for (const parsed of files) {
52
+ if (parsed.path === '' || parsed.hunks.length === 0)
53
+ throw new Error(`a malformed patch: ${parsed.path || '(no path)'}`)
54
+ }
55
+ return files
56
+ }
57
+
58
+ /**
59
+ * @param {string} value
60
+ * @param {string} prefix
61
+ */
62
+ function unprefix(value, prefix) {
63
+ if (!value.startsWith(prefix)) throw new Error(`a malformed patch path: ${value}`)
64
+ return value.slice(prefix.length)
65
+ }
66
+
67
+ /**
68
+ * Applies one file's hunks to its text. Returns the new text, or null when the patch removes the file.
69
+ * @param {string | null} original the file's text, null when it does not exist
70
+ * @param {FilePatch} patch
71
+ * @returns {{ ok: true, content: string | null } | { ok: false, reason: string }}
72
+ */
73
+ export function applyFilePatch(original, patch) {
74
+ if (patch.status === 'add') {
75
+ if (original !== null) return { ok: false, reason: 'it already exists (the patch would add it)' }
76
+ const added = patch.hunks.flatMap((h) => h.lines.filter((l) => l.op === '+').map((l) => l.text))
77
+ return { ok: true, content: `${added.join('\n')}\n` }
78
+ }
79
+ if (original === null) return { ok: false, reason: 'it is not there' }
80
+ const endsWithNewline = original.endsWith('\n')
81
+ let lines = original.split('\n')
82
+ if (endsWithNewline) lines.pop()
83
+ for (const hunk of patch.hunks) {
84
+ const from = hunk.lines.filter((l) => l.op !== '+').map((l) => l.text)
85
+ const to = hunk.lines.filter((l) => l.op !== '-').map((l) => l.text)
86
+ const at = matches(lines, from)
87
+ if (at.length !== 1) {
88
+ if (patch.status === 'delete' && at.length === 0)
89
+ return { ok: false, reason: 'it is not the file the starter wrote (the slice deletes it whole)' }
90
+ const first =
91
+ hunk.lines.find((l) => l.op === '-' && l.text.trim() !== '')?.text.trim() ?? from.join(' ').trim()
92
+ return {
93
+ ok: false,
94
+ reason:
95
+ at.length === 0
96
+ ? `it differs from the starter's where the patch edits it, near: ${first.slice(0, 80)}`
97
+ : `the place the patch edits is ambiguous (${at.length} matches), near: ${first.slice(0, 80)}`,
98
+ }
99
+ }
100
+ lines = [...lines.slice(0, at[0]), ...to, ...lines.slice(at[0] + from.length)]
101
+ }
102
+ if (patch.status === 'delete')
103
+ return lines.length === 0
104
+ ? { ok: true, content: null }
105
+ : { ok: false, reason: 'it holds more than the starter wrote' }
106
+ return { ok: true, content: lines.join('\n') + (endsWithNewline ? '\n' : '') }
107
+ }
108
+
109
+ /**
110
+ * Where `from` (a hunk's context and removed lines) is found in `lines`.
111
+ * @param {string[]} lines
112
+ * @param {string[]} from
113
+ * @returns {number[]}
114
+ */
115
+ function matches(lines, from) {
116
+ /** @type {number[]} */
117
+ const found = []
118
+ for (let i = 0; i + from.length <= lines.length; i++) {
119
+ if (from.every((text, k) => lines[i + k] === text)) found.push(i)
120
+ }
121
+ return found
122
+ }
package/src/tick/tick.js CHANGED
@@ -6,9 +6,9 @@
6
6
  // the by-hand, as one command; `sssb dev-tick` (dev-tick.js) is the same call on a timer, opt-in.
7
7
  //
8
8
  // What this is NOT: a way around the route's guard. The route is `withWebhookSecret(...)`, and this sends it the
9
- // per-checkout dev secret (`<app>/.data/auth/webhook-secret`, the file the simulated server generates) as a bearer,
10
- // exactly as an external caller would. It adds nothing to the server: no flag, no header the server honours, no
11
- // route. A server in real mode checks `WEBHOOK_SECRET` instead, never reads that file, and answers this 401.
9
+ // per-checkout dev secret (`<app>/.data/auth/webhook-secret`, the file the simulated server generates) in its header,
10
+ // exactly as an external caller would. It adds nothing to the server: no flag, no header beyond the credential every
11
+ // caller sends, no route. A server in real mode checks `WEBHOOK_SECRET` instead, never reads that file, and answers this 401.
12
12
  //
13
13
  // Run through the package script (`pnpm tick`, `pnpm tick:starter`): the working directory is then the app's, which is
14
14
  // where the server keeps `.data` (`APP_DATA_DIR` overrides it, for both).
@@ -58,7 +58,7 @@ const MIN_TIMEOUT_SECONDS = 0.1
58
58
  const MAX_TIMEOUT_SECONDS = 3600
59
59
 
60
60
  const USAGE = `usage: pnpm tick [--url <origin>] [--timeout <seconds>] (sssb tick also takes --app <dir>)
61
- (per app: pnpm tick = showcase, pnpm tick:starter = starter; direct: sssb tick <${TICK_APPS.join('|')}, or the slot an app declares for itself> ...)
61
+ (with no slot it ticks the app's own, the slot its package.json declares; or name one: sssb tick <${TICK_APPS.join('|')}, or the slot an app declares for itself> ...)
62
62
 
63
63
  --url <origin> the dev server's origin, loopback only (default: this checkout's port for the app)
64
64
  --timeout <seconds> give up on the request after this long, ${MIN_TIMEOUT_SECONDS} to ${MAX_TIMEOUT_SECONDS} (default ${DEFAULT_TIMEOUT_SECONDS})`
@@ -76,7 +76,7 @@ export class TickError extends Error {
76
76
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
77
77
 
78
78
  /**
79
- * Loopback only. The bearer is the dev secret and it is sent in the clear, so a URL that is not this machine is
79
+ * Loopback only. The secret is the dev secret and it is sent in the clear, so a URL that is not this machine is
80
80
  * refused rather than trusted: there is no flag to point this at a real deployment, whose scheduler is not this.
81
81
  *
82
82
  * @param {string} value
@@ -91,7 +91,7 @@ export function parseLoopbackOrigin(value) {
91
91
  }
92
92
  if (url.protocol !== 'http:' || !LOOPBACK_HOSTS.has(url.hostname)) {
93
93
  throw new TickError(
94
- `--url must be http on localhost, 127.0.0.1 or [::1] (the dev secret is sent as a bearer), got "${value}"`,
94
+ `--url must be http on localhost, 127.0.0.1 or [::1] (the dev secret is sent in the clear), got "${value}"`,
95
95
  { usage: true },
96
96
  )
97
97
  }
@@ -194,7 +194,7 @@ function unreachable(error, endpoint) {
194
194
  * One tick. Resolves to the route's JSON body; rejects with a `TickError` for anything that is not a 2xx.
195
195
  *
196
196
  * The first request to a checkout's server is what creates its secret file, so with none on disk yet one request
197
- * goes out with a throwaway bearer (a 401, by design) to make the server write it, then the real one follows.
197
+ * goes out with a throwaway secret (a 401, by design) to make the server write it, then the real one follows.
198
198
  *
199
199
  * `signal` ends a tick early (the dev ticker passes the one that stops it, so a tick in flight does not outlive the
200
200
  * server it was for).
@@ -204,12 +204,14 @@ function unreachable(error, endpoint) {
204
204
  */
205
205
  export async function tickOnce({ origin, timeoutMs, secretFile = secretFilePath(), fetchImpl = fetch, signal }) {
206
206
  const endpoint = `${origin}${TICK_PATH}`
207
- /** @param {string} bearer */
208
- const post = async (bearer) => {
207
+ /** @param {string} secret */
208
+ const post = async (secret) => {
209
209
  try {
210
210
  return await fetchImpl(endpoint, {
211
211
  method: 'POST',
212
- headers: { authorization: `Bearer ${bearer}` },
212
+ // The webhook secret's own header (`@sssb/kit/service-auth/webhook`'s WEBHOOK_SECRET_HEADER), which a
213
+ // deployment's CloudFront passes through; it would replace `Authorization` with its own signature.
214
+ headers: { 'x-sssb-webhook-secret': secret },
213
215
  signal: signal
214
216
  ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
215
217
  : AbortSignal.timeout(timeoutMs),
package/src/vitest.d.ts CHANGED
@@ -19,3 +19,20 @@ export interface AppTestProjectOptions {
19
19
 
20
20
  /** One app's Vitest project: rooted at the app, happy-dom, jest-dom, and the app's seam passed explicitly. */
21
21
  export declare function appTestProject(options: AppTestProjectOptions): Promise<TestProjectInlineConfiguration>
22
+
23
+ export interface WorkspaceAppProjectsOptions {
24
+ /** The workspace root, whose package.json's `sssb.apps` names the apps (else every `apps/<name>` that is a package). */
25
+ root: string
26
+ /** Each app's options beside its directory, given the app's absolute directory. */
27
+ options?: (appDir: string) => Omit<AppTestProjectOptions, 'appDir'>
28
+ }
29
+
30
+ /**
31
+ * One `appTestProject` per app of the workspace, in the order `sssb.apps` names them: the root's Vitest configs read the
32
+ * workspace's one list of apps rather than keeping a copy. Each project is named for its app's directory, or its path
33
+ * from the root with `/` as `-` when two apps' directories share a name (unless `options` names it). Throws when the workspace names
34
+ * no app.
35
+ */
36
+ export declare function workspaceAppProjects(
37
+ options: WorkspaceAppProjectsOptions,
38
+ ): Promise<TestProjectInlineConfiguration[]>
package/src/vitest.js CHANGED
@@ -1,11 +1,15 @@
1
1
  // @ts-check
2
- // THE VITEST PRESET: one app's test project (ADR-0014 part 3).
2
+ // THE VITEST PRESET: one app's test project (ADR-0014 part 3), and one for every app of the workspace.
3
3
  //
4
4
  // // vitest.config.ts, at the workspace root or in the app
5
5
  // import { defineConfig } from 'vitest/config'
6
6
  // import { appTestProject } from '@sssb/tools/vitest'
7
7
  // export default defineConfig({ test: { projects: [await appTestProject({ appDir: 'apps/console' })] } })
8
8
  //
9
+ // // vitest.config.ts, at the workspace root: a project for every app the root's `sssb.apps` names
10
+ // import { workspaceAppProjects } from '@sssb/tools/vitest'
11
+ // export default defineConfig(async () => ({ test: { projects: await workspaceAppProjects({ root: '.' }) } }))
12
+ //
9
13
  // One project per app, because the seam is a bare specifier: whatever resolves `@sssb/app-config` can name only one
10
14
  // app (ADR-0012's reason for a project per app). The project's root is the app, its tests are the app's colocated
11
15
  // `src/**/*.test.{ts,tsx}`, it runs in happy-dom with jest-dom's matchers, and, as every SSSB builder does, it passes
@@ -13,6 +17,7 @@
13
17
  // plugin and jest-dom are the app's own copies, loaded from the app's directory.
14
18
  // A guard plugin (framework-guard.js) fails a test file that loads framework source from any instance but the app's.
15
19
  import path from 'node:path'
20
+ import { appLabels, workspaceApps } from './app.js'
16
21
  import { frameworkGuard } from './framework-guard.js'
17
22
  import { importFromApp, resolveFromApp } from './kit.js'
18
23
 
@@ -53,3 +58,25 @@ export async function appTestProject({ appDir, name, include = [], alias = {}, e
53
58
  },
54
59
  }
55
60
  }
61
+
62
+ /** @type {import('./vitest.d.ts').workspaceAppProjects} */
63
+ export async function workspaceAppProjects({ root, options = () => ({}) }) {
64
+ const workspace = path.resolve(root)
65
+ // The one list of the workspace's apps, as `sssb doctor`, `sssb ci` and `sssb launch-json` read it: the root
66
+ // package.json's `sssb.apps`, else every apps/<name> that is a package.
67
+ const apps = workspaceApps(workspace)
68
+ if (apps.length === 0) {
69
+ throw new Error(
70
+ `@sssb/tools/vitest: ${workspace} names no app (\`sssb.apps\` in its package.json, or apps/<name>): nothing to test`,
71
+ )
72
+ }
73
+ // Each project named as `sssb ci` and `launch-json` name the app (its directory's name, or its path when two apps
74
+ // share one): Vitest refuses two projects of one name, and `apps/web` beside `services/web` is a valid list.
75
+ const labels = appLabels(workspace, apps)
76
+ return Promise.all(
77
+ apps.map((app) => {
78
+ const appDir = path.join(workspace, app)
79
+ return appTestProject({ name: labels.get(app), ...options(appDir), appDir })
80
+ }),
81
+ )
82
+ }