@kurvball/rehearse 1.14.0 → 1.16.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 (63) hide show
  1. package/dist/commands/announce.js +2 -2
  2. package/dist/commands/clean.js +6 -3
  3. package/dist/commands/compare.js +6 -1
  4. package/dist/commands/drive.js +49 -13
  5. package/dist/commands/init.js +1 -1
  6. package/dist/commands/run.js +8 -4
  7. package/dist/commands/services.d.ts +2 -0
  8. package/dist/commands/services.js +9 -1
  9. package/dist/commands/stage.js +18 -2
  10. package/dist/commands/up.js +15 -5
  11. package/dist/compare/compare.d.ts +2 -0
  12. package/dist/compare/compare.js +19 -10
  13. package/dist/detect/detect.js +4 -0
  14. package/dist/detect/index.d.ts +1 -0
  15. package/dist/detect/index.js +1 -0
  16. package/dist/detect/keys.d.ts +16 -0
  17. package/dist/detect/keys.js +141 -0
  18. package/dist/detect/write.d.ts +2 -0
  19. package/dist/detect/write.js +20 -1
  20. package/dist/drive/open.js +20 -9
  21. package/dist/drive/state.d.ts +1 -0
  22. package/dist/git/checkout.d.ts +6 -0
  23. package/dist/git/checkout.js +28 -19
  24. package/dist/git/index.d.ts +3 -2
  25. package/dist/git/index.js +3 -2
  26. package/dist/kinds/flow/kind.js +2 -2
  27. package/dist/manifest/index.d.ts +2 -1
  28. package/dist/manifest/index.js +1 -0
  29. package/dist/manifest/load.js +21 -0
  30. package/dist/manifest/order.d.ts +8 -0
  31. package/dist/manifest/order.js +53 -0
  32. package/dist/manifest/types.d.ts +15 -0
  33. package/dist/repositories/copies.d.ts +16 -0
  34. package/dist/repositories/copies.js +132 -0
  35. package/dist/repositories/index.d.ts +1 -0
  36. package/dist/repositories/index.js +1 -0
  37. package/dist/run/cache.d.ts +2 -1
  38. package/dist/run/cache.js +6 -3
  39. package/dist/run/index.d.ts +1 -1
  40. package/dist/run/index.js +1 -0
  41. package/dist/run/observation.d.ts +4 -0
  42. package/dist/run/observation.js +5 -1
  43. package/dist/run/session.d.ts +3 -1
  44. package/dist/run/session.js +32 -20
  45. package/dist/services/index.d.ts +2 -2
  46. package/dist/services/index.js +2 -2
  47. package/dist/services/registry.d.ts +1 -0
  48. package/dist/services/service.d.ts +4 -0
  49. package/dist/services/service.js +24 -8
  50. package/dist/stage/api.d.ts +2 -0
  51. package/dist/stage/api.js +4 -0
  52. package/dist/stage/sending.d.ts +2 -1
  53. package/dist/stage/sending.js +12 -5
  54. package/dist/stage/server.d.ts +2 -0
  55. package/dist/stage/server.js +14 -1
  56. package/llms.txt +5 -5
  57. package/package.json +2 -2
  58. package/schema/v1/common.schema.json +22 -0
  59. package/schema/v1/init.schema.json +2 -1
  60. package/schema/v1/manifest.schema.json +30 -0
  61. package/schema/v1/samples/manifest.yaml +8 -0
  62. package/schema/v1/services.schema.json +8 -0
  63. package/skill/rehearse/SKILL.md +4 -0
