@kurvball/rehearse 1.9.0 → 1.10.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 (41) hide show
  1. package/README.md +3 -2
  2. package/dist/commands/init.js +52 -7
  3. package/dist/detect/detect.d.ts +6 -0
  4. package/dist/detect/detect.js +48 -0
  5. package/dist/detect/finding.d.ts +18 -0
  6. package/dist/detect/finding.js +4 -0
  7. package/dist/detect/globs.d.ts +10 -0
  8. package/dist/detect/globs.js +43 -0
  9. package/dist/detect/index.d.ts +2 -0
  10. package/dist/detect/index.js +2 -0
  11. package/dist/detect/lockfiles.d.ts +15 -0
  12. package/dist/detect/lockfiles.js +64 -0
  13. package/dist/detect/paths.d.ts +5 -0
  14. package/dist/detect/paths.js +39 -0
  15. package/dist/detect/pieces.d.ts +14 -0
  16. package/dist/detect/pieces.js +119 -0
  17. package/dist/detect/prepare.d.ts +14 -0
  18. package/dist/detect/prepare.js +78 -0
  19. package/dist/detect/repository.d.ts +33 -0
  20. package/dist/detect/repository.js +166 -0
  21. package/dist/detect/scenarios.d.ts +26 -0
  22. package/dist/detect/scenarios.js +170 -0
  23. package/dist/detect/scripts.d.ts +46 -0
  24. package/dist/detect/scripts.js +233 -0
  25. package/dist/detect/services.d.ts +16 -0
  26. package/dist/detect/services.js +171 -0
  27. package/dist/detect/write.d.ts +18 -0
  28. package/dist/detect/write.js +115 -0
  29. package/dist/manifest/index.d.ts +1 -1
  30. package/dist/manifest/index.js +1 -1
  31. package/dist/manifest/init.d.ts +47 -1
  32. package/dist/manifest/init.js +19 -16
  33. package/dist/scenarios/glob.d.ts +1 -0
  34. package/dist/scenarios/glob.js +10 -3
  35. package/dist/scenarios/index.d.ts +1 -1
  36. package/dist/scenarios/index.js +1 -1
  37. package/llms.txt +1 -1
  38. package/package.json +1 -1
  39. package/schema/v1/init.schema.json +69 -1
  40. package/schema/v1/samples/init.json +46 -1
  41. package/skill/rehearse/SKILL.md +5 -0
package/README.md CHANGED
@@ -24,7 +24,8 @@ rehearse compare --base main
24
24
 
25
25
  ## What a repository declares
26
26
 
27
- One file, `rehearse.yaml`. Every block is optional: a repository declares what it has.
27
+ One file, `rehearse.yaml`. Every block is optional: a repository declares what it has. `rehearse init --detect` writes
28
+ it from what it finds: the base branch, the install, a service for each app's dev server, and the scenarios.
28
29
 
