Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/one-grammar-reads-every-escape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@fnndsc/menu": minor
"@fnndsc/fond": minor
"@fnndsc/brasa": minor
"@fnndsc/chell": patch
"@fnndsc/calypso": patch
"@fnndsc/stratus": patch
"@fnndsc/chili": patch
"@fnndsc/porter": patch
"@fnndsc/argus": patch
---

One grammar reads terminal escapes everywhere: a code cut across two writes or an OSC link no longer leaks into words.

`@fnndsc/menu` holds the escape grammar, one ECMA-48 state machine: CSI and its one-byte C1 form, OSC to BEL or either ST, DCS, SOS, PM and APC to either ST, charset and two-byte escapes, CAN and SUB aborting, a long string control discarded with bounded memory, its kept payload counted in the UTF-8 bytes of whole characters. An SGR's `:` subparameters keep their structure, so `38:2::255:0:0` draws red and `4:0` ends an underline (`4:2`–`4:5` draw double, curly, dotted and dashed ones); a character cut between a surrogate pair's halves, or with a sequence between them, is handed over whole; chell's row counter counts what the terminal is actually handed; a byte stream keeps a leading U+FEFF as the string face does. It reads a whole text (`ansi_strip`, `ansi_width`, `ansi_present`, `ansi_tokenize`, and `ansi_renderHtml` rebuilt on it) or a stream (`AnsiTokenizer` for typed tokens, `AnsiPlainStream` for words, from strings or UTF-8 bytes), and a text reads the same however it was cut; `textChunkings_list` and `byteChunkings_list` give a stream reader's tests the cuts. It also states the terminal state mark (`TERMINAL_STATE_OSC`, `TerminalState`, `terminalState_render`, `terminalState_parse`, `terminalState_isRunning`) that chell writes and ARGUS reads. The engine's pipe and tee boundary, a joblet's log (each channel its own stream), `ls`, `lolcat`, the notes, stratus's plugin rows, the daemon face's and console cage's log (each stream read on its own onto the one screen line, the line not yet ended replayed at the final handover), chell's row counter (a cursor save and restore read where they stand, wraps as an autowrapping terminal makes them) and widths, porter's boot rows and a stopped berth's last words (read from the engine's frames in order, each stream decoded whole), chili's widths, and ARGUS's readings, script and TD screens, trek bridge and console stream all use it. brasa no longer exports `ansi_strip`, and ARGUS's `answerModel` no longer exports `ansi_strip` (take menu's). A listing look (`ListingLook`, `@fnndsc/fond`) now measures its own coloured names (`name_width`), so fond reads no escape itself. A colour set on one line of the ARGUS console now goes on into the next, as on a terminal. `npm run lint:seam` refuses an escape pattern outside menu's grammar, and an inline comment cannot excuse one.
5 changes: 3 additions & 2 deletions apps/argus/src/app/binView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
* A module of the host: the host hands in the catalogue bindings and RUN
* as hooks; the module keeps the dive in progress.
*/
import { DAG_MODEL_KINDS, PLUGIN_INFO_MODEL_KIND, pipelineDiagramModelSchema, pluginInfoModelSchema, type PipelineDiagramNode, type PluginInfoModel, type PluginParameter, path_quote, arg_quote } from '@fnndsc/menu';
import { ansi_present, DAG_MODEL_KINDS, PLUGIN_INFO_MODEL_KIND, pipelineDiagramModelSchema, pluginInfoModelSchema, type PipelineDiagramNode, type PluginInfoModel, type PluginParameter, path_quote, arg_quote } from '@fnndsc/menu';

import type { ExecuteOutcome } from '../calypso/client.js';
import { ansi_renderHtml, html_escape } from '../console/ansi.js';
import type { FilesPanel } from '../features/files/panel.js';
Expand Down Expand Up @@ -86,7 +87,7 @@ export interface BinView {
* @returns HTML.
*/
export function binText_highlight(text: string): string {
if (/\x1b\[/.test(text)) return ansi_renderHtml(text);
if (ansi_present(text)) return ansi_renderHtml(text);
return html_escape(text)
.replace(/(&quot;[^&]*&quot;)/g, '<span class="man-str">$1</span>')
.replace(/(^|\s)(--?[a-zA-Z][\w-]*)/g, '$1<span class="man-flag">$2</span>')
Expand Down
3 changes: 1 addition & 2 deletions apps/argus/src/app/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@
* asks, the cohort and the /bin view as hooks; the module keeps each
* browser's binding and history, the preview provider and the readers.
*/
import { DAG_MODEL_KINDS, EDIT_CONFIRM_BYTES, path_isEditable, pipelineDiagramModelSchema, type PipelineDiagramNode, path_quote, arg_quote } from '@fnndsc/menu';
import { ansi_strip, DAG_MODEL_KINDS, EDIT_CONFIRM_BYTES, path_isEditable, pipelineDiagramModelSchema, type PipelineDiagramNode, path_quote, arg_quote } from '@fnndsc/menu';

import type { CatalogueBinding } from './desktop.js';
import type { HostContext } from './hostContext.js';
import { outcome_succeeded } from './lineRun.js';
import { link_compose } from './link.js';
import type { FileText } from './nodeOverlay.js';
import type { PaneInstance } from './panes.js';
import { ansi_strip } from '../calypso/answerModel.js';
import type { ExecuteOutcome } from '../calypso/client.js';
import type { PaneAskRequest } from '../features/ask/paneAsk.js';
import { editAsk_render, editLine_compose } from '../features/edit/line.js';
Expand Down
4 changes: 3 additions & 1 deletion apps/argus/src/app/consoleMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
*
* @module
*/
import type { TerminalState } from '@fnndsc/menu';

import type { ArgusClient } from '../calypso/client.js';
import type { ArgusTerminal } from '../console/terminal.js';
import { TerminalScreen, type TerminalState } from '../console/terminalScreen.js';
import { TerminalScreen } from '../console/terminalScreen.js';
import { question_stand } from './asks.js';
import type { PaneAskRequest } from '../features/ask/paneAsk.js';

Expand Down
16 changes: 13 additions & 3 deletions apps/argus/src/app/consoleStop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,22 @@
* is free again. Ctrl-C in the terminal does the same; the pill is for when
* the keyboard is not getting through, or the console is closed.
*
* Key components:
* - consoleStop_wire: stands the pill while something runs and sends the stop.
*
* Typical usage:
* ```ts
* consoleStop_wire(client, (): string | null => terminalId);
* ```
*
* Dependencies: the session client; menu's terminal state mark (which states run).
*
* @module
*/
import { terminalState_isRunning } from '@fnndsc/menu';

import type { ArgusClient } from '../calypso/client.js';

/** The terminal states during which something runs. */
const RUNNING: ReadonlySet<string> = new Set(['busy', 'asking', 'playing']);

/**
* Wires the STOP pill.
Expand All @@ -31,7 +41,7 @@ export function consoleStop_wire(client: ArgusClient, terminalId: () => string |
const show = (): void => {
const terminal: boolean = console_.classList.contains('console-terminal');
const running: boolean = terminal
? RUNNING.has(console_.dataset['terminalState'] ?? '')
? terminalState_isRunning(console_.dataset['terminalState'] ?? '')
: console_.dataset['busy'] === 'true';
pill.hidden = !running;
};
Expand Down
5 changes: 3 additions & 2 deletions apps/argus/src/app/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
* A module of the host: the host hands in its spawn and placement verbs; the
* module keeps the pane instances and their saves.
*/
import { ansi_strip, editExtension_extract } from '@fnndsc/menu';

import type { ExecuteOutcome, SurfaceEdit } from '../calypso/client.js';
import { lineVisible_run } from './lines.js';
import { EditPanel } from '../features/edit/panel.js';
import { editExtension_extract } from '@fnndsc/menu';
import { editLine_compose, saveLine_compose } from '../features/edit/line.js';
import type { ReplayPlace } from './desktop.js';
import type { HostContext } from './hostContext.js';
Expand Down Expand Up @@ -179,7 +180,7 @@ export function editor_wire(context: Pick<HostContext, 'layout' | 'panels' | 'su
void context.client.line_execute(line, { silent: true, observe: false }).then((outcome: ExecuteOutcome): void => {
if (outcome_succeeded(outcome)) return;
const refused = outcome.envelopes.find((envelope): boolean => envelope.status !== 'ok');
panel.opening_fail((refused?.renderedErr ?? '').replace(/\x1b\[[0-9;]*m/g, '').trim() || 'the kernel refused');
panel.opening_fail(ansi_strip(refused?.renderedErr ?? '').trim() || 'the kernel refused');
}).catch((error: unknown): void => panel.opening_fail(error instanceof Error ? error.message : String(error)));
return id;
};
Expand Down
5 changes: 3 additions & 2 deletions apps/argus/src/app/feedRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
* A module of the host: the host builds the feed verbs once
* (`feedVerbs_wire`) and hands them to every roster.
*/
import type { FeedListEntry } from '@fnndsc/menu';
import { ansi_strip, type FeedListEntry } from '@fnndsc/menu';

import type { ExecuteOutcome } from '../calypso/client.js';
import type { ListingAction } from '../features/roster/row.js';
import { RUNS_ROW_ROSTER, type RunsRowFacts } from '../features/roster/verbs.js';
Expand Down Expand Up @@ -108,7 +109,7 @@ export function feedRowHandlers_make(context: Pick<HostContext, 'panels' | 'subj
const quiet = { silent: true, observe: false };
const text_extract = (outcome: ExecuteOutcome | null): string | null =>
outcome !== null && outcome.envelopes.every((envelope): boolean => envelope.status === 'ok')
? outcome.envelopes.map((envelope): string => envelope.rendered).join('').replace(/\x1b\[[0-9;]*m/g, '')
? ansi_strip(outcome.envelopes.map((envelope): string => envelope.rendered).join(''))
: null;
void Promise.all([
context.client.line_execute(`cat /proc/jobs/feed_${feedId}/note`, quiet).catch((): null => null),
Expand Down
4 changes: 2 additions & 2 deletions apps/argus/src/app/lineRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* @module
*/

import { LINE_DECLINED_MODEL_KIND } from '@fnndsc/menu';
import { ansi_strip, LINE_DECLINED_MODEL_KIND } from '@fnndsc/menu';

import type { ExecuteOutcome, SurfaceAsk } from '../calypso/client.js';
import type { AskAbout, RunEnd } from '../features/script/model.js';
Expand Down Expand Up @@ -84,7 +84,7 @@ export function runEnd_read(outcome: ExecuteOutcome): RunEnd {
// channel, colour removed. Never what the line happened to print on the way.
const why: string[] = ok ? [] : refused.flatMap((envelope): string[] => (envelope.errors !== undefined && envelope.errors.length > 0
? envelope.errors.map((error): string => error.message)
: (envelope.renderedErr ?? '').replace(/\x1b\[[0-9;]*m/g, '').split('\n'))).map((line: string): string => line.trim()).filter((line: string): boolean => line !== '');
: ansi_strip(envelope.renderedErr ?? '').split('\n'))).map((line: string): string => line.trim()).filter((line: string): boolean => line !== '');
if (!ok && why.length === 0) why.push(outcome.exitCode !== undefined && outcome.exitCode !== 0 ? `the line ended with status ${String(outcome.exitCode)}, and the session gave no reason` : 'the session refused it, and gave no reason');
return { ok, declined: outcome.envelopes.some((envelope): boolean => envelope.model?.kind === LINE_DECLINED_MODEL_KIND), why };
}
Expand Down
7 changes: 3 additions & 4 deletions apps/argus/src/app/surfaceHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
*
* @module
*/
import type { WireEnvelope } from '@fnndsc/menu';
import { ansi_strip, type WireEnvelope } from '@fnndsc/menu';

import { binView_wire } from './binView.js';
import { browser_wire } from './browser.js';
Expand Down Expand Up @@ -452,10 +452,9 @@ export function surfaceRun_wire(s: Pick<SurfaceState, 'askOnPane_await' | 'catal
panel.run_show(data.feedId);
return;
}
const refusal: string = outcome.envelopes
const refusal: string = ansi_strip(outcome.envelopes
.map((envelope: WireEnvelope): string => envelope.renderedErr ?? '')
.join(' ')
.replace(/\x1b\[[0-9;]*m/g, '')
.join(' '))
.trim()
.split('\n')[0] ?? '';
const indicated: string | null = panel.indicated_get();
Expand Down
25 changes: 5 additions & 20 deletions apps/argus/src/calypso/answerModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,21 @@
* - `answerModel_extract`: the first model of a kind an answer carries, parsed.
* - `answerListings_extract`: the listings an `ls` answered.
* - `answerText_extract`: the text an answer rendered, plain.
* - `plain_extract`: a terminal's colour codes and carriage returns stripped.
* - `ansi_strip`: a terminal's escape sequences stripped (carriage returns kept).
* - `plain_extract`: a terminal's escape sequences (menu's grammar) and carriage returns stripped.
* - `ParsedModel`: a schema's safe parse, as a reading takes it.
*
* Typical usage:
* ```ts
* const model = answerModel_extract(answer, STRATUS_VM_COST_MODEL_KIND, (data: unknown) => vmCostModelSchema.safeParse(data));
* ```
*
* Dependencies: none; an answer is anything with envelopes.
* Dependencies: menu's escape grammar; an answer is anything with envelopes.
*
* @module
*/

import { ansi_strip } from '@fnndsc/menu';

/**
* An answer as these readings see it: its envelopes, each with what it rendered and the model it carries.
*
Expand Down Expand Up @@ -66,21 +67,6 @@ export interface ParsedModel<T> {
data?: T;
}

/**
* Strips ANSI escape sequences from rendered text; carriage returns are kept.
*
* @param text - The ANSI-decorated text.
* @returns The plain text.
*
* @example
* ```ts
* ansi_strip('\x1b[1mfeed_21\x1b[0m'); // 'feed_21'
* ```
*/
export function ansi_strip(text: string): string {
return text.replace(/\x1b\[[0-9;:]*[A-Za-z]/g, '');
}

/**
* Strips a terminal's colour codes and carriage returns from text a screen shows.
*
Expand All @@ -93,8 +79,7 @@ export function ansi_strip(text: string): string {
* ```
*/
export function plain_extract(text: string): string {
// eslint-disable-next-line no-control-regex
return text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r/g, '');
return ansi_strip(text).replace(/\r/g, '');
}

/**
Expand Down
Loading
Loading