@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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +116 -0
  3. package/package.json +89 -5
  4. package/src/app-port.js +77 -0
  5. package/src/app.js +142 -0
  6. package/src/assembly-checks.d.ts +57 -0
  7. package/src/assembly-checks.js +259 -0
  8. package/src/commands/add-app.js +344 -0
  9. package/src/commands/check-demo-size.js +80 -0
  10. package/src/commands/check-doc-paths.js +48 -0
  11. package/src/commands/check-e2e.js +611 -0
  12. package/src/commands/check-fences.js +51 -0
  13. package/src/commands/check-real-env.js +165 -0
  14. package/src/commands/check-tmpdir-leak.js +78 -0
  15. package/src/commands/ci.js +350 -0
  16. package/src/commands/dev-tick.js +25 -0
  17. package/src/commands/doctor-checks.js +1396 -0
  18. package/src/commands/doctor-settings.js +583 -0
  19. package/src/commands/doctor-vitest.js +262 -0
  20. package/src/commands/doctor.js +1033 -0
  21. package/src/commands/e2e-profile.js +94 -0
  22. package/src/commands/guide.js +108 -0
  23. package/src/commands/launch-json.js +55 -0
  24. package/src/commands/pin.js +411 -0
  25. package/src/commands/port.js +22 -0
  26. package/src/commands/remove-items.js +191 -0
  27. package/src/commands/serve-standalone.js +78 -0
  28. package/src/commands/tick.js +27 -0
  29. package/src/doc-paths.d.ts +106 -0
  30. package/src/doc-paths.js +328 -0
  31. package/src/framework-guard.js +35 -0
  32. package/src/kit.d.ts +49 -0
  33. package/src/kit.js +216 -0
  34. package/src/next.d.ts +16 -0
  35. package/src/next.js +55 -0
  36. package/src/ports.d.ts +72 -0
  37. package/src/ports.js +307 -0
  38. package/src/prune-mantine-css.js +171 -0
  39. package/src/remove-items/code.patch +798 -0
  40. package/src/remove-items/database.patch +218 -0
  41. package/src/remove-items/exact-patch.js +122 -0
  42. package/src/testing/tmp-dir-marker.js +9 -0
  43. package/src/testing/tmp-dir-setup.d.ts +2 -0
  44. package/src/testing/tmp-dir-setup.js +9 -0
  45. package/src/testing/tmp-dir.d.ts +20 -0
  46. package/src/testing/tmp-dir.js +174 -0
  47. package/src/tick/dev-tick.js +128 -0
  48. package/src/tick/tick.js +317 -0
  49. package/src/tick/ticker-marker.d.ts +17 -0
  50. package/src/tick/ticker-marker.js +83 -0
  51. package/src/tick/ticker.d.ts +36 -0
  52. package/src/tick/ticker.js +142 -0
  53. package/src/vite.d.ts +38 -0
  54. package/src/vite.js +64 -0
  55. package/src/vitest.d.ts +38 -0
  56. package/src/vitest.js +82 -0
  57. package/tsconfig.base.json +33 -0
  58. package/README.md +0 -3
