@skillstech/thunderlang 0.4.1 → 0.5.2

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.
@@ -0,0 +1,21 @@
1
+ import type { ReadItem, ReadKind } from './read.mjs';
2
+ export interface RepoItem extends ReadItem { file: string; language: string }
3
+ export interface RepoFacet { name: string; decisions: string[] }
4
+ export interface RepoReading {
5
+ schema: 'thunder-repo-reading-v1';
6
+ files: Array<{ path: string; language: string; counts: Record<ReadKind | 'partial', number> }>;
7
+ items: RepoItem[];
8
+ counts: Record<ReadKind | 'partial' | 'guarded' | 'route', number>;
9
+ languages: Record<string, number>;
10
+ folders: Record<string, number>;
11
+ answers: RepoFacet[];
12
+ inputs: RepoFacet[];
13
+ skipped: Array<{ path: string; reason: string }>;
14
+ }
15
+ export interface RepoFilter { query?: string; kinds?: Array<ReadKind | 'route' | 'guard'>; status?: string[]; languages?: string[]; path?: string; answer?: string; input?: string }
16
+ export const READ_REPO_SCHEMA: 'thunder-repo-reading-v1';
17
+ export const READ_SKIP_DIRS: Set<string>;
18
+ export function readableLanguage(path: string): string | null;
19
+ export function readRepo(files: Array<{ path: string; source: string; size?: number }>, options?: { maxFileBytes?: number; maxFiles?: number }): RepoReading;
20
+ export function searchRepo(index: RepoReading, filter?: RepoFilter): RepoItem[];
21
+ export function groupByFile(items: RepoItem[]): Array<{ file: string; language: string; items: RepoItem[] }>;
@@ -0,0 +1,139 @@
1
+ // Read a whole repository: run the single-file reader (read.mjs) over every supported file and
2
+ // merge the results into one searchable index, with facets a newcomer actually asks about:
3
+ // "where does the code decide Decline?" (answers), "which rules use creditScore?" (inputs),
4
+ // plus language, folder, kind, and how completely each item was read.
5
+ // Pure and browser-safe: callers pass { path, source } pairs (the CLI reads them from disk, the
6
+ // browser from a folder the person picks; nothing is uploaded). Deterministic, no AI.
7
+ import { readCode } from './read.mjs';
8
+
9
+ export const READ_REPO_SCHEMA = 'thunder-repo-reading-v1';
10
+
11
+ const EXT_LANG = [
12
+ [/\.d\.ts$/i, null],
13
+ [/\.min\.js$/i, null],
14
+ [/\.(ts|tsx|mts|cts)$/i, 'typescript'],
15
+ [/\.(js|jsx|mjs|cjs)$/i, 'javascript'],
16
+ [/\.pyi?$/i, 'python'],
17
+ [/\.go$/i, 'go'],
18
+ [/\.rs$/i, 'rust'],
19
+ [/\.cs$/i, 'csharp'],
20
+ [/\.java$/i, 'java'],
21
+ [/\.kts?$/i, 'kotlin'],
22
+ [/\.php$/i, 'php'],
23
+ [/\.rb$/i, 'ruby'],
24
+ ];
25
+
26
+ /** Folders that hold dependencies, build output, or tooling state rather than the application. */
27
+ export const READ_SKIP_DIRS = new Set([
28
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.vercel', '.turbo', 'coverage',
29
+ 'vendor', 'target', 'bin', 'obj', '__pycache__', '.venv', 'venv', 'env', '.tox', '.mypy_cache',
30
+ '.gradle', '.idea', '.vscode', '.intent', 'third_party', 'Pods', '.terraform',
31
+ ]);
32
+
33
+ /** The language the reader uses for a path, or null when the file is not read. */
34
+ export function readableLanguage(path) {
35
+ const p = String(path).replace(/\\/g, '/');
36
+ if (p.split('/').some((seg) => READ_SKIP_DIRS.has(seg))) return null;
37
+ for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
38
+ return null;
39
+ }
40
+
41
+ /** True for files that look machine-generated or minified (very long lines), which read as noise. */
42
+ function looksGenerated(source) {
43
+ const lines = source.split('\n');
44
+ if (/^\s*(\/\/|#)\s*(Code generated|@generated|<auto-generated)/im.test(lines.slice(0, 5).join('\n'))) return true;
45
+ const long = lines.filter((l) => l.length > 400).length;
46
+ return long > 3 && long / lines.length > 0.2;
47
+ }
48
+
49
+ const topFolder = (path) => {
50
+ const parts = String(path).replace(/\\/g, '/').split('/');
51
+ return parts.length > 1 ? parts[0] : '.';
52
+ };
53
+
54
+ /**
55
+ * Read every supported file into one index. `files` is [{ path, source }]. Files outside the
56
+ * supported languages, inside dependency/build folders, generated, or too large are listed in
57
+ * `skipped` with the reason, never silently dropped.
58
+ */
59
+ export function readRepo(files, { maxFileBytes = 400000, maxFiles = 5000 } = {}) {
60
+ const items = [], fileSummaries = [], skipped = [];
61
+ let considered = 0;
62
+ for (const f of files || []) {
63
+ const path = String(f.path).replace(/\\/g, '/').replace(/^\.\//, '');
64
+ const language = readableLanguage(path);
65
+ if (!language) continue; // not code this reader understands; not worth listing one by one
66
+ considered++;
67
+ if (considered > maxFiles) { skipped.push({ path, reason: `More than ${maxFiles} files; read a smaller folder to include this one.` }); continue; }
68
+ const source = String(f.source ?? '');
69
+ if (source.length > maxFileBytes || (f.size ?? 0) > maxFileBytes) { skipped.push({ path, reason: `Larger than ${Math.round(maxFileBytes / 1000)} KB.` }); continue; }
70
+ if (looksGenerated(source)) { skipped.push({ path, reason: 'Looks generated or minified.' }); continue; }
71
+ let reading;
72
+ try { reading = readCode(source, { language, file: path }); }
73
+ catch (e) { skipped.push({ path, reason: e instanceof Error ? e.message : 'Could not be read.' }); continue; }
74
+ for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
75
+ fileSummaries.push({ path, language, counts: reading.counts });
76
+ }
77
+ return { schema: READ_REPO_SCHEMA, ...summarize(items, fileSummaries), skipped };
78
+ }
79
+
80
+ function summarize(items, files) {
81
+ const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
82
+ const languages = {}, folders = {}, answers = new Map(), inputs = new Map();
83
+ for (const f of files) {
84
+ languages[f.language] = (languages[f.language] || 0) + 1;
85
+ const top = topFolder(f.path);
86
+ folders[top] = (folders[top] || 0) + 1;
87
+ }
88
+ for (const it of items) {
89
+ counts[it.kind]++;
90
+ if (it.status === 'partial') counts.partial++;
91
+ if (it.guards?.length) counts.guarded++;
92
+ if (it.route) counts.route++;
93
+ // Answers include what guards fail with or respond, so "where does the code fail with NotFound?" works.
94
+ const guardAnswers = (it.guards || []).filter((g) => ['fails', 'responds', 'returns'].includes(g.effect.kind)).map((g) => g.effect.name);
95
+ if (it.kind !== 'decision' && !guardAnswers.length) continue;
96
+ for (const result of new Set([...(it.rules || []).map((r) => r.result), it.otherwise?.result, ...guardAnswers].filter(Boolean))) {
97
+ if (!answers.has(result)) answers.set(result, []);
98
+ answers.get(result).push(it.id);
99
+ }
100
+ if (it.kind !== 'decision') continue;
101
+ for (const p of it.inputs || []) {
102
+ if (!inputs.has(p.name)) inputs.set(p.name, []);
103
+ inputs.get(p.name).push(it.id);
104
+ }
105
+ }
106
+ const byUse = (m) => [...m].map(([name, ids]) => ({ name, decisions: ids })).sort((a, b) => b.decisions.length - a.decisions.length || a.name.localeCompare(b.name));
107
+ return { files, items, counts, languages, folders, answers: byUse(answers), inputs: byUse(inputs) };
108
+ }
109
+
110
+ /**
111
+ * Filter the index. Every filter narrows: free text (all words must match), kinds, statuses,
112
+ * languages, a path prefix, an answer the decision can give, and an input it uses.
113
+ */
114
+ export function searchRepo(index, { query = '', kinds = [], status = [], languages = [], path = '', answer = '', input = '' } = {}) {
115
+ const terms = String(query).trim().toLowerCase().split(/\s+/).filter(Boolean);
116
+ const prefix = String(path).replace(/\\/g, '/').replace(/^\.\//, '');
117
+ return index.items.filter((it) => {
118
+ if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes('guard') && it.guards?.length) && !(kinds.includes('route') && it.route)) return false;
119
+ if (status.length && !status.includes(it.status)) return false;
120
+ if (languages.length && !languages.includes(it.language)) return false;
121
+ if (prefix && !it.file.startsWith(prefix)) return false;
122
+ if (answer && !((it.rules || []).some((r) => r.result === answer) || it.otherwise?.result === answer || (it.guards || []).some((g) => g.effect.name === answer))) return false;
123
+ if (input && !(it.inputs || []).some((p) => p.name === input)) return false;
124
+ if (!terms.length) return true;
125
+ const hay = [it.file, it.name, it.route && `${it.route.method} ${it.route.path}`, it.says, it.thunder, ...(it.guards || []).flatMap((g) => [g.code, g.effect.name, g.says]), ...(it.inputs || []).map((p) => `${p.name} ${p.type ?? ''}`), ...(it.rules || []).flatMap((r) => [r.when, r.result, r.says]), it.otherwise?.result]
126
+ .filter(Boolean).join(' ').toLowerCase();
127
+ return terms.every((t) => hay.includes(t));
128
+ });
129
+ }
130
+
131
+ /** Group items by file, keeping file order stable (path order) and item order (line order). */
132
+ export function groupByFile(items) {
133
+ const groups = new Map();
134
+ for (const it of items) {
135
+ if (!groups.has(it.file)) groups.set(it.file, []);
136
+ groups.get(it.file).push(it);
137
+ }
138
+ return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
139
+ }
package/src/read.d.mts ADDED
@@ -0,0 +1,29 @@
1
+ export type ReadKind = 'decision' | 'function' | 'error' | 'test';
2
+ export interface ReadInput { name: string; type: string | null }
3
+ export interface ReadRule { when: string; result: string; line: number; says: string }
4
+ export interface ReadUnread { line: number; text: string; reason: string }
5
+ export interface ReadGuard {
6
+ when: string | null; code: string; line: number; readable: boolean; says: string;
7
+ effect: { kind: 'fails' | 'responds' | 'nothing' | 'stops' | 'returns' | 'returns-computed'; name?: string; detail?: string | null };
8
+ }
9
+ export interface ReadItem {
10
+ id: string; kind: ReadKind; name: string; line: number; status: 'read' | 'partial' | 'signature-only';
11
+ says: string; provenance: 'inferred-from-code';
12
+ inputs?: ReadInput[]; returns?: string | null;
13
+ rules?: ReadRule[]; otherwise?: { result: string; line: number } | null;
14
+ thunder?: string; unread?: ReadUnread[]; guards?: ReadGuard[];
15
+ route?: { method: string; path: string };
16
+ }
17
+ export interface Reading {
18
+ schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
19
+ counts: Record<ReadKind | 'partial' | 'guarded' | 'route', number>; limitations: string[];
20
+ }
21
+ export const READ_SCHEMA: 'thunder-reading-v1';
22
+ export const READ_LANGUAGES: string[];
23
+ export function detectLanguage(source: string, file?: string): string;
24
+ export function readCode(source: string, options?: { language?: string; file?: string }): Reading;
25
+ export function searchReading(reading: Reading, filter?: { query?: string; kinds?: Array<ReadKind | 'route' | 'guard'>; status?: string[] }): ReadItem[];
26
+ export function terminatorEffect(stmt: string, language: string): ReadGuard['effect'] | { kind: 'passes-error' } | null;
27
+ export function toThunderCondition(text: string, inputs?: string[]): string | null;
28
+ export function toThunderOutcome(text: string): string | null;
29
+ export function sayCondition(cond: string): string;