@sssb/tools 0.0.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.
- package/LICENSE +21 -0
- package/bin/sssb.js +116 -0
- package/package.json +89 -5
- package/src/app-port.js +77 -0
- package/src/app.js +142 -0
- package/src/assembly-checks.d.ts +57 -0
- package/src/assembly-checks.js +259 -0
- package/src/commands/add-app.js +344 -0
- package/src/commands/check-demo-size.js +80 -0
- package/src/commands/check-doc-paths.js +48 -0
- package/src/commands/check-e2e.js +611 -0
- package/src/commands/check-fences.js +51 -0
- package/src/commands/check-real-env.js +165 -0
- package/src/commands/check-tmpdir-leak.js +78 -0
- package/src/commands/ci.js +350 -0
- package/src/commands/dev-tick.js +25 -0
- package/src/commands/doctor-checks.js +1396 -0
- package/src/commands/doctor-settings.js +583 -0
- package/src/commands/doctor-vitest.js +262 -0
- package/src/commands/doctor.js +1033 -0
- package/src/commands/e2e-profile.js +94 -0
- package/src/commands/guide.js +108 -0
- package/src/commands/launch-json.js +55 -0
- package/src/commands/pin.js +411 -0
- package/src/commands/port.js +22 -0
- package/src/commands/remove-items.js +191 -0
- package/src/commands/serve-standalone.js +78 -0
- package/src/commands/tick.js +27 -0
- package/src/doc-paths.d.ts +106 -0
- package/src/doc-paths.js +328 -0
- package/src/framework-guard.js +35 -0
- package/src/kit.d.ts +49 -0
- package/src/kit.js +216 -0
- package/src/next.d.ts +16 -0
- package/src/next.js +55 -0
- package/src/ports.d.ts +72 -0
- package/src/ports.js +307 -0
- package/src/prune-mantine-css.js +171 -0
- package/src/remove-items/code.patch +798 -0
- package/src/remove-items/database.patch +218 -0
- package/src/remove-items/exact-patch.js +122 -0
- package/src/testing/tmp-dir-marker.js +9 -0
- package/src/testing/tmp-dir-setup.d.ts +2 -0
- package/src/testing/tmp-dir-setup.js +9 -0
- package/src/testing/tmp-dir.d.ts +20 -0
- package/src/testing/tmp-dir.js +174 -0
- package/src/tick/dev-tick.js +128 -0
- package/src/tick/tick.js +317 -0
- package/src/tick/ticker-marker.d.ts +17 -0
- package/src/tick/ticker-marker.js +83 -0
- package/src/tick/ticker.d.ts +36 -0
- package/src/tick/ticker.js +142 -0
- package/src/vite.d.ts +38 -0
- package/src/vite.js +64 -0
- package/src/vitest.d.ts +38 -0
- package/src/vitest.js +82 -0
- package/tsconfig.base.json +33 -0
- package/README.md +0 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The suffix of the empty sibling file that tmp-dir.js (beside it) drops next to every scratch directory it
|
|
3
|
+
// creates (`<dir>` + this suffix). Its own module so the leak wrapper (`sssb check-tmpdir-leak`) reads the same
|
|
4
|
+
// constant the helper writes with, without loading the helper, which imports vitest.
|
|
5
|
+
//
|
|
6
|
+
// @sssb/kit keeps a copy of the helper for its own shipped tests (packages/kit/src/testing), because the framework
|
|
7
|
+
// depends on no other SSSB package (ADR-0014, rule 4). Its marker suffix must be this one, or the wrapper would not see
|
|
8
|
+
// the framework's leaks; tests/tooling/tmp-dir.test.ts holds the two equal.
|
|
9
|
+
export const TMP_DIR_MARKER_SUFFIX = '.sssb-test-tmp'
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// A Vitest setup file (`test.setupFiles`): registers the scratch-directory helper's cleanup hook at the top of every
|
|
3
|
+
// test file, before the file's own code. Vitest runs setup files before each file even with `isolate: false`, where
|
|
4
|
+
// the helper (./tmp-dir.js) loads only once per worker; this is what keeps its cleanup per file and last in order
|
|
5
|
+
// there. SSSB's Vitest preset (`@sssb/tools/vitest`) adds it to every app project; another config adds
|
|
6
|
+
// `'@sssb/tools/testing/tmp-dir-setup'` to its `setupFiles`.
|
|
7
|
+
import { registerTestTmpDirCleanup } from './tmp-dir.js'
|
|
8
|
+
|
|
9
|
+
registerTestTmpDirCleanup()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Make a scratch directory, `<tmpdir>/<prefix>XXXXXX`, that is removed when the test file finishes. Synchronous
|
|
3
|
+
* variant. Import this module before anything else in the file that registers hooks.
|
|
4
|
+
*/
|
|
5
|
+
export declare function makeTestTmpDir(prefix: string): string
|
|
6
|
+
|
|
7
|
+
/** Make a scratch directory that is removed when the test file finishes. Async variant. */
|
|
8
|
+
export declare function makeTestTmpDirAsync(prefix: string): Promise<string>
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Remove a directory this module made, and its marker, now rather than when the test file finishes. Does nothing for a
|
|
12
|
+
* path it did not make, or has already removed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function removeTestTmpDir(dir: string): void
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Register the current test file's cleanup hook, if it has none: what the setup module `@sssb/tools/testing/tmp-dir-setup`
|
|
18
|
+
* does before every file. Call it at a file's top level, never from a hook or a test.
|
|
19
|
+
*/
|
|
20
|
+
export declare function registerTestTmpDirCleanup(): void
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// THE ONLY WAY A TEST MAKES A SCRATCH DIRECTORY. A raw `mkdtemp` in a test file leaves the directory behind on every
|
|
3
|
+
// run; left long enough that has filled a developer's temp filesystem past 100GB. SSSB's lint rule
|
|
4
|
+
// `sssb/no-direct-mkdtemp` bans the raw call in test files, and `sssb check-tmpdir-leak` fails the run if a
|
|
5
|
+
// directory made here was not removed. Any workspace package may import this: it touches no framework code, so a
|
|
6
|
+
// package that does not use @sssb/kit (a CLI, a CloudFront function) uses it too (ADR-0014 part 3).
|
|
7
|
+
//
|
|
8
|
+
// Each call creates `<tmpdir>/<prefix>XXXXXX`, writes an EMPTY MARKER FILE beside it (`<dir>` + TMP_DIR_MARKER_SUFFIX)
|
|
9
|
+
// and queues both for removal when the test file finishes. The marker is a SIBLING, never inside the directory: some
|
|
10
|
+
// tests assert the exact contents of their directory, and a marker inside would be a fixture they have to know about.
|
|
11
|
+
// The marker is deleted only after its directory is, so a directory that cannot be removed keeps its marker and the
|
|
12
|
+
// leak wrapper still sees it.
|
|
13
|
+
//
|
|
14
|
+
// THE FILE'S CLEANUP HOOK is one `afterAll` at the file's top level, which removes every directory still queued: a
|
|
15
|
+
// worker runs its files one after another, so anything queued is this file's or an earlier one's. It must exist before
|
|
16
|
+
// the functions are called, because Vitest silently drops a hook registered at run time from inside another hook, so
|
|
17
|
+
// a helper that registered its own `afterAll` on first call would leak exactly when called from a `beforeAll`. Two
|
|
18
|
+
// things register it:
|
|
19
|
+
//
|
|
20
|
+
// * loading this module, which with isolation (Vitest's default) happens in every file;
|
|
21
|
+
// * the setup module `@sssb/tools/testing/tmp-dir-setup` (./tmp-dir-setup.js), which Vitest runs before every file
|
|
22
|
+
// even WITHOUT isolation (`isolate: false`), where this module loads once per worker and its load-time hook is the
|
|
23
|
+
// first file's alone. SSSB's Vitest preset (`@sssb/tools/vitest`) adds it to every app project.
|
|
24
|
+
//
|
|
25
|
+
// ORDERING: `afterAll` hooks run in reverse registration order, so a hook registered first runs last. The setup module
|
|
26
|
+
// runs before the test file, and an import of this module is hoisted above the file's own code, so the cleanup runs
|
|
27
|
+
// AFTER a file's own `afterAll`: a file that closes a database handle living in the directory closes it before the
|
|
28
|
+
// directory is deleted.
|
|
29
|
+
//
|
|
30
|
+
// WITHOUT ISOLATION AND WITHOUT THE SETUP MODULE, a later file has no file-level hook, and no hook registered later
|
|
31
|
+
// can be both last in the order and wide enough in scope: one registered from a `describe` belongs to that
|
|
32
|
+
// `describe`, which may finish while another part of the file still uses a directory. So such a file never removes
|
|
33
|
+
// its own directories. Its first call registers a hook that removes those of EARLIER files, which have finished (a
|
|
34
|
+
// worker runs its files one after another): each file's directories go when the next file with a hook finishes, and the
|
|
35
|
+
// worker's last file's are left, for `sssb check-tmpdir-leak` to report. The first such call says so once per worker, naming the
|
|
36
|
+
// setup module. `removeTestTmpDir` removes one now. tests/tooling/tmp-dir-isolation.test.ts runs each case in a real
|
|
37
|
+
// Vitest.
|
|
38
|
+
//
|
|
39
|
+
// LIMITS, both Vitest's: a file whose tests are all skipped (`it.skip`, a `-t` filter) runs no `afterAll`, so its
|
|
40
|
+
// directories are left until the next file in the worker registers, and with isolation, where nothing carries to the
|
|
41
|
+
// next file, for good. And the order above holds for `sequence.hooks: 'stack'`, Vitest's default; under `'list'` or
|
|
42
|
+
// `'parallel'` the cleanup can run before the file's own `afterAll`.
|
|
43
|
+
//
|
|
44
|
+
// The kit keeps its own copy (packages/kit/src/testing/tmp-dir.ts), because the framework depends on no other SSSB
|
|
45
|
+
// package; both write the same marker, which tests/tooling/tmp-dir.test.ts holds equal.
|
|
46
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
47
|
+
import { mkdtemp, writeFile } from 'node:fs/promises'
|
|
48
|
+
import { tmpdir } from 'node:os'
|
|
49
|
+
import path from 'node:path'
|
|
50
|
+
import { afterAll, expect } from 'vitest'
|
|
51
|
+
import { TMP_DIR_MARKER_SUFFIX } from './tmp-dir-marker.js'
|
|
52
|
+
|
|
53
|
+
/** Every directory made and not yet removed, with the test file it was made in. @type {{ dir: string, file: string }[]} */
|
|
54
|
+
const created = []
|
|
55
|
+
|
|
56
|
+
/** Test files with a file-level hook, by path ('' when Vitest names none). @type {Set<string>} */
|
|
57
|
+
const hookedFiles = new Set()
|
|
58
|
+
|
|
59
|
+
/** Test files without one that have a hook removing EARLIER files' directories. @type {Set<string>} */
|
|
60
|
+
const sweepingFiles = new Set()
|
|
61
|
+
|
|
62
|
+
let warned = false
|
|
63
|
+
|
|
64
|
+
const currentFile = () => expect.getState().testPath ?? ''
|
|
65
|
+
|
|
66
|
+
/** @param {string} dir */
|
|
67
|
+
function remove(dir) {
|
|
68
|
+
try {
|
|
69
|
+
rmSync(dir, { recursive: true, force: true })
|
|
70
|
+
rmSync(dir + TMP_DIR_MARKER_SUFFIX, { force: true })
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error(`tmp-dir: could not remove ${dir}`, error)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** @param {(entry: (typeof created)[number]) => boolean} which */
|
|
77
|
+
function removeQueued(which) {
|
|
78
|
+
for (let i = created.length - 1; i >= 0; i--) {
|
|
79
|
+
const entry = created[i]
|
|
80
|
+
if (entry && which(entry)) {
|
|
81
|
+
created.splice(i, 1)
|
|
82
|
+
remove(entry.dir)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A file's first registration: whatever is still queued or registered for another file is an earlier file's, which has
|
|
89
|
+
* finished (a worker runs its files one after another). Its directories go now, which also covers a file whose tests
|
|
90
|
+
* were all skipped, since Vitest runs no `afterAll` for a skipped suite; and its registry entries go, so a watch-mode
|
|
91
|
+
* rerun of that file registers again.
|
|
92
|
+
*
|
|
93
|
+
* @param {string} file
|
|
94
|
+
*/
|
|
95
|
+
function startFile(file) {
|
|
96
|
+
removeQueued((entry) => entry.file !== file)
|
|
97
|
+
for (const other of [...hookedFiles, ...sweepingFiles]) {
|
|
98
|
+
if (other !== file) {
|
|
99
|
+
hookedFiles.delete(other)
|
|
100
|
+
sweepingFiles.delete(other)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @type {import('./tmp-dir.d.ts').registerTestTmpDirCleanup} */
|
|
106
|
+
export function registerTestTmpDirCleanup() {
|
|
107
|
+
const file = currentFile()
|
|
108
|
+
if (hookedFiles.has(file)) return
|
|
109
|
+
startFile(file)
|
|
110
|
+
hookedFiles.add(file)
|
|
111
|
+
afterAll(() => {
|
|
112
|
+
// A watch-mode rerun of this file, in this worker, registers again.
|
|
113
|
+
hookedFiles.delete(file)
|
|
114
|
+
removeQueued(() => true)
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
registerTestTmpDirCleanup()
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The file the next directory belongs to. In a file without a file-level hook, also registers that file's hook for
|
|
122
|
+
* earlier files' directories, on its first call. Synchronous, so the async variant calls it before its first `await`,
|
|
123
|
+
* while the file may still be collected.
|
|
124
|
+
*/
|
|
125
|
+
function claim() {
|
|
126
|
+
const file = currentFile()
|
|
127
|
+
if (hookedFiles.has(file)) return file
|
|
128
|
+
if (!warned) {
|
|
129
|
+
warned = true
|
|
130
|
+
console.error(
|
|
131
|
+
`tmp-dir: ${file || 'a test file'} has no cleanup hook of its own: with Vitest's isolate: false, add ` +
|
|
132
|
+
"'@sssb/tools/testing/tmp-dir-setup' to test.setupFiles (SSSB's appTestProject does). Without it each " +
|
|
133
|
+
"file's scratch directories are removed only after the next file, and the last file's are left behind.",
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
if (!sweepingFiles.has(file)) {
|
|
137
|
+
startFile(file)
|
|
138
|
+
sweepingFiles.add(file)
|
|
139
|
+
afterAll(() => {
|
|
140
|
+
// A watch-mode rerun of this file, in this worker, registers again.
|
|
141
|
+
sweepingFiles.delete(file)
|
|
142
|
+
removeQueued((entry) => entry.file !== file)
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
return file
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @type {import('./tmp-dir.d.ts').makeTestTmpDir} */
|
|
149
|
+
export function makeTestTmpDir(prefix) {
|
|
150
|
+
const file = claim()
|
|
151
|
+
const dir = mkdtempSync(path.join(tmpdir(), prefix))
|
|
152
|
+
created.push({ dir, file })
|
|
153
|
+
writeFileSync(dir + TMP_DIR_MARKER_SUFFIX, '')
|
|
154
|
+
return dir
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** @type {import('./tmp-dir.d.ts').makeTestTmpDirAsync} */
|
|
158
|
+
export async function makeTestTmpDirAsync(prefix) {
|
|
159
|
+
// Before the `await`: a hook can be registered only while the file is collected.
|
|
160
|
+
const file = claim()
|
|
161
|
+
const dir = await mkdtemp(path.join(tmpdir(), prefix))
|
|
162
|
+
created.push({ dir, file })
|
|
163
|
+
await writeFile(dir + TMP_DIR_MARKER_SUFFIX, '')
|
|
164
|
+
return dir
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** @type {import('./tmp-dir.d.ts').removeTestTmpDir} */
|
|
168
|
+
export function removeTestTmpDir(dir) {
|
|
169
|
+
const index = created.findIndex((entry) => entry.dir === dir)
|
|
170
|
+
// Only a directory this module made and has not removed yet: anything else is not a scratch directory.
|
|
171
|
+
if (index < 0) return
|
|
172
|
+
created.splice(index, 1)
|
|
173
|
+
remove(dir)
|
|
174
|
+
}
|