@@ -0,0 +1,94 @@
1
+ // @ts-check
2
+ // `sssb e2e-profile [playwright args…]`: where the e2e wall clock actually goes.
3
+ //
4
+ // The alternative is optimising by intuition: "which tests are slow" is not guessable from reading them, because
5
+ // the expensive ones are expensive for different reasons (cold route compiles, real polling, repeated UI sign-ins)
6
+ // and only a ranking separates those. Run from an app's directory; every argument is forwarded to `playwright test`
7
+ // (`--project=chromium`, `--workers=1 --no-deps`), so this profiles whatever you can already run. It reads
8
+ // Playwright's own JSON report, so the numbers are Playwright's, not a wrapper's stopwatch.
9
+ import { spawnSync } from 'node:child_process'
10
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import path from 'node:path'
13
+ import { takeAppDir } from '../app.js'
14
+
15
+ const TOP_N = 20
16
+
17
+ /**
18
+ * @typedef {{ duration?: number }} Result
19
+ * @typedef {{ status?: string, results?: Result[] }} Test
20
+ * @typedef {{ title: string, tests?: Test[] }} Spec
21
+ * @typedef {{ file?: string, specs?: Spec[], suites?: Suite[] }} Suite
22
+ */
23
+
24
+ /** @param {string[]} args */
25
+ export async function run(args) {
26
+ const appDir = takeAppDir(args)
27
+ const scratch = mkdtempSync(path.join(tmpdir(), 'e2e-profile-'))
28
+ const reportFile = path.join(scratch, 'report.json')
29
+ try {
30
+ // The JSON reporter goes to a FILE, not stdout: stdout also carries `[WebServer]` output and the dev
31
+ // server's own logging, which would make the report unparseable.
32
+ const result = spawnSync('pnpm', ['exec', 'playwright', 'test', '--reporter=json', ...args], {
33
+ cwd: appDir,
34
+ stdio: 'inherit',
35
+ env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportFile },
36
+ })
37
+
38
+ /** @type {{ suites?: Suite[], stats?: { duration?: number } }} */
39
+ let report
40
+ try {
41
+ report = JSON.parse(readFileSync(reportFile, 'utf8'))
42
+ } catch {
43
+ console.error('\ne2e-profile: no parseable JSON report: the run probably failed before reporting.')
44
+ return result.status ?? 1
45
+ }
46
+
47
+ /** @type {{ title: string, file: string, duration: number }[]} */
48
+ const tests = []
49
+ /** @param {Suite} suite @param {string | undefined} file */
50
+ const walk = (suite, file) => {
51
+ const here = suite.file ?? file
52
+ for (const spec of suite.specs ?? []) {
53
+ for (const test of spec.tests ?? []) {
54
+ // Retries produce several results; charge the test the total, since that is the wall clock the
55
+ // run actually spent on it.
56
+ const duration = (test.results ?? []).reduce((sum, r) => sum + (r.duration ?? 0), 0)
57
+ tests.push({ title: spec.title, file: here ?? '?', duration })
58
+ }
59
+ }
60
+ for (const child of suite.suites ?? []) walk(child, here)
61
+ }
62
+ for (const suite of report.suites ?? []) walk(suite, undefined)
63
+
64
+ const wall = report.stats?.duration ?? 0
65
+ const summed = tests.reduce((sum, t) => sum + t.duration, 0)
66
+ const slowest = [...tests].sort((a, b) => b.duration - a.duration).slice(0, TOP_N)
67
+ /** @type {Map<string, number>} */
68
+ const byFile = new Map()
69
+ for (const t of tests) byFile.set(t.file, (byFile.get(t.file) ?? 0) + t.duration)
70
+
71
+ /** @param {number} ms */
72
+ const secs = (ms) => `${(ms / 1000).toFixed(1)}s`
73
+ /** @param {number} ms */
74
+ const pct = (ms) => (summed > 0 ? `${((ms / summed) * 100).toFixed(1)}%` : '-')
75
+
76
+ console.log(`\n${'='.repeat(78)}`)
77
+ console.log(`wall clock ${secs(wall)} across ${tests.length} tests (summed test time ${secs(summed)})`)
78
+ // Summed > wall means parallelism is working; summed ≈ wall means it is not.
79
+ console.log(`parallel speedup ${wall > 0 ? (summed / wall).toFixed(1) : '-'}x`)
80
+ console.log('='.repeat(78))
81
+ console.log(`\nslowest ${Math.min(TOP_N, slowest.length)} tests`)
82
+ for (const t of slowest) {
83
+ console.log(` ${secs(t.duration).padStart(7)} ${pct(t.duration).padStart(6)} ${t.file} › ${t.title}`)
84
+ }
85
+ console.log('\nby spec file')
86
+ for (const [file, ms] of [...byFile.entries()].sort((a, b) => b[1] - a[1])) {
87
+ console.log(` ${secs(ms).padStart(7)} ${pct(ms).padStart(6)} ${file}`)
88
+ }
89
+ console.log()
90
+ return result.status ?? 0
91
+ } finally {
92
+ rmSync(scratch, { recursive: true, force: true })
93
+ }
94
+ }
@@ -0,0 +1,108 @@
1
+ // @ts-check
2
+ // `sssb guide [--app <dir>] [--out <file>] [--check]`: copies the app guide that @sssb/kit ships (the rules an app author follows:
3
+ // the seam, vendor SDKs, getDb, i18n, router-agnostic screens, hermetic dev) into the repository, with a hash of its
4
+ // content stamped in a header line. The adopter's own CLAUDE.md imports that copy with Claude Code's `@path` import.
5
+ //
6
+ // THE TRUST DECISION (ADR-0014 part 9): agent instructions steer every agent working in the repository, so a change
7
+ // to them must arrive as a reviewable diff in the adopter's own PR, never silently through node_modules. `--check`
8
+ // (and, from P5, `sssb doctor`) fails when the stamped hash differs from the installed guide's, so an upgrade is not
9
+ // finished until the copy is refreshed and the change sits in the adopter's diff. The hash, not the bytes, is
10
+ // compared, so the adopter's formatter cannot make the copy look stale.
11
+ //
12
+ // The guide is the framework's published subpath `@sssb/kit/guide.md`, resolved from the app's directory through the
13
+ // shared resolver (rule 4). The framework starts shipping it at ADR-0014's P7; before that this command says so.
14
+ import { createHash } from 'node:crypto'
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { readJson, takeAppDir, takeFlag, takeOption, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
18
+ import { kitDirOf, resolveAppsKit } from '../kit.js'
19
+
20
+ const STAMP = /^<!-- sssb-guide sha256:([0-9a-f]{64}) /
21
+
22
+ /** @param {string | Buffer} text */
23
+ const sha256 = (text) => createHash('sha256').update(text).digest('hex')
24
+
25
+ /**
26
+ * The app whose kit's guide is copied. The copy is the workspace's, so the command has to work where people type it,
27
+ * the root, as `sssb doctor` does: with no `--app`, a working directory that resolves `@sssb/kit` is the app, and a
28
+ * workspace root that does not (a generated workspace's root takes no framework) uses the workspace's first app
29
+ * (`sssb.apps`, else `apps/*`).
30
+ * @param {string[]} args
31
+ * @param {string} [cwd]
32
+ * @returns {string}
33
+ */
34
+ function guideApp(args, cwd = process.cwd()) {
35
+ if (args.includes('--app')) return takeAppDir(args, cwd)
36
+ const here = path.resolve(cwd)
37
+ const isRoot = existsSync(path.join(here, 'pnpm-workspace.yaml')) && existsSync(path.join(here, 'package.json'))
38
+ if (isRoot && !resolvesKit(here)) {
39
+ const apps = workspaceApps(here)
40
+ if (apps.length === 0) {
41
+ throw new UsageError(
42
+ `sssb guide: ${here} is a workspace root that takes no @sssb/kit and has no apps (\`sssb.apps\` in its ` +
43
+ 'package.json, or apps/<name>): pass --app <dir>',
44
+ )
45
+ }
46
+ console.log(`sssb guide: no --app, and ${here} takes no @sssb/kit: using the guide of ${apps[0]}'s kit`)
47
+ return path.resolve(here, /** @type {string} */ (apps[0]))
48
+ }
49
+ // Anything else: the app is the working directory, and kitDirOf's refusal says to name one with --app.
50
+ return takeAppDir(args, cwd)
51
+ }
52
+
53
+ /** @param {string} dir */
54
+ function resolvesKit(dir) {
55
+ try {
56
+ kitDirOf(dir)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ /** @param {string[]} args */
64
+ export async function run(args) {
65
+ const appDir = guideApp(args)
66
+ const check = takeFlag(args, '--check')
67
+ const out = takeOption(args, '--out')
68
+ if (args.length > 0) throw new UsageError('usage: sssb guide [--app <dir>] [--out <file>] [--check]')
69
+ const target = path.resolve(out ?? path.join(workspaceRootOf(appDir), '.claude', 'sssb-guide.md'))
70
+
71
+ const kitDir = kitDirOf(appDir)
72
+ const version = readJson(path.join(kitDir, 'package.json')).version
73
+ let guide
74
+ try {
75
+ guide = resolveAppsKit(appDir, 'guide.md')
76
+ } catch (error) {
77
+ throw new UsageError(
78
+ `sssb guide: the @sssb/kit ${version} this app installs ships no app guide (\`@sssb/kit/guide.md\`); ` +
79
+ `it arrives with ADR-0014's P7 (${error instanceof Error ? error.message : String(error)})`,
80
+ )
81
+ }
82
+ const body = readFileSync(guide)
83
+ const hash = sha256(body)
84
+
85
+ if (check) {
86
+ const stamped = existsSync(target) ? STAMP.exec(readFileSync(target, 'utf8'))?.[1] : undefined
87
+ if (stamped === hash) {
88
+ console.log(`sssb guide: ${path.relative(process.cwd(), target)} matches @sssb/kit ${version}'s guide`)
89
+ return 0
90
+ }
91
+ console.error(
92
+ stamped === undefined
93
+ ? `sssb guide: ${target} is missing or carries no stamp. Run \`pnpm exec sssb guide\` and commit the copy.`
94
+ : `sssb guide: ${target} was copied from a different guide than @sssb/kit ${version} ships. Run ` +
95
+ '`pnpm exec sssb guide`, review the diff, and commit it with the upgrade.',
96
+ )
97
+ return 1
98
+ }
99
+ mkdirSync(path.dirname(target), { recursive: true })
100
+ writeFileSync(
101
+ target,
102
+ `<!-- sssb-guide sha256:${hash} (copied from @sssb/kit ${version} by \`sssb guide\`: edit nothing here; ` +
103
+ 'rerun it after an upgrade and review the diff) -->\n\n' +
104
+ body.toString('utf8'),
105
+ )
106
+ console.log(`sssb guide: wrote ${path.relative(process.cwd(), target)} from @sssb/kit ${version}`)
107
+ return 0
108
+ }
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ // `sssb launch-json`: generates `.claude/launch.json` for THIS checkout.
3
+ //
4
+ // The Claude desktop app's browser pane starts a dev server by name from that file and then waits on the `port`
5
+ // it declares. The file is static JSON with no way to read an env var, so a checked-in `"port": 3000` was wrong in
6
+ // every linked worktree the moment ports became per-checkout (src/ports.js): `pnpm dev` would bind the derived
7
+ // port while the pane waited on 3000 and timed out. The right value differs per checkout, so the file is
8
+ // generated and gitignored, and this generator is what is tracked instead. Run it from the workspace root's
9
+ // `prepare` script, so a fresh clone and every new worktree get a correct one from `pnpm install`.
10
+ //
11
+ // One configuration per workspace app (`sssb.apps`, else `apps/*`) that has a `dev` script and declares its port
12
+ // service (`"sssb": { "port": … }`), named `<app directory>-dev`.
13
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
14
+ import path from 'node:path'
15
+ import { declaredPortService } from '../app-port.js'
16
+ import { appLabels, readJson, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
17
+ import { portForRoot } from '../ports.js'
18
+
19
+ /** @param {string[]} args */
20
+ export async function run(args) {
21
+ if (args.length > 0) throw new UsageError('usage: sssb launch-json')
22
+ const root = workspaceRootOf(process.cwd())
23
+ const configurations = []
24
+ const apps = workspaceApps(root)
25
+ const labels = appLabels(root, apps)
26
+ for (const app of apps) {
27
+ const appDir = path.join(root, app)
28
+ const manifest = readJson(path.join(appDir, 'package.json'))
29
+ const service = declaredPortService(appDir)
30
+ if (!manifest.scripts?.dev || service === undefined) continue
31
+ configurations.push({
32
+ name: `${labels.get(app) ?? app}-dev`,
33
+ runtimeExecutable: 'pnpm',
34
+ runtimeArgs: ['--filter', manifest.name, 'dev'],
35
+ port: portForRoot(root, service),
36
+ })
37
+ }
38
+ const target = path.join(root, '.claude', 'launch.json')
39
+ const next = `${JSON.stringify({ version: '0.0.1', configurations }, null, 4)}\n`
40
+
41
+ // Only write when the content changes: `prepare` runs on every install, and rewriting an identical file would
42
+ // churn mtimes and any watcher pointed at it.
43
+ let current
44
+ try {
45
+ current = readFileSync(target, 'utf8')
46
+ } catch {
47
+ // No file yet (fresh clone, new worktree): fall through and write one.
48
+ }
49
+ if (current !== next) {
50
+ mkdirSync(path.dirname(target), { recursive: true })
51
+ writeFileSync(target, next)
52
+ console.log(`launch.json: ${configurations.map((c) => `${c.name} on ${c.port}`).join(', ') || 'no apps'}`)
53
+ }
54
+ return 0
55
+ }
@@ -0,0 +1,411 @@
1
+ // @ts-check
2
+ // `sssb pin [--app <dir>]`: raises both of a workspace's pins on SSSB to the installed `@sssb/kit`'s release commit
3
+ // (adoption review follow-up 7). An adopter keeps two pins on one commit of SSSB's repository: the reusable workflow's
4
+ // `uses: <owner>/<name>/.github/workflows/app-checks.yml@<sha>` in `.github/workflows/*.yml`, and the plugin marketplace's
5
+ // `ref` in `.claude/settings.json`. `sssb doctor` reports the pins that are not the commit the kit's stamp
6
+ // (`dist/release.json`) names; this command writes them, so an upgrade maintains one version, the npm one.
7
+ //
8
+ // - Idempotent: a pin already on the commit is left byte for byte as it was, and the run says so.
9
+ // - It says what it changed, file and line, with the commit it replaced.
10
+ // - It refuses, and writes nothing, when there is no commit to pin to (SSSB's own repository, where the kit is source,
11
+ // or a kit packed by hand without a stamp), or when the workspace's files are not the shape it can edit: no workflow
12
+ // calls SSSB's reusable workflow, `.claude/settings.json` is not JSON or declares no marketplace from SSSB's
13
+ // repository. Every pin is judged before the first file is written.
14
+ // - A `.claude/settings.json` that is missing is not a refusal, as it is not one for doctor: a workspace whose people do
15
+ // not use Claude Code has no plugin and so no second pin. Its workflow pin is raised and the run says so.
16
+ //
17
+ // The edit is made on the file's text, so what else is in the file, its formatting included, is untouched. The pin is a
18
+ // commit's SHA, never the release's tag, which can be moved (ADR-0014 part 7).
19
+ import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
20
+ import path from 'node:path'
21
+ import { readJson, takeAppDir, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
22
+ import { kitDirOf, kitReleaseStampOf, kitVersionOf } from '../kit.js'
23
+ import { githubRepositoryOf, isInRepoKit, sourceRepository, stampedCommit, WORKFLOW_USES } from './doctor-checks.js'
24
+
25
+ const SETTINGS = '.claude/settings.json'
26
+
27
+ /**
28
+ * @typedef {{ file: string, line?: number, what: string, from: string | null, to: string, comment?: true }} Change one
29
+ * pin: where it is, and the ref it had (null: none) and has; `comment`: only the version in its trailing comment moved
30
+ * @typedef {{ file: string, text: string }} SourceFile a file of the workspace, by the path shown for it, and its text
31
+ * @typedef {{ file: string, text: string, changes: Change[] }} Edited a file with the pins in it, `text` as it will be
32
+ * (the text it was, when no pin in it moves)
33
+ */
34
+
35
+ /**
36
+ * The version in a trailing comment after a workflow pin, in the forms the generator (`# @sssb/create 0.2.0`) and the
37
+ * earlier release notes (`# v0.2.0`) wrote, and `# @sssb/kit 0.2.0`, moved to `version`; any other comment, which is the adopter's, as it was.
38
+ * @param {string} rest what follows the ref on the `uses:` line
39
+ * @param {string} version
40
+ */
41
+ function withVersionComment(rest, version) {
42
+ return rest.replace(/^(['"]?\s+#\s*(?:@sssb\/(?:create|kit)\s+|v))\d[\w.+-]*(\s*)$/, `$1${version}$2`)
43
+ }
44
+
45
+ /**
46
+ * The workflow files' pins of `repository`'s reusable workflows, moved to `commit`.
47
+ * @param {SourceFile[]} workflows
48
+ * @param {string} repository `owner/name`, lowercased
49
+ * @param {string} commit
50
+ * @param {string} version the kit's, for a comment that names it
51
+ * @returns {Edited[]}
52
+ */
53
+ function raiseWorkflowPins(workflows, repository, commit, version) {
54
+ /** @type {Edited[]} */
55
+ const edited = []
56
+ for (const { file, text } of workflows) {
57
+ /** @type {Change[]} */
58
+ const changes = []
59
+ const lines = text.split('\n').map((line, index) => {
60
+ const match = WORKFLOW_USES.exec(line)
61
+ if (match?.[2]?.toLowerCase() !== repository) return line
62
+ const [, prefix = '', , workflow = '', ref = '', rest = ''] = match
63
+ const next = `${prefix}${commit}${withVersionComment(rest, version)}`
64
+ changes.push({
65
+ file,
66
+ line: index + 1,
67
+ what: workflow,
68
+ from: ref,
69
+ to: commit,
70
+ ...(ref === commit && next !== line ? { comment: true } : {}),
71
+ })
72
+ return next
73
+ })
74
+ if (changes.length > 0) edited.push({ file, text: lines.join('\n'), changes })
75
+ }
76
+ return edited
77
+ }
78
+
79
+ /**
80
+ * @typedef {{ kind: 'object', start: number, end: number, props: { key: string, keyStart: number, node: Node }[] }
81
+ * | { kind: 'array', start: number, end: number }
82
+ * | { kind: 'string', start: number, end: number, value: string }
83
+ * | { kind: 'other', start: number, end: number }} Node a JSON value and where its text sits
84
+ */
85
+
86
+ /**
87
+ * Where each value of a JSON text sits (the offsets of its first and one past its last character), so a value can be
88
+ * replaced without printing the whole file again. The text has already been through `JSON.parse`, so it is valid.
89
+ * @param {string} text
90
+ * @returns {Node}
91
+ */
92
+ function locate(text) {
93
+ let i = 0
94
+ const space = () => {
95
+ while (i < text.length && /\s/.test(text.charAt(i))) i++
96
+ }
97
+ /** @returns {Node & { kind: 'string' }} */
98
+ const string = () => {
99
+ const start = i
100
+ for (i++; text.charAt(i) !== '"'; i++) if (text.charAt(i) === '\\') i++
101
+ i++
102
+ return { kind: 'string', start, end: i, value: JSON.parse(text.slice(start, i)) }
103
+ }
104
+ /** @returns {Node} */
105
+ const value = () => {
106
+ space()
107
+ const start = i
108
+ const first = text.charAt(i)
109
+ if (first === '{') {
110
+ /** @type {(Node & { kind: 'object' })['props']} */
111
+ const props = []
112
+ i++
113
+ space()
114
+ while (text.charAt(i) !== '}') {
115
+ space()
116
+ const key = string()
117
+ space()
118
+ i++ // the colon
119
+ props.push({ key: key.value, keyStart: key.start, node: value() })
120
+ space()
121
+ if (text.charAt(i) === ',') i++
122
+ space()
123
+ }
124
+ i++
125
+ return { kind: 'object', start, end: i, props }
126
+ }
127
+ if (first === '[') {
128
+ i++
129
+ space()
130
+ while (text.charAt(i) !== ']') {
131
+ value()
132
+ space()
133
+ if (text.charAt(i) === ',') i++
134
+ space()
135
+ }
136
+ i++
137
+ return { kind: 'array', start, end: i }
138
+ }
139
+ if (first === '"') return string()
140
+ while (i < text.length && !/[\s,\]}]/.test(text.charAt(i))) i++
141
+ return { kind: 'other', start, end: i }
142
+ }
143
+ return value()
144
+ }
145
+
146
+ /**
147
+ * The property of an object node named `key`; of several, the last, which is the one `JSON.parse` keeps, and so the one
148
+ * Claude Code and `sssb doctor` read.
149
+ * @param {(Node & { kind: 'object' })['props']} props
150
+ * @param {string} key
151
+ */
152
+ const lastProp = (props, key) => props.findLast((prop) => prop.key === key)
153
+
154
+ /**
155
+ * The marketplaces `.claude/settings.json` declares from `repository`, their `ref` moved to `commit`: replaced where
156
+ * there is one, added to the `source` where there is none (a marketplace that follows the default branch).
157
+ * @param {SourceFile} settings
158
+ * @param {string} repository `owner/name`, lowercased
159
+ * @param {string} commit
160
+ * @returns {{ edited: Edited | null, refusal: string | null }}
161
+ */
162
+ function raiseMarketplacePins({ file, text }, repository, commit) {
163
+ try {
164
+ JSON.parse(text)
165
+ } catch (error) {
166
+ return {
167
+ edited: null,
168
+ refusal: `${file} is not JSON this command can read (${error instanceof Error ? error.message : error})`,
169
+ }
170
+ }
171
+ const root = locate(text)
172
+ const marketplaces = root.kind === 'object' ? lastProp(root.props, 'extraKnownMarketplaces') : null
173
+ /** @type {{ start: number, end: number, insert: string }[]} */
174
+ const edits = []
175
+ /** @type {Change[]} */
176
+ const changes = []
177
+ if (marketplaces?.node.kind === 'object') {
178
+ for (const { key: name, node: entry } of marketplaces.node.props) {
179
+ const source = entry.kind === 'object' ? lastProp(entry.props, 'source')?.node : null
180
+ if (source?.kind !== 'object') continue
181
+ const valueOf = (/** @type {string} */ key) => {
182
+ const node = lastProp(source.props, key)?.node
183
+ return node?.kind === 'string' ? node.value : undefined
184
+ }
185
+ if (
186
+ sourceRepository({ source: valueOf('source'), repo: valueOf('repo'), url: valueOf('url') }) !==
187
+ repository
188
+ )
189
+ continue
190
+ const what = `marketplace ${name}`
191
+ const ref = lastProp(source.props, 'ref')
192
+ if (ref === undefined) {
193
+ const last = source.props.at(-1)
194
+ const first = source.props[0]
195
+ if (last === undefined || first === undefined) continue
196
+ const lineStart = text.lastIndexOf('\n', first.keyStart) + 1
197
+ const indent = text.slice(lineStart, first.keyStart)
198
+ const multiline = text.slice(source.start, first.keyStart).includes('\n') && /^\s*$/.test(indent)
199
+ edits.push({
200
+ start: last.node.end,
201
+ end: last.node.end,
202
+ insert: multiline
203
+ ? `,${text.includes('\r\n') ? '\r\n' : '\n'}${indent}"ref": ${JSON.stringify(commit)}`
204
+ : `, "ref": ${JSON.stringify(commit)}`,
205
+ })
206
+ changes.push({ file, what, from: null, to: commit })
207
+ } else if (ref.node.kind !== 'string') {
208
+ return { edited: null, refusal: `${file} (${what}): its \`ref\` is not a string, so it is not a pin` }
209
+ } else {
210
+ if (ref.node.value !== commit)
211
+ edits.push({ start: ref.node.start, end: ref.node.end, insert: JSON.stringify(commit) })
212
+ changes.push({ file, what, from: ref.node.value, to: commit })
213
+ }
214
+ }
215
+ }
216
+ if (changes.length === 0)
217
+ return {
218
+ edited: null,
219
+ refusal: `${file} declares no marketplace from ${repository}: there is no plugin pin to raise`,
220
+ }
221
+ let next = text
222
+ for (const { start, end, insert } of edits.sort((a, b) => b.start - a.start))
223
+ next = next.slice(0, start) + insert + next.slice(end)
224
+ return { edited: { file, text: next, changes }, refusal: null }
225
+ }
226
+
227
+ /**
228
+ * Every pin of `repository` in the workspace's files, raised to `commit`; or what stops it. Pure: it reads nothing and
229
+ * writes nothing.
230
+ * @param {{
231
+ * commit: string,
232
+ * version: string,
233
+ * repository: string,
234
+ * workflows: SourceFile[],
235
+ * settings: SourceFile | null,
236
+ * }} input `version`: the installed kit's, which a workflow pin's comment may name; `settings`: null when the workspace
237
+ * has no `.claude/settings.json`
238
+ * @returns {{ files: Edited[], refusals: string[], notes: string[] }} `files`: each file that holds a pin, `text` as it
239
+ * will be; nothing is to be written when `refusals` is not empty
240
+ */
241
+ export function planPins({ commit, version, repository, workflows, settings }) {
242
+ /** @type {string[]} */
243
+ const refusals = []
244
+ /** @type {string[]} */
245
+ const notes = []
246
+ const files = raiseWorkflowPins(workflows, repository, commit, version)
247
+ if (files.length === 0)
248
+ refusals.push(
249
+ `no workflow under .github/workflows calls a reusable workflow of ${repository}, so there is no workflow pin to raise`,
250
+ )
251
+ if (settings === null)
252
+ notes.push(
253
+ `no ${SETTINGS}: no plugin marketplace pin to raise (a workspace whose people do not use Claude Code has none)`,
254
+ )
255
+ else {
256
+ const { edited, refusal } = raiseMarketplacePins(settings, repository, commit)
257
+ if (refusal !== null) refusals.push(refusal)
258
+ if (edited !== null) files.push(edited)
259
+ }
260
+ return { files, refusals, notes }
261
+ }
262
+
263
+ /**
264
+ * The app whose kit's stamp is read, as `sssb guide` chooses it: `--app <dir>`; else the working directory when it
265
+ * resolves `@sssb/kit`; else, at a workspace root that takes no framework (a generated workspace's), the first of the
266
+ * workspace's apps that resolves one (`guide` and `doctor` take its first app, resolving or not).
267
+ * @param {string[]} args
268
+ * @param {string} [cwd]
269
+ * @returns {string}
270
+ */
271
+ function pinApp(args, cwd = process.cwd()) {
272
+ if (args.includes('--app')) return takeAppDir(args, cwd)
273
+ const here = path.resolve(cwd)
274
+ const resolves = (/** @type {string} */ dir) => {
275
+ try {
276
+ kitDirOf(dir)
277
+ return true
278
+ } catch {
279
+ return false
280
+ }
281
+ }
282
+ const isRoot = existsSync(path.join(here, 'pnpm-workspace.yaml')) && existsSync(path.join(here, 'package.json'))
283
+ if (isRoot && !resolves(here)) {
284
+ const app = workspaceApps(here)
285
+ .map((dir) => path.resolve(here, dir))
286
+ .find(resolves)
287
+ if (app === undefined) {
288
+ throw new UsageError(
289
+ `sssb pin: ${here} is a workspace root that takes no @sssb/kit, and none of its apps (\`sssb.apps\` in its ` +
290
+ 'package.json, or apps/<name>) resolves one: pass --app <dir>',
291
+ )
292
+ }
293
+ return app
294
+ }
295
+ // Anything else: the app is the working directory, and kitDirOf's refusal says to name one with --app.
296
+ return takeAppDir(args, cwd)
297
+ }
298
+
299
+ /** @param {string} file */
300
+ const readIfThere = (file) => (existsSync(file) ? readFileSync(file, 'utf8') : null)
301
+
302
+ /**
303
+ * The workspace root's `.github/workflows/*.{yml,yaml}`, sorted, with their text (as doctor reads them).
304
+ * @param {string} root
305
+ * @returns {SourceFile[]}
306
+ */
307
+ function workflowFiles(root) {
308
+ const dir = path.join(root, '.github', 'workflows')
309
+ if (!existsSync(dir)) return []
310
+ return readdirSync(dir)
311
+ .filter((name) => /\.ya?ml$/.test(name))
312
+ .sort()
313
+ .map((name) => ({
314
+ file: `.github/workflows/${name}`,
315
+ text: /** @type {string} */ (readIfThere(path.join(dir, name))),
316
+ }))
317
+ }
318
+
319
+ /** @param {string[]} args */
320
+ export async function run(args) {
321
+ const appDir = realpathSync(pinApp(args))
322
+ if (args.length > 0) throw new UsageError(`sssb pin: unknown argument ${args[0]} (usage: pin [--app <dir>])`)
323
+ const root = realpathSync(workspaceRootOf(appDir))
324
+ const kitDir = kitDirOf(appDir)
325
+ const version = kitVersionOf(appDir)
326
+ const kit = `@sssb/kit ${version}`
327
+ const stamp = kitReleaseStampOf(appDir)
328
+
329
+ if (isInRepoKit(kitDir, root)) {
330
+ throw new UsageError(
331
+ `sssb pin: ${kit} here is this workspace's own source, which carries no release stamp (dist/release.json), so ` +
332
+ 'there is no release commit to pin SSSB to. Nothing was changed',
333
+ )
334
+ }
335
+ const commit = stampedCommit(stamp)
336
+ if (commit === null) {
337
+ throw new UsageError(
338
+ `sssb pin: ${kit} ` +
339
+ (stamp === null
340
+ ? 'carries no release stamp (dist/release.json): it was packed by hand, or before ADR-0014 P13 stamped one'
341
+ : 'has a release stamp (dist/release.json) that names no commit') +
342
+ ', so there is no release commit to pin SSSB to. Nothing was changed',
343
+ )
344
+ }
345
+ const repository = githubRepositoryOf(readJson(path.join(kitDir, 'package.json')).repository)
346
+ if (repository === null) {
347
+ throw new UsageError(
348
+ `sssb pin: ${kit}'s package.json names no GitHub repository, so this cannot tell which pins are SSSB's. Nothing was changed`,
349
+ )
350
+ }
351
+
352
+ const settingsText = readIfThere(path.join(root, ...SETTINGS.split('/')))
353
+ const workflows = workflowFiles(root)
354
+ const plan = planPins({
355
+ commit,
356
+ version,
357
+ repository,
358
+ workflows,
359
+ settings: settingsText === null ? null : { file: SETTINGS, text: settingsText },
360
+ })
361
+ if (plan.refusals.length > 0) {
362
+ throw new UsageError(
363
+ [
364
+ `sssb pin: not raising any pin, because the workspace's files are not what this command edits (${kit}, release commit ${commit}):`,
365
+ ...plan.refusals.map((refusal) => ` ${refusal}`),
366
+ 'Nothing was changed. Edit the pins by hand, as the release notes say, or put the files back in the shape ' +
367
+ '`sssb doctor` reads, then run this again',
368
+ ].join('\n'),
369
+ )
370
+ }
371
+
372
+ console.log(`sssb pin: ${kit}, release commit ${commit}`)
373
+ const before = new Map(
374
+ [...workflows, ...(settingsText === null ? [] : [{ file: SETTINGS, text: settingsText }])].map((f) => [
375
+ f.file,
376
+ f.text,
377
+ ]),
378
+ )
379
+ let moved = 0
380
+ /** @type {string[]} */
381
+ const marketplaces = []
382
+ for (const { file, text, changes } of plan.files) {
383
+ const changed = text !== before.get(file)
384
+ for (const change of changes) {
385
+ const where = `${file}${change.line === undefined ? '' : `:${change.line}`} (${change.what})`
386
+ const was = change.from === null ? 'no ref' : change.from
387
+ if (change.comment) {
388
+ console.log(` ${where}: already ${change.to}; the version in its comment is now ${version}`)
389
+ moved++
390
+ } else if (change.from === change.to) console.log(` ${where}: already ${change.to}`)
391
+ else {
392
+ console.log(` ${where}: ${was} -> ${change.to}`)
393
+ moved++
394
+ }
395
+ if (change.what.startsWith('marketplace ')) marketplaces.push(change.what.slice('marketplace '.length))
396
+ }
397
+ if (changed) writeFileSync(path.join(root, ...file.split('/')), text)
398
+ }
399
+ for (const note of plan.notes) console.log(` ${note}`)
400
+ if (moved === 0) console.log('Every pin was already the release commit: nothing changed.')
401
+ else {
402
+ console.log(`Raised ${moved} pin(s) to ${commit}. Review the diff, then commit it with the package versions.`)
403
+ if (marketplaces.length > 0) {
404
+ console.log(
405
+ 'Then each person updates their installed plugin and restarts Claude Code: ' +
406
+ `\`claude plugin marketplace update ${marketplaces[0]}\`, then \`claude plugin update <plugin>@${marketplaces[0]} --scope project\``,
407
+ )
408
+ }
409
+ }
410
+ return 0
411
+ }