@kurvball/rehearse 0.0.0-stage → 1.2.1

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 (266) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +102 -2
  3. package/dist/affected/affected.d.ts +22 -0
  4. package/dist/affected/affected.js +162 -0
  5. package/dist/affected/index.d.ts +1 -0
  6. package/dist/affected/index.js +1 -0
  7. package/dist/args.d.ts +12 -0
  8. package/dist/args.js +42 -0
  9. package/dist/cli.d.ts +4 -0
  10. package/dist/cli.js +100 -0
  11. package/dist/commands/check.d.ts +2 -0
  12. package/dist/commands/check.js +42 -0
  13. package/dist/commands/clean.d.ts +2 -0
  14. package/dist/commands/clean.js +37 -0
  15. package/dist/commands/command.d.ts +29 -0
  16. package/dist/commands/command.js +29 -0
  17. package/dist/commands/compare.d.ts +4 -0
  18. package/dist/commands/compare.js +84 -0
  19. package/dist/commands/drive.d.ts +2 -0
  20. package/dist/commands/drive.js +244 -0
  21. package/dist/commands/index.d.ts +3 -0
  22. package/dist/commands/index.js +32 -0
  23. package/dist/commands/init.d.ts +2 -0
  24. package/dist/commands/init.js +19 -0
  25. package/dist/commands/list.d.ts +2 -0
  26. package/dist/commands/list.js +69 -0
  27. package/dist/commands/open.d.ts +2 -0
  28. package/dist/commands/open.js +60 -0
  29. package/dist/commands/people.d.ts +2 -0
  30. package/dist/commands/people.js +49 -0
  31. package/dist/commands/run.d.ts +4 -0
  32. package/dist/commands/run.js +82 -0
  33. package/dist/commands/services.d.ts +28 -0
  34. package/dist/commands/services.js +51 -0
  35. package/dist/commands/stage.d.ts +7 -0
  36. package/dist/commands/stage.js +49 -0
  37. package/dist/commands/up.d.ts +3 -0
  38. package/dist/commands/up.js +77 -0
  39. package/dist/commands/validate.d.ts +2 -0
  40. package/dist/commands/validate.js +35 -0
  41. package/dist/commands/worlds.d.ts +2 -0
  42. package/dist/commands/worlds.js +15 -0
  43. package/dist/compare/announce.d.ts +6 -0
  44. package/dist/compare/announce.js +27 -0
  45. package/dist/compare/compare.d.ts +82 -0
  46. package/dist/compare/compare.js +310 -0
  47. package/dist/compare/diff.d.ts +15 -0
  48. package/dist/compare/diff.js +105 -0
  49. package/dist/compare/index.d.ts +4 -0
  50. package/dist/compare/index.js +4 -0
  51. package/dist/compare/setaside.d.ts +29 -0
  52. package/dist/compare/setaside.js +121 -0
  53. package/dist/compare/verdict.d.ts +21 -0
  54. package/dist/compare/verdict.js +30 -0
  55. package/dist/drive/aria.d.ts +8 -0
  56. package/dist/drive/aria.js +12 -0
  57. package/dist/drive/browser.d.ts +34 -0
  58. package/dist/drive/browser.js +216 -0
  59. package/dist/drive/daemon.d.ts +1 -0
  60. package/dist/drive/daemon.js +171 -0
  61. package/dist/drive/grammar.d.ts +93 -0
  62. package/dist/drive/grammar.js +303 -0
  63. package/dist/drive/index.d.ts +4 -0
  64. package/dist/drive/index.js +4 -0
  65. package/dist/drive/names.d.ts +24 -0
  66. package/dist/drive/names.js +97 -0
  67. package/dist/drive/state.d.ts +13 -0
  68. package/dist/drive/state.js +28 -0
  69. package/dist/errors.d.ts +26 -0
  70. package/dist/errors.js +32 -0
  71. package/dist/exec.d.ts +16 -0
  72. package/dist/exec.js +43 -0
  73. package/dist/git/checkout.d.ts +11 -0
  74. package/dist/git/checkout.js +84 -0
  75. package/dist/git/git.d.ts +7 -0
  76. package/dist/git/git.js +27 -0
  77. package/dist/git/index.d.ts +2 -0
  78. package/dist/git/index.js +2 -0
  79. package/dist/index.d.ts +18 -0
  80. package/dist/index.js +15 -0
  81. package/dist/kinds/all.d.ts +4 -0
  82. package/dist/kinds/all.js +4 -0
  83. package/dist/kinds/call/check.d.ts +29 -0
  84. package/dist/kinds/call/check.js +187 -0
  85. package/dist/kinds/call/definition.d.ts +16 -0
  86. package/dist/kinds/call/definition.js +33 -0
  87. package/dist/kinds/call/hurl.d.ts +65 -0
  88. package/dist/kinds/call/hurl.js +333 -0
  89. package/dist/kinds/call/kind.d.ts +8 -0
  90. package/dist/kinds/call/kind.js +122 -0
  91. package/dist/kinds/call/send.d.ts +32 -0
  92. package/dist/kinds/call/send.js +152 -0
  93. package/dist/kinds/call/words.d.ts +22 -0
  94. package/dist/kinds/call/words.js +24 -0
  95. package/dist/kinds/file/kind.d.ts +44 -0
  96. package/dist/kinds/file/kind.js +331 -0
  97. package/dist/kinds/file/layouts.d.ts +14 -0
  98. package/dist/kinds/file/layouts.js +103 -0
  99. package/dist/kinds/flow/kind.d.ts +21 -0
  100. package/dist/kinds/flow/kind.js +401 -0
  101. package/dist/kinds/flow/literal.d.ts +8 -0
  102. package/dist/kinds/flow/literal.js +148 -0
  103. package/dist/kinds/index.d.ts +10 -0
  104. package/dist/kinds/index.js +8 -0
  105. package/dist/kinds/kind.d.ts +57 -0
  106. package/dist/kinds/kind.js +21 -0
  107. package/dist/kinds/piece/canvas.d.ts +18 -0
  108. package/dist/kinds/piece/canvas.js +165 -0
  109. package/dist/kinds/piece/conventions.d.ts +12 -0
  110. package/dist/kinds/piece/conventions.js +101 -0
  111. package/dist/kinds/piece/csf.d.ts +10 -0
  112. package/dist/kinds/piece/csf.js +304 -0
  113. package/dist/kinds/piece/kind.d.ts +12 -0
  114. package/dist/kinds/piece/kind.js +297 -0
  115. package/dist/kinds/piece/server.d.ts +23 -0
  116. package/dist/kinds/piece/server.js +236 -0
  117. package/dist/manifest/fill.d.ts +4 -0
  118. package/dist/manifest/fill.js +7 -0
  119. package/dist/manifest/index.d.ts +5 -0
  120. package/dist/manifest/index.js +5 -0
  121. package/dist/manifest/init.d.ts +1 -0
  122. package/dist/manifest/init.js +47 -0
  123. package/dist/manifest/load.d.ts +7 -0
  124. package/dist/manifest/load.js +244 -0
  125. package/dist/manifest/types.d.ts +253 -0
  126. package/dist/manifest/types.js +7 -0
  127. package/dist/manifest/yaml.d.ts +5 -0
  128. package/dist/manifest/yaml.js +47 -0
  129. package/dist/people/index.d.ts +1 -0
  130. package/dist/people/index.js +1 -0
  131. package/dist/people/people.d.ts +39 -0
  132. package/dist/people/people.js +139 -0
  133. package/dist/run/cache.d.ts +20 -0
  134. package/dist/run/cache.js +98 -0
  135. package/dist/run/index.d.ts +4 -0
  136. package/dist/run/index.js +3 -0
  137. package/dist/run/observation.d.ts +27 -0
  138. package/dist/run/observation.js +1 -0
  139. package/dist/run/session.d.ts +32 -0
  140. package/dist/run/session.js +258 -0
  141. package/dist/run/vars.d.ts +3 -0
  142. package/dist/run/vars.js +13 -0
  143. package/dist/scenarios/area.d.ts +6 -0
  144. package/dist/scenarios/area.js +37 -0
  145. package/dist/scenarios/files.d.ts +9 -0
  146. package/dist/scenarios/files.js +26 -0
  147. package/dist/scenarios/glob.d.ts +6 -0
  148. package/dist/scenarios/glob.js +106 -0
  149. package/dist/scenarios/index.d.ts +4 -0
  150. package/dist/scenarios/index.js +4 -0
  151. package/dist/scenarios/read.d.ts +18 -0
  152. package/dist/scenarios/read.js +54 -0
  153. package/dist/scenarios/scenario.d.ts +34 -0
  154. package/dist/scenarios/scenario.js +10 -0
  155. package/dist/schema.d.ts +14 -0
  156. package/dist/schema.js +122 -0
  157. package/dist/services/index.d.ts +2 -0
  158. package/dist/services/index.js +2 -0
  159. package/dist/services/registry.d.ts +23 -0
  160. package/dist/services/registry.js +49 -0
  161. package/dist/services/service.d.ts +22 -0
  162. package/dist/services/service.js +284 -0
  163. package/dist/stage/api.d.ts +28 -0
  164. package/dist/stage/api.js +206 -0
  165. package/dist/stage/client/client/api.js +11 -0
  166. package/dist/stage/client/client/index.js +1 -0
  167. package/dist/stage/client/features/canvas/call.js +65 -0
  168. package/dist/stage/client/features/canvas/context.js +1 -0
  169. package/dist/stage/client/features/canvas/file.js +36 -0
  170. package/dist/stage/client/features/canvas/flow.js +59 -0
  171. package/dist/stage/client/features/canvas/index.js +1 -0
  172. package/dist/stage/client/features/canvas/observed.js +8 -0
  173. package/dist/stage/client/features/canvas/parts.js +24 -0
  174. package/dist/stage/client/features/canvas/piece.js +31 -0
  175. package/dist/stage/client/features/canvas/reach.js +6 -0
  176. package/dist/stage/client/features/canvas/views.js +16 -0
  177. package/dist/stage/client/features/list/index.js +1 -0
  178. package/dist/stage/client/features/list/list.js +53 -0
  179. package/dist/stage/client/features/list/reach.js +10 -0
  180. package/dist/stage/client/features/scenario/heading.js +14 -0
  181. package/dist/stage/client/features/scenario/index.js +1 -0
  182. package/dist/stage/client/features/scenario/reach.js +9 -0
  183. package/dist/stage/client/features/scenario/scenario.js +145 -0
  184. package/dist/stage/client/features/try/index.js +1 -0
  185. package/dist/stage/client/features/try/reach.js +12 -0
  186. package/dist/stage/client/features/try/try.js +65 -0
  187. package/dist/stage/client/index.html +16 -0
  188. package/dist/stage/client/main.js +24 -0
  189. package/dist/stage/client/primitives/busy.js +6 -0
  190. package/dist/stage/client/primitives/focus.js +21 -0
  191. package/dist/stage/client/primitives/h.js +25 -0
  192. package/dist/stage/client/primitives/index.js +6 -0
  193. package/dist/stage/client/primitives/keyed.js +16 -0
  194. package/dist/stage/client/primitives/say.js +6 -0
  195. package/dist/stage/client/primitives/state.js +21 -0
  196. package/dist/stage/client/primitives/types.js +1 -0
  197. package/dist/stage/client/primitives/verdicts.js +8 -0
  198. package/dist/stage/client/stage.css +652 -0
  199. package/dist/stage/compared.d.ts +20 -0
  200. package/dist/stage/compared.js +58 -0
  201. package/dist/stage/files.d.ts +4 -0
  202. package/dist/stage/files.js +59 -0
  203. package/dist/stage/guard.d.ts +3 -0
  204. package/dist/stage/guard.js +20 -0
  205. package/dist/stage/http.d.ts +12 -0
  206. package/dist/stage/http.js +34 -0
  207. package/dist/stage/index.d.ts +1 -0
  208. package/dist/stage/index.js +1 -0
  209. package/dist/stage/sending.d.ts +18 -0
  210. package/dist/stage/sending.js +66 -0
  211. package/dist/stage/server.d.ts +31 -0
  212. package/dist/stage/server.js +250 -0
  213. package/dist/version.d.ts +2 -0
  214. package/dist/version.js +5 -0
  215. package/dist/worlds/define.d.ts +16 -0
  216. package/dist/worlds/define.js +45 -0
  217. package/dist/worlds/index.d.ts +2 -0
  218. package/dist/worlds/index.js +2 -0
  219. package/dist/worlds/worlds.d.ts +15 -0
  220. package/dist/worlds/worlds.js +46 -0
  221. package/llms.txt +46 -0
  222. package/package.json +84 -3
  223. package/schema/v1/announce.schema.json +28 -0
  224. package/schema/v1/check.schema.json +67 -0
  225. package/schema/v1/clean.schema.json +19 -0
  226. package/schema/v1/common.schema.json +210 -0
  227. package/schema/v1/comparison.schema.json +298 -0
  228. package/schema/v1/dependents.schema.json +30 -0
  229. package/schema/v1/drive.schema.json +112 -0
  230. package/schema/v1/error.schema.json +26 -0
  231. package/schema/v1/file-scenario.schema.json +175 -0
  232. package/schema/v1/flow.schema.json +216 -0
  233. package/schema/v1/init.schema.json +20 -0
  234. package/schema/v1/list.schema.json +70 -0
  235. package/schema/v1/manifest.schema.json +430 -0
  236. package/schema/v1/observation.schema.json +388 -0
  237. package/schema/v1/open.schema.json +14 -0
  238. package/schema/v1/people.schema.json +88 -0
  239. package/schema/v1/samples/announce.yaml +5 -0
  240. package/schema/v1/samples/check.json +13 -0
  241. package/schema/v1/samples/clean.json +1 -0
  242. package/schema/v1/samples/comparison.json +83 -0
  243. package/schema/v1/samples/dependents.json +7 -0
  244. package/schema/v1/samples/drive.json +10 -0
  245. package/schema/v1/samples/error.json +10 -0
  246. package/schema/v1/samples/file-scenario.yaml +13 -0
  247. package/schema/v1/samples/flow.yaml +13 -0
  248. package/schema/v1/samples/init.json +1 -0
  249. package/schema/v1/samples/list.json +24 -0
  250. package/schema/v1/samples/manifest.yaml +55 -0
  251. package/schema/v1/samples/observation.json +49 -0
  252. package/schema/v1/samples/open.json +6 -0
  253. package/schema/v1/samples/people.json +11 -0
  254. package/schema/v1/samples/services.json +27 -0
  255. package/schema/v1/samples/stage.json +6 -0
  256. package/schema/v1/samples/try.json +13 -0
  257. package/schema/v1/samples/up.json +16 -0
  258. package/schema/v1/samples/validate.json +7 -0
  259. package/schema/v1/samples/worlds.json +21 -0
  260. package/schema/v1/services.schema.json +72 -0
  261. package/schema/v1/stage.schema.json +14 -0
  262. package/schema/v1/try.schema.json +56 -0
  263. package/schema/v1/up.schema.json +55 -0
  264. package/schema/v1/validate.schema.json +40 -0
  265. package/schema/v1/worlds.schema.json +33 -0
  266. package/skill/rehearse/SKILL.md +148 -0