@@ -0,0 +1,141 @@
1
+ import path from 'node:path';
2
+ import { readText, within } from './repository.js';
3
+ const ENV_NAME = '[A-Z][A-Z0-9_]*';
4
+ const WITHOUT_A_FALLBACK = '(?!\\s*(?:\\?\\?|\\|\\||\\?(?!\\.)|=(?!=)))';
5
+ const READS = [
6
+ new RegExp(`process\\.env\\.(${ENV_NAME})\\b${WITHOUT_A_FALLBACK}`, 'g'),
7
+ new RegExp(`process\\.env\\[\\s*['"\`](${ENV_NAME})['"\`]\\s*\\]${WITHOUT_A_FALLBACK}`, 'g'),
8
+ new RegExp(`(?:import\\.meta|Bun)\\.env\\.(${ENV_NAME})\\b${WITHOUT_A_FALLBACK}`, 'g'),
9
+ new RegExp(`Deno\\.env\\.get\\(\\s*['"\`](${ENV_NAME})['"\`]\\s*\\)${WITHOUT_A_FALLBACK}`, 'g'),
10
+ ];
11
+ const TAKEN_APART = /\{([^{}]*)\}\s*=\s*process\.env\b/g;
12
+ const TAKEN_WITHOUT_A_DEFAULT = new RegExp(`^\\s*(${ENV_NAME})\\s*(?::\\s*[A-Za-z_$][\\w$]*\\s*)?$`);
13
+ const SET_IN_AN_EXAMPLE = new RegExp(`^\\s*(?:export\\s+)?(${ENV_NAME})\\s*=`, 'gm');
14
+ const AN_EXAMPLE_ENV_FILE = /^\.env(?:\.[\w-]+)?\.(?:example|sample|template)$/;
15
+ const NOT_THE_APP = /^(?:scripts|tools|docs|bench|benchmarks|playwright|cypress|\.[^/]+)\/|^[^/]+\.config\.[^/]+$|(?:^|\/)(?:test|tests|__tests__|__mocks__|fixtures|e2e|examples)\/|\.(?:test|spec|stories)\.[^/]+$/;
16
+ const READ_AS_CODE = /\.(?:[cm]?[jt]s|tsx|jsx|astro|vue|svelte)$/;
17
+ const BLOCK_COMMENT = /(^|[\s;{}(),])\/\*[\s\S]*?\*\//gm;
18
+ const LINE_COMMENT = /(^|[\s;{}(),])\/\/.*$/gm;
19
+ const SOURCES_READ = 400;
20
+ const LAST_WORD_OF_A_SECRET = new Set([
21
+ 'KEY',
22
+ 'SECRET',
23
+ 'TOKEN',
24
+ 'PASSWORD',
25
+ 'PASSWD',
26
+ 'PASS',
27
+ 'CREDENTIAL',
28
+ 'CREDENTIALS',
29
+ ]);
30
+ const MEANT_TO_BE_SEEN = new Set(['PUBLIC', 'PUBLISHABLE']);
31
+ const A_KEY_THAT_NAMES_DATA = new Set([
32
+ 'SORT',
33
+ 'PARTITION',
34
+ 'PRIMARY',
35
+ 'FOREIGN',
36
+ 'IDEMPOTENCY',
37
+ 'DEDUP',
38
+ 'DEDUPE',
39
+ 'CACHE',
40
+ 'HASH',
41
+ 'ROUTING',
42
+ 'LOCK',
43
+ 'QUEUE',
44
+ 'OBJECT',
45
+ 'BUCKET',
46
+ 'STORAGE',
47
+ 'FILE',
48
+ 'INDEX',
49
+ 'LOOKUP',
50
+ 'SHARD',
51
+ 'TABLE',
52
+ 'ROW',
53
+ 'COLUMN',
54
+ 'NAMESPACE',
55
+ ]);
56
+ const and = (items) => items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
57
+ export function looksSecret(env) {
58
+ const words = env.split('_').filter(Boolean);
59
+ const last = words.at(-1) ?? '';
60
+ if (!LAST_WORD_OF_A_SECRET.has(last) || words.some((w) => MEANT_TO_BE_SEEN.has(w)))
61
+ return false;
62
+ return !(last === 'KEY' && A_KEY_THAT_NAMES_DATA.has(words.at(-2) ?? ''));
63
+ }
64
+ export const keyNameOf = (env) => env
65
+ .toLowerCase()
66
+ .replace(/_+/g, '-')
67
+ .replace(/^-+|-+$/g, '');
68
+ function namesRead(code) {
69
+ const text = code.replace(BLOCK_COMMENT, '$1').replace(LINE_COMMENT, '$1');
70
+ const names = READS.flatMap((re) => [...text.matchAll(re)].map((m) => m[1]));
71
+ for (const m of text.matchAll(TAKEN_APART))
72
+ for (const part of m[1].split(',')) {
73
+ const name = TAKEN_WITHOUT_A_DEFAULT.exec(part)?.[1];
74
+ if (name)
75
+ names.push(name);
76
+ }
77
+ return names;
78
+ }
79
+ const namesSetIn = (text) => [...text.matchAll(SET_IN_AN_EXAMPLE)].map((m) => m[1]);
80
+ function filesOf(repo, s) {
81
+ const dir = s.pkg.dir;
82
+ const others = repo.packages.map((p) => p.dir).filter((d) => d !== dir && within(dir, d));
83
+ return repo.files
84
+ .filter((f) => within(dir, f) && !others.some((d) => within(d, f)))
85
+ .map((f) => (dir ? f.slice(dir.length + 1) : f))
86
+ .filter((f) => !NOT_THE_APP.test(f));
87
+ }
88
+ function seenBy(repo, s) {
89
+ const inRepo = (f) => (s.pkg.dir ? `${s.pkg.dir}/${f}` : f);
90
+ const files = filesOf(repo, s);
91
+ const out = [];
92
+ for (const file of files.filter((f) => READ_AS_CODE.test(f)).slice(0, SOURCES_READ)) {
93
+ const text = readText(path.join(repo.root, inRepo(file)));
94
+ if (text !== null)
95
+ for (const env of namesRead(text))
96
+ out.push({ env, from: inRepo(file), onlyNamed: false, service: s.name });
97
+ }
98
+ for (const file of files.filter((f) => AN_EXAMPLE_ENV_FILE.test(f))) {
99
+ const text = readText(path.join(repo.root, inRepo(file)));
100
+ if (text !== null)
101
+ for (const env of namesSetIn(text))
102
+ out.push({ env, from: inRepo(file), onlyNamed: true, service: s.name });
103
+ }
104
+ return out.filter((x) => looksSecret(x.env) && !(x.env in s.env));
105
+ }
106
+ export function keysOf(repo, services) {
107
+ const byEnv = new Map();
108
+ for (const seen of services.flatMap((s) => seenBy(repo, s))) {
109
+ const known = byEnv.get(seen.env);
110
+ if (!known)
111
+ byEnv.set(seen.env, {
112
+ name: keyNameOf(seen.env),
113
+ env: seen.env,
114
+ from: seen.from,
115
+ onlyNamed: seen.onlyNamed,
116
+ services: [seen.service],
117
+ });
118
+ else if (!known.services.includes(seen.service))
119
+ known.services.push(seen.service);
120
+ }
121
+ const keys = [...byEnv.values()].sort((a, b) => (a.env < b.env ? -1 : a.env > b.env ? 1 : 0));
122
+ const taken = new Set();
123
+ for (const k of keys) {
124
+ let name = k.name;
125
+ for (let n = 2; taken.has(name); n += 1)
126
+ name = `${k.name}-${n}`;
127
+ k.name = name;
128
+ taken.add(name);
129
+ }
130
+ const findings = keys.map((k) => ({
131
+ kind: 'key',
132
+ name: k.name,
133
+ from: k.from,
134
+ written: true,
135
+ why: k.onlyNamed
136
+ ? `${k.env}, which ${k.from} names for ${and(k.services)}`
137
+ : `${k.env}, which ${and(k.services)} ${k.services.length === 1 ? 'reads' : 'read'}`,
138
+ next: `Keep it on this computer with rehearse keys add ${k.name}, or say where it is with from: op://…`,
139
+ }));
140
+ return { keys, findings };
141
+ }
@@ -1,3 +1,4 @@
1
+ import type { DetectedKey } from './keys.ts';
1
2
  import type { Blocks } from './scenarios.ts';
