@skillstech/thunderlang 1.2.0 → 1.4.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 +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -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 +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Types for the Thunder Software Passport (passport.mjs, passport-fs.mjs). Spec: docs/passport.md.
|
|
2
|
+
export const PASSPORT_SCHEMA: 'thunder-passport-v1';
|
|
3
|
+
export const ALWAYS_NOT_VERIFIED: string[];
|
|
4
|
+
export interface PassportInput { part: string; file: string; sha256: string | null }
|
|
5
|
+
export interface PassportEvidence {
|
|
6
|
+
id: string;
|
|
7
|
+
kind: 'test-run' | 'trace-link' | 'review' | 'accuracy-gate' | 'conformance' | 'access-flow' | string;
|
|
8
|
+
/** passed / failed: a command ran; read: read from code, nothing was run. */
|
|
9
|
+
status: 'passed' | 'failed' | 'read';
|
|
10
|
+
claim: string;
|
|
11
|
+
basis: { command?: string; cwd?: string; exitCode?: number; outputDigest?: string; outputTail?: string; from?: string; to?: string; base?: string; head?: string; [k: string]: unknown };
|
|
12
|
+
/** What this evidence does not cover. */
|
|
13
|
+
scope: string;
|
|
14
|
+
/** The files it depended on, by content hash; when one changes, the item is stale. */
|
|
15
|
+
inputs: PassportInput[];
|
|
16
|
+
}
|
|
17
|
+
export interface Passport {
|
|
18
|
+
schema: 'thunder-passport-v1';
|
|
19
|
+
subject: { kind: 'change' | 'feature'; parts: Array<{ name: string; path: string; sha: string | null; dirty: boolean }> };
|
|
20
|
+
purpose: { stated: boolean; text: string; source: string | null };
|
|
21
|
+
behavior: Array<{ part: string; file: string; lines: [number, number]; name: string; kind: string; change?: 'added' | 'changed' | 'removed'; text: string }>;
|
|
22
|
+
dependencies: { files: PassportInput[]; links: Array<{ kind: string; says: string; from: string; to: string }>; packages: Array<{ name: string; version?: string; from: string; dev?: boolean }>; services: Array<{ part: string; calls: string; at: string }> };
|
|
23
|
+
effects: Array<{ part: string; file: string; line: number; in: string; kind: 'reads' | 'writes' | 'sends' | 'deletes' | 'calls another part' | 'sends the person to'; says: string; how: 'detected' | 'observed' | 'declared'; basis: string }>;
|
|
24
|
+
evidence: PassportEvidence[];
|
|
25
|
+
unknowns: { notRead: Array<{ part: string; file: string; line: number; what: string }>; notLinked: Array<{ kind: string; call: string; at: string; why: string }>; untested: Array<{ part: string; what: string }>; notShown?: string; notVerified: string[] };
|
|
26
|
+
history: { base: string | null; head: string | null; changedFiles: Array<{ part: string; file: string; status: string }>; thunder: string | null; builtAt: string };
|
|
27
|
+
summary: { claims: number; passed: number; failed: number; readFromCode: number; unknowns: number; notVerified: number };
|
|
28
|
+
fingerprint: string;
|
|
29
|
+
}
|
|
30
|
+
export interface PassportCheck {
|
|
31
|
+
schema: 'thunder-passport-check-v1'; current: number; stale: number;
|
|
32
|
+
items: Array<{ id: string; kind: string; claim: string; freshness: 'current' | 'stale' | 'unknown'; changed: Array<{ part: string; file: string; now: 'changed' | 'missing' }> }>;
|
|
33
|
+
changedFiles: Array<{ part: string; file: string; now: 'changed' | 'missing' }>;
|
|
34
|
+
}
|
|
35
|
+
export function assemblePassport(input: {
|
|
36
|
+
parts: Array<{ name: string; path?: string; sha?: string | null; dirty?: boolean; files: Array<{ path: string; source: string }>; packages?: Passport['dependencies']['packages']; changes?: Array<{ file: string; status: 'added' | 'changed' | 'removed'; ranges: Array<[number, number]>; old?: string | null }> }>;
|
|
37
|
+
change?: { base: string; head: string | null } | null;
|
|
38
|
+
runs?: Array<{ command: string; part: string | null; cwd: string; exitCode: number; output: string }>;
|
|
39
|
+
purpose?: { text: string; source?: string } | null;
|
|
40
|
+
extra?: Array<Omit<PassportEvidence, 'id'>>;
|
|
41
|
+
builtAt?: string; thunder?: string | null;
|
|
42
|
+
}): Passport;
|
|
43
|
+
export function summarize(passport: Omit<Passport, 'summary' | 'fingerprint'>): Passport['summary'];
|
|
44
|
+
export function checkPassport(passport: Passport, options: { read: (part: string, file: string) => string | null }): PassportCheck;
|
|
45
|
+
export function renderPassportSummary(passport: Passport): string;
|
|
46
|
+
export function renderPassportMarkdown(passport: Passport): string;
|
package/src/passport.mjs
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// Thunder Software Passport (thunder-passport-v1): a portable evidence record for a feature or a change.
|
|
2
|
+
//
|
|
3
|
+
// It is not a certificate that the code is correct. It is an evidence manifest: every claim names its basis (a
|
|
4
|
+
// command and its exit code, or a source location), what it does not cover, and the exact files (by content hash)
|
|
5
|
+
// it depended on. When one of those files changes, the claim is stale, and checkPassport says so.
|
|
6
|
+
//
|
|
7
|
+
// This file is the pure, browser-safe half: it assembles a passport from what was read and run, renders it, and
|
|
8
|
+
// checks it against current file contents. Reading folders, git, and running commands is in passport-fs.mjs.
|
|
9
|
+
import { sha256 } from './hash.mjs';
|
|
10
|
+
import { thunderModel, modelText } from './model.mjs';
|
|
11
|
+
import { buildTrace, isTestFile } from './trace.mjs';
|
|
12
|
+
import { thunderReview } from './review.mjs';
|
|
13
|
+
|
|
14
|
+
export const PASSPORT_SCHEMA = 'thunder-passport-v1';
|
|
15
|
+
|
|
16
|
+
/** What nothing in a passport establishes unless an evidence item says otherwise. Always listed. */
|
|
17
|
+
export const ALWAYS_NOT_VERIFIED = [
|
|
18
|
+
'Deployment: how it is configured and run in a real environment.',
|
|
19
|
+
'External services: real providers, their answers, and their outages (tests use what the code was given).',
|
|
20
|
+
'More than one process or machine: anything kept in memory is not shared between copies.',
|
|
21
|
+
'Load and timing: behavior under many requests at once, beyond what the tests ran.',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const MAX_BEHAVIOR = 60;
|
|
25
|
+
const fileHash = (source) => sha256(String(source)); // 'sha256:<hex>'
|
|
26
|
+
|
|
27
|
+
const EFFECT = { find: 'reads', save: 'writes', send: 'sends', ask: 'calls another part', redirect: 'sends the person to' };
|
|
28
|
+
function effectKind(node) {
|
|
29
|
+
if (node.does === 'save' && /^(Deletes|Removes)\b/.test(node.text || '')) return 'deletes';
|
|
30
|
+
return EFFECT[node.does] ?? null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Assemble a passport from parts already read (and, for a change, their base versions), runs already made, and a
|
|
35
|
+
* purpose. Pure and deterministic: the same inputs (with the same `builtAt`) give the same passport.
|
|
36
|
+
* parts: [{ name, path, sha?, dirty?, files: [{ path, source, manifest? }], packages?: [{ name, version?, from }],
|
|
37
|
+
* changes?: [{ file, status: 'added'|'changed'|'removed', ranges: [[a, b]…], old?: string|null }] }]
|
|
38
|
+
* change: { base, head } when this is a change (each part's `changes` then say what changed); null for a snapshot
|
|
39
|
+
* runs: [{ command, part: name|null, cwd, exitCode, output }] (output: what it printed, both streams)
|
|
40
|
+
* purpose: { text, source } or null
|
|
41
|
+
* extra: evidence items supplied by other tools (an access-flow result, a conformance run…), already in shape
|
|
42
|
+
*/
|
|
43
|
+
export function assemblePassport({ parts, change = null, runs = [], purpose = null, extra = [], builtAt = new Date().toISOString(), thunder = null }) {
|
|
44
|
+
const hashes = new Map(); // `${part}/${file}` -> { part, file, sha256 }
|
|
45
|
+
for (const p of parts) for (const f of p.files) hashes.set(`${p.name}/${f.path}`, { part: p.name, file: f.path, sha256: fileHash(f.source) });
|
|
46
|
+
const inputOf = (part, file) => hashes.get(`${part}/${file}`) ?? { part, file, sha256: null };
|
|
47
|
+
const partInputs = (name) => [...hashes.values()].filter((h) => h.part === name);
|
|
48
|
+
|
|
49
|
+
const models = new Map(parts.map((p) => [p.name, thunderModel(p.files.filter((f) => !f.manifest), { name: p.name })]));
|
|
50
|
+
const changed = (p, file) => (p.changes ?? []).find((c) => c.file === file);
|
|
51
|
+
|
|
52
|
+
// Behavior: in a change, the actions and rules whose lines the change touched (or in an added file); in a
|
|
53
|
+
// snapshot, every action and rule. Test code is evidence, not behavior.
|
|
54
|
+
const behavior = [], effects = [], notRead = [];
|
|
55
|
+
for (const p of parts) {
|
|
56
|
+
const model = models.get(p.name);
|
|
57
|
+
for (const m of model.members) {
|
|
58
|
+
if (m.kind === 'setup' || isTestFile(m.file)) continue;
|
|
59
|
+
const c = change ? changed(p, m.file) : null;
|
|
60
|
+
if (change && !(c && (c.status === 'added' || c.ranges.some(([a, b]) => a <= m.lines[1] && b >= m.lines[0])))) continue;
|
|
61
|
+
const item = { part: p.name, file: m.file, lines: m.lines, name: m.label, kind: m.kind, ...(c ? { change: c.status } : {}) };
|
|
62
|
+
if (m.kind === 'not-read') { notRead.push({ part: p.name, file: m.file, line: m.lines[0], what: `${m.label}: Thunder does not read this yet` }); continue; }
|
|
63
|
+
let text = '';
|
|
64
|
+
try { text = modelText(model, m.id).trim(); } catch { text = ''; }
|
|
65
|
+
behavior.push({ ...item, text });
|
|
66
|
+
for (const nd of m.flow?.nodes ?? []) {
|
|
67
|
+
const kind = effectKind(nd);
|
|
68
|
+
if (kind) effects.push({ part: p.name, file: m.file, line: nd.line ?? m.lines[0], in: m.label, kind, says: nd.text, how: 'detected', basis: 'read from code; nothing was run' });
|
|
69
|
+
if (nd.does === 'code' && nd.line != null) notRead.push({ part: p.name, file: m.file, line: nd.line, what: `shown as code: ${String(nd.text).slice(0, 100)}` });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const u of model.unknowns ?? []) {
|
|
73
|
+
if (isTestFile(u.file)) continue;
|
|
74
|
+
const c = change ? changed(p, u.file) : null;
|
|
75
|
+
if (change && !(c && (c.status === 'added' || c.ranges.some(([a, b]) => u.line >= a && u.line <= b)))) continue;
|
|
76
|
+
const owner = model.members.find((m) => m.file === u.file && m.lines[0] <= u.line && m.lines[1] >= u.line);
|
|
77
|
+
notRead.push({ part: p.name, file: u.file, line: u.line, what: owner ? `${owner.label}: ${u.why}` : u.why });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const order = (a, b) => `${a.part}/${a.file}`.localeCompare(`${b.part}/${b.file}`) || ((a.lines?.[0] ?? a.line ?? 0) - (b.lines?.[0] ?? b.line ?? 0));
|
|
81
|
+
behavior.sort(order); effects.sort(order); notRead.sort(order);
|
|
82
|
+
{ const seen = new Set(); notRead.splice(0, notRead.length, ...notRead.filter((x) => { const k = `${x.part}/${x.file}:${x.line}`; if (seen.has(k)) return false; seen.add(k); return true; })); }
|
|
83
|
+
const shownBehavior = behavior.slice(0, MAX_BEHAVIOR);
|
|
84
|
+
|
|
85
|
+
// Dependencies: every file read (with its hash), the links between the parts, packages, and services called.
|
|
86
|
+
const trace = buildTrace(parts.map((p) => ({ name: p.name, sha: p.sha ?? null, dirty: !!p.dirty, files: p.files.filter((f) => !f.manifest) })));
|
|
87
|
+
const links = trace.links.map((l) => ({ kind: l.kind, says: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo}: ${l.method} ${l.path} (handled by ${l.to.label ?? l.route})` : `${l.from.repo} publishes ${l.event}, and ${l.to.repo} listens`, from: l.from.cite, to: l.to.cite }));
|
|
88
|
+
const services = [];
|
|
89
|
+
for (const r of trace.repos) for (const q of r.requests ?? []) if (q.base && q.base !== 'this app') services.push({ part: r.name, calls: `${q.method} ${q.base}${q.path}`, at: `${r.name}:${q.file}:${q.line}` });
|
|
90
|
+
|
|
91
|
+
// Evidence.
|
|
92
|
+
const evidence = [];
|
|
93
|
+
const add = (x) => evidence.push({ id: `e${evidence.length + 1}`, ...x });
|
|
94
|
+
for (const r of runs) {
|
|
95
|
+
const passed = r.exitCode === 0;
|
|
96
|
+
const tail = String(r.output ?? '').replace(/\s+$/, '').split('\n').slice(-12).join('\n');
|
|
97
|
+
add({
|
|
98
|
+
kind: 'test-run', status: passed ? 'passed' : 'failed',
|
|
99
|
+
claim: `\`${r.command}\`${r.part ? ` in ${r.part}` : ''} exited with ${r.exitCode}${passed ? '' : ' (a failure)'}.`,
|
|
100
|
+
basis: { command: r.command, cwd: r.cwd, exitCode: r.exitCode, outputDigest: fileHash(r.output ?? ''), outputTail: tail },
|
|
101
|
+
scope: 'Only what these tests exercise. Thunder did not measure which lines or paths they cover.',
|
|
102
|
+
inputs: r.part ? partInputs(r.part) : [...hashes.values()],
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
for (const l of trace.links) {
|
|
106
|
+
add({
|
|
107
|
+
kind: 'trace-link', status: 'read',
|
|
108
|
+
claim: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo} with ${l.method} ${l.path}, and ${l.to.repo} handles it.` : `${l.from.repo} publishes "${l.event}", and ${l.to.repo} listens for it.`,
|
|
109
|
+
basis: { from: l.from.cite, to: l.to.cite, rules: `thunder-trace rules v${trace.rulesVersion}` },
|
|
110
|
+
scope: 'Read from code; nothing was run. It does not show that the call succeeds or what it answers.',
|
|
111
|
+
inputs: [inputOf(l.from.repo, l.from.file), inputOf(l.to.repo, l.to.file)],
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
let review = null;
|
|
115
|
+
if (change) {
|
|
116
|
+
const oldFiles = [], newFiles = [], changedInputs = [];
|
|
117
|
+
for (const p of parts) for (const c of p.changes ?? []) {
|
|
118
|
+
if (c.old != null) oldFiles.push({ path: `${p.name}/${c.file}`, source: c.old });
|
|
119
|
+
const now = p.files.find((f) => f.path === c.file);
|
|
120
|
+
if (now && c.status !== 'removed') { newFiles.push({ path: `${p.name}/${c.file}`, source: now.source }); changedInputs.push(inputOf(p.name, c.file)); }
|
|
121
|
+
}
|
|
122
|
+
review = thunderReview(oldFiles, newFiles);
|
|
123
|
+
add({
|
|
124
|
+
kind: 'review', status: 'read',
|
|
125
|
+
claim: `What the change does, read from both versions: ${review.says}`,
|
|
126
|
+
basis: { base: change.base, head: change.head, schema: review.schema, meaning: review.summary.meaning, risk: review.summary.risk, form: review.summary.form },
|
|
127
|
+
scope: 'What the code says before and after; not whether it runs or is right.',
|
|
128
|
+
inputs: changedInputs,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
for (const x of extra) add({ ...x, inputs: (x.inputs ?? []).map((i) => (i.sha256 ? i : inputOf(i.part, i.file))) });
|
|
132
|
+
|
|
133
|
+
// Unknowns: what Thunder could not read or link, the parts no test ran in, and what nothing here verified.
|
|
134
|
+
const tested = new Set(runs.filter((r) => r.part).map((r) => r.part));
|
|
135
|
+
const anyUnscoped = runs.some((r) => !r.part);
|
|
136
|
+
const untested = anyUnscoped ? [] : parts.filter((p) => !tested.has(p.name)).map((p) => ({ part: p.name, what: `No tests were run in ${p.name}.` }));
|
|
137
|
+
const notLinked = trace.notLinked.map((n) => ({ kind: n.kind, call: n.call, at: n.from.cite, why: n.why }));
|
|
138
|
+
const unknowns = {
|
|
139
|
+
notRead, notLinked, untested,
|
|
140
|
+
...(behavior.length > MAX_BEHAVIOR ? { notShown: `${behavior.length - MAX_BEHAVIOR} more actions and rules are not listed (the first ${MAX_BEHAVIOR} are).` } : {}),
|
|
141
|
+
notVerified: [...ALWAYS_NOT_VERIFIED, ...runs.filter((r) => r.exitCode !== 0).map((r) => `\`${r.command}\` failed, so what it tests is not verified.`)],
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const changedFiles = change ? parts.flatMap((p) => (p.changes ?? []).map((c) => ({ part: p.name, file: c.file, status: c.status }))) : [];
|
|
145
|
+
const body = {
|
|
146
|
+
schema: PASSPORT_SCHEMA,
|
|
147
|
+
subject: { kind: change ? 'change' : 'feature', parts: parts.map((p) => ({ name: p.name, path: p.path ?? p.name, sha: p.sha ?? null, dirty: !!p.dirty })) },
|
|
148
|
+
purpose: purpose?.text ? { stated: true, text: purpose.text, source: purpose.source ?? 'given when the passport was built' } : { stated: false, text: 'not stated', source: null },
|
|
149
|
+
behavior: shownBehavior,
|
|
150
|
+
dependencies: { files: [...hashes.values()], links, packages: parts.flatMap((p) => p.packages ?? []), services },
|
|
151
|
+
effects,
|
|
152
|
+
evidence,
|
|
153
|
+
unknowns,
|
|
154
|
+
history: { base: change?.base ?? null, head: change?.head ?? null, changedFiles, thunder },
|
|
155
|
+
};
|
|
156
|
+
const summary = summarize(body);
|
|
157
|
+
return { ...body, summary, history: { ...body.history, builtAt }, fingerprint: sha256(JSON.stringify({ ...body, summary })) };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The counts people read first. A claim is an evidence item; nothing counts as verified without one. */
|
|
161
|
+
export function summarize(p) {
|
|
162
|
+
const by = (s) => p.evidence.filter((e) => e.status === s).length;
|
|
163
|
+
const u = p.unknowns;
|
|
164
|
+
return {
|
|
165
|
+
claims: p.evidence.length, passed: by('passed'), failed: by('failed'), readFromCode: by('read'),
|
|
166
|
+
unknowns: u.notRead.length + u.notLinked.length + u.untested.length, notVerified: u.notVerified.length,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Is each evidence item still about the code as it is now? `read(part, file)` gives a file's current text, or null
|
|
172
|
+
* when it is gone. Nothing is re-run: an item is `current` when every file it depended on is unchanged, else `stale`
|
|
173
|
+
* (naming each changed or missing file). Items with no recorded inputs are `unknown`.
|
|
174
|
+
*/
|
|
175
|
+
export function checkPassport(passport, { read }) {
|
|
176
|
+
if (passport?.schema !== PASSPORT_SCHEMA) throw new Error('this is not a Thunder passport (thunder-passport-v1).');
|
|
177
|
+
const cache = new Map();
|
|
178
|
+
const now = (part, file) => {
|
|
179
|
+
const k = `${part}/${file}`;
|
|
180
|
+
if (!cache.has(k)) { const s = read(part, file); cache.set(k, s == null ? null : fileHash(s)); }
|
|
181
|
+
return cache.get(k);
|
|
182
|
+
};
|
|
183
|
+
const items = passport.evidence.map((e) => {
|
|
184
|
+
if (!e.inputs?.length) return { id: e.id, kind: e.kind, claim: e.claim, freshness: 'unknown', changed: [] };
|
|
185
|
+
const changed = [];
|
|
186
|
+
for (const i of e.inputs) {
|
|
187
|
+
const h = now(i.part, i.file);
|
|
188
|
+
if (h == null) changed.push({ part: i.part, file: i.file, now: 'missing' });
|
|
189
|
+
else if (h !== i.sha256) changed.push({ part: i.part, file: i.file, now: 'changed' });
|
|
190
|
+
}
|
|
191
|
+
return { id: e.id, kind: e.kind, claim: e.claim, freshness: changed.length ? 'stale' : 'current', changed };
|
|
192
|
+
});
|
|
193
|
+
const files = passport.dependencies.files.map((f) => ({ ...f, now: now(f.part, f.file) })).filter((f) => f.now !== f.sha256)
|
|
194
|
+
.map((f) => ({ part: f.part, file: f.file, now: f.now == null ? 'missing' : 'changed' }));
|
|
195
|
+
return { schema: 'thunder-passport-check-v1', current: items.filter((x) => x.freshness === 'current').length, stale: items.filter((x) => x.freshness === 'stale').length, items, changedFiles: files };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const MARK = { passed: '✓', failed: '✗', read: '○' };
|
|
199
|
+
const STATUS_WORDS = { passed: 'ran and passed', failed: 'ran and failed', read: 'read from code, not run' };
|
|
200
|
+
|
|
201
|
+
/** A passport as short plain text for the terminal: the counts, then each evidence item with a mark and words. */
|
|
202
|
+
export function renderPassportSummary(p) {
|
|
203
|
+
const s = p.summary;
|
|
204
|
+
const L = [`Thunder passport (${p.subject.kind}): ${p.subject.parts.map((x) => x.name).join(', ')}`,
|
|
205
|
+
`Purpose: ${p.purpose.stated ? p.purpose.text : 'not stated'}`,
|
|
206
|
+
`${s.claims} claim${s.claims === 1 ? '' : 's'} with evidence (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), ${s.unknowns} unknown${s.unknowns === 1 ? '' : 's'}, ${s.notVerified} not verified`, '', 'Evidence'];
|
|
207
|
+
for (const e of p.evidence) L.push(` ${MARK[e.status] ?? '○'} ${STATUS_WORDS[e.status] ?? e.status}: ${e.claim}`);
|
|
208
|
+
if (!p.evidence.length) L.push(' (none: nothing in this passport is verified)');
|
|
209
|
+
L.push('', 'Not verified');
|
|
210
|
+
for (const x of p.unknowns.notVerified) L.push(` ○ ${x}`);
|
|
211
|
+
if (p.unknowns.untested.length) for (const x of p.unknowns.untested) L.push(` ○ ${x.what}`);
|
|
212
|
+
return L.join('\n');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The whole passport as Markdown, for a pull request or a folder. */
|
|
216
|
+
export function renderPassportMarkdown(p) {
|
|
217
|
+
const s = p.summary;
|
|
218
|
+
const L = [`# Thunder passport: ${p.subject.parts.map((x) => x.name).join(', ')}`, '',
|
|
219
|
+
`A ${p.subject.kind === 'change' ? `change${p.history.base ? ` from \`${String(p.history.base).slice(0, 12)}\`` : ''}` : 'snapshot'}. **${s.claims} claims with evidence** (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), **${s.unknowns} unknowns**, **${s.notVerified} not verified**. This is an evidence record, not a certificate: each claim says what it rests on and what it does not cover.`, '',
|
|
220
|
+
'## Purpose', '', p.purpose.stated ? `${p.purpose.text}\n\n(Source: ${p.purpose.source}.)` : 'Not stated. Thunder never guesses what a change is for.', ''];
|
|
221
|
+
const evidenceList = (list) => {
|
|
222
|
+
for (const e of list) {
|
|
223
|
+
L.push(`- ${MARK[e.status] ?? '○'} ${e.claim}`);
|
|
224
|
+
const b = e.basis;
|
|
225
|
+
L.push(` - Basis: ${b.command ? `\`${b.command}\` in \`${b.cwd}\`, exit ${b.exitCode}, output ${String(b.outputDigest).slice(0, 19)}…` : b.from ? `${b.from} → ${b.to}` : b.base ? `review of ${String(b.base).slice(0, 12)} → ${String(b.head ?? 'working tree').slice(0, 12)}` : JSON.stringify(b)}`);
|
|
226
|
+
L.push(` - Does not cover: ${e.scope}`);
|
|
227
|
+
L.push(` - Depends on ${e.inputs.length} file${e.inputs.length === 1 ? '' : 's'} (by content hash)`);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const ran = p.evidence.filter((e) => e.status === 'passed'), failedRuns = p.evidence.filter((e) => e.status === 'failed'), readOnly = p.evidence.filter((e) => e.status !== 'passed' && e.status !== 'failed');
|
|
231
|
+
L.push('## Verified by running (ran and passed)', '');
|
|
232
|
+
if (ran.length) evidenceList(ran); else L.push('Nothing was run, so nothing here is verified by running.');
|
|
233
|
+
if (failedRuns.length) { L.push('', '## Ran and failed', ''); evidenceList(failedRuns); }
|
|
234
|
+
L.push('', '## Read from code (not run)', '');
|
|
235
|
+
if (readOnly.length) evidenceList(readOnly); else L.push('None.');
|
|
236
|
+
L.push('', '## Not verified', '', ...p.unknowns.notVerified.map((x) => `- ${x}`), ...p.unknowns.untested.map((x) => `- ${x.what}`), '');
|
|
237
|
+
L.push('## Behavior', '');
|
|
238
|
+
for (const b of p.behavior) {
|
|
239
|
+
L.push(`### ${b.name} (${b.part}/${b.file}, lines ${b.lines[0]}–${b.lines[1]}${b.change ? `, ${b.change}` : ''})`, '', '```text', b.text || '(no reading)', '```', '');
|
|
240
|
+
}
|
|
241
|
+
if (p.unknowns.notShown) L.push(p.unknowns.notShown, '');
|
|
242
|
+
L.push('## Effects (detected in code, not observed)', '');
|
|
243
|
+
for (const e of p.effects) L.push(`- ${e.in} **${e.kind}**: ${e.says} (${e.part}/${e.file}:${e.line})`);
|
|
244
|
+
if (!p.effects.length) L.push('None detected.');
|
|
245
|
+
L.push('', '## Dependencies', '', ...p.dependencies.links.map((l) => `- ${l.says} (${l.from} → ${l.to})`));
|
|
246
|
+
if (p.dependencies.packages.length) L.push(...p.dependencies.packages.map((x) => `- package ${x.name}${x.version ? ` ${x.version}` : ''} (${x.from})`));
|
|
247
|
+
if (p.dependencies.services.length) L.push(...p.dependencies.services.map((x) => `- calls ${x.calls} (${x.at})`));
|
|
248
|
+
L.push(`- ${p.dependencies.files.length} files read, each recorded by content hash`, '');
|
|
249
|
+
L.push('## Unknowns', '');
|
|
250
|
+
for (const x of p.unknowns.notRead) L.push(`- not read: ${x.what} (${x.part}/${x.file}:${x.line})`);
|
|
251
|
+
for (const x of p.unknowns.notLinked) L.push(`- not linked: ${x.call}: ${x.why} (${x.at})`);
|
|
252
|
+
if (!p.unknowns.notRead.length && !p.unknowns.notLinked.length) L.push('Nothing Thunder failed to read or link.');
|
|
253
|
+
L.push('', '## History', '', `- Base: ${p.history.base ?? '(none: a snapshot)'}`, `- Head: ${p.history.head ?? '(working tree)'}`, ...p.history.changedFiles.map((c) => `- ${c.status}: ${c.part}/${c.file}`), `- Built: ${p.history.builtAt}${p.history.thunder ? ` with Thunder ${p.history.thunder}` : ''}`, `- Fingerprint: ${p.fingerprint}`, '');
|
|
254
|
+
return L.join('\n');
|
|
255
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Types for @skillstech/thunderlang/program (src/program.mjs). Results are plain objects; see docs/core.md.
|
|
2
|
+
export interface CoreDiagnostic { code: string; line: number; message: string; hint?: string; [k: string]: unknown }
|
|
3
|
+
export interface CoreResult { ok: boolean; program?: unknown; info?: unknown; diagnostics: CoreDiagnostic[]; file?: string; module?: string; kind?: string; [k: string]: unknown }
|
|
4
|
+
export interface RunOutput { status: number; stdout: string; stderr: string; [k: string]: unknown }
|
|
5
|
+
export type ReadText = ((path: string, cwd: string) => string) | null;
|
|
6
|
+
export const CORE_VERSION: string;
|
|
7
|
+
export const CODES: Record<string, unknown>;
|
|
8
|
+
export function compileCore(source: string, options?: { file?: string; imported?: unknown[]; srcModules?: unknown[] }): CoreResult;
|
|
9
|
+
export function diagnosticsText(result: CoreResult): string;
|
|
10
|
+
export function parseCore(source: string, ...rest: unknown[]): unknown;
|
|
11
|
+
export function checkCore(...args: unknown[]): unknown;
|
|
12
|
+
export function formatCore(source: string, options?: { width?: number }): unknown;
|
|
13
|
+
export function formatDiagnostic(...args: unknown[]): string;
|
|
14
|
+
export function runInProcess(options: { entry: CoreResult; cwd: string; deeper?: boolean; readText?: ReadText }): RunOutput;
|
|
15
|
+
export function recordedRun(options: { entry: CoreResult; cwd: string; readText?: ReadText }): unknown;
|
|
16
|
+
export function testInProcess(options: { results: CoreResult[]; cwd: string; deeper?: boolean; readText?: ReadText }): unknown;
|
|
17
|
+
export interface ScreenAppHandle { render(): unknown; readonly screen: string | null; press(label: string, nth?: number): { off: boolean; tree: unknown }; type(label: string, text: string, nth?: number): { tree: unknown } }
|
|
18
|
+
/** The same handle, by the name apps expect. */
|
|
19
|
+
export type ScreenApp = ScreenAppHandle;
|
|
20
|
+
export function screenApp(options: { entry: CoreResult; cwd?: string; readText?: ReadText }): ScreenAppHandle;
|
|
21
|
+
export function screenOutline(tree: unknown, indent?: string): string;
|
|
22
|
+
export function toPython(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
23
|
+
export function toTypeScript(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
24
|
+
export function toCSharp(program: unknown, info: unknown, options?: { source?: string; module?: string; namespace?: string; imports?: unknown[] }): string;
|
|
25
|
+
export function toJava(program: unknown, info: unknown, options?: { source?: string; module?: string; imports?: unknown[]; pkg?: string }): string;
|
|
26
|
+
export function toGo(program: unknown, info: unknown, options: { source?: string; module?: string; ns: unknown }): string;
|
|
27
|
+
export function goNamespaces(results: CoreResult[]): Map<string, unknown>;
|
|
28
|
+
export function toRust(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
29
|
+
export function toReact(program: unknown, info: unknown, options?: { source?: string }): string;
|
|
30
|
+
export function hasScreens(info: unknown): boolean;
|
|
31
|
+
export function pythonToCore(source: string): { core: string; functions: Array<{ name: string; exact: boolean }>; [k: string]: unknown };
|
package/src/program.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// @skillstech/thunderlang/program: write and run Thunder Core anywhere, including in a browser. Compile a program,
|
|
2
|
+
// run it on the Thunder engine, show its screens, and turn it into Python, TypeScript, C#, Java, Go, Rust, or React.
|
|
3
|
+
// Everything here is browser-safe (no node: imports; test/program-entry.test.mjs checks the whole import graph).
|
|
4
|
+
// Files are read only through the `readText` you pass, so a browser can hand in its own.
|
|
5
|
+
export { compileCore, diagnosticsText, parseCore, checkCore, formatCore, CODES, formatDiagnostic, CORE_VERSION } from './core/index.mjs';
|
|
6
|
+
export { runInProcess, recordedRun, testInProcess, screenApp, screenOutline } from './core/engine-core.mjs';
|
|
7
|
+
export { toPython } from './core/target-python.mjs';
|
|
8
|
+
export { toTypeScript } from './core/target-typescript.mjs';
|
|
9
|
+
export { toCSharp } from './core/target-csharp.mjs';
|
|
10
|
+
export { toJava } from './core/target-java.mjs';
|
|
11
|
+
export { toGo, goNamespaces } from './core/target-go.mjs';
|
|
12
|
+
export { toRust } from './core/target-rust.mjs';
|
|
13
|
+
export { toReact, hasScreens } from './core/target-react.mjs';
|
|
14
|
+
export { pythonToCore } from './core/from-python.mjs';
|
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
|
@@ -135,6 +135,27 @@ function matchClose(src, open) {
|
|
|
135
135
|
// The language being read. Only Rust has lifetimes ('static, 'a), which look like an opening quote.
|
|
136
136
|
let READING_RUST = false;
|
|
137
137
|
|
|
138
|
+
/** For C# and Java: a flag per character, 1 inside text ("…", $"…", @"…", '…', """…""") or a comment. */
|
|
139
|
+
function textRanges(src) {
|
|
140
|
+
const flags = new Uint8Array(src.length + 1);
|
|
141
|
+
for (let i = 0; i < src.length; i++) {
|
|
142
|
+
const c = src[i];
|
|
143
|
+
if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); const end = e < 0 ? src.length : e; flags.fill(1, i, end); i = end; continue; }
|
|
144
|
+
if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); const end = e < 0 ? src.length : e + 2; flags.fill(1, i, end); i = end - 1; continue; }
|
|
145
|
+
if (c === '"' || c === '\'') {
|
|
146
|
+
let end;
|
|
147
|
+
if (c === '"' && src[i - 1] === '@' || (c === '"' && src[i - 1] === '$' && src[i - 2] === '@')) {
|
|
148
|
+
// A verbatim string: "" is a quote inside it.
|
|
149
|
+
end = i + 1;
|
|
150
|
+
while (end < src.length && !(src[end] === '"' && src[end + 1] !== '"')) end += src[end] === '"' ? 2 : 1;
|
|
151
|
+
} else end = skipString(src, i);
|
|
152
|
+
flags.fill(1, i, Math.min(src.length, end + 1));
|
|
153
|
+
i = end;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return flags;
|
|
157
|
+
}
|
|
158
|
+
|
|
138
159
|
function skipString(src, i) {
|
|
139
160
|
const q = src[i];
|
|
140
161
|
// A multi-line string (triple quotes in Swift, Kotlin, Java, C#) runs to its closing triple quote.
|
|
@@ -244,7 +265,8 @@ function balancedReturnHead(after) {
|
|
|
244
265
|
if (c === '=' && after[i + 1] === '>') { if (depth === 0) break; i++; continue; } // => ends the type, or is a function type's arrow
|
|
245
266
|
if (c === '<' || c === '(' || c === '[') depth++;
|
|
246
267
|
else if (c === '>' || c === ')' || c === ']') depth--;
|
|
247
|
-
|
|
268
|
+
// (At the top, a "{" with no type before it, or after | or &, starts an object type: `): { ok: boolean } {`.)
|
|
269
|
+
else if (c === '{') { if (depth === 0 && !/^$|[|&]$/.test(after.slice(lead[0].length, i).trim())) break; depth++; }
|
|
248
270
|
else if (c === '}') depth--;
|
|
249
271
|
else if (c === ';' && depth === 0) break;
|
|
250
272
|
else if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < after.length && after[i] !== q) i++; }
|
|
@@ -324,7 +346,8 @@ function findFunctions(src, language) {
|
|
|
324
346
|
const patterns = {
|
|
325
347
|
typescript: [
|
|
326
348
|
/(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
|
|
327
|
-
|
|
349
|
+
// The type annotation stops at the end of its statement (";"), or `let a: T;` would name the next line's function.
|
|
350
|
+
/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
|
|
328
351
|
/^\s*(?:public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/gm,
|
|
329
352
|
],
|
|
330
353
|
go: [/func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\s*\(/g],
|
|
@@ -336,6 +359,9 @@ function findFunctions(src, language) {
|
|
|
336
359
|
patterns.javascript = patterns.typescript;
|
|
337
360
|
patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
|
|
338
361
|
const seen = new Set();
|
|
362
|
+
// C# and Java: words inside text (`$"known bug (fails as expected) {name}"`) are never a method, and neither is a
|
|
363
|
+
// lambda passed as an argument (`Check("…", async () => { … })`).
|
|
364
|
+
const inText = (language === 'csharp' || language === 'java') ? textRanges(src) : null;
|
|
339
365
|
for (const re of patterns[language] || []) {
|
|
340
366
|
let m;
|
|
341
367
|
re.lastIndex = 0;
|
|
@@ -343,6 +369,7 @@ function findFunctions(src, language) {
|
|
|
343
369
|
const name = m[1];
|
|
344
370
|
const open = src.indexOf('(', m.index + m[0].length - 1);
|
|
345
371
|
if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
|
|
372
|
+
if (inText && (inText[m.index + m[0].lastIndexOf(name, m[0].length - 1)] || (language === 'csharp' && name === 'async'))) continue;
|
|
346
373
|
const close = matchClose(src, open);
|
|
347
374
|
if (close < 0) continue;
|
|
348
375
|
// After the parameter list: an optional return type / throws clause, then a body. A signature's head is short,
|
|
@@ -417,8 +444,12 @@ function findFunctions(src, language) {
|
|
|
417
444
|
? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g]
|
|
418
445
|
: language === 'go'
|
|
419
446
|
? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
|
|
447
|
+
: language === 'csharp'
|
|
448
|
+
// ASP.NET minimal APIs: app.MapPost("/orders", async (OrderRequest request, OrderService orders) => { … })
|
|
449
|
+
? [/\b\w+\.Map(Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"\s*,\s*(?:async\s*)?\(/g]
|
|
420
450
|
: (language === 'typescript' || language === 'javascript')
|
|
421
|
-
|
|
451
|
+
// (The handler may be wrapped: `fastify.get('/x', handle(async (request) => …))`, `asyncHandler(…)`.)
|
|
452
|
+
? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
|
|
422
453
|
: [];
|
|
423
454
|
for (const re of routeRes) {
|
|
424
455
|
let m;
|
|
@@ -426,11 +457,31 @@ function findFunctions(src, language) {
|
|
|
426
457
|
const open = src.indexOf('(', m.index + m[0].length - 1);
|
|
427
458
|
const close = matchClose(src, open);
|
|
428
459
|
if (close < 0) continue;
|
|
460
|
+
const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
|
|
429
461
|
const brace = src.indexOf('{', close);
|
|
430
|
-
if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace)))
|
|
462
|
+
if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) {
|
|
463
|
+
// An arrow whose body is one expression: `async (request) => practiceView(…)`. It gives back that value;
|
|
464
|
+
// the expression runs to the first ")" or "," that closes the call around it.
|
|
465
|
+
const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
|
|
466
|
+
if (!(language === 'typescript' || language === 'javascript' || language === 'csharp') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
|
|
467
|
+
const from = close + 1 + arrow[0].length;
|
|
468
|
+
let depth = 0, end = from, q = null;
|
|
469
|
+
for (; end < src.length; end++) {
|
|
470
|
+
const c = src[end];
|
|
471
|
+
if (q) { if (c === q && src[end - 1] !== '\\') q = null; continue; }
|
|
472
|
+
if (c === "'" || c === '"' || c === '`') { q = c; continue; }
|
|
473
|
+
if ('([{'.includes(c)) depth++;
|
|
474
|
+
else if (')]}'.includes(c)) { if (depth === 0) break; depth--; }
|
|
475
|
+
else if ((c === ',' || c === ';') && depth === 0) break;
|
|
476
|
+
}
|
|
477
|
+
const expr = src.slice(from, end).trim();
|
|
478
|
+
if (!expr) continue;
|
|
479
|
+
// (Read as `return <expr>`: the body starts 7 characters early so every line number stays right.)
|
|
480
|
+
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 });
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
431
483
|
const bc = matchClose(src, brace);
|
|
432
484
|
if (bc < 0) continue;
|
|
433
|
-
const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
|
|
434
485
|
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
486
|
}
|
|
436
487
|
}
|
|
@@ -1156,6 +1207,14 @@ function annotateRoutes(fns, src) {
|
|
|
1156
1207
|
const above = fn.decorators
|
|
1157
1208
|
? [...fn.decorators].reverse()
|
|
1158
1209
|
: lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
|
|
1210
|
+
// Python's standard library server: a handler's do_POST answers POST, and the one path it checks
|
|
1211
|
+
// (`if self.path != "/charges": …`) is its route. Two or more paths checked: no single route, so none is named.
|
|
1212
|
+
const std = /^do_(GET|POST|PUT|PATCH|DELETE|HEAD)$/.exec(fn.name ?? '');
|
|
1213
|
+
const stdBody = typeof fn.body === 'string' ? fn.body : Array.isArray(fn.pyBody) ? fn.pyBody.map((x) => x.text).join('\n') : null;
|
|
1214
|
+
if (std && stdBody) {
|
|
1215
|
+
const paths = new Set([...stdBody.matchAll(/\bself\.path\s*(?:==|!=)\s*['"](\/[^'"]*)['"]/g)].map((x) => x[1]));
|
|
1216
|
+
if (paths.size === 1) { fn.route = { method: std[1], path: [...paths][0] }; continue; }
|
|
1217
|
+
}
|
|
1159
1218
|
for (const l of above) {
|
|
1160
1219
|
let m;
|
|
1161
1220
|
if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
|