@operad-io/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The CLI's terminal Markdown renderer now lives in the engine, so the TUI
3
+ * draws the same lines. This module keeps the CLI's import path and names.
4
+ */
5
+
6
+ export {
7
+ renderMarkdown,
8
+ renderMarkdownLines,
9
+ type MarkdownLine,
10
+ type RenderOptions,
11
+ } from "@operad-io/engine";
package/src/qr.ts ADDED
@@ -0,0 +1,405 @@
1
+ /**
2
+ * A QR code encoder for one job: a short link in byte mode, error correction M,
3
+ * versions 1 to 10 (up to 213 bytes). It has no dependency. The layout follows
4
+ * ISO/IEC 18004: finder, timing and alignment patterns, format and version
5
+ * information, the data and its Reed-Solomon codewords interleaved over the
6
+ * blocks, and the mask with the lowest penalty.
7
+ */
8
+
9
+ /** A square of modules; `true` is a dark module. */
10
+ export type QrMatrix = readonly (readonly boolean[])[];
11
+
12
+ /** The text does not fit in version 10 at error correction M. */
13
+ export class QrTooLongError extends Error {
14
+ constructor(bytes: number) {
15
+ super(`the link is ${bytes} bytes; a QR code here holds at most ${MAX_BYTES}`);
16
+ this.name = "QrTooLongError";
17
+ }
18
+ }
19
+
20
+ /** Per version at level M: the check codewords per block and the blocks as [count, data codewords]. */
21
+ const BLOCKS_M: readonly {
22
+ readonly ec: number;
23
+ readonly groups: readonly (readonly [number, number])[];
24
+ }[] = [
25
+ { ec: 10, groups: [[1, 16]] },
26
+ { ec: 16, groups: [[1, 28]] },
27
+ { ec: 26, groups: [[1, 44]] },
28
+ { ec: 18, groups: [[2, 32]] },
29
+ { ec: 24, groups: [[2, 43]] },
30
+ { ec: 16, groups: [[4, 27]] },
31
+ { ec: 18, groups: [[4, 31]] },
32
+ { ec: 22, groups: [[2, 38], [2, 39]] },
33
+ { ec: 22, groups: [[3, 36], [2, 37]] },
34
+ { ec: 26, groups: [[4, 43], [1, 44]] },
35
+ ];
36
+
37
+ /** The centres of the alignment patterns, per version. */
38
+ const ALIGNMENT: readonly (readonly number[])[] = [
39
+ [],
40
+ [6, 18],
41
+ [6, 22],
42
+ [6, 26],
43
+ [6, 30],
44
+ [6, 34],
45
+ [6, 22, 38],
46
+ [6, 24, 42],
47
+ [6, 26, 46],
48
+ [6, 28, 50],
49
+ ];
50
+
51
+ const MAX_VERSION = BLOCKS_M.length;
52
+
53
+ function dataCodewords(version: number): number {
54
+ const blocks = BLOCKS_M[version - 1];
55
+ if (blocks === undefined) throw new RangeError(`no version ${version}`);
56
+ return blocks.groups.reduce((sum, [count, size]) => sum + count * size, 0);
57
+ }
58
+
59
+ function countBits(version: number): number {
60
+ return version < 10 ? 8 : 16;
61
+ }
62
+
63
+ /** The most bytes a version 10 code holds in byte mode at level M. */
64
+ const MAX_BYTES = Math.floor((dataCodewords(MAX_VERSION) * 8 - 4 - 16) / 8);
65
+
66
+ // GF(256) with the QR polynomial x^8 + x^4 + x^3 + x^2 + 1.
67
+ const EXP = new Uint8Array(512);
68
+ const LOG = new Uint8Array(256);
69
+ {
70
+ let value = 1;
71
+ for (let power = 0; power < 255; power += 1) {
72
+ EXP[power] = value;
73
+ LOG[value] = power;
74
+ value <<= 1;
75
+ if (value & 0x100) value ^= 0x11d;
76
+ }
77
+ for (let power = 255; power < 512; power += 1) {
78
+ EXP[power] = EXP[power - 255] ?? 0;
79
+ }
80
+ }
81
+
82
+ function gfMultiply(left: number, right: number): number {
83
+ if (left === 0 || right === 0) return 0;
84
+ return EXP[(LOG[left] ?? 0) + (LOG[right] ?? 0)] ?? 0;
85
+ }
86
+
87
+ function generator(degree: number): number[] {
88
+ let poly = [1];
89
+ for (let root = 0; root < degree; root += 1) {
90
+ const next = new Array<number>(poly.length + 1).fill(0);
91
+ for (let index = 0; index < poly.length; index += 1) {
92
+ const coefficient = poly[index] ?? 0;
93
+ next[index] = (next[index] ?? 0) ^ coefficient;
94
+ next[index + 1] = (next[index + 1] ?? 0) ^ gfMultiply(coefficient, EXP[root] ?? 0);
95
+ }
96
+ poly = next;
97
+ }
98
+ return poly;
99
+ }
100
+
101
+ /** The `degree` Reed-Solomon check codewords of `data`. */
102
+ export function reedSolomon(data: readonly number[], degree: number): number[] {
103
+ const poly = generator(degree);
104
+ const remainder = new Array<number>(degree).fill(0);
105
+ for (const byte of data) {
106
+ const factor = byte ^ (remainder.shift() ?? 0);
107
+ remainder.push(0);
108
+ for (let index = 0; index < degree; index += 1) {
109
+ remainder[index] = (remainder[index] ?? 0) ^ gfMultiply(poly[index + 1] ?? 0, factor);
110
+ }
111
+ }
112
+ return remainder;
113
+ }
114
+
115
+ /** The 15 format bits for level M and a mask, after the BCH code and the XOR mask. */
116
+ export function formatBits(mask: number): number {
117
+ const data = (0b00 << 3) | mask; // level M is 00
118
+ let remainder = data;
119
+ for (let i = 0; i < 10; i += 1) remainder = (remainder << 1) ^ ((remainder >>> 9) * 0x537);
120
+ return ((data << 10) | remainder) ^ 0x5412;
121
+ }
122
+
123
+ /** The 18 version bits (versions 7 and up): the version and its BCH check. */
124
+ export function versionBits(version: number): number {
125
+ let remainder = version;
126
+ for (let i = 0; i < 12; i += 1) remainder = (remainder << 1) ^ ((remainder >>> 11) * 0x1f25);
127
+ return (version << 12) | remainder;
128
+ }
129
+
130
+ function bit(value: number, index: number): boolean {
131
+ return ((value >>> index) & 1) !== 0;
132
+ }
133
+
134
+ /** The codewords of the whole message, data and checks interleaved. */
135
+ function codewordsFor(bytes: Uint8Array, version: number): number[] {
136
+ const blocks = BLOCKS_M[version - 1];
137
+ if (blocks === undefined) throw new RangeError(`no version ${version}`);
138
+ const capacity = dataCodewords(version);
139
+
140
+ const bits: number[] = [];
141
+ const push = (value: number, length: number): void => {
142
+ for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1);
143
+ };
144
+ push(0b0100, 4);
145
+ push(bytes.length, countBits(version));
146
+ for (const byte of bytes) push(byte, 8);
147
+ push(0, Math.min(4, capacity * 8 - bits.length));
148
+ while (bits.length % 8 !== 0) bits.push(0);
149
+
150
+ const data: number[] = [];
151
+ for (let i = 0; i < bits.length; i += 8) {
152
+ let byte = 0;
153
+ for (let j = 0; j < 8; j += 1) byte = (byte << 1) | (bits[i + j] ?? 0);
154
+ data.push(byte);
155
+ }
156
+ for (let pad = 0xec; data.length < capacity; pad ^= 0xec ^ 0x11) data.push(pad);
157
+
158
+ const dataBlocks: number[][] = [];
159
+ let offset = 0;
160
+ for (const [count, size] of blocks.groups) {
161
+ for (let i = 0; i < count; i += 1) {
162
+ dataBlocks.push(data.slice(offset, offset + size));
163
+ offset += size;
164
+ }
165
+ }
166
+ const checkBlocks = dataBlocks.map((block) => reedSolomon(block, blocks.ec));
167
+
168
+ const result: number[] = [];
169
+ const longest = Math.max(...dataBlocks.map((block) => block.length));
170
+ for (let i = 0; i < longest; i += 1) {
171
+ for (const block of dataBlocks) {
172
+ const value = block[i];
173
+ if (value !== undefined) result.push(value);
174
+ }
175
+ }
176
+ for (let i = 0; i < blocks.ec; i += 1) {
177
+ for (const block of checkBlocks) result.push(block[i] ?? 0);
178
+ }
179
+ return result;
180
+ }
181
+
182
+ class Grid {
183
+ readonly size: number;
184
+ readonly modules: boolean[][];
185
+ readonly reserved: boolean[][];
186
+
187
+ constructor(readonly version: number) {
188
+ this.size = version * 4 + 17;
189
+ this.modules = Array.from({ length: this.size }, () => new Array<boolean>(this.size).fill(false));
190
+ this.reserved = Array.from({ length: this.size }, () => new Array<boolean>(this.size).fill(false));
191
+ }
192
+
193
+ set(x: number, y: number, dark: boolean): void {
194
+ const row = this.modules[y];
195
+ const mark = this.reserved[y];
196
+ if (row === undefined || mark === undefined || x < 0 || x >= this.size) return;
197
+ row[x] = dark;
198
+ mark[x] = true;
199
+ }
200
+
201
+ get(x: number, y: number): boolean {
202
+ return this.modules[y]?.[x] ?? false;
203
+ }
204
+
205
+ finder(cx: number, cy: number): void {
206
+ for (let dy = -4; dy <= 4; dy += 1) {
207
+ for (let dx = -4; dx <= 4; dx += 1) {
208
+ const distance = Math.max(Math.abs(dx), Math.abs(dy));
209
+ this.set(cx + dx, cy + dy, distance !== 2 && distance !== 4);
210
+ }
211
+ }
212
+ }
213
+
214
+ alignment(cx: number, cy: number): void {
215
+ for (let dy = -2; dy <= 2; dy += 1) {
216
+ for (let dx = -2; dx <= 2; dx += 1) {
217
+ this.set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
218
+ }
219
+ }
220
+ }
221
+
222
+ drawFunctionPatterns(): void {
223
+ const size = this.size;
224
+ for (let i = 0; i < size; i += 1) {
225
+ this.set(6, i, i % 2 === 0);
226
+ this.set(i, 6, i % 2 === 0);
227
+ }
228
+ this.finder(3, 3);
229
+ this.finder(size - 4, 3);
230
+ this.finder(3, size - 4);
231
+ const centres = ALIGNMENT[this.version - 1] ?? [];
232
+ const last = centres.length - 1;
233
+ for (let i = 0; i < centres.length; i += 1) {
234
+ for (let j = 0; j < centres.length; j += 1) {
235
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) continue;
236
+ this.alignment(centres[i] ?? 0, centres[j] ?? 0);
237
+ }
238
+ }
239
+ this.drawFormat(0);
240
+ if (this.version >= 7) {
241
+ const bits = versionBits(this.version);
242
+ for (let i = 0; i < 18; i += 1) {
243
+ const a = size - 11 + (i % 3);
244
+ const b = Math.floor(i / 3);
245
+ this.set(a, b, bit(bits, i));
246
+ this.set(b, a, bit(bits, i));
247
+ }
248
+ }
249
+ }
250
+
251
+ drawFormat(mask: number): void {
252
+ const size = this.size;
253
+ const bits = formatBits(mask);
254
+ for (let i = 0; i <= 5; i += 1) this.set(8, i, bit(bits, i));
255
+ this.set(8, 7, bit(bits, 6));
256
+ this.set(8, 8, bit(bits, 7));
257
+ this.set(7, 8, bit(bits, 8));
258
+ for (let i = 9; i < 15; i += 1) this.set(14 - i, 8, bit(bits, i));
259
+ for (let i = 0; i < 8; i += 1) this.set(size - 1 - i, 8, bit(bits, i));
260
+ for (let i = 8; i < 15; i += 1) this.set(8, size - 15 + i, bit(bits, i));
261
+ this.set(8, size - 8, true);
262
+ }
263
+
264
+ drawCodewords(codewords: readonly number[]): void {
265
+ const size = this.size;
266
+ let index = 0;
267
+ for (let right = size - 1; right >= 1; right -= 2) {
268
+ if (right === 6) right = 5;
269
+ for (let vertical = 0; vertical < size; vertical += 1) {
270
+ for (let j = 0; j < 2; j += 1) {
271
+ const x = right - j;
272
+ const upward = ((right + 1) & 2) === 0;
273
+ const y = upward ? size - 1 - vertical : vertical;
274
+ if (this.reserved[y]?.[x] === true) continue;
275
+ const word = codewords[index >>> 3];
276
+ const dark = word !== undefined && bit(word, 7 - (index & 7));
277
+ const row = this.modules[y];
278
+ if (row !== undefined) row[x] = dark;
279
+ index += 1;
280
+ }
281
+ }
282
+ }
283
+ }
284
+
285
+ applyMask(mask: number): void {
286
+ for (let y = 0; y < this.size; y += 1) {
287
+ for (let x = 0; x < this.size; x += 1) {
288
+ if (this.reserved[y]?.[x] === true) continue;
289
+ let invert: boolean;
290
+ switch (mask) {
291
+ case 0: invert = (x + y) % 2 === 0; break;
292
+ case 1: invert = y % 2 === 0; break;
293
+ case 2: invert = x % 3 === 0; break;
294
+ case 3: invert = (x + y) % 3 === 0; break;
295
+ case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; break;
296
+ case 5: invert = ((x * y) % 2) + ((x * y) % 3) === 0; break;
297
+ case 6: invert = (((x * y) % 2) + ((x * y) % 3)) % 2 === 0; break;
298
+ default: invert = (((x + y) % 2) + ((x * y) % 3)) % 2 === 0; break;
299
+ }
300
+ const row = this.modules[y];
301
+ if (invert && row !== undefined) row[x] = !row[x];
302
+ }
303
+ }
304
+ }
305
+
306
+ penalty(): number {
307
+ const size = this.size;
308
+ let total = 0;
309
+ const lines: boolean[][] = [];
310
+ for (let y = 0; y < size; y += 1) lines.push(this.modules[y] ?? []);
311
+ for (let x = 0; x < size; x += 1) {
312
+ lines.push(Array.from({ length: size }, (_, y) => this.get(x, y)));
313
+ }
314
+ // Rules 1 and 3 on every row and column.
315
+ for (const line of lines) {
316
+ let run = 1;
317
+ for (let i = 1; i <= size; i += 1) {
318
+ if (i < size && line[i] === line[i - 1]) {
319
+ run += 1;
320
+ } else {
321
+ if (run >= 5) total += 3 + (run - 5);
322
+ run = 1;
323
+ }
324
+ }
325
+ const text = line.map((dark) => (dark ? "1" : "0")).join("");
326
+ for (const pattern of ["10111010000", "00001011101"]) {
327
+ let at = text.indexOf(pattern);
328
+ while (at >= 0) {
329
+ total += 40;
330
+ at = text.indexOf(pattern, at + 1);
331
+ }
332
+ }
333
+ }
334
+ // Rule 2: 2 by 2 blocks of one colour.
335
+ for (let y = 0; y < size - 1; y += 1) {
336
+ for (let x = 0; x < size - 1; x += 1) {
337
+ const colour = this.get(x, y);
338
+ if (colour === this.get(x + 1, y) && colour === this.get(x, y + 1) && colour === this.get(x + 1, y + 1)) {
339
+ total += 3;
340
+ }
341
+ }
342
+ }
343
+ // Rule 4: the share of dark modules.
344
+ let dark = 0;
345
+ for (const row of this.modules) for (const module of row) if (module) dark += 1;
346
+ const cells = size * size;
347
+ total += (Math.ceil(Math.abs(dark * 20 - cells * 10) / cells) - 1) * 10;
348
+ return total;
349
+ }
350
+ }
351
+
352
+ /** Encodes `text` as UTF-8 bytes in a QR code at level M, the smallest version that fits. */
353
+ export function encodeQr(text: string): QrMatrix {
354
+ const bytes = new TextEncoder().encode(text);
355
+ let version = 1;
356
+ while (
357
+ version <= MAX_VERSION &&
358
+ 4 + countBits(version) + bytes.length * 8 > dataCodewords(version) * 8
359
+ ) {
360
+ version += 1;
361
+ }
362
+ if (version > MAX_VERSION) throw new QrTooLongError(bytes.length);
363
+
364
+ const grid = new Grid(version);
365
+ grid.drawFunctionPatterns();
366
+ grid.drawCodewords(codewordsFor(bytes, version));
367
+
368
+ let best = 0;
369
+ let lowest = Number.POSITIVE_INFINITY;
370
+ for (let mask = 0; mask < 8; mask += 1) {
371
+ grid.applyMask(mask);
372
+ grid.drawFormat(mask);
373
+ const score = grid.penalty();
374
+ if (score < lowest) {
375
+ lowest = score;
376
+ best = mask;
377
+ }
378
+ grid.applyMask(mask);
379
+ }
380
+ grid.applyMask(best);
381
+ grid.drawFormat(best);
382
+ return grid.modules.map((row) => [...row]);
383
+ }
384
+
385
+ /**
386
+ * The matrix as terminal text: two module rows per line in half blocks, black
387
+ * on white with a quiet zone of four modules, so a phone reads it on a dark
388
+ * terminal too.
389
+ */
390
+ export function renderQr(matrix: QrMatrix, quiet = 4): string {
391
+ const size = matrix.length;
392
+ const at = (x: number, y: number): boolean => matrix[y - quiet]?.[x - quiet] === true;
393
+ const total = size + quiet * 2;
394
+ const lines: string[] = [];
395
+ for (let y = 0; y < total; y += 2) {
396
+ let line = "";
397
+ for (let x = 0; x < total; x += 1) {
398
+ const top = at(x, y);
399
+ const bottom = at(x, y + 1);
400
+ line += top ? (bottom ? "█" : "▀") : bottom ? "▄" : " ";
401
+ }
402
+ lines.push(`\u001b[30;47m${line}\u001b[0m`);
403
+ }
404
+ return `${lines.join("\n")}\n`;
405
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `operad serve stop`: stops the `serve` that holds this home's `serve.lock`.
3
+ *
4
+ * The lock names a PID, and a PID can be reused after `serve` died without
5
+ * releasing it. So before it signals, the command asks the OS for that
6
+ * process's command line (`ps -p <pid> -o command=`, the same on macOS and
7
+ * Linux) and signals only a process whose command line has `serve` as a word.
8
+ * It sends SIGTERM, the stop `serve` already handles, and never SIGKILL.
9
+ */
10
+
11
+ import { StateError, pidAlive, readLockPid, serveLockPath } from "@operad-io/engine";
12
+ import { existsSync } from "node:fs";
13
+
14
+ export const DEFAULT_STOP_TIMEOUT_SECS = 30;
15
+ const COMMAND_ASKS = 20;
16
+ const COMMAND_ASK_WAIT_MS = 50;
17
+
18
+ export interface ServeStopOptions {
19
+ readonly home: string;
20
+ readonly timeoutSecs: number;
21
+ readonly write: (text: string) => void;
22
+ /** Test hooks. */
23
+ readonly isAlive?: ((pid: number) => boolean) | undefined;
24
+ readonly commandOf?: ((pid: number) => string | undefined) | undefined;
25
+ readonly signal?: ((pid: number) => void) | undefined;
26
+ readonly sleep?: ((ms: number) => Promise<void>) | undefined;
27
+ readonly clock?: (() => number) | undefined;
28
+ }
29
+
30
+ /** The command line of a process, or undefined when `ps` cannot say. */
31
+ export function processCommand(pid: number): string | undefined {
32
+ const result = Bun.spawnSync({
33
+ cmd: ["ps", "-p", String(pid), "-o", "command="],
34
+ stdout: "pipe",
35
+ stderr: "ignore",
36
+ });
37
+ if (result.exitCode !== 0) return undefined;
38
+ const text = result.stdout.toString().trim();
39
+ return text.length > 0 ? text : undefined;
40
+ }
41
+
42
+ /** True when the command line has `serve` as a word of its own. */
43
+ export function isServeCommand(command: string): boolean {
44
+ return /(^|\s)serve(\s|$)/.test(command);
45
+ }
46
+
47
+ /** Parses `--timeout <secs>`: a whole number of at least 1. */
48
+ export function parseStopTimeout(value: string): number {
49
+ if (!/^\d+$/.test(value) || Number(value) < 1) {
50
+ throw new RangeError(
51
+ `serve stop --timeout needs a whole number of seconds, at least 1, got "${value}"`,
52
+ );
53
+ }
54
+ return Number(value);
55
+ }
56
+
57
+ export async function serveStop(options: ServeStopOptions): Promise<void> {
58
+ const path = serveLockPath(options.home);
59
+ const isAlive = options.isAlive ?? pidAlive;
60
+ const pid = readLockPid(path);
61
+ if (pid === undefined || !isAlive(pid)) {
62
+ options.write(`no operad serve runs for ${options.home}\n`);
63
+ return;
64
+ }
65
+
66
+ const sleep =
67
+ options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
68
+ const commandOf = options.commandOf ?? processCommand;
69
+ // `ps` under load can answer nothing for a live process (exit 0 with empty
70
+ // output, seen in T-0108), so "cannot say" is asked again a few times while
71
+ // the process lives. A command line that is not a serve is final.
72
+ let command = commandOf(pid);
73
+ for (let ask = 1; command === undefined && ask < COMMAND_ASKS && isAlive(pid); ask += 1) {
74
+ await sleep(COMMAND_ASK_WAIT_MS);
75
+ command = commandOf(pid);
76
+ }
77
+ if (command === undefined && !isAlive(pid)) {
78
+ options.write(`no operad serve runs for ${options.home}\n`);
79
+ return;
80
+ }
81
+ if (command === undefined) {
82
+ throw new StateError(
83
+ `process ${pid} holds ${path} but ps could not say what it is; nothing was signalled`,
84
+ );
85
+ }
86
+ if (!isServeCommand(command)) {
87
+ throw new StateError(
88
+ `process ${pid} holds ${path} but is not an operad serve; nothing was signalled`,
89
+ );
90
+ }
91
+
92
+ (options.signal ?? ((target) => process.kill(target, "SIGTERM")))(pid);
93
+ options.write(`stopping operad serve (pid ${pid})\n`);
94
+
95
+ const clock = options.clock ?? (() => Date.now());
96
+ const deadline = clock() + options.timeoutSecs * 1_000;
97
+ for (;;) {
98
+ if (!isAlive(pid) || !existsSync(path)) {
99
+ options.write("stopped\n");
100
+ return;
101
+ }
102
+ if (clock() >= deadline) break;
103
+ await sleep(50);
104
+ }
105
+ throw new StateError(
106
+ `operad serve (pid ${pid}) did not stop within ${options.timeoutSecs} seconds; to force it: kill -9 ${pid}`,
107
+ );
108
+ }