@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,297 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { jsonDifferences, noCounts, setAsideText, textDifferences, } from '../../compare/index.js';
6
+ import { calm, contextFor, errorsOf, FIXED_TIME, launch } from '../../drive/index.js';
7
+ import { errorText } from '../../errors.js';
8
+ import { hashOf } from '../../manifest/index.js';
9
+ import { registerReader, toPosix } from '../../scenarios/index.js';
10
+ import { broken, registerRunner } from '../kind.js';
11
+ import { ROOT_ID, THREW } from './canvas.js';
12
+ import { metaTitle, propertyString, statementAt, storyExportsOf, storyNameFromExport, titleFromPath, toId, } from './csf.js';
13
+ import { resolvable, startPieceServer } from './server.js';
14
+ const LOAD_MS = 20_000;
15
+ const WCAG = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'];
16
+ const escaped = (name) => name.replace(/\$/g, '\\$');
17
+ function exportText(code, name) {
18
+ const at = new RegExp(`\\bexport\\s+(?:const|let|var|function\\*?|async\\s+function\\*?|class)\\s+${escaped(name)}\\b`).exec(code);
19
+ if (at)
20
+ return statementAt(code, at.index);
21
+ const declaredApart = new RegExp(`\\b(?:const|let|var|function\\*?|class)\\s+${escaped(name)}\\b`).exec(code);
22
+ if (declaredApart)
23
+ return statementAt(code, declaredApart.index);
24
+ const declaredAfterAComma = new RegExp(`[,]\\s*${escaped(name)}\\s*(?::[^=]+)?=`).exec(code);
25
+ return declaredAfterAComma ? statementAt(code, declaredAfterAComma.index + 1) : '';
26
+ }
27
+ function metaText(code) {
28
+ const direct = /\bexport\s+default\s+([A-Za-z_$][\w$]*)?/.exec(code);
29
+ const renamed = /\bexport\s*\{[^}]*?\b([A-Za-z_$][\w$]*)\s+as\s+default\b/.exec(code);
30
+ const name = direct?.[1] ?? renamed?.[1];
31
+ const declared = name ? new RegExp(`\\b(?:const|let|var)\\s+${escaped(name)}\\b`).exec(code) : null;
32
+ return [
33
+ declared ? statementAt(code, declared.index) : '',
34
+ direct ? statementAt(code, direct.index) : '',
35
+ ].join('\n');
36
+ }
37
+ const squeeze = (s) => s.replace(/\s+/g, ' ').trim();
38
+ function displayName(code, exportName) {
39
+ const at = new RegExp(`\\bexport\\s+const\\s+${exportName.replace(/\$/g, '\\$')}\\b[^=]*=\\s*`).exec(code);
40
+ if (at) {
41
+ const brace = code.indexOf('{', at.index + at[0].length - 1);
42
+ if (brace === at.index + at[0].length) {
43
+ const named = propertyString(code, brace, 'name');
44
+ if (named)
45
+ return named;
46
+ }
47
+ }
48
+ const legacy = new RegExp(`\\b${exportName.replace(/\$/g, '\\$')}\\.storyName\\s*=\\s*['"\`]([^'"\`]+)['"\`]`).exec(code);
49
+ return legacy?.[1] ?? storyNameFromExport(exportName);
50
+ }
51
+ const hasPackageJson = (dir) => {
52
+ try {
53
+ readFileSync(path.join(dir, 'package.json'));
54
+ return true;
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ };
60
+ export function packageOf(checkout, abs) {
61
+ for (let at = path.dirname(abs);; at = path.dirname(at)) {
62
+ if (hasPackageJson(at) && resolvable(at, 'vite') && resolvable(at, 'react'))
63
+ return at;
64
+ if (path.resolve(at) === path.resolve(checkout) || path.dirname(at) === at)
65
+ return null;
66
+ }
67
+ }
68
+ registerReader({
69
+ kind: 'piece',
70
+ read(f, text, ctx) {
71
+ const exports = storyExportsOf(text);
72
+ const title = metaTitle(text);
73
+ const meta = squeeze(metaText(text));
74
+ const pkg = packageOf(ctx.checkout, f.abs);
75
+ const fileTitle = title ?? titleFromPath(f.file);
76
+ const short = fileTitle.split('/').at(-1) ?? fileTitle;
77
+ return exports.map((exportName) => {
78
+ const name = displayName(text, exportName);
79
+ let storyId = null;
80
+ try {
81
+ storyId = title ? toId(title, name) : null;
82
+ }
83
+ catch {
84
+ storyId = null;
85
+ }
86
+ return {
87
+ id: `${f.file}#${exportName}`,
88
+ kind: 'piece',
89
+ name: `${short} · ${name}`,
90
+ file: f.file,
91
+ abs: f.abs,
92
+ line: null,
93
+ from: f.from,
94
+ area: ctx.area,
95
+ definition: hashOf({ story: squeeze(exportText(text, exportName)), meta }),
96
+ world: null,
97
+ person: null,
98
+ service: null,
99
+ covers: f.covers,
100
+ spec: {
101
+ exportName,
102
+ title,
103
+ storyId,
104
+ packageDir: pkg,
105
+ inPackage: pkg ? toPosix(path.relative(pkg, f.abs)) : f.file,
106
+ },
107
+ };
108
+ });
109
+ },
110
+ });
111
+ let axeSource = null;
112
+ function axe() {
113
+ axeSource ??= readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.min.js'), 'utf8');
114
+ return axeSource;
115
+ }
116
+ const withoutScreenshotPath = ({ screenshot: _whereOnThisMachine, ...seen }) => seen;
117
+ async function observe(page, url, shot, errors) {
118
+ errors.length = 0;
119
+ await page.goto(url, { waitUntil: 'load', timeout: LOAD_MS });
120
+ await page
121
+ .waitForFunction(() => document.body.dataset.rehearseMounted === 'yes' || !!document.querySelector('[data-rehearse-piece]'), undefined, { timeout: LOAD_MS })
122
+ .catch(() => undefined);
123
+ await calm(page);
124
+ const failed = await page.$('[data-rehearse-piece="failed"]');
125
+ const mounted = await page.evaluate(() => document.body.dataset.rehearseMounted === 'yes');
126
+ const threw = failed
127
+ ? ((await failed.textContent()) ?? 'it threw')
128
+ : mounted
129
+ ? null
130
+ : `It never rendered${errors.length ? `: ${errors[0]}` : ' within 20 seconds'}`;
131
+ const root = page.locator(`#${ROOT_ID}`);
132
+ const tree = threw ? null : await root.ariaSnapshot({ timeout: 5_000 }).catch(() => null);
133
+ let violations = [];
134
+ if (!threw) {
135
+ await page.addScriptTag({ content: axe() });
136
+ violations = await page.evaluate(async ({ id, tags }) => {
137
+ const w = window;
138
+ const r = await w.axe.run(document.getElementById(id), {
139
+ runOnly: { type: 'tag', values: tags },
140
+ resultTypes: ['violations'],
141
+ });
142
+ return r.violations.map((v) => ({ id: v.id, help: v.help, nodes: v.nodes.length }));
143
+ }, { id: ROOT_ID, tags: WCAG });
144
+ }
145
+ const png = await page.screenshot({ path: shot, fullPage: true });
146
+ return {
147
+ tree,
148
+ threw,
149
+ errors: errors.filter((e) => !e.startsWith(THREW) && !/^\[vite\]|WebSocket connection to 'ws:\/\//.test(e)),
150
+ violations,
151
+ screenshot: shot,
152
+ pixels: createHash('sha256').update(png).digest('hex').slice(0, 16),
153
+ };
154
+ }
155
+ const idOf = (id) => createHash('sha256').update(id).digest('hex').slice(0, 12);
156
+ export async function runPieces(scenarios, ctx, browser) {
157
+ const out = new Map();
158
+ const m = ctx.manifest;
159
+ const settings = m.scenarios.pieces;
160
+ const schemes = settings.schemes ?? ['light'];
161
+ const byPackage = new Map();
162
+ for (const s of scenarios) {
163
+ const spec = s.spec;
164
+ if (!spec.packageDir) {
165
+ out.set(s.id, broken('runner', `No package with Vite and React holds ${s.file}, so Rehearse can't render it.`));
166
+ continue;
167
+ }
168
+ byPackage.set(spec.packageDir, [...(byPackage.get(spec.packageDir) ?? []), s]);
169
+ }
170
+ if (byPackage.size === 0)
171
+ return out;
172
+ const own = !browser;
173
+ const b = browser ?? (await launch());
174
+ try {
175
+ for (const [dir, group] of byPackage) {
176
+ let server;
177
+ try {
178
+ server = await startPieceServer({
179
+ dir,
180
+ config: settings.config ?? null,
181
+ styles: settings.styles ?? null,
182
+ preview: settings.preview ?? null,
183
+ pieces: group.map((s) => ({
184
+ file: s.spec.inPackage,
185
+ exportName: s.spec.exportName,
186
+ })),
187
+ progress: ctx.progress,
188
+ });
189
+ }
190
+ catch (error) {
191
+ for (const s of group)
192
+ out.set(s.id, broken('runner', errorText(error)));
193
+ continue;
194
+ }
195
+ try {
196
+ const seen = new Map();
197
+ for (const scheme of schemes) {
198
+ const context = await contextFor(b, null, null, scheme, settings.viewport ?? { width: 1024, height: 768 });
199
+ const page = await context.newPage();
200
+ await page.clock.setFixedTime(FIXED_TIME);
201
+ const errors = errorsOf(page);
202
+ for (const s of group) {
203
+ const spec = s.spec;
204
+ const shot = path.join(ctx.keep, `piece-${idOf(s.id)}-${scheme}.png`);
205
+ try {
206
+ const one = await observe(page, server.canvas(spec.inPackage, spec.exportName), shot, errors);
207
+ seen.set(s.id, { ...seen.get(s.id), [scheme]: one });
208
+ }
209
+ catch (error) {
210
+ seen.set(s.id, {
211
+ ...seen.get(s.id),
212
+ [scheme]: {
213
+ tree: null,
214
+ threw: `It didn't render: ${errorText(error)}`,
215
+ errors: [],
216
+ violations: [],
217
+ screenshot: null,
218
+ pixels: null,
219
+ },
220
+ });
221
+ }
222
+ }
223
+ await context.close();
224
+ }
225
+ for (const s of group) {
226
+ const spec = s.spec;
227
+ const schemesSeen = seen.get(s.id) ?? {};
228
+ const threw = Object.entries(schemesSeen).find(([, x]) => x.threw);
229
+ out.set(s.id, {
230
+ ok: !threw,
231
+ failures: threw
232
+ ? [{ text: `render in ${threw[0]}`, expected: 'it renders', got: threw[1].threw }]
233
+ : [],
234
+ observed: {
235
+ kind: 'piece',
236
+ storyId: spec.storyId,
237
+ schemes: Object.fromEntries(Object.entries(schemesSeen).map(([k, x]) => [k, withoutScreenshotPath(x)])),
238
+ },
239
+ artifacts: Object.entries(schemesSeen)
240
+ .filter(([, x]) => x.screenshot)
241
+ .map(([scheme, x]) => ({ kind: 'screenshot', path: x.screenshot, label: scheme })),
242
+ broke: null,
243
+ });
244
+ }
245
+ }
246
+ finally {
247
+ await server.close();
248
+ }
249
+ }
250
+ }
251
+ finally {
252
+ if (own)
253
+ await b.close();
254
+ }
255
+ return out;
256
+ }
257
+ registerRunner({
258
+ kind: 'piece',
259
+ version: 'piece/2',
260
+ services: () => [],
261
+ run: (scenarios, ctx) => runPieces(scenarios, ctx),
262
+ compare(base, head, rules, counts, _s, m) {
263
+ const compared = new Set(m.scenarios.pieces.compare ?? ['tree', 'errors', 'violations']);
264
+ const a = (base.schemes ?? {});
265
+ const b = (head.schemes ?? {});
266
+ const diffs = [];
267
+ for (const scheme of new Set([...Object.keys(a), ...Object.keys(b)])) {
268
+ const x = a[scheme];
269
+ const y = b[scheme];
270
+ if (!x || !y) {
271
+ diffs.push({
272
+ path: scheme,
273
+ base: x ? 'rendered' : '(absent)',
274
+ head: y ? 'rendered' : '(absent)',
275
+ count: 1,
276
+ });
277
+ continue;
278
+ }
279
+ if ((x.threw === null) !== (y.threw === null))
280
+ diffs.push({
281
+ path: `${scheme} render`,
282
+ base: x.threw ?? 'it renders',
283
+ head: y.threw ?? 'it renders',
284
+ count: 1,
285
+ });
286
+ if (compared.has('tree'))
287
+ diffs.push(...textDifferences(setAsideText(x.tree ?? '', rules, noCounts()), setAsideText(y.tree ?? '', rules, counts), `${scheme} tree`));
288
+ if (compared.has('errors'))
289
+ diffs.push(...jsonDifferences(x.errors.map((e) => setAsideText(e, rules, noCounts())), y.errors.map((e) => setAsideText(e, rules, counts)), `${scheme} errors`));
290
+ if (compared.has('violations'))
291
+ diffs.push(...jsonDifferences(x.violations.map((v) => v.id).sort(), y.violations.map((v) => v.id).sort(), `${scheme} violations`));
292
+ if (compared.has('screenshot') && x.pixels !== y.pixels)
293
+ diffs.push({ path: `${scheme} screenshot`, base: x.pixels ?? '', head: y.pixels ?? '', count: 1 });
294
+ }
295
+ return diffs;
296
+ },
297
+ });
@@ -0,0 +1,23 @@
1
+ import { type Found } from './conventions.ts';
2
+ export declare const HOST = "127.0.0.1";
3
+ export declare const resolvable: (dir: string, request: string) => boolean;
4
+ export interface PieceServerOptions {
5
+ dir: string;
6
+ config?: string | null;
7
+ styles?: string | null;
8
+ preview?: string | null;
9
+ pieces: readonly {
10
+ file: string;
11
+ exportName: string;
12
+ }[];
13
+ progress?: (line: string) => void;
14
+ }
15
+ export interface PieceServer {
16
+ dir: string;
17
+ url: string;
18
+ config: Found | null;
19
+ styles: Found | null;
20
+ canvas(file: string, exportName: string): string;
21
+ close(): Promise<void>;
22
+ }
23
+ export declare function startPieceServer(o: PieceServerOptions): Promise<PieceServer>;
@@ -0,0 +1,236 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { readFileSync } from 'node:fs';
10
+ import { createServer as createHttpServer } from 'node:http';
11
+ import { createRequire } from 'node:module';
12
+ import path from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { init, parse } from 'es-module-lexer';
15
+ import { RehearseError, errorText } from '../../errors.js';
16
+ import { freePort } from '../../services/index.js';
17
+ import { CANVAS_MODULE, CANVAS_PATH, canvasHtml, canvasKeyOf, canvasModule, canvasScript, missingHtml, SHIMMED, SHIMS, } from './canvas.js';
18
+ import { cacheDirOf, findConfig, findStyles } from './conventions.js';
19
+ import { titleFromPath } from './csf.js';
20
+ export const HOST = '127.0.0.1';
21
+ const SETTLE_LIMIT_MS = 60_000;
22
+ const SETTLE_PAUSE_MS = 150;
23
+ const SETTLE_CALM = 3;
24
+ const CRAWL_LIMIT = 5_000;
25
+ const SHIM_MODULE = '\0rehearse-shim:';
26
+ function entryOf(exports) {
27
+ if (typeof exports === 'string')
28
+ return exports;
29
+ if (exports && typeof exports === 'object' && !Array.isArray(exports)) {
30
+ const e = exports;
31
+ if ('.' in e)
32
+ return entryOf(e['.']);
33
+ return entryOf(e.import ?? e.node ?? e.default);
34
+ }
35
+ return null;
36
+ }
37
+ async function importFrom(dir, name) {
38
+ const requireThere = createRequire(path.join(dir, 'package.json'));
39
+ let manifest;
40
+ try {
41
+ manifest = requireThere.resolve(`${name}/package.json`);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
47
+ const entry = entryOf(pkg.exports) ?? pkg.module ?? pkg.main ?? 'index.js';
48
+ return (await import(__rewriteRelativeImportExtension(pathToFileURL(path.join(path.dirname(manifest), entry)).href)));
49
+ }
50
+ export const resolvable = (dir, request) => {
51
+ try {
52
+ createRequire(path.join(dir, 'package.json')).resolve(request);
53
+ return true;
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ };
59
+ const urlOf = (root, file) => {
60
+ const relative = path.relative(root, file);
61
+ if (!relative.startsWith('..') && !path.isAbsolute(relative))
62
+ return `/${relative.split(path.sep).join('/')}`;
63
+ return `/@fs${file
64
+ .split(path.sep)
65
+ .join('/')
66
+ .replace(/^(?!\/)/, '/')}`;
67
+ };
68
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
69
+ const optimizerOf = (vite) => vite.environments?.client?.depsOptimizer;
70
+ const optimizerHash = (vite) => {
71
+ const metadata = optimizerOf(vite)?.metadata;
72
+ return `${metadata?.browserHash ?? ''}:${Object.keys(metadata?.discovered ?? {}).length}`;
73
+ };
74
+ async function optimizerSettled(vite) {
75
+ const begun = Date.now();
76
+ let last = '';
77
+ let calm = 0;
78
+ while (Date.now() - begun < SETTLE_LIMIT_MS) {
79
+ const optimizer = optimizerOf(vite);
80
+ if (!optimizer?.metadata)
81
+ return;
82
+ await optimizer.scanProcessing;
83
+ const discovered = Object.values(optimizer.metadata.discovered ?? {});
84
+ await Promise.all(discovered.map((d) => d.processing?.catch(() => undefined)));
85
+ const now = optimizerHash(vite);
86
+ calm = now === last && discovered.length === 0 ? calm + 1 : 0;
87
+ last = now;
88
+ if (calm >= SETTLE_CALM)
89
+ return;
90
+ await pause(SETTLE_PAUSE_MS);
91
+ }
92
+ }
93
+ const crawled = (url) => url.startsWith('/') &&
94
+ !url.startsWith('/@vite/') &&
95
+ !url.startsWith('/@react-refresh') &&
96
+ !url.startsWith('/@id/') &&
97
+ !url.includes('/node_modules/');
98
+ async function warm(vite, urls) {
99
+ const seen = new Set();
100
+ const visit = async (url) => {
101
+ if (seen.has(url) || seen.size >= CRAWL_LIMIT)
102
+ return;
103
+ seen.add(url);
104
+ let code;
105
+ try {
106
+ const result = await vite.transformRequest(url);
107
+ if (!result)
108
+ return;
109
+ code = result.code;
110
+ }
111
+ catch {
112
+ return;
113
+ }
114
+ let imports;
115
+ try {
116
+ [imports] = parse(code);
117
+ }
118
+ catch {
119
+ return;
120
+ }
121
+ await Promise.all(imports
122
+ .map((i) => i.n)
123
+ .filter((n) => typeof n === 'string' && crawled(n))
124
+ .map(visit));
125
+ };
126
+ await Promise.all(urls.map(visit));
127
+ }
128
+ export async function startPieceServer(o) {
129
+ const { dir } = o;
130
+ const vitePackage = await importFrom(dir, 'vite');
131
+ if (!vitePackage)
132
+ throw new RehearseError('piece', `${dir} has no Vite in its node_modules, so Rehearse can't render its pieces.`);
133
+ if (!resolvable(dir, 'react') || !resolvable(dir, 'react-dom/client'))
134
+ throw new RehearseError('piece', `${dir} has no React in its node_modules, so Rehearse can't render its pieces.`);
135
+ await init;
136
+ const config = findConfig(dir, o.config ?? null);
137
+ const styles = findStyles(dir, o.styles ?? null);
138
+ const preview = o.preview ? path.resolve(dir, o.preview) : null;
139
+ const port = await freePort();
140
+ const reactDeps = ['react', 'react/jsx-runtime', 'react/jsx-dev-runtime', 'react-dom', 'react-dom/client'];
141
+ if (resolvable(dir, 'react/compiler-runtime'))
142
+ reactDeps.push('react/compiler-runtime');
143
+ const http = createHttpServer();
144
+ let vite;
145
+ const plugin = {
146
+ name: 'rehearse-pieces',
147
+ enforce: 'pre',
148
+ resolveId(source) {
149
+ const shim = SHIMMED[source];
150
+ if (shim)
151
+ return `${SHIM_MODULE}${shim}`;
152
+ const key = canvasKeyOf(source);
153
+ return key === null ? null : `${CANVAS_MODULE}${JSON.stringify(key)}`;
154
+ },
155
+ load(id) {
156
+ if (id.startsWith(SHIM_MODULE))
157
+ return SHIMS[id.slice(SHIM_MODULE.length)] ?? null;
158
+ if (!id.startsWith(CANVAS_MODULE))
159
+ return null;
160
+ const [file, exportName] = JSON.parse(id.slice(CANVAS_MODULE.length));
161
+ return canvasModule({ viteUrl: urlOf(vite.config.root, path.join(dir, file)), exportName, title: titleFromPath(file) }, styles ? urlOf(vite.config.root, styles.file) : null, preview ? urlOf(vite.config.root, preview) : null);
162
+ },
163
+ };
164
+ const inline = {
165
+ configFile: config?.file ?? false,
166
+ root: dir,
167
+ cacheDir: cacheDirOf(dir),
168
+ base: '/',
169
+ mode: 'development',
170
+ clearScreen: false,
171
+ logLevel: 'error',
172
+ appType: 'custom',
173
+ server: { middlewareMode: true, hmr: { server: http }, host: HOST, port, watch: null },
174
+ optimizeDeps: { include: reactDeps, exclude: Object.keys(SHIMMED) },
175
+ plugins: [plugin],
176
+ };
177
+ const make = vitePackage.createServer;
178
+ vite = await make({ ...inline, configLoader: 'runner' }).catch(() => make({ ...inline, configLoader: 'bundle' }));
179
+ const send = (res, status, type, body) => {
180
+ res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' });
181
+ res.end(body);
182
+ };
183
+ const answer = async (req, res) => {
184
+ const url = new URL(req.url ?? '/', `http://${HOST}`);
185
+ if (url.pathname === CANVAS_PATH) {
186
+ const file = url.searchParams.get('file');
187
+ const exportName = url.searchParams.get('export');
188
+ if (!file || !exportName)
189
+ return send(res, 404, 'text/html; charset=utf-8', missingHtml('The address names no piece: add ?file=…&export=…'));
190
+ const html = await vite.transformIndexHtml(url.pathname + url.search, canvasHtml(file, exportName, `${file} · ${exportName}`));
191
+ return send(res, 200, 'text/html; charset=utf-8', html);
192
+ }
193
+ if (url.pathname === '/')
194
+ return send(res, 200, 'text/plain; charset=utf-8', "Rehearse's pieces\n");
195
+ vite.middlewares(req, res, () => send(res, 404, 'text/plain; charset=utf-8', 'Not found\n'));
196
+ };
197
+ http.on('request', (req, res) => {
198
+ answer(req, res).catch((error) => {
199
+ if (!res.headersSent)
200
+ send(res, 500, 'text/plain; charset=utf-8', `${errorText(error)}\n`);
201
+ else
202
+ res.end();
203
+ });
204
+ });
205
+ const begun = Date.now();
206
+ const urls = [
207
+ ...o.pieces.map((p) => urlOf(vite.config.root, path.join(dir, p.file))),
208
+ ...(styles ? [urlOf(vite.config.root, styles.file)] : []),
209
+ ...(preview ? [urlOf(vite.config.root, preview)] : []),
210
+ ...[...new Map(o.pieces.map((p) => [p.file, p])).values()].map((p) => canvasScript(p.file, p.exportName)),
211
+ ];
212
+ for (let round = 0; round < 3; round += 1) {
213
+ const before = optimizerHash(vite);
214
+ await warm(vite, urls);
215
+ await optimizerSettled(vite);
216
+ if (optimizerHash(vite) === before)
217
+ break;
218
+ }
219
+ await new Promise((resolve, reject) => {
220
+ http.once('error', reject);
221
+ http.listen(port, HOST, () => resolve());
222
+ });
223
+ o.progress?.(`Pieces in ${dir} are served at http://${HOST}:${port} (ready in ${Date.now() - begun} ms).`);
224
+ return {
225
+ dir,
226
+ url: `http://${HOST}:${port}`,
227
+ config,
228
+ styles,
229
+ canvas: (file, exportName) => `http://${HOST}:${port}${CANVAS_PATH}?file=${encodeURIComponent(file)}&export=${encodeURIComponent(exportName)}`,
230
+ close: async () => {
231
+ http.closeAllConnections?.();
232
+ await new Promise((resolve) => http.close(() => resolve()));
233
+ await vite.close();
234
+ },
235
+ };
236
+ }
@@ -0,0 +1,4 @@
1
+ export type Vars = Readonly<Record<string, string | number | null | undefined>>;
2
+ export declare const fill: (template: string, vars: Vars) => string;
3
+ export declare const placeholdersIn: (template: string) => string[];
4
+ export declare const fillEnv: (env: Readonly<Record<string, string>>, vars: Vars) => Record<string, string>;
@@ -0,0 +1,7 @@
1
+ const PLACEHOLDER = /\{\{\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*\}\}/g;
2
+ export const fill = (template, vars) => template.replace(PLACEHOLDER, (asWritten, name) => {
3
+ const v = vars[name];
4
+ return v === undefined || v === null ? asWritten : String(v);
5
+ });
6
+ export const placeholdersIn = (template) => [...template.matchAll(PLACEHOLDER)].map((m) => m[1]);
7
+ export const fillEnv = (env, vars) => Object.fromEntries(Object.entries(env).map(([k, v]) => [k, fill(v, vars)]));
@@ -0,0 +1,5 @@
1
+ export { fill, fillEnv } from './fill.ts';
2
+ export { STARTER } from './init.ts';
3
+ export { findManifest, hashOf, loadManifest, MANIFEST_FILE, manifestFrom } from './load.ts';
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
+ export { readYaml } from './yaml.ts';
@@ -0,0 +1,5 @@
1
+ export { fill, fillEnv } from './fill.js';
2
+ export { STARTER } from './init.js';
3
+ export { findManifest, hashOf, loadManifest, MANIFEST_FILE, manifestFrom } from './load.js';
4
+ export { KIND_BLOCK, KINDS, } from './types.js';
5
+ export { readYaml } from './yaml.js';
@@ -0,0 +1 @@
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";
@@ -0,0 +1,47 @@
1
+ export const STARTER = `# rehearse.yaml: what this repository has, so a change can be rehearsed before it ships.
2
+ # Every block is optional. Delete what you don't have. Reference: the docs' rehearse.yaml page.
3
+ version: 1
4
+
5
+ # The branch production runs. Comparisons use it as the base.
6
+ base: main
7
+
8
+ # Run once in a fresh checkout of a base commit, before anything else.
9
+ # prepare: pnpm install --frozen-lockfile --offline
10
+
11
+ # What can come up. {{port}} is filled with the port; port: auto picks a free one.
12
+ services:
13
+ web:
14
+ up: pnpm dev --port {{port}}
15
+ port: auto
16
+ ready: http://127.0.0.1:{{port}}/
17
+
18
+ # Who you can sign in as. A sign-in command prints {"people": {"name": "token"}}.
19
+ # signIn: node scripts/people.mjs
20
+ people:
21
+ owner:
22
+ describe: The organisation's owner
23
+ default: true
24
+
25
+ # Named starting states. A world extends another and adds to it.
26
+ worlds:
27
+ empty:
28
+ describe: Nothing but the schema
29
+ default: true
30
+ # one-org:
31
+ # extends: empty
32
+ # add: node scripts/seed.mjs one-org --url {{web_url}}
33
+
34
+ # Fakes for what can't run locally, named in every result.
35
+ # standins:
36
+ # ai:
37
+ # replaces: The model provider
38
+ # by: test/fixtures/ai-fake.ts
39
+ # env: { AI_PROVIDER: fake }
40
+
41
+ # Where the scenarios are. A path starting with ./ is read beside this file; any other, from each checkout.
42
+ scenarios:
43
+ pieces: ['src/**/*.stories.tsx']
44
+ flows: ['**/*.flow.yaml']
45
+ calls: ['**/*.hurl']
46
+ files: ['**/*.rehearse.yaml']
47
+ `;
@@ -0,0 +1,7 @@
1
+ import type { Manifest } from './types.ts';
2
+ export declare const MANIFEST_FILE = "rehearse.yaml";
3
+ export declare const MANIFEST_VARIABLE = "REHEARSE_MANIFEST";
4
+ export declare function findManifest(cwd: string, given: string | null, env?: NodeJS.ProcessEnv): string;
5
+ export declare function manifestFrom(text: string, file: string): Manifest;
6
+ export declare function loadManifest(file: string): Manifest;
7
+ export declare function hashOf(value: unknown): string;