flagstaff 1.7.5 → 1.8.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.
package/README.md CHANGED
@@ -29,7 +29,7 @@
29
29
  <a href="https://burgee.interlace.tools/docs/compatibility"><img src="https://img.shields.io/badge/boxen%20suite-213%2F213-0a6b47?style=flat-square" alt="flagstaff/boxen passes 213 of 213 cases of the boxen test suite" /></a>
30
30
  <a href="https://burgee.interlace.tools/docs/compatibility"><img src="https://img.shields.io/badge/cli--table3%20suite-29%2F29-0a6b47?style=flat-square" alt="flagstaff/cli-table3 passes 29 of 29 cases of the cli-table3 test suite" /></a>
31
31
  <a href="https://burgee.interlace.tools/docs/compatibility"><img src="https://img.shields.io/badge/log--update%20suite-99%2F99-0a6b47?style=flat-square" alt="flagstaff/log-update passes 99 of 99 cases of the log-update test suite" /></a>
32
- <a href="https://burgee.interlace.tools/docs/compatibility"><img src="https://img.shields.io/badge/ora%20suite-99%2F99-0a6b47?style=flat-square" alt="flagstaff/ora passes 99 of 99 cases of the ora test suite" /></a>
32
+ <a href="https://burgee.interlace.tools/docs/compatibility"><img src="https://img.shields.io/badge/ora%20suite-223%2F223-0a6b47?style=flat-square" alt="flagstaff/ora passes 223 of 223 cases of the ora test suite" /></a>
33
33
  </p>
34
34
 
35
35
  <p align="center">
