@zsailer/jupyter-server-side-documents-conformance 0.0.0-stage → 0.0.3

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.
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env node
2
+ // `rtc-conformance`: run the real-time collaboration conformance tests against a backend. See --help.
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { grepFor, helpFor, parse } from './args.mjs';
9
+ import { pick } from './picker.mjs';
10
+ import { welcome } from './welcome.mjs';
11
+
12
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
13
+ const PACKAGE_ROOT = path.resolve(HERE, '..');
14
+ // in a checkout the version is the repo's; in the published package it is the package's own
15
+ const VERSION = (() => {
16
+ const read = file => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {});
17
+ const repo = read(path.join(PACKAGE_ROOT, '..', 'package.json'));
18
+ return (repo.name === 'notebook-scenario-docs' ? repo : read(path.join(PACKAGE_ROOT, 'package.json'))).version;
19
+ })();
20
+
21
+ const color = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
22
+ const paint = (code, s) => (color ? `\u001b[${code}m${s}\u001b[0m` : s);
23
+ const dim = s => paint('2', s);
24
+ const bold = s => paint('1', s);
25
+ const red = s => paint('31', s);
26
+
27
+ function fail(message, hint) {
28
+ console.error(`\n ${red('✗')} ${message}`);
29
+ if (hint) {
30
+ console.error(`\n${hint.split('\n').map(l => ` ${dim(l)}`).join('\n')}`);
31
+ }
32
+ console.error('');
33
+ process.exit(2);
34
+ }
35
+
36
+ /**
37
+ * Playwright does not compile TypeScript inside node_modules, so a copy installed there (npx, npm install) is unpacked
38
+ * once into a cache and run from there.
39
+ */
40
+ function suiteDir() {
41
+ if (!PACKAGE_ROOT.includes(`${path.sep}node_modules${path.sep}`)) {
42
+ return PACKAGE_ROOT;
43
+ }
44
+ const cache = path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'jupyter-server-side-documents-conformance', VERSION);
45
+ if (!fs.existsSync(path.join(cache, 'package.json'))) {
46
+ fs.mkdirSync(cache, { recursive: true });
47
+ fs.cpSync(PACKAGE_ROOT, cache, { recursive: true, filter: src => !path.relative(PACKAGE_ROOT, src).split(path.sep).includes('node_modules') });
48
+ }
49
+ if (!fs.existsSync(path.join(cache, 'node_modules'))) {
50
+ console.log(`\n ${dim('Setting up the tests (first run only)…')}`);
51
+ if (spawnSync('npm', ['install', '--no-audit', '--no-fund', '--silent'], { cwd: cache, stdio: 'inherit' }).status !== 0) {
52
+ fail('npm install failed while setting up the tests', `Look in ${cache}`);
53
+ }
54
+ }
55
+ return cache;
56
+ }
57
+
58
+ function loadStories(suite) {
59
+ return JSON.parse(fs.readFileSync(path.join(suite, 'stories.json'), 'utf8'));
60
+ }
61
+
62
+ function needsOf(s) {
63
+ return s.internal ? 'not checkable from outside' : s.requires.length ? `needs ${s.requires.join(', ')}` : 'needs nothing special';
64
+ }
65
+
66
+ function list(suite, options) {
67
+ const all = loadStories(suite);
68
+ const groups = [...new Set(all.map(s => s.group))];
69
+ if (options.group && !groups.includes(options.group)) {
70
+ fail(`No group called "${options.group}"`, `The groups are: ${groups.join(', ')}`);
71
+ }
72
+ const q = options.filter?.toLowerCase();
73
+ const stories = all
74
+ .filter(s => !options.group || s.group === options.group)
75
+ .filter(s => !q || [s.id, s.title, s.group, ...s.requires].join(' ').toLowerCase().includes(q));
76
+ if (!stories.length) {
77
+ fail(`No story matches "${options.filter}"`, 'Try a word from a title, an id, or a need such as releaseRoom.');
78
+ }
79
+ console.log('');
80
+ let group;
81
+ for (const s of stories) {
82
+ if (s.group !== group) {
83
+ if (group !== undefined) {
84
+ console.log('');
85
+ }
86
+ group = s.group;
87
+ console.log(` ${bold((s.groupTitle ?? group).toUpperCase())} ${dim(`${stories.filter(x => x.group === group).length} · ${group}`)}`);
88
+ }
89
+ const tags = [s.proposed ? 'proposed' : '', s.needsAlignment ? 'open question' : ''].filter(Boolean);
90
+ console.log(` ${bold(s.id.padEnd(5))} ${s.title}`);
91
+ console.log(` ${dim([needsOf(s), ...tags].join(' · '))}`);
92
+ }
93
+ const free = stories.filter(s => !s.internal && !s.requires.length).length;
94
+ console.log(`\n ${dim(`${stories.length} stories · ${free} need nothing special from a backend`)}`);
95
+ console.log(` ${dim('rtc-conformance pick to choose some · rtc-conformance run <id> to run one')}\n`);
96
+ }
97
+
98
+ /** The interactive way in: a list to choose from. Resolves with the ids chosen, or exits if the person leaves. */
99
+ async function choose(suite) {
100
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
101
+ fail('Picking stories needs a terminal', 'Name the stories instead:\n rtc-conformance run Z3 C2\nor see them with:\n rtc-conformance list');
102
+ }
103
+ const chosen = await pick(loadStories(suite));
104
+ if (!chosen) {
105
+ console.log(`\n ${dim('Nothing run.')}\n`);
106
+ process.exit(0);
107
+ }
108
+ console.log(`\n ${dim(`Running ${chosen.length === 1 ? chosen[0] : `${chosen.length} stories: ${chosen.join(', ')}`}`)}`);
109
+ return chosen;
110
+ }
111
+
112
+ async function serving(url) {
113
+ try {
114
+ return (await fetch(`${url}/lab`, { signal: AbortSignal.timeout(3000) })).ok;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ function findPythonEnv() {
121
+ const found = spawnSync('python3', ['-c', 'import jupyter_server_documents, sys; print(sys.prefix)'], { encoding: 'utf8' });
122
+ return found.status === 0 ? found.stdout.trim() : undefined;
123
+ }
124
+
125
+ /**
126
+ * Start the server the tests run against: the command the person gave (--start), or a JupyterLab with
127
+ * jupyter-server-documents, set up by the suite's own config (server/conformance_config.py) with the suite's own copy of
128
+ * the backend's side of the control contract (server/jsd_control.py). Nothing is taken from the backend's repo.
129
+ */
130
+ async function startServer(suite, options, port, out) {
131
+ fs.mkdirSync(out, { recursive: true });
132
+ const logFile = path.join(out, 'server.log');
133
+ const log = fs.openSync(logFile, 'w');
134
+ const env = { ...process.env, CONFORMANCE_PORT: String(port) };
135
+ let rootDir = options['root-dir'];
136
+ let command;
137
+ let args;
138
+ if (options.start) {
139
+ command = 'sh';
140
+ args = ['-c', options.start.replaceAll('{port}', String(port))];
141
+ } else {
142
+ const pythonEnv = options.env ?? process.env.JSD_ENV ?? findPythonEnv();
143
+ if (!pythonEnv) {
144
+ fail("Can't find a Python environment with jupyter_server_documents", 'Run this inside the environment you develop it in, or point at one:\n rtc-conformance run --env /path/to/env');
145
+ }
146
+ rootDir ??= path.join(os.tmpdir(), 'conformance-root');
147
+ fs.rmSync(rootDir, { recursive: true, force: true });
148
+ fs.mkdirSync(rootDir, { recursive: true });
149
+ env.CONFORMANCE_CONTROL = 'jsd_control';
150
+ command = path.join(pythonEnv, 'bin', 'jupyter');
151
+ args = ['lab', '--config', path.join(suite, 'server', 'conformance_config.py'), `--port=${port}`, '--no-browser', `--ServerApp.root_dir=${rootDir}`];
152
+ }
153
+ const server = spawn(command, args, { env, cwd: fs.mkdtempSync(path.join(os.tmpdir(), 'conformance-server-')), stdio: ['ignore', log, log], detached: true });
154
+ let exited = false;
155
+ server.on('exit', () => (exited = true));
156
+ // from the moment it exists, the server goes when this command does, however that happens (also during start-up)
157
+ process.once('exit', () => stop(server));
158
+ for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143], ['SIGHUP', 129]]) {
159
+ process.on(signal, () => {
160
+ stop(server);
161
+ process.exit(code);
162
+ });
163
+ }
164
+
165
+ const frames = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
166
+ for (let i = 0; i < 900; i++) {
167
+ if (await serving(`http://localhost:${port}`)) {
168
+ process.stdout.write('\r\u001b[2K');
169
+ return { server, rootDir };
170
+ }
171
+ if (exited) {
172
+ stop(server);
173
+ const tail = fs.readFileSync(logFile, 'utf8').trim().split('\n').slice(-12).join('\n');
174
+ fail('The server stopped before it was ready', tail);
175
+ }
176
+ if (process.stdout.isTTY) {
177
+ process.stdout.write(`\r ${dim(`${frames[i % frames.length]} Starting the server…`)}`);
178
+ }
179
+ await new Promise(r => setTimeout(r, 200));
180
+ }
181
+ stop(server);
182
+ fail('The server did not come up in 3 minutes', `Its log is ${logFile}`);
183
+ }
184
+
185
+ function stop(server) {
186
+ try {
187
+ process.kill(-server.pid);
188
+ } catch {
189
+ /* already gone */
190
+ }
191
+ }
192
+
193
+ function open(file) {
194
+ spawnSync(process.platform === 'darwin' ? 'open' : 'xdg-open', [file], { stdio: 'ignore' });
195
+ }
196
+
197
+ function watchPages(results) {
198
+ const pages = [];
199
+ if (!fs.existsSync(results)) {
200
+ return pages;
201
+ }
202
+ for (const dir of fs.readdirSync(results)) {
203
+ const folder = path.join(results, dir);
204
+ if (fs.existsSync(path.join(folder, 'error-context.md')) && fs.existsSync(path.join(folder, 'watch.html'))) {
205
+ pages.push(path.join(folder, 'watch.html'));
206
+ }
207
+ }
208
+ return pages;
209
+ }
210
+
211
+ async function run(suite, stories, options) {
212
+ const out = path.resolve(options.out ?? 'conformance-results');
213
+ const results = path.join(out, 'results');
214
+ const backend = options.backend ?? 'jsd';
215
+ const port = Number(process.env.COMPLIANCE_PORT ?? 8899);
216
+ let baseURL = options.url?.replace(/\/$/, '');
217
+
218
+ console.log(`\n ${bold('rtc-conformance')} ${dim(`v${VERSION}`)}`);
219
+
220
+ let server;
221
+ let rootDir = options['root-dir'];
222
+ if (!baseURL) {
223
+ if (!options.start && backend !== 'jsd') {
224
+ fail(`Don't know how to start "${backend}"`, 'Give a command that starts it, or a server that is already running:\n rtc-conformance run --start "<command that serves JupyterLab on {port}>"\n rtc-conformance run --url http://localhost:8888');
225
+ }
226
+ baseURL = `http://localhost:${port}`;
227
+ if (await serving(baseURL)) {
228
+ fail(`Something is already serving ${baseURL}`, 'Stop it, or run the tests against it:\n rtc-conformance run --url ' + baseURL);
229
+ }
230
+ console.log(` ${dim(options.start ? 'your server' : backend)}\n`);
231
+ const started = await startServer(suite, options, port, out);
232
+ server = started.server;
233
+ rootDir = rootDir ?? started.rootDir;
234
+ } else {
235
+ console.log(` ${dim(baseURL)}\n`);
236
+ }
237
+ const quit = () => server && stop(server);
238
+ process.on('SIGINT', () => (quit(), process.exit(130)));
239
+ process.on('SIGTERM', () => (quit(), process.exit(143)));
240
+
241
+ spawnSync('npx', ['playwright', 'install', 'chromium'], { cwd: suite, stdio: 'ignore' });
242
+
243
+ const knownGaps = path.resolve(options['known-gaps'] ?? 'conformance-known-gaps.json');
244
+ const grep = grepFor(stories, options.group);
245
+ const args = ['playwright', 'test', '--reporter', path.join(suite, 'runtime', 'reporter.ts'), '--output', results];
246
+ if (grep) {
247
+ args.push('--grep', grep);
248
+ }
249
+ if (options.headed) {
250
+ args.push('--headed');
251
+ }
252
+ const child = spawn('npx', args, {
253
+ cwd: suite,
254
+ stdio: 'inherit',
255
+ env: {
256
+ ...process.env,
257
+ COMPLIANCE_BASE_URL: baseURL,
258
+ COMPLIANCE_ADAPTER: options.adapter ?? 'http',
259
+ ...(rootDir ? { COMPLIANCE_ROOT_DIR: rootDir } : {}),
260
+ ...(fs.existsSync(knownGaps) ? { COMPLIANCE_KNOWN_GAPS: knownGaps } : {}),
261
+ PLAYWRIGHT_HTML_OPEN: 'never'
262
+ }
263
+ });
264
+ const code = await new Promise(resolve => child.on('exit', c => resolve(c ?? 1)));
265
+ quit();
266
+
267
+ const pages = watchPages(results);
268
+ if (pages.length) {
269
+ console.log(`\n ${dim('Watch the tabs of a failed story side by side:')}`);
270
+ for (const page of pages.slice(0, 5)) {
271
+ console.log(` ${dim(path.relative(process.cwd(), page))}`);
272
+ }
273
+ if (options.open) {
274
+ pages.slice(0, 5).forEach(open);
275
+ } else {
276
+ console.log(` ${dim('(--open opens them)')}`);
277
+ }
278
+ }
279
+ console.log('');
280
+ process.exit(code);
281
+ }
282
+
283
+ let parsed;
284
+ try {
285
+ parsed = parse(process.argv.slice(2));
286
+ } catch (error) {
287
+ fail(error.message, 'rtc-conformance help');
288
+ }
289
+ const { command, stories, options, topic } = parsed;
290
+ if (command === 'welcome') {
291
+ console.log(welcome({ version: VERSION, color }).join('\n'));
292
+ } else if (command === 'help') {
293
+ console.log(`\n${helpFor(topic)}`);
294
+ } else if (command === 'version') {
295
+ console.log(VERSION);
296
+ } else if (command === 'list') {
297
+ list(suiteDir(), options);
298
+ } else if (command === 'pick' || options.interactive) {
299
+ const suite = suiteDir();
300
+ await run(suite, await choose(suite), options);
301
+ } else {
302
+ await run(suiteDir(), stories, options);
303
+ }
package/bin/picker.mjs ADDED
@@ -0,0 +1,256 @@
1
+ // The interactive story picker of `rtc-conformance pick`: a list grouped by topic, in which a person selects several stories.
2
+ // The behaviour is pure functions (createPicker, reduce, render), so it is tested without a terminal; `pick` is the thin
3
+ // part that reads keys and draws.
4
+ import readline from 'node:readline';
5
+
6
+ /** @typedef {{id: string, group: string, groupTitle?: string, title: string, requires?: string[], proposed?: boolean, internal?: string}} Story */
7
+
8
+ export function createPicker(stories, { preselected = [] } = {}) {
9
+ return { stories, selected: new Set(preselected), filter: '', typing: false, cursor: 0, top: 0, hint: '' };
10
+ }
11
+
12
+ /** The stories that match what was typed: in the id, the title, the group, or what a story needs. */
13
+ export function visible(state) {
14
+ const q = state.filter.trim().toLowerCase();
15
+ if (!q) {
16
+ return state.stories;
17
+ }
18
+ return state.stories.filter(s => [s.id, s.title, s.group, s.groupTitle ?? '', ...(s.requires ?? [])].join(' ').toLowerCase().includes(q));
19
+ }
20
+
21
+ /**
22
+ * How many stories, from `top`, fit in `budget` lines. A group's title takes a line, and a blank line before it unless
23
+ * it is the first, so a window of a few groups shows fewer stories than lines.
24
+ */
25
+ export function fitCount(list, top, budget) {
26
+ let used = 0;
27
+ let n = 0;
28
+ let group;
29
+ for (let i = top; i < list.length; i++) {
30
+ const extra = list[i].group === group ? 0 : group === undefined ? 1 : 2;
31
+ if (used + extra + 1 > budget) {
32
+ break;
33
+ }
34
+ used += extra + 1;
35
+ n++;
36
+ group = list[i].group;
37
+ }
38
+ return Math.max(1, n);
39
+ }
40
+
41
+ function clamp(state, budget) {
42
+ const list = visible(state);
43
+ const n = list.length;
44
+ const cursor = Math.max(0, Math.min(state.cursor, n - 1));
45
+ let top = Math.max(0, Math.min(state.top, cursor));
46
+ // scroll until the arrow is inside the window
47
+ while (top < cursor && cursor >= top + fitCount(list, top, budget)) {
48
+ top++;
49
+ }
50
+ return { ...state, cursor: n ? cursor : 0, top };
51
+ }
52
+
53
+ function toggle(selected, ids, on) {
54
+ const next = new Set(selected);
55
+ ids.forEach(id => (on ? next.add(id) : next.delete(id)));
56
+ return next;
57
+ }
58
+
59
+ /**
60
+ * One key. Returns {state} to go on, or {state, done: 'run' | 'cancel'}.
61
+ * Keys are 'up', 'down', 'pageup', 'pagedown', 'home', 'end', 'space', 'enter', 'escape', 'backspace', 'ctrl-c', or the
62
+ * character typed.
63
+ */
64
+ export function reduce(state, key, budget = 14) {
65
+ const list = visible(state);
66
+ const go = next => ({ state: clamp({ ...state, hint: '', ...next }, budget) });
67
+
68
+ if (key === 'ctrl-c') {
69
+ return { state, done: 'cancel' };
70
+ }
71
+
72
+ if (state.typing) {
73
+ if (key === 'enter') {
74
+ return go({ typing: false });
75
+ }
76
+ if (key === 'escape') {
77
+ return go({ typing: false, filter: '', cursor: 0, top: 0 });
78
+ }
79
+ if (key === 'backspace') {
80
+ return go({ filter: state.filter.slice(0, -1), cursor: 0, top: 0 });
81
+ }
82
+ const char = key === 'space' ? ' ' : key;
83
+ if (char.length === 1 && char >= ' ') {
84
+ return go({ filter: state.filter + char, cursor: 0, top: 0 });
85
+ }
86
+ return { state };
87
+ }
88
+
89
+ const here = list[state.cursor];
90
+ switch (key) {
91
+ case 'up':
92
+ case 'k':
93
+ return go({ cursor: state.cursor - 1 });
94
+ case 'down':
95
+ case 'j':
96
+ return go({ cursor: state.cursor + 1 });
97
+ case 'pageup':
98
+ return go({ cursor: state.cursor - fitCount(list, state.top, budget) });
99
+ case 'pagedown':
100
+ return go({ cursor: state.cursor + fitCount(list, state.top, budget) });
101
+ case 'home':
102
+ return go({ cursor: 0 });
103
+ case 'end':
104
+ return go({ cursor: list.length - 1 });
105
+ case 'space':
106
+ return here ? go({ selected: toggle(state.selected, [here.id], !state.selected.has(here.id)), cursor: state.cursor + 1 }) : { state };
107
+ case 'a': {
108
+ const all = list.length > 0 && list.every(s => state.selected.has(s.id));
109
+ return go({ selected: toggle(state.selected, list.map(s => s.id), !all) });
110
+ }
111
+ case 'g': {
112
+ if (!here) {
113
+ return { state };
114
+ }
115
+ const ids = list.filter(s => s.group === here.group).map(s => s.id);
116
+ return go({ selected: toggle(state.selected, ids, !ids.every(id => state.selected.has(id))) });
117
+ }
118
+ case 'c':
119
+ return go({ selected: new Set() });
120
+ case '/':
121
+ return go({ typing: true });
122
+ case 'escape':
123
+ if (state.filter) {
124
+ return go({ filter: '', cursor: 0, top: 0 });
125
+ }
126
+ return { state, done: 'cancel' };
127
+ case 'q':
128
+ return { state, done: 'cancel' };
129
+ case 'enter':
130
+ if (state.selected.size === 0 && here) {
131
+ // nothing chosen: run the one under the cursor, which is what a person pressing enter means
132
+ return { state: { ...state, selected: new Set([here.id]) }, done: 'run' };
133
+ }
134
+ if (state.selected.size === 0) {
135
+ return { state: { ...state, hint: 'Nothing matches: press escape to clear the filter' } };
136
+ }
137
+ return { state, done: 'run' };
138
+ default:
139
+ return { state };
140
+ }
141
+ }
142
+
143
+ const paint = (on, code, s) => (on ? `\u001b[${code}m${s}\u001b[0m` : s);
144
+
145
+ /** The lines to draw. `budget` is how many lines the list may take, the titles of groups included. */
146
+ export function render(state, { width = 100, budget = 14, color = true } = {}) {
147
+ const dim = s => paint(color, '2', s);
148
+ const bold = s => paint(color, '1', s);
149
+ const green = s => paint(color, '32', s);
150
+ const yellow = s => paint(color, '33', s);
151
+ const cyan = s => paint(color, '36', s);
152
+ const list = visible(state);
153
+ const lines = [];
154
+
155
+ lines.push(` ${bold('Pick the stories to run')}`);
156
+ lines.push(` ${dim('↑↓ move · space select · a all shown · g whole group · / filter · enter run · q quit')}`);
157
+ if (state.typing || state.filter) {
158
+ lines.push(` ${cyan('filter')} ${state.filter}${state.typing ? dim('▌') : ''}${state.typing ? '' : dim(' (escape clears it)')}`);
159
+ }
160
+ lines.push('');
161
+
162
+ const shown = fitCount(list, state.top, budget);
163
+ const slice = list.slice(state.top, state.top + shown);
164
+ if (!slice.length) {
165
+ lines.push(` ${dim('No story matches')}`);
166
+ }
167
+ let group;
168
+ slice.forEach((s, i) => {
169
+ if (s.group !== group) {
170
+ if (group !== undefined) {
171
+ lines.push('');
172
+ }
173
+ group = s.group;
174
+ const count = list.filter(x => x.group === group).length;
175
+ lines.push(` ${dim(`${(s.groupTitle ?? s.group).toUpperCase()} · ${count}`)}`);
176
+ }
177
+ const index = state.top + i;
178
+ const on = state.selected.has(s.id);
179
+ const needs = s.internal ? 'not checkable from outside' : (s.requires ?? []).join(', ');
180
+ const tags = [s.proposed ? 'proposed' : ''].filter(Boolean).join(', ');
181
+ const right = [needs, tags].filter(Boolean).join(' · ');
182
+ const room = Math.max(12, width - 18 - s.id.length - Math.min(right.length, 30));
183
+ const title = s.title.length > room ? `${s.title.slice(0, room - 1)}…` : s.title;
184
+ const pointer = index === state.cursor ? cyan('❯') : ' ';
185
+ const box = on ? green('◉') : dim('○');
186
+ const text = index === state.cursor ? bold(title) : title;
187
+ lines.push(` ${pointer} ${box} ${bold(s.id.padEnd(5))} ${text}${right ? ` ${dim(right.length > 30 ? `${right.slice(0, 29)}…` : right)}` : ''}`);
188
+ });
189
+
190
+ const above = state.top;
191
+ const below = Math.max(0, list.length - state.top - shown);
192
+ const more = [above ? `↑ ${above} above` : '', below ? `↓ ${below} below` : ''].filter(Boolean).join(' ');
193
+ lines.push('');
194
+ lines.push(` ${state.selected.size ? yellow(`${state.selected.size} selected`) : dim('space selects several · enter runs the one under the arrow')}${more ? ` ${dim(more)}` : ''}`);
195
+ if (state.hint) {
196
+ lines.push(` ${yellow(state.hint)}`);
197
+ }
198
+ return lines;
199
+ }
200
+
201
+ const NAMES = { return: 'enter', escape: 'escape', backspace: 'backspace', up: 'up', down: 'down', pageup: 'pageup', pagedown: 'pagedown', home: 'home', end: 'end', space: 'space' };
202
+
203
+ /** Show the picker and resolve with the ids chosen, or null if the person left. */
204
+ export function pick(stories, { stdin = process.stdin, stdout = process.stdout, preselected = [] } = {}) {
205
+ return new Promise(resolve => {
206
+ const color = !process.env.NO_COLOR;
207
+ // the title, the keys, the filter, two blank lines, the count and a line for the cursor are not the list
208
+ const budgetFor = () => Math.max(8, (stdout.rows || 30) - 9);
209
+ let state = createPicker(stories, { preselected });
210
+ let drawn = 0;
211
+
212
+ const draw = () => {
213
+ const lines = render(state, { width: stdout.columns || 100, budget: budgetFor(), color });
214
+ if (drawn) {
215
+ stdout.write(`\u001b[${drawn}A\r\u001b[J`);
216
+ }
217
+ stdout.write(lines.join('\n') + '\n');
218
+ drawn = lines.length;
219
+ };
220
+
221
+ readline.emitKeypressEvents(stdin);
222
+ stdin.setRawMode(true);
223
+ stdin.resume();
224
+ stdout.write('\u001b[?25l');
225
+
226
+ const finish = result => {
227
+ stdin.off('keypress', onKey);
228
+ stdin.setRawMode(false);
229
+ stdin.pause();
230
+ stdout.write('\u001b[?25h');
231
+ if (drawn) {
232
+ stdout.write(`\u001b[${drawn}A\r\u001b[J`);
233
+ }
234
+ resolve(result);
235
+ };
236
+
237
+ const onKey = (str, key = {}) => {
238
+ const name = key.ctrl && key.name === 'c' ? 'ctrl-c' : NAMES[key.name] ?? (str && str.length === 1 ? str : '');
239
+ if (!name) {
240
+ return;
241
+ }
242
+ const out = reduce(state, name, budgetFor());
243
+ state = out.state;
244
+ if (out.done === 'run') {
245
+ finish([...state.selected]);
246
+ } else if (out.done === 'cancel') {
247
+ finish(null);
248
+ } else {
249
+ draw();
250
+ }
251
+ };
252
+
253
+ stdin.on('keypress', onKey);
254
+ draw();
255
+ });
256
+ }
@@ -0,0 +1,95 @@
1
+ // The welcome screen of `rtc-conformance`: what is shown when it is run with nothing to do. A pure function of the
2
+ // version and whether to use colour, so it is tested without a terminal.
3
+
4
+ // The Jupyter logo as an outline in braille (two crescents and three small circles), drawn by scripts/draw-logo.py:
5
+ // change the geometry there and paste the new rows here. LOGO_COLORS gives the colour of each character: 0 none,
6
+ // 1 the crescents, 2 to 4 the circles.
7
+ const LOGO = [
8
+ '⠀⢠⠒⠒⡄⠀⠀⠀⠀⠀⢀⣀⠤⠤⠤⠤⠤⠤⠤⠤⠤⣀⡀⠀⠀⠀⠀⠀⡠⠒⢄⠀⠀',
9
+ '⠀⠱⣀⣀⠎⠀⢀⠤⠒⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠒⠤⡀⠀⠑⠤⠊⠀⠀',
10
+ '⠀⠀⠀⠀⡠⠊⠁⣀⣀⠤⠤⠤⠒⠒⠒⠒⠒⠒⠒⠒⠒⠤⠤⠤⣀⣀⠈⠑⢄⠀⠀⠀⠀',
11
+ '⠀⠀⢀⠮⠔⠒⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠒⠢⠵⡀⠀⠀',
12
+ '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
13
+ '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
14
+ '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
15
+ '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
16
+ '⠀⠀⠈⢖⠢⠤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠤⠔⡲⠁⠀⠀',
17
+ '⠀⠀⠀⠀⠑⢄⡀⠉⠉⠒⠒⠒⠤⠤⠤⠤⠤⠤⠤⠤⠤⠒⠒⠒⠉⠉⢀⡠⠊⠀⠀⠀⠀',
18
+ '⠀⠀⢠⠒⠒⡄⠈⠒⠤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⠤⠒⠁⠀⠀⠀⠀⠀⠀',
19
+ '⠀⠀⠈⠒⠒⠁⠀⠀⠀⠀⠈⠉⠒⠒⠒⠒⠒⠒⠒⠒⠒⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀'
20
+ ];
21
+ const LOGO_COLORS = [
22
+ '022220000011111111111110000033300',
23
+ '022220111110000000000011111033300',
24
+ '000011111111111111111111111110000',
25
+ '001111100000000000000000001111100',
26
+ '000000000000000000000000000000000',
27
+ '000000000000000000000000000000000',
28
+ '000000000000000000000000000000000',
29
+ '000000000000000000000000000000000',
30
+ '001111100000000000000000001111100',
31
+ '000011111111111111111111111110000',
32
+ '004444111110000000000011111000000',
33
+ '004444000011111111111110000000000'
34
+ ];
35
+
36
+ // the 256-colour palette entries nearest to the colours of the logo
37
+ const COLORS = { 1: 208, 2: 250, 3: 246, 4: 248 };
38
+
39
+ /**
40
+ * The logo as rows of terminal text: in colour, or the same shape without. `labels` puts text inside the arcs: a row
41
+ * number to { text, paint }, centred.
42
+ */
43
+ export function logo({ color = true, labels = {} } = {}) {
44
+ return LOGO.map((row, r) => {
45
+ const cells = [...row].map((ch, c) => {
46
+ const id = +LOGO_COLORS[r][c];
47
+ // an empty braille character is drawn as a space: some fonts draw it as something else
48
+ if (ch === '\u2800') {
49
+ return ' ';
50
+ }
51
+ return color && id ? `\u001b[38;5;${COLORS[id]}m${ch}\u001b[0m` : ch;
52
+ });
53
+ const label = labels[r];
54
+ if (label) {
55
+ const start = Math.floor((cells.length - label.text.length) / 2);
56
+ [...label.text].forEach((ch, i) => (cells[start + i] = color ? label.paint(ch) : ch));
57
+ }
58
+ return cells.join('');
59
+ });
60
+ }
61
+
62
+ /** The lines of the welcome screen. */
63
+ export function welcome({ version, color = true } = {}) {
64
+ const paint = (code, s) => (color ? `\u001b[${code}m${s}\u001b[0m` : s);
65
+ const bold = s => paint('1', s);
66
+ const dim = s => paint('2', s);
67
+
68
+ // the name sits inside the arcs, like a wordmark
69
+ const art = logo({
70
+ color,
71
+ labels: { 5: { text: 'rtc-conformance', paint: bold }, 6: { text: `v${version}`, paint: dim } }
72
+ }).map(row => ` ${row}`);
73
+
74
+ const commands = [
75
+ ['rtc-conformance pick', 'choose stories from a list, then run them'],
76
+ ['rtc-conformance run Z3', 'run one story'],
77
+ ['rtc-conformance list', 'see every story, and what each needs'],
78
+ ['rtc-conformance help', 'everything it can do']
79
+ ];
80
+ const width = Math.max(...commands.map(([c]) => c.length)) + 2;
81
+
82
+ return [
83
+ '',
84
+ ...art,
85
+ '',
86
+ ' Real-time collaboration, held to what people should experience.',
87
+ '',
88
+ ' Plays a notebook backend through the situations people really meet when',
89
+ ' they share a notebook, and tells you which of them it gets right.',
90
+ '',
91
+ ` ${bold('Try one of these')}`,
92
+ ...commands.map(([command, what]) => ` ${bold(command)}${' '.repeat(width - command.length)}${what}`),
93
+ ''
94
+ ];
95
+ }
@@ -0,0 +1,12 @@
1
+ # Known gaps
2
+
3
+ One file per adapter (`<adapter>.json`), listing the accepted stories that backend is known not to meet yet:
4
+
5
+ ```json
6
+ { "C2": "an offline add is lost when the server rebuilds the notebook (jupyter-server-documents#102)" }
7
+ ```
8
+
9
+ A listed story still runs, and is expected to fail (Playwright's `test.fail`). That keeps a run green while the gap is
10
+ open, and turns red the day the story starts passing, as a reminder to delete the entry.
11
+
12
+ This is a fact about a backend. Whether a case is agreed is the story's own `status`.
@@ -0,0 +1 @@
1
+ {}