@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,191 @@
1
+ // @ts-check
2
+ // `sssb remove-items [--app <dir>] [--drop-migrations] [--dry-run]`: takes the starter's example Items slice out of an app
3
+ // in one step, and leaves the app green. The first thing every adopter does is this sweep by hand over about fifteen
4
+ // files (SSSB's docs/adopting-reference.md, "To remove the Items slice"); this is that sweep as a patch the starter's own
5
+ // test keeps true.
6
+ //
7
+ // WHAT IT DOES. Two patches, `remove-items/code.patch` and `remove-items/database.patch` (a unified diff of the starter
8
+ // against the starter without Items, applied EXACTLY by ./exact-patch.js). The code half removes everything an app's
9
+ // code says about Items: the card, the route, the query, the ability, the catalog namespace, the dashboard's glue, the
10
+ // static demo's card, the specs that name Items, and the proofs of paging. It writes nothing of its own: the starter's
11
+ // other e2e spec (the Simulator's) stays, so the app still has one for `sssb check-e2e`. The database half removes the migrations, the table's type and its
12
+ // RLS proofs, and only runs with `--drop-migrations`.
13
+ //
14
+ // THE RULE FOR MIGRATIONS. A database that ran `1001_items` records it, and the migrator refuses to start when a migration
15
+ // it recorded is gone from the code (Kysely: "previously executed migration ... is missing"). So this command never
16
+ // deletes a migration unless it is told to: `--drop-migrations` is for an app whose database has never run them (a
17
+ // workspace just generated: delete the local `.data` too), and without it the migrations, `ItemsTable` and the RLS proofs
18
+ // of `items` stay, registered, which keeps every gate green and every recorded migration in place. Both halves are
19
+ // one choice, made once: the second half is not available after the first ran on its own.
20
+ //
21
+ // KEEPING THE PATCHES TRUE. They are diffs of the starter, so a change to a starter file they touch (or to the Items
22
+ // slice's own) fails tests/tooling/remove-items.test.ts, which names the file. Regenerate on a scratch branch off the change:
23
+ // edit the starter into its Items-less form in two commits (the code half, then the database half), and write
24
+ // `git diff --no-renames -U3 --relative=apps/starter <before> <after> -- apps/starter` for each into code.patch and
25
+ // database.patch. The starter is untouched by the change itself: the scratch branch is thrown away.
26
+ //
27
+ // WHEN IT REFUSES. It computes every edit in memory first and writes only if every one applies. A file the starter wrote
28
+ // and the adopter has not touched inside a hunk applies, wherever the hunk has moved to; one they edited, deleted, or
29
+ // that is not there is named, with what is wrong, and NOTHING is written. Adopter-written code is never deleted silently.
30
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
31
+ import path from 'node:path'
32
+ import { takeAppDir, takeFlag, UsageError } from '../app.js'
33
+ import { applyFilePatch, parsePatch } from '../remove-items/exact-patch.js'
34
+
35
+ const USAGE = 'usage: sssb remove-items [--app <dir>] [--drop-migrations] [--dry-run]'
36
+
37
+ /** @param {string} name */
38
+ const patchFile = (name) => readFileSync(new URL(`../remove-items/${name}.patch`, import.meta.url), 'utf8')
39
+
40
+ /**
41
+ * @param {string[]} args
42
+ * @returns {Promise<number>}
43
+ */
44
+ export async function run(args) {
45
+ if (args.includes('--help') || args.includes('-h')) {
46
+ console.log(
47
+ [
48
+ USAGE,
49
+ '',
50
+ "Takes the starter's example Items slice out of the app (the card, the route, the query, the ability, the catalog",
51
+ "namespace, the dashboard's and the static demo's card, the specs that name Items).",
52
+ '',
53
+ ' --drop-migrations also remove 1001_items, 1002_items_keyset_index, the table type and its RLS proofs. For an app whose',
54
+ ' database has never run them: delete the local `.data` after. A database that ran a migration',
55
+ ' records it, and the migrator refuses to start when it is gone from the code, so without this flag',
56
+ ' they stay, registered, and the app stays green.',
57
+ ' --dry-run say what would change, and change nothing.',
58
+ '',
59
+ 'It refuses, naming each file, when the slice is not what the starter wrote, and writes nothing.',
60
+ ].join('\n'),
61
+ )
62
+ return 0
63
+ }
64
+ const appDir = takeAppDir(args)
65
+ const drop = takeFlag(args, '--drop-migrations')
66
+ const dry = takeFlag(args, '--dry-run')
67
+ if (args.length > 0) throw new UsageError(`sssb remove-items: unexpected ${args.join(' ')}\n${USAGE}`)
68
+ if (!existsSync(path.join(appDir, 'src/app-config'))) {
69
+ throw new UsageError(`sssb remove-items: ${appDir} has no src/app-config, so it is not an SSSB app\n${USAGE}`)
70
+ }
71
+
72
+ /** What each file holds now, as the plan builds on it: null is "not there". @type {Map<string, string | null>} */
73
+ const state = new Map()
74
+ /** @type {Map<string, 'add' | 'edit' | 'delete'>} */
75
+ const actions = new Map()
76
+ /** @param {string} file */
77
+ const current = (file) => {
78
+ if (!state.has(file)) {
79
+ const full = path.join(appDir, file)
80
+ state.set(file, existsSync(full) ? readFileSync(full, 'utf8') : null)
81
+ }
82
+ return /** @type {string | null} */ (state.get(file))
83
+ }
84
+
85
+ /** @type {string[]} */
86
+ const problems = []
87
+ for (const half of drop ? ['code', 'database'] : ['code']) {
88
+ for (const patch of parsePatch(patchFile(half))) {
89
+ const before = current(patch.path)
90
+ const result = applyFilePatch(before, patch)
91
+ if (!result.ok) {
92
+ problems.push(`${patch.path}: ${result.reason}`)
93
+ continue
94
+ }
95
+ state.set(patch.path, result.content)
96
+ const was = actions.get(patch.path)
97
+ actions.set(
98
+ patch.path,
99
+ result.content === null ? 'delete' : was === 'add' || before === null ? 'add' : 'edit',
100
+ )
101
+ }
102
+ // The database half is a patch on what the code half leaves; after a refusal that state is a guess.
103
+ if (problems.length > 0) break
104
+ }
105
+
106
+ if (problems.length > 0) {
107
+ console.error(
108
+ [
109
+ `sssb remove-items: nothing was changed. ${problems.length === 1 ? 'One file is' : `${problems.length} files are`} not what the starter wrote, so removing the Items slice would mean guessing:`,
110
+ ...problems.map((problem) => ` ${problem}`),
111
+ '',
112
+ 'Restore each file and run this again, or take the slice out by hand: SSSB\'s docs/adopting-reference.md, "To remove the Items slice".',
113
+ 'If the slice is already gone, there is nothing to do.',
114
+ ].join('\n'),
115
+ )
116
+ return 1
117
+ }
118
+
119
+ const where = path.relative(process.cwd(), appDir) || '.'
120
+ const listing = [...actions].map(([file, action]) => ` ${action.padEnd(6)} ${file}`)
121
+ if (dry) {
122
+ console.log(
123
+ [
124
+ `sssb remove-items --dry-run, in ${where}${drop ? ' (--drop-migrations)' : ''}: this would`,
125
+ ...listing,
126
+ '',
127
+ 'Nothing was written.',
128
+ ].join('\n'),
129
+ )
130
+ return 0
131
+ }
132
+
133
+ let written = 0
134
+ try {
135
+ for (const [file, action] of actions) {
136
+ const full = path.join(appDir, file)
137
+ if (action === 'delete') {
138
+ rmSync(full)
139
+ pruneEmptyDirectories(path.dirname(full), appDir)
140
+ } else {
141
+ mkdirSync(path.dirname(full), { recursive: true })
142
+ writeFileSync(full, /** @type {string} */ (state.get(file)))
143
+ }
144
+ written++
145
+ }
146
+ } catch (error) {
147
+ // Every refusal is decided before the first write; this is the disk failing part-way, which no plan can rule out.
148
+ throw new UsageError(
149
+ `sssb remove-items: the disk failed after ${written} of ${actions.size} files (${/** @type {Error} */ (error).message}). The app is half changed: \`git status\` shows which, and \`git restore .\` puts it back before you run this again.`,
150
+ )
151
+ }
152
+ // Next's dev server writes a type validator that names every route file (`.next/dev/types/validator.ts`), and the app's
153
+ // tsconfig includes it. `next typegen`, which `pnpm typecheck` runs, rewrites only `.next/types`, so after the route
154
+ // is gone a leftover validator fails typecheck on a module that no longer exists. It is generated, ignored by git, and
155
+ // written again by the next `pnpm dev`.
156
+ rmSync(path.join(appDir, '.next/dev/types'), { recursive: true, force: true })
157
+ console.log(
158
+ [
159
+ `sssb remove-items: took the Items slice out of ${where}.`,
160
+ ...listing,
161
+ '',
162
+ ...(drop
163
+ ? [
164
+ 'The migrations and the table are gone too. This is only safe for a database that never ran 1001_items: delete the',
165
+ `local data directory (${path.join(where, '.data')}) so the dev database starts from the new migration list, and number your`,
166
+ 'first table 1001, as an app with no migrations does.',
167
+ ]
168
+ : [
169
+ 'The database half stayed: 1001_items, 1002_items_keyset_index, the `items` table type and its RLS proofs. A database',
170
+ 'that ran them records them, and the migrator refuses a recorded migration that is gone. If no database ever did,',
171
+ 'restore the app and run `sssb remove-items --drop-migrations` instead: the two halves are one choice, made once.',
172
+ ]),
173
+ '',
174
+ 'Then run `pnpm verify`.',
175
+ ].join('\n'),
176
+ )
177
+ return 0
178
+ }
179
+
180
+ /**
181
+ * Removes `dir` and its parents while they are empty, stopping before `stop`.
182
+ * @param {string} dir
183
+ * @param {string} stop
184
+ */
185
+ function pruneEmptyDirectories(dir, stop) {
186
+ let at = dir
187
+ while (path.resolve(at) !== path.resolve(stop) && existsSync(at) && readdirSync(at).length === 0) {
188
+ rmdirSync(at)
189
+ at = path.dirname(at)
190
+ }
191
+ }
package/src/kit.d.ts CHANGED
@@ -10,6 +10,12 @@ export declare function kitDirOf(appDir: string): string
10
10
  /** The version in the package.json of the `@sssb/kit` an app resolves (`kitDirOf`). */