@@ -0,0 +1,4 @@
1
+ import type { ServerResponse } from 'node:http';
2
+ export declare function fileThePageMayShow(file: string, keptOrCompared: readonly string[]): string | null;
3
+ export declare function serveFile(res: ServerResponse, wanted: string, keptOrCompared: readonly string[]): void;
4
+ export declare function servePage(res: ServerResponse, pathname: string): void;
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { PACKAGE_ROOT } from '../version.js';
4
+ import { fail } from './http.js';
5
+ const CLIENT = path.join(PACKAGE_ROOT, 'dist', 'stage', 'client');
6
+ const TYPES = {
7
+ '.html': 'text/html; charset=utf-8',
8
+ '.css': 'text/css; charset=utf-8',
9
+ '.js': 'text/javascript; charset=utf-8',
10
+ '.svg': 'image/svg+xml',
11
+ '.png': 'image/png',
12
+ '.json': 'application/json; charset=utf-8',
13
+ };
14
+ const realFolder = (dir) => {
15
+ try {
16
+ return [realpathSync(dir) + path.sep];
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ };
22
+ const inGitsOwnFolder = (inside) => inside.split(path.sep).includes('.git');
23
+ export function fileThePageMayShow(file, keptOrCompared) {
24
+ let real;
25
+ try {
26
+ real = realpathSync(file);
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ const root = keptOrCompared.flatMap(realFolder).find((r) => real.startsWith(r));
32
+ if (!root || inGitsOwnFolder(real.slice(root.length)))
33
+ return null;
34
+ return statSync(real).isFile() ? real : null;
35
+ }
36
+ export function serveFile(res, wanted, keptOrCompared) {
37
+ const file = fileThePageMayShow(wanted, keptOrCompared);
38
+ if (!file)
39
+ return fail(res, 404, 'not_found', 'No such file here.');
40
+ res.writeHead(200, {
41
+ 'content-type': TYPES[path.extname(file)] ?? 'text/plain; charset=utf-8',
42
+ 'cache-control': 'no-store',
43
+ });
44
+ res.end(readFileSync(file));
45
+ }
46
+ export function servePage(res, pathname) {
47
+ const name = pathname === '/' ? 'index.html' : pathname.slice(1);
48
+ const file = path.join(CLIENT, name);
49
+ if (!file.startsWith(CLIENT + path.sep) || !existsSync(file) || !statSync(file).isFile()) {
50
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
51
+ res.end(existsSync(CLIENT) ? 'Not found\n' : 'The stage’s page isn’t built: run `pnpm build` in Rehearse.\n');
52
+ return;
53
+ }
54
+ res.writeHead(200, {
55
+ 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream',
56
+ 'cache-control': 'no-store',
57
+ });
58
+ res.end(readFileSync(file));
59
+ }
@@ -0,0 +1,3 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ export declare const STAGE_HOST = "127.0.0.1";
3
+ export declare function refusalOf(req: IncomingMessage, port: number): [number, string] | null;
@@ -0,0 +1,20 @@
1
+ export const STAGE_HOST = '127.0.0.1';
2
+ const ownHostsAt = (port) => [`${STAGE_HOST}:${port}`, `localhost:${port}`];
3
+ export function refusalOf(req, port) {
4
+ const ownHosts = ownHostsAt(port);
5
+ if (!ownHosts.includes(req.headers.host ?? ''))
6
+ return [403, 'The stage answers only at its own address.'];
7
+ const origin = req.headers.origin;
8
+ if (origin !== undefined && !ownHosts.some((h) => origin === `http://${h}`))
9
+ return [403, 'The stage answers only its own page.'];
10
+ if (req.method !== 'GET' &&
11
+ req.method !== 'HEAD' &&
12
+ !/^application\/json\b/i.test(req.headers['content-type'] ?? ''))
13
+ return [415, 'The stage takes JSON: send content-type application/json.'];
14
+ const site = req.headers['sec-fetch-site'];
15
+ const asksTheApiOrFiles = /^\/(api\/|files)/.test(req.url ?? '/');
16
+ const followsALinkToThePage = !asksTheApiOrFiles && req.method === 'GET';
17
+ if (site && site !== 'same-origin' && !followsALinkToThePage)
18
+ return [403, 'The stage answers only its own page.'];
19
+ return null;
20
+ }
@@ -0,0 +1,12 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Manifest } from '../manifest/index.ts';
3
+ export type Side = 'base' | 'head';
4
+ export type Handler = (req: IncomingMessage, url: URL) => Promise<unknown>;
5
+ export declare const json: (res: ServerResponse, status: number, body: unknown) => void;
6
+ export declare const fail: (res: ServerResponse, status: number, code: string, says: string) => void;
7
+ export declare function answer(res: ServerResponse, work: Promise<unknown>): void;
8
+ export declare function bodyOf(req: IncomingMessage): Promise<Record<string, unknown>>;
9
+ export declare const str: (v: unknown) => string | null;
10
+ export declare const sideOf: (v: unknown) => Side;
11
+ export declare function worldIn(m: Manifest, v: unknown): string | null;
12
+ export declare function personIn(m: Manifest, v: unknown): string | null;
@@ -0,0 +1,34 @@
1
+ import { RehearseError, errorText } from '../errors.js';
2
+ export const json = (res, status, body) => {
3
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
4
+ res.end(JSON.stringify(body));
5
+ };
6
+ export const fail = (res, status, code, says) => json(res, status, { v: 1, ok: false, error: { code, says } });
7
+ export function answer(res, work) {
8
+ work.then((body) => json(res, 200, body), (error) => fail(res, error instanceof RehearseError && error.code !== 'crashed' ? 400 : 500, error instanceof RehearseError ? error.code : 'crashed', errorText(error)));
9
+ }
10
+ export async function bodyOf(req) {
11
+ let text = '';
12
+ for await (const chunk of req)
13
+ text += String(chunk);
14
+ try {
15
+ return JSON.parse(text || '{}');
16
+ }
17
+ catch {
18
+ throw new RehearseError('usage', 'The stage takes JSON.');
19
+ }
20
+ }
21
+ export const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
22
+ export const sideOf = (v) => (v === 'base' ? 'base' : 'head');
23
+ export function worldIn(m, v) {
24
+ const w = str(v);
25
+ if (w !== null && !(w in m.worlds))
26
+ throw new RehearseError('no_world', `There is no world “${w}” in rehearse.yaml.`);
27
+ return w;
28
+ }
29
+ export function personIn(m, v) {
30
+ const p = str(v);
31
+ if (p !== null && !(p in m.people))
32
+ throw new RehearseError('no_person', `There is no person “${p}” in rehearse.yaml.`);
33
+ return p;
34
+ }
@@ -0,0 +1 @@
1
+ export { runningStage, startStage, type Stage } from './server.ts';
@@ -0,0 +1 @@
1
+ export { runningStage, startStage } from './server.js';
@@ -0,0 +1,18 @@
1
+ import { type Manifest } from '../manifest/index.ts';
2
+ import { type Running } from '../services/index.ts';
3
+ import type { Side } from './http.ts';
4
+ export interface SideSession {
5
+ side: Side;
6
+ checkout: string;
7
+ world: string | null;
8
+ started: Running[];
9
+ running: Running[];
10
+ tokens: Record<string, string>;
11
+ variables: Record<string, string>;
12
+ }
13
+ export interface ServicesForSending {
14
+ upOnlyOn(side: Side, world: string | null): Promise<SideSession>;
15
+ takeDown(): Promise<void>;
16
+ tokens(): Record<string, string>;
17
+ }
18
+ export declare function servicesForSending(m: Manifest, checkoutOf: (side: Side) => Promise<string>, progress: (line: string) => void): ServicesForSending;
@@ -0,0 +1,66 @@
1
+ import { RehearseError } from '../errors.js';
2
+ import { fill } from '../manifest/index.js';
3
+ import { signIn } from '../people/index.js';
4
+ import { applyWorld, baseVars } from '../run/index.js';
5
+ import { bringDown, bringUp, liveServices, makeRoom } from '../services/index.js';
6
+ export function servicesForSending(m, checkoutOf, progress) {
7
+ let session = null;
8
+ const takeDown = async () => {
9
+ const s = session;
10
+ session = null;
11
+ if (s)
12
+ for (const r of s.started.toReversed())
13
+ await bringDown(m, r, progress);
14
+ };
15
+ const upOnlyOn = async (side, world) => {
16
+ const checkout = await checkoutOf(side);
17
+ if (session && session.side === side && session.world === world)
18
+ return session;
19
+ await takeDown();
20
+ await makeRoom(m, checkout, progress);
21
+ let running = await liveServices(m, checkout);
22
+ const already = running.find((r) => (r.world ?? null) !== world);
23
+ if (already)
24
+ throw new RehearseError('service', `${already.name} is already up on the ${side} with ${already.world ? `the world ${already.world}` : 'no world'}: bring it down with rehearse down to send in ${world ? `the world ${world}` : 'no world'}.`);
25
+ const started = [];
26
+ try {
27
+ const fresh = Object.values(m.services).some((s) => !running.some((r) => r.name === s.name));
28
+ if (world && fresh)
29
+ await applyWorld(m, world, 'before', checkout, baseVars(m, checkout, running));
30
+ for (const s of Object.values(m.services)) {
31
+ if (running.some((r) => r.name === s.name))
32
+ continue;
33
+ const r = await bringUp(m, s, checkout, {
34
+ world,
35
+ real: new Set(),
36
+ vars: baseVars(m, checkout, running),
37
+ progress,
38
+ });
39
+ started.push(r);
40
+ running = [...running, r];
41
+ }
42
+ if (world && started.length)
43
+ await applyWorld(m, world, 'add', checkout, baseVars(m, checkout, running));
44
+ const vars = baseVars(m, checkout, running);
45
+ const signed = m.signIn || Object.values(m.people).some((p) => p.token)
46
+ ? await signIn(m, { cwd: checkout, env: {}, fill: (t) => fill(t, vars) })
47
+ : null;
48
+ session = {
49
+ side,
50
+ checkout,
51
+ world,
52
+ started,
53
+ running,
54
+ tokens: signed?.tokens ?? {},
55
+ variables: { ...vars, ...signed?.variables },
56
+ };
57
+ return session;
58
+ }
59
+ catch (error) {
60
+ for (const r of started.toReversed())
61
+ await bringDown(m, r, progress).catch(() => undefined);
62
+ throw error;
63
+ }
64
+ };
65
+ return { upOnlyOn, takeDown, tokens: () => session?.tokens ?? {} };
66
+ }
@@ -0,0 +1,31 @@
1
+ import { type Server } from 'node:http';
2
+ import { type Fetcher } from '../kinds/index.ts';
3
+ import type { Manifest } from '../manifest/index.ts';
4
+ import { STAGE_HOST } from './guard.ts';
5
+ import { type Side } from './http.ts';
6
+ export { STAGE_HOST };
7
+ export type { Side };
8
+ export interface StageOptions {
9
+ manifest: Manifest;
10
+ repo: string;
11
+ cwd: string;
12
+ head: string | null;
13
+ base: string | null;
14
+ port: number;
15
+ anyPort?: boolean;
16
+ progress: (line: string) => void;
17
+ }
18
+ export interface Stage {
19
+ url: string;
20
+ port: number;
21
+ server: Server;
22
+ close(): Promise<void>;
23
+ forget(): void;
24
+ }
25
+ export declare const stageFile: (m: Manifest) => string;
26
+ export declare function runningStage(m: Manifest): Promise<{
27
+ url: string;
28
+ pid: number;
29
+ } | null>;
30
+ export declare function boundTo(origins: readonly string[], refused: (origin: string) => void, fetcher?: Fetcher): Fetcher;
31
+ export declare function startStage(o: StageOptions): Promise<Stage>;
@@ -0,0 +1,250 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import path from 'node:path';
4
+ import { RehearseError, errorText } from '../errors.js';
5
+ import { checkoutFor } from '../git/index.js';
6
+ import { parseHurl, Refusal, sendFile, startPieceServer, } from '../kinds/index.js';
7
+ import { scrubDeep } from '../people/index.js';
8
+ import { readScenarios } from '../scenarios/index.js';
9
+ import { alive, stateDir } from '../services/index.js';
10
+ import { apiOf } from './api.js';
11
+ import { lastCompared } from './compared.js';
12
+ import { serveFile, servePage } from './files.js';
13
+ import { refusalOf, STAGE_HOST } from './guard.js';
14
+ import { answer, bodyOf, fail, personIn, sideOf, str, worldIn } from './http.js';
15
+ import { servicesForSending } from './sending.js';
16
+ export { STAGE_HOST };
17
+ const SHARE_ONE_SET_OF_SERVICES = ['POST /api/run', 'POST /api/compare', 'POST /api/send'];
18
+ export const stageFile = (m) => path.join(stateDir(m.dir), 'stage.json');
19
+ async function answersAsAStage(url) {
20
+ try {
21
+ const r = await fetch(new URL('/api/index', url), { signal: AbortSignal.timeout(3000) });
22
+ await r.body?.cancel();
23
+ return r.status === 200;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ export async function runningStage(m) {
30
+ let s;
31
+ try {
32
+ s = JSON.parse(readFileSync(stageFile(m), 'utf8'));
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ if (!s.url || !s.pid || !alive(s.pid))
38
+ return null;
39
+ return (await answersAsAStage(s.url)) ? { url: s.url, pid: s.pid } : null;
40
+ }
41
+ export function boundTo(origins, refused, fetcher = fetch) {
42
+ return (input, init) => {
43
+ const href = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
44
+ const origin = new URL(href).origin;
45
+ if (!origins.includes(origin)) {
46
+ refused(origin);
47
+ return Promise.reject(new Error(`not sent to ${origin}`));
48
+ }
49
+ return fetcher(input, init);
50
+ };
51
+ }
52
+ const listenAt = (server, at) => new Promise((resolve, reject) => {
53
+ const failed = (error) => reject(error);
54
+ server.once('error', failed);
55
+ server.listen(at, STAGE_HOST, () => {
56
+ server.off('error', failed);
57
+ resolve();
58
+ });
59
+ });
60
+ export async function startStage(o) {
61
+ const m = o.manifest;
62
+ const other = await runningStage(m);
63
+ if (other && other.pid !== process.pid)
64
+ throw new RehearseError('stage', `A stage already runs for this repository at ${other.url} (pid ${other.pid}). Open it, or stop it with kill ${other.pid}.`);
65
+ const head = o.head
66
+ ? await checkoutFor(m, o.repo, o.head, o.progress, [], o.cwd)
67
+ : { path: o.repo, ref: null };
68
+ let base = null;
69
+ const baseRef = o.base ?? m.base;
70
+ const baseCheckout = async () => (base ??= await checkoutFor(m, head.path, baseRef, o.progress, [head.path], o.cwd));
71
+ const checkoutOf = async (side) => (side === 'head' ? head.path : (await baseCheckout()).path);
72
+ const scenarioOn = async (side, id) => (await readScenarios(m, await checkoutOf(side))).scenarios.find((s) => s.id === id) ?? null;
73
+ const sending = servicesForSending(m, checkoutOf, o.progress);
74
+ const pieces = new Map();
75
+ const api = {
76
+ ...apiOf({
77
+ m,
78
+ asked: o,
79
+ head,
80
+ baseRef,
81
+ checkoutOf,
82
+ scenarioOn,
83
+ runs: new Map(),
84
+ compared: lastCompared(path.join(stateDir(m.dir), 'compare'), head.path, baseRef),
85
+ sending,
86
+ triesFile: path.join(stateDir(m.dir), 'tries.jsonl'),
87
+ }),
88
+ 'POST /api/send': async (req) => {
89
+ const b = await bodyOf(req);
90
+ const side = sideOf(b.side);
91
+ const text = str(b.text);
92
+ if (!text)
93
+ throw new RehearseError('usage', 'Give the call’s text to send.');
94
+ const as = personIn(m, b.person);
95
+ const own = str(b.id) ? await scenarioOn(side, str(b.id)) : null;
96
+ const world = worldIn(m, b.world) ?? own?.world ?? m.defaults.world;
97
+ let parsed;
98
+ try {
99
+ parsed = parseHurl(text, 'stage.hurl').calls[0];
100
+ }
101
+ catch (error) {
102
+ if (error instanceof Refusal)
103
+ throw new RehearseError('usage', `Line ${error.line}: ${error.says}`);
104
+ throw error;
105
+ }
106
+ if (!parsed)
107
+ throw new RehearseError('usage', 'The text holds no call: start it with a method and a URL, such as GET {{api}}/health.');
108
+ const s = await sending.upOnlyOn(side, world);
109
+ const service = m.scenarios.calls.service ?? m.defaults.service;
110
+ const running = s.running.find((r) => r.name === service);
111
+ const origins = s.running.flatMap((r) => {
112
+ try {
113
+ return r.url ? [new URL(r.url).origin] : [];
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ });
119
+ let elsewhere = null;
120
+ const { sent } = await sendFile([parsed], {
121
+ variables: {
122
+ ...s.variables,
123
+ ...m.scenarios.calls.variables,
124
+ ...(running?.url && { api: running.url.replace(/\/+$/, '') }),
125
+ },
126
+ people: s.tokens,
127
+ as,
128
+ }, null, boundTo(origins, (origin) => (elsewhere = origin)));
129
+ if (elsewhere)
130
+ throw new RehearseError('usage', `The stage sends calls only to this product's services (${origins.join(', ') || 'none is up'}), not to ${elsewhere}.`);
131
+ const one = sent[0];
132
+ return scrubDeep({
133
+ v: 1,
134
+ side,
135
+ request: one.request,
136
+ who: one.who,
137
+ status: one.status,
138
+ contentType: one.contentType,
139
+ body: one.body,
140
+ failures: one.failures,
141
+ ms: one.ms,
142
+ }, s.tokens);
143
+ },
144
+ 'GET /api/piece': async (_req, url) => {
145
+ const id = url.searchParams.get('id') ?? '';
146
+ const side = sideOf(url.searchParams.get('side'));
147
+ const s = await scenarioOn(side, id);
148
+ const spec = s?.spec;
149
+ if (!s || s.kind !== 'piece' || !spec?.packageDir)
150
+ throw new RehearseError('no_scenario', `The ${side} has no piece “${id}” with a package that runs Vite and React.`);
151
+ const key = `${side}|${spec.packageDir}`;
152
+ let server = pieces.get(key);
153
+ if (!server) {
154
+ server = await startPieceServer({
155
+ dir: spec.packageDir,
156
+ config: m.scenarios.pieces.config ?? null,
157
+ styles: m.scenarios.pieces.styles ?? null,
158
+ preview: m.scenarios.pieces.preview ?? null,
159
+ pieces: [{ file: spec.inPackage, exportName: spec.exportName }],
160
+ progress: o.progress,
161
+ });
162
+ pieces.set(key, server);
163
+ }
164
+ return { v: 1, url: server.canvas(spec.inPackage, spec.exportName) };
165
+ },
166
+ };
167
+ let queue = Promise.resolve();
168
+ const oneAtATime = (work) => {
169
+ const next = queue.then(work, work);
170
+ queue = next.catch(() => undefined);
171
+ return next;
172
+ };
173
+ for (const key of SHARE_ONE_SET_OF_SERVICES) {
174
+ const work = api[key];
175
+ api[key] = (req, url) => oneAtATime(() => work(req, url));
176
+ }
177
+ let port = 0;
178
+ const handle = (req, res) => {
179
+ const refused = refusalOf(req, port);
180
+ if (refused)
181
+ return fail(res, refused[0], 'refused', refused[1]);
182
+ let url;
183
+ try {
184
+ url = new URL(req.url ?? '/', `http://${STAGE_HOST}:${port}`);
185
+ }
186
+ catch {
187
+ return fail(res, 400, 'usage', 'That address makes no sense to the stage.');
188
+ }
189
+ const handler = api[`${req.method} ${url.pathname}`];
190
+ if (handler)
191
+ return answer(res, handler(req, url));
192
+ if (url.pathname === '/files')
193
+ return serveFile(res, url.searchParams.get('path') ?? '', [
194
+ stateDir(m.dir),
195
+ head.path,
196
+ ...(base ? [base.path] : []),
197
+ ]);
198
+ servePage(res, url.pathname);
199
+ };
200
+ const server = createServer((req, res) => {
201
+ res.setHeader('x-content-type-options', 'nosniff');
202
+ try {
203
+ handle(req, res);
204
+ }
205
+ catch (error) {
206
+ if (!res.headersSent)
207
+ fail(res, 500, 'crashed', errorText(error));
208
+ else
209
+ res.destroy();
210
+ }
211
+ });
212
+ try {
213
+ await listenAt(server, o.port);
214
+ }
215
+ catch (error) {
216
+ if (error.code !== 'EADDRINUSE')
217
+ throw error;
218
+ if (!o.anyPort)
219
+ throw new RehearseError('stage', `Port ${o.port} is taken: give the stage another with --port.`);
220
+ await listenAt(server, 0);
221
+ }
222
+ port = server.address().port;
223
+ const url = `http://${STAGE_HOST}:${port}/`;
224
+ mkdirSync(stateDir(m.dir), { recursive: true });
225
+ writeFileSync(stageFile(m), `${JSON.stringify({ url, port, pid: process.pid, since: new Date().toISOString() }, null, 2)}\n`);
226
+ function forget() {
227
+ try {
228
+ const written = JSON.parse(readFileSync(stageFile(m), 'utf8'));
229
+ if (written.pid === process.pid)
230
+ writeFileSync(stageFile(m), '{}\n');
231
+ }
232
+ catch {
233
+ return;
234
+ }
235
+ }
236
+ return {
237
+ url,
238
+ port,
239
+ server,
240
+ forget,
241
+ async close() {
242
+ forget();
243
+ server.closeAllConnections?.();
244
+ await new Promise((resolve) => server.close(() => resolve()));
245
+ for (const p of pieces.values())
246
+ await p.close().catch(() => undefined);
247
+ await sending.takeDown().catch(() => undefined);
248
+ },
249
+ };
250
+ }
@@ -0,0 +1,2 @@
1
+ export declare const PACKAGE_ROOT: string;
2
+ export declare const VERSION: string;
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
5
+ export const VERSION = JSON.parse(readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
@@ -0,0 +1,16 @@
1
+ export interface WorldContext {
2
+ world: string;
3
+ url: string | null;
4
+ args: Record<string, string>;
5
+ shared: Record<string, unknown>;
6
+ }
7
+ export interface WorldDefinition<C extends WorldContext = WorldContext> {
8
+ name: string;
9
+ extends?: string;
10
+ describe?: string;
11
+ add(ctx: C): void | Promise<void>;
12
+ }
13
+ export declare const defineWorld: <C extends WorldContext = WorldContext>(w: WorldDefinition<C>) => WorldDefinition<C>;
14
+ export declare function worldChain<C extends WorldContext>(worlds: readonly WorldDefinition<C>[], name: string): WorldDefinition<C>[];
15
+ export declare function buildWorld<C extends WorldContext>(worlds: readonly WorldDefinition<C>[], name: string, ctx: Omit<C, 'world'>): Promise<string[]>;
16
+ export declare function worldMain(worlds: readonly WorldDefinition[], argv?: readonly string[]): Promise<void>;
@@ -0,0 +1,45 @@
1
+ export const defineWorld = (w) => w;
2
+ export function worldChain(worlds, name) {
3
+ const byName = new Map(worlds.map((w) => [w.name, w]));
4
+ const chain = [];
5
+ for (let at = name; at !== undefined; at = byName.get(at)?.extends) {
6
+ const w = byName.get(at);
7
+ if (!w)
8
+ throw new Error(`There is no world “${at}”: there is ${[...byName.keys()].join(', ') || 'none'}.`);
9
+ if (chain.includes(w))
10
+ throw new Error(`The worlds extend in a circle at “${at}”.`);
11
+ chain.unshift(w);
12
+ }
13
+ return chain;
14
+ }
15
+ export async function buildWorld(worlds, name, ctx) {
16
+ const chain = worldChain(worlds, name);
17
+ const full = { ...ctx, world: name };
18
+ for (const w of chain)
19
+ await w.add(full);
20
+ return chain.map((w) => w.name);
21
+ }
22
+ export async function worldMain(worlds, argv = process.argv.slice(2)) {
23
+ const [name, ...rest] = argv;
24
+ if (!name) {
25
+ process.stderr.write(`Name a world: ${worlds.map((w) => w.name).join(', ')}.\n`);
26
+ process.exitCode = 2;
27
+ return;
28
+ }
29
+ const args = {};
30
+ for (let i = 0; i < rest.length; i += 2)
31
+ if (rest[i]?.startsWith('--') && rest[i + 1] !== undefined)
32
+ args[rest[i].slice(2)] = rest[i + 1];
33
+ try {
34
+ const built = await buildWorld(worlds, name, {
35
+ url: args.url ?? process.env.REHEARSE_URL ?? null,
36
+ args,
37
+ shared: {},
38
+ });
39
+ process.stdout.write(`${JSON.stringify({ v: 1, world: name, built })}\n`);
40
+ }
41
+ catch (error) {
42
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
43
+ process.exitCode = 1;
44
+ }
45
+ }
@@ -0,0 +1,2 @@
1
+ export { buildWorld, defineWorld, worldChain, worldMain, type WorldContext, type WorldDefinition, } from './define.ts';
2
+ export { applyWorld, chainOf, worldsOut } from './worlds.ts';
@@ -0,0 +1,2 @@
1
+ export { buildWorld, defineWorld, worldChain, worldMain, } from './define.js';
2
+ export { applyWorld, chainOf, worldsOut } from './worlds.js';
@@ -0,0 +1,15 @@
1
+ import { type Manifest, type World } from '../manifest/index.ts';
2
+ export declare function chainOf(m: Manifest, name: string): World[];
3
+ export interface WorldsOut {
4
+ v: 1;
5
+ worlds: {
6
+ name: string;
7
+ describe: string | null;
8
+ extends: string | null;
9
+ chain: string[];
10
+ add: string | null;
11
+ default: boolean;
12
+ }[];
13
+ }
14
+ export declare function worldsOut(m: Manifest): WorldsOut;
15
+ export declare function applyWorld(m: Manifest, world: string, when: 'before' | 'add', cwd: string, vars: Record<string, string>): Promise<void>;
@@ -0,0 +1,46 @@
1
+ import { RehearseError } from '../errors.js';
2
+ import { sh, tail } from '../exec.js';
3
+ import { fill } from '../manifest/index.js';
4
+ export function chainOf(m, name) {
5
+ const chain = [];
6
+ const seen = new Set();
7
+ for (let at = name; at !== null; at = m.worlds[at]?.extends ?? null) {
8
+ const w = m.worlds[at];
9
+ if (!w) {
10
+ const known = Object.keys(m.worlds);
11
+ throw new RehearseError('no_world', `There is no world “${at}”${known.length ? `: there is ${known.map((k) => `“${k}”`).join(', ')}` : ' in the manifest'}.`);
12
+ }
13
+ if (seen.has(at))
14
+ throw new RehearseError('manifest', `The worlds extend in a circle at “${at}”.`);
15
+ seen.add(at);
16
+ chain.unshift(w);
17
+ }
18
+ return chain;
19
+ }
20
+ export function worldsOut(m) {
21
+ return {
22
+ v: 1,
23
+ worlds: Object.values(m.worlds).map((w) => ({
24
+ name: w.name,
25
+ describe: w.describe,
26
+ extends: w.extends,
27
+ chain: chainOf(m, w.name).map((x) => x.name),
28
+ add: w.add,
29
+ default: m.defaults.world === w.name,
30
+ })),
31
+ };
32
+ }
33
+ export async function applyWorld(m, world, when, cwd, vars) {
34
+ for (const w of chainOf(m, world)) {
35
+ const command = w[when];
36
+ if (!command)
37
+ continue;
38
+ const ran = await sh(fill(command, { ...vars, world }), {
39
+ cwd,
40
+ timeoutMs: 5 * 60_000,
41
+ env: vars.url ? { REHEARSE_URL: vars.url } : {},
42
+ });
43
+ if (ran.code !== 0)
44
+ throw new RehearseError('world', `The world ${w.name} didn't build (${command}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
45
+ }
46
+ }