@userspace-dev/ansi 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.
package/dist/screen.js ADDED
@@ -0,0 +1,508 @@
1
+ import { readLink, SAFE_PROTOCOLS } from "./link.js";
2
+ import { Row } from "./row.js";
3
+ import { createSgr, PLAIN } from "./style.js";
4
+ import { createTokenizer } from "./tokenizer.js";
5
+ import { clusters, clusterWidth, isNarrow, join, mayJoin } from "./width.js";
6
+ const TAB = 8;
7
+ /**
8
+ * No terminal is larger. Without a limit, a few bytes of cursor movement could
9
+ * make a line of billions of cells.
10
+ */
11
+ const MAX_COUNT = 1_000;
12
+ /** Old lines are dropped this many at a time, since shifting rows is slow. */
13
+ const TRIM_BATCH = 256;
14
+ /**
15
+ * Follows the cursor the way a terminal does, so spinners, progress bars and
16
+ * redrawn lines end up as the lines a person would see. A line feed also
17
+ * returns to the first column, since captured output rarely has `\r\n`.
18
+ */
19
+ export function createScreen({ columns = Infinity, rows: height = 24, maxLines = Infinity, protocols = SAFE_PROTOCOLS, } = {}) {
20
+ /** Where cursor movement stops on lines that never wrap. */
21
+ const limit = Math.min(columns, MAX_COUNT);
22
+ const applySgr = createSgr();
23
+ let nextId = 0;
24
+ let main = createBuffer(height);
25
+ let buffer = main;
26
+ /** The cursor saved on the alternate screen, which outlives it. */
27
+ let alternateSaved = main.saved;
28
+ let style = PLAIN;
29
+ let link;
30
+ /** The character before the cursor, which the next chunk may still extend. */
31
+ let previous = null;
32
+ let dropped = 0;
33
+ let view = null;
34
+ /** Lines that still exist, but are over the limit. */
35
+ let hidden = 0;
36
+ const createRow = () => new Row(nextId++);
37
+ const lastRow = () => buffer.base + height - 1;
38
+ /** The last column, where movement stops. */
39
+ const column = () => Math.min(buffer.x, columns - 1);
40
+ /** The row at an index, about to be changed. */
41
+ const rowAt = (index) => {
42
+ while (buffer.rows.length <= index)
43
+ buffer.rows.push(createRow());
44
+ view = null;
45
+ return buffer.rows[index];
46
+ };
47
+ const currentRow = () => rowAt(buffer.y);
48
+ const regionTop = () => buffer.base + buffer.top;
49
+ const regionBottom = () => buffer.base + buffer.bottom;
50
+ /** Moves lines up within the region, starting at a row. */
51
+ const scrollUp = (from, count) => {
52
+ const end = regionBottom();
53
+ const amount = Math.min(count, end - from + 1);
54
+ rowAt(end);
55
+ buffer.rows.splice(from, amount);
56
+ buffer.rows.splice(end - amount + 1, 0, ...Array.from({ length: amount }, createRow));
57
+ };
58
+ /** Moves lines down within the region, starting at a row. */
59
+ const scrollDown = (from, count) => {
60
+ const end = regionBottom();
61
+ const amount = Math.min(count, end - from + 1);
62
+ rowAt(end);
63
+ buffer.rows.splice(end - amount + 1, amount);
64
+ buffer.rows.splice(from, 0, ...Array.from({ length: amount }, createRow));
65
+ };
66
+ const lineFeed = () => {
67
+ currentRow();
68
+ if (buffer.y === regionBottom()) {
69
+ if (buffer.top === 0 && buffer === main) {
70
+ // Lines that leave at the very top are kept.
71
+ rowAt(buffer.y);
72
+ buffer.rows.splice(buffer.y + 1, 0, createRow());
73
+ buffer.base++;
74
+ buffer.y++;
75
+ trim();
76
+ }
77
+ else {
78
+ scrollUp(regionTop(), 1);
79
+ }
80
+ }
81
+ else if (buffer.y < lastRow()) {
82
+ buffer.y++;
83
+ }
84
+ currentRow();
85
+ };
86
+ const trim = () => {
87
+ buffer.rows[buffer.base - 1]?.freeze();
88
+ const excess = Math.min(buffer.base, buffer.rows.length - Math.max(maxLines, height));
89
+ if (excess >= TRIM_BATCH) {
90
+ buffer.rows.splice(0, excess);
91
+ buffer.base -= excess;
92
+ buffer.y -= excess;
93
+ buffer.saved.y -= excess;
94
+ dropped += excess;
95
+ }
96
+ };
97
+ const wrap = () => {
98
+ // A wide character that does not fit leaves its column empty.
99
+ currentRow().truncate(buffer.x);
100
+ buffer.x = 0;
101
+ lineFeed();
102
+ };
103
+ const writeNarrow = (text) => {
104
+ let rest = text;
105
+ while (rest) {
106
+ if (buffer.x >= columns)
107
+ wrap();
108
+ const part = rest.slice(0, columns - buffer.x);
109
+ currentRow().write(buffer.x, part, part.length, style, link);
110
+ buffer.x += part.length;
111
+ rest = rest.slice(part.length);
112
+ }
113
+ previous = { text: text.slice(-1), width: 1 };
114
+ };
115
+ const writeCluster = (text) => {
116
+ const whole = previous && join(previous.text, text);
117
+ if (previous && whole !== null) {
118
+ const added = whole.slice(previous.text.length);
119
+ const room = columns - buffer.x;
120
+ const grow = Math.min(clusterWidth(whole) - previous.width, room);
121
+ const extra = Math.max(0, grow);
122
+ if (added)
123
+ currentRow().join(buffer.x, previous.width, added, extra);
124
+ buffer.x += extra;
125
+ previous = { text: whole, width: previous.width + extra };
126
+ return;
127
+ }
128
+ const width = clusterWidth(text);
129
+ // A mark without anything to mark.
130
+ if (width === 0)
131
+ return;
132
+ if (buffer.x + width > columns && buffer.x > 0)
133
+ wrap();
134
+ currentRow().write(buffer.x, text, width, style, link);
135
+ buffer.x += width;
136
+ previous = { text, width };
137
+ };
138
+ const write = (text) => {
139
+ if (isNarrow(text) && !(previous && mayJoin(previous.text))) {
140
+ writeNarrow(text);
141
+ return;
142
+ }
143
+ for (const cluster of clusters(text)) {
144
+ writeCluster(cluster);
145
+ }
146
+ };
147
+ const nextTab = (x) => {
148
+ if (!buffer.tabs)
149
+ return Math.min((Math.floor(x / TAB) + 1) * TAB, limit - 1);
150
+ for (let i = x + 1; i < limit; i++)
151
+ if (buffer.tabs.has(i))
152
+ return i;
153
+ return limit - 1;
154
+ };
155
+ const previousTab = (x) => {
156
+ if (!buffer.tabs)
157
+ return Math.max(0, Math.ceil(x / TAB) - 1) * TAB;
158
+ for (let i = x - 1; i > 0; i--)
159
+ if (buffer.tabs.has(i))
160
+ return i;
161
+ return 0;
162
+ };
163
+ const ownTabs = () => {
164
+ if (!buffer.tabs) {
165
+ buffer.tabs = new Set();
166
+ for (let i = 0; i < limit; i += TAB)
167
+ buffer.tabs.add(i);
168
+ }
169
+ return buffer.tabs;
170
+ };
171
+ const control = (code) => {
172
+ previous = null;
173
+ switch (code) {
174
+ case 0x08:
175
+ buffer.x = Math.max(0, column() - 1);
176
+ break;
177
+ case 0x09:
178
+ // Tabs reach further than other movement, as they cost a byte each.
179
+ if (buffer.x < columns) {
180
+ buffer.x =
181
+ buffer.x >= limit - 1 && columns > limit
182
+ ? buffer.x + TAB - (buffer.x % TAB)
183
+ : nextTab(buffer.x);
184
+ }
185
+ break;
186
+ case 0x0a:
187
+ case 0x0b:
188
+ case 0x0c:
189
+ case 0x85:
190
+ buffer.x = 0;
191
+ lineFeed();
192
+ break;
193
+ case 0x0d:
194
+ buffer.x = 0;
195
+ break;
196
+ case 0x84:
197
+ lineFeed();
198
+ break;
199
+ case 0x88:
200
+ ownTabs().add(buffer.x);
201
+ break;
202
+ }
203
+ };
204
+ const moveTo = (x, y) => {
205
+ buffer.x = Math.max(0, Math.min(x, limit - 1));
206
+ buffer.y = Math.max(buffer.base, Math.min(y, lastRow()));
207
+ };
208
+ /** Moves up or down, stopping at the edge of the region when inside it. */
209
+ const moveBy = (x, rows) => {
210
+ const { y } = buffer;
211
+ const first = y >= regionTop() ? regionTop() : buffer.base;
212
+ const last = y <= regionBottom() ? regionBottom() : lastRow();
213
+ moveTo(x, Math.max(first, Math.min(y + rows, last)));
214
+ };
215
+ const eraseLine = (mode) => {
216
+ const row = currentRow();
217
+ if (mode === 0)
218
+ row.truncate(buffer.x);
219
+ else if (mode === 1)
220
+ row.blank(0, buffer.x + 1);
221
+ else if (mode === 2)
222
+ row.truncate(0);
223
+ };
224
+ const clearRows = (from, to) => {
225
+ for (let i = from; i < Math.min(to, buffer.rows.length); i++) {
226
+ rowAt(i).truncate(0);
227
+ }
228
+ };
229
+ const eraseDisplay = (mode) => {
230
+ view = null;
231
+ if (mode === 0) {
232
+ eraseLine(0);
233
+ buffer.rows.length = Math.min(buffer.rows.length, buffer.y + 1);
234
+ }
235
+ else if (mode === 1) {
236
+ clearRows(buffer.base, buffer.y);
237
+ eraseLine(1);
238
+ }
239
+ else if (mode === 2) {
240
+ clearRows(buffer.base, lastRow() + 1);
241
+ }
242
+ else if (mode === 3) {
243
+ buffer.rows.splice(0, buffer.base);
244
+ buffer.y -= buffer.base;
245
+ buffer.saved.y -= buffer.base;
246
+ buffer.base = 0;
247
+ }
248
+ };
249
+ const save = () => {
250
+ buffer.saved = { x: buffer.x, y: buffer.y, style };
251
+ };
252
+ const restore = () => {
253
+ style = buffer.saved.style;
254
+ moveTo(buffer.saved.x, buffer.saved.y);
255
+ };
256
+ /** Switches to a blank second screen, or back to what was there before. */
257
+ const setAlternate = (on) => {
258
+ if (on === (buffer !== main))
259
+ return;
260
+ const { x, y, base, saved } = buffer;
261
+ if (on) {
262
+ buffer = createBuffer(height);
263
+ buffer.saved = alternateSaved;
264
+ }
265
+ else {
266
+ buffer = main;
267
+ alternateSaved = saved;
268
+ }
269
+ buffer.x = x;
270
+ buffer.y = buffer.base + (y - base);
271
+ view = null;
272
+ };
273
+ const setMode = (mode, on) => {
274
+ switch (mode) {
275
+ case "47":
276
+ case "1047":
277
+ setAlternate(on);
278
+ break;
279
+ case "1048":
280
+ if (on)
281
+ save();
282
+ else
283
+ restore();
284
+ break;
285
+ case "1049":
286
+ if (on)
287
+ save();
288
+ setAlternate(on);
289
+ if (!on)
290
+ restore();
291
+ break;
292
+ }
293
+ };
294
+ const setRegion = (first, last) => {
295
+ const bottom = last === 0 || last > height ? height : last;
296
+ const top = first || 1;
297
+ if (bottom > top) {
298
+ buffer.top = top - 1;
299
+ buffer.bottom = bottom - 1;
300
+ moveTo(0, buffer.base);
301
+ }
302
+ };
303
+ const isInRegion = () => buffer.y >= regionTop() && buffer.y <= regionBottom();
304
+ const csi = ({ prefix, params, intermediates, final }) => {
305
+ if (final === "m" && !prefix && !intermediates) {
306
+ style = applySgr(style, params);
307
+ return;
308
+ }
309
+ previous = null;
310
+ if (intermediates)
311
+ return;
312
+ if (prefix) {
313
+ if (prefix === "?" && (final === "h" || final === "l")) {
314
+ for (const mode of params.split(";"))
315
+ setMode(mode, final === "h");
316
+ }
317
+ return;
318
+ }
319
+ const [first = 0, second = 0] = params
320
+ .split(";")
321
+ .map((value) => Number.parseInt(value, 10) || 0);
322
+ const count = Math.min(first || 1, MAX_COUNT);
323
+ switch (final) {
324
+ case "A":
325
+ moveBy(column(), -count);
326
+ break;
327
+ case "B":
328
+ moveBy(column(), count);
329
+ break;
330
+ case "C":
331
+ case "a":
332
+ moveTo(column() + count, buffer.y);
333
+ break;
334
+ case "D":
335
+ moveTo(column() - count, buffer.y);
336
+ break;
337
+ case "E":
338
+ moveBy(0, count);
339
+ break;
340
+ case "F":
341
+ moveBy(0, -count);
342
+ break;
343
+ case "G":
344
+ case "`":
345
+ moveTo(count - 1, buffer.y);
346
+ break;
347
+ case "d":
348
+ moveTo(column(), buffer.base + count - 1);
349
+ break;
350
+ case "e":
351
+ moveTo(column(), buffer.y + count);
352
+ break;
353
+ case "H":
354
+ case "f":
355
+ moveTo(Math.min(second || 1, MAX_COUNT) - 1, buffer.base + count - 1);
356
+ break;
357
+ case "I":
358
+ for (let i = 0; i < count && buffer.x < limit - 1; i++) {
359
+ buffer.x = nextTab(buffer.x);
360
+ }
361
+ break;
362
+ case "Z":
363
+ if (buffer.x >= columns)
364
+ break;
365
+ for (let i = 0; i < count && buffer.x > 0; i++) {
366
+ buffer.x = previousTab(buffer.x);
367
+ }
368
+ break;
369
+ case "g":
370
+ if (first === 0)
371
+ ownTabs().delete(buffer.x);
372
+ else if (first === 3)
373
+ buffer.tabs = new Set();
374
+ break;
375
+ case "J":
376
+ eraseDisplay(first);
377
+ break;
378
+ case "K":
379
+ eraseLine(first);
380
+ break;
381
+ case "X":
382
+ buffer.x = column();
383
+ currentRow().blank(buffer.x, buffer.x + count);
384
+ break;
385
+ case "P":
386
+ buffer.x = column();
387
+ currentRow().remove(buffer.x, count);
388
+ break;
389
+ case "@":
390
+ buffer.x = column();
391
+ currentRow().insert(buffer.x, count, limit);
392
+ break;
393
+ case "L":
394
+ if (isInRegion()) {
395
+ scrollDown(buffer.y, count);
396
+ buffer.x = 0;
397
+ }
398
+ break;
399
+ case "M":
400
+ if (isInRegion()) {
401
+ scrollUp(buffer.y, count);
402
+ buffer.x = 0;
403
+ }
404
+ break;
405
+ case "S":
406
+ scrollUp(regionTop(), count);
407
+ break;
408
+ case "T":
409
+ scrollDown(regionTop(), count);
410
+ break;
411
+ case "r":
412
+ setRegion(first, second);
413
+ break;
414
+ case "s":
415
+ save();
416
+ break;
417
+ case "u":
418
+ restore();
419
+ break;
420
+ }
421
+ };
422
+ const esc = (intermediates, final) => {
423
+ previous = null;
424
+ if (intermediates)
425
+ return;
426
+ switch (final) {
427
+ case "7":
428
+ save();
429
+ break;
430
+ case "8":
431
+ restore();
432
+ break;
433
+ case "c":
434
+ reset();
435
+ break;
436
+ case "D":
437
+ buffer.x = column();
438
+ lineFeed();
439
+ break;
440
+ case "E":
441
+ buffer.x = 0;
442
+ lineFeed();
443
+ break;
444
+ case "H":
445
+ ownTabs().add(buffer.x);
446
+ break;
447
+ case "M":
448
+ buffer.x = column();
449
+ if (buffer.y === regionTop())
450
+ scrollDown(buffer.y, 1);
451
+ else if (buffer.y > buffer.base)
452
+ buffer.y--;
453
+ break;
454
+ }
455
+ };
456
+ const reset = () => {
457
+ main = buffer = createBuffer(height);
458
+ alternateSaved = main.saved;
459
+ style = PLAIN;
460
+ link = undefined;
461
+ previous = null;
462
+ dropped = 0;
463
+ view = null;
464
+ };
465
+ const tokenizer = createTokenizer({
466
+ text: write,
467
+ control,
468
+ csi,
469
+ esc,
470
+ osc(data) {
471
+ const next = readLink(data, protocols);
472
+ if (next !== null)
473
+ link = next;
474
+ },
475
+ });
476
+ const lines = () => {
477
+ if (!view) {
478
+ const all = buffer.rows.map((row) => row.line());
479
+ while (all.at(-1)?.segments.length === 0)
480
+ all.pop();
481
+ hidden = Math.max(0, all.length - maxLines);
482
+ view = hidden > 0 ? all.slice(hidden) : all;
483
+ }
484
+ return view;
485
+ };
486
+ return {
487
+ write: tokenizer.write,
488
+ end: tokenizer.end,
489
+ lines,
490
+ get droppedLines() {
491
+ lines();
492
+ return dropped + hidden;
493
+ },
494
+ reset,
495
+ };
496
+ }
497
+ function createBuffer(height) {
498
+ return {
499
+ rows: [],
500
+ base: 0,
501
+ x: 0,
502
+ y: 0,
503
+ saved: { x: 0, y: 0, style: PLAIN },
504
+ top: 0,
505
+ bottom: height - 1,
506
+ tabs: null,
507
+ };
508
+ }
@@ -0,0 +1,10 @@
1
+ import { type ParserOptions, type Segment } from "./parser.ts";
2
+ /**
3
+ * A transform stream from text to segments.
4
+ *
5
+ * @example
6
+ * response.body
7
+ * .pipeThrough(new TextDecoderStream())
8
+ * .pipeThrough(createAnsiStream())
9
+ */
10
+ export declare function createAnsiStream(options?: ParserOptions): TransformStream<string, Segment[]>;
package/dist/stream.js ADDED
@@ -0,0 +1,24 @@
1
+ import { createParser } from "./parser.js";
2
+ /**
3
+ * A transform stream from text to segments.
4
+ *
5
+ * @example
6
+ * response.body
7
+ * .pipeThrough(new TextDecoderStream())
8
+ * .pipeThrough(createAnsiStream())
9
+ */
10
+ export function createAnsiStream(options) {
11
+ const parser = createParser(options);
12
+ return new TransformStream({
13
+ transform(chunk, controller) {
14
+ const segments = parser.write(chunk);
15
+ if (segments.length > 0)
16
+ controller.enqueue(segments);
17
+ },
18
+ flush(controller) {
19
+ const segments = parser.end();
20
+ if (segments.length > 0)
21
+ controller.enqueue(segments);
22
+ },
23
+ });
24
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Removes every escape sequence and control character except tabs, line feeds
3
+ * and carriage returns. All text stays, including text that a terminal would
4
+ * have overwritten; use `toText` for what was left on screen.
5
+ */
6
+ export declare function strip(text: string): string;
package/dist/strip.js ADDED
@@ -0,0 +1,33 @@
1
+ import { createTokenizer } from "./tokenizer.js";
2
+ // Anything that is not text, a tab, a line feed or a carriage return.
3
+ const NEEDS_WORK = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
4
+ /**
5
+ * Removes every escape sequence and control character except tabs, line feeds
6
+ * and carriage returns. All text stays, including text that a terminal would
7
+ * have overwritten; use `toText` for what was left on screen.
8
+ */
9
+ export function strip(text) {
10
+ if (!NEEDS_WORK.test(text)) {
11
+ return text;
12
+ }
13
+ let result = "";
14
+ const tokenizer = createTokenizer({
15
+ text(value) {
16
+ result += value;
17
+ },
18
+ control(code) {
19
+ if (code === 0x09 || code === 0x0a || code === 0x0d) {
20
+ result += String.fromCharCode(code);
21
+ }
22
+ else if (code === 0x85) {
23
+ result += "\n";
24
+ }
25
+ },
26
+ csi() { },
27
+ esc() { },
28
+ osc() { },
29
+ });
30
+ tokenizer.write(text);
31
+ tokenizer.end();
32
+ return result;
33
+ }
@@ -0,0 +1,29 @@
1
+ /** A palette index from 0 to 255, or a hex color. */
2
+ export type Color = number | `#${string}`;
3
+ export type Underline = "single" | "double" | "curly" | "dotted" | "dashed";
4
+ /** Only what is on is present, so a plain style is an empty object. */
5
+ export type Style = {
6
+ readonly fg?: Color;
7
+ readonly bg?: Color;
8
+ readonly underlineColor?: Color;
9
+ readonly underline?: Underline;
10
+ readonly bold?: true;
11
+ readonly dim?: true;
12
+ readonly italic?: true;
13
+ readonly blink?: true;
14
+ readonly inverse?: true;
15
+ /** Concealed: present in the output, invisible to a person. */
16
+ readonly hidden?: true;
17
+ readonly strike?: true;
18
+ readonly overline?: true;
19
+ };
20
+ export declare const PLAIN: Style;
21
+ /**
22
+ * Applies SGR parameters, remembering the results. Output repeats a handful of
23
+ * styles, and the same style is then the same object.
24
+ */
25
+ export declare function createSgr(): (style: Style, params: string) => Style;
26
+ /** Applies the parameters of an SGR sequence (`ESC [ … m`) to a style. */
27
+ export declare function applySgr(style: Style, params: string): Style;
28
+ export declare function isSameStyle(a: Style, b: Style): boolean;
29
+ export declare function hex(r: number, g: number, b: number): `#${string}`;