11
11
  export declare function kitVersionOf(appDir: string): string
12
12
 
13
+ /**
14
+ * The text of the release stamp, `dist/release.json`, in the `@sssb/kit` an app resolves: the commit the package was
15
+ * packed from. Null when it has none (SSSB's own source, a package packed before the stamp existed or by hand).
16
+ */
17
+ export declare function kitReleaseStampOf(appDir: string): string | null
18
+
13
19
  /**
14
20
  * The shared real-path check: `file` must be part of the `@sssb/kit` that `appDir` resolves. Throws for anything
15
21
  * else (the hoisted copy, another app's instance, a framework source tree reached by a path). Returns the file's real
package/src/kit.js CHANGED
@@ -131,6 +131,17 @@ export function kitVersionOf(appDir) {
131
131
  return manifest.version
132
132
  }
133
133
 
134
+ /**
135
+ * The text of the release stamp (`dist/release.json`) the app's `@sssb/kit` carries, or null when it has none. It is a
136
+ * file `@sssb/kit`'s prepack writes into the package, so it is read from the kit directory the app resolves, here.
137
+ *
138
+ * @type {import('./kit.d.ts').kitReleaseStampOf}
139
+ */
140
+ export function kitReleaseStampOf(appDir) {
141
+ const stamp = path.join(kitDirOf(appDir), 'dist', 'release.json')
142
+ return existsSync(stamp) ? readFileSync(stamp, 'utf8') : null
143
+ }
144
+
134
145
  /**
135
146
  * The shared real-path check: `file` must be part of the `@sssb/kit` that `appDir` resolves. Anything else (the
136
147
  * hoisted copy, another app's instance, this repository's source reached by a path) throws.
package/src/ports.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  export type PortService = 'showcase' | 'starter' | 'ladle' | 'contractPg'
3
3
 
4
4
  /**
5
- * A port slot an app names for itself, in its package.json: `"sssb": { "port": { "name": "ledger", "default": 3700 } }`.
5
+ * A port slot an app names for itself, in its package.json: `"sssb": { "port": { "name": "ledger", "default": 3800 } }`.
6
6
  * `name` is lowercase words joined by `-` (at most 32 characters) and is not a built-in's; it names the `LEDGER_PORT`
7
7
  * variable (`<NAME>_PORT`, with `-` as `_`). `default` is the port in a main checkout, an integer from 1024 to 49151
8
8
  * that no built-in service or custom slot's derived band holds.
package/src/ports.js CHANGED
@@ -21,8 +21,9 @@
21
21
  // anything: `SHOWCASE_PORT=3210 pnpm dev`.
22
22
  //
23
23
  // A SERVICE is one of the built-ins below, named by a string, or a SLOT an app declares for itself in its package.json,
24
- // `"sssb": { "port": { "name": "ledger", "default": 3700 } }`, for a workspace whose apps are not SSSB's two: without
25
- // it two apps made from the starter share `starter`, and so one port. A custom slot follows the same three rules: its
24
+ // `"sssb": { "port": { "name": "ledger", "default": 3800 } }`. Every app of a workspace needs a slot of its own, since two
25
+ // apps on one slot bind one port (`@sssb/create` and `sssb add-app` give each app a slot named for it, and an app
26
+ // generated before keeps the built-in `starter`). A custom slot follows the same three rules: its
26
27
  // variable is `LEDGER_PORT`, a main checkout gets its `default`, and a linked worktree derives from a band the
27
28
  // built-ins do not use (CUSTOM_BAND), keyed on the name as well as the checkout so two slots of one worktree differ.
28
29
  //
@@ -58,8 +59,8 @@ function findCheckoutRoot(start) {
58
59
  const SLOTS = 200
59
60
 
60
61
  /**
61
- * The port services. They are SSSB's two reference apps' slots plus two tools, and an app keeps the slot it was
62
- * generated with when it is renamed (the starter's `starter` slot is the adopter's app's). Derived showcase and
62
+ * The port services. They are SSSB's two reference apps' slots plus two tools. An app `@sssb/create` writes declares a
63
+ * slot of its own instead (named for its slug), and one generated before it did keeps `starter`. Derived showcase and
63
64
  * starter ports share a slot and sit adjacent (3200/3201, 3202/3203, …) so one session's pair never straddles
64
65
  * another's. No derived band overlaps the defaults.
65
66
  * @type {Record<string, { env: string, fallback: number, derive: (slot: number) => number }>}