@@ -342,7 +342,7 @@ the change ([Migrate](https://burgee.interlace.tools/docs/migrate)).
342
342
 
343
343
  ### The ora path
344
344
 
345
- `flagstaff/ora` is ora 9's whole API, graded **99 / 99 by ora's own test suite** through
345
+ `flagstaff/ora` is ora 10's whole API, graded **223 / 223 by ora's own test suite** through
346
346
  [`compat-oracle`](https://github.com/ofri-peretz/burgee/blob/main/packages/compat-oracle/README.md). One import changes:
347
347
 
348
348
  ```diff
@@ -353,22 +353,21 @@ the change ([Migrate](https://burgee.interlace.tools/docs/migrate)).
353
353
  Everything else stays: `ora({ text, spinner, color, indent, prefixText, suffixText })`,
354
354
  `.start() .stop() .succeed() .fail() .warn() .info() .stopAndPersist()`, `oraPromise()`,
355
355
  the `spinners` corpus, the stream hooks that keep a `console.log` above the frame, the
356
- synchronized-output sequences, the render deferral, the stdin discarder.
356
+ synchronized-output sequences, the pause while another writer's line is unfinished, the frame
357
+ kept above the last row of the screen, the stdin discarder.
357
358
 
358
- What changes is the bill. ora 9.4.1 ships 114,102 B of JavaScript across **seventeen
359
+ What changes is the bill. ora 10.0.0 ships 128,182 B of JavaScript across **seventeen
359
360
  packages** — ora, chalk, cli-spinners, string-width, log-symbols, cli-cursor,
360
361
  restore-cursor, onetime, mimic-function, signal-exit, is-interactive, is-unicode-supported,
361
362
  stdin-discarder, yoctocolors, strip-ansi, ansi-regex, get-east-asian-width. `flagstaff/ora`
362
- is 55,641 B across **two** — itself and roundel — **49% of ora's**, and 20,250 B of that is
363
+ is 53,486 B across **two** — itself and roundel — **42% of ora's**, and 20,250 B of that is
363
364
  the spinner corpus ora's API re-exports. Nothing in it reaches the frame loop, so a program
364
365
  that migrates its spinner today can adopt `hoist()` a file at a time, or never ([measured](https://burgee.interlace.tools/docs/benchmarks)).
365
366
 
366
367
  Both sides are counted the same way, so the number reproduces: shipped code and data —
367
368
  `.js`/`.mjs`/`.cjs` plus the `.json` a module imports, `package.json` never counted. Ours is
368
369
  the import graph walked from `dist/` by `weight.test.ts`; ora's is every package that graph
369
- touches in ora's own resolved tree, counted whole. Counting ora the stricter way — only the
370
- 27 files its graph actually reaches — gives 101,809 B, and `flagstaff/ora` is still 55% of
371
- that ([measured](https://burgee.interlace.tools/docs/benchmarks)).
370
+ touches in ora's own resolved tree, counted whole ([measured](https://burgee.interlace.tools/docs/benchmarks)).
372
371
 
373
372
  The cursor comes back the way ora's does. A spinner that hid the cursor restores it on a
374
373
  clean exit **and** on `SIGINT`, `SIGTERM` and `SIGHUP` — node does not run `'exit'`
@@ -404,7 +403,7 @@ screen, not the bytes.
404
403
  `logUpdateStderr`, with the row-level diffing intact: a five-row frame whose last row is a
405
404
  counter costs one row of output per tick, not five.
406
405
 
407
- log-update ships 113.4 KB across **sixteen** packages. This subpath reaches two, both from
406
+ log-update ships 114.3 KB across **sixteen** packages. This subpath reaches two, both from
408
407
  this repository: `linegauge/wrap` for the wrapper, and `closeout` for the cursor.
409
408
  It carries no port of `slice-ansi` — the wrapper already makes every row self-contained,
410
409
  so clipping a frame to the terminal's height is an array slice. `signal-exit`, 22.0 KB of
@@ -486,10 +485,10 @@ path instead. The current grades are generated under *Benchmarks* below and publ
486
485
  Every subpath is a lock, not a convention, and the numbers below are asserted by
487
486
  `weight.test.ts` against `dist/`, not estimated: `flagstaff/loop` reaches 4.4 KB on disk and
488
487
  never the plugin registry; `flagstaff/plugin` 8.4 KB, of which 2.4 KB is the schema;
489
- `flagstaff/spinner` 9.4 KB; `flagstaff/ora` 46.5 KB — 55.9 KB with roundel counted, against
490
- ora's own 113.6 KB; `flagstaff/log-update` 29.6 KB, against
491
- log-update's own 113.4 KB across sixteen, reaching only `linegauge/wrap` and `closeout`; `flagstaff/boxen` 17.6 KB — 67.8 KB with linegauge and
492
- roundel counted, against boxen 9's own 114.9 KB across fourteen; `flagstaff/cli-table3` 32.9 KB —
488
+ `flagstaff/spinner` 9.4 KB; `flagstaff/ora` 44.1 KB — 53.5 KB with roundel counted, against
489
+ ora 10's own 128.2 KB; `flagstaff/log-update` 29.6 KB, against
490
+ log-update's own 114.3 KB across sixteen, reaching only `linegauge/wrap` and `closeout`; `flagstaff/boxen` 17.6 KB — 67.8 KB with linegauge and
491
+ roundel counted, against boxen 9's own 115.8 KB across fourteen; `flagstaff/cli-table3` 32.9 KB —
493
492
  42.3 KB with roundel, against cli-table3's own 106.0 KB across seven. The three façades share `wrap.js` and
494
493
  `width.js`, and the first two share `closeout`; none reaches another's port, and none
495
494
  reaches the core. `sideEffects: false` lets a
@@ -507,7 +506,7 @@ Graded by the incumbent's own test suite:
507
506
  | `boxen` | 213 / 213 |
508
507
  | `cli-table3` | 29 / 29 |
509
508
  | `log-update` | 99 / 99 |
510
- | `ora` | 99 / 99 |
509
+ | `ora` | 223 / 223 |
511
510
 
512
511
  ## For agents
513
512
 
@@ -551,13 +550,14 @@ Plugins register under the `tokens`, `glyphs`, `spinners`, `borders`, `component
551
550
 
552
551
  ## The family
553
552
 
554
- Ten packages, one repository, one release pipeline. Each installs and works on its own, and each
553
+ Eleven packages, one repository, one release pipeline. Each installs and works on its own, and each
555
554
  owns one job. Six of them — `bellpull`, `closeout`, `linegauge`, `paratext`, `roundel`, `seniority`
556
555
  — depend on nothing; the others depend only on packages in this table, and every dependency points
557
556
  one way, down the [layers](https://burgee.interlace.tools/docs/concepts/family).
558
557
 
559
558
  No package declares a dependency from outside the family; `react` and `react-reconciler` are
560
- optional peers of `controlroom`, which npm does not install.
559
+ optional peers of `controlroom`, which npm does not install; `vitest` is an optional peer of
560
+ `oxmutate`, which npm does not install.
561
561
  [`package-shape-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/package-shape-lock.test.ts)
562
562
  holds that for every manifest, and
563
563
  [`independence-install-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/independence-install-lock.test.ts)
@@ -580,6 +580,7 @@ keeps both true.
580
580
  | [closeout](https://closeout.interlace.tools/docs) | Exit handlers, terminal restore and a bounded shutdown | signal-exit, exit-hook, restore-cursor, cli-cursor and onetime |
581
581
  | [bellpull](https://bellpull.interlace.tools/docs) | Subprocesses, and which executable actually ran | cross-spawn and which |
582
582
  | [controlroom](https://controlroom.interlace.tools/docs) | Keyboard-driven terminal screens, inline or full-screen | ink |
583
+ | [oxmutate](https://oxmutate.interlace.tools/docs) | Mutation testing on the oxc engine, inside your own Vitest | Stryker |
583
584
 
584
585
  Every migration guide, and the family-wide [compatibility](https://burgee.interlace.tools/docs/compatibility)
585
586
  and [benchmarks](https://burgee.interlace.tools/docs/benchmarks) pages, are on
package/dist/box.js CHANGED
@@ -26,14 +26,11 @@ function fitTitle(title, cells) {
26
26
  function topBorder(style, inner, title) {
27
27
  if (style.top === '')
28
28
  return '';
29
- if (title === undefined || title === '')
30
- return style.topLeft + style.top.repeat(inner) + style.topRight;
31
- const fitted = fitTitle(title, Math.max(0, inner - BORDER_CELLS - BORDER_CELLS));
29
+ const fitted = fitTitle(title ?? '', Math.max(0, inner - BORDER_CELLS - BORDER_CELLS));
32
30
  if (fitted === '')
33
31
  return style.topLeft + style.top.repeat(inner) + style.topRight;
34
32
  const label = ` ${fitted} `;
35
- const rest = Math.max(0, inner - width(label) - 1);
36
- return `${style.topLeft}${style.top}${label}${style.top.repeat(rest)}${style.topRight}`;
33
+ return `${style.topLeft}${style.top}${label}${style.top.repeat(inner - width(label) - 1)}${style.topRight}`;
37
34
  }
38
35
  export function box(text, options = {}) {
39
36
  const style = resolve(options.border ?? 'round');
package/dist/conforms.js CHANGED
@@ -7,25 +7,28 @@ function typeOf(value) {
7
7
  return Number.isInteger(value) ? 'integer' : 'number';
8
8
  return typeof value;
9
9
  }
10
+ function checkString(value, node, path) {
11
+ if (value.length < (node.minLength ?? 0))
12
+ return `${path}: must not be empty`;
13
+ if (!new RegExp(node.pattern ?? '').test(value))
14
+ return `${path}: ${JSON.stringify(value)} does not match ${String(node.pattern)}`;
15
+ return undefined;
16
+ }
10
17
  function checkScalar(value, node, path) {
11
18
  if (node.const !== undefined && value !== node.const)
12
19
  return `${path}: expected ${JSON.stringify(node.const)}, got ${JSON.stringify(value)}`;
13
20
  if (node.enum !== undefined && !node.enum.includes(value))
14
21
  return `${path}: not one of ${JSON.stringify(node.enum)}`;
15
- if (typeof value === 'string') {
16
- if (node.minLength !== undefined && value.length < node.minLength)
17
- return `${path}: must not be empty`;
18
- if (node.pattern !== undefined && !new RegExp(node.pattern).test(value))
19
- return `${path}: ${JSON.stringify(value)} does not match ${node.pattern}`;
20
- }
21
- if (typeof value === 'number' && node.minimum !== undefined && value < node.minimum)
22
- return `${path}: must be at least ${node.minimum}`;
23
- if (typeof value === 'number' && node.maximum !== undefined && value > node.maximum)
24
- return `${path}: must be at most ${node.maximum}`;
22
+ if (typeof value === 'string')
23
+ return checkString(value, node, path);
24
+ if (typeof value === 'number' && value < (node.minimum ?? -Infinity))
25
+ return `${path}: must be at least ${String(node.minimum)}`;
26
+ if (typeof value === 'number' && value > (node.maximum ?? Infinity))
27
+ return `${path}: must be at most ${String(node.maximum)}`;
25
28
  return undefined;
26
29
  }
27
30
  function checkArray(value, node, path, root) {
28
- if (node.minItems !== undefined && value.length < node.minItems)
31
+ if (value.length < (node.minItems ?? 0))
29
32
  return `${path}: needs at least ${node.minItems} item(s)`;
30
33
  const { items } = node;
31
34
  if (items === undefined)
@@ -38,13 +41,20 @@ function checkArray(value, node, path, root) {
38
41
  return undefined;
39
42
  }
40
43
  const isSchema = (x) => typeof x === 'object' && x !== null;
44
+ const present = (record, key) => Object.hasOwn(record, key) || (Reflect.has(record, key) && !Reflect.has(Object.prototype, key));
45
+ function ruleFor(node, key) {
46
+ const { properties = {}, additionalProperties } = node;
47
+ if (Object.hasOwn(properties, key))
48
+ return properties[key];
49
+ return isSchema(additionalProperties) ? additionalProperties : undefined;
50
+ }
41
51
  function checkObject(record, node, path, root) {
42
52
  for (const key of node.required ?? []) {
43
- if (!(key in record))
53
+ if (!present(record, key))
44
54
  return `${path}.${key}: required`;
45
55
  }
46
56
  for (const [key, child] of Object.entries(record)) {
47
- const rule = node.properties?.[key] ?? (isSchema(node.additionalProperties) ? node.additionalProperties : undefined);
57
+ const rule = ruleFor(node, key);
48
58
  if (rule === undefined) {
49
59
  if (node.additionalProperties === false)
50
60
  return `${path}.${key}: not allowed`;
package/dist/link.d.ts CHANGED
@@ -45,6 +45,7 @@ export interface Linked {
45
45
  /** A table cell: text, or text with somewhere to go. A plain string stays a plain string. */
46
46
  export type Cell = string | Linked;
47
47
  export declare const cellText: (cell: Cell | undefined) => string;
48
+ /** A plain string has no `href`, so reading one off it is the `undefined` a plain cell means. */
48
49
  export declare const cellHref: (cell: Cell | undefined) => string | undefined;
49
50
  /**
50
51
  * What the content reads as **before** the drawing measures it: the bare text where the
package/dist/link.js CHANGED
@@ -10,11 +10,9 @@ export function painter(terminal) {
10
10
  return { live: supportsLink(runtime), paint: linkFor(runtime) };
11
11
  }
12
12
  export const cellText = (cell) => (typeof cell === 'string' ? cell : (cell?.text ?? ''));
13
- export const cellHref = (cell) => (typeof cell === 'string' || cell === undefined ? undefined : cell.href);
13
+ export const cellHref = (cell) => cell?.href;
14
14
  export function laid(text, href, painted) {
15
- if (href === undefined || href === '')
16
- return text;
17
- return painted.live ? text : painted.paint(text, href);
15
+ return painted.live ? text : painted.paint(text, href ?? '');
18
16
  }
19
17
  export function painted(line, href, painter_) {
20
18
  if (!painter_.live || href === undefined || href === '' || line === '')
package/dist/log-tail.js CHANGED
@@ -20,8 +20,11 @@ export function logTail({ height = HEIGHT } = {}) {
20
20
  frame: (_t, { lines }) => {
21
21
  const current = lines.findLastIndex((entry) => typeof entry !== 'string');
22
22
  let window = [];
23
- for (let i = lines.length - 1; i >= 0 && window.length < shown; i -= 1)
23
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
24
+ if (window.length >= shown)
25
+ break;
24
26
  window = [...rows(lines[i], i === current), ...window];
27
+ }
25
28
  window = window.slice(-shown);
26
29
  if (current >= 0 && !window.some((row) => row.current))
27
30
  window = [...rows(lines[current], true).slice(0, 1), ...window.slice(window.length - (shown - 1))];
package/dist/loop.js CHANGED
@@ -35,19 +35,18 @@ export function hoist(component, rt, initial, opts = {}) {
35
35
  }
36
36
  const TICK_CAP = 1000;
37
37
  function nextDue(timers, until) {
38
- return timers.filter((t) => t.at <= until).sort((a, b) => a.at - b.at || a.id - b.id)[0];
38
+ return timers.filter((t) => t.at <= until).sort((a, b) => a.at - b.at)[0];
39
39
  }
40
40
  export function manualClock(start = 0) {
41
41
  let now = start;
42
- let nextId = 0;
43
42
  let timers = [];
44
43
  return {
45
44
  now: () => now,
46
45
  schedule(fn, ms) {
47
- const id = nextId++;
48
- timers.push({ id, at: now + Math.max(0, ms), fn });
46
+ const timer = { at: now + Math.max(0, ms), fn };
47
+ timers.push(timer);
49
48
  return () => {
50
- timers = timers.filter((t) => t.id !== id);
49
+ timers = timers.filter((t) => t !== timer);
51
50
  };
52
51
  },
53
52
  tick(ms) {
@@ -55,10 +54,10 @@ export function manualClock(start = 0) {
55
54
  let ran = 0;
56
55
  let due = nextDue(timers, until);
57
56
  while (due !== undefined && ran < TICK_CAP) {
58
- const { id, at, fn } = due;
59
- timers = timers.filter((t) => t.id !== id);
60
- now = Math.max(now, at);
61
- fn();
57
+ const timer = due;
58
+ timers = timers.filter((t) => t !== timer);
59
+ now = Math.max(now, timer.at);
60
+ timer.fn();
62
61
  ran += 1;
63
62
  due = nextDue(timers, until);
64
63
  }
package/dist/markdown.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { command, heading, muted, value } from 'roundel/tokens';
2
- const FENCE = /^ {0,3}(`{3,}|~{3,})/;
2
+ const FENCE = /^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/;
3
3
  const HEADING = /^ {0,3}#{1,6}(?=[ \t]|$)/;
4
4
  const BLANK = /^[ \t]*$/;
5
5
  const ITEM = /^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]/;
@@ -47,7 +47,7 @@ class Splitter {
47
47
  return;
48
48
  }
49
49
  this.commit();
50
- const opened = { kind, lines: [], end, fence: FENCE.exec(line)?.[1] ?? '' };
50
+ const opened = { kind, lines: [], end, fence: FENCE.exec(line)?.[1] };
51
51
  this.#open = opened;
52
52
  extend(opened, line, end);
53
53
  if (kind === 'heading')
@@ -90,14 +90,15 @@ function inline(line) {
90
90
  }
91
91
  return drawn + line.slice(at);
92
92
  }
93
+ const CLOSING = /[ \t]#+[ \t]*$/;
93
94
  function draw(block) {
94
95
  if (block.kind === 'heading')
95
- return styled(heading, block.source.slice(HEADING.exec(block.source)[0].length).trim(), block.source);
96
+ return styled(heading, block.source.slice(HEADING.exec(block.source)[0].length).replace(CLOSING, '').trim(), block.source);
96
97
  const lines = block.source.split('\n');
97
98
  if (block.kind !== 'code')
98
99
  return lines.map(inline).join('\n');
99
- const fence = FENCE.exec(block.source)[1];
100
- return lines.map((line, i) => (i === 0 || (i === lines.length - 1 && closes(line, fence)) ? muted(line) : command(line))).join('\n');
100
+ const fence = FENCE.exec(lines[0])[1];
101
+ return lines.map((line, i) => (i === 0 || closes(line, fence) ? muted(line) : command(line))).join('\n');
101
102
  }
102
103
  export function markdown() {
103
104
  return {
package/dist/ora.d.ts CHANGED
@@ -71,6 +71,12 @@ export declare class Ora {
71
71
  set isSilent(value: boolean);
72
72
  frame(): string;
73
73
  clear(): this;
74
+ /**
75
+ * A stream without the readline cursor methods — a CI log stream that reports a TTY — gets
76
+ * the frame written where the cursor is. Unfinished external output is left alone until its
77
+ * newline, with no timeout: resized rows cannot be counted reliably, and a replay would
78
+ * duplicate rows already in scrollback.
79
+ */
74
80
  render(): this;
75
81
  start(text?: string): this;
76
82
  stop(): this;
@@ -78,8 +84,13 @@ export declare class Ora {
78
84
  fail(text?: string): this;
79
85
  warn(text?: string): this;
80
86
  info(text?: string): this;
81
- stopAndPersist(options?: PersistOptions): this;
87
+ stopAndPersist(options?: PersistOptions | null): this;
82
88
  }
83
89
  export default function ora(options?: Options | string): Ora;
84
- /** Run an action under a spinner, and land on the right symbol whichever way it ends. */
85
- export declare function oraPromise<T>(action: Promise<T> | ((spinner: Ora) => Promise<T>), options?: PromiseOptions<T> | string): Promise<T>;
90
+ /**
91
+ * Run an action under a spinner, and land on the right symbol whichever way it ends. The
92
+ * action's own outcome wins: a `failText` that throws, or a persist the stream cannot write,
93
+ * never replaces the action's error, and a persist that fails never discards its result. A
94
+ * `successText` that throws is the caller's error and is not drawn as a failure.
95
+ */
96
+ export declare function oraPromise<T>(action: Promise<T> | ((spinner: Ora) => Promise<T>), options?: PromiseOptions<T> | string | null): Promise<T>;
package/dist/ora.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import { HIDE_CURSOR, rawMode, SHOW_CURSOR } from 'closeout/cursor';
3
3
  import restoreCursor from 'closeout/restore-cursor';
4
- import { lineCount } from 'linegauge';
4
+ import { strip, width } from 'linegauge';
5
5
  import { beginSynchronizedOutput, endSynchronizedOutput } from 'paratext/csi';
6
6
  import chalk from 'roundel/chalk';
7
7
  import { unicode } from 'roundel/terminal';
@@ -72,10 +72,65 @@ class StdinDiscarder {
72
72
  }
73
73
  }
74
74
  const stdinDiscarder = new StdinDiscarder();
75
- const RENDER_DEFERRAL_TIMEOUT = 200;
76
75
  const FALLBACK_INTERVAL = 100;
77
76
  const DEFAULT_COLUMNS = 80;
78
- const TRUNCATION_RESERVE = 1;
77
+ const TRUNCATION_MESSAGE = '... (content truncated to fit terminal)';
78
+ const STYLE_RESET = '\u001B[0m';
79
+ const TAB_STOP = 8;
80
+ let graphemes;
81
+ const segmenter = () => (graphemes ??= new Intl.Segmenter());
82
+ const CONTROL_CHARACTER = /([\t\n\r])/u;
83
+ const PRINTABLE_ASCII = /^[ -~]+$/u;
84
+ const tabStopWidth = (column, columns) => {
85
+ const nextStop = Math.floor(column / TAB_STOP) * TAB_STOP + TAB_STOP;
86
+ return Math.max(0, Math.min(nextStop, columns - 1) - column);
87
+ };
88
+ function layOut(text, columns) {
89
+ const rows = [];
90
+ let cells = [];
91
+ let column = 0;
92
+ let expandedText = '';
93
+ const startRow = () => {
94
+ cells = [];
95
+ column = 0;
96
+ rows.push(cells);
97
+ };
98
+ const writeGrapheme = (grapheme, cellWidth) => {
99
+ if (cellWidth === 0)
100
+ return;
101
+ if (column + cellWidth > columns)
102
+ startRow();
103
+ cells[column++] = grapheme;
104
+ for (let index = 1; index < cellWidth; index += 1)
105
+ cells[column++] = '';
106
+ };
107
+ const writeTab = () => {
108
+ const end = column + tabStopWidth(column, columns);
109
+ expandedText += ' '.repeat(end - column);
110
+ for (; column < end; column += 1)
111
+ cells[column] ??= ' ';
112
+ };
113
+ startRow();
114
+ for (const part of strip(text).split(CONTROL_CHARACTER)) {
115
+ if (part === '\t') {
116
+ writeTab();
117
+ continue;
118
+ }
119
+ expandedText += part;
120
+ if (part === '\n')
121
+ startRow();
122
+ else if (part === '\r')
123
+ column = 0;
124
+ else if (PRINTABLE_ASCII.test(part))
125
+ for (const character of part)
126
+ writeGrapheme(character, 1);
127
+ else
128
+ for (const { segment } of segmenter().segment(part))
129
+ writeGrapheme(segment, width(segment));
130
+ }
131
+ return { rows, expandedText };
132
+ }
133
+ const rowCount = (text, columns) => layOut(text, columns).rows.length;
79
134
  const activeHooksPerStream = new Map();
80
135
  const writeHooks = new WeakMap();
81
136
  const validColors = new Set(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray']);
@@ -84,10 +139,26 @@ function paint(color, text) {
84
139
  return text;
85
140
  return chalk[color]?.(text) ?? text;
86
141
  }
142
+ function formatAffix(value, separator, placeBefore) {
143
+ const resolved = typeof value === 'function' ? value() : value;
144
+ if (typeof resolved === 'string' && resolved !== '')
145
+ return placeBefore ? separator + resolved : resolved + separator;
146
+ return '';
147
+ }
148
+ function buildOutputLine(symbol, text, prefixText, suffixText) {
149
+ const hasSymbol = symbol !== '';
150
+ const hasText = typeof text === 'string' && text !== '';
151
+ const fullPrefixText = formatAffix(prefixText, hasSymbol || hasText ? ' ' : '', false);
152
+ const fullText = typeof text === 'string' ? (hasSymbol ? ' ' : '') + text : '';
153
+ const bodyEndsWithSeparator = hasSymbol && text === '';
154
+ return fullPrefixText + symbol + fullText + formatAffix(suffixText, bodyEndsWithSeparator ? '' : ' ', true);
155
+ }
87
156
  export class Ora {
88
157
  #linesToClear = 0;
89
158
  #frameIndex = -1;
90
159
  #lastFrameTime = 0;
160
+ #renderedFrame;
161
+ #renderedColumns;
91
162
  #options;
92
163
  #spinner;
93
164
  #stream;
@@ -95,19 +166,19 @@ export class Ora {
95
166
  #hookedStreams = new Map();
96
167
  #isInternalWrite = false;
97
168
  #drainHandler;
98
- #deferRenderTimer;
169
+ #hasUnfinishedLine = false;
99
170
  #isDiscardingStdin = false;
100
171
  #color;
101
172
  constructor(options) {
102
173
  const given = typeof options === 'string' ? { text: options } : options;
103
174
  this.#options = { color: 'cyan', stream: rt.stderr, discardStdin: true, hideCursor: true, isEnabled: false, isSilent: false, indent: 0, ...given };
104
175
  this.color = this.#options.color;
105
- this.#stream = this.#options.stream;
176
+ this.#stream = this.#options.stream ?? rt.stderr;
106
177
  if (typeof given?.isEnabled !== 'boolean')
107
178
  this.#options.isEnabled = isInteractive(this.#stream);
108
179
  if (typeof given?.isSilent !== 'boolean')
109
180
  this.#options.isSilent = false;
110
- if (this.#options.interval !== undefined && !(Number.isInteger(this.#options.interval) && this.#options.interval > 0)) {
181
+ if (this.#options.interval !== undefined && !(Number.isSafeInteger(this.#options.interval) && this.#options.interval > 0)) {
111
182
  throw new Error('The `interval` option must be a positive integer');
112
183
  }
113
184
  const userInterval = this.#options.interval;
@@ -131,15 +202,13 @@ export class Ora {
131
202
  },
132
203
  });
133
204
  Object.defineProperty(this, '_frameIndex', { get: () => this.#frameIndex });
205
+ Object.defineProperty(this, '_renderedFrame', { get: () => this.#renderedFrame });
206
+ Object.defineProperty(this, '_renderedColumns', { get: () => this.#renderedColumns });
134
207
  Object.defineProperty(this, '_lineCount', {
135
208
  get: () => {
136
- const columns = this.#stream.columns ?? DEFAULT_COLUMNS;
137
- const prefixText = typeof this.#options.prefixText === 'function' ? '' : this.#options.prefixText;
138
- const suffixText = typeof this.#options.suffixText === 'function' ? '' : this.#options.suffixText;
139
- const fullPrefixText = typeof prefixText === 'string' && prefixText !== '' ? `${prefixText} ` : '';
140
- const fullSuffixText = typeof suffixText === 'string' && suffixText !== '' ? ` ${suffixText}` : '';
141
- const text = typeof this.#options.text === 'string' ? ` ${this.#options.text}` : '';
142
- return lineCount(`${' '.repeat(this.#options.indent)}${fullPrefixText}-${text}${fullSuffixText}`, columns);
209
+ const { prefixText, suffixText } = this.#options;
210
+ const line = buildOutputLine('-', this.#options.text, typeof prefixText === 'function' ? '' : prefixText, typeof suffixText === 'function' ? '' : suffixText);
211
+ return rowCount(' '.repeat(this.#options.indent) + line, this.#columns);
143
212
  },
144
213
  });
145
214
  }
@@ -148,7 +217,7 @@ export class Ora {
148
217
  }
149
218
  set indent(indent) {
150
219
  const value = indent === undefined ? 0 : indent;
151
- if (!(value >= 0 && Number.isInteger(value)))
220
+ if (!(value >= 0 && Number.isSafeInteger(value)))
152
221
  throw new Error('The `indent` option must be an integer from 0 and up');
153
222
  this.#options.indent = value;
154
223
  }
@@ -159,27 +228,27 @@ export class Ora {
159
228
  return this.#spinner;
160
229
  }
161
230
  set spinner(spinner) {
162
- this.#frameIndex = -1;
163
- this.#options.interval = undefined;
164
- if (typeof spinner === 'object') {
231
+ if (typeof spinner === 'object' && spinner !== null) {
165
232
  if (!Array.isArray(spinner.frames) || spinner.frames.length === 0 || spinner.frames.some((frame) => typeof frame !== 'string')) {
166
233
  throw new Error('The given spinner must have a non-empty `frames` array of strings');
167
234
  }
168
- if (spinner.interval !== undefined && !(Number.isInteger(spinner.interval) && spinner.interval > 0)) {
235
+ if (spinner.interval !== undefined && !(Number.isSafeInteger(spinner.interval) && spinner.interval > 0)) {
169
236
  throw new Error('`spinner.interval` must be a positive integer if provided');
170
237
  }
171
238
  this.#spinner = spinner;
172
- return;
173
239
  }
174
- const named = spinner === undefined || spinner === 'default' ? undefined : spinners[spinner];
175
- if (!unicode(rt))
176
- this.#spinner = spinners['line'];
177
- else if (spinner === undefined)
178
- this.#spinner = spinners['dots'];
179
- else if (named !== undefined)
180
- this.#spinner = named;
181
- else
182
- throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);
240
+ else if (spinner !== undefined && (spinner === 'default' || !Object.hasOwn(spinners, spinner))) {
241
+ throw new Error(`There is no built-in spinner named '${String(spinner)}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);
242
+ }
243
+ else {
244
+ this.#spinner = (unicode(rt) ? spinners[spinner ?? 'dots'] : spinners['line']);
245
+ }
246
+ this.#frameIndex = -1;
247
+ this.#options.interval = undefined;
248
+ if (!this.isSpinning)
249
+ return;
250
+ this.#startRenderTimer();
251
+ this.render();
183
252
  }
184
253
  get text() {
185
254
  return this.#options.text;
@@ -233,29 +302,18 @@ export class Ora {
233
302
  this.#lastFrameTime = now;
234
303
  }
235
304
  const frame = paint(this.#color, this.#spinner.frames[this.#frameIndex] ?? '');
236
- const text = typeof this.#options.text === 'string' ? ` ${this.#options.text}` : '';
237
- return this.#fullPrefixText() + frame + text + this.#fullSuffixText();
305
+ return ' '.repeat(this.#options.indent) + buildOutputLine(frame, this.text, this.#options.prefixText, this.#options.suffixText);
238
306
  }
239
307
  clear() {
240
- if (!this.isEnabled || this.#stream.isTTY !== true)
308
+ if (!this.isEnabled)
241
309
  return this;
242
- this.#internalWrite(() => {
243
- this.#stream.cursorTo?.(0);
244
- for (let index = 0; index < this.#linesToClear; index += 1) {
245
- if (index > 0)
246
- this.#stream.moveCursor?.(0, -1);
247
- this.#stream.clearLine?.(1);
248
- }
249
- if (this.#options.indent)
250
- this.#stream.cursorTo?.(this.#options.indent);
251
- return undefined;
252
- });
253
- this.#linesToClear = 0;
310
+ this.#clearDisplay();
254
311
  return this;
255
312
  }
256
313
  render() {
257
- if (!this.isEnabled || this.#drainHandler || this.#deferRenderTimer)
314
+ if (!this.isEnabled || this.#drainHandler || this.#hasUnfinishedLine)
258
315
  return this;
316
+ let frameContent = this.frame();
259
317
  const useSynchronizedOutput = this.#stream.isTTY === true;
260
318
  let shouldDisableSynchronizedOutput = false;
261
319
  try {
@@ -263,14 +321,19 @@ export class Ora {
263
321
  this.#internalWrite(() => this.#stream.write(beginSynchronizedOutput));
264
322
  shouldDisableSynchronizedOutput = true;
265
323
  }
266
- this.clear();
267
- let frameContent = this.frame();
268
- const columns = this.#stream.columns ?? DEFAULT_COLUMNS;
269
- const actualLineCount = lineCount(frameContent, columns);
270
- const consoleHeight = this.#stream.rows;
271
- if (consoleHeight !== undefined && consoleHeight > 1 && actualLineCount > consoleHeight) {
272
- const lines = frameContent.split('\n');
273
- frameContent = [...lines.slice(0, consoleHeight - TRUNCATION_RESERVE), '... (content truncated to fit terminal)'].join('\n');
324
+ if (this.#linesToClear > 0)
325
+ this.#clearDisplay();
326
+ else if (this.#canMoveCursor(this.#stream)) {
327
+ const stream = this.#stream;
328
+ this.#internalWrite(() => stream.cursorTo(0));
329
+ }
330
+ const columns = this.#columns;
331
+ let layout = layOut(frameContent, columns);
332
+ const rows = this.#stream.rows;
333
+ const maxRows = rows !== undefined && rows > 1 ? rows - 1 : undefined;
334
+ if (maxRows !== undefined && layout.rows.length > maxRows) {
335
+ frameContent = truncateFrame(frameContent, columns, maxRows);
336
+ layout = layOut(frameContent, columns);
274
337
  }
275
338
  const canContinue = this.#internalWrite(() => this.#stream.write(frameContent));
276
339
  if (canContinue === false && this.#stream.isTTY === true) {
@@ -280,7 +343,9 @@ export class Ora {
280
343
  };
281
344
  this.#stream.once?.('drain', this.#drainHandler);
282
345
  }
283
- this.#linesToClear = lineCount(frameContent, columns);
346
+ this.#linesToClear = layout.rows.length;
347
+ this.#renderedFrame = layout.expandedText;
348
+ this.#renderedColumns = columns;
284
349
  }
285
350
  finally {
286
351
  if (shouldDisableSynchronizedOutput)
@@ -291,17 +356,15 @@ export class Ora {
291
356
  start(text) {
292
357
  if (text !== undefined)
293
358
  this.text = text;
294
- if (this.isSilent)
359
+ if (this.isSpinning || this.isSilent)
295
360
  return this;
296
361
  if (!this.isEnabled) {
297
362
  const symbol = this.text ? '-' : '';
298
- const line = ' '.repeat(this.#options.indent) + this.#buildOutputLine(symbol, this.text, this.#options.prefixText, this.#options.suffixText);
363
+ const line = ' '.repeat(this.#options.indent) + buildOutputLine(symbol, this.text, this.#options.prefixText, this.#options.suffixText);
299
364
  if (line.trim() !== '')
300
365
  this.#internalWrite(() => this.#stream.write(`${line}\n`));
301
366
  return this;
302
367
  }
303
- if (this.isSpinning)
304
- return this;
305
368
  if (this.#options.hideCursor)
306
369
  this.#hideCursor();
307
370
  if (this.#options.discardStdin && rt.stdin.isTTY) {
@@ -309,30 +372,27 @@ export class Ora {
309
372
  this.#isDiscardingStdin = true;
310
373
  }
311
374
  this.#installHook();
312
- this.render();
313
- this.#id = setInterval(this.render.bind(this), this.interval);
375
+ try {
376
+ this.render();
377
+ }
378
+ catch (error) {
379
+ this.#release();
380
+ this.#showCursor();
381
+ throw error;
382
+ }
383
+ this.#startRenderTimer();
314
384
  return this;
315
385
  }
316
386
  stop() {
317
- clearInterval(this.#id);
318
- this.#id = undefined;
319
- this.#frameIndex = -1;
320
- this.#lastFrameTime = 0;
321
- this.#clearRenderDeferral();
322
- this.#uninstallHook();
323
- if (this.#drainHandler) {
324
- this.#stream.removeListener?.('drain', this.#drainHandler);
325
- this.#drainHandler = undefined;
326
- }
327
- if (this.isEnabled) {
328
- this.clear();
329
- if (this.#options.hideCursor)
330
- this.#showCursor();
387
+ const wasSpinning = this.isSpinning;
388
+ this.#release();
389
+ try {
390
+ this.#clearDisplay();
331
391
  }
332
- if (this.#isDiscardingStdin) {
333
- this.#isDiscardingStdin = false;
334
- stdinDiscarder.stop();
392
+ catch {
335
393
  }
394
+ if (wasSpinning)
395
+ this.#showCursor();
336
396
  return this;
337
397
  }
338
398
  succeed(text) {
@@ -347,15 +407,17 @@ export class Ora {
347
407
  info(text) {
348
408
  return this.stopAndPersist({ symbol: logSymbols.info, ...(text === undefined ? {} : { text }) });
349
409
  }
350
- stopAndPersist(options = {}) {
410
+ stopAndPersist(options) {
411
+ const hasUnfinishedLine = this.#hasUnfinishedLine;
412
+ this.stop();
351
413
  if (this.isSilent)
352
414
  return this;
353
- const symbol = options.symbol ?? ' ';
354
- const text = options.text ?? this.text;
355
- const prefixText = options.prefixText ?? this.#options.prefixText;
356
- const suffixText = options.suffixText ?? this.#options.suffixText;
357
- const textToWrite = `${this.#buildOutputLine(symbol, text, prefixText, suffixText)}\n`;
358
- this.stop();
415
+ const symbolText = String(options?.symbol ?? ' ');
416
+ const symbol = this.isEnabled && this.#stream.isTTY === true ? symbolText : strip(symbolText);
417
+ const text = options?.text ?? this.text;
418
+ const prefixText = options?.prefixText ?? this.#options.prefixText;
419
+ const suffixText = options?.suffixText ?? this.#options.suffixText;
420
+ const textToWrite = `${hasUnfinishedLine ? '\n' : ''}${' '.repeat(this.#options.indent)}${buildOutputLine(symbol, text, prefixText, suffixText)}\n`;
359
421
  this.#internalWrite(() => this.#stream.write(textToWrite));
360
422
  return this;
361
423
  }
@@ -369,51 +431,79 @@ export class Ora {
369
431
  }
370
432
  }
371
433
  #tryRender() {
372
- if (this.isSpinning)
373
- this.render();
374
- }
375
- #hideCursor() {
376
- if (this.#stream.isTTY !== true)
434
+ if (!this.isSpinning)
377
435
  return;
378
- restoreCursor();
379
- this.#stream.write(HIDE_CURSOR);
436
+ try {
437
+ this.render();
438
+ }
439
+ catch {
440
+ this.#release();
441
+ this.#showCursor();
442
+ }
380
443
  }
381
- #showCursor() {
382
- if (this.#stream.isTTY !== true)
444
+ #release() {
445
+ clearInterval(this.#id);
446
+ this.#id = undefined;
447
+ this.#frameIndex = -1;
448
+ this.#lastFrameTime = 0;
449
+ this.#uninstallHook();
450
+ if (this.#drainHandler) {
451
+ this.#stream.removeListener?.('drain', this.#drainHandler);
452
+ this.#drainHandler = undefined;
453
+ }
454
+ this.#hasUnfinishedLine = false;
455
+ if (!this.#isDiscardingStdin)
383
456
  return;
384
- this.#stream.write(SHOW_CURSOR);
457
+ this.#isDiscardingStdin = false;
458
+ stdinDiscarder.stop();
385
459
  }
386
- #formatAffix(value, separator, placeBefore) {
387
- const resolved = typeof value === 'function' ? value() : value;
388
- if (typeof resolved === 'string' && resolved !== '')
389
- return placeBefore ? separator + resolved : resolved + separator;
390
- return '';
460
+ #startRenderTimer() {
461
+ clearInterval(this.#id);
462
+ this.#id = setInterval(this.#tryRender.bind(this), this.interval);
391
463
  }
392
- #fullPrefixText(prefixText = this.#options.prefixText, postfix = ' ') {
393
- return this.#formatAffix(prefixText, postfix, false);
464
+ get #columns() {
465
+ return this.#stream.columns || DEFAULT_COLUMNS;
394
466
  }
395
- #fullSuffixText(suffixText = this.#options.suffixText, prefix = ' ') {
396
- return this.#formatAffix(suffixText, prefix, true);
467
+ #canMoveCursor(stream) {
468
+ return stream.isTTY === true && typeof stream.cursorTo === 'function' && typeof stream.moveCursor === 'function' && typeof stream.clearLine === 'function';
397
469
  }
398
- #buildOutputLine(symbol, text, prefixText, suffixText) {
399
- const separator = symbol ? ' ' : '';
400
- const fullText = typeof text === 'string' ? separator + text : '';
401
- return this.#fullPrefixText(prefixText, ' ') + symbol + fullText + this.#fullSuffixText(suffixText, ' ');
470
+ #clearDisplay() {
471
+ const stream = this.#stream;
472
+ if (!this.#canMoveCursor(stream) || this.#linesToClear === 0)
473
+ return;
474
+ const columns = this.#columns;
475
+ if (this.#renderedFrame !== undefined && this.#renderedColumns !== columns) {
476
+ this.#linesToClear = Math.min(this.#linesToClear, rowCount(this.#renderedFrame, columns));
477
+ }
478
+ try {
479
+ const count = this.#linesToClear;
480
+ this.#internalWrite(() => {
481
+ stream.cursorTo(0);
482
+ for (let index = 0; index < count; index += 1) {
483
+ if (index > 0)
484
+ stream.moveCursor(0, -1);
485
+ stream.clearLine(1);
486
+ }
487
+ });
488
+ }
489
+ finally {
490
+ this.#linesToClear = 0;
491
+ this.#renderedFrame = undefined;
492
+ }
402
493
  }
403
- #scheduleRenderDeferral() {
404
- if (this.#deferRenderTimer)
494
+ #hideCursor() {
495
+ if (this.#stream.isTTY !== true)
405
496
  return;
406
- this.#deferRenderTimer = setTimeout(() => {
407
- this.#deferRenderTimer = undefined;
408
- if (this.isSpinning)
409
- this.#tryRender();
410
- }, RENDER_DEFERRAL_TIMEOUT);
411
- this.#deferRenderTimer.unref?.();
497
+ restoreCursor();
498
+ this.#stream.write(HIDE_CURSOR);
412
499
  }
413
- #clearRenderDeferral() {
414
- if (this.#deferRenderTimer) {
415
- clearTimeout(this.#deferRenderTimer);
416
- this.#deferRenderTimer = undefined;
500
+ #showCursor() {
501
+ if (!this.#options.hideCursor || this.#stream.isTTY !== true)
502
+ return;
503
+ try {
504
+ this.#stream.write(SHOW_CURSOR);
505
+ }
506
+ catch {
417
507
  }
418
508
  }
419
509
  #installHook() {
@@ -452,19 +542,32 @@ export class Ora {
452
542
  const [enc, cb] = typeof encoding === 'function' ? [undefined, encoding] : [encoding, callback];
453
543
  if (this.#isInternalWrite)
454
544
  return originalWrite.call(stream, chunk, enc, cb);
455
- this.clear();
456
- const chunkString = stringifyChunk(chunk, enc);
457
- const terminatesLine = chunkString.endsWith('\n') || chunkString.endsWith('\r');
545
+ this.#clearDisplay();
546
+ const chunkString = strip(stringifyChunk(chunk, enc));
547
+ if (chunkString !== '')
548
+ this.#hasUnfinishedLine = !chunkString.endsWith('\n');
458
549
  const writeResult = originalWrite.call(stream, chunk, enc, cb);
459
- if (terminatesLine)
460
- this.#clearRenderDeferral();
461
- else if (chunkString.length > 0)
462
- this.#scheduleRenderDeferral();
463
- if (this.isSpinning && !this.#deferRenderTimer)
464
- this.render();
550
+ this.#tryRender();
465
551
  return writeResult;
466
552
  }
467
553
  }
554
+ function truncateFrame(frameContent, columns, maxRows) {
555
+ let message = TRUNCATION_MESSAGE;
556
+ while (message.length > 1 && rowCount(message, columns) > maxRows)
557
+ message = message.slice(0, -1);
558
+ let rowBudget = maxRows - rowCount(message, columns);
559
+ const keptLines = [];
560
+ for (const line of frameContent.split('\n')) {
561
+ const lineRows = layOut(line, columns).rows;
562
+ if (lineRows.length > rowBudget) {
563
+ keptLines.push(...lineRows.slice(0, rowBudget).map((cells) => cells.join('')));
564
+ break;
565
+ }
566
+ keptLines.push(line);
567
+ rowBudget -= lineRows.length;
568
+ }
569
+ return [...keptLines, STYLE_RESET + message].join('\n');
570
+ }
468
571
  function stringifyChunk(chunk, encoding) {
469
572
  if (chunk === undefined || chunk === null)
470
573
  return '';
@@ -479,6 +582,7 @@ function stringifyChunk(chunk, encoding) {
479
582
  export default function ora(options) {
480
583
  return new Ora(options);
481
584
  }
585
+ const resolveText = (value, argument) => (typeof value === 'function' ? value(argument) : value);
482
586
  export async function oraPromise(action, options) {
483
587
  const actionIsFunction = typeof action === 'function';
484
588
  const actionIsPromise = typeof action?.then === 'function';
@@ -486,22 +590,37 @@ export async function oraPromise(action, options) {
486
590
  throw new TypeError('Parameter `action` must be a Function or a Promise');
487
591
  const settings = typeof options === 'object' && options !== null ? options : {};
488
592
  const { successText, failText, successSymbol, failSymbol } = settings;
489
- const spinner = ora(options).start();
593
+ const spinner = ora(options ?? undefined).start();
594
+ let result;
490
595
  try {
491
- const result = await (actionIsFunction ? action(spinner) : action);
492
- const text = successText === undefined ? undefined : typeof successText === 'string' ? successText : successText(result);
493
- if (successSymbol === undefined)
494
- spinner.succeed(text);
495
- else
496
- spinner.stopAndPersist({ symbol: successSymbol, ...(text === undefined ? {} : { text }) });
497
- return result;
596
+ result = await (actionIsFunction ? action(spinner) : action);
498
597
  }
499
598
  catch (error) {
500
- const text = failText === undefined ? undefined : typeof failText === 'string' ? failText : failText(error);
501
- if (failSymbol === undefined)
502
- spinner.fail(text);
503
- else
504
- spinner.stopAndPersist({ symbol: failSymbol, ...(text === undefined ? {} : { text }) });
599
+ let text;
600
+ try {
601
+ text = resolveText(failText, error);
602
+ }
603
+ catch {
604
+ }
605
+ try {
606
+ spinner.stopAndPersist({ symbol: failSymbol ?? logSymbols.error, ...(text === undefined ? {} : { text }) });
607
+ }
608
+ catch {
609
+ }
610
+ throw error;
611
+ }
612
+ let text;
613
+ try {
614
+ text = resolveText(successText, result);
615
+ }
616
+ catch (error) {
617
+ spinner.stop();
505
618
  throw error;
506
619
  }
620
+ try {
621
+ spinner.stopAndPersist({ symbol: successSymbol ?? logSymbols.success, ...(text === undefined ? {} : { text }) });
622
+ }
623
+ catch {
624
+ }
625
+ return result;
507
626
  }
package/dist/plugin.js CHANGED
@@ -24,7 +24,7 @@ export function validate(plugin) {
24
24
  throw new PluginError('E_PLUGIN_SCHEMA', problem, 'compare the object against flagstaff/schema.json');
25
25
  }
26
26
  const { contract, components = {} } = plugin;
27
- if (contract !== undefined && contract > CONTRACT) {
27
+ if ((contract ?? CONTRACT) > CONTRACT) {
28
28
  throw new PluginError('E_PLUGIN_CONTRACT', `plugin declares contract ${contract}; this flagstaff knows ${CONTRACT}`, `upgrade flagstaff, or set contract: ${CONTRACT}`);
29
29
  }
30
30
  for (const [name, component] of Object.entries(components)) {
@@ -47,7 +47,7 @@ function deepFrozen(value, seen = new WeakMap()) {
47
47
  const copy = (Array.isArray(value) ? [] : {});
48
48
  seen.set(value, copy);
49
49
  for (const [k, v] of Object.entries(value))
50
- Object.defineProperty(copy, k, { value: deepFrozen(v, seen), writable: true, enumerable: true, configurable: true });
50
+ Object.defineProperty(copy, k, { value: deepFrozen(v, seen), enumerable: true });
51
51
  return frozen(copy);
52
52
  }
53
53
  export function register(plugin) {
@@ -10,8 +10,8 @@ const END_SYNC = `${CSI}?2026l`;
10
10
  const SAVE = '\u001B7';
11
11
  const RESTORE = '\u001B8';
12
12
  function columnsOf(out) {
13
- const { columns } = out;
14
- return columns !== undefined && columns > 0 ? columns : DEFAULT_COLUMNS;
13
+ const { columns = 0 } = out;
14
+ return columns > 0 ? columns : DEFAULT_COLUMNS;
15
15
  }
16
16
  function diff(was, now, sameWidth) {
17
17
  const { lines: before, rows: beforeRows } = was;
@@ -34,7 +34,7 @@ function diff(was, now, sameWidth) {
34
34
  }
35
35
  row += beforeRows[line];
36
36
  }
37
- if (sameWidth && line === last && before.length === after.length && before[line] === after[line])
37
+ if (sameWidth && before.length === after.length && before[line] === after[line])
38
38
  return out === '' ? '' : `${SAVE}${out}${RESTORE}`;
39
39
  move(row);
40
40
  return `${out}${CSI}0J${after.slice(line).join('\n')}`;
@@ -42,7 +42,7 @@ function diff(was, now, sameWidth) {
42
42
  export function frameWriter(out) {
43
43
  let shown;
44
44
  let whole;
45
- let size = '';
45
+ let size;
46
46
  const write = (bytes) => {
47
47
  if (bytes !== '')
48
48
  out.write(`${BEGIN_SYNC}${bytes}${END_SYNC}`);
@@ -51,13 +51,14 @@ export function frameWriter(out) {
51
51
  paint(lines) {
52
52
  let frame = lines.length === 0 ? [''] : [...lines];
53
53
  const columns = columnsOf(out);
54
- const tall = (out.rows ?? 0) > 0 ? out.rows : Number.POSITIVE_INFINITY;
54
+ const { rows: height = 0 } = out;
55
+ const tall = height > 0 ? height : Number.POSITIVE_INFINITY;
55
56
  const heights = () => frame.map((line) => lineCount(line, columns));
56
57
  let rows = heights();
57
58
  whole = undefined;
58
59
  if (rows.reduce((sum, n) => sum + n, 0) > tall) {
59
60
  let cut = frame.length;
60
- for (let used = 1; cut > 0 && (used += rows[cut - 1]) <= tall;)
61
+ for (let used = 1; (used += rows[cut - 1]) <= tall;)
61
62
  cut -= 1;
62
63
  whole = frame;
63
64
  frame = [muted(`… ${cut} more`), ...frame.slice(cut)];
@@ -70,7 +71,7 @@ export function frameWriter(out) {
70
71
  shown = now;
71
72
  },
72
73
  release() {
73
- if (shown !== undefined && whole !== undefined)
74
+ if (whole !== undefined)
74
75
  write(diff(shown, { lines: whole, rows: [] }, false));
75
76
  shown = whole = undefined;
76
77
  },
@@ -127,16 +128,14 @@ export function ttyProjection(component, out, clock) {
127
128
  return new TtyProjection(component, out, clock);
128
129
  }
129
130
  export function staticProjection(component, out) {
130
- let written = [];
131
+ let written;
131
132
  const emit = (state) => {
132
133
  const text = component.static(state);
133
134
  if (text === '')
134
135
  return;
135
136
  const lines = text.split('\n');
136
- let shared = 0;
137
- while (shared < written.length && shared < lines.length && written[shared] === lines[shared])
138
- shared += 1;
139
- const fresh = lines.slice(shared);
137
+ const shared = lines.findIndex((line, i) => line !== written?.[i]);
138
+ const fresh = shared === -1 ? [] : lines.slice(shared);
140
139
  written = lines;
141
140
  if (fresh.length > 0)
142
141
  out.write(`${fresh.join('\n')}\n`);
package/dist/table.js CHANGED
@@ -8,9 +8,9 @@ const CHROME_PER_COLUMN = 3;
8
8
  const MIN_COLUMN = 3;
9
9
  const V = '│';
10
10
  const lay = (cell, paint) => laid(cellText(cell), cellHref(cell), paint);
11
- function fitWidths(widths, available, { columns: bounds = [] }) {
11
+ function fitWidths(widths, available, { columns: bounds }) {
12
12
  for (let total = widths.reduce((sum, w) => sum + w, 0); total > available; total--) {
13
- const pick = widths.reduce((best, w, i) => (w > (bounds[i]?.min ?? MIN_COLUMN) && (best < 0 || w > widths[best]) ? i : best), -1);
13
+ const pick = widths.reduce((best, w, i) => (w > (bounds?.[i]?.min ?? MIN_COLUMN) && (best < 0 || w > widths[best]) ? i : best), -1);
14
14
  if (pick < 0)
15
15
  break;
16
16
  widths.splice(pick, 1, widths[pick] - 1);
@@ -27,11 +27,12 @@ function layoutRow(row, widths, options, paint) {
27
27
  const line = painted(plain, cellHref(row[i]), paint);
28
28
  return options.align?.[i] === 'right' ? gap + line : line + gap;
29
29
  };
30
- return Array.from({ length: Math.max(1, ...cells.map((lines) => lines.length)) }, (_, line) => `${V} ${widths.map((w, i) => pad(cells[i]?.[line] ?? '', w, i)).join(` ${V} `)} ${V}`);
30
+ return Array.from({ length: Math.max(...cells.map((lines) => lines.length)) }, (_, line) => `${V} ${cells.map((lines, i) => pad(lines[line] ?? '', widths[i], i)).join(` ${V} `)} ${V}`);
31
31
  }
32
32
  const rule = (widths, [left, mid, right]) => `${left}${widths.map((w) => '─'.repeat(w + 2)).join(mid)}${right}`;
33
33
  export function table(rows, options = {}) {
34
- const columns = Math.max(options.head?.length ?? 0, ...rows.map((row) => row.length), 1);
34
+ const all = options.head === undefined ? rows : [options.head, ...rows];
35
+ const columns = Math.max(1, ...all.map((row) => row.length));
35
36
  options.columns?.forEach((column, i) => {
36
37
  const { min = 0, max = min || 1 } = column ?? {};
37
38
  if ((min % 1) + (max % 1) !== 0 || min < 0 || max < Math.max(min, 1))
@@ -39,7 +40,6 @@ export function table(rows, options = {}) {
39
40
  });
40
41
  const available = Math.max(columns * MIN_COLUMN, (options.width ?? DEFAULT_WIDTH) - columns * CHROME_PER_COLUMN - 1);
41
42
  const paint = painter(options.terminal);
42
- const all = options.head === undefined ? rows : [options.head, ...rows];
43
43
  const widths = fitWidths(Array.from({ length: columns }, (_, i) => Math.min(options.columns?.[i]?.max ?? Infinity, Math.max(0, ...all.map((row) => width(lay(row[i], paint)))))), available, options);
44
44
  const out = [rule(widths, '┌┬┐')];
45
45
  if (options.head !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flagstaff",
3
- "version": "1.7.5",
3
+ "version": "1.8.1",
4
4
  "description": "Spinners, progress, boxes and tables on one terminal frame loop, with a static projection for pipes, screen readers and agents, and a plugin host. No dependency outside the burgee family. Drop-in paths for ora, log-update, boxen and cli-table3.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -164,9 +164,9 @@
164
164
  ],
165
165
  "dependencies": {
166
166
  "closeout": "^1.1.8",
167
- "linegauge": "^1.1.5",
168
- "paratext": "^1.0.11",
169
- "roundel": "^1.2.1"
167
+ "linegauge": "^1.2.0",
168
+ "paratext": "^1.0.12",
169
+ "roundel": "^1.3.1"
170
170
  },
171
171
  "devDependencies": {
172
172
  "fast-check": "^4.10.2",