@nbtca/prompt 1.5.13 → 1.5.15

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.
@@ -1,11 +1,27 @@
1
1
  import chalk from 'chalk';
2
- import gradient from 'gradient-string';
3
2
  import { pickIcon } from './icons.js';
4
- export const brandGradient = gradient([
5
- { color: '#124689', pos: 0 },
6
- { color: '#0ea5e9', pos: 0.55 },
7
- { color: '#06b6d4', pos: 1 },
8
- ]);
3
+ const BRAND_STOPS = [
4
+ { at: 0, rgb: [0x12, 0x46, 0x89] },
5
+ { at: 0.55, rgb: [0x0e, 0xa5, 0xe9] },
6
+ { at: 1, rgb: [0x06, 0xb6, 0xd4] },
7
+ ];
8
+ function brandColorAt(position) {
9
+ const upper = BRAND_STOPS.findIndex((stop) => stop.at >= position);
10
+ const to = BRAND_STOPS[Math.max(upper, 1)] ?? BRAND_STOPS[2];
11
+ const from = BRAND_STOPS[Math.max(upper, 1) - 1] ?? BRAND_STOPS[0];
12
+ const ratio = (position - from.at) / (to.at - from.at);
13
+ const mix = (index) => Math.round(from.rgb[index] + (to.rgb[index] - from.rgb[index]) * ratio);
14
+ return [mix(0), mix(1), mix(2)];
15
+ }
16
+ export function brandGradient(text) {
17
+ const lines = text.split('\n').map((line) => Array.from(line));
18
+ const span = Math.max(1, ...lines.map((line) => line.length - 1));
19
+ return lines
20
+ .map((line) => line
21
+ .map((char, column) => char.trim() ? chalk.rgb(...brandColorAt(Math.min(1, column / span)))(char) : char)
22
+ .join(''))
23
+ .join('\n');
24
+ }
9
25
  export function brandMark(s) {
10
26
  if (process.env['NO_COLOR'])
11
27
  return s;
@@ -17,11 +33,12 @@ export const c = {
17
33
  success: (s) => chalk.green(s),
18
34
  error: (s) => chalk.red(s),
19
35
  warn: (s) => chalk.yellow(s),
20
- heading: (s) => chalk.bold.white(s),
36
+ heading: (s) => chalk.bold(s),
21
37
  muted: (s) => chalk.dim(s),
22
38
  subtle: (s) => chalk.gray(s),
23
39
  label: (s) => chalk.bold.cyan(s),
24
40
  url: (s) => chalk.dim.underline(s),
41
+ code: (s) => chalk.yellow(s),
25
42
  version: (s) => chalk.dim(s),
26
43
  latency: (ms) => {
27
44
  const s = `${ms}ms`;
@@ -35,6 +52,7 @@ export const c = {
35
52
  export const glyph = {
36
53
  cursor: () => pickIcon('→', '>'),
37
54
  rule: () => pickIcon('─', '-'),
55
+ bar: () => pickIcon('│', '|'),
38
56
  bullet: () => pickIcon('·', '.'),
39
57
  dot: () => pickIcon('●', '*'),
40
58
  updown: () => pickIcon('↑↓', 'up/down'),
@@ -48,8 +66,8 @@ export const space = {
48
66
  indent: ' ',
49
67
  };
50
68
  export const type = {
51
- heading: (s) => chalk.bold.white(s),
52
- label: (s) => chalk.white(s),
69
+ heading: (s) => chalk.bold(s),
70
+ label: (s) => s,
53
71
  body: (s) => s,
54
72
  hint: (s) => chalk.dim(s),
55
73
  active: (s) => chalk.bold(c.brand(s)),
@@ -1,4 +1,7 @@
1
+ import { addLocalDays } from '../core/calendar-day.js';
2
+ import { fmt, t } from '../i18n/index.js';
1
3
  const UPCOMING_DAYS = 30;
4
+ const YEAR_DAYS = 365;
2
5
  export function weekRange(now) {
3
6
  const start = new Date(now);
4
7
  start.setHours(0, 0, 0, 0);
@@ -13,18 +16,37 @@ export function dayRange(now) {
13
16
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
14
17
  return { start, end };
15
18
  }
19
+ export function eventEnd(event) {
20
+ return (event.end ??
21
+ (event.isAllDay
22
+ ? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
23
+ : event.start));
24
+ }
25
+ function hasEnded(event, now) {
26
+ return event.start < now && eventEnd(event) <= now;
27
+ }
16
28
  export function currentEvents(calendar, now) {
17
29
  const { start } = dayRange(now);
18
30
  const end = new Date(now.getTime() + UPCOMING_DAYS * 86_400_000);
19
- return calendar.inRange(start, end).filter((event) => {
20
- if (event.start >= now)
21
- return true;
22
- const eventEnd = event.end ??
23
- (event.isAllDay
24
- ? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
25
- : event.start);
26
- return eventEnd > now;
27
- });
31
+ return calendar.inRange(start, end).filter((event) => !hasEnded(event, now));
32
+ }
33
+ export function pastYearRange(now) {
34
+ return { start: addLocalDays(now, -YEAR_DAYS), end: now };
35
+ }
36
+ export function pastEvents(calendar, now) {
37
+ const { start, end } = pastYearRange(now);
38
+ return calendar
39
+ .inRange(start, end)
40
+ .filter((event) => hasEnded(event, now))
41
+ .reverse();
42
+ }
43
+ export function searchEvents(calendar, query, now) {
44
+ const pool = calendar.inRange(pastYearRange(now).start, addLocalDays(now, YEAR_DAYS));
45
+ const matches = filterEvents(pool, query);
46
+ return {
47
+ upcoming: matches.filter((event) => !hasEnded(event, now)),
48
+ past: matches.filter((event) => hasEnded(event, now)).reverse(),
49
+ };
28
50
  }
29
51
  export function monthRange(now) {
30
52
  const start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
@@ -49,6 +71,14 @@ export function countdownParts(target, now) {
49
71
  minutes: totalMin % 60,
50
72
  };
51
73
  }
74
+ export function formatDuration(p) {
75
+ const d = t().calendar.duration;
76
+ if (p.days > 0)
77
+ return fmt(d.days, { days: p.days, hours: p.hours });
78
+ if (p.hours > 0)
79
+ return fmt(d.hours, { hours: p.hours, minutes: p.minutes });
80
+ return fmt(d.minutes, { minutes: p.minutes });
81
+ }
52
82
  /** True once a countdown is close enough to call out visually (default: 15
53
83
  * minutes or less). A `past` countdown is never urgent — there's nothing
54
84
  * left to hurry for. */
@@ -4,8 +4,8 @@ import { c, type, space, glyph } from '../core/theme.js';
4
4
  import { pickIcon } from '../core/icons.js';
5
5
  import { padEndV, sanitizeTerminalLine, sanitizeTerminalText, truncate, visualWidth, wrapAnsiWithIndent, wrapAnsiToVisualWidth, } from '../core/text.js';
6
6
  import { t } from '../i18n/index.js';
7
- import { addLocalDays, localDayDifference } from '../core/calendar-day.js';
8
- import { countdownParts, isCountdownUrgent, buildExportFilename } from './calendar-query.js';
7
+ import { localDayDifference } from '../core/calendar-day.js';
8
+ import { countdownParts, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
9
9
  import { loadFeedCache, saveFeedCache } from './calendar-store.js';
10
10
  import { writeFileSync, existsSync } from 'fs';
11
11
  import { join } from 'path';
@@ -88,7 +88,7 @@ export async function loadCalendarOrCache(signal) {
88
88
  }
89
89
  }
90
90
  export function yearHeatmap(calendar, now) {
91
- return calendar.heatmap({ start: addLocalDays(now, -365), end: now, bucket: 'day' });
91
+ return calendar.heatmap({ ...pastYearRange(now), bucket: 'day' });
92
92
  }
93
93
  export function serializeEvents(events) {
94
94
  return events.map((event) => ({
@@ -166,7 +166,22 @@ function styleTitle(title, style) {
166
166
  return style(title);
167
167
  return `${type.hint(match[1])}${match[2]}${style(title.slice(match[0].length))}`;
168
168
  }
169
- export function renderEventBrief(e, now) {
169
+ const TIME_COLUMN = ' 00:00'.length;
170
+ export function eventWhen(e) {
171
+ return e.time ? `${e.date} ${e.time}` : padEndV(e.date, visualWidth(e.date) + TIME_COLUMN);
172
+ }
173
+ export function recurringMark(e) {
174
+ return e.recurring ? ` ${pickIcon('↻', '~')}` : '';
175
+ }
176
+ function hangingLines(marker, content, cols) {
177
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
178
+ const prefixes = [`${space.indent}${marker} `, `${marker} `, marker, ''];
179
+ const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
180
+ const continuation = ' '.repeat(visualWidth(prefix));
181
+ const contentWidth = Math.max(1, width - visualWidth(prefix));
182
+ return wrapAnsiToVisualWidth(content, contentWidth).map((line, index) => `${index === 0 ? prefix : continuation}${line}`);
183
+ }
184
+ export function renderEventBriefLines(e, now, cols = Number.POSITIVE_INFINITY) {
170
185
  const dot = pickIcon('·', '-');
171
186
  const proximity = eventProximity(e.startDate, now);
172
187
  const dateStyle = proximity === 'today'
@@ -176,37 +191,26 @@ export function renderEventBrief(e, now) {
176
191
  : proximity === 'week'
177
192
  ? type.body
178
193
  : type.hint;
179
- const dateTime = `${e.date}${e.time ? ' ' + e.time : ''}`;
180
194
  const marker = proximity === 'today' ? type.active(pickIcon('●', '*')) : dateStyle(pickIcon('·', '-'));
181
195
  const titleStyled = styleTitle(e.title, proximity === 'today' ? type.active : type.body);
182
- const recurringMark = e.recurring ? ` ${type.hint(pickIcon('↻', '~'))}` : '';
183
- return `${space.indent}${marker} ${dateStyle(dateTime)} ${type.hint(dot)} ${titleStyled}${recurringMark}`;
196
+ const content = `${dateStyle(eventWhen(e))} ${type.hint(dot)} ${titleStyled}${type.hint(recurringMark(e))}`;
197
+ return hangingLines(marker, content, cols);
198
+ }
199
+ export function renderEventBrief(e, now) {
200
+ return renderEventBriefLines(e, now)[0] ?? '';
184
201
  }
185
202
  export function renderCountdownBanner(event, now, cols = Number.POSITIVE_INFINITY) {
186
203
  if (!event)
187
204
  return '';
188
205
  const trans = t();
189
206
  const p = countdownParts(event.startDate, now);
190
- const inp = trans.calendar.inPrefix;
191
207
  const when = p.past
192
208
  ? trans.calendar.startingNow
193
- : p.days > 0
194
- ? `${inp} ${p.days}d ${p.hours}h`
195
- : p.hours > 0
196
- ? `${inp} ${p.hours}h ${p.minutes}m`
197
- : `${inp} ${p.minutes}m`;
209
+ : `${trans.calendar.inPrefix} ${formatDuration(p)}`;
198
210
  const whenStyled = isCountdownUrgent(p) ? c.warn(when) : type.hint(when);
199
211
  const dot = pickIcon('·', '-');
200
- const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
201
- const cursor = type.active(glyph.cursor());
202
- const prefixes = [`${space.indent}${cursor} `, `${cursor} `, cursor, ''];
203
- const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
204
- const continuation = ' '.repeat(visualWidth(prefix));
205
- const contentWidth = Math.max(1, width - visualWidth(prefix));
206
212
  const content = `${type.label(trans.calendar.next)} ${dot} ${type.body(event.title)} ${dot} ${whenStyled}`;
207
- return wrapAnsiToVisualWidth(content, contentWidth)
208
- .map((line, index) => `${index === 0 ? prefix : continuation}${line}`)
209
- .join('\n');
213
+ return hangingLines(type.active(glyph.cursor()), content, cols).join('\n');
210
214
  }
211
215
  export function exportEventIcs(event, dir = process.cwd()) {
212
216
  const base = buildExportFilename(event);
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { createDocsClient } from '@nbtca/docs';
3
+ import { createDocsStore } from './docs-store.js';
3
4
  const contextKey = Symbol.for('@nbtca/prompt/docs-fetch-context/v2');
4
5
  const globalWithContext = globalThis;
5
6
  function abortError(signal) {
@@ -158,7 +159,8 @@ function beginDocsFetch() {
158
159
  },
159
160
  };
160
161
  }
161
- const defaultClient = createDocsClient();
162
+ const store = createDocsStore();
163
+ const defaultClient = createDocsClient({ store });
162
164
  const clientsBySignal = new WeakMap();
163
165
  const clients = new Set([defaultClient]);
164
166
  function clientFor(signal) {
@@ -167,7 +169,7 @@ function clientFor(signal) {
167
169
  const existing = clientsBySignal.get(signal);
168
170
  if (existing)
169
171
  return existing;
170
- const client = createDocsClient();
172
+ const client = createDocsClient({ store });
171
173
  clientsBySignal.set(signal, client);
172
174
  clients.add(client);
173
175
  signal.addEventListener('abort', () => {
@@ -177,6 +179,9 @@ function clientFor(signal) {
177
179
  }, { once: true });
178
180
  return client;
179
181
  }
182
+ export function peekDocs() {
183
+ return defaultClient.peekAll();
184
+ }
180
185
  export function clearDocsClients() {
181
186
  for (const client of clients)
182
187
  client.clear();
@@ -0,0 +1,265 @@
1
+ import chalk from 'chalk';
2
+ import { c, glyph, type } from '../core/theme.js';
3
+ import { pickIcon } from '../core/icons.js';
4
+ import { padEndV, sanitizeTerminalText, stripAnsi, visualWidth, wrapAnsiToVisualWidth, } from '../core/text.js';
5
+ export function isInternalHref(href) {
6
+ return /^\.{0,2}\/./.test(href);
7
+ }
8
+ const ENTITIES = {
9
+ amp: '&',
10
+ lt: '<',
11
+ gt: '>',
12
+ quot: '"',
13
+ apos: "'",
14
+ nbsp: ' ',
15
+ };
16
+ function decodeEntities(text) {
17
+ return text.replace(/&(?:#(\d{1,7})|#x([\da-f]{1,6})|([a-z]+));/gi, (match, dec, hex, name) => {
18
+ if (name)
19
+ return ENTITIES[name.toLowerCase()] ?? match;
20
+ const codePoint = dec ? Number(dec) : parseInt(hex ?? '', 16);
21
+ return codePoint <= 0x10ffff ? sanitizeTerminalText(String.fromCodePoint(codePoint)) : match;
22
+ });
23
+ }
24
+ const CJK = '[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\u3000-\\u303f\\uff00-\\uffef]';
25
+ const CJK_SOFT_BREAK = new RegExp(`(?<=${CJK})[ \\t]*\\n[ \\t]*(?=${CJK})`, 'gu');
26
+ function joinSoftBreaks(text) {
27
+ return text.replace(CJK_SOFT_BREAK, '').replace(/[ \t]*\n[ \t]*/g, ' ');
28
+ }
29
+ function renderInline(tokens, hrefs) {
30
+ return (tokens ?? []).map((token) => renderInlineToken(token, hrefs)).join('');
31
+ }
32
+ function renderLink(token, hrefs) {
33
+ const text = renderInline(token.tokens, hrefs);
34
+ const bare = (href) => href.replace(/^(?:https?:\/\/|mailto:)/, '').replace(/\/$/, '');
35
+ const selfLabelled = bare(stripAnsi(text)) === bare(token.href);
36
+ if (isInternalHref(token.href) || token.href.startsWith('#') || selfLabelled) {
37
+ return chalk.underline(c.accent(text));
38
+ }
39
+ return hrefs ? `${c.accent(text)} ${c.url(`(${token.href})`)}` : c.accent(text);
40
+ }
41
+ function renderInlineToken(token, hrefs) {
42
+ switch (token.type) {
43
+ case 'text':
44
+ return token.tokens
45
+ ? renderInline(token.tokens, hrefs)
46
+ : joinSoftBreaks(decodeEntities(token.text));
47
+ case 'escape':
48
+ return token.text;
49
+ case 'strong':
50
+ return chalk.bold(renderInline(token.tokens, hrefs));
51
+ case 'em':
52
+ return chalk.italic(renderInline(token.tokens, hrefs));
53
+ case 'del':
54
+ return chalk.strikethrough(c.muted(renderInline(token.tokens, hrefs)));
55
+ case 'codespan':
56
+ return c.code(token.text);
57
+ case 'br':
58
+ return '\n';
59
+ case 'link':
60
+ return renderLink(token, hrefs);
61
+ case 'image':
62
+ return `${pickIcon('🖼️', '[image]')} ${token.text || 'image'}`;
63
+ case 'html':
64
+ case 'blockquote':
65
+ case 'code':
66
+ case 'def':
67
+ case 'heading':
68
+ case 'hr':
69
+ case 'list':
70
+ case 'list_item':
71
+ case 'paragraph':
72
+ case 'space':
73
+ case 'table':
74
+ return '';
75
+ }
76
+ }
77
+ function wrap(text, width) {
78
+ return text.split('\n').flatMap((line) => wrapAnsiToVisualWidth(line, width));
79
+ }
80
+ function hang(lines, first, rest) {
81
+ return lines.map((line, index) => {
82
+ if (index === 0)
83
+ return first + line;
84
+ return line ? rest + line : '';
85
+ });
86
+ }
87
+ function styleHeading(text, depth) {
88
+ if (depth === 1)
89
+ return chalk.bold(c.brand(text));
90
+ if (depth === 2)
91
+ return type.heading(text);
92
+ if (depth === 3)
93
+ return c.label(text);
94
+ return chalk.bold(text);
95
+ }
96
+ function renderHeading(token, width) {
97
+ const lines = wrap(styleHeading(renderInline(token.tokens, false), token.depth), width);
98
+ if (token.depth !== 2)
99
+ return lines;
100
+ const underline = Math.min(width, Math.max(...lines.map(visualWidth)));
101
+ return [...lines, c.muted(glyph.rule().repeat(underline))];
102
+ }
103
+ function renderCode(token, width) {
104
+ const gutter = c.muted(glyph.bar());
105
+ const body = token.text
106
+ .replace(/\t/g, ' ')
107
+ .split('\n')
108
+ .flatMap((line) => wrapAnsiToVisualWidth(line, Math.max(1, width - 2)))
109
+ .map((line) => (line ? `${gutter} ${c.code(line)}` : gutter));
110
+ const lang = token.lang?.split(/\s/, 1)[0];
111
+ return lang ? [c.muted(lang), ...body] : body;
112
+ }
113
+ function renderBlockquote(token, width, depth) {
114
+ const bar = c.accent(glyph.bar());
115
+ return renderBlocks(token.tokens, Math.max(1, width - 2), depth, false).map((line) => line ? `${bar} ${line}` : bar);
116
+ }
117
+ const BULLETS = ['•', '◦', '▪'];
118
+ function renderList(token, width, depth) {
119
+ const start = token.start === '' ? 1 : token.start;
120
+ const bullet = pickIcon(BULLETS[depth % BULLETS.length] ?? '•', '-');
121
+ const numbers = token.items.map((_, index) => `${start + index}.`);
122
+ const numberWidth = Math.max(...numbers.map((label) => label.length));
123
+ const lines = [];
124
+ token.items.forEach((item, index) => {
125
+ const marker = token.ordered ? (numbers[index] ?? '').padStart(numberWidth) : bullet;
126
+ const box = item.task
127
+ ? item.checked
128
+ ? c.success(pickIcon('☑', '[x]'))
129
+ : c.muted(pickIcon('☐', '[ ]'))
130
+ : '';
131
+ const first = `${c.accent(marker)} ${box ? `${box} ` : ''}`;
132
+ const indent = ' '.repeat(visualWidth(first));
133
+ const body = renderBlocks(item.tokens, Math.max(1, width - indent.length), depth + 1, !token.loose);
134
+ if (token.loose && index > 0)
135
+ lines.push('');
136
+ lines.push(...hang(body.length > 0 ? body : [''], first, indent));
137
+ });
138
+ return lines;
139
+ }
140
+ const MIN_COLUMN = 6;
141
+ function alignCell(text, width, align) {
142
+ const pad = Math.max(0, width - visualWidth(text));
143
+ if (align === 'right')
144
+ return ' '.repeat(pad) + text;
145
+ if (align === 'center') {
146
+ const left = Math.floor(pad / 2);
147
+ return ' '.repeat(left) + text + ' '.repeat(pad - left);
148
+ }
149
+ return text + ' '.repeat(pad);
150
+ }
151
+ function cellWidth(text) {
152
+ return Math.max(0, ...text.split('\n').map(visualWidth));
153
+ }
154
+ function renderRecords(header, rows, width) {
155
+ const labelWidth = Math.min(Math.max(...header.map(visualWidth)), Math.max(1, Math.floor(width / 3)));
156
+ const valueWidth = Math.max(1, width - labelWidth - 2);
157
+ const lines = [];
158
+ rows.forEach((row, rowIndex) => {
159
+ if (rowIndex > 0)
160
+ lines.push(c.muted(glyph.rule().repeat(width)));
161
+ header.forEach((label, column) => {
162
+ const value = row[column] ?? '';
163
+ if (!stripAnsi(value).trim())
164
+ return;
165
+ const labels = wrapAnsiToVisualWidth(label, labelWidth);
166
+ const values = wrap(value, valueWidth);
167
+ for (let line = 0; line < Math.max(labels.length, values.length); line += 1) {
168
+ const text = values[line] ?? '';
169
+ lines.push(`${c.muted(padEndV(labels[line] ?? '', labelWidth))}${text ? ` ${text}` : ''}`);
170
+ }
171
+ });
172
+ });
173
+ return lines;
174
+ }
175
+ function renderTable(token, width) {
176
+ const header = token.header.map((cell) => renderInline(cell.tokens, false));
177
+ const rows = token.rows.map((row) => row.map((cell) => renderInline(cell.tokens, false)));
178
+ const natural = header.map((label, column) => Math.max(cellWidth(label), ...rows.map((row) => cellWidth(row[column] ?? ''))));
179
+ const available = width - (3 * header.length + 1);
180
+ const floor = natural.map((columnWidth) => Math.min(columnWidth, MIN_COLUMN));
181
+ if (available < floor.reduce((sum, value) => sum + value, 0)) {
182
+ return renderRecords(header, rows, width);
183
+ }
184
+ const widths = [...natural];
185
+ const total = widths.reduce((sum, value) => sum + value, 0);
186
+ for (let excess = total - available; excess > 0; excess -= 1) {
187
+ const slack = widths.map((value, column) => value - (floor[column] ?? 0));
188
+ const widest = slack.indexOf(Math.max(...slack));
189
+ widths[widest] = (widths[widest] ?? 0) - 1;
190
+ }
191
+ const corners = pickIcon('┌┬┐├┼┤└┴┘', '+++++++++');
192
+ const border = (row) => c.muted(corners.charAt(row * 3) +
193
+ widths.map((w) => glyph.rule().repeat(w + 2)).join(corners.charAt(row * 3 + 1)) +
194
+ corners.charAt(row * 3 + 2));
195
+ const bar = c.muted(glyph.bar());
196
+ const renderRow = (cells) => {
197
+ const wrapped = widths.map((w, column) => wrap(cells[column] ?? '', Math.max(1, w)));
198
+ const height = Math.max(...wrapped.map((lines) => lines.length));
199
+ return Array.from({ length: height }, (_, line) => {
200
+ const parts = wrapped.map((lines, column) => alignCell(lines[line] ?? '', widths[column] ?? 0, token.align[column] ?? null));
201
+ return `${bar} ${parts.join(` ${bar} `)} ${bar}`;
202
+ });
203
+ };
204
+ const body = rows.map(renderRow);
205
+ const separated = body.some((lines) => lines.length > 1);
206
+ return [
207
+ border(0),
208
+ ...renderRow(header.map((label) => chalk.bold(label))),
209
+ border(1),
210
+ ...body.flatMap((lines, index) => (separated && index > 0 ? [border(1), ...lines] : lines)),
211
+ border(2),
212
+ ];
213
+ }
214
+ function renderBlock(token, width, depth) {
215
+ switch (token.type) {
216
+ case 'heading':
217
+ return renderHeading(token, width);
218
+ case 'paragraph':
219
+ return wrap(renderInline(token.tokens, true), width);
220
+ case 'text':
221
+ return wrap(renderInlineToken(token, true), width);
222
+ case 'code':
223
+ return renderCode(token, width);
224
+ case 'blockquote':
225
+ return renderBlockquote(token, width, depth);
226
+ case 'list':
227
+ return renderList(token, width, depth);
228
+ case 'table':
229
+ return renderTable(token, width);
230
+ case 'hr':
231
+ return [c.muted(glyph.rule().repeat(width))];
232
+ case 'html': {
233
+ const text = decodeEntities(token.text.replace(/<[^>]*>/g, '')).trim();
234
+ return text ? wrap(text, width) : [];
235
+ }
236
+ case 'space':
237
+ case 'def':
238
+ case 'list_item':
239
+ return [];
240
+ case 'br':
241
+ case 'codespan':
242
+ case 'del':
243
+ case 'em':
244
+ case 'escape':
245
+ case 'image':
246
+ case 'link':
247
+ case 'strong':
248
+ return wrap(renderInlineToken(token, true), width);
249
+ }
250
+ }
251
+ function renderBlocks(tokens, width, depth, tight) {
252
+ const lines = [];
253
+ for (const token of tokens) {
254
+ const block = renderBlock(token, width, depth);
255
+ if (block.length === 0)
256
+ continue;
257
+ if (lines.length > 0 && !tight)
258
+ lines.push('');
259
+ lines.push(...block);
260
+ }
261
+ return lines;
262
+ }
263
+ export function renderMarkdown(tokens, width) {
264
+ return renderBlocks(tokens, Math.max(1, Math.floor(width)), 0, false);
265
+ }
@@ -1,34 +1,44 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { getStateDir, getWritableStateDir } from '../config/paths.js';
4
- const INDEX_FILE = 'docs-index.json';
5
- const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
6
- function isDocItem(value) {
7
- const item = value;
8
- return (typeof item?.name === 'string' &&
9
- typeof item.path === 'string' &&
10
- (item.type === 'file' || item.type === 'dir'));
4
+ const DIR = 'docs';
5
+ const MAX_BYTES = 4 * 1024 * 1024;
6
+ const KEY_RE = /^[\w-]{1,80}$/;
7
+ function keyFile(dir, key) {
8
+ if (!KEY_RE.test(key))
9
+ throw new TypeError('Invalid docs cache key.');
10
+ return path.join(dir, key);
11
11
  }
12
- export function saveDocsIndex(docs, dir) {
13
- try {
14
- fs.writeFileSync(path.join(dir ?? getWritableStateDir(), INDEX_FILE), JSON.stringify(docs), {
15
- encoding: 'utf8',
16
- mode: 0o600,
17
- });
18
- }
19
- catch {
20
- /* best effort */
12
+ function evict(dir, maxBytes) {
13
+ const files = fs
14
+ .readdirSync(dir)
15
+ .map((name) => {
16
+ const file = path.join(dir, name);
17
+ const stat = fs.statSync(file);
18
+ return { file, size: stat.size, usedAt: stat.mtimeMs };
19
+ })
20
+ .sort((left, right) => right.usedAt - left.usedAt);
21
+ let total = 0;
22
+ for (const { file, size } of files) {
23
+ total += size;
24
+ if (total > maxBytes)
25
+ fs.rmSync(file, { force: true });
21
26
  }
22
27
  }
23
- export function loadDocsIndex(dir, maxAgeMs = MAX_AGE_MS) {
24
- try {
25
- const file = path.join(dir ?? getStateDir(), INDEX_FILE);
26
- if (Date.now() - fs.statSync(file).mtimeMs > maxAgeMs)
27
- return null;
28
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
29
- return Array.isArray(parsed) && parsed.every(isDocItem) ? parsed : null;
30
- }
31
- catch {
32
- return null;
33
- }
28
+ export function createDocsStore(root, maxBytes = MAX_BYTES) {
29
+ return {
30
+ read(key) {
31
+ const file = keyFile(path.join(root ?? getStateDir(), DIR), key);
32
+ const value = fs.readFileSync(file, 'utf8');
33
+ const now = new Date();
34
+ fs.utimes(file, now, now, () => undefined);
35
+ return value;
36
+ },
37
+ write(key, value) {
38
+ const dir = path.join(root ?? getWritableStateDir(), DIR);
39
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
40
+ fs.writeFileSync(keyFile(dir, key), value, { encoding: 'utf8', mode: 0o600 });
41
+ evict(dir, maxBytes);
42
+ },
43
+ };
34
44
  }