29
30
  ```yaml
30
31
  base: main
@@ -58,7 +59,7 @@ Scenarios use formats agents already write:
58
59
 
59
60
  | Command | What it does |
60
61
  | ------------------------------------------- | ------------------------------------------------- |
61
- | `rehearse init` | Writes a starter `rehearse.yaml` |
62
+ | `rehearse init [--detect]` | Writes `rehearse.yaml`, filled in from the repo |
62
63
  | `rehearse check` | Reads the manifest and every scenario file |
63
64
  | `rehearse services`, `people`, `worlds` | What can come up, who you can be, where you start |
64
65
  | `rehearse list [--affected <file>…]` | The scenarios, or those a change reaches, and why |
@@ -1,19 +1,64 @@
1
1
  import { existsSync, writeFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
- import { said } from './command.js';
4
- import { MANIFEST_FILE, STARTER } from '../manifest/index.js';
3
+ import { columns, said } from './command.js';
4
+ import { detect, printable } from '../detect/index.js';
5
+ import { MANIFEST_FILE, manifestFrom, STARTER } from '../manifest/index.js';
5
6
  import { RehearseError } from '../errors.js';
7
+ const label = (f) => (f.name ? `${f.kind} ${f.name}` : f.kind);
8
+ const NEXT_SAYS = [
9
+ 'reads the manifest and every scenario file',
10
+ 'lists every scenario it found',
11
+ 'on a change: runs each scenario on the base and here, and compares them',
12
+ ];
13
+ function detectedText(file, d) {
14
+ const written = d.findings.filter((f) => f.written);
15
+ const left = d.findings.filter((f) => !f.written);
16
+ const nextOf = (f) => (f.next ? [['', printable(f.next)]] : []);
17
+ return [
18
+ `Wrote ${file} from what the repository has.`,
19
+ '',
20
+ ...(written.length
21
+ ? [
22
+ 'Found and written:',
23
+ columns(written.flatMap((f) => [
24
+ [label(f), printable(`${f.why} (${f.from})`)],
25
+ ...nextOf(f),
26
+ ])),
27
+ ]
28
+ : ['It found nothing to fill in, so every block is commented: keep the ones this repository has.']),
29
+ ...(left.length
30
+ ? [
31
+ '',
32
+ 'Found, not written:',
33
+ columns(left.flatMap((f) => [
34
+ [label(f), printable(`${f.from}: ${f.why}`)],
35
+ ...nextOf(f),
36
+ ])),
37
+ ]
38
+ : []),
39
+ '',
40
+ 'Next:',
41
+ columns(d.next.map((command, i) => [command, NEXT_SAYS[i] ?? ''])),
42
+ '',
43
+ ].join('\n');
44
+ }
6
45
  export const init = {
7
46
  name: 'init',
8
- summary: 'Writes a starter rehearse.yaml in this folder, every block commented.',
9
- usage: 'rehearse init [--force] [--json]',
10
- spec: { valued: [], bare: ['force'] },
47
+ summary: 'Writes a starter rehearse.yaml in this folder, every block commented, or with --detect, filled in from what it finds.',
48
+ usage: "rehearse init [--detect] [--force] [--json]\n\n--detect looks at the repository and fills in what it finds: the base branch, prepare, services and scenarios.\nEach block says what it was detected from; what it found but couldn't write is named, with the next step.",
49
+ spec: { valued: [], bare: ['detect', 'force'] },
11
50
  async run(args, ctx) {
12
51
  const file = path.join(ctx.cwd, MANIFEST_FILE);
13
52
  const there = existsSync(file);
14
53
  if (there && !args.flags.has('force'))
15
54
  throw new RehearseError('exists', `${file} is already there. Give --force to replace it.`);
16
- writeFileSync(file, STARTER);
17
- return said({ v: 1, file, replaced: there }, `Wrote ${file}.\nKeep the blocks this repository has, then run \`rehearse check\`.\n`);
55
+ if (!args.flags.has('detect')) {
56
+ writeFileSync(file, STARTER);
57
+ return said({ v: 1, file, replaced: there }, `Wrote ${file}.\nKeep the blocks this repository has, then run \`rehearse check\`.\n`);
58
+ }
59
+ const { text, detected } = detect(ctx.cwd);
60
+ manifestFrom(text, file);
61
+ writeFileSync(file, text);
62
+ return said({ v: 1, file, replaced: there, detected }, detectedText(file, detected));
18
63
  },
19
64
  };
