@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
@@ -0,0 +1,233 @@
1
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
2
+ const MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
3
+ const RUNS_OTHERS = new Set([
4
+ 'turbo',
5
+ 'nx',
6
+ 'lerna',
7
+ 'concurrently',
8
+ 'npm-run-all',
9
+ 'npm-run-all2',
10
+ 'run-p',
11
+ 'run-s',
12
+ 'wireit',
13
+ 'ultra',
14
+ ]);
15
+ const WORKSPACE_FLAGS = /^(?:-r|--recursive|-F|--filter(?:=.*)?|-w|--workspace(?:=.*)?|--workspaces|-ws|--parallel)$/;
16
+ const NOT_SERVERS = new Set([
17
+ 'tsc',
18
+ 'tsup',
19
+ 'rollup',
20
+ 'esbuild',
21
+ 'webpack',
22
+ 'babel',
23
+ 'swc',
24
+ 'unbuild',
25
+ 'storybook',
26
+ 'start-storybook',
27
+ 'build-storybook',
28
+ 'vitest',
29
+ 'jest',
30
+ 'mocha',
31
+ 'eslint',
32
+ 'oxlint',
33
+ 'prettier',
34
+ 'tailwindcss',
35
+ 'postcss',
36
+ 'sass',
37
+ 'chokidar',
38
+ ]);
39
+ const NODE_RUNNERS = new Set(['node', 'tsx', 'ts-node', 'ts-node-dev', 'nodemon', 'node-dev', 'bun']);
40
+ const TAKES_A_VALUE = new Set([
41
+ '-r',
42
+ '--require',
43
+ '--import',
44
+ '--loader',
45
+ '--experimental-loader',
46
+ '-C',
47
+ '--conditions',
48
+ '--env-file',
49
+ '--watch-path',
50
+ '--tsconfig',
51
+ '-P',
52
+ '--project',
53
+ '--compiler',
54
+ '-O',
55
+ '--compiler-options',
56
+ '--title',
57
+ ]);
58
+ const NODEMON_TAKES_A_VALUE = new Set([
59
+ '-w',
60
+ '--watch',
61
+ '-e',
62
+ '--ext',
63
+ '-i',
64
+ '--ignore',
65
+ '-x',
66
+ '--exec',
67
+ '--delay',
68
+ '-d',
69
+ '--signal',
70
+ '-s',
71
+ ]);
72
+ export const FILE_LIKE = /\.(?:[cm]?[jt]s|tsx|jsx)$/;
73
+ export function wordsOf(segment) {
74
+ const words = [];
75
+ const word = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g;
76
+ for (let m = word.exec(segment); m; m = word.exec(segment))
77
+ words.push(m[1] ?? m[2] ?? m[3]);
78
+ return words;
79
+ }
80
+ export function unwrap(words) {
81
+ const env = [];
82
+ let i = 0;
83
+ for (;;) {
84
+ while (i < words.length && ASSIGNMENT.test(words[i]))
85
+ env.push(words[i++]);
86
+ const word = words[i];
87
+ if (word === 'cross-env' ||
88
+ word === 'cross-env-shell' ||
89
+ word === 'npx' ||
90
+ word === 'pnpx' ||
91
+ word === 'bunx') {
92
+ i += 1;
93
+ while (i < words.length && words[i].startsWith('-'))
94
+ i += 1;
95
+ continue;
96
+ }
97
+ if (word === 'dotenv' || word === 'env-cmd') {
98
+ const end = words.indexOf('--', i);
99
+ if (end !== -1)
100
+ i = end + 1;
101
+ else
102
+ for (i += 1; i < words.length && words[i].startsWith('-');)
103
+ i += 2;
104
+ continue;
105
+ }
106
+ if (word !== undefined && MANAGERS.has(word) && words[i + 1] === 'exec') {
107
+ i += words[i + 2] === '--' ? 3 : 2;
108
+ continue;
109
+ }
110
+ return { words: words.slice(i), env };
111
+ }
112
+ }
113
+ function entryOf(tool, rest) {
114
+ const valued = tool === 'nodemon' ? NODEMON_TAKES_A_VALUE : TAKES_A_VALUE;
115
+ for (let i = 0; i < rest.length; i += 1) {
116
+ const word = rest[i];
117
+ if (word.startsWith('-')) {
118
+ if (valued.has(word))
119
+ i += 1;
120
+ continue;
121
+ }
122
+ if ((tool === 'tsx' && word === 'watch') || (tool === 'bun' && word === 'run'))
123
+ continue;
124
+ return word;
125
+ }
126
+ return null;
127
+ }
128
+ export function segmentsOf(text) {
129
+ const segments = [];
130
+ let current = '';
131
+ let quote = null;
132
+ let together = null;
133
+ const cut = () => {
134
+ segments.push(current.trim());
135
+ current = '';
136
+ };
137
+ for (let i = 0; i < text.length; i += 1) {
138
+ const c = text[i];
139
+ if (c === '\\' && quote !== "'" && i + 1 < text.length) {
140
+ current += c + text[(i += 1)];
141
+ continue;
142
+ }
143
+ if (quote) {
144
+ if (c === quote)
145
+ quote = null;
146
+ current += c;
147
+ continue;
148
+ }
149
+ if (c === "'" || c === '"') {
150
+ quote = c;
151
+ current += c;
152
+ }
153
+ else if (text.startsWith('&&', i) || text.startsWith('||', i)) {
154
+ cut();
155
+ i += 1;
156
+ }
157
+ else if (c === ';')
158
+ cut();
159
+ else if (c === '&' && text[i - 1] !== '>' && text[i + 1] !== '>') {
160
+ together ??= '&';
161
+ cut();
162
+ }
163
+ else if (c === '|') {
164
+ together ??= '|';
165
+ cut();
166
+ }
167
+ else
168
+ current += c;
169
+ }
170
+ cut();
171
+ return { segments: segments.filter(Boolean), together };
172
+ }
173
+ const PORT_FLAGS = {
174
+ vite: ['--port'],
175
+ astro: ['--port'],
176
+ next: ['-p', '--port'],
177
+ };
178
+ function portIn(framework, words) {
179
+ const at = words.findIndex((w) => PORT_FLAGS[framework].some((f) => w === f || w.startsWith(`${f}=`)));
180
+ if (at === -1)
181
+ return null;
182
+ return words[at].includes('=') ? words[at] : `${words[at]} ${words[at + 1] ?? ''}`.trim();
183
+ }
184
+ function readFrom(scripts, script, top, depth) {
185
+ const { segments, together } = segmentsOf(scripts[script] ?? '');
186
+ if (together)
187
+ return { as: 'together', script: top, how: together };
188
+ const { words, env } = unwrap(wordsOf(segments.at(-1) ?? ''));
189
+ const [tool = '', ...rest] = words;
190
+ const first = rest[0];
191
+ if (MANAGERS.has(tool)) {
192
+ if (rest.some((w) => WORKSPACE_FLAGS.test(w)) || first === 'workspaces' || first === 'workspace')
193
+ return { as: 'others', script: top, tool: words.join(' ') };
194
+ const [named, after] = rest.filter((w) => !w.startsWith('-'));
195
+ const target = named === 'run' || named === 'run-script' ? after : named;
196
+ if (target && target !== script && target in scripts && depth < 3)
197
+ return tool === 'npm' && !rest.includes('--')
198
+ ? { as: 'handover', script: top, via: words.join(' ') }
199
+ : readFrom(scripts, target, top, depth + 1);
200
+ if (tool === 'bun' && target && FILE_LIKE.test(target))
201
+ return { as: 'node', script: top, entry: target, tool };
202
+ return { as: 'unknown', script: top, tool: words.join(' ') };
203
+ }
204
+ if (RUNS_OTHERS.has(tool))
205
+ return { as: 'others', script: top, tool };
206
+ const framework = tool === 'vite' && first !== 'build' && first !== 'optimize' && first !== 'preview'
207
+ ? 'vite'
208
+ : (tool === 'next' && (first === 'dev' || first === undefined || first.startsWith('-'))) ||
209
+ (tool === 'astro' && first === 'dev')
210
+ ? tool
211
+ : null;
212
+ if (framework) {
213
+ const port = portIn(framework, words);
214
+ return port ? { as: 'fixed', script: top, port } : { as: 'framework', framework, script: top, words };
215
+ }
216
+ if (tool === 'vite' && first === 'preview')
217
+ return { as: 'unknown', script: top, tool: 'vite preview' };
218
+ if (tool === 'webpack' && first === 'serve')
219
+ return { as: 'unknown', script: top, tool: 'webpack serve' };
220
+ if ((tool === 'next' || tool === 'astro') && first !== 'build' && first !== 'check' && first !== 'sync')
221
+ return { as: 'unknown', script: top, tool: `${tool}${first ? ` ${first}` : ''}` };
222
+ if (NODE_RUNNERS.has(tool)) {
223
+ const port = env.find((e) => e.startsWith('PORT='));
224
+ return port
225
+ ? { as: 'fixed', script: top, port }
226
+ : { as: 'node', script: top, entry: entryOf(tool, rest), tool };
227
+ }
228
+ if (NOT_SERVERS.has(tool) || tool === '' || tool === 'vite' || tool === 'next' || tool === 'astro')
229
+ return { as: 'tool' };
230
+ return { as: 'unknown', script: top, tool };
231
+ }
232
+ export const readScript = (scripts, script) => readFrom(scripts, script, script, 0);
233
+ export const quoted = (word) => /^[\w@%+=:./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
@@ -0,0 +1,16 @@
1
+ import type { Finding } from './finding.ts';
2
+ import { type Package, type Repository } from './repository.ts';
3
+ import { type Framework } from './scripts.ts';
4
+ export interface Service {
5
+ name: string;
6
+ pkg: Package;
7
+ server: Framework | 'node';
8
+ up: string;
9
+ env: Record<string, string>;
10
+ ready: string;
11
+ built: string | null;
12
+ }
13
+ export declare function servicesOf(repo: Repository): {
14
+ services: Service[];
15
+ findings: Finding[];
16
+ };
@@ -0,0 +1,171 @@
1
+ import path from 'node:path';
2
+ import { isFile, joined, readText, within, } from './repository.js';
3
+ import { FILE_LIKE, quoted, readScript } from './scripts.js';
4
+ const SCRIPTS = ['dev', 'start', 'serve', 'develop'];
5
+ const RUN = {
6
+ pnpm: (s, a) => `pnpm run ${quoted(s)}${a ? ` ${a}` : ''}`,
7
+ npm: (s, a) => `npm run ${quoted(s)}${a ? ` -- ${a}` : ''}`,
8
+ yarn: (s, a) => `yarn run ${quoted(s)}${a ? ` ${a}` : ''}`,
9
+ bun: (s, a) => `bun run ${quoted(s)}${a ? ` ${a}` : ''}`,
10
+ };
11
+ const NAMES = { vite: 'Vite', next: 'Next', astro: 'Astro' };
12
+ const READS_PORT = /process\.env\.PORT\b|process\.env\[\s*['"`]PORT['"`]\s*\]|\{[^}]*\bPORT\b[^}]*\}\s*=\s*process\.env\b|(?:Bun|import\.meta)\.env\.PORT\b|Deno\.env\.get\(\s*['"`]PORT['"`]/;
13
+ const HEALTH = /['"`](\/(?:api\/)?(?:healthz?|livez|readyz|ping))['"`]/;
14
+ const RELATIVE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
15
+ const EXTENSIONS = ['', '.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '/index.js', '/index.mjs', '/index.ts'];
16
+ const SOURCES_READ = 200;
17
+ const BY_HAND = 'Write its service by hand: an up command with {{port}} where the port goes, and port: auto.';
18
+ function resolveFile(repo, from, spec) {
19
+ const base = joined(from, spec);
20
+ const tried = [...EXTENSIONS.map((e) => base + e), base.replace(/\.([cm]?)js$/, '.$1ts')];
21
+ return tried.find((f) => !f.startsWith('..') && isFile(path.join(repo.root, f))) ?? null;
22
+ }
23
+ function sourcesFrom(repo, entry) {
24
+ const text = readText(path.join(repo.root, entry));
25
+ if (text === null)
26
+ return [];
27
+ const out = [{ file: entry, text }];
28
+ for (const m of text.matchAll(RELATIVE_IMPORT)) {
29
+ if (out.length > 20)
30
+ break;
31
+ const file = resolveFile(repo, path.posix.dirname(entry), m[1]);
32
+ const more = file && !out.some((o) => o.file === file) ? readText(path.join(repo.root, file)) : null;
33
+ if (file && more !== null)
34
+ out.push({ file, text: more });
35
+ }
36
+ return out;
37
+ }
38
+ function sourcesIn(repo, dir) {
39
+ return repo.files
40
+ .filter((f) => within(joined(dir, 'src'), f) && FILE_LIKE.test(f))
41
+ .slice(0, SOURCES_READ)
42
+ .flatMap((file) => {
43
+ const text = readText(path.join(repo.root, file));
44
+ return text === null ? [] : [{ file, text }];
45
+ });
46
+ }
47
+ function nodeServer(repo, pkg, read) {
48
+ const its = `its ${read.script} script`;
49
+ if (!read.entry)
50
+ return { why: `${its} runs ${read.tool} without a file Rehearse can read.`, next: BY_HAND };
51
+ const entry = resolveFile(repo, pkg.dir, read.entry);
52
+ const built = entry === null || repo.ignored(entry);
53
+ const canBuild = pkg.scripts.build !== undefined;
54
+ const sources = built ? (canBuild ? sourcesIn(repo, pkg.dir) : []) : sourcesFrom(repo, entry);
55
+ const reading = sources.find((s) => READS_PORT.test(s.text));
56
+ if (!reading)
57
+ return {
58
+ why: built
59
+ ? `${its} runs ${read.entry}, which is built, and ${canBuild ? 'no file in src/ reads PORT' : 'there is no build script'}, so Rehearse can't give it a free port.`
60
+ : `${its} runs ${read.entry}, which doesn't read PORT, so Rehearse can't give it a free port.`,
61
+ next: 'Make it listen on process.env.PORT, or write its service by hand with {{port}} where the port goes.',
62
+ };
63
+ const health = [reading, ...sources].map((s) => HEALTH.exec(s.text)?.[1]).find(Boolean) ?? '/';
64
+ const manager = repo.managerOf(pkg.dir);
65
+ return {
66
+ service: {
67
+ pkg,
68
+ server: 'node',
69
+ up: RUN[manager](read.script, ''),
70
+ env: { PORT: '{{port}}' },
71
+ ready: `http://127.0.0.1:{{port}}${health}`,
72
+ built: built ? joined(pkg.dir, read.entry) : null,
73
+ },
74
+ what: `a Node server that reads PORT${built ? ', built first' : ''}, on a free port`,
75
+ };
76
+ }
77
+ function frameworkServer(repo, pkg, read) {
78
+ const { framework, script, words } = read;
79
+ const manager = repo.managerOf(pkg.dir);
80
+ const more = [
81
+ ...(framework === 'vite' && !words.includes('--strictPort') ? ['--strictPort'] : []),
82
+ ...(framework !== 'next' && !words.some((w) => w === '--host' || w.startsWith('--host='))
83
+ ? ['--host', '127.0.0.1']
84
+ : []),
85
+ ];
86
+ const up = RUN[manager](script, [framework === 'next' ? '-p' : '--port', '{{port}}', ...more].join(' '));
87
+ return {
88
+ service: { pkg, server: framework, up, env: {}, ready: 'http://127.0.0.1:{{port}}/', built: null },
89
+ what: `${NAMES[framework]}'s dev server, on a free port`,
90
+ };
91
+ }
92
+ function left(read) {
93
+ const its = `its ${read.script} script`;
94
+ switch (read.as) {
95
+ case 'others':
96
+ return {
97
+ why: `${its} runs ${read.tool}, which starts other packages' scripts; Rehearse brings each app up as a service of its own.`,
98
+ };
99
+ case 'unknown':
100
+ return {
101
+ why: `${its} runs ${read.tool}, and Rehearse can't tell how that takes a port.`,
102
+ next: BY_HAND,
103
+ };
104
+ case 'fixed':
105
+ return {
106
+ why: `${its} fixes its port (${read.port}), so Rehearse can't give it a free one without running something else.`,
107
+ next: 'Take the port out of the script, since Rehearse gives it one, or write its service by hand.',
108
+ };
109
+ case 'together':
110
+ return {
111
+ why: read.how === '&'
112
+ ? `${its} runs commands side by side (&), and a service is one server Rehearse gives one port.`
113
+ : `${its} pipes the server's output into another command (|), so the port Rehearse adds wouldn't reach the server.`,
114
+ next: BY_HAND,
115
+ };
116
+ case 'handover':
117
+ return {
118
+ why: `${its} hands over to ${read.via}, which doesn't pass on the port Rehearse adds.`,
119
+ next: `End that call with --, as in ${read.via} --, or write its service by hand.`,
120
+ };
121
+ }
122
+ }
123
+ function seen(repo, pkg) {
124
+ for (const script of SCRIPTS.filter((s) => s in pkg.scripts)) {
125
+ const read = readScript(pkg.scripts, script);
126
+ if (read.as === 'framework')
127
+ return frameworkServer(repo, pkg, read);
128
+ if (read.as === 'node')
129
+ return nodeServer(repo, pkg, read);
130
+ if (read.as !== 'tool')
131
+ return left(read);
132
+ }
133
+ return null;
134
+ }
135
+ const safe = (word) => (word ?? '')
136
+ .replace(/^@[^/]+\//, '')
137
+ .replace(/[^A-Za-z0-9_-]+/g, '-')
138
+ .replace(/^[^A-Za-z_]+|-+$/g, '');
139
+ function nameOf(pkg, server, taken) {
140
+ const byKind = server === 'node' ? 'api' : 'web';
141
+ const tried = (pkg.dir ? [safe(path.posix.basename(pkg.dir)), safe(pkg.name), byKind] : [byKind]).filter(Boolean);
142
+ const free = tried.find((name) => !taken.has(name));
143
+ if (free)
144
+ return free;
145
+ for (let n = 2;; n += 1)
146
+ if (!taken.has(`${tried[0]}-${n}`))
147
+ return `${tried[0]}-${n}`;
148
+ }
149
+ export function servicesOf(repo) {
150
+ const services = [];
151
+ const findings = [];
152
+ for (const pkg of repo.packages) {
153
+ const found = seen(repo, pkg);
154
+ if (!found)
155
+ continue;
156
+ if ('service' in found) {
157
+ const name = nameOf(pkg, found.service.server, new Set(services.map((s) => s.name)));
158
+ services.push({ name, ...found.service });
159
+ findings.push({ kind: 'service', name, from: pkg.file, written: true, why: found.what });
160
+ }
161
+ else
162
+ findings.push({
163
+ kind: 'service',
164
+ from: pkg.file,
165
+ written: false,
166
+ why: found.why,
167
+ ...(found.next !== undefined && { next: found.next }),
168
+ });
169
+ }
170
+ return { services, findings };
171
+ }
@@ -0,0 +1,18 @@
1
+ import type { Blocks } from './scenarios.ts';
2
+ import type { Service } from './services.ts';
3
+ export interface Plan {
4
+ base: {
5
+ branch: string;
6
+ from: string;
7
+ } | null;
8
+ prepare: {
9
+ command: string;
10
+ from: string[];
11
+ } | null;
12
+ services: readonly Service[];
13
+ blocks: Blocks;
14
+ prefix: string;
15
+ }
16
+ export declare function scalar(value: string): string;
17
+ export declare const commented: (block: string) => string;
18
+ export declare function manifestText(plan: Plan): string;
@@ -0,0 +1,115 @@
1
+ import { STARTER_BLOCKS } from '../manifest/index.js';
2
+ import { escapeGlob } from '../scenarios/index.js';
3
+ import { counted, hasControl, printable } from './finding.js';
4
+ import { joined } from './repository.js';
5
+ const HEAD = `# rehearse.yaml: what this repository has, so a change can be rehearsed before it ships.
6
+ # rehearse init --detect wrote the blocks it found, each saying what from, and left the rest commented.
7
+ # Every block is optional. Reference: the docs' rehearse.yaml page.
8
+ version: 1
9
+ `;
10
+ const WHAT = {
11
+ vite: "Vite's dev server",
12
+ next: "Next's dev server",
13
+ astro: "Astro's dev server",
14
+ node: 'a Node server that reads PORT',
15
+ };
16
+ const SPECIAL = /^(?:true|false|yes|no|on|off|y|n|null|~)$/i;
17
+ const NUMBER = /^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$|^0x[\da-f]+$|^0o[0-7]+$|^[-+]?\.(?:inf|nan)$/i;
18
+ const doubleQuoted = (value) => JSON.stringify(value).replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
19
+ const singleQuoted = (value) => hasControl(value) ? doubleQuoted(value) : `'${value.replace(/'/g, "''")}'`;
20
+ export function scalar(value) {
21
+ if (hasControl(value))
22
+ return doubleQuoted(value);
23
+ const plain = /^[A-Za-z0-9_./(]/.test(value) &&
24
+ !/[\n\t]|: | #|:$|\s$/.test(value) &&
25
+ !SPECIAL.test(value) &&
26
+ !NUMBER.test(value);
27
+ return plain ? value : `'${value.replace(/'/g, "''")}'`;
28
+ }
29
+ const list = (values) => `[${values.map(singleQuoted).join(', ')}]`;
30
+ const and = (items) => items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
31
+ const explanation = (block) => block.split('\n')[0];
32
+ function commentedLine(line) {
33
+ if (line === '')
34
+ return line;
35
+ const indented = /^(\s+)#\s?(.*)$/.exec(line);
36
+ if (indented)
37
+ return `# ${indented[1]}${indented[2]}`;
38
+ return line.startsWith('#') ? line : `# ${line}`;
39
+ }
40
+ export const commented = (block) => block.split('\n').map(commentedLine).join('\n');
41
+ function base(plan) {
42
+ if (!plan.base)
43
+ return STARTER_BLOCKS.base;
44
+ return `${explanation(STARTER_BLOCKS.base)}\n# Detected from ${printable(plan.base.from)}.\nbase: ${scalar(plan.base.branch)}\n`;
45
+ }
46
+ function prepare(plan) {
47
+ if (!plan.prepare)
48
+ return STARTER_BLOCKS.prepare;
49
+ return `${explanation(STARTER_BLOCKS.prepare)}\n# Detected from ${printable(and(plan.prepare.from))}.\nprepare: ${scalar(plan.prepare.command)}\n`;
50
+ }
51
+ function services(plan) {
52
+ if (plan.services.length === 0)
53
+ return commented(STARTER_BLOCKS.services);
54
+ const lines = [explanation(STARTER_BLOCKS.services), 'services:'];
55
+ for (const s of plan.services) {
56
+ const cwd = joined(plan.prefix, s.pkg.dir);
57
+ const env = Object.entries(s.env);
58
+ lines.push(` # Detected from ${printable(s.pkg.file)}: ${WHAT[s.server]}${s.built ? ', built first' : ''}.`, ` ${s.name}:`, ` up: ${scalar(s.up)}`, ...(cwd ? [` cwd: ${scalar(cwd)}`] : []), ' port: auto', ` ready: ${scalar(s.ready)}`, ...(env.length ? [' env:', ...env.map(([k, v]) => ` ${k}: ${scalar(v)}`)] : []));
59
+ }
60
+ return `${lines.join('\n')}\n`;
61
+ }
62
+ function scenarios(plan) {
63
+ const b = plan.blocks;
64
+ if (!b.pieces && !b.flows && !b.calls && !b.files)
65
+ return commented(STARTER_BLOCKS.scenarios);
66
+ const starter = new Map(STARTER_BLOCKS.scenarios
67
+ .split('\n')
68
+ .map((line) => /^ {2}(\w+):/.exec(line))
69
+ .filter((m) => m !== null)
70
+ .map((m) => [m[1], m.input.trim()]));
71
+ const block = (kind, from, paths, settings) => {
72
+ const set = settings.filter((s) => s[1] !== null);
73
+ const globs = list(paths.map((p) => joined(escapeGlob(plan.prefix), p)));
74
+ return [
75
+ ` # Detected from ${printable(from)}.`,
76
+ ...(set.length
77
+ ? [` ${kind}:`, ` paths: ${globs}`, ...set.map(([k, v]) => ` ${k}: ${scalar(v)}`)]
78
+ : [` ${kind}: ${globs}`]),
79
+ ];
80
+ };
81
+ const left = (kind) => [` # ${starter.get(kind)}`];
82
+ const lines = [
83
+ explanation(STARTER_BLOCKS.scenarios),
84
+ 'scenarios:',
85
+ ...(b.pieces
86
+ ? block('pieces', `${counted(b.pieces.count, 'story file', 'story files')}${b.pieces.previewFile ? ` and ${b.pieces.previewFile}` : ''}`, b.pieces.paths, [['preview', b.pieces.preview]])
87
+ : left('pieces')),
88
+ ...(b.flows
89
+ ? block('flows', counted(b.flows.count, 'flow file', 'flow files'), b.flows.paths, [
90
+ ['service', b.flows.service],
91
+ ])
92
+ : left('flows')),
93
+ ...(b.calls
94
+ ? block('calls', counted(b.calls.count, '.hurl file', '.hurl files'), b.calls.paths, [
95
+ ['service', b.calls.service],
96
+ ])
97
+ : left('calls')),
98
+ ...(b.files
99
+ ? block('files', counted(b.files.count, 'file scenario', 'file scenarios'), b.files.paths, [])
100
+ : left('files')),
101
+ ];
102
+ return `${lines.join('\n')}\n`;
103
+ }
104
+ export function manifestText(plan) {
105
+ return [
106
+ HEAD,
107
+ base(plan),
108
+ prepare(plan),
109
+ services(plan),
110
+ commented(STARTER_BLOCKS.people),
111
+ commented(STARTER_BLOCKS.worlds),
112
+ commented(STARTER_BLOCKS.standins),
113
+ scenarios(plan),
114
+ ].join('\n');
115
+ }
@@ -1,5 +1,5 @@
1
1
  export { fill, fillEnv } from './fill.ts';
2
- export { STARTER } from './init.ts';
3
- export { findManifest, hashOf, loadManifest, MANIFEST_FILE, manifestFrom } from './load.ts';
2
+ export { STARTER, STARTER_BLOCKS, STARTER_HEAD } from './init.ts';
3
+ export { findManifest, hashOf, INERT_BY_DEFAULT, loadManifest, MANIFEST_FILE, manifestFrom } from './load.ts';
4
4
  export { KIND_BLOCK, KINDS, type Kind, type Manifest, type PathEntry, type Person, type Real, type Service, type Standin, type World, } from './types.ts';
5
5
  export { readYaml } from './yaml.ts';
@@ -1,5 +1,5 @@
1
1
  export { fill, fillEnv } from './fill.js';
2
- export { STARTER } from './init.js';
3
- export { findManifest, hashOf, loadManifest, MANIFEST_FILE, manifestFrom } from './load.js';
2
+ export { STARTER, STARTER_BLOCKS, STARTER_HEAD } from './init.js';
3
+ export { findManifest, hashOf, INERT_BY_DEFAULT, loadManifest, MANIFEST_FILE, manifestFrom } from './load.js';
4
4
  export { KIND_BLOCK, KINDS, } from './types.js';
5
5
  export { readYaml } from './yaml.js';
@@ -1 +1,47 @@
1
- export declare const STARTER = "# rehearse.yaml: what this repository has, so a change can be rehearsed before it ships.\n# Every block is optional. Delete what you don't have. Reference: the docs' rehearse.yaml page.\nversion: 1\n\n# The branch production runs. Comparisons use it as the base.\nbase: main\n\n# Run once in a fresh checkout of a base commit, before anything else.\n# prepare: pnpm install --frozen-lockfile --offline\n\n# What can come up. {{port}} is filled with the port; port: auto picks a free one.\nservices:\n web:\n up: pnpm dev --port {{port}}\n port: auto\n ready: http://127.0.0.1:{{port}}/\n\n# Who you can sign in as. A sign-in command prints {\"people\": {\"name\": \"token\"}}.\n# signIn: node scripts/people.mjs\npeople:\n owner:\n describe: The organisation's owner\n default: true\n\n# Named starting states. A world extends another and adds to it.\nworlds:\n empty:\n describe: Nothing but the schema\n default: true\n # one-org:\n # extends: empty\n # add: node scripts/seed.mjs one-org --url {{web_url}}\n\n# Fakes for what can't run locally, named in every result.\n# standins:\n# ai:\n# replaces: The model provider\n# by: test/fixtures/ai-fake.ts\n# env: { AI_PROVIDER: fake }\n\n# Where the scenarios are. A path starting with ./ is read beside this file; any other, from each checkout.\nscenarios:\n pieces: ['src/**/*.stories.tsx']\n flows: ['**/*.flow.yaml']\n calls: ['**/*.hurl']\n files: ['**/*.rehearse.yaml']\n";
1
+ export declare const STARTER_HEAD = "# rehearse.yaml: what this repository has, so a change can be rehearsed before it ships.\n# Every block is optional. Delete what you don't have. Reference: the docs' rehearse.yaml page.\nversion: 1\n";
2
+ export declare const STARTER_BLOCKS: {
3
+ readonly base: `# The branch production runs. Comparisons use it as the base.
4
+ base: main
5
+ `;
6
+ readonly prepare: `# Run once in a fresh checkout of a base commit, before anything else.
7
+ # prepare: pnpm install --frozen-lockfile --offline
8
+ `;
9
+ readonly services: `# What can come up. {{port}} is filled with the port; port: auto picks a free one.
10
+ services:
11
+ web:
12
+ up: pnpm dev --port {{port}}
13
+ port: auto
14
+ ready: http://127.0.0.1:{{port}}/
15
+ `;
16
+ readonly people: `# Who you can sign in as. A sign-in command prints {"people": {"name": "token"}}.
17
+ # signIn: node scripts/people.mjs
18
+ people:
19
+ owner:
20
+ describe: The organisation's owner
21
+ default: true
22
+ `;
23
+ readonly worlds: `# Named starting states. A world extends another and adds to it.
24
+ worlds:
25
+ empty:
26
+ describe: Nothing but the schema
27
+ default: true
28
+ # one-org:
29
+ # extends: empty
30
+ # add: node scripts/seed.mjs one-org --url {{web_url}}
31
+ `;
32
+ readonly standins: `# Fakes for what can't run locally, named in every result.
33
+ # standins:
34
+ # ai:
35
+ # replaces: The model provider
36
+ # by: test/fixtures/ai-fake.ts
37
+ # env: { AI_PROVIDER: fake }
38
+ `;
39
+ readonly scenarios: `# Where the scenarios are. A path starting with ./ is read beside this file; any other, from each checkout.
40
+ scenarios:
41
+ pieces: ['src/**/*.stories.tsx']
42
+ flows: ['**/*.flow.yaml']
43
+ calls: ['**/*.hurl']
44
+ files: ['**/*.rehearse.yaml']
45
+ `;
46
+ };
47
+ export declare const STARTER: string;