2
3
  import type { Service } from './services.ts';
3
4
  export interface Plan {
@@ -10,6 +11,7 @@ export interface Plan {
10
11
  from: string[];
11
12
  } | null;
12
13
  services: readonly Service[];
14
+ keys: readonly DetectedKey[];
13
15
  blocks: Blocks;
14
16
  prefix: string;
15
17
  }
@@ -55,10 +55,28 @@ function services(plan) {
55
55
  for (const s of plan.services) {
56
56
  const cwd = joined(plan.prefix, s.pkg.dir);
57
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)}`)] : []));
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)}`)] : []), ...keysGivenTo(plan, s));
59
59
  }
60
60
  return `${lines.join('\n')}\n`;
61
61
  }
62
+ function keysGivenTo(plan, s) {
63
+ const given = plan.keys.filter((k) => k.services.includes(s.name));
64
+ return given.length ? [' keys:', ...given.map((k) => ` ${k.env}: ${scalar(k.name)}`)] : [];
65
+ }
66
+ function keys(plan) {
67
+ if (plan.keys.length === 0)
68
+ return null;
69
+ return [
70
+ '# The keys services get as they start, by name: where each comes from, never its value.',
71
+ '# None says where it is yet: keep each with rehearse keys add <key>, or give it from: op://vault/item/field.',
72
+ 'keys:',
73
+ ...plan.keys.flatMap((k) => [
74
+ ` # ${k.onlyNamed ? 'Named' : 'Read'} in ${printable(k.from)}.`,
75
+ ` ${scalar(k.name)}:`,
76
+ ]),
77
+ '',
78
+ ].join('\n');
79
+ }
62
80
  function scenarios(plan) {
63
81
  const b = plan.blocks;
64
82
  if (!b.pieces && !b.flows && !b.calls && !b.files)
@@ -107,6 +125,7 @@ export function manifestText(plan) {
107
125
  base(plan),
108
126
  prepare(plan),
109
127
  services(plan),
128
+ ...[keys(plan)].filter((block) => block !== null),
110
129
  commented(STARTER_BLOCKS.people),
111
130
  commented(STARTER_BLOCKS.worlds),
112
131
  commented(STARTER_BLOCKS.standins),
@@ -1,10 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { knowKeys } from '../keys/index.js';
3
- import { fill } from '../manifest/index.js';
3
+ import { fill, withWhatTheyName } from '../manifest/index.js';
4
4
  import { scrub, signIn } from '../people/index.js';
5
5
  import { startPieceServer } from '../kinds/index.js';
6
6
  import { applyWorld, baseVars } from '../run/index.js';
7
7
  import { bringDown, bringUp, runningServices, stateDir } from '../services/index.js';
8
+ import { copiesFor, rootsOf } from '../repositories/index.js';
8
9
  import { readScenarios } from '../scenarios/index.js';
9
10
  import { calm, contextFor, errorsOf, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
10
11
  import { noteSecretsOn, SECRET_AUTOCOMPLETE } from './secrets.js';
@@ -53,17 +54,27 @@ export async function openPage(m, checkout, o, showing = {}) {
53
54
  else {
54
55
  if (o.world)
55
56
  await applyWorld(m, o.world, 'before', checkout, baseVars(m, checkout, running));
56
- mine = await bringUp(m, svc, checkout, {
57
- world: o.world,
58
- real: new Set(),
59
- vars: baseVars(m, checkout, running),
60
- ...(showing.progress && { progress: showing.progress }),
61
- });
62
- started.push(mine);
63
- running = [...running, mine];
57
+ const roots = rootsOf(await copiesFor(m, {}, checkout, showing.progress ?? (() => undefined)));
58
+ for (const named of withWhatTheyName(m, [svc.name])) {
59
+ if (running.some((r) => r.name === named))
60
+ continue;
61
+ const r = await bringUp(m, m.services[named], checkout, {
62
+ world: o.world,
63
+ real: new Set(),
64
+ vars: baseVars(m, checkout, running),
65
+ roots,
66
+ ...(showing.progress && { progress: showing.progress }),
67
+ });
68
+ started.push(r);
69
+ running = [...running, r];
70
+ if (named === svc.name)
71
+ mine = r;
72
+ }
64
73
  if (o.world)
65
74
  await applyWorld(m, o.world, 'add', checkout, baseVars(m, checkout, running));
66
75
  }
76
+ if (!mine)
77
+ throw new Error(`${svc.name} didn't come up.`);
67
78
  if (!mine.url)
68
79
  throw new Error(`${svc.name} has no URL to open.`);
69
80
  url = new URL(o.start ?? '/', mine.url).href;
@@ -6,6 +6,7 @@ export interface Driving {
6
6
  pid?: number;
7
7
  secret?: string;
8
8
  started?: boolean;
9
+ alsoStarted?: string[];
9
10
  since: string;
10
11
  }
11
12
  export declare function readDriving(manifestDir: string): Driving | null;
@@ -10,7 +10,13 @@ export type Tree = {
10
10
  repo: string;
11
11
  commit: string;
12
12
  };
13
+ export declare function folderNamed(given: string, cwd?: string): string | null;
13
14
  export declare function locate(repo: string, given: string, cwd?: string): Tree;
15
+ export declare function preparedOnce(dir: string, how: {
16
+ prepare: string | null;
17
+ seed: boolean;
18
+ given: string;
19
+ }, progress: (line: string) => void): Promise<void>;
14
20
  export declare function checkoutFor(m: Manifest, repo: string, given: string, progress: (line: string) => void, keep?: readonly string[], cwd?: string): Promise<{
15
21
  path: string;
16
22
  ref: string | null;
@@ -33,18 +33,39 @@ export function overlay(m, checkout) {
33
33
  }
34
34
  }
35
35
  const NAMED_AS_A_FOLDER = /^(?:\.{1,2}(?:\/|$)|\/|~\/)/;
36
+ export function folderNamed(given, cwd = process.cwd()) {
37
+ if (!NAMED_AS_A_FOLDER.test(given))
38
+ return null;
39
+ const asPath = path.resolve(cwd, given.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
40
+ if (!existsSync(asPath) || !statSync(asPath).isDirectory())
41
+ throw new RehearseError('no_checkout', `There is no checkout at ${asPath}.`);
42
+ return topOf(asPath) ?? asPath;
43
+ }
36
44
  export function locate(repo, given, cwd = process.cwd()) {
37
- if (NAMED_AS_A_FOLDER.test(given)) {
38
- const asPath = path.resolve(cwd, given.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
39
- if (!existsSync(asPath) || !statSync(asPath).isDirectory())
40
- throw new RehearseError('no_checkout', `There is no checkout at ${asPath}.`);
41
- return { folder: topOf(asPath) ?? asPath };
42
- }
45
+ const folder = folderNamed(given, cwd);
46
+ if (folder !== null)
47
+ return { folder };
43
48
  const commit = commitOf(repo, given);
44
49
  if (!commit)
45
50
  throw new RehearseError('git', `${given} isn't a commit Rehearse can find in ${repo}.${existsSync(path.resolve(cwd, given)) ? ` To mean the folder, write ./${given}.` : ''}`);
46
51
  return { repo: topOf(repo) ?? repo, commit };
47
52
  }
53
+ export async function preparedOnce(dir, how, progress) {
54
+ const { prepare, given } = how;
55
+ if (!prepare || existsSync(preparedMark(dir)))
56
+ return;
57
+ const seeded = how.seed ? seedDependencies(dir, progress) : [];
58
+ progress(`Preparing ${dir}: ${prepare}`);
59
+ let ran = await sh(prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
60
+ if (ran.code !== 0 && seeded.length > 0) {
61
+ progress(`Preparing ${dir} again, without the seeded dependencies: ${prepare}`);
62
+ unseed(seeded);
63
+ ran = await sh(prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
64
+ }
65
+ if (ran.code !== 0)
66
+ throw new RehearseError('prepare', `Preparing ${given} failed (${prepare}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
67
+ writeFileSync(preparedMark(dir), `${new Date().toISOString()}\n`);
68
+ }
48
69
  export async function checkoutFor(m, repo, given, progress, keep = [], cwd = process.cwd()) {
49
70
  const found = locate(repo, given, cwd);
50
71
  if ('folder' in found)
@@ -57,19 +78,7 @@ export async function checkoutFor(m, repo, given, progress, keep = [], cwd = pro
57
78
  gitOr(repo, ['worktree', 'prune']);
58
79
  git(repo, ['worktree', 'add', '--detach', dir, commit]);
59
80
  }
60
- if (m.prepare && !existsSync(preparedMark(dir))) {
61
- const seeded = m.seed ? seedDependencies(dir, progress) : [];
62
- progress(`Preparing ${dir}: ${m.prepare}`);
63
- let ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
64
- if (ran.code !== 0 && seeded.length > 0) {
65
- progress(`Preparing ${dir} again, without the seeded dependencies: ${m.prepare}`);
66
- unseed(seeded);
67
- ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
68
- }
69
- if (ran.code !== 0)
70
- throw new RehearseError('prepare', `Preparing ${given} failed (${m.prepare}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
71
- writeFileSync(preparedMark(dir), `${new Date().toISOString()}\n`);
72
- }
81
+ await preparedOnce(dir, { prepare: m.prepare, seed: m.seed, given }, progress);
73
82
  const now = new Date();
74
83
  utimesSync(dir, now, now);
75
84
  evict(m, repo, [dir, ...keep]);
@@ -1,2 +1,3 @@
1
- export { checkoutFor, evict, infoOf, locate, overlay, type Tree } from './checkout.ts';
2
- export { commitOf, gitOr, topOf } from './git.ts';
1
+ export { checkoutFor, evict, folderNamed, infoOf, locate, overlay, preparedOnce, type Tree, } from './checkout.ts';
2
+ export { commitOf, git, gitOr, isDirty, topOf } from './git.ts';
3
+ export { preparedMark } from './seed.ts';
package/dist/git/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export { checkoutFor, evict, infoOf, locate, overlay } from './checkout.js';
2
- export { commitOf, gitOr, topOf } from './git.js';
1
+ export { checkoutFor, evict, folderNamed, infoOf, locate, overlay, preparedOnce, } from './checkout.js';
2
+ export { commitOf, git, gitOr, isDirty, topOf } from './git.js';
3
+ export { preparedMark } from './seed.js';
@@ -10,7 +10,7 @@ import { readScenarios, registerReader } from '../../scenarios/index.js';
10
10
  import { validate } from '../../schema.js';
11
11
  import { broken, registerRunner } from '../kind.js';
12
12
  import { startPieceServer } from '../piece/server.js';
13
- import { envOf, handoverSettled, restart, restartable, stateDir, } from '../../services/index.js';
13
+ import { cwdOf, envOf, handoverSettled, restart, restartable, stateDir, } from '../../services/index.js';
14
14
  import { applyWorld } from '../../worlds/index.js';
15
15
  import { defaultExportOf, LiteralError } from './literal.js';
16
16
  const refuse = (says, line) => {
@@ -95,7 +95,7 @@ async function throughDriver(s, ctx) {
95
95
  const m = ctx.manifest;
96
96
  const svc = m.services[s.service];
97
97
  const running = ctx.running.find((r) => r.name === svc.name);
98
- const cwd = svc.cwd ? path.resolve(ctx.checkout, svc.cwd) : ctx.checkout;
98
+ const cwd = cwdOf(svc, running);
99
99
  const env = envOf(m, running);
100
100
  const drive = async (argv) => {
101
101
  const ran = await sh(`${svc.drive} ${argv.map(quote).join(' ')} --json`, { cwd, env, timeoutMs: 60_000 });
@@ -1,5 +1,6 @@
1
1
  export { fill, fillEnv, placeholdersIn } from './fill.ts';
2
2
  export { STARTER, STARTER_BLOCKS, STARTER_HEAD } from './init.ts';
3
+ export { servicesNamedBy, upOrder, withWhatTheyName } from './order.ts';
3
4
  export { findManifest, hashOf, INERT_BY_DEFAULT, loadManifest, MANIFEST_FILE, manifestFrom } from './load.ts';
4
- export { KIND_BLOCK, KINDS, type Key, type Kind, type Manifest, type PathEntry, type Person, type Real, type Service, type Standin, type World, } from './types.ts';
5
+ export { KIND_BLOCK, KINDS, type Key, type Kind, type Manifest, type PathEntry, type Person, type Real, type Repository, type Service, type Standin, type World, } from './types.ts';
5
6
  export { readYaml } from './yaml.ts';
@@ -1,5 +1,6 @@
1
1
  export { fill, fillEnv, placeholdersIn } from './fill.js';
2
2
  export { STARTER, STARTER_BLOCKS, STARTER_HEAD } from './init.js';
3
+ export { servicesNamedBy, upOrder, withWhatTheyName } from './order.js';
3
4
  export { findManifest, hashOf, INERT_BY_DEFAULT, loadManifest, MANIFEST_FILE, manifestFrom } from './load.js';
4
5
  export { KIND_BLOCK, KINDS, } from './types.js';
5
6
  export { readYaml } from './yaml.js';
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { RehearseError } from '../errors.js';
5
5
  import { validate } from '../schema.js';
6
+ import { NamedInACircle, upOrder } from './order.js';
6
7
  import { readYaml } from './yaml.js';
7
8
  export const INERT_BY_DEFAULT = [
8
9
  '.changeset/*.md',
@@ -75,8 +76,16 @@ function serviceOf(name, s) {
75
76
  isolate: s.isolate ?? null,
76
77
  drive: s.drive ?? null,
77
78
  keys: s.keys ?? {},
79
+ repository: s.repository ?? null,
78
80
  };
79
81
  }
82
+ const AN_ADDRESS = /^(?:[a-z][a-z0-9+.-]*:\/\/|[\w.-]+@[\w.-]+:|[\w-]+(?:\.[\w-]+)+:)/i;
83
+ function repositoryOf(dir, name, r) {
84
+ const from = AN_ADDRESS.test(r.from)
85
+ ? r.from
86
+ : path.resolve(dir, r.from.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
87
+ return { name, from, base: r.base ?? null, prepare: r.prepare ?? null };
88
+ }
80
89
  function keyOf(name, k) {
81
90
  if (k === null)
82
91
  return { name, from: null, find: null };
@@ -150,6 +159,9 @@ function checkWhatTheSchemaCant(m) {
150
159
  };
151
160
  defaults('person', Object.values(m.people), 'people');
152
161
  defaults('world', Object.values(m.worlds), 'worlds');
162
+ for (const s of Object.values(m.services))
163
+ if (s.repository !== null)
164
+ named('The repository', s.repository, Object.keys(m.repositories), ['services', s.name, 'repository']);
153
165
  for (const s of Object.values(m.services))
154
166
  for (const [env, key] of Object.entries(s.keys)) {
155
167
  named('The key', key, Object.keys(m.keys), ['services', s.name, 'keys', env]);
@@ -162,6 +174,14 @@ function checkWhatTheSchemaCant(m) {
162
174
  if (alsoFrom)
163
175
  refuse(m.file, at(['services', s.name, 'keys', env]), `${s.name} gets ${env} from both ${alsoFrom.includes(' ') || alsoFrom === 'Rehearse' ? alsoFrom : `the stand-in ${alsoFrom}`} and its keys: give it one of them.`);
164
176
  }
177
+ try {
178
+ upOrder(m);
179
+ }
180
+ catch (error) {
181
+ if (!(error instanceof NamedInACircle))
182
+ throw error;
183
+ refuse(m.file, at(['services', error.circle[0]]), error.message);
184
+ }
165
185
  for (const [i, rule] of [...m.setAside.keys, ...m.setAside.values].entries()) {
166
186
  try {
167
187
  void new RegExp(rule);
@@ -249,6 +269,7 @@ export function manifestFrom(text, file) {
249
269
  affected: { graph: raw.affected?.graph ?? null, inert: raw.affected?.inert ?? [...INERT_BY_DEFAULT] },
250
270
  budget: { services: raw.budget?.services ?? 1, checkouts: raw.budget?.checkouts ?? 3 },
251
271
  keys: Object.fromEntries(Object.entries(raw.keys ?? {}).map(([n, k]) => [n, keyOf(n, k)])),
272
+ repositories: Object.fromEntries(Object.entries(raw.repositories ?? {}).map(([n, r]) => [n, repositoryOf(dir, n, r)])),
252
273
  lineOf: (at, key) => read.lineOf(at, key),
253
274
  };
254
275
  checkWhatTheSchemaCant(m);
@@ -0,0 +1,8 @@
1
+ import type { Manifest, Service } from './types.ts';
2
+ export declare function servicesNamedBy(m: Manifest, s: Service): string[];
3
+ export declare class NamedInACircle extends Error {
4
+ readonly circle: readonly string[];
5
+ constructor(circle: readonly string[]);
6
+ }
7
+ export declare const upOrder: (m: Manifest) => string[];
8
+ export declare const withWhatTheyName: (m: Manifest, names: Iterable<string>) => string[];
@@ -0,0 +1,53 @@
1
+ import { placeholdersIn } from './fill.js';
2
+ const ANOTHERS_ADDRESS = /^([A-Za-z_][A-Za-z0-9_-]*)_(?:url|port)$/;
3
+ const serviceNamed = (m, name) => Object.hasOwn(m.services, name) ? m.services[name] : undefined;
4
+ function textsOf(m, s) {
5
+ const standins = Object.values(m.standins).filter((x) => x.services === null || x.services.includes(s.name));
6
+ return [
7
+ s.up,
8
+ s.url,
9
+ s.down,
10
+ ...(s.ready === null ? [] : Object.values(s.ready)),
11
+ ...Object.values(s.env),
12
+ ...standins.flatMap((x) => [...Object.values(x.env), ...Object.values(x.real?.env ?? {})]),
13
+ ].filter((t) => typeof t === 'string');
14
+ }
15
+ export function servicesNamedBy(m, s) {
16
+ const named = new Set();
17
+ for (const text of textsOf(m, s))
18
+ for (const placeholder of placeholdersIn(text)) {
19
+ const name = ANOTHERS_ADDRESS.exec(placeholder)?.[1];
20
+ if (name !== undefined && name !== s.name && serviceNamed(m, name))
21
+ named.add(name);
22
+ }
23
+ return Object.keys(m.services).filter((name) => named.has(name));
24
+ }
25
+ export class NamedInACircle extends Error {
26
+ circle;
27
+ constructor(circle) {
28
+ super(`${circle
29
+ .slice(0, -1)
30
+ .map((name, i) => `${name} names ${circle[i + 1]}'s address`)
31
+ .join(', ')}, so none of them can come up first.`);
32
+ this.circle = circle;
33
+ }
34
+ }
35
+ function dependenciesFirst(m, names) {
36
+ const order = [];
37
+ const visit = (name, path) => {
38
+ if (order.includes(name))
39
+ return;
40
+ if (path.includes(name))
41
+ throw new NamedInACircle([...path.slice(path.indexOf(name)), name]);
42
+ const s = serviceNamed(m, name);
43
+ if (s)
44
+ for (const named of servicesNamedBy(m, s))
45
+ visit(named, [...path, name]);
46
+ order.push(name);
47
+ };
48
+ for (const name of names)
49
+ visit(name, []);
50
+ return order;
51
+ }
52
+ export const upOrder = (m) => dependenciesFirst(m, Object.keys(m.services));
53
+ export const withWhatTheyName = (m, names) => dependenciesFirst(m, names);
@@ -47,6 +47,18 @@ export interface RawManifest {
47
47
  checkouts?: number;
48
48
  };
49
49
  keys?: Record<string, RawKey>;
50
+ repositories?: Record<string, RawRepository>;
51
+ }
52
+ export interface RawRepository {
53
+ from: string;
54
+ base?: string;
55
+ prepare?: string;
56
+ }
57
+ export interface Repository {
58
+ name: string;
59
+ from: string;
60
+ base: string | null;
61
+ prepare: string | null;
50
62
  }
51
63
  export type RawKey = string | null | {
52
64
  from?: string;
@@ -78,6 +90,7 @@ export interface RawService {
78
90
  };
79
91
  drive?: string;
80
92
  keys?: Record<string, string>;
93
+ repository?: string;
81
94
  }
82
95
  export type Ready = {
83
96
  http: string;
@@ -102,6 +115,7 @@ export interface Service {
102
115
  } | null;
103
116
  drive: string | null;
104
117
  keys: Record<string, string>;
118
+ repository: string | null;
105
119
  }
106
120
  export type Real = 'local' | 'stand-in' | 'real';
107
121
  export interface Step {
@@ -267,5 +281,6 @@ export interface Manifest {
267
281
  checkouts: number;
268
282
  };
269
283
  keys: Record<string, Key>;
284
+ repositories: Record<string, Repository>;
270
285
  lineOf(at: readonly string[], key?: string): number | undefined;
271
286
  }
@@ -0,0 +1,16 @@
1
+ import type { Manifest } from '../manifest/index.ts';
2
+ export interface Copy {
3
+ path: string;
4
+ ref: string | null;
5
+ commit: string | null;
6
+ dirty: boolean;
7
+ }
8
+ export type Copies = Record<string, Copy>;
9
+ export declare const repositoriesDir: (m: Manifest) => string;
10
+ export declare function copyOf(m: Manifest, name: string, given: string | null, forSet: string, progress: (line: string) => void, cwd?: string): Promise<Copy>;
11
+ export declare function evictCopies(m: Manifest, name: string): string[];
12
+ export declare function refsOf(given: readonly string[], flag: string): Record<string, string>;
13
+ export declare function refuseUnknownRepositories(m: Manifest, given: Readonly<Record<string, string>>): void;
14
+ export declare function copiesFor(m: Manifest, given: Readonly<Record<string, string>>, forSet: string, progress: (line: string) => void, cwd?: string): Promise<Copies>;
15
+ export declare const pinnedOf: (copies: Readonly<Copies>) => Record<string, string>;
16
+ export declare const rootsOf: (copies: Readonly<Copies> | undefined) => Record<string, string>;