@kurvball/rehearse 1.9.0 → 1.11.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 (50) hide show
  1. package/README.md +3 -2
  2. package/dist/affected/affected.d.ts +1 -0
  3. package/dist/affected/affected.js +16 -6
  4. package/dist/commands/init.js +52 -7
  5. package/dist/commands/list.js +1 -0
  6. package/dist/compare/compare.js +2 -0
  7. package/dist/detect/detect.d.ts +6 -0
  8. package/dist/detect/detect.js +48 -0
  9. package/dist/detect/finding.d.ts +18 -0
  10. package/dist/detect/finding.js +4 -0
  11. package/dist/detect/globs.d.ts +10 -0
  12. package/dist/detect/globs.js +43 -0
  13. package/dist/detect/index.d.ts +2 -0
  14. package/dist/detect/index.js +2 -0
  15. package/dist/detect/lockfiles.d.ts +15 -0
  16. package/dist/detect/lockfiles.js +64 -0
  17. package/dist/detect/paths.d.ts +5 -0
  18. package/dist/detect/paths.js +39 -0
  19. package/dist/detect/pieces.d.ts +14 -0
  20. package/dist/detect/pieces.js +119 -0
  21. package/dist/detect/prepare.d.ts +14 -0
  22. package/dist/detect/prepare.js +78 -0
  23. package/dist/detect/repository.d.ts +33 -0
  24. package/dist/detect/repository.js +166 -0
  25. package/dist/detect/scenarios.d.ts +26 -0
  26. package/dist/detect/scenarios.js +170 -0
  27. package/dist/detect/scripts.d.ts +46 -0
  28. package/dist/detect/scripts.js +233 -0
  29. package/dist/detect/services.d.ts +16 -0
  30. package/dist/detect/services.js +171 -0
  31. package/dist/detect/write.d.ts +18 -0
  32. package/dist/detect/write.js +115 -0
  33. package/dist/manifest/index.d.ts +2 -2
  34. package/dist/manifest/index.js +2 -2
  35. package/dist/manifest/init.d.ts +47 -1
  36. package/dist/manifest/init.js +19 -16
  37. package/dist/manifest/load.d.ts +1 -0
  38. package/dist/manifest/load.js +14 -1
  39. package/dist/manifest/types.d.ts +2 -0
  40. package/dist/scenarios/glob.d.ts +1 -0
  41. package/dist/scenarios/glob.js +10 -3
  42. package/dist/scenarios/index.d.ts +1 -1
  43. package/dist/scenarios/index.js +1 -1
  44. package/llms.txt +1 -1
  45. package/package.json +1 -1
  46. package/schema/v1/init.schema.json +69 -1
  47. package/schema/v1/list.schema.json +7 -0
  48. package/schema/v1/manifest.schema.json +5 -0
  49. package/schema/v1/samples/init.json +46 -1
  50. 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 |
@@ -14,6 +14,7 @@ export interface Affected {
14
14
  by: 'all' | 'graph' | 'packages';
15
15
  graph: string | null;
16
16
  files: string[];
17
+ inert: string[];
17
18
  said: string | null;
18
19
  reached: Reached[];
19
20
  }
@@ -79,6 +79,11 @@ export async function affected(m, checkout, given, scenarios) {
79
79
  const files = [
80
80
  ...new Set(given.map((f) => toPosix(path.relative(checkout, path.resolve(checkout, f))))),
81
81
  ].sort();
82
+ const neverInert = new Set([
83
+ toPosix(path.relative(checkout, m.file)),
84
+ ...scenarios.map((s) => toPosix(path.relative(checkout, path.resolve(s.from === 'manifest' ? m.dir : checkout, s.file)))),
85
+ ]);
86
+ const inert = files.filter((f) => !neverInert.has(f) && matches(f, m.affected.inert));
82
87
  const pkgs = workspaceOf(checkout);
83
88
  const graph = graphCommand(m, checkout);
84
89
  let said = null;
@@ -119,7 +124,7 @@ export async function affected(m, checkout, given, scenarios) {
119
124
  why.add(`it covers ${r}${via}`);
120
125
  const p = pkgOf(r);
121
126
  if (!p) {
122
- if (!graphHolds && (!through || through === r))
127
+ if (!graphHolds && (!through || through === r) && !inert.includes(r))
123
128
  why.add(`${r} is outside every package, so it reaches every scenario`);
124
129
  return;
125
130
  }
@@ -148,15 +153,20 @@ export async function affected(m, checkout, given, scenarios) {
148
153
  reached.push({ scenario: s, reachedBy: [...why] });
149
154
  }
150
155
  const unknown = graphRead?.unknown.filter((f) => files.includes(f)) ?? [];
156
+ const howItReached = graphRead
157
+ ? unknown.length
158
+ ? `The graph doesn't hold ${unknown.join(', ')}: for ${unknown.length === 1 ? 'it' : 'those'}, Rehearse took the package and the packages that depend on it.`
159
+ : null
160
+ : [said, jsOnly].filter(Boolean).join(' ') || null;
161
+ const inertSaid = inert.length
162
+ ? `${inert.length === 1 ? `${inert[0]} is` : `${inert.length} files (${inert.join(', ')}) are`} outside every package but change no behaviour, so ${inert.length === 1 ? 'it reaches' : 'they reach'} only what covers ${inert.length === 1 ? 'it' : 'them'} or what the graph says (affected.inert).`
163
+ : null;
151
164
  return {
152
165
  by: graphRead ? 'graph' : 'packages',
153
166
  graph: graphRead ? graph : null,
154
167
  files,
155
- said: graphRead
156
- ? unknown.length
157
- ? `The graph doesn't hold ${unknown.join(', ')}: for ${unknown.length === 1 ? 'it' : 'those'}, Rehearse took the package and the packages that depend on it.`
158
- : null
159
- : [said, jsOnly].filter(Boolean).join(' ') || null,
168
+ inert,
169
+ said: [howItReached, inertSaid].filter(Boolean).join(' ') || null,
160
170
  reached,
161
171
  };
162
172
  }
@@ -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
  };
@@ -55,6 +55,7 @@ export const list = {
55
55
  by: reach.by,
56
56
  graph: reach.graph,
57
57
  files: reach.files,
58
+ ...(reach.inert.length && { inert: reach.inert }),
58
59
  said: reach.said,
59
60
  scenarios: reach.reached.map((r) => row(r.scenario, r.reachedBy)),
60
61
  refused: read.refused,
@@ -125,6 +125,8 @@ export async function compare(m, o) {
125
125
  const baseCommit = commitOf(base.path);
126
126
  const files = baseCommit ? changedFiles(head.path, baseCommit) : [];
127
127
  const reach = await affected(m, head.path, files, headScenarios);
128
+ if (reach.inert.length && reach.said)
129
+ o.progress(reach.said);
128
130
  const ids = new Set(reach.reached.map((r) => r.scenario.id));
129
131
  headScenarios = headScenarios.filter((s) => ids.has(s.id));
130
132
  const baseReach = await affected(m, base.path, files, baseScenarios);
@@ -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;