@@ -0,0 +1,6 @@
1
+ import type { Detected } from './finding.ts';
2
+ export interface Detection {
3
+ text: string;
4
+ detected: Detected;
5
+ }
6
+ export declare function detect(root: string): Detection;
@@ -0,0 +1,48 @@
1
+ import { buildsOf, prepareOf } from './prepare.js';
2
+ import { defaultBranch, readRepository } from './repository.js';
3
+ import { scenariosOf } from './scenarios.js';
4
+ import { quoted } from './scripts.js';
5
+ import { servicesOf } from './services.js';
6
+ import { manifestText } from './write.js';
7
+ export function detect(root) {
8
+ const repo = readRepository(root);
9
+ const branch = defaultBranch(root);
10
+ const found = servicesOf(repo);
11
+ const scenarios = scenariosOf(repo, found.services);
12
+ const prepare = prepareOf(repo, buildsOf(repo, found.services, scenarios.pieceDirs));
13
+ const findings = [
14
+ ...(branch
15
+ ? [{ kind: 'base', from: branch.from, written: true, why: `${branch.branch}, the default branch` }]
16
+ : []),
17
+ ...prepare.findings,
18
+ ...found.findings,
19
+ ...scenarios.findings,
20
+ ...(repo.git && !repo.ignored('.rehearse/runs')
21
+ ? [
22
+ {
23
+ kind: 'gitignore',
24
+ from: '.gitignore',
25
+ written: false,
26
+ why: "Rehearse keeps base checkouts, its cache and runs in .rehearse/, and git doesn't ignore it.",
27
+ next: 'Add .rehearse/ to .gitignore.',
28
+ },
29
+ ]
30
+ : []),
31
+ ];
32
+ const base = branch?.branch ?? 'main';
33
+ const against = branch && !branch.local ? `origin/${base}` : base;
34
+ return {
35
+ text: manifestText({
36
+ base: branch,
37
+ prepare: prepare.command === null ? null : { command: prepare.command, from: prepare.from },
38
+ services: found.services,
39
+ blocks: scenarios.blocks,
40
+ prefix: repo.prefix,
41
+ }),
42
+ detected: {
43
+ base,
44
+ findings,
45
+ next: ['rehearse check', 'rehearse list', `rehearse compare --base ${quoted(against)}`],
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,18 @@
1
+ export interface Finding {
2
+ kind: string;
3
+ name?: string;
4
+ from: string;
5
+ count?: number;
6
+ written: boolean;
7
+ why: string;
8
+ next?: string;
9
+ }
10
+ export interface Detected {
11
+ base: string;
12
+ findings: Finding[];
13
+ next: string[];
14
+ }
15
+ export declare const GUIDE = "https://rehearse.kurvball.ca";
16
+ export declare const hasControl: (text: string) => boolean;
17
+ export declare const printable: (text: string) => string;
18
+ export declare const counted: (n: number, one: string, many: string) => string;
@@ -0,0 +1,4 @@
1
+ export const GUIDE = 'https://rehearse.kurvball.ca';
2
+ export const hasControl = (text) => /[\p{Cc}\u2028\u2029]/u.test(text);
3
+ export const printable = (text) => text.replace(/[\p{Cc}\u2028\u2029]/gu, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
4
+ export const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
@@ -0,0 +1,10 @@
1
+ import { type SchemaName } from '../schema.ts';
2
+ import { type Repository } from './repository.ts';
3
+ export declare const either: (values: readonly string[]) => string;
4
+ export declare const globOf: (files: readonly string[], name: string) => string;
5
+ export declare const extensionsOf: (files: readonly string[], re: RegExp) => string[];
6
+ export declare const and: (items: readonly string[]) => string;
7
+ export declare function unreadable(repo: Repository, files: readonly string[], schema: SchemaName): {
8
+ file: string;
9
+ says: string;
10
+ } | null;
@@ -0,0 +1,43 @@
1
+ import path from 'node:path';
2
+ import { readYaml } from '../manifest/index.js';
3
+ import { escapeGlob } from '../scenarios/index.js';
4
+ import { validate } from '../schema.js';
5
+ import { joined, readText } from './repository.js';
6
+ function commonDir(files) {
7
+ let common = null;
8
+ for (const file of files) {
9
+ const parts = path.posix
10
+ .dirname(file)
11
+ .split('/')
12
+ .filter((p) => p !== '.');
13
+ if (common === null)
14
+ common = parts;
15
+ else {
16
+ let i = 0;
17
+ while (i < common.length && common[i] === parts[i])
18
+ i += 1;
19
+ common = common.slice(0, i);
20
+ }
21
+ }
22
+ return (common ?? []).join('/');
23
+ }
24
+ export const either = (values) => {
25
+ const unique = [...new Set(values)].sort();
26
+ return unique.length === 1 ? unique[0] : `{${unique.join(',')}}`;
27
+ };
28
+ export const globOf = (files, name) => joined(escapeGlob(commonDir(files)), '**', name);
29
+ export const extensionsOf = (files, re) => files.map((f) => re.exec(f)?.[1] ?? '').filter(Boolean);
30
+ export const and = (items) => items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
31
+ export function unreadable(repo, files, schema) {
32
+ for (const file of files) {
33
+ try {
34
+ const invalid = validate(schema, readYaml(readText(path.join(repo.root, file)) ?? '', file).value);
35
+ if (invalid.length)
36
+ return { file, says: invalid[0].says };
37
+ }
38
+ catch (error) {
39
+ return { file, says: error.message.split('\n')[0] ?? '' };
40
+ }
41
+ }
42
+ return null;
43
+ }
@@ -0,0 +1,2 @@
1
+ export { detect, type Detection } from './detect.ts';
2
+ export { printable, type Detected, type Finding } from './finding.ts';
@@ -0,0 +1,2 @@
1
+ export { detect } from './detect.js';
2
+ export { printable } from './finding.js';
@@ -0,0 +1,15 @@
1
+ import type { Finding } from './finding.ts';
2
+ export type Manager = 'pnpm' | 'npm' | 'yarn' | 'bun';
3
+ export interface Lockfile {
4
+ dir: string;
5
+ file: string;
6
+ manager: Manager;
7
+ install: string;
8
+ }
9
+ export interface Locked {
10
+ lockfile: Lockfile | null;
11
+ manager: Manager | null;
12
+ finding: Finding | null;
13
+ }
14
+ export declare function managerNamed(packageManager: unknown): Manager | null;
15
+ export declare function lockIn(root: string, dir: string, declared: Manager | null): Locked;
@@ -0,0 +1,64 @@
1
+ import path from 'node:path';
2
+ import { isFile, joined, readHead } from './paths.js';
3
+ const LOCKFILES = [
4
+ ['pnpm-lock.yaml', 'pnpm'],
5
+ ['package-lock.json', 'npm'],
6
+ ['npm-shrinkwrap.json', 'npm'],
7
+ ['yarn.lock', 'yarn'],
8
+ ['bun.lock', 'bun'],
9
+ ['bun.lockb', 'bun'],
10
+ ];
11
+ const YARN_HEADER_BYTES = 512;
12
+ const INSTALL = {
13
+ pnpm: () => 'pnpm install --frozen-lockfile --prefer-offline',
14
+ npm: () => 'npm ci',
15
+ yarn: (file) => readHead(file, YARN_HEADER_BYTES).includes('# yarn lockfile v1')
16
+ ? 'yarn install --frozen-lockfile'
17
+ : 'yarn install --immutable',
18
+ bun: () => 'bun install --frozen-lockfile',
19
+ };
20
+ export function managerNamed(packageManager) {
21
+ const said = typeof packageManager === 'string' ? packageManager.split('@')[0] : null;
22
+ return said === 'pnpm' || said === 'npm' || said === 'yarn' || said === 'bun' ? said : null;
23
+ }
24
+ const and = (items) => items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
25
+ export function lockIn(root, dir, declared) {
26
+ const found = LOCKFILES.map(([name, manager]) => ({ file: joined(dir, name), manager })).filter((f) => isFile(path.join(root, f.file)));
27
+ if (found.length === 0)
28
+ return { lockfile: null, manager: null, finding: null };
29
+ const managers = [...new Set(found.map((f) => f.manager))];
30
+ const chosen = declared ?? (managers.length === 1 ? managers[0] : null);
31
+ const mine = found.find((f) => f.manager === chosen);
32
+ const files = (list) => list.map((f) => f.file);
33
+ if (chosen && mine) {
34
+ const others = found.filter((f) => f.manager !== chosen);
35
+ return {
36
+ lockfile: { ...mine, dir, install: INSTALL[chosen](path.join(root, mine.file)) },
37
+ manager: chosen,
38
+ finding: others.length
39
+ ? {
40
+ kind: 'prepare',
41
+ from: files(others).join(', '),
42
+ written: false,
43
+ why: `packageManager says ${chosen}, so prepare installs from ${mine.file} and leaves out ${and(files(others))}.`,
44
+ next: `Remove ${and(files(others))} if ${chosen} is what this repository uses.`,
45
+ }
46
+ : null,
47
+ };
48
+ }
49
+ return {
50
+ lockfile: null,
51
+ manager: chosen ?? found[0].manager,
52
+ finding: {
53
+ kind: 'prepare',
54
+ from: files(found).join(', '),
55
+ written: false,
56
+ why: chosen
57
+ ? `packageManager says ${chosen}, but the lockfile is ${and(files(found))}, so Rehearse can't tell how to install.`
58
+ : `There are lockfiles for ${and(managers)}, and no packageManager in package.json says which one installs.`,
59
+ next: chosen
60
+ ? `Commit ${chosen}'s lockfile, or set packageManager to the manager ${and(files(found))} is for.`
61
+ : "Remove the lockfiles you don't use, or set packageManager in package.json.",
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,5 @@
1
+ export declare const joined: (...parts: string[]) => string;
2
+ export declare const within: (dir: string, file: string) => boolean;
3
+ export declare function readText(file: string): string | null;
4
+ export declare function readHead(file: string, bytes: number): string;
5
+ export declare const isFile: (file: string) => boolean;
@@ -0,0 +1,39 @@
1
+ import { closeSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const READ_LIMIT = 512 * 1024;
4
+ export const joined = (...parts) => {
5
+ const at = path.posix.normalize(path.posix.join('.', ...parts.filter(Boolean)));
6
+ return at === '.' ? '' : at;
7
+ };
8
+ export const within = (dir, file) => dir === '' || file.startsWith(`${dir}/`);
9
+ export function readText(file) {
10
+ try {
11
+ return statSync(file).size > READ_LIMIT ? null : readFileSync(file, 'utf8');
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export function readHead(file, bytes) {
18
+ let fd = null;
19
+ try {
20
+ fd = openSync(file, 'r');
21
+ const buffer = Buffer.alloc(bytes);
22
+ return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0)).toString('utf8');
23
+ }
24
+ catch {
25
+ return '';
26
+ }
27
+ finally {
28
+ if (fd !== null)
29
+ closeSync(fd);
30
+ }
31
+ }
32
+ export const isFile = (file) => {
33
+ try {
34
+ return statSync(file).isFile();
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ };
@@ -0,0 +1,14 @@
1
+ import { type Finding } from './finding.ts';
2
+ import { type Repository } from './repository.ts';
3
+ export interface PiecesBlock {
4
+ paths: string[];
5
+ preview: string | null;
6
+ previewFile: string | null;
7
+ count: number;
8
+ }
9
+ export declare const PIECE: RegExp;
10
+ export declare function piecesOf(repo: Repository, stories: readonly string[]): {
11
+ block: PiecesBlock | null;
12
+ findings: Finding[];
13
+ dirs: string[];
14
+ };
@@ -0,0 +1,119 @@
1
+ import path from 'node:path';
2
+ import { counted, GUIDE } from './finding.js';
3
+ import { and, either, extensionsOf, globOf } from './globs.js';
4
+ import { declares, isFile, joined } from './repository.js';
5
+ export const PIECE = /\.stories\.(tsx|jsx|ts|js)$/;
6
+ const PREVIEWS = ['tsx', 'ts', 'jsx', 'js', 'mjs', 'mts'].map((ext) => `.storybook/preview.${ext}`);
7
+ function pieceGroups(repo, stories) {
8
+ const memo = new Map();
9
+ const lacks = (dir) => {
10
+ if (!memo.has(dir))
11
+ memo.set(dir, ['vite', 'react'].filter((name) => !declares(repo, dir, name)));
12
+ return memo.get(dir);
13
+ };
14
+ const groups = new Map();
15
+ for (const file of stories) {
16
+ let nearest = null;
17
+ let renders = null;
18
+ for (let dir = joined(path.posix.dirname(file)); renders === null; dir = joined(dir, '..')) {
19
+ if (isFile(path.join(repo.root, dir, 'package.json'))) {
20
+ const missing = lacks(dir);
21
+ if (missing.length === 0)
22
+ renders = { dir, files: [], missing };
23
+ else
24
+ nearest ??= { dir, files: [], missing };
25
+ }
26
+ if (dir === '')
27
+ break;
28
+ }
29
+ const group = renders ?? nearest ?? { dir: '', files: [], missing: ['vite', 'react'] };
30
+ const key = `${group.dir}\0${group.missing.join()}`;
31
+ if (!groups.has(key))
32
+ groups.set(key, group);
33
+ groups.get(key).files.push(file);
34
+ }
35
+ return [...groups.values()];
36
+ }
37
+ function previewOf(repo, dir) {
38
+ for (let at = dir;; at = joined(at, '..')) {
39
+ const found = PREVIEWS.map((p) => joined(at, p)).find((f) => isFile(path.join(repo.root, f)));
40
+ if (found)
41
+ return found;
42
+ if (at === '')
43
+ return null;
44
+ }
45
+ }
46
+ const named = (dir) => dir || 'the root package';
47
+ function previewFor(repo, dirs) {
48
+ const found = dirs.map((dir) => ({ dir, file: previewOf(repo, dir) }));
49
+ const paths = new Set(found.map((f) => (f.file ? path.posix.relative(f.dir || '.', f.file) : null)));
50
+ const shared = paths.size === 1 ? [...paths][0] : null;
51
+ if (shared !== null)
52
+ return {
53
+ shared: {
54
+ preview: shared,
55
+ file: found.length === 1 ? found[0].file : `${shared} in each story package`,
56
+ },
57
+ finding: null,
58
+ };
59
+ const having = found.filter((f) => f.file);
60
+ if (having.length === 0)
61
+ return { shared: null, finding: null };
62
+ const lacking = found.filter((f) => !f.file).map((f) => named(f.dir));
63
+ const has = (n) => (n === 1 ? 'has' : 'have');
64
+ return {
65
+ shared: null,
66
+ finding: {
67
+ kind: 'preview',
68
+ from: having.map((f) => f.file).join(', '),
69
+ written: false,
70
+ why: lacking.length
71
+ ? `${and(having.map((f) => named(f.dir)))} ${has(having.length)} a Storybook preview and ${and(lacking)} ${has(lacking.length)} none, but one preview path serves the pieces of every package.`
72
+ : 'The story packages keep their Storybook previews at different paths, but one preview path serves the pieces of every package.',
73
+ next: 'Give each story package its preview at the same path, then add it under pieces as preview.',
74
+ },
75
+ };
76
+ }
77
+ export function piecesOf(repo, stories) {
78
+ const findings = [];
79
+ const written = [];
80
+ for (const group of pieceGroups(repo, stories)) {
81
+ const glob = globOf(group.files, `*.stories.${either(extensionsOf(group.files, PIECE))}`);
82
+ if (group.missing.length === 0) {
83
+ written.push({ dir: group.dir, glob, count: group.files.length });
84
+ continue;
85
+ }
86
+ findings.push({
87
+ kind: 'pieces',
88
+ from: glob,
89
+ count: group.files.length,
90
+ written: false,
91
+ why: `${counted(group.files.length, 'story file', 'story files')} in ${named(group.dir)}, which has no ${group.missing.join(' or ')}: Rehearse renders pieces with their package's own Vite and React.`,
92
+ next: `Add ${group.missing.join(' and ')} to its devDependencies, then add a pieces block: ${GUIDE}/guides/pieces/`,
93
+ });
94
+ }
95
+ const dirs = written.map((w) => w.dir);
96
+ const { shared, finding } = previewFor(repo, dirs);
97
+ for (const w of written)
98
+ findings.push({
99
+ kind: 'pieces',
100
+ from: w.glob,
101
+ count: w.count,
102
+ written: true,
103
+ why: `${counted(w.count, 'story file', 'story files')}, rendered with the Vite and React of ${named(w.dir)}${shared ? ', with the preview' : ''}`,
104
+ });
105
+ if (finding)
106
+ findings.push(finding);
107
+ return {
108
+ block: written.length
109
+ ? {
110
+ paths: written.map((w) => w.glob),
111
+ preview: shared?.preview ?? null,
112
+ previewFile: shared?.file ?? null,
113
+ count: written.reduce((n, w) => n + w.count, 0),
114
+ }
115
+ : null,
116
+ findings,
117
+ dirs,
118
+ };
119
+ }
@@ -0,0 +1,14 @@
1
+ import type { Finding } from './finding.ts';
2
+ import { type Package, type Repository } from './repository.ts';
3
+ import type { Service } from './services.ts';
4
+ export interface Build {
5
+ pkg: Package;
6
+ why: string;
7
+ }
8
+ export interface Prepare {
9
+ command: string | null;
10
+ from: string[];
11
+ findings: Finding[];
12
+ }
13
+ export declare function buildsOf(repo: Repository, services: readonly Service[], pieceDirs: readonly string[]): Build[];
14
+ export declare function prepareOf(repo: Repository, builds: readonly Build[]): Prepare;
@@ -0,0 +1,78 @@
1
+ import path from 'node:path';
2
+ import { dependenciesOf, isFile, joined, packageAt } from './repository.js';
3
+ import { quoted } from './scripts.js';
4
+ function entryOf(json) {
5
+ const pick = (value) => {
6
+ if (typeof value === 'string')
7
+ return value;
8
+ if (!value || typeof value !== 'object' || Array.isArray(value))
9
+ return null;
10
+ const v = value;
11
+ return pick(v['.'] ?? v.import ?? v.default ?? v.require ?? v.node);
12
+ };
13
+ return (pick(json.exports) ??
14
+ (typeof json.module === 'string' ? json.module : null) ??
15
+ (typeof json.main === 'string' ? json.main : null));
16
+ }
17
+ export function buildsOf(repo, services, pieceDirs) {
18
+ const byName = new Map(repo.packages.filter((p) => p.name).map((p) => [p.name, p]));
19
+ const users = [
20
+ ...services.map((s) => ({ pkg: s.pkg, by: s.name })),
21
+ ...pieceDirs.flatMap((dir) => {
22
+ const pkg = packageAt(repo.root, dir);
23
+ return pkg ? [{ pkg, by: `the pieces in ${dir || 'the root package'}` }] : [];
24
+ }),
25
+ ];
26
+ const walked = new Set(users.map((u) => u.pkg.dir));
27
+ const checked = new Set();
28
+ const used = [];
29
+ for (let i = 0; i < users.length; i += 1) {
30
+ const { pkg, by } = users[i];
31
+ for (const name of dependenciesOf(pkg.json)) {
32
+ const dep = byName.get(name);
33
+ if (!dep || dep.dir === pkg.dir || checked.has(dep.dir))
34
+ continue;
35
+ checked.add(dep.dir);
36
+ if (!walked.has(dep.dir))
37
+ users.push({ pkg: dep, by });
38
+ walked.add(dep.dir);
39
+ const entry = entryOf(dep.json);
40
+ const file = entry ? joined(dep.dir, entry) : null;
41
+ if (file && dep.scripts.build && (!isFile(path.join(repo.root, file)) || repo.ignored(file)))
42
+ used.push({ pkg: dep, why: `${by} uses ${name}, whose ${entry} its build writes` });
43
+ }
44
+ }
45
+ const own = services
46
+ .filter((s) => s.built !== null && s.pkg.scripts.build)
47
+ .map((s) => ({ pkg: s.pkg, why: `${s.name} runs ${s.built}, which its build writes` }));
48
+ return [...used.toReversed(), ...own];
49
+ }
50
+ const inside = (dir, command) => dir ? `(cd ${quoted(dir)} && ${command})` : command;
51
+ export function prepareOf(repo, builds) {
52
+ const steps = [];
53
+ const findings = [];
54
+ for (const lock of repo.lockfiles) {
55
+ steps.push(inside(joined(repo.prefix, lock.dir), lock.install));
56
+ findings.push({ kind: 'prepare', from: lock.file, written: true, why: lock.install });
57
+ }
58
+ findings.push(...repo.locking);
59
+ const installs = repo.lockfiles.length > 0 || repo.locking.length === 0;
60
+ for (const build of builds) {
61
+ const run = `${repo.managerOf(build.pkg.dir)} run build`;
62
+ if (installs)
63
+ steps.push(inside(joined(repo.prefix, build.pkg.dir), run));
64
+ findings.push({
65
+ kind: 'build',
66
+ from: build.pkg.file,
67
+ written: installs,
68
+ why: installs
69
+ ? `${run}: ${build.why}`
70
+ : `${build.why}, but it waits for an install prepare can't write.`,
71
+ });
72
+ }
73
+ return {
74
+ command: steps.length ? steps.join(' && ') : null,
75
+ from: findings.filter((f) => f.written).map((f) => f.from),
76
+ findings,
77
+ };
78
+ }
@@ -0,0 +1,33 @@
1
+ import type { Finding } from './finding.ts';
2
+ import { type Lockfile, type Manager } from './lockfiles.ts';
3
+ export { isFile, joined, readText, within } from './paths.ts';
4
+ export type { Lockfile, Manager } from './lockfiles.ts';
5
+ export type PackageJson = Record<string, unknown>;
6
+ export interface Package {
7
+ dir: string;
8
+ file: string;
9
+ name: string | null;
10
+ json: PackageJson;
11
+ scripts: Record<string, string>;
12
+ }
13
+ export interface Repository {
14
+ root: string;
15
+ prefix: string;
16
+ git: boolean;
17
+ files: readonly string[];
18
+ packages: Package[];
19
+ workspaces: boolean;
20
+ lockfiles: Lockfile[];
21
+ locking: Finding[];
22
+ managerOf(dir: string): Manager;
23
+ ignored(file: string): boolean;
24
+ }
25
+ export declare const dependenciesOf: (json: PackageJson) => string[];
26
+ export declare function packageAt(root: string, dir: string): Package | null;
27
+ export declare function readRepository(root: string): Repository;
28
+ export declare function declares(repo: Repository, dir: string, name: string): boolean;
29
+ export declare function defaultBranch(root: string): {
30
+ branch: string;
31
+ from: string;
32
+ local: boolean;
33
+ } | null;