@skillstech/thunderlang 1.2.0 → 1.3.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/CHANGELOG.md +131 -0
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +2716 -345
- package/package.json +1 -1
- package/src/cli.mjs +31 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +43 -0
package/src/libraries.mjs
CHANGED
|
@@ -75,6 +75,13 @@ const URL_WORDS = (u) => {
|
|
|
75
75
|
return /^[A-Za-z_][\w.]*$/.test(t) ? `the ${words(t.split('.').pop()).replace(/\burl\b/, 'URL')}` : 'an address worked out by the code';
|
|
76
76
|
};
|
|
77
77
|
|
|
78
|
+
/** A file path in words: a quoted path as written, a name as "at <name>" ("Reads the file at config path"). */
|
|
79
|
+
const FILE_WORDS = (u) => {
|
|
80
|
+
const t = String(u || '').trim();
|
|
81
|
+
if (/^["'`]/.test(t)) return t.slice(1, -1).replace(/\$\{[^}]*\}/g, '…');
|
|
82
|
+
return /^[A-Za-z_][\w.]*$/.test(t) ? `at ${t.includes('.') ? `the ${words(t.split('.').pop())}` : words(t)}` : 'at a path worked out by the code';
|
|
83
|
+
};
|
|
84
|
+
|
|
78
85
|
// Spring Data / Rails-style derived query names: findByEmailAndActive -> "whose email is … and active is …".
|
|
79
86
|
function derivedWhose(name, args) {
|
|
80
87
|
const m = name.match(/^(?:find|get|read|query|search|stream|count|exists|delete|remove)(?:All|First|Top\d*|One)?By(\w+)$/);
|
|
@@ -175,9 +182,9 @@ const CATALOG = [
|
|
|
175
182
|
{ re: /^json\s*\.\s*Marshal\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON`, does: 'calculate' }) },
|
|
176
183
|
{ re: /^json\s*\.\s*Unmarshal\s*\(\s*[^,]+,\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads the JSON into ${words(m[1])}`, does: 'calculate' }) },
|
|
177
184
|
{ re: /^json\s*\.\s*NewDecoder\s*\(\s*r\.Body\s*\)\s*\.\s*Decode\s*\(\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads what it was sent into ${words(m[1])}`, does: 'calculate' }) },
|
|
178
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${
|
|
179
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${
|
|
180
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${
|
|
185
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${FILE_WORDS(m[2])}`, does: 'find' }) },
|
|
186
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
|
|
187
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
|
|
181
188
|
{ re: /^(?:Date\.now|datetime\.now|datetime\.utcnow|time\.Now|DateTime\.Now|DateTime\.UtcNow|Instant\.now|LocalDateTime\.now|Time\.now)\s*\(?\s*\)?$/, say: () => ({ says: 'the current time', does: 'calculate', value: true }) },
|
|
182
189
|
];
|
|
183
190
|
|
package/src/model.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
|
|
3
3
|
// and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
|
|
4
4
|
// them may say more than the model does. Browser-safe: takes [{ path, source }].
|
|
5
|
+
import { readScreens, screenText } from './screens.mjs';
|
|
5
6
|
import { readCode, INFRA_LANGUAGES } from './read.mjs';
|
|
6
7
|
import { readableLanguage, readingOf } from './read-repo.mjs';
|
|
7
8
|
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
@@ -59,10 +60,17 @@ function kindWords(type) {
|
|
|
59
60
|
const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^(?:Array|List|ArrayList|LinkedList|Vec|VecDeque|IList|IEnumerable|ICollection|IReadOnlyList|Collection|Set|HashSet|MutableList|MutableSet|Sequence|Iterable)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
|
|
60
61
|
if (list) { const inner = (list[1] || list[2] || list[3] || list[4]).trim(); return `a list of ${kindWords(inner)?.replace(/^an? /, '') ?? inner}s`.replace(/wordss$/, 'words').replace(/ys$/, 'ies').replace(/(yes or no)s$/, '$1 answers'); }
|
|
61
62
|
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
|
|
62
|
-
if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ??
|
|
63
|
+
if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ?? withArticle(inner)}, or nothing`; }
|
|
63
64
|
const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
|
|
64
65
|
if (map) return 'a lookup table';
|
|
65
|
-
return /^[A-Z]/.test(t) ?
|
|
66
|
+
return /^[A-Z]/.test(t) ? withArticle(t) : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** "a" or "an" by the sound of the word: an AgentCheckResult, an Order, a User, an Unknown, a Euro. */
|
|
70
|
+
export function withArticle(w) {
|
|
71
|
+
const t = String(w);
|
|
72
|
+
const an = /^(?:[AEIOaeio]|U(?:n|m|nd|tt|pp)|u(?:n|m)|[FHLMNRSX][A-Z0-9]|[fhlmnrsx](?=[A-Z0-9]))/.test(t) && !/^(?:Eu|eu|Uni|uni|Use|use|Usu|One|one|Ur)/.test(t);
|
|
73
|
+
return `${an ? 'an' : 'a'} ${t}`;
|
|
66
74
|
}
|
|
67
75
|
|
|
68
76
|
/** C: a function belongs to a struct it takes first (`library_late_fee(const Library *lib, …)`) or is named after. */
|
|
@@ -808,6 +816,20 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
808
816
|
const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
|
|
809
817
|
// The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
|
|
810
818
|
try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
|
|
819
|
+
// Screens: React and Angular components read as what a person sees and does (src/screens.mjs). Listed only when
|
|
820
|
+
// there are some; the function or class behind each one points to it.
|
|
821
|
+
try {
|
|
822
|
+
const screens = readScreens(files, { members });
|
|
823
|
+
if (screens.length) {
|
|
824
|
+
model.screens = screens;
|
|
825
|
+
for (const sc of screens) {
|
|
826
|
+
const m = members.find((x) => x.file === sc.file && x.name === sc.name);
|
|
827
|
+
if (m) { m.screen = sc.id; sc.member = m.id; }
|
|
828
|
+
const t = things.find((x) => x.file === sc.file && x.name === sc.name);
|
|
829
|
+
if (t) { t.screen = sc.id; sc.thing = t.id; }
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
} catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` }); }
|
|
811
833
|
return model;
|
|
812
834
|
}
|
|
813
835
|
|
|
@@ -853,6 +875,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
|
|
|
853
875
|
* cannot disagree. Pass the model and an id.
|
|
854
876
|
*/
|
|
855
877
|
export function modelText(model, id, { note = null, full = false } = {}) {
|
|
878
|
+
const sc = (model.screens ?? []).find((x) => x.id === id);
|
|
879
|
+
if (sc) return screenText(sc);
|
|
856
880
|
const t = model.things.find((x) => x.id === id);
|
|
857
881
|
if (t) {
|
|
858
882
|
const lines = [t.kind === 'resource' ? `Resource ${t.label} (${t.resourceType})` : `${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
|
|
@@ -878,7 +902,7 @@ export function modelText(model, id, { note = null, full = false } = {}) {
|
|
|
878
902
|
|
|
879
903
|
// ── The five reading levels: what each one shows, decided here so every product shows the same thing ─────────
|
|
880
904
|
|
|
881
|
-
const SYMBOL_OF = { action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
|
|
905
|
+
const SYMBOL_OF = { screen: 'screen', action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
|
|
882
906
|
|
|
883
907
|
const SETTING_WORDS = { parameter: 'given when it starts or is built', variable: 'a variable kept outside the file', secret: 'a secret (only its name is shown)', literal: 'written in the file', computed: 'worked out when it runs' };
|
|
884
908
|
const APPLIED_WORDS = { parameter: 'given when it is applied', computed: 'worked out when it is applied' };
|
|
@@ -1036,6 +1060,17 @@ function detailsFacts(model, member) {
|
|
|
1036
1060
|
return { inputs, changes, stops, givesBack, reliesOn, ...(answers ? { answers } : {}), ...(limits ? { limits } : {}), openQuestions };
|
|
1037
1061
|
}
|
|
1038
1062
|
|
|
1063
|
+
/** One reading level of a screen (a React or Angular component): the same five levels as any member. */
|
|
1064
|
+
function screenLevel(lv, sc, model) {
|
|
1065
|
+
const base = { level: lv.id, name: lv.name, question: lv.question };
|
|
1066
|
+
const about = { scope: 'screen', id: sc.id, title: sc.label, symbol: 'screen', file: sc.file, lines: sc.lines, framework: sc.framework, ...(sc.selector ? { selector: sc.selector } : {}) };
|
|
1067
|
+
if (lv.id === 'big-picture') return { ...base, ...about, inputs: sc.inputs, state: sc.state, outputs: sc.outputs, ...(sc.services ? { services: sc.services } : {}), uses: sc.uses, usedBy: sc.usedBy ?? [], events: sc.events.length, notRead: sc.notRead.length };
|
|
1068
|
+
if (lv.id === 'flow') return { ...base, ...about, shows: sc.shows, ...(sc.early ? { early: sc.early } : {}) };
|
|
1069
|
+
if (lv.id === 'details') return { ...base, ...about, inputs: sc.inputs, state: sc.state, events: sc.events, effects: sc.effects, outputs: sc.outputs, notRead: sc.notRead, source: 'Read from code by the Thunder compiler, with no AI.' };
|
|
1070
|
+
if (lv.id === 'text') return { ...base, ...about, text: screenText(sc) };
|
|
1071
|
+
return { ...base, ...about, language: model.files.find((f) => f.path === sc.file)?.language ?? null, ...(sc.template ? { template: sc.template } : {}) };
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1039
1074
|
/**
|
|
1040
1075
|
* What one reading level shows: `level` is a LEVELS id (big-picture, flow, details, text, original); `focus` is a
|
|
1041
1076
|
* Thing or member id, or nothing for the whole model. Flow and Details need an action or rule; without one they
|
|
@@ -1044,6 +1079,8 @@ function detailsFacts(model, member) {
|
|
|
1044
1079
|
export function readLevel(model, level, focus, { full = false } = {}) {
|
|
1045
1080
|
const lv = LEVELS.find((l) => l.id === level);
|
|
1046
1081
|
if (!lv) throw new Error(`Unknown reading level "${level}". Use one of: ${LEVELS.map((l) => l.id).join(', ')}.`);
|
|
1082
|
+
const screen = focus ? (model.screens ?? []).find((x) => x.id === focus) : undefined;
|
|
1083
|
+
if (screen) return screenLevel(lv, screen, model);
|
|
1047
1084
|
const member = focus ? model.members.find((m) => m.id === focus) : undefined;
|
|
1048
1085
|
const thing = focus && !member ? model.things.find((t) => t.id === focus) : undefined;
|
|
1049
1086
|
if (focus && !member && !thing) throw new Error(`Nothing in this model has the id "${focus}".`);
|
|
@@ -1062,14 +1099,16 @@ export function readLevel(model, level, focus, { full = false } = {}) {
|
|
|
1062
1099
|
|
|
1063
1100
|
if (!member && (lv.id === 'flow' || lv.id === 'details')) {
|
|
1064
1101
|
const inScope = model.members.filter((m) => m.kind !== 'setup' && (!thing || m.owner === thing.id));
|
|
1065
|
-
|
|
1102
|
+
const screens = thing ? [] : (model.screens ?? []).map((x) => ({ id: x.id, label: x.label, symbol: 'screen' }));
|
|
1103
|
+
return { ...base, ...about, needsFocus: true, says: `${lv.name} shows one ${screens.length ? 'screen, action, or rule' : 'action or rule'}. Choose one.`, choose: [...screens, ...inScope.filter((m) => !m.screen).map(short)] };
|
|
1066
1104
|
}
|
|
1067
1105
|
if (lv.id === 'big-picture') {
|
|
1068
1106
|
if (member) {
|
|
1069
1107
|
return { ...base, ...about, ...(member.route ? { route: member.route } : {}), ...(member.doc ? { doc: member.doc } : {}),
|
|
1070
1108
|
...(owner ? { owner: { id: owner.id, label: owner.label } } : {}), youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), uses, usedBy };
|
|
1071
1109
|
}
|
|
1072
|
-
|
|
1110
|
+
// (A screen's function or class is listed once, as the screen.)
|
|
1111
|
+
const inScope = (m) => m.kind !== 'setup' && (thing ? m.owner === thing.id : !m.screen);
|
|
1073
1112
|
const resourceCard = (t) => ({ id: t.id, label: t.label, symbol: 'resource', resourceType: t.resourceType, address: t.address, file: t.file,
|
|
1074
1113
|
knows: t.knows.map((k) => ({ label: k.label, value: k.kind, ...(k.computed ? { computed: true } : {}), ...(k.secret ? { secret: true } : {}), line: k.line })),
|
|
1075
1114
|
links: (model.links || []).filter((l) => l.from === t.id || l.to === t.id).map((l) => ({ from: l.from, to: l.to, kind: l.kind, ...(l.line ? { line: l.line } : {}) })) });
|
|
@@ -1077,15 +1116,17 @@ export function readLevel(model, level, focus, { full = false } = {}) {
|
|
|
1077
1116
|
const thingCard = (t) => ({ id: t.id, label: t.label, ...(t.doc ? { doc: t.doc } : {}), knows: t.knows.map((k) => ({ label: k.label, ...(k.start ? { start: k.start } : {}) })), can: model.members.filter((m) => m.owner === t.id && m.kind !== 'setup' && !m.callback).map(short) });
|
|
1078
1117
|
return { ...base, ...about,
|
|
1079
1118
|
...(thing?.doc ?? model.files[0]?.purpose ? { purpose: thing?.doc ?? model.files[0]?.purpose } : {}),
|
|
1080
|
-
things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing')).map(thingCard),
|
|
1119
|
+
things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing' && !t.screen)).map(thingCard),
|
|
1081
1120
|
resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === 'resource')).map(resourceCard),
|
|
1082
1121
|
...(thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] }),
|
|
1083
1122
|
data: thing ? [] : model.things.filter((t) => t.kind !== 'thing' && t.kind !== 'resource').map((t) => ({ id: t.id, label: t.label, symbol: SYMBOL_OF[t.kind], ...(t.choices.length ? { choices: t.choices } : {}), knows: t.knows.map((k) => k.label) })),
|
|
1084
1123
|
actions: model.members.filter((m) => inScope(m) && m.kind === 'action').map(short),
|
|
1085
1124
|
rules: model.members.filter((m) => inScope(m) && m.kind === 'rule').map(short),
|
|
1086
1125
|
// (A callback is reached from the step that passes it, not listed on its own.)
|
|
1087
|
-
loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
|
|
1126
|
+
loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && !m.screen && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
|
|
1088
1127
|
unknowns: thing ? [] : model.unknowns,
|
|
1128
|
+
// The app's screens (React and Angular components), and the screens and components each one shows.
|
|
1129
|
+
...(!thing && model.screens?.length ? { screens: [...model.screens].sort((x, y) => ['page', 'top', 'part'].indexOf(x.role) - ['page', 'top', 'part'].indexOf(y.role)).map((x) => ({ id: x.id, label: x.label, framework: x.framework, file: x.file, ...(x.selector ? { selector: x.selector } : {}), ...(x.role ? { role: x.role } : {}), uses: x.uses.map((u) => u.label) })) } : {}),
|
|
1089
1130
|
// The app's map: which areas (folders) call which, and send requests or events to which.
|
|
1090
1131
|
...(thing ? {} : { calls: callsSummary(model), notLinked: model.notLinked ?? [] }) };
|
|
1091
1132
|
}
|
|
@@ -1103,7 +1144,8 @@ export function readLevel(model, level, focus, { full = false } = {}) {
|
|
|
1103
1144
|
const extra = [];
|
|
1104
1145
|
if (!focus && model.permissions?.length) extra.push(`Permissions\n${model.permissions.map((p) => ` ${p.says ?? `${p.who} can ${p.can} ${p.on}`}${p.wide && !/\(wide\)/.test(p.says ?? '') ? ' (wide)' : ''} (line ${p.line})`).join('\n')}\n`);
|
|
1105
1146
|
if (!focus && model.settings?.length) extra.push(`Settings\n${model.settings.map((x) => ` Setting ${x.name}: ${settingWords(x, model)} (line ${x.line})`).join('\n')}\n`);
|
|
1106
|
-
|
|
1147
|
+
// The whole app: its screens first (as screens, not as the classes behind them), then everything else.
|
|
1148
|
+
const text = focus ? modelText(model, focus, { full }) : [...(model.screens ?? []).map((sc) => screenText(sc)), ...model.things.filter((t) => !t.screen).map((t) => modelText(model, t.id)), ...model.members.filter((m) => !m.owner && m.kind !== 'setup' && !m.screen).map((m) => modelText(model, m.id, { full })), ...extra].join('\n');
|
|
1107
1149
|
return { ...base, ...about, text };
|
|
1108
1150
|
}
|
|
1109
1151
|
return { ...base, ...about, language: (member ?? thing) ? (member?.language ?? model.files.find((f) => f.path === thing.file)?.language ?? null) : (model.files[0]?.language ?? null) };
|
package/src/read-level.mjs
CHANGED
|
@@ -21,7 +21,9 @@ export function nearestLevel(word) {
|
|
|
21
21
|
export function findFocus(model, name) {
|
|
22
22
|
if (!name) return { id: null };
|
|
23
23
|
const want = squash(name);
|
|
24
|
-
|
|
24
|
+
// A screen and the function or class behind it share a name: the screen is what a person means.
|
|
25
|
+
const screens = model.screens ?? [];
|
|
26
|
+
const pool = [...screens, ...model.members.filter((m) => m.kind !== 'setup' && !m.screen), ...model.things.filter((t) => !t.screen)];
|
|
25
27
|
const exact = pool.filter((x) => x.id === name || squash(x.label) === want || squash(x.name) === want);
|
|
26
28
|
if (exact.length === 1) return { id: exact[0].id };
|
|
27
29
|
if (exact.length > 1) return { error: `"${name}" names ${exact.length} things: ${exact.map((x) => `${x.label} (${at(x.file, x.lines)})`).join(', ')}. Use one of their ids with --focus: ${exact.map((x) => x.id).join(', ')}.` };
|
|
@@ -69,7 +71,50 @@ function flowLines(flow) {
|
|
|
69
71
|
const whenText = (when) => (when?.length ? ` when ${when.map((w) => w.says ?? (/^if /i.test(w.question) && /^yes$/i.test(w.answer) ? w.question.replace(/^if /i, '').replace(/\?$/, '') : `${w.question.replace(/\?$/, '')}: ${w.answer}`)).join(' and ')}` : '');
|
|
70
72
|
|
|
71
73
|
/** One level as terminal text. `sources` maps a file path to its text (for the original level). */
|
|
74
|
+
/** A screen's outline: what it shows, as nested lines (otherwise branches included). */
|
|
75
|
+
function outline(items, pad, L) {
|
|
76
|
+
for (const it of items) {
|
|
77
|
+
L.push(`${pad}${it.notRead ? '?' : '•'} ${it.says}${it.line ? ` (line ${it.line})` : ''}`);
|
|
78
|
+
if (it.kids) outline(it.kids, `${pad} `, L);
|
|
79
|
+
if (it.otherwise) { L.push(`${pad} ${it.otherwise.says}`); outline(it.otherwise.kids, `${pad} `, L); }
|
|
80
|
+
}
|
|
81
|
+
return L;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function renderScreen(r, next) {
|
|
85
|
+
const L = [`${r.name} · ${r.title} (${r.framework === 'react' ? 'React' : 'Angular'} screen${r.selector ? ` <${r.selector}>` : ''}, ${r.file}:${r.lines[0]})`, r.question, ''];
|
|
86
|
+
const inputs = (r.inputs ?? []).map((i) => `${i.label}${i.kind ? ` (${i.kind})` : ''}`).join(', ');
|
|
87
|
+
const state = (r.state ?? []).map((x) => `${x.label}${x.start ? ` (${/^(from|worked out)/.test(x.start) ? x.start : `starts as ${x.start}`})` : ''}`).join(', ');
|
|
88
|
+
if (r.level === 'big-picture') {
|
|
89
|
+
L.push(`It receives: ${inputs || 'nothing'}`, `It remembers: ${state || 'nothing'}`);
|
|
90
|
+
if (r.outputs?.length) L.push(`It sends: ${r.outputs.map((o) => o.label).join(', ')}`);
|
|
91
|
+
if (r.services?.length) L.push(`It uses: ${r.services.join(', ')}`);
|
|
92
|
+
if (r.uses?.length) L.push(`It shows: ${r.uses.map((u) => u.label).join(', ')}`);
|
|
93
|
+
if (r.usedBy?.length) L.push(`Shown by: ${r.usedBy.map((u) => u.label).join(', ')}`);
|
|
94
|
+
L.push(`Events: ${r.events}${r.notRead ? ` Not read: ${r.notRead}` : ''}`, '', `Next: ${next('flow')}`);
|
|
95
|
+
return L.join('\n');
|
|
96
|
+
}
|
|
97
|
+
if (r.level === 'flow') {
|
|
98
|
+
for (const e of r.early ?? []) { L.push(` When ${e.when}, it shows only:`); outline(e.shows.length ? e.shows : [{ says: 'nothing' }], ' ', L); }
|
|
99
|
+
if (r.shows.length) { L.push(' It shows:'); outline(r.shows, ' ', L); } else L.push(' It shows nothing Thunder could read.');
|
|
100
|
+
L.push('', `Next: ${next('details')}`);
|
|
101
|
+
return L.join('\n');
|
|
102
|
+
}
|
|
103
|
+
if (r.level === 'details') {
|
|
104
|
+
L.push(`It receives: ${inputs || 'nothing'}`, `It remembers: ${state || 'nothing'}`);
|
|
105
|
+
if (r.events.length) { L.push('When someone acts:'); for (const e of r.events) L.push(` • ${e.when}: ${e.runs}${e.line ? ` (line ${e.line})` : ''}`); }
|
|
106
|
+
if (r.effects.length) { L.push('By itself:'); for (const e of r.effects) L.push(` • ${e.when}: ${e.runs}${e.line ? ` (line ${e.line})` : ''}`); }
|
|
107
|
+
if (r.outputs.length) L.push(`It sends: ${r.outputs.map((o) => o.label).join(', ')}`);
|
|
108
|
+
if (r.notRead.length) { L.push("Can't tell from the code:"); for (const n of r.notRead) L.push(` ? ${n.line ? `line ${n.line}: ` : ''}\`${n.code}\`: ${n.why}`); }
|
|
109
|
+
L.push('', r.source);
|
|
110
|
+
return L.join('\n');
|
|
111
|
+
}
|
|
112
|
+
if (r.level === 'text') return [...L, r.text.trimEnd()].join('\n');
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
72
116
|
export function renderLevel(r, { sources = {}, file = 'file' } = {}) {
|
|
117
|
+
if (r.scope === 'screen' && r.level !== 'original') return renderScreen(r, (lv) => `thunder read ${file} --level ${lv} --focus "${r.title}"`);
|
|
73
118
|
const L = [`${r.name} · ${r.title}${r.file && r.scope !== 'app' ? ` (${at(r.file, r.lines)})` : ''}`, r.question, ''];
|
|
74
119
|
const next = (lv, focus) => `thunder read ${file} --level ${lv}${focus ? ` --focus "${focus}"` : ''}`;
|
|
75
120
|
|
|
@@ -92,8 +137,9 @@ export function renderLevel(r, { sources = {}, file = 'file' } = {}) {
|
|
|
92
137
|
if (loose.length) L.push(`Actions and rules: ${list(loose.map((c) => `${c.label}${c.symbol === 'rule' ? ' (rule)' : ''}`))}`);
|
|
93
138
|
if (r.data.length) { L.push('Data'); for (const d of r.data) L.push(` ${d.label}: ${d.choices ? d.choices.join(' | ') : list(d.knows) || '(nothing it knows)'}`); }
|
|
94
139
|
if (r.permissions?.length) L.push(`Permissions: ${r.permissions.length}`);
|
|
140
|
+
if (r.screens?.length) { L.push('Screens'); for (const x of r.screens) L.push(` ${x.label} (${x.role === 'page' ? 'page, ' : x.role === 'part' ? 'part, ' : ''}${x.framework === 'react' ? 'React' : 'Angular'}${x.selector ? ` <${x.selector}>` : ''})${x.uses.length ? `: shows ${x.uses.join(', ')}` : ''}`); }
|
|
95
141
|
if (r.unknowns?.length) L.push(`Not read: ${r.unknowns.length} part${r.unknowns.length === 1 ? '' : 's'} Thunder could not explain (see --level details)`);
|
|
96
|
-
const first = r.things[0]?.can[0] ?? loose[0];
|
|
142
|
+
const first = r.screens?.[0] ? { label: r.screens[0].label } : r.things[0]?.can[0] ?? loose[0];
|
|
97
143
|
if (first) L.push('', `Next: ${next('flow', first.label.replace(/\?$/, ''))}`);
|
|
98
144
|
return L.join('\n').trimEnd();
|
|
99
145
|
}
|
package/src/read-repo-fs.mjs
CHANGED
|
@@ -22,7 +22,8 @@ const MANIFEST = /^(go\.mod|package\.json|tsconfig\.json|jsconfig\.json)$/;
|
|
|
22
22
|
* go.mod, package.json, and tsconfig/jsconfig files that say which imports are this repo's own (for thunderModel's
|
|
23
23
|
* calls across files); they are not code and are not read as code.
|
|
24
24
|
*/
|
|
25
|
-
|
|
25
|
+
// templates: also bring Angular component templates (*.component.html), which screens read with their component.
|
|
26
|
+
export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, templates = false } = {}) {
|
|
26
27
|
const out = [];
|
|
27
28
|
const walk = (dir) => {
|
|
28
29
|
let names;
|
|
@@ -36,6 +37,7 @@ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400
|
|
|
36
37
|
const path = relative(root, full).split('\\').join('/');
|
|
37
38
|
if (st.isDirectory()) walk(full);
|
|
38
39
|
else if (manifests && MANIFEST.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), manifest: true });
|
|
40
|
+
else if (templates && /\.component\.html$/i.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), template: true });
|
|
39
41
|
else if (readableLanguage(path) || (!name.includes('.') && shebangShell(full, st.size))) {
|
|
40
42
|
// Oversized files are not loaded; readRepo lists them as skipped from their size.
|
|
41
43
|
out.push(st.size > maxFileBytes ? { path, source: '', size: st.size } : { path, source: readFileSync(full, 'utf8') });
|
package/src/read.mjs
CHANGED
|
@@ -244,7 +244,8 @@ function balancedReturnHead(after) {
|
|
|
244
244
|
if (c === '=' && after[i + 1] === '>') { if (depth === 0) break; i++; continue; } // => ends the type, or is a function type's arrow
|
|
245
245
|
if (c === '<' || c === '(' || c === '[') depth++;
|
|
246
246
|
else if (c === '>' || c === ')' || c === ']') depth--;
|
|
247
|
-
|
|
247
|
+
// (At the top, a "{" with no type before it, or after | or &, starts an object type: `): { ok: boolean } {`.)
|
|
248
|
+
else if (c === '{') { if (depth === 0 && !/^$|[|&]$/.test(after.slice(lead[0].length, i).trim())) break; depth++; }
|
|
248
249
|
else if (c === '}') depth--;
|
|
249
250
|
else if (c === ';' && depth === 0) break;
|
|
250
251
|
else if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < after.length && after[i] !== q) i++; }
|
|
@@ -324,7 +325,8 @@ function findFunctions(src, language) {
|
|
|
324
325
|
const patterns = {
|
|
325
326
|
typescript: [
|
|
326
327
|
/(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
|
|
327
|
-
|
|
328
|
+
// The type annotation stops at the end of its statement (";"), or `let a: T;` would name the next line's function.
|
|
329
|
+
/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
|
|
328
330
|
/^\s*(?:public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/gm,
|
|
329
331
|
],
|
|
330
332
|
go: [/func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\s*\(/g],
|
|
@@ -418,7 +420,8 @@ function findFunctions(src, language) {
|
|
|
418
420
|
: language === 'go'
|
|
419
421
|
? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
|
|
420
422
|
: (language === 'typescript' || language === 'javascript')
|
|
421
|
-
|
|
423
|
+
// (The handler may be wrapped: `fastify.get('/x', handle(async (request) => …))`, `asyncHandler(…)`.)
|
|
424
|
+
? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
|
|
422
425
|
: [];
|
|
423
426
|
for (const re of routeRes) {
|
|
424
427
|
let m;
|
|
@@ -426,11 +429,31 @@ function findFunctions(src, language) {
|
|
|
426
429
|
const open = src.indexOf('(', m.index + m[0].length - 1);
|
|
427
430
|
const close = matchClose(src, open);
|
|
428
431
|
if (close < 0) continue;
|
|
432
|
+
const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
|
|
429
433
|
const brace = src.indexOf('{', close);
|
|
430
|
-
if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace)))
|
|
434
|
+
if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) {
|
|
435
|
+
// An arrow whose body is one expression: `async (request) => practiceView(…)`. It gives back that value;
|
|
436
|
+
// the expression runs to the first ")" or "," that closes the call around it.
|
|
437
|
+
const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
|
|
438
|
+
if (!(language === 'typescript' || language === 'javascript') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
|
|
439
|
+
const from = close + 1 + arrow[0].length;
|
|
440
|
+
let depth = 0, end = from, q = null;
|
|
441
|
+
for (; end < src.length; end++) {
|
|
442
|
+
const c = src[end];
|
|
443
|
+
if (q) { if (c === q && src[end - 1] !== '\\') q = null; continue; }
|
|
444
|
+
if (c === "'" || c === '"' || c === '`') { q = c; continue; }
|
|
445
|
+
if ('([{'.includes(c)) depth++;
|
|
446
|
+
else if (')]}'.includes(c)) { if (depth === 0) break; depth--; }
|
|
447
|
+
else if ((c === ',' || c === ';') && depth === 0) break;
|
|
448
|
+
}
|
|
449
|
+
const expr = src.slice(from, end).trim();
|
|
450
|
+
if (!expr) continue;
|
|
451
|
+
// (Read as `return <expr>`: the body starts 7 characters early so every line number stays right.)
|
|
452
|
+
fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: from - 7, body: `return ${expr};`, route: { method, path: m[2] }, expressionBody: true });
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
431
455
|
const bc = matchClose(src, brace);
|
|
432
456
|
if (bc < 0) continue;
|
|
433
|
-
const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
|
|
434
457
|
fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method, path: m[2] } });
|
|
435
458
|
}
|
|
436
459
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// thunder replay: the Thunder Time Machine. Step forward and back through a recording made with
|
|
2
|
+
// `thunder run --record <file>`: each statement as it ran, the values it changed, what it printed, what a function
|
|
3
|
+
// gave back, and where a choice or a loop went. It replays a recording: going back shows an earlier moment and never
|
|
4
|
+
// undoes anything the program did.
|
|
5
|
+
// thunder replay <file> [--step n] [--json]
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
import { paint, paintThunderLine, useColor } from './term.mjs';
|
|
9
|
+
|
|
10
|
+
const SCHEMA = 'thunder-time-machine-v1';
|
|
11
|
+
const USAGE = `usage: thunder replay <recording.json> [--step n] [--json]
|
|
12
|
+
Step through a recording made with: thunder run <program> --record <recording.json>
|
|
13
|
+
Keys: Enter or n for the next step, b to go back, j and a number to jump (j 7), q to quit.`;
|
|
14
|
+
|
|
15
|
+
/** The text of a Thunder line from the recording's copy of the program. */
|
|
16
|
+
const lineText = (trace, file, line) => {
|
|
17
|
+
const src = trace.files?.[file] ?? Object.values(trace.files ?? {})[0];
|
|
18
|
+
return src ? (src.split('\n')[line - 1] ?? '').trim() : '';
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where a choice or a loop went, in words. For When / Otherwise when / Otherwise, the arm whose lines hold the next
|
|
23
|
+
* step answers it: the first arm is "yes"; a later one is "no", then that arm.
|
|
24
|
+
*/
|
|
25
|
+
function branchText(trace, s) {
|
|
26
|
+
if (s.next == null) return s.kind === 'if' ? ' → no, so nothing inside ran' : ' → the steps inside did not run';
|
|
27
|
+
if (s.kind !== 'if') return ` → goes on to line ${s.next}`;
|
|
28
|
+
const src = (trace.files?.[s.file] ?? '').split('\n');
|
|
29
|
+
const indent = (l) => l.match(/^\s*/)[0].length;
|
|
30
|
+
const base = indent(src[s.line - 1] ?? '');
|
|
31
|
+
const arms = [{ line: s.line, text: (src[s.line - 1] ?? '').trim() }];
|
|
32
|
+
for (let k = s.line; k < src.length; k++) {
|
|
33
|
+
const l = src[k];
|
|
34
|
+
if (!l.trim()) continue;
|
|
35
|
+
if (indent(l) < base || (indent(l) === base && !/^\s*Otherwise\b/.test(l))) break;
|
|
36
|
+
if (indent(l) === base) arms.push({ line: k + 1, text: l.trim() });
|
|
37
|
+
}
|
|
38
|
+
const arm = [...arms].reverse().find((x) => x.line < s.next) ?? arms[0];
|
|
39
|
+
if (arm === arms[0]) return ' → yes';
|
|
40
|
+
if (/^Otherwise:$/.test(arm.text)) return ` → no, so the Otherwise steps (line ${arm.line})`;
|
|
41
|
+
return ` → no; then: ${arm.text.replace(/^Otherwise\s+(when|if)\s+/i, '').replace(/:$/, '')} → yes (line ${arm.line})`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** One step as a few lines of plain text. */
|
|
45
|
+
export function renderStep(trace, i) {
|
|
46
|
+
const steps = trace.steps;
|
|
47
|
+
const s = steps[i];
|
|
48
|
+
if (!s) return `There is no step ${i + 1}. This recording has ${steps.length} step${steps.length === 1 ? '' : 's'}.`;
|
|
49
|
+
const where = s.fn ? `inside "${s.fn.replace(/_/g, ' ')}"` : 'in the program';
|
|
50
|
+
const L = [`⏱ Step ${s.n} of ${steps.length} · ${s.file}, line ${s.line} · ${where}`, ` ${paintThunderLine(lineText(trace, s.file, s.line), useColor())}`];
|
|
51
|
+
// A call: the steps deeper than this one, right after it, belong to the function it called.
|
|
52
|
+
let j = i + 1;
|
|
53
|
+
while (j < steps.length && steps[j].depth > s.depth) j++;
|
|
54
|
+
const calls = j > i + 1 && !('next' in s) ? steps[i + 1] : null;
|
|
55
|
+
if (calls) L.push(` Calls "${(calls.fn ?? 'a function').replace(/_/g, ' ')}" (step${j - i - 1 === 1 ? '' : 's'} ${i + 2}${j - i - 1 > 1 ? `–${j}` : ''}), then:`);
|
|
56
|
+
if ('next' in s) L.push(branchText(trace, s));
|
|
57
|
+
for (const c of s.changes ?? []) L.push(` ${c.name}: ${c.before != null ? `${c.before} → ` : '→ '}${c.after}`);
|
|
58
|
+
if (s.gives != null) L.push(` gives back ${s.gives}`);
|
|
59
|
+
if (s.said) for (const line of s.said.replace(/\n$/, '').split('\n')) L.push(` says: ${line}`);
|
|
60
|
+
if (s.failed && !('next' in s)) L.push(` ✗ stopped here${trace.stderr ? `: ${trace.stderr.trim().replace(/^.*?: /, '')}` : ''}`);
|
|
61
|
+
if (!s.changes && s.gives == null && !s.said && !('next' in s) && !s.failed && !calls) L.push(' (nothing changed)');
|
|
62
|
+
return L.join('\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function replayMain(argv, { input = process.stdin, output = process.stdout } = {}) {
|
|
66
|
+
const a = { _: [], step: null, json: false };
|
|
67
|
+
for (let i = 0; i < argv.length; i++) {
|
|
68
|
+
const x = argv[i];
|
|
69
|
+
if (x === '--step') a.step = argv[++i];
|
|
70
|
+
else if (x === '--json') a.json = true;
|
|
71
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return Promise.resolve(0); }
|
|
72
|
+
else if (x.startsWith('--')) { console.error(`thunder replay: there is no option ${x}.\n${USAGE}`); return Promise.resolve(2); }
|
|
73
|
+
else a._.push(x);
|
|
74
|
+
}
|
|
75
|
+
if (a._.length !== 1) { console.error(`thunder replay: name one recording.\n${USAGE}`); return Promise.resolve(2); }
|
|
76
|
+
let trace;
|
|
77
|
+
try { trace = JSON.parse(readFileSync(a._[0], 'utf8')); }
|
|
78
|
+
catch (e) { console.error(`thunder replay: couldn't read ${a._[0]}${e.code === 'ENOENT' ? ': there is no such file' : ': it is not a recording'}. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
|
|
79
|
+
if (trace?.schema !== SCHEMA || !Array.isArray(trace.steps)) { console.error(`thunder replay: ${a._[0]} is not a Thunder recording. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
|
|
80
|
+
const total = trace.steps.length;
|
|
81
|
+
const say = (s = '') => output.write(`${paint(s, useColor(output))}\n`);
|
|
82
|
+
if (!total) { say('This recording has no steps (the program had nothing to run).'); return Promise.resolve(0); }
|
|
83
|
+
if (a.step != null) {
|
|
84
|
+
const n = Number(a.step);
|
|
85
|
+
if (!Number.isInteger(n) || n < 1 || n > total) { console.error(`thunder replay: --step needs a number from 1 to ${total}.`); return Promise.resolve(2); }
|
|
86
|
+
say(a.json ? JSON.stringify(trace.steps[n - 1], null, 2) : renderStep(trace, n - 1));
|
|
87
|
+
return Promise.resolve(0);
|
|
88
|
+
}
|
|
89
|
+
if (a.json) { say(JSON.stringify(trace, null, 2)); return Promise.resolve(0); }
|
|
90
|
+
|
|
91
|
+
// Step through: one step at a time, from the terminal or from piped lines.
|
|
92
|
+
say(`⚡ Replaying ${trace.program}: ${total} step${total === 1 ? '' : 's'}, recorded with Thunder™ ${trace.thunder}.`);
|
|
93
|
+
say('This replays a recording. Going back shows an earlier moment; it never undoes anything the program did.');
|
|
94
|
+
say('');
|
|
95
|
+
const rl = createInterface({ input, terminal: false });
|
|
96
|
+
const it = rl[Symbol.asyncIterator]();
|
|
97
|
+
let i = 0;
|
|
98
|
+
const show = () => { say(renderStep(trace, i)); };
|
|
99
|
+
const ask = async () => {
|
|
100
|
+
output.write(`\n ${i + 1 < total ? 'Enter/n next' : 'last step'} · b back · j N jump · q quit > `);
|
|
101
|
+
const r = await it.next();
|
|
102
|
+
if (r.done) return null;
|
|
103
|
+
if (!input.isTTY) output.write(`${r.value}\n`);
|
|
104
|
+
return r.value.trim();
|
|
105
|
+
};
|
|
106
|
+
return (async () => {
|
|
107
|
+
show();
|
|
108
|
+
for (;;) {
|
|
109
|
+
const c = await ask();
|
|
110
|
+
if (c == null || /^q/i.test(c)) break;
|
|
111
|
+
if (c === '' || /^n/i.test(c)) { if (i + 1 < total) i++; else { say('\nThat was the last step.'); continue; } }
|
|
112
|
+
else if (/^b/i.test(c)) { if (i > 0) i--; else { say('\nThis is the first step.'); continue; } }
|
|
113
|
+
else if (/^j\s*\d+$/i.test(c)) { const n = Number(c.replace(/\D/g, '')); if (n >= 1 && n <= total) i = n - 1; else { say(`\nJump to a step from 1 to ${total}.`); continue; } }
|
|
114
|
+
else { say('\nType Enter or n (next), b (back), j and a number (jump), or q (quit).'); continue; }
|
|
115
|
+
say('');
|
|
116
|
+
show();
|
|
117
|
+
}
|
|
118
|
+
rl.close();
|
|
119
|
+
say('');
|
|
120
|
+
if (trace.status !== 0) say(`The program stopped with a problem: ${trace.stderr.trim()}`);
|
|
121
|
+
return 0;
|
|
122
|
+
})();
|
|
123
|
+
}
|