@skillstech/thunderlang 0.5.4 → 0.5.5
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 +96 -0
- package/dist/core.cjs +2240 -424
- package/dist/index.cjs +1247 -113
- package/package.json +1 -1
- package/src/cli.mjs +45 -2
- package/src/core.d.ts +14 -0
- package/src/core.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- package/src/read.d.mts +25 -1
- package/src/read.mjs +280 -23
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.mjs +351 -49
- package/src/thunder-repo.mjs +1 -1
- package/src/thunderize.d.mts +14 -0
- package/src/thunderize.mjs +82 -0
- package/src/visual.d.mts +40 -0
- package/src/visual.mjs +304 -0
package/dist/core.cjs
CHANGED
|
@@ -58,6 +58,7 @@ __export(core_exports, {
|
|
|
58
58
|
IR_RELATIONSHIP_TYPES: () => IR_RELATIONSHIP_TYPES,
|
|
59
59
|
IR_SCHEMA: () => IR_SCHEMA,
|
|
60
60
|
KNOWN_LENSES: () => KNOWN_LENSES,
|
|
61
|
+
MODEL_SCHEMA: () => MODEL_SCHEMA,
|
|
61
62
|
MODE_VALUES: () => MODE_VALUES,
|
|
62
63
|
NODE_FIELDS: () => NODE_FIELDS,
|
|
63
64
|
NODE_STATUSES: () => NODE_STATUSES,
|
|
@@ -68,7 +69,7 @@ __export(core_exports, {
|
|
|
68
69
|
PROOF_CHECK_KEYS: () => PROOF_CHECK_KEYS,
|
|
69
70
|
PROOF_SCHEMA: () => PROOF_SCHEMA,
|
|
70
71
|
PROOF_STATUSES: () => PROOF_STATUSES,
|
|
71
|
-
PROVENANCE: () =>
|
|
72
|
+
PROVENANCE: () => PROVENANCE2,
|
|
72
73
|
READ_LANGUAGES: () => READ_LANGUAGES,
|
|
73
74
|
READ_REPO_SCHEMA: () => READ_REPO_SCHEMA,
|
|
74
75
|
READ_SCHEMA: () => READ_SCHEMA,
|
|
@@ -82,10 +83,12 @@ __export(core_exports, {
|
|
|
82
83
|
RULE_OWNERS: () => RULE_OWNERS,
|
|
83
84
|
RULE_PHASES: () => RULE_PHASES,
|
|
84
85
|
RUNTIME_SCHEMA: () => RUNTIME_SCHEMA,
|
|
86
|
+
SAME_SCHEMA: () => SAME_SCHEMA,
|
|
85
87
|
SCAN_SCHEMA: () => SCAN_SCHEMA,
|
|
86
88
|
SCHEMA_VERSION: () => SCHEMA_VERSION,
|
|
87
89
|
SCOPE_TYPES: () => SCOPE_TYPES,
|
|
88
90
|
SEED_SCHEMA: () => SEED_SCHEMA,
|
|
91
|
+
SEMANTIC_TYPES: () => SEMANTIC_TYPES3,
|
|
89
92
|
SENSITIVITY: () => SENSITIVITY,
|
|
90
93
|
STEPS_SCHEMA: () => STEPS_SCHEMA,
|
|
91
94
|
STYLE_ADDRESS_SPACE: () => STYLE_ADDRESS_SPACE,
|
|
@@ -93,6 +96,10 @@ __export(core_exports, {
|
|
|
93
96
|
SUPPORTED_LANGUAGES: () => SUPPORTED_LANGUAGES,
|
|
94
97
|
SYNC_SCHEMA: () => SYNC_SCHEMA,
|
|
95
98
|
TEST_SCHEMA: () => TEST_SCHEMA,
|
|
99
|
+
THING_LANGUAGES: () => THING_LANGUAGES,
|
|
100
|
+
THUNDERIZE_SCHEMA: () => THUNDERIZE_SCHEMA,
|
|
101
|
+
THUNDER_TEXT_EXT: () => THUNDER_TEXT_EXT,
|
|
102
|
+
THUNDER_VISUAL: () => THUNDER_VISUAL,
|
|
96
103
|
TOKEN_PATHS: () => TOKEN_PATHS,
|
|
97
104
|
TRANSLATE_LANGUAGES: () => TRANSLATE_LANGUAGES,
|
|
98
105
|
TWELVE_FACTOR_SCHEMA: () => TWELVE_FACTOR_SCHEMA,
|
|
@@ -100,11 +107,14 @@ __export(core_exports, {
|
|
|
100
107
|
VERIFICATION_RULES: () => VERIFICATION_RULES,
|
|
101
108
|
VIEWS: () => VIEWS,
|
|
102
109
|
VIEW_SCHEMA: () => VIEW_SCHEMA,
|
|
110
|
+
VISUAL_SCHEMA: () => VISUAL_SCHEMA,
|
|
103
111
|
WRITE_SCHEMA: () => WRITE_SCHEMA,
|
|
104
112
|
analyzeStyle: () => analyzeStyle,
|
|
105
113
|
anchorReport: () => anchorReport,
|
|
106
114
|
applyEdits: () => applyEdits,
|
|
115
|
+
askAsQuestion: () => askAsQuestion,
|
|
107
116
|
atlasNode: () => atlasNode,
|
|
117
|
+
autocorrectSource: () => autocorrectSource,
|
|
108
118
|
blocksProduction: () => blocksProduction,
|
|
109
119
|
buildArchitectureGraph: () => buildArchitectureGraph,
|
|
110
120
|
buildAtlas: () => buildAtlas,
|
|
@@ -120,25 +130,33 @@ __export(core_exports, {
|
|
|
120
130
|
checkDecisionCases: () => checkDecisionCases,
|
|
121
131
|
classify: () => classify,
|
|
122
132
|
classifyStatement: () => classifyStatement,
|
|
133
|
+
compareRules: () => compareRules,
|
|
123
134
|
compileExpr: () => compileExpr,
|
|
124
135
|
compileGuard: () => compileGuard,
|
|
125
136
|
compileHumanContract: () => compileHumanContract,
|
|
126
137
|
compilePlainContract: () => compilePlainContract,
|
|
127
138
|
compileSource: () => compileSource,
|
|
139
|
+
completenessOf: () => completenessOf,
|
|
128
140
|
comprehensionLevel: () => comprehensionLevel,
|
|
129
141
|
comprehensionReport: () => comprehensionReport,
|
|
142
|
+
conditionText: () => conditionText,
|
|
130
143
|
confidenceFromClassification: () => confidenceFromClassification,
|
|
131
144
|
contradictionsView: () => contradictionsView,
|
|
132
145
|
coverageView: () => coverageView,
|
|
133
146
|
detectLanguage: () => detectLanguage,
|
|
134
147
|
diffGraphs: () => diffGraphs,
|
|
148
|
+
displayLabel: () => displayLabel,
|
|
135
149
|
draftIntent: () => draftIntent,
|
|
136
150
|
editStep: () => editStep,
|
|
137
151
|
evalExpr: () => evalExpr,
|
|
138
152
|
evaluateDecision: () => evaluateDecision,
|
|
139
153
|
expandNode: () => expandNode,
|
|
140
154
|
explainPlain: () => explainPlain,
|
|
155
|
+
flowOf: () => flowOf,
|
|
141
156
|
gapsView: () => gapsView,
|
|
157
|
+
getCodeActions: () => getCodeActions,
|
|
158
|
+
getCompletions: () => getCompletions,
|
|
159
|
+
getHover: () => getHover,
|
|
142
160
|
graphToIR: () => graphToIR,
|
|
143
161
|
graphToSource: () => graphToSource,
|
|
144
162
|
groupByFile: () => groupByFile,
|
|
@@ -158,10 +176,12 @@ __export(core_exports, {
|
|
|
158
176
|
makeEvent: () => makeEvent,
|
|
159
177
|
makeScope: () => makeScope,
|
|
160
178
|
mergeGraphs: () => mergeGraphs,
|
|
179
|
+
modelText: () => modelText,
|
|
161
180
|
normalizeSeeds: () => normalizeSeeds,
|
|
162
181
|
parseIntent: () => parseIntent,
|
|
163
182
|
parsePlainContract: () => parsePlainContract,
|
|
164
183
|
parseToStructured: () => parseToStructured,
|
|
184
|
+
plainFromReading: () => plainFromReading,
|
|
165
185
|
plainToThunder: () => plainToThunder,
|
|
166
186
|
previewHumanContract: () => previewHumanContract,
|
|
167
187
|
previewPlainContract: () => previewPlainContract,
|
|
@@ -178,14 +198,17 @@ __export(core_exports, {
|
|
|
178
198
|
renderMermaid: () => renderMermaid,
|
|
179
199
|
renderPlainContract: () => renderPlainContract,
|
|
180
200
|
renderReviewBrief: () => renderReviewBrief,
|
|
201
|
+
renderSame: () => renderSame,
|
|
181
202
|
renderTestplan: () => renderTestplan,
|
|
182
203
|
replaceSpan: () => replaceSpan,
|
|
183
204
|
resolveObligations: () => resolveObligations,
|
|
184
205
|
reviewAtlasExitCode: () => reviewAtlasExitCode,
|
|
185
206
|
risksView: () => risksView,
|
|
207
|
+
ruleFlow: () => ruleFlow,
|
|
186
208
|
ruleNamespace: () => ruleNamespace,
|
|
187
209
|
ruleParts: () => ruleParts,
|
|
188
210
|
runTests: () => runTests,
|
|
211
|
+
sameMeaning: () => sameMeaning,
|
|
189
212
|
scanIntent: () => scanIntent,
|
|
190
213
|
scanProject: () => scanProject,
|
|
191
214
|
searchAtlas: () => searchAtlas,
|
|
@@ -199,8 +222,14 @@ __export(core_exports, {
|
|
|
199
222
|
slug: () => slug,
|
|
200
223
|
spanRange: () => spanRange,
|
|
201
224
|
spanText: () => spanText,
|
|
225
|
+
stepDoes: () => stepDoes,
|
|
202
226
|
styleDiagnostics: () => styleDiagnostics,
|
|
203
227
|
subjectName: () => subjectName,
|
|
228
|
+
thunderModel: () => thunderModel,
|
|
229
|
+
thunderText: () => thunderText,
|
|
230
|
+
thunderTokens: () => thunderTokens,
|
|
231
|
+
thunderizeFile: () => thunderizeFile,
|
|
232
|
+
thunderizeFiles: () => thunderizeFiles,
|
|
204
233
|
toCSharp: () => toCSharp,
|
|
205
234
|
toCss: () => toCss,
|
|
206
235
|
toDesignTokens: () => toDesignTokens,
|
|
@@ -216,6 +245,8 @@ __export(core_exports, {
|
|
|
216
245
|
unverifiedView: () => unverifiedView,
|
|
217
246
|
validateIR: () => validateIR,
|
|
218
247
|
validateProof: () => validateProof,
|
|
248
|
+
visualFor: () => visualFor,
|
|
249
|
+
visualForStep: () => visualForStep,
|
|
219
250
|
writeRule: () => writeRule
|
|
220
251
|
});
|
|
221
252
|
module.exports = __toCommonJS(core_exports);
|
|
@@ -958,14 +989,14 @@ function parseIntent(source) {
|
|
|
958
989
|
break;
|
|
959
990
|
// ── System profile ──
|
|
960
991
|
case "capability": {
|
|
961
|
-
const
|
|
992
|
+
const cap2 = { name: arg, description: null, implements: [], line: node2.line };
|
|
962
993
|
for (const c of kids(node2)) {
|
|
963
994
|
const k = firstWord(c.text);
|
|
964
995
|
const a = rest(c.text);
|
|
965
|
-
if (k === "description")
|
|
966
|
-
else if (k === "implements")
|
|
996
|
+
if (k === "description") cap2.description = stripQuotes(a || leafItems(c).join(" "));
|
|
997
|
+
else if (k === "implements") cap2.implements.push(...a ? [a] : leafItems(c));
|
|
967
998
|
}
|
|
968
|
-
ast.capabilities.push(
|
|
999
|
+
ast.capabilities.push(cap2);
|
|
969
1000
|
break;
|
|
970
1001
|
}
|
|
971
1002
|
case "interface": {
|
|
@@ -1884,8 +1915,8 @@ function readUnknowns(ast, source) {
|
|
|
1884
1915
|
}
|
|
1885
1916
|
function previewHumanContract(source) {
|
|
1886
1917
|
const first = source.split(/\r?\n/).find((l) => l.trim() && !l.trim().startsWith("#"))?.trim() ?? "";
|
|
1887
|
-
const
|
|
1888
|
-
const canonicalSource =
|
|
1918
|
+
const compact2 = first.startsWith("contract ");
|
|
1919
|
+
const canonicalSource = compact2 ? compileHumanContract(source) : source;
|
|
1889
1920
|
const ast = parseIntent(canonicalSource);
|
|
1890
1921
|
const tests = runTests(ast);
|
|
1891
1922
|
const declared = (ast.tests ?? []).flatMap((t) => t.cases);
|
|
@@ -1894,7 +1925,7 @@ function previewHumanContract(source) {
|
|
|
1894
1925
|
const report = {
|
|
1895
1926
|
schema: "thunder-human-preview-v1",
|
|
1896
1927
|
experimental: true,
|
|
1897
|
-
origin: ast.lift?.inferred ? "inferred-code" :
|
|
1928
|
+
origin: ast.lift?.inferred ? "inferred-code" : compact2 ? "human-v1" : "thunderlang",
|
|
1898
1929
|
mission: ast.mission,
|
|
1899
1930
|
purpose: ast.goal,
|
|
1900
1931
|
canonicalSource,
|
|
@@ -1979,10 +2010,45 @@ var KNOWN_CALLS = [
|
|
|
1979
2010
|
{ re: /^(?:events?|bus|publisher|emitter|queue)\.(?:publish|emit|send|enqueue|push)$/i, say: () => "Announces an event" },
|
|
1980
2011
|
{ re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf)\b/i, say: () => "Writes a log or message" }
|
|
1981
2012
|
];
|
|
2013
|
+
var possessiveWords = (path) => {
|
|
2014
|
+
const parts = String(path).replace(/^\$/, "").replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, ".$1").split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x));
|
|
2015
|
+
return parts.length > 1 ? `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}` : words2(parts[0] || path);
|
|
2016
|
+
};
|
|
2017
|
+
var plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => v.length > 1 && v === v.toUpperCase() ? words2(v) : m);
|
|
1982
2018
|
function sayCodeCondition(cond) {
|
|
1983
|
-
let c = String(cond).trim().replace(/\s*(\{|:|then|do)\s*$/, "").trim();
|
|
2019
|
+
let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, "").trim();
|
|
1984
2020
|
while (c.startsWith("(") && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
|
|
1985
|
-
|
|
2021
|
+
const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
|
|
2022
|
+
const plural2 = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
|
|
2023
|
+
if (prop && plural2(words2(prop[3]), !!prop[4])) return `${words2(prop[2])} ${prop[1] ? "has no" : "has"} ${words2(prop[3])}`;
|
|
2024
|
+
const yesNo = (w, call2) => /^(is|has|can|should|was) /.test(w) || !call2 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
|
|
2025
|
+
if (prop && yesNo(words2(prop[3]), !!prop[4])) {
|
|
2026
|
+
const neg = !!prop[1];
|
|
2027
|
+
const w = words2(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
|
|
2028
|
+
const verb = /^(is|was) /.test(w) ? w.replace(/^(is|was) /, neg ? "$1 not " : "$1 ") : /^(has|can|should) /.test(w) ? (neg ? `does not ${w.replace(/^has /, "have ")}` : w).replace(/^does not can /, "cannot ").replace(/^does not should /, "should not ") : `is ${neg ? "not " : ""}${w}`;
|
|
2029
|
+
return `${words2(prop[2])} ${verb}`;
|
|
2030
|
+
}
|
|
2031
|
+
let pred;
|
|
2032
|
+
if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words2(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words2(pred[3])}`;
|
|
2033
|
+
c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`).replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
|
|
2034
|
+
c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
|
|
2035
|
+
let call;
|
|
2036
|
+
if (call = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) {
|
|
2037
|
+
const neg = !!call[1] !== (call[2] === "isset");
|
|
2038
|
+
const what = possessiveWords(call[3]);
|
|
2039
|
+
return call[2] === "isset" || call[2] === "is_null" ? `${what} is ${call[2] === "isset" === !call[1] ? "" : "not "}set` : `${what} is ${neg ? "not " : ""}empty`;
|
|
2040
|
+
}
|
|
2041
|
+
if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
|
|
2042
|
+
const w = words2(call[2]);
|
|
2043
|
+
return call[1] ? `not: ${w}` : w;
|
|
2044
|
+
}
|
|
2045
|
+
const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
|
|
2046
|
+
if (bare && !/^(true|false|True|False|None|null|nil)$/.test(bare[2])) {
|
|
2047
|
+
const parts = bare[2].split(".");
|
|
2048
|
+
const what = parts.length > 1 ? `the ${words2(parts[0])}'s ${words2(parts[1])}` : words2(parts[0]);
|
|
2049
|
+
return `${what} is ${bare[1] ? "not " : ""}set`;
|
|
2050
|
+
}
|
|
2051
|
+
return clip(c.replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, " is empty").replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, " is not empty").replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, " is set").replace(/\bis not None\b/g, "is set").replace(/\bis None\b/g, "is empty").replace(/\s*(===|==)\s*/g, " is ").replace(/\s*(!==|!=)\s*/g, " is not ").replace(/\s*&&\s*/g, " and ").replace(/\s*\|\|\s*/g, " or ").replace(/\s+not\s+in\s+/g, " is not in ").replace(/(?<!\bis(?: not)?)\s+in\s+(?=[\w$])/g, " is in ").replace(/\s+<=\s+/g, " is at most ").replace(/\s+>=\s+/g, " is at least ").replace(/\s+<\s+/g, " is less than ").replace(/(?<![-=])\s+>\s+/g, " is more than ").replace(/(^|[\s(])!(?=[\w(])/g, "$1not ").replace(/\s+/g, " "), 70);
|
|
1986
2052
|
}
|
|
1987
2053
|
function matchingClose(str, open) {
|
|
1988
2054
|
let depth = 0;
|
|
@@ -1994,12 +2060,12 @@ function matchingClose(str, open) {
|
|
|
1994
2060
|
}
|
|
1995
2061
|
var lastWords = (path) => words2(String(path).split(".").pop());
|
|
1996
2062
|
function targetWords(path) {
|
|
1997
|
-
const parts = String(path).replace(
|
|
2063
|
+
const parts = String(path).replace(/^[@$]+/, "").replace(/#/g, "").replace(/\[.*$/, "").split(".").filter((p) => !/^(this|self)$/.test(p));
|
|
1998
2064
|
if (parts.length <= 1) return words2(parts[0] || path);
|
|
1999
|
-
return
|
|
2065
|
+
return `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}`;
|
|
2000
2066
|
}
|
|
2001
2067
|
function callee(text) {
|
|
2002
|
-
const m = String(text).match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
|
|
2068
|
+
const m = String(text).replace(/\[[^\]]*\]/g, "").match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
|
|
2003
2069
|
return m ? m[1].replace(/<[^()]*?>/g, "").replace(/\(\)/g, "").replace(/::|->/g, ".").replace(/#/g, "") : null;
|
|
2004
2070
|
}
|
|
2005
2071
|
function sayCall(name, args) {
|
|
@@ -2015,7 +2081,12 @@ function firstArgs(text) {
|
|
|
2015
2081
|
return open >= 0 ? text.slice(open + 1, open + 120) : "";
|
|
2016
2082
|
}
|
|
2017
2083
|
function sayValue(expr) {
|
|
2018
|
-
|
|
2084
|
+
if (/^[A-Z][A-Za-z0-9]*\.[A-Z][A-Z0-9_]+$/.test(stripTail(expr))) return plainEnums(stripTail(expr));
|
|
2085
|
+
const e = stripTail(expr).replace(/\s+as\s+[\w.<>\[\]|, ]+$/, "");
|
|
2086
|
+
const py = sayPython(e);
|
|
2087
|
+
if (py) return py;
|
|
2088
|
+
const common = sayCommon(e);
|
|
2089
|
+
if (common) return common;
|
|
2019
2090
|
if (/^["'`].*["'`]$/.test(e)) return `"${clip(e.slice(1, -1), 40)}"`;
|
|
2020
2091
|
if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
|
|
2021
2092
|
const c = callee(e);
|
|
@@ -2023,9 +2094,77 @@ function sayValue(expr) {
|
|
|
2023
2094
|
if (/^new\s/.test(e)) return `a new ${c.split(".").pop()}`;
|
|
2024
2095
|
return `the result of ${lastWords(c)}`;
|
|
2025
2096
|
}
|
|
2026
|
-
if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words2(e.split(".").pop());
|
|
2097
|
+
if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words2(e.replace(/^\$/, "").split(".").pop());
|
|
2098
|
+
if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
|
|
2099
|
+
return null;
|
|
2100
|
+
}
|
|
2101
|
+
var PY_SUMMARY = [
|
|
2102
|
+
{ re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ""} matches` },
|
|
2103
|
+
{ re: /^all$/, say: (src, cond) => `whether every item in ${src}${cond ? ` where ${cond}` : ""} matches` },
|
|
2104
|
+
{ re: /^sum$/, say: (src) => `a total over ${src}` },
|
|
2105
|
+
{ re: /^min$/, say: (src) => `the smallest in ${src}` },
|
|
2106
|
+
{ re: /^max$/, say: (src) => `the largest in ${src}` },
|
|
2107
|
+
{ re: /^(?:sorted)$/, say: (src) => `${src}, sorted` }
|
|
2108
|
+
];
|
|
2109
|
+
var lastSeg = (x) => words2(String(x).trim().replace(/\(\)$/, "").split(".").pop());
|
|
2110
|
+
function sayPython(value) {
|
|
2111
|
+
const e = String(value).trim();
|
|
2112
|
+
let m = e.match(/^\[\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\]$/);
|
|
2113
|
+
if (m) {
|
|
2114
|
+
const [, expr, v, src, cond] = m;
|
|
2115
|
+
const vars = v.replace(/[()]/g, "").split(/\s*,\s*/);
|
|
2116
|
+
const bareCond = cond && cond.replace(new RegExp(`\\b(?:${vars.join("|")})\\.`, "g"), "");
|
|
2117
|
+
const condSaid = cond ? /^\w+$/.test(bareCond) ? words2(bareCond) : sayCodeCondition(bareCond) : null;
|
|
2118
|
+
if (vars.includes(expr.trim())) return condSaid ? `the items in ${lastSeg(src)} where ${condSaid}` : `the items in ${lastSeg(src)}`;
|
|
2119
|
+
return `one ${lastSeg(expr.replace(/\(.*$/, ""))} for each item in ${lastSeg(src)}${condSaid ? ` where ${condSaid}` : ""}`;
|
|
2120
|
+
}
|
|
2121
|
+
if (m = e.match(/^\{\s*(.+?)\s*:\s*.+?\s+for\s+[\w, ()]+?\s+in\s+(.+?)(?:\s+if\s+.+?)?\s*\}$/)) return `a lookup by ${lastSeg(m[1])} built from ${lastSeg(m[2])}`;
|
|
2122
|
+
if (m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) return `how many ${lastSeg(m[1])}`;
|
|
2123
|
+
if (m = e.match(/^(\w+)\(\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\)$/)) {
|
|
2124
|
+
const hit = PY_SUMMARY.find((k) => k.re.test(m[1]));
|
|
2125
|
+
if (hit) {
|
|
2126
|
+
const vars = m[3].replace(/[()]/g, "").split(/\s*,\s*/);
|
|
2127
|
+
const condSaid = m[5] ? sayCodeCondition(m[5].replace(new RegExp(`\\b(?:${vars.join("|")})\\.`, "g"), "")) : null;
|
|
2128
|
+
return hit.say(lastSeg(m[4]), condSaid);
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
if (m = e.match(/^(any|all|sum|min|max|sorted)\(\s*([\w.]+)\s*\)$/)) return PY_SUMMARY.find((k) => k.re.test(m[1])).say(lastSeg(m[2]));
|
|
2027
2132
|
return null;
|
|
2028
2133
|
}
|
|
2134
|
+
function sayCommon(value) {
|
|
2135
|
+
const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, "");
|
|
2136
|
+
let m;
|
|
2137
|
+
const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
|
|
2138
|
+
if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
|
|
2139
|
+
if (m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
|
|
2140
|
+
if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
|
|
2141
|
+
if (m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/)) return `a new ${m[1]}`;
|
|
2142
|
+
if (m = e.match(/^&([A-Z]\w*)$/)) return `a new ${m[1]}`;
|
|
2143
|
+
if (m = e.match(/^[\w.]+\.(?:get|get_or_404|find|Find|findById|find_by_id)\(\s*([A-Z]\w*)\s*,\s*([\w.]+)\s*\)$/)) return `the ${m[1]} with ${lastSeg(m[2])}`;
|
|
2144
|
+
if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return `the ${lastSeg(m[2])} entry in ${lastSeg(m[1])}`;
|
|
2145
|
+
if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e)) return "text built from its parts";
|
|
2146
|
+
if (m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/)) return e.split(/\s*,\s*/).map(lastSeg).join(" and ");
|
|
2147
|
+
if (m = e.match(/^make\(\s*(\[\]|map\[)/)) return m[1] === "[]" ? "an empty list" : "an empty lookup table";
|
|
2148
|
+
if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return "text built from its parts";
|
|
2149
|
+
if (m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]/)) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
2150
|
+
if (m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/)) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
2151
|
+
if (m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/)) return `${lastSeg(m[1])} split at "${m[2]}"`;
|
|
2152
|
+
if (m = e.match(/^@?([\w.]+?)(?:\.copy|\.clone|\.Clone|\.dup)(?:\(\))?$/)) return `a copy of ${lastSeg(m[1])}`;
|
|
2153
|
+
if ((m = e.match(/^(?:str|String|string)\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:toString|to_s|ToString)\(\)$/))) return `${lastSeg(m[1])} as text`;
|
|
2154
|
+
if (m = e.match(/^(?:int|float|Number|parseInt|parseFloat|strconv\.Atoi|Integer\.parseInt|int\.Parse)\(\s*([\w.]+)/)) return `${lastSeg(m[1])} as a number`;
|
|
2155
|
+
if (m = e.match(/^(?:JSON\.parse|json\.loads|json\.load|JsonSerializer\.Deserialize\w*)\(\s*([\w.]+)/)) return `${lastSeg(m[1])} read as JSON`;
|
|
2156
|
+
if (m = e.match(/^(?:JSON\.stringify|json\.dumps|JsonSerializer\.Serialize)\(\s*([\w.]+)/)) return `${lastSeg(m[1])} written as JSON`;
|
|
2157
|
+
if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)\b/.test(e)) return "an empty lookup table";
|
|
2158
|
+
if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)\b/.test(e)) return "an empty list";
|
|
2159
|
+
if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
|
|
2160
|
+
return null;
|
|
2161
|
+
}
|
|
2162
|
+
var LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
|
|
2163
|
+
function sayWhether(expr) {
|
|
2164
|
+
const e = String(expr).trim();
|
|
2165
|
+
if (!LOGIC.test(e) || /=>|\blambda\b|\?.*:/.test(e) || e.length > 90) return null;
|
|
2166
|
+
return `whether ${sayCodeCondition(e)}`;
|
|
2167
|
+
}
|
|
2029
2168
|
var CHAIN = [
|
|
2030
2169
|
{ re: /\.(?:map|Select|flatMap|SelectMany|map_values|collect\{)\s*[({]/, say: (src) => `one for each item in ${src}` },
|
|
2031
2170
|
{ re: /\.(?:filter|Where|filter_map|select|reject|grep)\s*[({]/, say: (src) => `the items in ${src} that match` },
|
|
@@ -2048,14 +2187,27 @@ function sayChain(value) {
|
|
|
2048
2187
|
}
|
|
2049
2188
|
function classifyStatement(raw, { inner = 0 } = {}) {
|
|
2050
2189
|
const text = String(raw).trim();
|
|
2051
|
-
const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.");
|
|
2190
|
+
const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
|
|
2052
2191
|
const code = clip(head, 90);
|
|
2053
2192
|
let m;
|
|
2054
2193
|
const innerNote = inner ? ` (${inner} step${inner === 1 ? "" : "s"} inside)` : "";
|
|
2194
|
+
let inl;
|
|
2195
|
+
if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
|
|
2196
|
+
return { kind: "branch", says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
|
|
2197
|
+
}
|
|
2198
|
+
if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
|
|
2199
|
+
const cond = sayCodeCondition(inl[3]);
|
|
2200
|
+
return { kind: "branch", says: inl[2] === "unless" ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === "unless", code, inline: inl[1] };
|
|
2201
|
+
}
|
|
2202
|
+
if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words2(inl[1])} yet`, code };
|
|
2203
|
+
if (inl = head.match(/^([\w$.]+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::\s*[^=]+)?=>|[\w$]+\s*=>)/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
|
|
2204
|
+
if (m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) return { kind: "check", says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, "")) ? words2(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
|
|
2205
|
+
if (/^default\s*(?::|->)/.test(head)) return { kind: "check", says: "Otherwise", code, caseLabel: true };
|
|
2055
2206
|
if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
|
|
2056
2207
|
const name = m?.[1] ? m[1].split(".").pop() : null;
|
|
2057
2208
|
const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
|
|
2058
|
-
|
|
2209
|
+
const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
|
|
2210
|
+
return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
|
|
2059
2211
|
}
|
|
2060
2212
|
if (m = head.match(/^return\b\s*(.*)$/)) {
|
|
2061
2213
|
const expr = stripTail(m[1]);
|
|
@@ -2071,12 +2223,19 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2071
2223
|
}
|
|
2072
2224
|
const chain = sayChain(expr);
|
|
2073
2225
|
if (chain) return { kind: "return", says: `Returns ${chain}`, code };
|
|
2074
|
-
if (
|
|
2226
|
+
if (/^\(?\s*\{/.test(expr)) return { kind: "return", says: "Returns an object", code };
|
|
2075
2227
|
if (/^\(?\s*</.test(expr)) return { kind: "return", says: "Returns what to show on screen", code };
|
|
2076
|
-
const v = sayValue(expr);
|
|
2228
|
+
const v = sayValue(expr) || sayWhether(expr);
|
|
2077
2229
|
return { kind: "return", says: v ? `Returns ${v}` : "Returns a computed value", code, ...v ? {} : { value: clip(expr, 60) } };
|
|
2078
2230
|
}
|
|
2079
|
-
if (m = head.match(/^for\s*\(?\s*(?:
|
|
2231
|
+
if (m = head.match(/^for\b\s*\(?\s*(?:(?:var|let|const|int|long|size_t|auto|\$)\s*)?\$?(\w+)\s*:?=\s*([^;]+?)\s*;\s*([^;]*?)\s*;\s*[^)]*?\)?\s*\{?\s*$/)) {
|
|
2232
|
+
return { kind: "loop", says: `Counts ${words2(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
|
|
2233
|
+
}
|
|
2234
|
+
if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val)?\s*[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
|
|
2235
|
+
const src = stripTail(m[3]).replace(/\($/, "()").replace(/^Object\.entries\((.+)\)$/, "$1").replace(/\.(?:items|entries)\(\)$/, "");
|
|
2236
|
+
return { kind: "loop", says: `For each ${words2(m[1])} and ${words2(m[2])} in ${words2(src.split(".").pop())}${innerNote}`, code };
|
|
2237
|
+
}
|
|
2238
|
+
if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
|
|
2080
2239
|
return { kind: "loop", says: `For each ${words2(m[1].split(",").pop().trim())} in ${words2(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
|
|
2081
2240
|
}
|
|
2082
2241
|
if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words2(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
|
|
@@ -2084,7 +2243,12 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2084
2243
|
if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
|
|
2085
2244
|
if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
|
|
2086
2245
|
if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words2(m[1].split(".").pop())}${innerNote}`, code };
|
|
2087
|
-
if (m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${
|
|
2246
|
+
if (m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
|
|
2247
|
+
if (m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*([\w.]+)\(.*\);\s*err\s*!=\s*nil\s*\{?\s*$/)) return { kind: "branch", says: `If ${lastWords(m[1])} fails${innerNote}`, code };
|
|
2248
|
+
if (m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/)) {
|
|
2249
|
+
const cond = sayCodeCondition(m[1]);
|
|
2250
|
+
return { kind: "branch", says: `If ${cond}${innerNote}`, cond: m[1], code };
|
|
2251
|
+
}
|
|
2088
2252
|
if (m = head.match(/^(?:if|elif|else\s+if|unless|when)\b\s*(.*?)\s*(?:\{|:|then)?\s*$/)) {
|
|
2089
2253
|
const cond = sayCodeCondition(m[1]);
|
|
2090
2254
|
return { kind: "branch", says: `If ${/^unless\b/.test(head) ? "not: " : ""}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, "$1"), code, negate: /^unless\b/.test(head) };
|
|
@@ -2126,6 +2290,8 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2126
2290
|
const value = stripTail(m[3]);
|
|
2127
2291
|
const target = words2(m[2]);
|
|
2128
2292
|
const c2 = value ? callee(value) : null;
|
|
2293
|
+
const everyday = value ? sayPython(value) || sayCommon(value) : null;
|
|
2294
|
+
if (everyday) return { kind: "set", says: `Sets ${target} to ${everyday}`, code };
|
|
2129
2295
|
if (c2) {
|
|
2130
2296
|
const known = sayCall(c2, firstArgs(value));
|
|
2131
2297
|
if (known) return { kind: "call", says: `${known}, keeping the result as ${target}`, code, callee: c2 };
|
|
@@ -2135,11 +2301,17 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2135
2301
|
const v = value ? sayValue(value) : null;
|
|
2136
2302
|
return { kind: "set", says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
2137
2303
|
}
|
|
2138
|
-
if ((m = head.match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
|
|
2139
|
-
const target = m[1].split(/\s*,\s*/).map(targetWords).join(", ");
|
|
2304
|
+
if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, "").match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
|
|
2305
|
+
const target = m[1].split(/\s*,\s*/).filter((t) => t !== "_").map(targetWords).join(", ") || targetWords(m[1]);
|
|
2140
2306
|
const value = stripTail(m[3]);
|
|
2141
|
-
|
|
2307
|
+
if (m[2] === "=" && !/[(?]/.test(value.replace(/^\(|\)$/g, "")) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, ".")) && !/=>/.test(value)) return { kind: "set", says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
|
|
2308
|
+
if (m[2] === "=" && /^[A-Za-z_]\w*$/.test(value) && m[1].split(".").pop() === value && /^(self|this)\./.test(m[1])) return { kind: "set", says: `Keeps the ${words2(value)} it is given`, code };
|
|
2309
|
+
const chain = value ? sayPython(value) || sayChain(value) : null;
|
|
2142
2310
|
if (chain) return { kind: "set", says: `Works out ${target}: ${chain}`, code };
|
|
2311
|
+
const common = value ? sayCommon(m[3].trim().replace(/;$/, "")) || sayCommon(value) : null;
|
|
2312
|
+
if (common) return { kind: "set", says: `Sets ${target} to ${common}`, code };
|
|
2313
|
+
const keyed = m[2] === "=" && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
|
|
2314
|
+
if (keyed) return { kind: "set", says: `Records ${words2(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
|
|
2143
2315
|
const c2 = callee(value);
|
|
2144
2316
|
if (c2) {
|
|
2145
2317
|
const known = sayCall(c2, firstArgs(value));
|
|
@@ -2148,10 +2320,25 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2148
2320
|
return { kind: "set", says: `Works out ${target} from ${lastWords(c2)}`, code, callee: c2 };
|
|
2149
2321
|
}
|
|
2150
2322
|
if (!value) return { kind: "set", says: `Works out ${target}`, code };
|
|
2151
|
-
if (m[2] === "+=" || m[2] === "-=")
|
|
2323
|
+
if (m[2] === "+=" || m[2] === "-=") {
|
|
2324
|
+
const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words2).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
|
|
2325
|
+
return { kind: "set", says: what ? `${m[2] === "+=" ? "Adds" : "Subtracts"} ${what}${m[2] === "+=" ? "to" : "from"} ${target}` : `${m[2] === "+=" ? "Adds to" : "Subtracts from"} ${target}`, code };
|
|
2326
|
+
}
|
|
2152
2327
|
const v = sayValue(value);
|
|
2153
2328
|
return { kind: "set", says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
2154
2329
|
}
|
|
2330
|
+
if (m = head.match(/^([\w$.]+)\.(?:set|Set|put|setdefault|Add)\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,/)) return { kind: "call", says: `Sets "${m[2]}" on ${lastSeg(m[1])}`, code, callee: `${m[1]}.set` };
|
|
2331
|
+
if ((m = head.match(/^([\w$.]+)\.(?:remove|Remove|discard|delete|pop)\(\s*([\w$]+)\s*\)/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
|
|
2332
|
+
const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
|
|
2333
|
+
const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
|
|
2334
|
+
return { kind: "call", says: `Removes ${words2(m[2])} from ${where}`, code, callee: m[1] };
|
|
2335
|
+
}
|
|
2336
|
+
if ((m = head.match(/^([\w$.]+)\.(?:append|push|add|Add|insert|appendleft|extend)\(\s*([\w$.]*)\s*\)?/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
|
|
2337
|
+
const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
|
|
2338
|
+
const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
|
|
2339
|
+
const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf("(") + 1))?.[1];
|
|
2340
|
+
return { kind: "call", says: added ? `Adds a new ${words2(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words2(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
|
|
2341
|
+
}
|
|
2155
2342
|
const c = callee(head);
|
|
2156
2343
|
if (c) {
|
|
2157
2344
|
const known = sayCall(c, firstArgs(head));
|
|
@@ -2160,61 +2347,175 @@ function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
2160
2347
|
if ((m = head.match(/^([a-z_][\w.]*[?!]?)\s+(?![=<>!+\-*/%]|and\b|or\b|if\b|unless\b)(.+)$/)) && !/^(?:if|for|while|return|else|elsif|when|case|def|class|module|end|not|const|let|var|val|new|await|typeof|delete|void|in|of|throw|import|export|from|as|is)$/.test(m[1])) {
|
|
2161
2348
|
if (/^assert/.test(m[1])) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
|
|
2162
2349
|
const known = sayCall(m[1], m[2]);
|
|
2163
|
-
|
|
2350
|
+
const named = /^[:'"]([\w ]+)['"]?/.exec(m[2].trim())?.[1];
|
|
2351
|
+
return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words2(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
|
|
2164
2352
|
}
|
|
2165
2353
|
return { kind: "other", says: clip(head, 70), code };
|
|
2166
2354
|
}
|
|
2167
2355
|
var spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...s.start != null && s.end != null ? { start: s.start, end: s.end } : {} });
|
|
2356
|
+
var BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
|
|
2357
|
+
var balanced = (x) => {
|
|
2358
|
+
let d = 0;
|
|
2359
|
+
for (const ch of x) {
|
|
2360
|
+
if (ch === "(") d++;
|
|
2361
|
+
else if (ch === ")" && --d < 0) return false;
|
|
2362
|
+
}
|
|
2363
|
+
return d === 0;
|
|
2364
|
+
};
|
|
2365
|
+
function asCall(list, i) {
|
|
2366
|
+
const st = list[i];
|
|
2367
|
+
if (st?.kind === "return" && BARE_CALL.test(st.code || "") && !/^(?:self|nil|true|false|null|none)$/i.test(st.code)) {
|
|
2368
|
+
list[i] = { ...st, kind: "call", says: `Calls ${lastWords(st.code)}`, callee: st.code };
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
var CLAUSE = /^(?:elif\b|elsif\b|else\s+if\b|else\b|except\b|catch\b|rescue\b|finally\b|ensure\b)/;
|
|
2372
|
+
function attachClause(step, clause) {
|
|
2373
|
+
const kw = clause.kind;
|
|
2374
|
+
const kids2 = stepsFrom(clause.children || []).steps;
|
|
2375
|
+
let target = step;
|
|
2376
|
+
while (target.otherwise?.length === 1 && target.otherwise[0].elseIf) target = target.otherwise[0];
|
|
2377
|
+
if (kw === "elif") {
|
|
2378
|
+
const head = clause.head.replace(/^(?:elif|elsif|else\s+if)\b/, "if");
|
|
2379
|
+
const branch = { ...classifyStatement(head), line: clause.line, span: { startLine: clause.line, endLine: clause.endLine ?? clause.line }, elseIf: true };
|
|
2380
|
+
if (kids2.length) branch.children = kids2;
|
|
2381
|
+
target.otherwise = [branch];
|
|
2382
|
+
} else if (kw === "else") {
|
|
2383
|
+
target.otherwise = kids2;
|
|
2384
|
+
target.otherwiseLine = clause.line;
|
|
2385
|
+
} else if (kw === "catch") {
|
|
2386
|
+
const what = (clause.head.replace(/\\/g, ".").replace(/\(\s*\./, "(").match(/^(?:except|catch|rescue)\s*\(?\s*(?:[\w.]+\s+)?\(?\.?([A-Z][\w.:]*(?:\s*[,|]\s*\.?[A-Z][\w.:]*)*)/) || [])[1]?.replace(/::/g, ".");
|
|
2387
|
+
(step.handlers ||= []).push({ says: what ? `If ${what.split(/\s*[,|]\s*/).map((x) => x.split(".").pop()).join(" or ")} goes wrong` : "If anything goes wrong", line: clause.line, steps: kids2 });
|
|
2388
|
+
} else if (kw === "finally") {
|
|
2389
|
+
for (let i = 0; i < kids2.length; i++) asCall(kids2, i);
|
|
2390
|
+
step.always = { line: clause.line, steps: kids2 };
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2168
2393
|
function stepsFrom(statements) {
|
|
2169
2394
|
const steps = [];
|
|
2170
2395
|
const skipped = [];
|
|
2396
|
+
let into = null, intoAlways = false;
|
|
2171
2397
|
for (const s of statements) {
|
|
2172
|
-
|
|
2398
|
+
const t0 = (s.text || "").trim();
|
|
2399
|
+
if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
|
|
2400
|
+
const st = stepsFrom([s]).steps;
|
|
2401
|
+
into.push(...st);
|
|
2402
|
+
for (let i = 0; i < into.length - (intoAlways ? 0 : 1); i++) asCall(into, i);
|
|
2403
|
+
continue;
|
|
2404
|
+
}
|
|
2405
|
+
if (CLAUSE.test(t0)) {
|
|
2406
|
+
const prev = steps[steps.length - 1];
|
|
2407
|
+
if (/^(?:rescue|ensure|except|finally)\b/.test(t0) && steps.length && !(prev && prev.kind === "try")) {
|
|
2408
|
+
const tried = steps.splice(0, steps.length);
|
|
2409
|
+
for (let i = 0; i < tried.length - 1; i++) asCall(tried, i);
|
|
2410
|
+
steps.push({ kind: "try", says: "Tries these steps and handles any error", code: "(the whole method)", line: tried[0].line, span: { startLine: tried[0].span.startLine, endLine: tried[tried.length - 1].span.endLine }, children: tried });
|
|
2411
|
+
}
|
|
2412
|
+
const prev2 = steps[steps.length - 1];
|
|
2413
|
+
if (prev2 && (prev2.kind === "branch" || prev2.kind === "try")) {
|
|
2414
|
+
const prev3 = prev2;
|
|
2415
|
+
const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? "elif" : /^else\b/.test(t0) ? "else" : /^(?:finally|ensure)\b/.test(t0) ? "finally" : "catch";
|
|
2416
|
+
attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: s.children || [] });
|
|
2417
|
+
intoAlways = kw === "finally";
|
|
2418
|
+
into = s.children?.length ? null : kw === "catch" ? prev3.handlers?.[prev3.handlers.length - 1]?.steps ?? null : kw === "finally" ? prev3.always?.steps ?? null : null;
|
|
2419
|
+
prev3.span = { ...prev3.span, endLine: Math.max(prev3.span.endLine, s.endLine ?? s.line) };
|
|
2420
|
+
continue;
|
|
2421
|
+
}
|
|
2173
2422
|
skipped.push(spanOf(s));
|
|
2174
2423
|
continue;
|
|
2175
2424
|
}
|
|
2176
|
-
if (!
|
|
2177
|
-
|
|
2178
|
-
|
|
2425
|
+
if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) {
|
|
2426
|
+
if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s));
|
|
2427
|
+
continue;
|
|
2428
|
+
}
|
|
2429
|
+
if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) {
|
|
2179
2430
|
skipped.push(spanOf(s));
|
|
2180
2431
|
continue;
|
|
2181
2432
|
}
|
|
2182
|
-
if (/^[)\]}]+[):;,]*$/.test(
|
|
2433
|
+
if (/^[)\]}]+[):;,]*$/.test(t0) || /^\.\.\.$/.test(t0) || /^\.[A-Za-z_]/.test(t0) || /^@\w+(?:\(.*\))?$/.test(t0) || /^#?\[[\w:]+(?:\(.*\))?\]$/.test(t0) || /^:(?:param|rtype|return|raises|type)\b/.test(t0)) {
|
|
2183
2434
|
skipped.push(spanOf(s));
|
|
2184
2435
|
continue;
|
|
2185
2436
|
}
|
|
2186
2437
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
2187
2438
|
if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
|
|
2188
|
-
const kids2 = stepsFrom(s.children
|
|
2439
|
+
const kids2 = stepsFrom(s.children).steps;
|
|
2189
2440
|
if (kids2.length) {
|
|
2190
2441
|
step.children = kids2;
|
|
2191
2442
|
step.says = step.says.replace(/ \(\d+ steps? inside\)$/, "");
|
|
2192
2443
|
}
|
|
2193
2444
|
}
|
|
2445
|
+
if (step.inline && !step.children) {
|
|
2446
|
+
const kid = classifyStatement(step.inline);
|
|
2447
|
+
step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
|
|
2448
|
+
delete step.inline;
|
|
2449
|
+
} else delete step.inline;
|
|
2450
|
+
for (const c of s.clauses || []) attachClause(step, c);
|
|
2194
2451
|
steps.push(step);
|
|
2195
2452
|
}
|
|
2453
|
+
for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
|
|
2196
2454
|
const more = Math.max(0, steps.length - MAX_STEPS);
|
|
2197
|
-
|
|
2455
|
+
for (const st of steps) if (restates(st)) st.restates = true;
|
|
2456
|
+
return { steps, more, skipped, readable: readableShare(steps) };
|
|
2457
|
+
}
|
|
2458
|
+
var GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec|make|build|create|new|init|load|fetch|parse|convert|to|from|str|int|float|bool|list|dict|set|tuple|len|any|all|map|filter|next|iter|super|format|join|split|strip|copy|update|value|values|items|keys)$/;
|
|
2459
|
+
function restates(st) {
|
|
2460
|
+
const s = st.says || "";
|
|
2461
|
+
if (st.kind === "other") return false;
|
|
2462
|
+
if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
|
|
2463
|
+
const same = s.match(/^Works out (.+) from (.+)$/);
|
|
2464
|
+
if (same && same[1].trim() === same[2].trim()) return true;
|
|
2465
|
+
if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
|
|
2466
|
+
const via = s.match(/(?:the result of|from|^Calls) ([\w ]+?)$/);
|
|
2467
|
+
if (via && GENERIC_CALLS.test(via[1].trim())) return true;
|
|
2468
|
+
return false;
|
|
2198
2469
|
}
|
|
2470
|
+
var readableShare = (steps) => steps.length ? steps.filter((x) => x.kind !== "other" && !x.restates).length / steps.length : 0;
|
|
2471
|
+
var blockEnd = (text, open) => {
|
|
2472
|
+
let depth = 0;
|
|
2473
|
+
for (let i = open; i < text.length; i++) {
|
|
2474
|
+
const c = text[i];
|
|
2475
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
2476
|
+
for (i++; i < text.length && text[i] !== c; i++) if (text[i] === "\\") i++;
|
|
2477
|
+
continue;
|
|
2478
|
+
}
|
|
2479
|
+
if (c === "{") depth++;
|
|
2480
|
+
else if (c === "}" && --depth === 0) return i;
|
|
2481
|
+
}
|
|
2482
|
+
return -1;
|
|
2483
|
+
};
|
|
2199
2484
|
function braceStatements(stmts, split = null) {
|
|
2200
2485
|
return stmts.map((s) => {
|
|
2201
|
-
const
|
|
2202
|
-
|
|
2486
|
+
const text = s.text;
|
|
2487
|
+
const open = text.indexOf("{");
|
|
2488
|
+
const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
|
|
2489
|
+
const read = (o, e) => {
|
|
2490
|
+
const body = e > o ? text.slice(o + 1, e) : "";
|
|
2491
|
+
const base = s.start != null ? s.start + o + 1 : null;
|
|
2492
|
+
if (!body || !split) return [];
|
|
2493
|
+
const kids2 = split(body, lineAtPos(o + 1)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
|
|
2494
|
+
return braceStatements(kids2, split);
|
|
2495
|
+
};
|
|
2496
|
+
let children = [], inner = 0;
|
|
2497
|
+
const clauses = [];
|
|
2203
2498
|
if (open >= 0) {
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2499
|
+
const end = blockEnd(text, open);
|
|
2500
|
+
const body = end > open ? text.slice(open + 1, end) : "";
|
|
2501
|
+
inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
|
|
2502
|
+
children = read(open, end);
|
|
2503
|
+
let pos = end + 1;
|
|
2504
|
+
while (end >= 0) {
|
|
2505
|
+
const rest2 = text.slice(pos);
|
|
2506
|
+
const m = rest2.match(/^\s*(else\s+if\b|elseif\b|elsif\b|else\b|catch\b|rescue\b|finally\b|ensure\b)/);
|
|
2507
|
+
if (!m) break;
|
|
2508
|
+
const kw = m[1].replace(/\s+/g, " ");
|
|
2509
|
+
const o = text.indexOf("{", pos + m[0].length);
|
|
2510
|
+
if (o < 0) break;
|
|
2511
|
+
const e = blockEnd(text, o);
|
|
2512
|
+
const clauseHead = text.slice(pos + m[0].length - m[1].length, o).trim();
|
|
2513
|
+
clauses.push({ kind: /^(else if|elseif|elsif)$/.test(kw) ? "elif" : kw === "else" ? "else" : kw === "finally" || kw === "ensure" ? "finally" : "catch", head: clauseHead, line: lineAtPos(pos + rest2.indexOf(m[1])), children: read(o, e) });
|
|
2514
|
+
if (e < 0) break;
|
|
2515
|
+
pos = e + 1;
|
|
2211
2516
|
}
|
|
2212
|
-
body = end > open ? s.text.slice(open + 1, end) : "";
|
|
2213
2517
|
}
|
|
2214
|
-
|
|
2215
|
-
const base = s.start != null && open >= 0 ? s.start + open + 1 : null;
|
|
2216
|
-
const children = body && split ? split(body, s.line).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} })) : [];
|
|
2217
|
-
return { text: s.text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children };
|
|
2518
|
+
return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {} };
|
|
2218
2519
|
});
|
|
2219
2520
|
}
|
|
2220
2521
|
function indentStatements(body, { depthKey = "indent" } = {}) {
|
|
@@ -2247,24 +2548,11 @@ function indentStatements(body, { depthKey = "indent" } = {}) {
|
|
|
2247
2548
|
for (let i = 0; i < body.length; i++) {
|
|
2248
2549
|
const l = body[i];
|
|
2249
2550
|
if ((l[depthKey] ?? 0) !== base) continue;
|
|
2250
|
-
let
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
inner++;
|
|
2256
|
-
const d = body[k][depthKey] ?? 0;
|
|
2257
|
-
if (childDepth === null) childDepth = d;
|
|
2258
|
-
if (d === childDepth) children.push({ text: body[k].text, line: body[k].line });
|
|
2259
|
-
last = body[k].line;
|
|
2260
|
-
}
|
|
2261
|
-
children.forEach((c, n) => {
|
|
2262
|
-
const next = children[n + 1];
|
|
2263
|
-
const nextIdx = next ? body.findIndex((x) => x.line === next.line) : -1;
|
|
2264
|
-
const until = next ? body[nextIdx - 1]?.line ?? c.line : last;
|
|
2265
|
-
c.endLine = Math.max(c.line, until);
|
|
2266
|
-
});
|
|
2267
|
-
out.push({ text: l.text, line: l.line, endLine: last, inner, children });
|
|
2551
|
+
let k = i + 1;
|
|
2552
|
+
while (k < body.length && (body[k][depthKey] ?? 0) > base) k++;
|
|
2553
|
+
const block = body.slice(i + 1, k);
|
|
2554
|
+
const children = block.length ? indentStatements(block, { depthKey }) : [];
|
|
2555
|
+
out.push({ text: l.text, line: l.line, endLine: block.length ? block[block.length - 1].line : l.endLine ?? l.line, inner: block.length, children });
|
|
2268
2556
|
}
|
|
2269
2557
|
return out;
|
|
2270
2558
|
}
|
|
@@ -3179,7 +3467,7 @@ function notesSummary(ast) {
|
|
|
3179
3467
|
byLens
|
|
3180
3468
|
};
|
|
3181
3469
|
}
|
|
3182
|
-
var COMPILER_VERSION = "0.5.
|
|
3470
|
+
var COMPILER_VERSION = "0.5.5";
|
|
3183
3471
|
var PROOF_SCHEMA_VERSION = "0.1.0";
|
|
3184
3472
|
var SOURCE_PRODUCT = "skillstech-compiler";
|
|
3185
3473
|
function buildContractGraph(ast, generatedAt) {
|
|
@@ -4579,7 +4867,7 @@ function liftSource(source, { language = "typescript", file = "", seeds = void 0
|
|
|
4579
4867
|
}
|
|
4580
4868
|
const intentText = renderLiftedIntent(lifted);
|
|
4581
4869
|
const diagnostics = liftDiagnostics(lifted, codeFacts);
|
|
4582
|
-
const
|
|
4870
|
+
const summary2 = {
|
|
4583
4871
|
schemaVersion: IR_SCHEMA_VERSION,
|
|
4584
4872
|
sourceLanguage: codeFacts.sourceLanguage,
|
|
4585
4873
|
mission: lifted.mission,
|
|
@@ -4591,7 +4879,7 @@ function liftSource(source, { language = "typescript", file = "", seeds = void 0
|
|
|
4591
4879
|
tests: codeFacts.tests.length,
|
|
4592
4880
|
seeds: normSeeds.map((s) => s.nodeId)
|
|
4593
4881
|
};
|
|
4594
|
-
return { ok: true, codeFacts, lifted, intentText, diagnostics, summary, seeds: normSeeds };
|
|
4882
|
+
return { ok: true, codeFacts, lifted, intentText, diagnostics, summary: summary2, seeds: normSeeds };
|
|
4595
4883
|
}
|
|
4596
4884
|
|
|
4597
4885
|
// src/read.mjs
|
|
@@ -4612,7 +4900,27 @@ function detectLanguage(source, file = "") {
|
|
|
4612
4900
|
if (/:\s*(number|string|boolean)\b|\binterface\s+\w+|\bexport\s+(function|const)\b/.test(s)) return "typescript";
|
|
4613
4901
|
return "javascript";
|
|
4614
4902
|
}
|
|
4615
|
-
var
|
|
4903
|
+
var lineStarts = /* @__PURE__ */ new Map();
|
|
4904
|
+
function startsOf(src) {
|
|
4905
|
+
let starts = lineStarts.get(src);
|
|
4906
|
+
if (!starts) {
|
|
4907
|
+
starts = [0];
|
|
4908
|
+
for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
|
|
4909
|
+
if (lineStarts.size > 8) lineStarts.delete(lineStarts.keys().next().value);
|
|
4910
|
+
lineStarts.set(src, starts);
|
|
4911
|
+
}
|
|
4912
|
+
return starts;
|
|
4913
|
+
}
|
|
4914
|
+
var lineAt = (src, idx) => {
|
|
4915
|
+
const starts = startsOf(src);
|
|
4916
|
+
let lo = 0, hi = starts.length - 1;
|
|
4917
|
+
while (lo < hi) {
|
|
4918
|
+
const mid = lo + hi + 1 >> 1;
|
|
4919
|
+
if (starts[mid] <= idx) lo = mid;
|
|
4920
|
+
else hi = mid - 1;
|
|
4921
|
+
}
|
|
4922
|
+
return lo + 1;
|
|
4923
|
+
};
|
|
4616
4924
|
function matchClose(src, open) {
|
|
4617
4925
|
const pairs = { "{": "}", "(": ")", "[": "]" };
|
|
4618
4926
|
const stack = [pairs[src[open]]];
|
|
@@ -4671,6 +4979,7 @@ function skipString(src, i) {
|
|
|
4671
4979
|
}
|
|
4672
4980
|
var stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/.*$/gm, "$1");
|
|
4673
4981
|
function parseParams2(raw, language) {
|
|
4982
|
+
raw = String(raw).replace(/#\[[^\]]*\]\s*/g, "").replace(/\[\w+(?:\([^)]*\))?\]\s*/g, "");
|
|
4674
4983
|
const parts = [];
|
|
4675
4984
|
let depth = 0, cur = "";
|
|
4676
4985
|
for (const ch of raw) {
|
|
@@ -4713,6 +5022,37 @@ function parseParams2(raw, language) {
|
|
|
4713
5022
|
for (const g of pendingGo) out.push({ name: g, type: null });
|
|
4714
5023
|
return out;
|
|
4715
5024
|
}
|
|
5025
|
+
function balancedReturnHead(after) {
|
|
5026
|
+
const lead = after.match(/^\s*:/);
|
|
5027
|
+
if (!lead) return null;
|
|
5028
|
+
let i = lead[0].length, depth = 0;
|
|
5029
|
+
for (; i < after.length; i++) {
|
|
5030
|
+
const c = after[i];
|
|
5031
|
+
if (c === "=" && after[i + 1] === ">") {
|
|
5032
|
+
if (depth === 0) break;
|
|
5033
|
+
i++;
|
|
5034
|
+
continue;
|
|
5035
|
+
}
|
|
5036
|
+
if (c === "<" || c === "(" || c === "[") depth++;
|
|
5037
|
+
else if (c === ">" || c === ")" || c === "]") depth--;
|
|
5038
|
+
else if (c === "{") {
|
|
5039
|
+
if (depth === 0) break;
|
|
5040
|
+
depth++;
|
|
5041
|
+
} else if (c === "}") depth--;
|
|
5042
|
+
else if (c === ";" && depth === 0) break;
|
|
5043
|
+
else if (c === '"' || c === "'" || c === "`") {
|
|
5044
|
+
const q = c;
|
|
5045
|
+
i++;
|
|
5046
|
+
while (i < after.length && after[i] !== q) i++;
|
|
5047
|
+
}
|
|
5048
|
+
}
|
|
5049
|
+
const type = after.slice(lead[0].length, i).trim();
|
|
5050
|
+
const tail = after.slice(i).match(/^\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
|
|
5051
|
+
if (!type || !tail) return null;
|
|
5052
|
+
const whole = after.slice(0, i) + tail[0];
|
|
5053
|
+
const m = [whole, type, void 0, void 0, tail[1]];
|
|
5054
|
+
return m;
|
|
5055
|
+
}
|
|
4716
5056
|
function simpleType(t) {
|
|
4717
5057
|
if (!t) return null;
|
|
4718
5058
|
const s = String(t).trim().replace(/^&(mut\s+)?/, "");
|
|
@@ -4725,13 +5065,30 @@ function findFunctions(src, language) {
|
|
|
4725
5065
|
const fns = [];
|
|
4726
5066
|
if (language === "python") {
|
|
4727
5067
|
const lines = src.split("\n");
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
5068
|
+
let decorators = [];
|
|
5069
|
+
for (let i = 0; i < lines.length; i++) {
|
|
5070
|
+
const l = lines[i];
|
|
5071
|
+
if (/^\s*@/.test(l)) {
|
|
5072
|
+
const { text, end } = pyBalanced(lines, i, l.indexOf("@"));
|
|
5073
|
+
decorators.push(text.replace(/\s+/g, " ").trim());
|
|
5074
|
+
i = end;
|
|
5075
|
+
continue;
|
|
5076
|
+
}
|
|
5077
|
+
const start = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(/);
|
|
5078
|
+
if (!start) {
|
|
5079
|
+
if (l.trim() && !/^\s*#/.test(l)) decorators = [];
|
|
5080
|
+
continue;
|
|
5081
|
+
}
|
|
5082
|
+
const head = pyHeader(lines, i, start[0].length - 1);
|
|
5083
|
+
if (!head) {
|
|
5084
|
+
decorators = [];
|
|
5085
|
+
continue;
|
|
5086
|
+
}
|
|
5087
|
+
const indent = start[1].length;
|
|
4732
5088
|
const body = [];
|
|
4733
|
-
|
|
4734
|
-
|
|
5089
|
+
const inline = pyNoComment(head.after).trim();
|
|
5090
|
+
if (inline) body.push({ text: inline, line: head.endLine + 1, indent: indent + 4 });
|
|
5091
|
+
for (let j = head.endLine + 1; j < lines.length; j++) {
|
|
4735
5092
|
const t = lines[j];
|
|
4736
5093
|
if (!t.trim() || /^\s*#/.test(t)) continue;
|
|
4737
5094
|
const ind = t.match(/^\s*/)[0].length;
|
|
@@ -4740,8 +5097,10 @@ function findFunctions(src, language) {
|
|
|
4740
5097
|
if (!code) continue;
|
|
4741
5098
|
body.push({ text: code, line: j + 1, indent: ind });
|
|
4742
5099
|
}
|
|
4743
|
-
|
|
4744
|
-
|
|
5100
|
+
const doc = inline ? null : pyDocstring(lines, head.endLine + 1);
|
|
5101
|
+
fns.push({ name: start[2], line: i + 1, params: parseParams2(head.params, language), returns: head.returns, pyBody: body, ...decorators.length ? { decorators } : {}, ...doc ? { doc } : {} });
|
|
5102
|
+
decorators = [];
|
|
5103
|
+
}
|
|
4745
5104
|
annotateRoutes(fns, src);
|
|
4746
5105
|
return fns;
|
|
4747
5106
|
}
|
|
@@ -4770,9 +5129,11 @@ function findFunctions(src, language) {
|
|
|
4770
5129
|
if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
|
|
4771
5130
|
const close = matchClose(src, open);
|
|
4772
5131
|
if (close < 0) continue;
|
|
4773
|
-
const after = src.slice(close + 1);
|
|
4774
|
-
const
|
|
5132
|
+
const after = src.slice(close + 1, close + 1 + 4e3);
|
|
5133
|
+
const typed = language === "typescript" || language === "javascript" ? balancedReturnHead(after) : null;
|
|
5134
|
+
const head = typed ?? (language === "kotlin" ? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/) : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/));
|
|
4775
5135
|
if (!head || head[4] === ";") continue;
|
|
5136
|
+
if (/\(\?:const\|let\|var\)/.test(re.source) && head[4] !== "=>") continue;
|
|
4776
5137
|
if (language === "kotlin" && head[4] === "=") {
|
|
4777
5138
|
const markerAt2 = close + 1 + head[0].length - 1;
|
|
4778
5139
|
const fnLine2 = lineAt(src, m.index + m[0].lastIndexOf(name));
|
|
@@ -4835,15 +5196,178 @@ function findFunctions(src, language) {
|
|
|
4835
5196
|
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] } });
|
|
4836
5197
|
}
|
|
4837
5198
|
}
|
|
5199
|
+
if (language === "typescript" || language === "javascript") {
|
|
5200
|
+
const re = /\b\w+\.route\(\s*\{/g;
|
|
5201
|
+
let m;
|
|
5202
|
+
while (m = re.exec(src)) {
|
|
5203
|
+
const objOpen = m.index + m[0].length - 1;
|
|
5204
|
+
const objClose = matchClose(src, objOpen);
|
|
5205
|
+
if (objClose < 0) continue;
|
|
5206
|
+
const obj = src.slice(objOpen, objClose);
|
|
5207
|
+
const method = (obj.match(/\bmethod\s*:\s*['"`](\w+)['"`]/) || [])[1];
|
|
5208
|
+
const url = (obj.match(/\b(?:url|path)\s*:\s*['"`]([^'"`]+)['"`]/) || [])[1];
|
|
5209
|
+
const h = obj.match(/\bhandler\s*:\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/);
|
|
5210
|
+
if (!method || !url || !h) continue;
|
|
5211
|
+
const pOpen = objOpen + h.index + h[0].length - 1;
|
|
5212
|
+
const pClose = matchClose(src, pOpen);
|
|
5213
|
+
const brace = pClose < 0 ? -1 : src.indexOf("{", pClose);
|
|
5214
|
+
if (brace < 0 || !/^\s*(=>\s*)?(:\s*[\w<>\[\]|. ]+)?\s*(=>\s*)?$/.test(src.slice(pClose + 1, brace))) continue;
|
|
5215
|
+
const bc = matchClose(src, brace);
|
|
5216
|
+
if (bc < 0) continue;
|
|
5217
|
+
fns.push({ name: `${method.toUpperCase()} ${url}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: method.toUpperCase(), path: url } });
|
|
5218
|
+
}
|
|
5219
|
+
}
|
|
4838
5220
|
annotateRoutes(fns, src);
|
|
4839
5221
|
return fns.sort((a, b) => a.line - b.line);
|
|
4840
5222
|
}
|
|
5223
|
+
function displayLabel(name) {
|
|
5224
|
+
const w = String(name).replace(/^_+|_+$/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
|
|
5225
|
+
return w ? w.charAt(0).toUpperCase() + w.slice(1) : String(name);
|
|
5226
|
+
}
|
|
5227
|
+
var PLUMBING = /^(self|this|cls|db|session|conn|connection|cursor|tx|transaction|request|req|res|response|ctx|context|c|w|r|next|logger|log|deps|container|di|cancellationToken|ct|ec|app|g)$/i;
|
|
5228
|
+
var PLUMBING_TYPE = /\b(Session|AsyncSession|DbContext|Connection|HttpRequest|HttpResponse|Request|Response|Context|ResponseWriter|CancellationToken|ILogger|Logger|NextFunction)\b/;
|
|
5229
|
+
var allSteps = (steps) => (steps || []).flatMap((s) => [s, ...allSteps(s.children), ...allSteps(s.otherwise), ...(s.handlers || []).flatMap((h) => allSteps(h.steps)), ...allSteps(s.always?.steps)]);
|
|
5230
|
+
function completenessOf(item2) {
|
|
5231
|
+
const reasons = [];
|
|
5232
|
+
if (item2.kind === "decision") {
|
|
5233
|
+
if (item2.unread?.length) reasons.push(`${item2.unread.length} line${item2.unread.length === 1 ? "" : "s"} not read`);
|
|
5234
|
+
return { level: reasons.length ? "partly explained" : "explained", reasons };
|
|
5235
|
+
}
|
|
5236
|
+
const steps = allSteps(item2.steps);
|
|
5237
|
+
if (!steps.length) return { level: "found", reasons: ["No steps could be read; see the original code."] };
|
|
5238
|
+
const code = steps.filter((s) => s.kind === "other").length;
|
|
5239
|
+
const restated = steps.filter((s) => s.restates).length;
|
|
5240
|
+
if (code) reasons.push(`${code} step${code === 1 ? "" : "s"} shown as code`);
|
|
5241
|
+
if (restated) reasons.push(`${restated} step${restated === 1 ? "" : "s"} only restate the code`);
|
|
5242
|
+
if (item2.anchor && item2.anchor.coverage < 1) reasons.push(`${item2.anchor.missing.length ? `lines ${item2.anchor.missing.join(", ")}` : "some lines"} not tied to a step`);
|
|
5243
|
+
return { level: reasons.length ? "partly explained" : "explained", reasons };
|
|
5244
|
+
}
|
|
5245
|
+
function pyBalanced(lines, i, col) {
|
|
5246
|
+
let depth = 0, text = "", quote = null;
|
|
5247
|
+
for (let j = i; j < lines.length; j++) {
|
|
5248
|
+
const l = j === i ? lines[j].slice(col) : lines[j];
|
|
5249
|
+
for (let k = 0; k < l.length; k++) {
|
|
5250
|
+
const c = l[k];
|
|
5251
|
+
if (quote) {
|
|
5252
|
+
if (c === "\\") k++;
|
|
5253
|
+
else if (c === quote) quote = null;
|
|
5254
|
+
continue;
|
|
5255
|
+
}
|
|
5256
|
+
if (c === '"' || c === "'") quote = c;
|
|
5257
|
+
else if (c === "#") break;
|
|
5258
|
+
else if ("([{".includes(c)) depth++;
|
|
5259
|
+
else if (")]}".includes(c)) depth--;
|
|
5260
|
+
}
|
|
5261
|
+
text += (j === i ? "" : "\n") + l;
|
|
5262
|
+
quote = null;
|
|
5263
|
+
if (depth <= 0) return { text, end: j };
|
|
5264
|
+
}
|
|
5265
|
+
return { text, end: lines.length - 1 };
|
|
5266
|
+
}
|
|
5267
|
+
function pyHeader(lines, i, open) {
|
|
5268
|
+
let depth = 0, quote = null, params = "", closed = false, tail = "";
|
|
5269
|
+
for (let j = i; j < lines.length && j < i + 80; j++) {
|
|
5270
|
+
const l = lines[j];
|
|
5271
|
+
for (let k = j === i ? open : 0; k < l.length; k++) {
|
|
5272
|
+
const c = l[k];
|
|
5273
|
+
if (!closed) {
|
|
5274
|
+
if (quote) {
|
|
5275
|
+
params += c;
|
|
5276
|
+
if (c === "\\") {
|
|
5277
|
+
params += l[k + 1] ?? "";
|
|
5278
|
+
k++;
|
|
5279
|
+
} else if (c === quote) quote = null;
|
|
5280
|
+
continue;
|
|
5281
|
+
}
|
|
5282
|
+
if (c === "#") break;
|
|
5283
|
+
if (c === '"' || c === "'") {
|
|
5284
|
+
quote = c;
|
|
5285
|
+
params += c;
|
|
5286
|
+
continue;
|
|
5287
|
+
}
|
|
5288
|
+
if (c === "(") {
|
|
5289
|
+
if (depth++ === 0) continue;
|
|
5290
|
+
} else if (c === ")") {
|
|
5291
|
+
if (--depth === 0) {
|
|
5292
|
+
closed = true;
|
|
5293
|
+
continue;
|
|
5294
|
+
}
|
|
5295
|
+
}
|
|
5296
|
+
params += c;
|
|
5297
|
+
continue;
|
|
5298
|
+
}
|
|
5299
|
+
if (c === "#" && depth === 0) break;
|
|
5300
|
+
if ("([{".includes(c)) depth++;
|
|
5301
|
+
else if (")]}".includes(c)) depth--;
|
|
5302
|
+
if (c === ":" && depth === 0) {
|
|
5303
|
+
const ret = tail.trim().replace(/^->\s*/, "").replace(/\s+/g, " ").trim();
|
|
5304
|
+
return { params: params.replace(/\s+/g, " ").trim(), returns: ret || null, after: l.slice(k + 1), endLine: j };
|
|
5305
|
+
}
|
|
5306
|
+
tail += c;
|
|
5307
|
+
}
|
|
5308
|
+
if (!closed) params += " ";
|
|
5309
|
+
else tail += " ";
|
|
5310
|
+
}
|
|
5311
|
+
return null;
|
|
5312
|
+
}
|
|
5313
|
+
function pyDocstring(lines, from) {
|
|
5314
|
+
let j = from;
|
|
5315
|
+
while (j < lines.length && (!lines[j].trim() || /^\s*#/.test(lines[j]))) j++;
|
|
5316
|
+
const first = lines[j]?.trim();
|
|
5317
|
+
const m = first?.match(/^([rRuU]?)("""|\'\'\'|"|')/);
|
|
5318
|
+
if (!m) return null;
|
|
5319
|
+
const q = m[2];
|
|
5320
|
+
let text = first.slice(m[0].length);
|
|
5321
|
+
if (text.includes(q)) text = text.slice(0, text.indexOf(q));
|
|
5322
|
+
else {
|
|
5323
|
+
if (q.length === 1) return null;
|
|
5324
|
+
for (let k = j + 1; k < lines.length && k < j + 60; k++) {
|
|
5325
|
+
const at = lines[k].indexOf(q);
|
|
5326
|
+
if (at >= 0) {
|
|
5327
|
+
text += "\n" + lines[k].slice(0, at);
|
|
5328
|
+
break;
|
|
5329
|
+
}
|
|
5330
|
+
text += "\n" + lines[k];
|
|
5331
|
+
}
|
|
5332
|
+
}
|
|
5333
|
+
return cleanDoc(text);
|
|
5334
|
+
}
|
|
5335
|
+
function cleanDoc(text) {
|
|
5336
|
+
const para = [];
|
|
5337
|
+
for (const raw of String(text).split("\n")) {
|
|
5338
|
+
const t = raw.replace(/^\s*(\*|\/\/\/?|#)?\s?/, "").trim();
|
|
5339
|
+
if (/^(@\w+|:(param|return|rtype|raises|type)\b|(Args|Arguments|Parameters|Returns|Raises|Yields|Example|Examples|Note|Notes)\s*:|<\/?(summary|param|returns)\b)/i.test(t)) break;
|
|
5340
|
+
if (!t) {
|
|
5341
|
+
if (para.length) break;
|
|
5342
|
+
continue;
|
|
5343
|
+
}
|
|
5344
|
+
para.push(t.replace(/<\/?summary>/g, ""));
|
|
5345
|
+
}
|
|
5346
|
+
const s = para.join(" ").replace(/\s+/g, " ").trim();
|
|
5347
|
+
if (!s) return null;
|
|
5348
|
+
return s.length > 300 ? `${s.slice(0, 299)}\u2026` : s;
|
|
5349
|
+
}
|
|
5350
|
+
function leadingDoc(lines, fnLine, language) {
|
|
5351
|
+
let k = fnLine - 2;
|
|
5352
|
+
while (k >= 0 && /^\s*(@|#\[|\[[A-Z])/.test(lines[k])) k--;
|
|
5353
|
+
if (k < 0) return null;
|
|
5354
|
+
if (/\*\/\s*$/.test(lines[k])) {
|
|
5355
|
+
const end = k;
|
|
5356
|
+
while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
|
|
5357
|
+
if (k < 0) return null;
|
|
5358
|
+
return cleanDoc(lines.slice(k, end + 1).join("\n").replace(/^\s*\/\*\*/, "").replace(/\*\/\s*$/, ""));
|
|
5359
|
+
}
|
|
5360
|
+
const lineDoc = language === "go" ? /^\s*\/\/(?!\/)/ : language === "ruby" ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
|
|
5361
|
+
const got = [];
|
|
5362
|
+
while (k >= 0 && lineDoc.test(lines[k])) got.unshift(lines[k--]);
|
|
5363
|
+
return got.length ? cleanDoc(got.join("\n")) : null;
|
|
5364
|
+
}
|
|
4841
5365
|
function annotateRoutes(fns, src) {
|
|
4842
5366
|
const lines = src.split("\n");
|
|
4843
5367
|
for (const fn of fns) {
|
|
4844
5368
|
if (fn.route) continue;
|
|
4845
|
-
|
|
4846
|
-
|
|
5369
|
+
const above = fn.decorators ? [...fn.decorators].reverse() : lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
|
|
5370
|
+
for (const l of above) {
|
|
4847
5371
|
let m;
|
|
4848
5372
|
if (m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i)) {
|
|
4849
5373
|
fn.route = { method: m[1].toUpperCase(), path: m[2] };
|
|
@@ -5197,7 +5721,7 @@ function toThunderOutcome(text) {
|
|
|
5197
5721
|
if (/^[A-Z][A-Za-z0-9_]*$/.test(s)) return s;
|
|
5198
5722
|
return null;
|
|
5199
5723
|
}
|
|
5200
|
-
var
|
|
5724
|
+
var lastSeg2 = (s) => String(s).split(/\.|::/).pop();
|
|
5201
5725
|
var firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
|
|
5202
5726
|
function splitTop(str, delim) {
|
|
5203
5727
|
const out = [];
|
|
@@ -5223,21 +5747,21 @@ function splitTop(str, delim) {
|
|
|
5223
5747
|
function terminatorEffect(stmt, language) {
|
|
5224
5748
|
const s = String(stmt).trim().replace(/;$/, "").trim();
|
|
5225
5749
|
let m;
|
|
5226
|
-
if (m = s.match(/^throw\s+new\s+([\w.$]+)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name:
|
|
5227
|
-
if (m = s.match(/^throw\s+([\w.$]+)$/)) return { kind: "fails", name:
|
|
5228
|
-
if (m = s.match(/^throw\s+([A-Z][\w.$]*)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name:
|
|
5750
|
+
if (m = s.match(/^throw\s+new\s+([\w.$]+)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name: lastSeg2(m[1]), detail: firstString(m[2]) };
|
|
5751
|
+
if (m = s.match(/^throw\s+([\w.$]+)$/)) return { kind: "fails", name: lastSeg2(m[1]) };
|
|
5752
|
+
if (m = s.match(/^throw\s+([A-Z][\w.$]*)\s*\(([\s\S]*)\)$/)) return { kind: "fails", name: lastSeg2(m[1]), detail: firstString(m[2]) };
|
|
5229
5753
|
if ((m = s.match(/^error\(([\s\S]*)\)$/)) && language === "kotlin") return { kind: "fails", name: "IllegalStateException", detail: firstString(m[1]) };
|
|
5230
5754
|
if (m = s.match(/^abort\(\s*(\d{3})\b/)) return { kind: "responds", name: m[1] };
|
|
5231
|
-
if (m = s.match(/^raise\s+([\w.]+)(?:\(([\s\S]*)\))?$/)) return { kind: "fails", name:
|
|
5755
|
+
if (m = s.match(/^raise\s+([\w.]+)(?:\(([\s\S]*)\))?$/)) return { kind: "fails", name: lastSeg2(m[1]), detail: m[2] ? firstString(m[2]) : null };
|
|
5232
5756
|
if (language === "ruby") {
|
|
5233
|
-
if (m = s.match(/^raise\s+([A-Z][\w:]*)(?:\.new)?\s*(?:,\s*|\(\s*)?([\s\S]*?)\)?$/)) return { kind: "fails", name:
|
|
5757
|
+
if (m = s.match(/^raise\s+([A-Z][\w:]*)(?:\.new)?\s*(?:,\s*|\(\s*)?([\s\S]*?)\)?$/)) return { kind: "fails", name: lastSeg2(m[1]), detail: firstString(m[2] || "") };
|
|
5234
5758
|
if (m = s.match(/^(?:raise|fail)\s+(["'][\s\S]*)$/)) return { kind: "fails", name: "RuntimeError", detail: firstString(m[1]) };
|
|
5235
5759
|
if (m = s.match(/^(?:head|halt)\s+(?::|")?(\w+)"?/)) return { kind: "responds", name: m[1] };
|
|
5236
5760
|
}
|
|
5237
5761
|
if (m = s.match(/^panic!?\(([\s\S]*)\)$/)) return { kind: "fails", name: "panic", detail: firstString(m[1]) };
|
|
5238
5762
|
if (m = s.match(/^return\s+Err\(([\s\S]*)\)$/)) {
|
|
5239
5763
|
const inner = m[1].trim();
|
|
5240
|
-
return { kind: "fails", name: firstString(inner) ? "error" :
|
|
5764
|
+
return { kind: "fails", name: firstString(inner) ? "error" : lastSeg2(inner.replace(/\(.*$/s, "")), detail: firstString(inner) };
|
|
5241
5765
|
}
|
|
5242
5766
|
if (s === "return") return { kind: "stops" };
|
|
5243
5767
|
if ((m = s.match(/^render\b.*\bstatus:\s*(?::|")?(\w+)/)) && language === "ruby") return { kind: "responds", name: m[1] };
|
|
@@ -5343,7 +5867,7 @@ function valueLiteral(text) {
|
|
|
5343
5867
|
var rebind = (guard, name, subject) => guard.replace(new RegExp(`\\b${name}\\b`, "g"), subject);
|
|
5344
5868
|
function switchArms(body, language, baseLine) {
|
|
5345
5869
|
const arms = [];
|
|
5346
|
-
const
|
|
5870
|
+
const lineOf3 = (idx) => baseLine + lineAt(body, idx) - 1;
|
|
5347
5871
|
if (language === "rust" || language === "csharp-expr") {
|
|
5348
5872
|
let i = 0;
|
|
5349
5873
|
while (i < body.length) {
|
|
@@ -5366,7 +5890,7 @@ function switchArms(body, language, baseLine) {
|
|
|
5366
5890
|
value = body.slice(j, end).trim();
|
|
5367
5891
|
}
|
|
5368
5892
|
const g = head.match(/^(.*?)\s+(?:if|when)\s+(.+)$/s);
|
|
5369
|
-
arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line:
|
|
5893
|
+
arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line: lineOf3(i) });
|
|
5370
5894
|
i = end + 1;
|
|
5371
5895
|
}
|
|
5372
5896
|
return arms;
|
|
@@ -5405,8 +5929,8 @@ function switchArms(body, language, baseLine) {
|
|
|
5405
5929
|
}
|
|
5406
5930
|
const patterns = [...pending, pattern];
|
|
5407
5931
|
pending = [];
|
|
5408
|
-
if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line:
|
|
5409
|
-
else arms.push({ pattern: patterns.join(language === "go" && patterns.length === 1 ? "" : ", ") || patterns[0], guard: g ? g[2].trim() : null, value, line:
|
|
5932
|
+
if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line: lineOf3(starts[k]) });
|
|
5933
|
+
else arms.push({ pattern: patterns.join(language === "go" && patterns.length === 1 ? "" : ", ") || patterns[0], guard: g ? g[2].trim() : null, value, line: lineOf3(starts[k]) });
|
|
5410
5934
|
}
|
|
5411
5935
|
return arms;
|
|
5412
5936
|
}
|
|
@@ -5535,11 +6059,14 @@ function splitStatements(body, baseLine) {
|
|
|
5535
6059
|
}
|
|
5536
6060
|
}
|
|
5537
6061
|
} else if (c === ";" && depth === 0) {
|
|
6062
|
+
if (/^\s*(?:if|for|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes("{") && /\{/.test(src.slice(i, src.indexOf("\n", i) < 0 ? void 0 : src.indexOf("\n", i)))) continue;
|
|
5538
6063
|
i++;
|
|
5539
6064
|
break;
|
|
5540
6065
|
} else if (c === "\n" && depth === 0) {
|
|
5541
6066
|
const before = src.slice(start, i).trimEnd();
|
|
5542
|
-
|
|
6067
|
+
let j = i + 1;
|
|
6068
|
+
while (j < src.length && (src[j] === " " || src[j] === " " || src[j] === "\n" || src[j] === "\r")) j++;
|
|
6069
|
+
const after = src.slice(j, j + 24);
|
|
5543
6070
|
if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) {
|
|
5544
6071
|
i++;
|
|
5545
6072
|
break;
|
|
@@ -5548,7 +6075,9 @@ function splitStatements(body, baseLine) {
|
|
|
5548
6075
|
}
|
|
5549
6076
|
const raw = src.slice(start, i);
|
|
5550
6077
|
const text = raw.trim();
|
|
5551
|
-
|
|
6078
|
+
let e = raw.length;
|
|
6079
|
+
while (e > 0 && /[\s;]/.test(raw[e - 1])) e--;
|
|
6080
|
+
const end = start + e;
|
|
5552
6081
|
if (text) out.push({ text, line: baseLine + lineAt(src, start) - 1, endLine: baseLine + lineAt(src, Math.max(start, end - 1)) - 1, start, end });
|
|
5553
6082
|
}
|
|
5554
6083
|
return out;
|
|
@@ -5584,7 +6113,7 @@ function readBraceStatements(stmts, language, inputs) {
|
|
|
5584
6113
|
const head = splitIf(t, language);
|
|
5585
6114
|
if (head && !/^else\b/.test(head.remaining)) {
|
|
5586
6115
|
const single = head.branch.replace(/^return\s+/, "").replace(/;\s*$/, "");
|
|
5587
|
-
const looksLikeError = /^(Err[A-Z]\w*|\w*(Error|Exception))$/.test(
|
|
6116
|
+
const looksLikeError = /^(Err[A-Z]\w*|\w*(Error|Exception))$/.test(lastSeg2(single));
|
|
5588
6117
|
const isFixedReturn = /^return\s/.test(head.branch) && toThunderOutcome(single) && !looksLikeError && (language !== "go" || !single.includes(","));
|
|
5589
6118
|
if (!isFixedReturn) {
|
|
5590
6119
|
const g = makeGuard(head.cond, head.branch, language, inputs, st.line);
|
|
@@ -6217,7 +6746,7 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
6217
6746
|
let stmts = [];
|
|
6218
6747
|
try {
|
|
6219
6748
|
if (lang === "python") stmts = indentStatements(fn.pyBody, { depthKey: "indent" });
|
|
6220
|
-
else if (lang === "ruby") stmts = indentStatements(fn.rbBody, { depthKey: "depth" });
|
|
6749
|
+
else if (lang === "ruby") stmts = indentStatements(fn.rbBody.map((l) => /^(elsif|else|rescue|ensure)\b/.test(l.text) ? { ...l, depth: Math.max(0, l.depth - 1) } : l), { depthKey: "depth" });
|
|
6221
6750
|
else if (typeof fn.body === "string" && fn.bodyStart != null) stmts = braceStatements(splitStatements(lang === "kotlin" ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), splitStatements);
|
|
6222
6751
|
} catch {
|
|
6223
6752
|
return null;
|
|
@@ -6249,8 +6778,9 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
6249
6778
|
}
|
|
6250
6779
|
for (const st of r.steps) {
|
|
6251
6780
|
if (st.kind !== "branch" || !st.cond) continue;
|
|
6252
|
-
const
|
|
6253
|
-
|
|
6781
|
+
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ""));
|
|
6782
|
+
const cond = bareProperty ? null : toThunderCondition(st.cond, names);
|
|
6783
|
+
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? "not: " : ""}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, " is not empty").replace(/ is ""/g, " is empty")}${inner || ""}`);
|
|
6254
6784
|
delete st.cond;
|
|
6255
6785
|
delete st.negate;
|
|
6256
6786
|
}
|
|
@@ -6265,6 +6795,7 @@ function readCode(source, { language, file = "" } = {}) {
|
|
|
6265
6795
|
const code = lang === "php" ? normalizePhp(src) : src;
|
|
6266
6796
|
const items = [];
|
|
6267
6797
|
const srcLines = src.split("\n");
|
|
6798
|
+
const codeLines = code.split("\n");
|
|
6268
6799
|
for (const fn of findFunctions(code, lang)) {
|
|
6269
6800
|
const inputs = fn.params;
|
|
6270
6801
|
const names = inputs.map((p) => p.name);
|
|
@@ -6283,13 +6814,17 @@ function readCode(source, { language, file = "" } = {}) {
|
|
|
6283
6814
|
guards.sort((a, b) => a.line - b.line);
|
|
6284
6815
|
}
|
|
6285
6816
|
const guardNote = guards.length ? ` It checks ${guards.length} condition${guards.length === 1 ? "" : "s"} first: ${guards.map((g) => g.says.replace(/\.$/, "")).join("; ")}.` : "";
|
|
6817
|
+
const doc = fn.doc ?? (lang === "python" ? null : leadingDoc(codeLines, fn.line, lang));
|
|
6286
6818
|
const base = {
|
|
6287
6819
|
id: `${fn.name}:${fn.line}`,
|
|
6288
6820
|
name: fn.name,
|
|
6821
|
+
label: displayLabel(fn.name),
|
|
6289
6822
|
line: fn.line,
|
|
6290
|
-
|
|
6823
|
+
// Framework plumbing (a database session, the request, a context) is marked so views can leave it out of "You give it".
|
|
6824
|
+
inputs: inputs.map((p) => PLUMBING.test(p.name) || PLUMBING_TYPE.test(String(p.type ?? "")) ? { ...p, plumbing: true } : p),
|
|
6291
6825
|
returns: simpleType(fn.returns),
|
|
6292
6826
|
...fn.route ? { route: fn.route } : {},
|
|
6827
|
+
...doc ? { doc } : {},
|
|
6293
6828
|
provenance: "inferred-from-code"
|
|
6294
6829
|
};
|
|
6295
6830
|
if (isDecision) {
|
|
@@ -6312,6 +6847,9 @@ function readCode(source, { language, file = "" } = {}) {
|
|
|
6312
6847
|
status: "signature-only",
|
|
6313
6848
|
...st ? { steps: st.steps, stepsMore: st.more, stepsReadable: Math.round(st.readable * 100) / 100, ...st.anchor ? { anchor: st.anchor } : {} } : {},
|
|
6314
6849
|
says: fn.route ? `Handles ${fn.route.method} ${fn.route.path || "(this controller's path)"}.${guardNote}` : `${fn.name} takes ${inputs.length ? inputs.map((p) => p.type && !/[<>\[\]]/.test(p.type) ? `${p.name} (${p.type})` : p.name).join(", ") : "no inputs"}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ""}. ${guards.length ? "" : " Its body does more than choose between fixed answers, so no rules are shown."}${guardNote}`,
|
|
6850
|
+
// The same facts as separate fields, so a view never has to cut sentences out of `says`.
|
|
6851
|
+
headline: fn.route ? `Handles ${fn.route.method} ${fn.route.path || "(this controller's path)"}.` : `${displayLabel(fn.name)} takes ${inputs.length ? inputs.map((p) => p.name).join(", ") : "no inputs"}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ""}.`,
|
|
6852
|
+
...guards.length ? {} : { note: "Its body does more than choose between fixed answers, so no rules are shown." },
|
|
6315
6853
|
guards,
|
|
6316
6854
|
unread: read.unread
|
|
6317
6855
|
});
|
|
@@ -6321,6 +6859,7 @@ function readCode(source, { language, file = "" } = {}) {
|
|
|
6321
6859
|
for (const e of facts?.errors || []) items.push({ id: `error:${e.name}:${e.line}`, kind: "error", name: e.name, line: e.line, status: "read", says: /\s/.test(e.name) ? `Can fail with the error "${e.name}".` : `Raises ${e.name}.`, provenance: "inferred-from-code" });
|
|
6322
6860
|
for (const t of facts?.tests || []) items.push({ id: `test:${t.name}:${t.line}`, kind: "test", name: t.name, line: t.line, status: "read", says: `A test named "${t.name}".`, provenance: "inferred-from-code" });
|
|
6323
6861
|
items.sort((a, b) => a.line - b.line);
|
|
6862
|
+
for (const it of items) if (it.kind === "function" || it.kind === "decision") it.completeness = completenessOf(it);
|
|
6324
6863
|
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
6325
6864
|
for (const it of items) {
|
|
6326
6865
|
counts[it.kind]++;
|
|
@@ -6354,14 +6893,14 @@ function searchReading(reading, { query = "", kinds = [], status = [] } = {}) {
|
|
|
6354
6893
|
|
|
6355
6894
|
// src/anchor.mjs
|
|
6356
6895
|
var ANCHOR_SCHEMA = "thunder-anchor-v1";
|
|
6357
|
-
var
|
|
6896
|
+
var lineStarts2 = (source) => {
|
|
6358
6897
|
const out = [0];
|
|
6359
6898
|
for (let i = 0; i < source.length; i++) if (source[i] === "\n") out.push(i + 1);
|
|
6360
6899
|
return out;
|
|
6361
6900
|
};
|
|
6362
6901
|
function spanRange(source, span) {
|
|
6363
6902
|
if (span.exact === "offset" && span.start != null && span.end != null) return [span.start, span.end];
|
|
6364
|
-
const starts =
|
|
6903
|
+
const starts = lineStarts2(source);
|
|
6365
6904
|
const a = starts[span.startLine - 1] ?? source.length;
|
|
6366
6905
|
const nextLine = starts[span.endLine];
|
|
6367
6906
|
const b = nextLine != null ? nextLine - 1 : source.length;
|
|
@@ -6450,7 +6989,7 @@ function editStep({ source, language, file = "", functionName, line = null, path
|
|
|
6450
6989
|
if (!edited) problems.push("The edited step is no longer read as a step.");
|
|
6451
6990
|
else if (norm3(spanText(next, edited.span)) !== norm3(replacement)) problems.push("The edited step does not match the new code exactly.");
|
|
6452
6991
|
if (problems.length) return { ok: false, source, problems };
|
|
6453
|
-
const starts =
|
|
6992
|
+
const starts = lineStarts2(source);
|
|
6454
6993
|
return {
|
|
6455
6994
|
ok: true,
|
|
6456
6995
|
source: next,
|
|
@@ -6515,9 +7054,9 @@ function candidates(type, u) {
|
|
|
6515
7054
|
if (!out.size) out.add(0);
|
|
6516
7055
|
return [...out].sort((a, b) => a - b);
|
|
6517
7056
|
}
|
|
6518
|
-
function assignments(inputs, values,
|
|
7057
|
+
function assignments(inputs, values, cap2 = 4096) {
|
|
6519
7058
|
const total = inputs.reduce((n, i) => n * values[i].length, 1);
|
|
6520
|
-
if (total <=
|
|
7059
|
+
if (total <= cap2) {
|
|
6521
7060
|
let acc = [{}];
|
|
6522
7061
|
for (const name of inputs) acc = acc.flatMap((a) => values[name].map((v) => ({ ...a, [name]: v })));
|
|
6523
7062
|
return acc;
|
|
@@ -6526,15 +7065,15 @@ function assignments(inputs, values, cap = 4096) {
|
|
|
6526
7065
|
return [base, ...inputs.flatMap((n) => values[n].map((v) => ({ ...base, [n]: v })))];
|
|
6527
7066
|
}
|
|
6528
7067
|
var lit = (v) => typeof v === "string" ? JSON.stringify(v) : String(v);
|
|
6529
|
-
function recoverModel(
|
|
6530
|
-
if (!
|
|
6531
|
-
const results = [...
|
|
7068
|
+
function recoverModel(item2, { extraConditions = [] } = {}) {
|
|
7069
|
+
if (!item2 || item2.kind !== "decision" || !item2.rules?.length || !item2.otherwise) return { ok: false, reason: "Only decisions (functions that choose between fixed answers) can become a contract." };
|
|
7070
|
+
const results = [...item2.rules.map((r) => r.result), item2.otherwise.result];
|
|
6532
7071
|
const bad = results.find((r) => !OUTCOME.test(r));
|
|
6533
7072
|
if (bad) return { ok: false, reason: `The answer ${bad} is not a name. Contracts answer with names such as Approve or Review.` };
|
|
6534
7073
|
const notes = [];
|
|
6535
7074
|
const renames = /* @__PURE__ */ new Map();
|
|
6536
|
-
const conditions = [...
|
|
6537
|
-
const refs = usage(conditions, new Set((
|
|
7075
|
+
const conditions = [...item2.rules.map((r) => r.when), ...extraConditions];
|
|
7076
|
+
const refs = usage(conditions, new Set((item2.inputs || []).map((p) => p.name)));
|
|
6538
7077
|
for (const path of refs.keys()) if (path.includes(".")) {
|
|
6539
7078
|
renames.set(path, flat(path));
|
|
6540
7079
|
notes.push(`${flat(path)} stands for ${path} in the code.`);
|
|
@@ -6545,9 +7084,9 @@ function recoverModel(item, { extraConditions = [] } = {}) {
|
|
|
6545
7084
|
if (t.t === "num" || t.t === "bool") return String(t.v);
|
|
6546
7085
|
return t.v;
|
|
6547
7086
|
}).join(" ").replace(/\( /g, "(").replace(/ \)/g, ")");
|
|
6548
|
-
const declared = new Map((
|
|
7087
|
+
const declared = new Map((item2.inputs || []).map((p) => [p.name, p.type]));
|
|
6549
7088
|
const order = (path) => {
|
|
6550
|
-
const i = (
|
|
7089
|
+
const i = (item2.inputs || []).findIndex((p) => p.name === path.split(".")[0]);
|
|
6551
7090
|
return i < 0 ? 999 : i;
|
|
6552
7091
|
};
|
|
6553
7092
|
const names = [...refs.keys()].sort((a, b) => order(a) - order(b)).map((p) => renames.get(p) ?? p);
|
|
@@ -6560,25 +7099,25 @@ function recoverModel(item, { extraConditions = [] } = {}) {
|
|
|
6560
7099
|
for (const s of u.strings) if (!STRING_LIT.test(s)) return { ok: false, reason: `The text "${s}" has characters a contract example cannot hold yet.` };
|
|
6561
7100
|
values[name] = candidates(types[name], u);
|
|
6562
7101
|
}
|
|
6563
|
-
const rules =
|
|
6564
|
-
const decisionName = pascal2(
|
|
7102
|
+
const rules = item2.rules.map((r) => ({ when: rewrite(r.when), result: r.result }));
|
|
7103
|
+
const decisionName = pascal2(item2.name);
|
|
6565
7104
|
const canonical = parseIntent([
|
|
6566
7105
|
`decision ${decisionName}`,
|
|
6567
7106
|
" inputs",
|
|
6568
7107
|
...names.map((n) => ` ${n}`),
|
|
6569
7108
|
...rules.flatMap((r, i) => [` rule r${i + 1}`, ` when ${r.when}`, ` return ${r.result}`]),
|
|
6570
7109
|
" default",
|
|
6571
|
-
` return ${
|
|
7110
|
+
` return ${item2.otherwise.result}`
|
|
6572
7111
|
].join("\n")).decisions[0];
|
|
6573
7112
|
const run = (a) => evaluateDecision(canonical, a);
|
|
6574
7113
|
const all = assignments(names, values).map((a) => ({ a, r: run(a) }));
|
|
6575
7114
|
return { ok: true, notes, refs, renames, names, types, values, rules, decisionName, canonical, run, all };
|
|
6576
7115
|
}
|
|
6577
|
-
function promoteDecision(
|
|
6578
|
-
const model = recoverModel(
|
|
7116
|
+
function promoteDecision(item2, { file = item2.file || "" } = {}) {
|
|
7117
|
+
const model = recoverModel(item2);
|
|
6579
7118
|
if (!model.ok) return model;
|
|
6580
7119
|
const { notes, refs, renames, names, types, rules, decisionName, run, all } = model;
|
|
6581
|
-
const results = [...
|
|
7120
|
+
const results = [...item2.rules.map((r) => r.result), item2.otherwise.result];
|
|
6582
7121
|
const chosen = [];
|
|
6583
7122
|
const key = (a) => names.map((n) => lit(a[n])).join("|");
|
|
6584
7123
|
const add = (a, label) => {
|
|
@@ -6613,7 +7152,7 @@ function promoteDecision(item, { file = item.file || "" } = {}) {
|
|
|
6613
7152
|
for (const w of unreached) notes.push(`No example reaches the rule "${sayCondition(w)}"; an earlier rule always answers first, or the examples need other values.`);
|
|
6614
7153
|
const outcomes = [...new Set(results)];
|
|
6615
7154
|
const sig = names.map((n) => `${n}: ${types[n]}`).join(", ");
|
|
6616
|
-
const where = file ? `${file} line ${
|
|
7155
|
+
const where = file ? `${file} line ${item2.line}` : `line ${item2.line}`;
|
|
6617
7156
|
const source = [
|
|
6618
7157
|
`# Recovered from ${where} by thunder read. Inferred from code, not written by a person.`,
|
|
6619
7158
|
"# The examples record what the code does today. Confirm each answer, or change it where the code is wrong.",
|
|
@@ -6623,7 +7162,7 @@ function promoteDecision(item, { file = item.file || "" } = {}) {
|
|
|
6623
7162
|
"",
|
|
6624
7163
|
`decision ${decisionName}(${sig})`,
|
|
6625
7164
|
...rules.map((r) => ` when ${r.when} -> ${r.result}`),
|
|
6626
|
-
` otherwise -> ${
|
|
7165
|
+
` otherwise -> ${item2.otherwise.result}`,
|
|
6627
7166
|
"",
|
|
6628
7167
|
`examples ${decisionName}`,
|
|
6629
7168
|
...chosen.map((c) => ` case "${c.label.replace(/"/g, "")}": (${names.map((n) => `${n}: ${lit(c.a[n])}`).join(", ")}) -> ${c.result}`),
|
|
@@ -6826,7 +7365,7 @@ function writeRule({ source, language, file = "", decision: name, line = null, r
|
|
|
6826
7365
|
});
|
|
6827
7366
|
if (problems.length) return fail3(...problems);
|
|
6828
7367
|
const starts = lineStartsOf(source);
|
|
6829
|
-
const
|
|
7368
|
+
const lineOf3 = (off) => {
|
|
6830
7369
|
let lo = 0, hi = starts.length - 1;
|
|
6831
7370
|
while (lo < hi) {
|
|
6832
7371
|
const m = lo + hi + 1 >> 1;
|
|
@@ -6835,7 +7374,7 @@ function writeRule({ source, language, file = "", decision: name, line = null, r
|
|
|
6835
7374
|
}
|
|
6836
7375
|
return lo + 1;
|
|
6837
7376
|
};
|
|
6838
|
-
const change = real.slice().reverse().map((e) => ({ line:
|
|
7377
|
+
const change = real.slice().reverse().map((e) => ({ line: lineOf3(e.start), column: e.start - starts[lineOf3(e.start) - 1] + 1, before: e.was, after: e.text }));
|
|
6839
7378
|
const label = (r) => r === "otherwise" ? "Otherwise" : `If ${sayCondition(r.when)}`;
|
|
6840
7379
|
const beforeRule = index === "otherwise" ? `Otherwise, the answer is ${target.result}` : `${label(target)}, the answer is ${target.result}`;
|
|
6841
7380
|
const afterRule = index === "otherwise" ? `Otherwise, the answer is ${wantResult}` : `If ${sayCondition(newWhen)}, the answer is ${wantResult}`;
|
|
@@ -6854,7 +7393,7 @@ function changedCases(before, after) {
|
|
|
6854
7393
|
return { checked: a.all.length, changed, note: `Checked ${a.all.length} boundary input${a.all.length === 1 ? "" : "s"}; ${changed.length} now get${changed.length === 1 ? "s" : ""} a different answer. These are the values on each side of every limit, not every possible input.` };
|
|
6855
7394
|
}
|
|
6856
7395
|
var CMP_WORDS = { "<=": "at most", "<": "less than", ">=": "at least", ">": "more than", "==": "is", "!=": "is not" };
|
|
6857
|
-
var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op,
|
|
7396
|
+
var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words6]) => ({ op, words: words6 }));
|
|
6858
7397
|
function ruleParts(when) {
|
|
6859
7398
|
return tokenize(when).map((t) => {
|
|
6860
7399
|
if (t.t === "num") return { kind: "number", value: t.v };
|
|
@@ -6978,8 +7517,8 @@ function parsePlainContract(source) {
|
|
|
6978
7517
|
const input = parseInputLine(text, line);
|
|
6979
7518
|
if (RESERVED.has(input.id) || !input.id) fail2(line, "Choose a different name for this input.");
|
|
6980
7519
|
if (model.inputs.some((i) => i.id === input.id)) fail2(line, `${input.label} is listed twice.`);
|
|
6981
|
-
const
|
|
6982
|
-
if (input.kind === "yesno" && (
|
|
7520
|
+
const words6 = model.inputs.flatMap((i) => i.kind === "yesno" ? [i.yes, i.no] : []);
|
|
7521
|
+
if (input.kind === "yesno" && (words6.includes(input.yes) || words6.includes(input.no))) fail2(line, "Each yes/no word must be unique across inputs.");
|
|
6983
7522
|
model.inputs.push(input);
|
|
6984
7523
|
} else if (section === "decision") {
|
|
6985
7524
|
let m;
|
|
@@ -7137,152 +7676,1544 @@ function previewPlainContract(sourceOrModel) {
|
|
|
7137
7676
|
application: "not_checked"
|
|
7138
7677
|
};
|
|
7139
7678
|
}
|
|
7679
|
+
var spaced = (s) => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, " ").toLowerCase();
|
|
7680
|
+
function plainFromReading(item2) {
|
|
7681
|
+
if (!item2 || item2.kind !== "decision" || !item2.rules?.length || !item2.otherwise) return null;
|
|
7682
|
+
const inferred = [];
|
|
7683
|
+
const whens = (item2.rules ?? []).map((r) => r.when ?? "").join(" and ");
|
|
7684
|
+
const typed = (item2.inputs ?? []).map((i) => {
|
|
7685
|
+
if (i.type) return i;
|
|
7686
|
+
const esc = i.name.replace(/[$]/g, "\\$");
|
|
7687
|
+
if (new RegExp(`\\b${esc}\\s*(>=|<=|<|>|==)\\s*-?\\d`).test(whens)) {
|
|
7688
|
+
inferred.push(i.name);
|
|
7689
|
+
return { ...i, type: "number" };
|
|
7690
|
+
}
|
|
7691
|
+
if (new RegExp(`(^|\\s|not\\s+|!)${esc}(\\s|$)`).test(whens)) {
|
|
7692
|
+
inferred.push(i.name);
|
|
7693
|
+
return { ...i, type: "boolean" };
|
|
7694
|
+
}
|
|
7695
|
+
return i;
|
|
7696
|
+
});
|
|
7697
|
+
const inputs = typed.map((i) => i.type === "boolean" ? { id: i.name, kind: "yesno", label: `it is ${spaced(i.name)}`, yes: spaced(i.name), no: `not ${spaced(i.name)}` } : i.type === "number" ? { id: i.name, kind: "number", label: `the ${spaced(i.name)}` } : { id: i.name, kind: "other", label: `the ${spaced(i.name)}` });
|
|
7698
|
+
const model = {
|
|
7699
|
+
schema: PLAIN_SCHEMA,
|
|
7700
|
+
title: spaced(item2.name).replace(/^./, (c) => c.toUpperCase()),
|
|
7701
|
+
why: "",
|
|
7702
|
+
question: `How is ${spaced(item2.name)} decided?`,
|
|
7703
|
+
inputs,
|
|
7704
|
+
rules: [],
|
|
7705
|
+
otherwise: "",
|
|
7706
|
+
examples: [],
|
|
7707
|
+
provenance: "inferred-from-code",
|
|
7708
|
+
needsReview: []
|
|
7709
|
+
};
|
|
7710
|
+
const outcome = (t) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(t) || /^-?\d+(\.\d+)?$/.test(t) ? t : null;
|
|
7711
|
+
const stateFacts = [];
|
|
7712
|
+
const input = (id2) => inputs.find((i) => i.id === id2);
|
|
7713
|
+
const factFor = (path) => {
|
|
7714
|
+
const id2 = path.replace(/[^A-Za-z0-9_]/g, "_");
|
|
7715
|
+
let f = input(id2);
|
|
7716
|
+
if (!f) {
|
|
7717
|
+
const word = spaced(path.split(".").pop());
|
|
7718
|
+
f = { id: id2, kind: "yesno", label: `it is ${word}`, yes: word, no: `not ${word}`, fromState: true };
|
|
7719
|
+
if (inputs.some((i) => i.kind === "yesno" && (i.yes === f.yes || i.no === f.yes))) return null;
|
|
7720
|
+
inputs.push(f);
|
|
7721
|
+
stateFacts.push(path);
|
|
7722
|
+
}
|
|
7723
|
+
return f;
|
|
7724
|
+
};
|
|
7725
|
+
for (const r of item2.rules) {
|
|
7726
|
+
const when = r.when.trim();
|
|
7727
|
+
const join = / or /.test(when) ? "any" : "all";
|
|
7728
|
+
if (/ or /.test(when) && / and /.test(when)) return null;
|
|
7729
|
+
const conditions = [];
|
|
7730
|
+
for (const part of when.split(join === "all" ? " and " : " or ")) {
|
|
7731
|
+
const t = part.trim();
|
|
7732
|
+
let m;
|
|
7733
|
+
const input2 = (id2) => inputs.find((i) => i.id === id2);
|
|
7734
|
+
if ((m = t.match(/^(not\s+|!)?([A-Za-z_]\w*)$/)) && input2(m[2])?.kind === "yesno") conditions.push({ input: m[2], op: "is", value: !m[1] });
|
|
7735
|
+
else if ((m = t.match(/^([A-Za-z_]\w*)\s*(>=|<=|<|>|==)\s*(-?\d+(?:\.\d+)?)$/)) && input2(m[1])?.kind === "number") conditions.push({ input: m[1], op: m[2], value: Number(m[3]) });
|
|
7736
|
+
else if (m = t.match(/^([A-Za-z_][\w.]*)\s*(==|!=)\s*"([^"]*)"$/)) {
|
|
7737
|
+
let f = input2(m[1]);
|
|
7738
|
+
if (!f) {
|
|
7739
|
+
const id2 = m[1].replace(/[^A-Za-z0-9_]/g, "_");
|
|
7740
|
+
f = { id: id2, kind: "text", label: `the ${spaced(m[1].split(".").pop())}` };
|
|
7741
|
+
if (m[1].includes(".")) stateFacts.push(m[1]);
|
|
7742
|
+
inputs.push(f);
|
|
7743
|
+
}
|
|
7744
|
+
if (f.kind === "yesno" || f.kind === "number") return null;
|
|
7745
|
+
f.kind = "text";
|
|
7746
|
+
conditions.push({ input: f.id, op: m[2], value: m[3] });
|
|
7747
|
+
} else if ((m = t.match(/^(not\s+|!)?([A-Za-z_][\w.]*)$/)) && !input2(m[2])) {
|
|
7748
|
+
const f = factFor(m[2]);
|
|
7749
|
+
if (!f) return null;
|
|
7750
|
+
conditions.push({ input: f.id, op: "is", value: !m[1] });
|
|
7751
|
+
} else return null;
|
|
7752
|
+
}
|
|
7753
|
+
if (!outcome(r.result)) return null;
|
|
7754
|
+
model.rules.push({ outcome: r.result, join, conditions });
|
|
7755
|
+
}
|
|
7756
|
+
if (!outcome(item2.otherwise.result)) return null;
|
|
7757
|
+
model.otherwise = item2.otherwise.result;
|
|
7758
|
+
for (const i of inputs) {
|
|
7759
|
+
model.needsReview.push(i.kind === "yesno" ? `What does "${i.yes}" mean in business words?` : `Is ${i.label} money, a count, or something else?`);
|
|
7760
|
+
}
|
|
7761
|
+
for (const path of stateFacts) model.needsReview.push(`${spaced(path.split(".").pop())} comes from the code's own state, not from an input.`);
|
|
7762
|
+
if (item2.status === "partial") {
|
|
7763
|
+
model.partial = true;
|
|
7764
|
+
model.needsReview.unshift(`Thunder could not read ${item2.unread?.length || "some"} line(s) of this function, so the picture may be incomplete.`);
|
|
7765
|
+
}
|
|
7766
|
+
for (const name of inferred) model.needsReview.push(`The code does not declare a type for ${spaced(name)}; Thunder inferred it from how the rule uses it.`);
|
|
7767
|
+
model.needsReview.push("Why does this rule exist? Code shows what happens, not why.", "No examples yet: add cases before relying on it.");
|
|
7768
|
+
return model;
|
|
7769
|
+
}
|
|
7140
7770
|
|
|
7141
|
-
// src/
|
|
7142
|
-
var
|
|
7143
|
-
var
|
|
7144
|
-
|
|
7145
|
-
"
|
|
7146
|
-
"
|
|
7147
|
-
"
|
|
7148
|
-
"
|
|
7149
|
-
"Outcome",
|
|
7150
|
-
"Metric",
|
|
7151
|
-
"Requirement",
|
|
7152
|
-
"Constraint",
|
|
7153
|
-
"Invariant",
|
|
7154
|
-
"Guarantee",
|
|
7155
|
-
"Never",
|
|
7156
|
-
"Conflict",
|
|
7157
|
-
"Journey",
|
|
7158
|
-
"ExperienceContract",
|
|
7159
|
-
"ExperienceState",
|
|
7160
|
-
"Pattern",
|
|
7161
|
-
"DesignArtifact",
|
|
7162
|
-
"DesignComponent",
|
|
7163
|
-
"StyleIntent",
|
|
7164
|
-
"Capability",
|
|
7165
|
-
"SystemContract",
|
|
7166
|
-
"ImplementationMapping",
|
|
7167
|
-
"VerificationRule",
|
|
7168
|
-
"VerificationResult",
|
|
7169
|
-
"Approval",
|
|
7170
|
-
"Release",
|
|
7171
|
-
"OutcomeContract",
|
|
7172
|
-
"OutcomeResult",
|
|
7173
|
-
"LearningArtifact",
|
|
7174
|
-
"Unknown",
|
|
7175
|
-
"Assumption",
|
|
7176
|
-
"Question",
|
|
7177
|
-
"Lifecycle",
|
|
7178
|
-
"LifecycleState",
|
|
7179
|
-
"Temporal",
|
|
7180
|
-
"Command",
|
|
7181
|
-
"Event",
|
|
7182
|
-
"FailureHandler",
|
|
7183
|
-
"Decision",
|
|
7184
|
-
"Rule",
|
|
7185
|
-
"Skill"
|
|
7771
|
+
// src/visual.mjs
|
|
7772
|
+
var VISUAL_SCHEMA = "thunder-visual-v1";
|
|
7773
|
+
var PRINCIPLE = "We are no longer writing code for the computer. We are writing code for humans.";
|
|
7774
|
+
var FORMS = [
|
|
7775
|
+
{ id: "picture", name: "Thunder", role: "main", says: "The visual form: cards, steps, and maps. What most people read." },
|
|
7776
|
+
{ id: "text", name: "Thunder Text", role: "detail", says: "The same meaning in structured words, for reading in detail, reviewing, and storing." },
|
|
7777
|
+
{ id: "meaning", name: "The meaning", role: "model", says: "The one reading both views are made from. The picture and Thunder Text are two views of it, never translations of each other." },
|
|
7778
|
+
{ id: "source", name: "Original code", role: "evidence", says: "The code in its own language. Always one click away (View original)." }
|
|
7186
7779
|
];
|
|
7187
|
-
var
|
|
7188
|
-
"
|
|
7189
|
-
"
|
|
7190
|
-
"
|
|
7191
|
-
"
|
|
7192
|
-
"
|
|
7193
|
-
"
|
|
7194
|
-
"constrained_by",
|
|
7195
|
-
"implemented_by",
|
|
7196
|
-
"represented_by",
|
|
7197
|
-
"verified_by",
|
|
7198
|
-
"approved_by",
|
|
7199
|
-
"released_in",
|
|
7200
|
-
"resulted_in",
|
|
7201
|
-
"contradicts",
|
|
7202
|
-
"supersedes",
|
|
7203
|
-
"depends_on",
|
|
7204
|
-
"blocks",
|
|
7205
|
-
"teaches",
|
|
7206
|
-
"generated_from",
|
|
7207
|
-
"transitions_to",
|
|
7208
|
-
"requires_skill"
|
|
7780
|
+
var ZOOM = [
|
|
7781
|
+
{ level: 0, name: "App", from: "A product or a repository", element: "app", atlas: "Z0" },
|
|
7782
|
+
{ level: 1, name: "Area", from: "A feature area, service, package, or folder (Atlas; optional in Read in Thunder)", element: "area", atlas: "Z1" },
|
|
7783
|
+
{ level: 2, name: "File", from: "A file, module, or class", element: "file", atlas: "Z2" },
|
|
7784
|
+
{ level: 3, name: "Action", from: "A door into the app: an endpoint or a screen, and the handler behind it", element: "action", atlas: "Z3" },
|
|
7785
|
+
{ level: 4, name: "Rule", from: "One decision (a Thunder card) or the steps of a function", element: "decision", atlas: "Z3" },
|
|
7786
|
+
{ level: 5, name: "Original", from: "The exact lines in the original language", element: "source", atlas: "Z4" }
|
|
7209
7787
|
];
|
|
7210
|
-
var
|
|
7211
|
-
"
|
|
7212
|
-
"
|
|
7213
|
-
"
|
|
7214
|
-
"
|
|
7215
|
-
"
|
|
7216
|
-
"
|
|
7217
|
-
"
|
|
7218
|
-
"
|
|
7219
|
-
"
|
|
7220
|
-
"
|
|
7221
|
-
"
|
|
7222
|
-
|
|
7223
|
-
|
|
7788
|
+
var COLORS = {
|
|
7789
|
+
structure: { hex: "#C4B5FD", name: "violet", for: "Structure words: when, otherwise, all of these, for each" },
|
|
7790
|
+
question: { hex: "#7FB2FF", name: "blue", for: "A decision's question and branches (If)" },
|
|
7791
|
+
fact: { hex: "#FCD34D", name: "yellow", for: "Facts a rule reads, values a step works out, routes" },
|
|
7792
|
+
comparison: { hex: "#F472B6", name: "pink", for: "Comparisons and checks: at least, at most, is set" },
|
|
7793
|
+
amount: { hex: "#FDBA74", name: "orange", for: "Amounts and numbers" },
|
|
7794
|
+
outcome: { hex: "#67E8F9", name: "cyan", for: "Outcomes and what a function hands back" },
|
|
7795
|
+
name: { hex: "#BEF264", name: "lime", for: "Example names" },
|
|
7796
|
+
failure: { hex: "#FDBA74", name: "orange", for: "Ways a function fails (always with the \u2715 mark and the word Fails, which tell it apart from amounts)" },
|
|
7797
|
+
pass: { hex: "#34D399", name: "green", for: "ONLY a check that ran and passed" },
|
|
7798
|
+
fail: { hex: "#F87171", name: "red", for: "ONLY a check that ran and failed" },
|
|
7799
|
+
unread: { hex: "#9CA3AF", name: "grey, dashed", for: "Not established: not read, not confirmed, or not run" }
|
|
7800
|
+
};
|
|
7801
|
+
var LINES = {
|
|
7802
|
+
solid: "From code (read exactly) or confirmed by a person",
|
|
7803
|
+
dashed: "Not established: not read, only partly read, an AI summary, or not yet run"
|
|
7804
|
+
};
|
|
7805
|
+
var PROVENANCE = {
|
|
7806
|
+
"from-code": { label: "From code", line: "solid", says: "Read exactly from the source by the Thunder compiler, with no AI." },
|
|
7807
|
+
confirmed: { label: "Confirmed", line: "solid", says: "A person confirmed this reading is what the software should do." },
|
|
7808
|
+
"authors-note": { label: "Author's note", line: "solid", says: "The code author's own words (docstring or doc comment), verbatim. A statement, not a reading." },
|
|
7809
|
+
"ai-summary": { label: "AI summary", line: "dashed", says: "Written by AI to explain. Never evidence; the exact reading is shown beneath it." },
|
|
7810
|
+
"not-read": { label: "Not read yet", line: "dashed", says: "Thunder could not read this yet. The original code is shown instead, never a guess." }
|
|
7811
|
+
};
|
|
7812
|
+
var STEP_MARKS = {
|
|
7813
|
+
check: { mark: "\u2713", label: "Check", color: "comparison", show: "words" },
|
|
7814
|
+
branch: { mark: "\u25C7", label: "If", color: "question", show: "words" },
|
|
7815
|
+
loop: { mark: "\u21BB", label: "For each", color: "structure", show: "words" },
|
|
7816
|
+
set: { mark: "=", label: "Works out", color: "fact", show: "words" },
|
|
7817
|
+
call: { mark: "\u2192", label: "Calls", color: "outcome", show: "words" },
|
|
7818
|
+
return: { mark: "\u21E5", label: "Gives back", color: "outcome", show: "words" },
|
|
7819
|
+
fail: { mark: "\u2715", label: "Fails", color: "failure", show: "words" },
|
|
7820
|
+
try: { mark: "\u26C9", label: "Tries", color: "structure", show: "words" },
|
|
7821
|
+
restates: { mark: "\xB7", label: "Code", color: "unread", show: "code", line: "dashed" },
|
|
7822
|
+
other: { mark: "\xB7", label: "Not read yet", color: "unread", show: "code", line: "dashed" }
|
|
7823
|
+
};
|
|
7824
|
+
var ELEMENTS = {
|
|
7825
|
+
app: { zoom: 0, name: "App", shape: "map", status: "available", shows: "Its folders or areas, how many actions, decisions, and functions each holds, and what could not be read yet.", text: "App <name>" },
|
|
7826
|
+
area: { zoom: 1, name: "Area", shape: "map-region", status: "available", shows: "A folder, package, or service, with its files.", text: "Area <name>" },
|
|
7827
|
+
file: { zoom: 2, name: "File", shape: "stack", status: "available", shows: "What you can do here: every action and function in the file, in order.", text: "File <path>" },
|
|
7828
|
+
"data-shape": { zoom: 2, name: "Data shape", shape: "table-card", status: "planned", shows: "A record, class, enum, or database table: its fields, their kinds, and the allowed values.", text: "A <Name> has\n <field>, <kind>" },
|
|
7829
|
+
action: { zoom: 3, name: "Action", shape: "steps-card", badge: "route", status: "available", shows: "A door into the app (an endpoint with its method and path, or a screen), then what its handler does as steps.", text: "When someone calls <METHOD> <path>" },
|
|
7830
|
+
decision: { zoom: 4, name: "Thunder card", shape: "card", status: "available", shows: "One decision: its question, the facts it reads, each rule, the outcome otherwise, and examples you can ask.", text: "<Question>?\n <Outcome> when ...\n Otherwise, <Outcome>." },
|
|
7831
|
+
function: { zoom: 4, name: "Steps card", shape: "steps-card", status: "available", shows: "What a function does, as a short list of steps with one level of nesting.", text: "What <name> does\n - <step>" },
|
|
7832
|
+
"not-read": { zoom: 4, name: "Not-read-yet card", shape: "dashed-card", line: "dashed", status: "available", shows: "A function Thunder cannot read well yet, with its original code.", text: "Not read: <name> (see the code)" },
|
|
7833
|
+
error: { zoom: 4, name: "Failure", shape: "chip", mark: "\u2715", color: "failure", status: "available", shows: "A way the code can fail, by name.", text: "Can fail with <Name>" },
|
|
7834
|
+
test: { zoom: 4, name: "Test", shape: "chip", mark: "\u2691", color: "structure", status: "available", shows: "A test that exists. Green or red only once it has run.", text: "Test: <name>" },
|
|
7835
|
+
event: { zoom: 3, name: "Trigger", shape: "steps-card", badge: "when", status: "planned", shows: "Something that runs when an event happens (a database trigger, a message handler, a schedule).", text: "When <event>, it\n - <step>" },
|
|
7836
|
+
source: { zoom: 5, name: "Original code", shape: "code", status: "available", shows: "The exact lines, highlighted, in the original language.", text: "(the original code)" }
|
|
7837
|
+
};
|
|
7838
|
+
var LANGUAGES = {
|
|
7839
|
+
python: { name: "Python", status: "available", action: "@app.get / @router.post (FastAPI), @app.route (Flask)", decision: "a def that returns fixed answers", doc: "docstring", "data-shape": "@dataclass, pydantic BaseModel, Enum (planned)" },
|
|
7840
|
+
typescript: { name: "TypeScript", status: "available", action: "NestJS @Get/@Post, Express router.post(...)", decision: "a function that returns fixed answers", doc: "/** JSDoc */", "data-shape": "interface, type, enum (planned)" },
|
|
7841
|
+
javascript: { name: "JavaScript", status: "available", action: "Express app.get / router.post(...)", decision: "a function that returns fixed answers", doc: "/** JSDoc */", "data-shape": "classes (planned)" },
|
|
7842
|
+
go: { name: "Go", status: "available", action: "not yet (net/http, Gin planned)", decision: "a func that returns fixed answers", doc: "// comment above the func", "data-shape": "struct, const iota (planned)" },
|
|
7843
|
+
rust: { name: "Rust", status: "available", action: "not yet (Actix, Axum planned)", decision: "a fn with match or if returning fixed answers", doc: "/// doc comment", "data-shape": "struct, enum (planned)" },
|
|
7844
|
+
csharp: { name: "C#", status: "available", action: "[HttpGet] / [HttpPost]", decision: "a method that returns fixed answers", doc: "/// <summary>", "data-shape": "class, record, enum (planned)" },
|
|
7845
|
+
java: { name: "Java", status: "available", action: "@GetMapping / @PostMapping (Spring)", decision: "a method that returns fixed answers", doc: "/** Javadoc */", "data-shape": "class, record, enum (planned)" },
|
|
7846
|
+
kotlin: { name: "Kotlin", status: "available", action: "Spring annotations", decision: "a fun with when or if returning fixed answers", doc: "/** KDoc */", "data-shape": "data class, enum class (planned)" },
|
|
7847
|
+
php: { name: "PHP", status: "available", action: "#[Route] (Symfony)", decision: "a function that returns fixed answers", doc: "/** PHPDoc */", "data-shape": "class, enum (planned)" },
|
|
7848
|
+
ruby: { name: "Ruby", status: "available", action: "Sinatra get/post blocks (Rails routes.rb planned)", decision: "a def that returns fixed answers", doc: "# comment above the def", "data-shape": "class, Struct (planned)" },
|
|
7849
|
+
sql: { name: "SQL", status: "planned", action: "(none: SQL is reached through the app)", decision: "CHECK constraints, CASE expressions, IF in procedures", doc: "-- comment above, COMMENT ON", "data-shape": "CREATE TABLE / VIEW", event: "CREATE TRIGGER", steps: "SELECT / INSERT / UPDATE / DELETE: which data, filtered by which conditions, changed how" }
|
|
7850
|
+
};
|
|
7851
|
+
var RULES = [
|
|
7852
|
+
"Show the picture first, Thunder Text second, and the original code one click away.",
|
|
7853
|
+
"Never draw a guess. What Thunder cannot read is shown as Not read yet, dashed, with the original code.",
|
|
7854
|
+
"Green and red mean only a check that ran and passed or failed.",
|
|
7855
|
+
"Every element shows where it came from: From code, Confirmed, Author's note, AI summary, or Not read yet.",
|
|
7856
|
+
"An AI summary is labeled, dashed, and always sits above the exact reading it summarizes, never instead of it.",
|
|
7857
|
+
"The author's note (a docstring) is shown as the author's statement, verbatim, separate from what the code does.",
|
|
7858
|
+
"Say the action that is really possible: Propose rule change until a change is written back and checked; never Update code.",
|
|
7859
|
+
"Use the reader's words: plain names, no syntax. A step that would only restate the code shows the code instead."
|
|
7224
7860
|
];
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
|
|
7232
|
-
|
|
7233
|
-
|
|
7234
|
-
|
|
7235
|
-
|
|
7236
|
-
|
|
7237
|
-
|
|
7238
|
-
|
|
7239
|
-
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
|
|
7243
|
-
|
|
7244
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7256
|
-
|
|
7257
|
-
|
|
7258
|
-
|
|
7259
|
-
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
|
|
7263
|
-
|
|
7264
|
-
|
|
7265
|
-
|
|
7861
|
+
var words4 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
|
|
7862
|
+
function visualFor(item2) {
|
|
7863
|
+
if (!item2 || typeof item2 !== "object") throw new Error("visualFor needs a reader item.");
|
|
7864
|
+
const base = { provenance: item2.provenance === "confirmed" ? "confirmed" : "from-code", ...item2.doc ? { doc: { text: item2.doc, provenance: "authors-note" } } : {} };
|
|
7865
|
+
if (item2.kind === "error") return { element: "error", shape: "chip", line: "solid", mark: "\u2715", color: "failure", title: `Can fail with ${item2.name}`, ...base };
|
|
7866
|
+
if (item2.kind === "test") return { element: "test", shape: "chip", line: "solid", mark: "\u2691", color: "structure", title: `Test: ${item2.name}`, ...base };
|
|
7867
|
+
const badge = item2.route ? { kind: "route", text: `${item2.route.method} ${item2.route.path}`.trim() } : void 0;
|
|
7868
|
+
if (item2.kind === "decision") {
|
|
7869
|
+
const card = safePlain(item2);
|
|
7870
|
+
return { element: "decision", shape: "card", line: item2.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words4(item2.name)} decides`, ...badge ? { badge } : {}, ...item2.status === "partial" ? { note: "Partly read" } : {}, ...base };
|
|
7871
|
+
}
|
|
7872
|
+
const readable = (item2.stepsReadable ?? 0) >= 0.5 && item2.steps?.length;
|
|
7873
|
+
if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words4(item2.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
|
|
7874
|
+
return { element: item2.route ? "action" : "function", shape: "steps-card", line: "solid", title: item2.route ? `When someone calls ${badge.text}` : `What ${words4(item2.name)} does`, ...badge ? { badge } : {}, ...base };
|
|
7875
|
+
}
|
|
7876
|
+
function visualForStep(step) {
|
|
7877
|
+
const key = step?.restates ? "restates" : STEP_MARKS[step?.kind] ? step.kind : "other";
|
|
7878
|
+
const m = STEP_MARKS[key];
|
|
7879
|
+
return { mark: m.mark, label: m.label, color: m.color, show: m.show, line: m.line || "solid", text: m.show === "code" ? step.code ?? step.says : step.says };
|
|
7880
|
+
}
|
|
7881
|
+
function safePlain(item2) {
|
|
7882
|
+
try {
|
|
7883
|
+
return plainFromReading(item2);
|
|
7884
|
+
} catch {
|
|
7885
|
+
return null;
|
|
7886
|
+
}
|
|
7887
|
+
}
|
|
7888
|
+
function thunderText(item2) {
|
|
7889
|
+
const v = visualFor(item2);
|
|
7890
|
+
if (item2.kind === "error" || item2.kind === "test") return `${v.title}
|
|
7891
|
+
`;
|
|
7892
|
+
if (item2.kind === "decision") {
|
|
7893
|
+
const card = safePlain(item2);
|
|
7894
|
+
if (card) {
|
|
7895
|
+
if (item2.doc && !card.why) card.why = item2.doc;
|
|
7896
|
+
return renderPlainContract(card).replace(/\n+Examples\s*$/, "\n");
|
|
7897
|
+
}
|
|
7898
|
+
}
|
|
7899
|
+
const out = [v.title];
|
|
7900
|
+
if (item2.doc) out.push(` Author's note: "${item2.doc}"`);
|
|
7901
|
+
if (item2.inputs?.length) out.push(` Takes ${item2.inputs.map((p) => words4(p.name)).join(", ")}`);
|
|
7902
|
+
const steps = item2.steps || [];
|
|
7903
|
+
const lines = (list, depth) => {
|
|
7904
|
+
for (const st of list) {
|
|
7905
|
+
const s = visualForStep(st);
|
|
7906
|
+
const pad = " ".repeat(depth + 1);
|
|
7907
|
+
out.push(s.show === "code" ? `${pad}- \`${s.text}\` (code, not explained)` : `${pad}- ${s.text}`);
|
|
7908
|
+
if (st.children?.length) lines(st.children, depth + 1);
|
|
7909
|
+
if (st.otherwise?.length) {
|
|
7910
|
+
out.push(`${pad} Otherwise:`);
|
|
7911
|
+
lines(st.otherwise, depth + 2);
|
|
7912
|
+
}
|
|
7913
|
+
for (const h of st.handlers || []) {
|
|
7914
|
+
out.push(`${pad} ${h.says}:`);
|
|
7915
|
+
lines(h.steps, depth + 2);
|
|
7916
|
+
}
|
|
7917
|
+
if (st.always) {
|
|
7918
|
+
out.push(`${pad} Always, at the end:`);
|
|
7919
|
+
lines(st.always.steps, depth + 2);
|
|
7266
7920
|
}
|
|
7267
7921
|
}
|
|
7268
7922
|
};
|
|
7923
|
+
if (steps.length) lines(steps, 0);
|
|
7924
|
+
else if (item2.kind === "decision" && item2.rules?.length) {
|
|
7925
|
+
for (const r of item2.rules) out.push(` - ${r.result} when ${r.says ?? r.when}`);
|
|
7926
|
+
if (item2.otherwise) out.push(` - Otherwise, ${item2.otherwise.result}`);
|
|
7927
|
+
} else out.push(" Not read: see the original code.");
|
|
7928
|
+
return `${out.join("\n")}
|
|
7929
|
+
`;
|
|
7269
7930
|
}
|
|
7270
|
-
var
|
|
7271
|
-
{
|
|
7272
|
-
{
|
|
7273
|
-
{
|
|
7274
|
-
{
|
|
7275
|
-
{
|
|
7276
|
-
{
|
|
7277
|
-
{
|
|
7278
|
-
{
|
|
7279
|
-
{
|
|
7280
|
-
{
|
|
7281
|
-
{
|
|
7282
|
-
{
|
|
7283
|
-
{
|
|
7284
|
-
|
|
7285
|
-
|
|
7931
|
+
var SYMBOLS = {
|
|
7932
|
+
app: { name: "App", says: "The whole program, as a map.", color: "structure", paths: ["M6 11 L16 7 L28 11 L38 7 V33 L28 37 L16 33 L6 37 Z", "M16 7 V33 M28 11 V37"] },
|
|
7933
|
+
area: { name: "Area", says: "A part of the app that belongs together.", color: "structure", paths: ["M5 13 H17 L21 17 H39 V35 H5 Z"] },
|
|
7934
|
+
file: { name: "File", says: "One page of the program.", color: "structure", paths: ["M11 5 H27 L35 13 V39 H11 Z", "M27 5 V13 H35", "M16 22 H30 M16 28 H30 M16 34 H24"] },
|
|
7935
|
+
thing: { name: "Thing", says: "Something the app knows about. It knows stuff and can do stuff.", color: "outcome", beginner: true, paths: ["M22 5 L38 13 V31 L22 39 L6 31 V13 Z", "M6 13 L22 21 L38 13 M22 21 V39"] },
|
|
7936
|
+
data: { name: "Data", says: "Information: a record of facts, or a list of allowed choices.", color: "outcome", beginner: true, paths: ["M8 10 C8 6 36 6 36 10 V34 C36 38 8 38 8 34 Z", "M8 10 C8 14 36 14 36 10", "M8 22 C8 26 36 26 36 22"] },
|
|
7937
|
+
record: { name: "Record", says: "A Thing that only remembers facts, like an ID card.", color: "outcome", group: "data", paths: ["M9 10 H35 A4 4 0 0 1 39 14 V30 A4 4 0 0 1 35 34 H9 A4 4 0 0 1 5 30 V14 A4 4 0 0 1 9 10 Z", "M11 29 H19 M24 18 H34 M24 24 H34 M24 30 H30"], circles: [[15, 20, 4]] },
|
|
7938
|
+
choices: { name: "Choices", says: "Only one of these values is allowed.", color: "outcome", group: "data", paths: ["M10 7 H34 A4 4 0 0 1 34 15 H10 A4 4 0 0 1 10 7 Z", "M10 18 H34 A4 4 0 0 1 34 26 H10 A4 4 0 0 1 10 18 Z", "M10 29 H34 A4 4 0 0 1 34 37 H10 A4 4 0 0 1 10 29 Z"], circles: [[12, 22, 1.8]], fill: true },
|
|
7939
|
+
action: { name: "Action", says: "A door into the app: something a person can do.", color: "fact", beginner: true, paths: ["M11 39 V6 H33 V39", "M6 39 H38"], circles: [[27, 23, 1.8]], fill: true },
|
|
7940
|
+
rule: { name: "Rule", says: "A decision: look at some facts, pick one answer.", color: "question", beginner: true, paths: ["M22 4 L38 20 L22 36 L6 20 Z", "M22 36 V41 M15 29 L9 37 M29 29 L35 37"] },
|
|
7941
|
+
steps: { name: "Steps", says: "A how-to: do this, then this, then this.", color: "structure", beginner: true, paths: ["M10 5 H34 A4 4 0 0 1 38 9 V35 A4 4 0 0 1 34 39 H10 A4 4 0 0 1 6 35 V9 A4 4 0 0 1 10 5 Z", "M13 14 H14 M19 14 H31 M13 22 H14 M19 22 H31 M13 30 H14 M19 30 H27"] },
|
|
7942
|
+
setup: { name: "Starts with", says: "What a new Thing has when it is made.", color: "structure", paths: ["M22 5 V15 M22 29 V39 M5 22 H15 M29 22 H39 M10 10 L16 16 M28 28 L34 34 M34 10 L28 16 M16 28 L10 34"] },
|
|
7943
|
+
stop: { name: "Stop", says: "Something is wrong, so it stops and says why.", color: "failure", beginner: true, paths: ["M15 5 H29 L39 15 V29 L29 39 H15 L5 29 V15 Z", "M16 22 H28"] },
|
|
7944
|
+
"not-read": { name: "Not read yet", says: "Thunder shows the code, because it can't explain it yet.", color: "unread", dashed: true, paths: ["M11 5 H33 V39 H11 Z", "M17 22 H27"] }
|
|
7945
|
+
};
|
|
7946
|
+
var DOES = {
|
|
7947
|
+
start: { label: "Starts", mark: "\u25B6", color: "fact" },
|
|
7948
|
+
find: { label: "Finds", mark: "\u2315", color: "fact" },
|
|
7949
|
+
"keep-only": { label: "Keeps only", mark: "\u23DA", color: "fact" },
|
|
7950
|
+
check: { label: "Checks", mark: "\u2713", color: "comparison" },
|
|
7951
|
+
decide: { label: "Asks", mark: "\u25C7", color: "question" },
|
|
7952
|
+
calculate: { label: "Works out", mark: "=", color: "fact" },
|
|
7953
|
+
save: { label: "Saves", mark: "\u2913", color: "outcome" },
|
|
7954
|
+
send: { label: "Tells someone", mark: "\u2709", color: "outcome" },
|
|
7955
|
+
ask: { label: "Asks another part", mark: "\u21C4", color: "outcome" },
|
|
7956
|
+
repeat: { label: "For each", mark: "\u21BB", color: "structure" },
|
|
7957
|
+
answer: { label: "Gives back", mark: "\u21E5", color: "outcome" },
|
|
7958
|
+
stop: { label: "Stops", mark: "\u25A0", color: "failure", symbol: "stop" },
|
|
7959
|
+
do: { label: "Does", mark: "\u2192", color: "outcome" },
|
|
7960
|
+
code: { label: "Not read yet", mark: "\xB7", color: "unread", dashed: true }
|
|
7961
|
+
};
|
|
7962
|
+
var BEGINNER = ["thing", "action", "rule", "steps", "data", "stop"];
|
|
7963
|
+
var THUNDER_VISUAL = { schema: VISUAL_SCHEMA, principle: PRINCIPLE, forms: FORMS, zoom: ZOOM, colors: COLORS, lines: LINES, provenance: PROVENANCE, steps: STEP_MARKS, elements: ELEMENTS, languages: LANGUAGES, rules: RULES, symbols: SYMBOLS, does: DOES, beginner: BEGINNER };
|
|
7964
|
+
var STRUCTURE_WORDS = /^(?:Ask:|Yes:|No:|Otherwise:|Otherwise,|Always, at the end:|For each:|When done:|You give it:|You get back:|Takes|Author's note:|It knows|It can|One of:|We need|Examples|Why:|When someone calls|What|Thing|Record|Choices|Area|File|App|Not read)(?=\s|$)/;
|
|
7965
|
+
function thunderTokens(line) {
|
|
7966
|
+
const out = [];
|
|
7967
|
+
const push = (text, role = null) => {
|
|
7968
|
+
if (text) out.push({ text, role });
|
|
7969
|
+
};
|
|
7970
|
+
let rest2 = String(line);
|
|
7971
|
+
const lead = rest2.match(/^\s*(?:- )?/)[0];
|
|
7972
|
+
push(lead.includes("-") ? lead.slice(0, lead.indexOf("-")) : lead, null);
|
|
7973
|
+
if (lead.includes("-")) push("- ", "structure");
|
|
7974
|
+
rest2 = rest2.slice(lead.length);
|
|
7975
|
+
const lineNo = rest2.match(/\s+\(line \d+\)\s*$/);
|
|
7976
|
+
const tail = lineNo ? lineNo[0] : "";
|
|
7977
|
+
if (lineNo) rest2 = rest2.slice(0, rest2.length - tail.length);
|
|
7978
|
+
let m;
|
|
7979
|
+
if ((m = rest2.match(/^(Stop|Fails with)(:?\s*)([\w.]*)(:?\s*)(.*)$/)) && (/^Stop/.test(rest2) || /^Fails with/.test(rest2))) {
|
|
7980
|
+
push(m[1], "failure");
|
|
7981
|
+
push(m[2]);
|
|
7982
|
+
push(m[3], "failure");
|
|
7983
|
+
push(m[4]);
|
|
7984
|
+
words6(m[5]);
|
|
7985
|
+
} else if (m = rest2.match(/^(Answer:|Gives back|Returns)(\s*)(.*)$/)) {
|
|
7986
|
+
push(m[1], "structure");
|
|
7987
|
+
push(m[2]);
|
|
7988
|
+
push(m[3], "outcome");
|
|
7989
|
+
} else if (m = rest2.match(/^(Ask:)(\s*)(.*)$/)) {
|
|
7990
|
+
push(m[1], "structure");
|
|
7991
|
+
push(m[2]);
|
|
7992
|
+
words6(m[3], "question");
|
|
7993
|
+
} else if (m = rest2.match(/^`(.*)`(.*)$/)) {
|
|
7994
|
+
push(`\`${m[1]}\``, "unread");
|
|
7995
|
+
push(m[2], "unread");
|
|
7996
|
+
} else {
|
|
7997
|
+
const s = rest2.match(STRUCTURE_WORDS);
|
|
7998
|
+
if (s) {
|
|
7999
|
+
push(s[0], "structure");
|
|
8000
|
+
words6(rest2.slice(s[0].length));
|
|
8001
|
+
} else words6(rest2);
|
|
8002
|
+
}
|
|
8003
|
+
push(tail, "unread");
|
|
8004
|
+
return out;
|
|
8005
|
+
function words6(text, base = null) {
|
|
8006
|
+
const re = /("[^"]*")|(\$?-?\d[\d,]*(?:\.\d+)?%?)|\b(and|or|not|if|otherwise|for each|in|from|to|of)\b|\b(is at least|is at most|is less than|is more than|is not in|is in|is not set|is set|is not empty|is empty|is not|at least|at most|less than|more than|exactly|whether|has no)\b/g;
|
|
8007
|
+
let last = 0, x;
|
|
8008
|
+
while (x = re.exec(text)) {
|
|
8009
|
+
push(text.slice(last, x.index), base);
|
|
8010
|
+
if (x[1]) push(x[1], "name");
|
|
8011
|
+
else if (x[2]) push(x[2], "amount");
|
|
8012
|
+
else if (x[3]) push(x[3], "structure");
|
|
8013
|
+
else push(x[4], "comparison");
|
|
8014
|
+
last = x.index + x[0].length;
|
|
8015
|
+
}
|
|
8016
|
+
push(text.slice(last), base);
|
|
8017
|
+
}
|
|
8018
|
+
}
|
|
8019
|
+
|
|
8020
|
+
// src/read-repo.mjs
|
|
8021
|
+
var READ_REPO_SCHEMA = "thunder-repo-reading-v1";
|
|
8022
|
+
var EXT_LANG = [
|
|
8023
|
+
[/\.d\.ts$/i, null],
|
|
8024
|
+
[/\.min\.js$/i, null],
|
|
8025
|
+
[/\.(ts|tsx|mts|cts)$/i, "typescript"],
|
|
8026
|
+
[/\.(js|jsx|mjs|cjs)$/i, "javascript"],
|
|
8027
|
+
[/\.pyi?$/i, "python"],
|
|
8028
|
+
[/\.go$/i, "go"],
|
|
8029
|
+
[/\.rs$/i, "rust"],
|
|
8030
|
+
[/\.cs$/i, "csharp"],
|
|
8031
|
+
[/\.java$/i, "java"],
|
|
8032
|
+
[/\.kts?$/i, "kotlin"],
|
|
8033
|
+
[/\.php$/i, "php"],
|
|
8034
|
+
[/\.rb$/i, "ruby"]
|
|
8035
|
+
];
|
|
8036
|
+
var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
8037
|
+
"node_modules",
|
|
8038
|
+
".git",
|
|
8039
|
+
"dist",
|
|
8040
|
+
"build",
|
|
8041
|
+
"out",
|
|
8042
|
+
".next",
|
|
8043
|
+
".nuxt",
|
|
8044
|
+
".vercel",
|
|
8045
|
+
".turbo",
|
|
8046
|
+
"coverage",
|
|
8047
|
+
"vendor",
|
|
8048
|
+
"target",
|
|
8049
|
+
"bin",
|
|
8050
|
+
"obj",
|
|
8051
|
+
"__pycache__",
|
|
8052
|
+
".venv",
|
|
8053
|
+
"venv",
|
|
8054
|
+
"env",
|
|
8055
|
+
".tox",
|
|
8056
|
+
".mypy_cache",
|
|
8057
|
+
".gradle",
|
|
8058
|
+
".idea",
|
|
8059
|
+
".vscode",
|
|
8060
|
+
".intent",
|
|
8061
|
+
"third_party",
|
|
8062
|
+
"Pods",
|
|
8063
|
+
".terraform"
|
|
8064
|
+
]);
|
|
8065
|
+
function readableLanguage(path) {
|
|
8066
|
+
const p = String(path).replace(/\\/g, "/");
|
|
8067
|
+
if (p.split("/").some((seg) => READ_SKIP_DIRS.has(seg))) return null;
|
|
8068
|
+
for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
|
|
8069
|
+
return null;
|
|
8070
|
+
}
|
|
8071
|
+
function looksGenerated(source) {
|
|
8072
|
+
const lines = source.split("\n");
|
|
8073
|
+
if (/^\s*(\/\/|#)\s*(Code generated|@generated|<auto-generated)/im.test(lines.slice(0, 5).join("\n"))) return true;
|
|
8074
|
+
const long = lines.filter((l) => l.length > 400).length;
|
|
8075
|
+
return long > 3 && long / lines.length > 0.2;
|
|
8076
|
+
}
|
|
8077
|
+
var topFolder = (path) => {
|
|
8078
|
+
const parts = String(path).replace(/\\/g, "/").split("/");
|
|
8079
|
+
return parts.length > 1 ? parts[0] : ".";
|
|
8080
|
+
};
|
|
8081
|
+
function readRepo(files, { maxFileBytes = 4e5, maxFiles = 5e3 } = {}) {
|
|
8082
|
+
const items = [], fileSummaries = [], skipped = [];
|
|
8083
|
+
let considered = 0;
|
|
8084
|
+
for (const f of files || []) {
|
|
8085
|
+
const path = String(f.path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
8086
|
+
const language = readableLanguage(path);
|
|
8087
|
+
if (!language) continue;
|
|
8088
|
+
considered++;
|
|
8089
|
+
if (considered > maxFiles) {
|
|
8090
|
+
skipped.push({ path, reason: `More than ${maxFiles} files; read a smaller folder to include this one.` });
|
|
8091
|
+
continue;
|
|
8092
|
+
}
|
|
8093
|
+
const source = String(f.source ?? "");
|
|
8094
|
+
if (source.length > maxFileBytes || (f.size ?? 0) > maxFileBytes) {
|
|
8095
|
+
skipped.push({ path, reason: `Larger than ${Math.round(maxFileBytes / 1e3)} KB.` });
|
|
8096
|
+
continue;
|
|
8097
|
+
}
|
|
8098
|
+
if (looksGenerated(source)) {
|
|
8099
|
+
skipped.push({ path, reason: "Looks generated or minified." });
|
|
8100
|
+
continue;
|
|
8101
|
+
}
|
|
8102
|
+
let reading;
|
|
8103
|
+
try {
|
|
8104
|
+
reading = readCode(source, { language, file: path });
|
|
8105
|
+
} catch (e) {
|
|
8106
|
+
skipped.push({ path, reason: e instanceof Error ? e.message : "Could not be read." });
|
|
8107
|
+
continue;
|
|
8108
|
+
}
|
|
8109
|
+
for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
|
|
8110
|
+
fileSummaries.push({ path, language, counts: reading.counts });
|
|
8111
|
+
}
|
|
8112
|
+
return { schema: READ_REPO_SCHEMA, ...summarize(items, fileSummaries), skipped };
|
|
8113
|
+
}
|
|
8114
|
+
function summarize(items, files) {
|
|
8115
|
+
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
8116
|
+
const languages = {}, folders = {}, answers = /* @__PURE__ */ new Map(), inputs = /* @__PURE__ */ new Map();
|
|
8117
|
+
for (const f of files) {
|
|
8118
|
+
languages[f.language] = (languages[f.language] || 0) + 1;
|
|
8119
|
+
const top = topFolder(f.path);
|
|
8120
|
+
folders[top] = (folders[top] || 0) + 1;
|
|
8121
|
+
}
|
|
8122
|
+
for (const it of items) {
|
|
8123
|
+
counts[it.kind]++;
|
|
8124
|
+
if (it.status === "partial") counts.partial++;
|
|
8125
|
+
if (it.guards?.length) counts.guarded++;
|
|
8126
|
+
if (it.route) counts.route++;
|
|
8127
|
+
const guardAnswers = (it.guards || []).filter((g) => ["fails", "responds", "returns"].includes(g.effect.kind)).map((g) => g.effect.name);
|
|
8128
|
+
if (it.kind !== "decision" && !guardAnswers.length) continue;
|
|
8129
|
+
for (const result of new Set([...(it.rules || []).map((r) => r.result), it.otherwise?.result, ...guardAnswers].filter(Boolean))) {
|
|
8130
|
+
if (!answers.has(result)) answers.set(result, []);
|
|
8131
|
+
answers.get(result).push(it.id);
|
|
8132
|
+
}
|
|
8133
|
+
if (it.kind !== "decision") continue;
|
|
8134
|
+
for (const p of it.inputs || []) {
|
|
8135
|
+
if (!inputs.has(p.name)) inputs.set(p.name, []);
|
|
8136
|
+
inputs.get(p.name).push(it.id);
|
|
8137
|
+
}
|
|
8138
|
+
}
|
|
8139
|
+
const byUse = (m) => [...m].map(([name, ids]) => ({ name, decisions: ids })).sort((a, b) => b.decisions.length - a.decisions.length || a.name.localeCompare(b.name));
|
|
8140
|
+
return { files, items, counts, languages, folders, answers: byUse(answers), inputs: byUse(inputs) };
|
|
8141
|
+
}
|
|
8142
|
+
function searchRepo(index, { query = "", kinds = [], status = [], languages = [], path = "", answer = "", input = "" } = {}) {
|
|
8143
|
+
const terms = String(query).trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
8144
|
+
const prefix = String(path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
8145
|
+
return index.items.filter((it) => {
|
|
8146
|
+
if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes("guard") && it.guards?.length) && !(kinds.includes("route") && it.route)) return false;
|
|
8147
|
+
if (status.length && !status.includes(it.status)) return false;
|
|
8148
|
+
if (languages.length && !languages.includes(it.language)) return false;
|
|
8149
|
+
if (prefix && !it.file.startsWith(prefix)) return false;
|
|
8150
|
+
if (answer && !((it.rules || []).some((r) => r.result === answer) || it.otherwise?.result === answer || (it.guards || []).some((g) => g.effect.name === answer))) return false;
|
|
8151
|
+
if (input && !(it.inputs || []).some((p) => p.name === input)) return false;
|
|
8152
|
+
if (!terms.length) return true;
|
|
8153
|
+
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].filter(Boolean).join(" ").toLowerCase();
|
|
8154
|
+
return terms.every((t) => hay.includes(t));
|
|
8155
|
+
});
|
|
8156
|
+
}
|
|
8157
|
+
function groupByFile(items) {
|
|
8158
|
+
const groups = /* @__PURE__ */ new Map();
|
|
8159
|
+
for (const it of items) {
|
|
8160
|
+
if (!groups.has(it.file)) groups.set(it.file, []);
|
|
8161
|
+
groups.get(it.file).push(it);
|
|
8162
|
+
}
|
|
8163
|
+
return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
|
|
8164
|
+
}
|
|
8165
|
+
|
|
8166
|
+
// src/model.mjs
|
|
8167
|
+
var MODEL_SCHEMA = "thunder-model-v1";
|
|
8168
|
+
var THING_LANGUAGES = ["python", "typescript", "javascript"];
|
|
8169
|
+
var words5 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
|
|
8170
|
+
var cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
8171
|
+
var stripQuotes2 = (v) => v.replace(/^[rbuf]*(["'`])(.*)\1$/s, "$2");
|
|
8172
|
+
function startValue(expr, params = {}) {
|
|
8173
|
+
const e = String(expr ?? "").trim();
|
|
8174
|
+
if (!e) return null;
|
|
8175
|
+
if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, "")} unless told otherwise` : "given when it starts";
|
|
8176
|
+
if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+)$/.test(e)) return "empty at first";
|
|
8177
|
+
if (/^(None|null|undefined)$/.test(e)) return "nothing at first";
|
|
8178
|
+
if (/^(True|true)$/.test(e)) return "yes at first";
|
|
8179
|
+
if (/^(False|false)$/.test(e)) return "no at first";
|
|
8180
|
+
if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
|
|
8181
|
+
if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes2(e)}" at first`;
|
|
8182
|
+
const en = e.match(/^[A-Z]\w*\.([A-Z][A-Z0-9_]+)$/);
|
|
8183
|
+
if (en) return `${words5(en[1])} at first`;
|
|
8184
|
+
return "worked out when it starts";
|
|
8185
|
+
}
|
|
8186
|
+
var KIND_WORDS = [
|
|
8187
|
+
[/^(int|float|number|double|long|decimal|Decimal|bigint)$/i, "a number"],
|
|
8188
|
+
[/^(str|string|String|text)$/i, "words"],
|
|
8189
|
+
[/^(bool|boolean)$/i, "yes or no"],
|
|
8190
|
+
[/^(date|datetime|Date|LocalDate|Instant)$/i, "a date"]
|
|
8191
|
+
];
|
|
8192
|
+
function kindWords(type) {
|
|
8193
|
+
const t = String(type ?? "").trim();
|
|
8194
|
+
if (!t) return null;
|
|
8195
|
+
for (const [re, w] of KIND_WORDS) if (re.test(t)) return w;
|
|
8196
|
+
const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^Array<(.+)>$|^(.+)\[\]$/);
|
|
8197
|
+
if (list) return `a list of ${(list[1] || list[2] || list[3]).trim()}s`;
|
|
8198
|
+
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
|
|
8199
|
+
if (opt) return `${kindWords(opt[1] || opt[2] || opt[3]) ?? `a ${opt[1] || opt[2] || opt[3]}`}, or nothing`;
|
|
8200
|
+
return /^[A-Z]/.test(t) ? `a ${t}` : null;
|
|
8201
|
+
}
|
|
8202
|
+
function pythonThings(src, file) {
|
|
8203
|
+
const lines = src.split("\n");
|
|
8204
|
+
const out = [];
|
|
8205
|
+
for (let i = 0; i < lines.length; i++) {
|
|
8206
|
+
const m = lines[i].match(/^(\s*)class\s+(\w+)\s*(?:\(([^)]*)\))?\s*:/);
|
|
8207
|
+
if (!m) continue;
|
|
8208
|
+
const indent = m[1].length;
|
|
8209
|
+
const decorators = [];
|
|
8210
|
+
for (let k = i - 1; k >= 0 && /^\s*@/.test(lines[k]); k--) decorators.unshift(lines[k].trim());
|
|
8211
|
+
let end = i;
|
|
8212
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
8213
|
+
if (!lines[j].trim() || /^\s*#/.test(lines[j])) continue;
|
|
8214
|
+
if (lines[j].match(/^\s*/)[0].length <= indent) break;
|
|
8215
|
+
end = j;
|
|
8216
|
+
}
|
|
8217
|
+
const body = lines.slice(i + 1, end + 1);
|
|
8218
|
+
const bodyIndent = (body.find((l) => l.trim()) || "").match(/^\s*/)[0].length;
|
|
8219
|
+
const top = body.map((l, k) => ({ text: l, line: i + 2 + k })).filter((l) => l.text.trim() && l.text.match(/^\s*/)[0].length === bodyIndent);
|
|
8220
|
+
const bases = (m[3] || "").split(",").map((b) => b.trim());
|
|
8221
|
+
const isEnum = bases.some((b) => /(^|\.)(Enum|IntEnum|StrEnum|Flag)$/.test(b));
|
|
8222
|
+
const isRecord = !isEnum && (decorators.some((d) => /@(dataclasses\.)?dataclass\b|@attr\.s\b|@define\b/.test(d)) || bases.some((b) => /(BaseModel|NamedTuple|TypedDict|Schema)$/.test(b)));
|
|
8223
|
+
const docLine = top[0] && top[0].text.trim().match(/^[rRuU]?("""|'''|"|')(.*?)(\1)?$/);
|
|
8224
|
+
const doc = docLine ? (docLine[3] ? docLine[2].trim() : docLine[2].trim()) || null : null;
|
|
8225
|
+
const thing = { kind: isEnum ? "choices" : isRecord ? "record" : "thing", name: m[2], file, lines: [i + 1, end + 1], indent, ...doc ? { doc } : {}, knows: [], choices: [] };
|
|
8226
|
+
for (const l of top) {
|
|
8227
|
+
const t = l.text.trim();
|
|
8228
|
+
if (/^(def|async def|class|@|"""|'''|#)/.test(t)) continue;
|
|
8229
|
+
let f;
|
|
8230
|
+
if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes2(f[2].trim()) : words5(f[1]));
|
|
8231
|
+
else if (f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/)) thing.knows.push({ name: f[1], label: words5(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
|
|
8232
|
+
}
|
|
8233
|
+
const init = body.findIndex((l) => /^\s*def\s+__init__\s*\(/.test(l));
|
|
8234
|
+
if (init >= 0) {
|
|
8235
|
+
const sig = body.slice(init).join("\n").match(/def\s+__init__\s*\(([^)]*)\)/s);
|
|
8236
|
+
const params = {};
|
|
8237
|
+
for (const p of (sig?.[1] || "").split(",").map((x) => x.trim()).filter((x) => x && x !== "self")) {
|
|
8238
|
+
const pm = p.match(/^(\w+)(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/);
|
|
8239
|
+
if (pm) params[pm[1]] = pm[2] ?? null;
|
|
8240
|
+
}
|
|
8241
|
+
const initIndent = body[init].match(/^\s*/)[0].length;
|
|
8242
|
+
for (let k = init + 1; k < body.length; k++) {
|
|
8243
|
+
const ln = body[k];
|
|
8244
|
+
if (ln.trim() && ln.match(/^\s*/)[0].length <= initIndent) break;
|
|
8245
|
+
const a = ln.trim().match(/^self\.(\w+)\s*(?::\s*([^=]+))?=\s*(.+)$/);
|
|
8246
|
+
if (a && !thing.knows.some((x) => x.name === a[1])) {
|
|
8247
|
+
const pType = /^\w+$/.test(a[3].trim()) ? (sig?.[1] || "").match(new RegExp(`\\b${a[3].trim()}\\s*:\\s*([\\w\\[\\]. |]+)`))?.[1] : void 0;
|
|
8248
|
+
thing.knows.push({ name: a[1], label: words5(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? "a list" : null), start: startValue(a[3], params), line: i + 2 + k });
|
|
8249
|
+
}
|
|
8250
|
+
}
|
|
8251
|
+
}
|
|
8252
|
+
out.push(thing);
|
|
8253
|
+
}
|
|
8254
|
+
return out;
|
|
8255
|
+
}
|
|
8256
|
+
function braceEnd(src, open) {
|
|
8257
|
+
let depth = 0;
|
|
8258
|
+
for (let i = open; i < src.length; i++) {
|
|
8259
|
+
const c = src[i];
|
|
8260
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
8261
|
+
const q = c;
|
|
8262
|
+
for (i++; i < src.length && src[i] !== q; i++) if (src[i] === "\\") i++;
|
|
8263
|
+
continue;
|
|
8264
|
+
}
|
|
8265
|
+
if (c === "{") depth++;
|
|
8266
|
+
else if (c === "}" && --depth === 0) return i;
|
|
8267
|
+
}
|
|
8268
|
+
return -1;
|
|
8269
|
+
}
|
|
8270
|
+
var lineOf2 = (src, idx) => src.slice(0, idx).split("\n").length;
|
|
8271
|
+
function tsThings(src, file) {
|
|
8272
|
+
const out = [];
|
|
8273
|
+
const re = /(?:^|\n)[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|enum)\s+(\w+)[^{]*\{/g;
|
|
8274
|
+
let m;
|
|
8275
|
+
while (m = re.exec(src)) {
|
|
8276
|
+
const open = m.index + m[0].length - 1;
|
|
8277
|
+
const close = braceEnd(src, open);
|
|
8278
|
+
if (close < 0) continue;
|
|
8279
|
+
const body = src.slice(open + 1, close);
|
|
8280
|
+
const startLine = lineOf2(src, m.index + (m[0].startsWith("\n") ? 1 : 0));
|
|
8281
|
+
const before = src.slice(0, m.index).split("\n").slice(-4).join("\n");
|
|
8282
|
+
const docm = before.match(/\/\*\*([\s\S]*?)\*\/\s*$/);
|
|
8283
|
+
const doc = docm ? docm[1].split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim()).filter((l) => l && !l.startsWith("@")).join(" ") || null : null;
|
|
8284
|
+
const thing = { kind: m[1] === "enum" ? "choices" : m[1] === "interface" ? "record" : "thing", name: m[2], file, lines: [startLine, lineOf2(src, close)], ...doc ? { doc } : {}, knows: [], choices: [] };
|
|
8285
|
+
if (m[1] === "enum") {
|
|
8286
|
+
for (const part of body.split(",")) {
|
|
8287
|
+
const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s);
|
|
8288
|
+
if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes2(e[2].trim()) : words5(e[1]));
|
|
8289
|
+
}
|
|
8290
|
+
} else {
|
|
8291
|
+
let depth = 0, own = "";
|
|
8292
|
+
for (const c of body) {
|
|
8293
|
+
if (c === "{") depth++;
|
|
8294
|
+
if (depth === 0) own += c;
|
|
8295
|
+
if (c === "}") depth--;
|
|
8296
|
+
}
|
|
8297
|
+
const ownLines = own.split(/[;\n]/).map((l) => l.trim()).filter(Boolean);
|
|
8298
|
+
for (const l of ownLines) {
|
|
8299
|
+
const f = l.match(/^(?:(?:public|private|protected|readonly|static|declare)\s+)*(\w+)(\?)?\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/) || l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*(\w+)()\s*=\s*(.+)$/);
|
|
8300
|
+
if (!f || /\(/.test(f[1])) continue;
|
|
8301
|
+
const hasType = f.length > 4 && f[3] && !l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*\w+\s*=/);
|
|
8302
|
+
thing.knows.push({ name: f[1], label: words5(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? f[4] ? startValue(f[4]) : null : startValue(f[3]), line: null });
|
|
8303
|
+
}
|
|
8304
|
+
const ctor = body.match(/constructor\s*\(([^)]*)\)\s*\{/);
|
|
8305
|
+
if (ctor) {
|
|
8306
|
+
const params = {};
|
|
8307
|
+
for (const p of ctor[1].split(",").map((x) => x.trim()).filter(Boolean)) {
|
|
8308
|
+
const pm = p.match(/^(?:(?:public|private|protected|readonly)\s+)*(\w+)\??(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/);
|
|
8309
|
+
if (pm) params[pm[1]] = pm[2] ?? null;
|
|
8310
|
+
}
|
|
8311
|
+
const cOpen = body.indexOf("{", ctor.index + ctor[0].length - 1);
|
|
8312
|
+
const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
|
|
8313
|
+
for (const a of cBody.matchAll(/this\.(\w+)\s*=\s*([^;\n]+)/g)) {
|
|
8314
|
+
if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words5(a[1]), kind: null, start: startValue(a[2], params), line: null });
|
|
8315
|
+
else {
|
|
8316
|
+
const k = thing.knows.find((x) => x.name === a[1]);
|
|
8317
|
+
if (!k.start) k.start = startValue(a[2], params);
|
|
8318
|
+
}
|
|
8319
|
+
}
|
|
8320
|
+
}
|
|
8321
|
+
}
|
|
8322
|
+
out.push(thing);
|
|
8323
|
+
}
|
|
8324
|
+
return out;
|
|
8325
|
+
}
|
|
8326
|
+
function stepDoes(step) {
|
|
8327
|
+
const s = step.says || "", c = step.callee || "";
|
|
8328
|
+
if (step.restates || step.kind === "other") return "code";
|
|
8329
|
+
if (step.kind === "fail") return "stop";
|
|
8330
|
+
if (step.kind === "loop") return "repeat";
|
|
8331
|
+
if (step.kind === "return") return "answer";
|
|
8332
|
+
if (step.kind === "check") return "check";
|
|
8333
|
+
if (step.kind === "branch") return "decide";
|
|
8334
|
+
if (/^Writes to the database|^(Records|Adds to|Removes)/.test(s)) return "save";
|
|
8335
|
+
if (/^(Sends an email|Announces an event|Writes a log)/.test(s)) return "send";
|
|
8336
|
+
if (/^(Calls another service|Calls Stripe)/.test(s)) return "ask";
|
|
8337
|
+
if (/\b(filter|where|select|query|find|get|fetch|load|read|search|lookup|scalars|all)\b/i.test(c) || /the items in .* where|the first item in|the .* entry in|the .* with /.test(s)) return /\b(filter|where)\b/i.test(c) || / where /.test(s) ? "keep-only" : "find";
|
|
8338
|
+
if (step.kind === "set") return "calculate";
|
|
8339
|
+
return "do";
|
|
8340
|
+
}
|
|
8341
|
+
var possessive = (text) => String(text).replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => /^(self|this)$/.test(a) ? `the ${words5(b)}` : `the ${words5(a)}'s ${words5(b)}`).replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words5(m));
|
|
8342
|
+
var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : cap(words5(r));
|
|
8343
|
+
function askAsQuestion(step, ruleLabel) {
|
|
8344
|
+
let c = String(step.says).replace(/^If /, "").replace(/ \(\d+ steps? inside\)$/, "").trim();
|
|
8345
|
+
let flip = false;
|
|
8346
|
+
if (/^not: /.test(c)) {
|
|
8347
|
+
c = c.slice(5);
|
|
8348
|
+
flip = true;
|
|
8349
|
+
}
|
|
8350
|
+
if (ruleLabel) {
|
|
8351
|
+
const negated = /^not\b|^!/.test(String(step.code || "").replace(/^\s*if\s*\(?\s*/, "")) || /\bnot\s+(self|this)\./.test(step.code || "") || /!\s*(this|self)\./.test(step.code || "");
|
|
8352
|
+
return { text: `${ruleLabel.replace(/\?$/, "")}?`, flip: negated };
|
|
8353
|
+
}
|
|
8354
|
+
let m;
|
|
8355
|
+
if (m = c.match(/^not (.+)$/)) {
|
|
8356
|
+
c = m[1];
|
|
8357
|
+
flip = !flip;
|
|
8358
|
+
}
|
|
8359
|
+
if (m = c.match(/^(.+?) is not (.+)$/)) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip: !flip };
|
|
8360
|
+
if (m = c.match(/^(.+?) has no (.+)$/)) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip: !flip };
|
|
8361
|
+
if (m = c.match(/^(.+?) is (.+)$/)) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip };
|
|
8362
|
+
if (m = c.match(/^(.+?) has (.+)$/)) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip };
|
|
8363
|
+
return { text: `${cap(possessive(c))}?`, flip };
|
|
8364
|
+
}
|
|
8365
|
+
function ruleFlow(item2, start) {
|
|
8366
|
+
const nodes2 = [], edges = [];
|
|
8367
|
+
let n = 0;
|
|
8368
|
+
const node2 = (kind, text, extra = {}) => {
|
|
8369
|
+
const id2 = `n${n++}`;
|
|
8370
|
+
nodes2.push({ id: id2, kind, text, row: nodes2.length, ...extra });
|
|
8371
|
+
return id2;
|
|
8372
|
+
};
|
|
8373
|
+
let prev = node2("start", start, { lane: 0, does: "start" });
|
|
8374
|
+
let label;
|
|
8375
|
+
for (const r of item2.rules || []) {
|
|
8376
|
+
const d = node2("decision", `${cap(possessive(r.says ?? r.when))}?`, { lane: 0, line: r.line, does: "decide" });
|
|
8377
|
+
edges.push({ from: prev, to: d, ...label ? { label } : {} });
|
|
8378
|
+
const out = node2("end", answerWords(r.result), { lane: 1, line: r.line, does: "answer", answer: true, value: r.result });
|
|
8379
|
+
edges.push({ from: d, to: out, label: "yes" });
|
|
8380
|
+
prev = d;
|
|
8381
|
+
label = "no";
|
|
8382
|
+
}
|
|
8383
|
+
if (item2.otherwise) {
|
|
8384
|
+
const o = node2("end", answerWords(item2.otherwise.result), { lane: 0, line: item2.otherwise.line, does: "answer", answer: true, otherwise: true, value: item2.otherwise.result });
|
|
8385
|
+
edges.push({ from: prev, to: o, ...label ? { label } : {} });
|
|
8386
|
+
}
|
|
8387
|
+
const decisions = nodes2.filter((x) => x.kind === "decision");
|
|
8388
|
+
const answers = nodes2.filter((x) => x.answer && !x.otherwise);
|
|
8389
|
+
const fallback = nodes2.find((x) => x.otherwise);
|
|
8390
|
+
const chain = (i) => i < decisions.length ? [{ id: decisions[i].id, yes: [{ id: answers[i].id }], no: chain(i + 1) }] : fallback ? [{ id: fallback.id }] : [];
|
|
8391
|
+
return { nodes: nodes2, edges, blocks: chain(0) };
|
|
8392
|
+
}
|
|
8393
|
+
function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(), memberLabel = /* @__PURE__ */ new Map() } = {}) {
|
|
8394
|
+
const nodes2 = [], edges = [];
|
|
8395
|
+
let n = 0;
|
|
8396
|
+
const node2 = (kind, text, extra = {}) => {
|
|
8397
|
+
const id2 = `n${n++}`;
|
|
8398
|
+
nodes2.push({ id: id2, kind, text, ...extra });
|
|
8399
|
+
return id2;
|
|
8400
|
+
};
|
|
8401
|
+
const connect = (open2, to) => {
|
|
8402
|
+
for (const o of open2) edges.push({ from: o.id, to, ...o.label ? { label: o.label } : {} });
|
|
8403
|
+
};
|
|
8404
|
+
const usesOf = (st) => {
|
|
8405
|
+
for (const c of String(st.code || "").matchAll(/(?:\b(?:self|this)\.)?\b([A-Za-z_]\w*)\s*\(/g)) {
|
|
8406
|
+
const id2 = memberIndex.get(c[1].toLowerCase());
|
|
8407
|
+
if (id2) return id2;
|
|
8408
|
+
}
|
|
8409
|
+
return null;
|
|
8410
|
+
};
|
|
8411
|
+
const walk = (list, open2, lane) => {
|
|
8412
|
+
const blocks3 = [];
|
|
8413
|
+
for (const st of list) {
|
|
8414
|
+
const does = stepDoes(st);
|
|
8415
|
+
const base = { line: st.line, lane, does, ...usesOf(st) ? { uses: usesOf(st) } : {} };
|
|
8416
|
+
if (st.kind === "branch") {
|
|
8417
|
+
const { text, flip } = askAsQuestion(st, base.uses && memberLabel.get(base.uses));
|
|
8418
|
+
const [into, past] = flip ? ["no", "yes"] : ["yes", "no"];
|
|
8419
|
+
const d = node2("decision", text, base);
|
|
8420
|
+
connect(open2, d);
|
|
8421
|
+
const inside = walk(st.children || [], [{ id: d, label: into }], lane + 1);
|
|
8422
|
+
const other = st.otherwise?.length ? walk(st.otherwise, [{ id: d, label: past }], lane + 1) : { open: [{ id: d, label: past }], blocks: [] };
|
|
8423
|
+
blocks3.push({ id: d, [into]: inside.blocks, [past]: other.blocks });
|
|
8424
|
+
open2 = [...other.open, ...inside.open];
|
|
8425
|
+
} else if (st.kind === "loop") {
|
|
8426
|
+
const l = node2("loop", st.says, base);
|
|
8427
|
+
connect(open2, l);
|
|
8428
|
+
const body = walk(st.children || [], [{ id: l, label: "each" }], lane + 1);
|
|
8429
|
+
for (const b of body.open) edges.push({ from: b.id, to: l, label: "next" });
|
|
8430
|
+
blocks3.push({ id: l, each: body.blocks });
|
|
8431
|
+
open2 = [{ id: l, label: "done" }];
|
|
8432
|
+
} else if (st.kind === "fail") {
|
|
8433
|
+
const sn = node2("stop", st.says.replace(/^Fails with /, "Stop: "), base);
|
|
8434
|
+
connect(open2, sn);
|
|
8435
|
+
blocks3.push({ id: sn });
|
|
8436
|
+
open2 = [];
|
|
8437
|
+
} else if (st.kind === "return") {
|
|
8438
|
+
const e = node2("end", st.restates ? st.code : st.says.replace(/^Returns /, "Gives back "), { ...base, ...st.restates ? { code: true } : {} });
|
|
8439
|
+
connect(open2, e);
|
|
8440
|
+
blocks3.push({ id: e });
|
|
8441
|
+
open2 = [];
|
|
8442
|
+
} else if (st.kind === "try") {
|
|
8443
|
+
const t = node2("step", st.says, base);
|
|
8444
|
+
connect(open2, t);
|
|
8445
|
+
const body = walk(st.children || [], [{ id: t }], lane);
|
|
8446
|
+
let after = body.open;
|
|
8447
|
+
const handlers = [];
|
|
8448
|
+
for (const h of st.handlers || []) {
|
|
8449
|
+
const hn = node2("decision", `${h.says}?`, { line: h.line, lane: lane + 1, does: "decide", handler: true });
|
|
8450
|
+
edges.push({ from: t, to: hn, label: "error" });
|
|
8451
|
+
const hw = walk(h.steps, [{ id: hn, label: "yes" }], lane + 1);
|
|
8452
|
+
handlers.push({ id: hn, blocks: hw.blocks });
|
|
8453
|
+
after = [...after, ...hw.open];
|
|
8454
|
+
}
|
|
8455
|
+
let always = null;
|
|
8456
|
+
if (st.always) {
|
|
8457
|
+
const an = node2("step", "Always, at the end", { line: st.always.line, lane, does: "do", always: true });
|
|
8458
|
+
connect(after, an);
|
|
8459
|
+
const aw = walk(st.always.steps, [{ id: an }], lane);
|
|
8460
|
+
always = { id: an, blocks: aw.blocks };
|
|
8461
|
+
after = aw.open;
|
|
8462
|
+
}
|
|
8463
|
+
blocks3.push({ id: t, body: body.blocks, ...handlers.length ? { handlers } : {}, ...always ? { always } : {} });
|
|
8464
|
+
open2 = after;
|
|
8465
|
+
} else {
|
|
8466
|
+
const k = node2(does === "code" ? "code" : "step", does === "code" ? st.code ?? st.says : st.says, base);
|
|
8467
|
+
connect(open2, k);
|
|
8468
|
+
open2 = [{ id: k }];
|
|
8469
|
+
if (st.children?.length) {
|
|
8470
|
+
const inner = walk(st.children, open2, lane + 1);
|
|
8471
|
+
blocks3.push({ id: k, body: inner.blocks });
|
|
8472
|
+
open2 = inner.open;
|
|
8473
|
+
} else blocks3.push({ id: k });
|
|
8474
|
+
}
|
|
8475
|
+
}
|
|
8476
|
+
return { open: open2, blocks: blocks3 };
|
|
8477
|
+
};
|
|
8478
|
+
const s0 = node2("start", start, { lane: 0, does: "start" });
|
|
8479
|
+
const { open, blocks: blocks2 } = walk(steps || [], [{ id: s0 }], 0);
|
|
8480
|
+
if (open.length) connect(open, node2("end", "Done", { lane: 0, does: "answer" }));
|
|
8481
|
+
nodes2.forEach((x, i) => {
|
|
8482
|
+
x.row = i;
|
|
8483
|
+
});
|
|
8484
|
+
return { nodes: nodes2, edges, blocks: blocks2 };
|
|
8485
|
+
}
|
|
8486
|
+
var idOf = (...parts) => parts.join("#").replace(/\s+/g, "");
|
|
8487
|
+
function thunderModel(files, { name = "app" } = {}) {
|
|
8488
|
+
const things = [], members = [], links = [], unknowns = [], fileInfo = [];
|
|
8489
|
+
for (const f of files) {
|
|
8490
|
+
const language = readableLanguage(f.path);
|
|
8491
|
+
if (!language || !f.source) continue;
|
|
8492
|
+
let reading;
|
|
8493
|
+
try {
|
|
8494
|
+
reading = readCode(f.source, { language, file: f.path });
|
|
8495
|
+
} catch (e) {
|
|
8496
|
+
unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` });
|
|
8497
|
+
continue;
|
|
8498
|
+
}
|
|
8499
|
+
let fileThings = [];
|
|
8500
|
+
try {
|
|
8501
|
+
fileThings = language === "python" ? pythonThings(f.source, f.path) : THING_LANGUAGES.includes(language) ? tsThings(f.source, f.path) : [];
|
|
8502
|
+
} catch (e) {
|
|
8503
|
+
unknowns.push({ file: f.path, line: 1, why: `Classes in this file could not be drawn as Things: ${e.message}` });
|
|
8504
|
+
}
|
|
8505
|
+
if (!THING_LANGUAGES.includes(language) && /\b(class|struct|record|enum|interface|data class)\s+[A-Z]/.test(f.source)) {
|
|
8506
|
+
unknowns.push({ file: f.path, line: 1, why: `Classes, records, and choices in ${language} are not drawn as Things yet; their functions are read.` });
|
|
8507
|
+
}
|
|
8508
|
+
for (const t of fileThings) {
|
|
8509
|
+
t.id = idOf(f.path, t.name);
|
|
8510
|
+
t.label = cap(words5(t.name));
|
|
8511
|
+
t.can = [];
|
|
8512
|
+
things.push(t);
|
|
8513
|
+
}
|
|
8514
|
+
const moduleDoc = language === "python" ? (f.source.match(/^\s*(?:#.*\n|\s*\n)*[rRuU]?("""|''')([\s\S]*?)\1/)?.[2] ?? "").trim().split(/\n\s*\n/)[0].replace(/\s+/g, " ") : "";
|
|
8515
|
+
fileInfo.push({ path: f.path, language, ...moduleDoc ? { purpose: moduleDoc } : {} });
|
|
8516
|
+
const fns = reading.items.filter((i) => i.kind === "function" || i.kind === "decision");
|
|
8517
|
+
const fileMembers = fns.map((item2) => {
|
|
8518
|
+
const owner = fileThings.filter((t) => item2.line > t.lines[0] && item2.line <= t.lines[1]).sort((a, b) => b.lines[0] - a.lines[0])[0];
|
|
8519
|
+
const v = visualFor(item2);
|
|
8520
|
+
const setup = /^(__init__|constructor|init|New)$/.test(item2.name) && owner;
|
|
8521
|
+
const kind = setup ? "setup" : v.element === "action" ? "action" : v.element === "decision" ? "rule" : v.element === "not-read" ? "not-read" : "steps";
|
|
8522
|
+
const bodyEnd2 = item2.anchor?.bodyLines?.[1] ?? Math.max(item2.line, ...(item2.rules || []).map((r) => r.line || 0), item2.otherwise?.line || 0);
|
|
8523
|
+
let rule = null;
|
|
8524
|
+
if (kind === "rule") {
|
|
8525
|
+
try {
|
|
8526
|
+
rule = plainFromReading(item2);
|
|
8527
|
+
} catch {
|
|
8528
|
+
rule = null;
|
|
8529
|
+
}
|
|
8530
|
+
}
|
|
8531
|
+
const m = {
|
|
8532
|
+
id: idOf(f.path, owner?.name ?? "", item2.name, item2.line),
|
|
8533
|
+
kind,
|
|
8534
|
+
name: item2.name,
|
|
8535
|
+
label: setup ? `A new ${owner.label} starts with` : cap(words5(item2.name.replace(/^__|__$/g, ""))),
|
|
8536
|
+
...owner ? { owner: owner.id } : {},
|
|
8537
|
+
file: f.path,
|
|
8538
|
+
language,
|
|
8539
|
+
lines: [item2.line, bodyEnd2],
|
|
8540
|
+
...item2.doc ? { doc: item2.doc } : {},
|
|
8541
|
+
...item2.route ? { route: `${item2.route.method} ${item2.route.path}`.trim() } : {},
|
|
8542
|
+
youGive: (item2.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name)).map((p) => words5(p.name)),
|
|
8543
|
+
...item2.returns && kind !== "rule" ? { youGetBack: kindWords(item2.returns) ?? item2.returns } : {},
|
|
8544
|
+
...rule ? { rule, question: rule.question } : {},
|
|
8545
|
+
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
8546
|
+
...kind === "rule" ? { yesNo: [...(item2.rules || []).map((r) => r.result), item2.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {},
|
|
8547
|
+
_steps: item2.steps || [],
|
|
8548
|
+
_item: item2
|
|
8549
|
+
};
|
|
8550
|
+
if (owner) owner.can.push(m.id);
|
|
8551
|
+
if (kind === "not-read") unknowns.push({ id: m.id, file: f.path, line: item2.line, why: "Thunder cannot explain this function yet; its code is shown instead." });
|
|
8552
|
+
return m;
|
|
8553
|
+
});
|
|
8554
|
+
const byName = new Map(fileMembers.map((m) => [m.name.toLowerCase(), m.id]));
|
|
8555
|
+
const labels = new Map(fileMembers.map((m) => [m.id, m.label]));
|
|
8556
|
+
for (const m of fileMembers) {
|
|
8557
|
+
const start = m.youGive.length ? `You give it: ${m.youGive.join(", ")}` : "Start";
|
|
8558
|
+
m.flow = m.kind === "rule" || m._item.kind === "decision" && m._item.rules?.length ? ruleFlow(m._item, start) : flowOf(m._steps, { start, memberIndex: byName, memberLabel: labels });
|
|
8559
|
+
for (const nd of m.flow.nodes) if (nd.uses && nd.uses !== m.id) links.push({ from: m.id, to: nd.uses, kind: "uses", node: nd.id });
|
|
8560
|
+
delete m._steps;
|
|
8561
|
+
delete m._item;
|
|
8562
|
+
members.push(m);
|
|
8563
|
+
}
|
|
8564
|
+
}
|
|
8565
|
+
return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
|
|
8566
|
+
}
|
|
8567
|
+
function flowLines(flow, depth = 1) {
|
|
8568
|
+
const byId = new Map(flow.nodes.map((n) => [n.id, n]));
|
|
8569
|
+
const out = [];
|
|
8570
|
+
const pad = (d) => " ".repeat(d);
|
|
8571
|
+
const at = (n) => n.line ? ` (line ${n.line})` : "";
|
|
8572
|
+
const say = (n) => n.kind === "code" ? `\`${n.text}\` (code, not explained)` : n.kind === "decision" ? `Ask: ${n.text}` : n.kind === "end" && n.answer ? `Answer: ${n.text}` : n.text;
|
|
8573
|
+
const go = (blocks2, d) => {
|
|
8574
|
+
for (const b of blocks2 || []) {
|
|
8575
|
+
const n = byId.get(b.id);
|
|
8576
|
+
out.push(`${pad(d)}- ${say(n)}${at(n)}`);
|
|
8577
|
+
if (n.kind === "decision") {
|
|
8578
|
+
for (const side of ["yes", "no"]) {
|
|
8579
|
+
if (!(side in b)) continue;
|
|
8580
|
+
if (b[side].length) {
|
|
8581
|
+
out.push(`${pad(d + 1)}${side === "yes" ? "Yes" : "No"}:`);
|
|
8582
|
+
go(b[side], d + 2);
|
|
8583
|
+
} else out.push(`${pad(d + 1)}${side === "yes" ? "Yes" : "No"}: continue`);
|
|
8584
|
+
}
|
|
8585
|
+
}
|
|
8586
|
+
if (b.each) {
|
|
8587
|
+
out.push(`${pad(d + 1)}For each:`);
|
|
8588
|
+
go(b.each, d + 2);
|
|
8589
|
+
}
|
|
8590
|
+
if (b.body) go(b.body, d + 1);
|
|
8591
|
+
for (const h of b.handlers || []) {
|
|
8592
|
+
out.push(`${pad(d + 1)}${byId.get(h.id).text.replace(/\?$/, "")}:`);
|
|
8593
|
+
go(h.blocks, d + 2);
|
|
8594
|
+
}
|
|
8595
|
+
if (b.always) {
|
|
8596
|
+
out.push(`${pad(d + 1)}Always, at the end:`);
|
|
8597
|
+
go(b.always.blocks, d + 2);
|
|
8598
|
+
}
|
|
8599
|
+
}
|
|
8600
|
+
};
|
|
8601
|
+
go(flow.blocks, depth);
|
|
8602
|
+
return out;
|
|
8603
|
+
}
|
|
8604
|
+
function modelText(model, id2) {
|
|
8605
|
+
const t = model.things.find((x) => x.id === id2);
|
|
8606
|
+
if (t) {
|
|
8607
|
+
const lines2 = [`${t.kind === "thing" ? "Thing" : t.kind === "record" ? "Record" : "Choices"} ${t.label}`];
|
|
8608
|
+
if (t.doc) lines2.push(` Author's note: ${t.doc}`);
|
|
8609
|
+
if (t.choices.length) lines2.push(` One of: ${t.choices.join(", ")}`);
|
|
8610
|
+
if (t.knows.length) {
|
|
8611
|
+
lines2.push(" It knows");
|
|
8612
|
+
for (const k of t.knows) lines2.push(` ${k.label}: ${[k.kind, k.start].filter(Boolean).join(", ") || "a value"}`);
|
|
8613
|
+
}
|
|
8614
|
+
if (t.can.length) {
|
|
8615
|
+
lines2.push(" It can");
|
|
8616
|
+
for (const c of t.can) lines2.push(` ${model.members.find((m2) => m2.id === c)?.label}`);
|
|
8617
|
+
}
|
|
8618
|
+
return `${lines2.join("\n")}
|
|
8619
|
+
`;
|
|
8620
|
+
}
|
|
8621
|
+
const m = model.members.find((x) => x.id === id2);
|
|
8622
|
+
if (!m) throw new Error(`Nothing in the model has id ${id2}.`);
|
|
8623
|
+
const owner = m.owner && model.things.find((x) => x.id === m.owner);
|
|
8624
|
+
const lines = [`${m.label}${owner && m.kind !== "setup" ? ` (${owner.label})` : ""}${m.kind === "rule" ? ": a rule" : ""}`];
|
|
8625
|
+
if (m.route) lines.push(` When someone calls ${m.route}`);
|
|
8626
|
+
if (m.doc) lines.push(` Author's note: ${m.doc}`);
|
|
8627
|
+
if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(", ")}`);
|
|
8628
|
+
if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
|
|
8629
|
+
lines.push(...flowLines(m.flow));
|
|
8630
|
+
return `${lines.join("\n")}
|
|
8631
|
+
`;
|
|
8632
|
+
}
|
|
8633
|
+
|
|
8634
|
+
// src/thunderize.mjs
|
|
8635
|
+
var THUNDERIZE_SCHEMA = "thunderize-v1";
|
|
8636
|
+
var THUNDER_TEXT_EXT = ".thunder-text";
|
|
8637
|
+
var LANGUAGE_NAMES = { typescript: "TypeScript", javascript: "JavaScript", python: "Python", go: "Go", rust: "Rust", csharp: "C#", java: "Java", kotlin: "Kotlin", php: "PHP", ruby: "Ruby" };
|
|
8638
|
+
function thunderizeFile(path, source, language = readableLanguage(path)) {
|
|
8639
|
+
const reading = readCode(source, { language, file: path });
|
|
8640
|
+
const main = reading.items.filter((i) => i.kind === "decision" || i.kind === "function");
|
|
8641
|
+
const failures = [...new Set(reading.items.filter((i) => i.kind === "error").map((i) => i.name))];
|
|
8642
|
+
const counts = { actions: 0, rules: 0, functions: 0, notReadYet: 0, failures: failures.length };
|
|
8643
|
+
const parts = main.map((item2) => {
|
|
8644
|
+
const v = visualFor(item2);
|
|
8645
|
+
if (v.element === "action") counts.actions++;
|
|
8646
|
+
else if (v.element === "decision") counts.rules++;
|
|
8647
|
+
else if (v.element === "not-read") counts.notReadYet++;
|
|
8648
|
+
else counts.functions++;
|
|
8649
|
+
return `# line ${item2.line}${v.line === "dashed" ? " \xB7 not read yet" : ""}
|
|
8650
|
+
${thunderText(item2).trimEnd()}`;
|
|
8651
|
+
});
|
|
8652
|
+
const header = `File ${path} (${LANGUAGE_NAMES[reading.language] || reading.language})
|
|
8653
|
+
Read from code by the Thunder compiler, no AI. ${summary(counts)}`;
|
|
8654
|
+
const footer = failures.length ? `
|
|
8655
|
+
Can fail with: ${failures.join(", ")}` : "";
|
|
8656
|
+
return { path, language: reading.language, out: `${path}${THUNDER_TEXT_EXT}`, counts, items: main.map((i) => ({ name: i.name, line: i.line, ...pick(visualFor(i)) })), text: `${header}
|
|
8657
|
+
|
|
8658
|
+
${parts.join("\n\n")}${footer}
|
|
8659
|
+
` };
|
|
8660
|
+
}
|
|
8661
|
+
var pick = (v) => ({ element: v.element, title: v.title, ...v.badge ? { route: v.badge.text } : {} });
|
|
8662
|
+
var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
8663
|
+
function summary(c) {
|
|
8664
|
+
const bits = [c.actions && plural(c.actions, "action"), c.rules && plural(c.rules, "rule"), c.functions && plural(c.functions, "function"), c.notReadYet && `${c.notReadYet} not read yet`].filter(Boolean);
|
|
8665
|
+
return bits.length ? `${bits.join(", ")}.` : "Nothing to read.";
|
|
8666
|
+
}
|
|
8667
|
+
function thunderizeFiles(files, { name = "app" } = {}) {
|
|
8668
|
+
const out = [], skipped = [];
|
|
8669
|
+
for (const f of files) {
|
|
8670
|
+
const language = readableLanguage(f.path);
|
|
8671
|
+
if (!language) {
|
|
8672
|
+
skipped.push({ path: f.path, reason: "not a language Thunder reads yet" });
|
|
8673
|
+
continue;
|
|
8674
|
+
}
|
|
8675
|
+
if (!f.source) {
|
|
8676
|
+
skipped.push({ path: f.path, reason: f.size ? "too large to read" : "empty" });
|
|
8677
|
+
continue;
|
|
8678
|
+
}
|
|
8679
|
+
try {
|
|
8680
|
+
out.push(thunderizeFile(f.path, f.source, language));
|
|
8681
|
+
} catch (e) {
|
|
8682
|
+
skipped.push({ path: f.path, reason: `could not be read: ${e.message}` });
|
|
8683
|
+
}
|
|
8684
|
+
}
|
|
8685
|
+
out.sort((a, b) => a.path.localeCompare(b.path));
|
|
8686
|
+
const total = { files: out.length, actions: 0, rules: 0, functions: 0, notReadYet: 0 };
|
|
8687
|
+
for (const f of out) for (const k of ["actions", "rules", "functions", "notReadYet"]) total[k] += f.counts[k];
|
|
8688
|
+
const langs = [...new Set(out.map((f) => LANGUAGE_NAMES[f.language] || f.language))].sort();
|
|
8689
|
+
const areas = /* @__PURE__ */ new Map();
|
|
8690
|
+
for (const f of out) {
|
|
8691
|
+
const area = f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ".";
|
|
8692
|
+
if (!areas.has(area)) areas.set(area, []);
|
|
8693
|
+
areas.get(area).push(f);
|
|
8694
|
+
}
|
|
8695
|
+
const lines = [
|
|
8696
|
+
`App ${name}`,
|
|
8697
|
+
` ${plural(total.files, "file")} read in ${langs.join(", ") || "no language"}: ${summary(total).replace(/\.$/, "")}.`,
|
|
8698
|
+
" Read from code by the Thunder compiler, no AI. Each file has its own Thunder Text beside it."
|
|
8699
|
+
];
|
|
8700
|
+
for (const [area, list] of areas) {
|
|
8701
|
+
lines.push("", `Area ${area === "." ? "(top level)" : area}`);
|
|
8702
|
+
for (const f of list) {
|
|
8703
|
+
const doors = f.items.filter((i) => i.element === "action" || i.element === "decision");
|
|
8704
|
+
lines.push(` File ${f.path}: ${summary(f.counts)}`);
|
|
8705
|
+
for (const d of doors) lines.push(` ${d.element === "action" ? d.title : `Rule: ${d.title}`}`);
|
|
8706
|
+
}
|
|
8707
|
+
}
|
|
8708
|
+
if (skipped.length) {
|
|
8709
|
+
lines.push("", "Not read");
|
|
8710
|
+
for (const s of skipped) lines.push(` ${s.path}: ${s.reason}`);
|
|
8711
|
+
}
|
|
8712
|
+
return { schema: THUNDERIZE_SCHEMA, name, counts: total, languages: langs, files: out, skipped, index: `${lines.join("\n")}
|
|
8713
|
+
` };
|
|
8714
|
+
}
|
|
8715
|
+
|
|
8716
|
+
// src/same.mjs
|
|
8717
|
+
var SAME_SCHEMA = "thunder-same-v1";
|
|
8718
|
+
var MAX_CASES = 4096;
|
|
8719
|
+
var nameKey = (name) => String(name).replace(/[_\s-]/g, "").toLowerCase();
|
|
8720
|
+
var norm4 = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
|
8721
|
+
var stemKey = (path) => nameKey(String(path).replace(/\.[^./]+$/, "").replace(/\\/g, "/"));
|
|
8722
|
+
function compact(it, key, file, language) {
|
|
8723
|
+
const base = { key, file, language, name: it.name, kind: it.kind, line: it.line, route: it.route, element: visualFor(it).element };
|
|
8724
|
+
return it.kind === "decision" ? { ...it, ...base } : { ...base, flat: flatSteps(it.steps) };
|
|
8725
|
+
}
|
|
8726
|
+
function readAll(files) {
|
|
8727
|
+
const items = /* @__PURE__ */ new Map(), byName = /* @__PURE__ */ new Map(), unreadable = [];
|
|
8728
|
+
for (const f of files) {
|
|
8729
|
+
const language = readableLanguage(f.path);
|
|
8730
|
+
if (!language || !f.source) continue;
|
|
8731
|
+
let reading;
|
|
8732
|
+
try {
|
|
8733
|
+
reading = readCode(f.source, { language, file: f.path });
|
|
8734
|
+
} catch (e) {
|
|
8735
|
+
unreadable.push({ path: f.path, reason: e.message });
|
|
8736
|
+
continue;
|
|
8737
|
+
}
|
|
8738
|
+
const seen = /* @__PURE__ */ new Map();
|
|
8739
|
+
for (const it of reading.items) {
|
|
8740
|
+
if (it.kind !== "decision" && it.kind !== "function") continue;
|
|
8741
|
+
const n = nameKey(it.name);
|
|
8742
|
+
const nth = (seen.get(n) || 0) + 1;
|
|
8743
|
+
seen.set(n, nth);
|
|
8744
|
+
const key = `${stemKey(f.path)}#${n}${nth > 1 ? `#${nth}` : ""}`;
|
|
8745
|
+
items.set(key, compact(it, key, f.path, language));
|
|
8746
|
+
byName.set(n, byName.has(n) ? null : key);
|
|
8747
|
+
}
|
|
8748
|
+
}
|
|
8749
|
+
return { items, byName, unreadable };
|
|
8750
|
+
}
|
|
8751
|
+
function caseValues(models) {
|
|
8752
|
+
const byInput = /* @__PURE__ */ new Map();
|
|
8753
|
+
for (const m of models) for (const input of m.inputs) {
|
|
8754
|
+
if (!byInput.has(input.id)) byInput.set(input.id, { kind: input.kind, values: /* @__PURE__ */ new Set() });
|
|
8755
|
+
const slot = byInput.get(input.id);
|
|
8756
|
+
if (input.kind === "yesno") {
|
|
8757
|
+
slot.values.add(true);
|
|
8758
|
+
slot.values.add(false);
|
|
8759
|
+
}
|
|
8760
|
+
}
|
|
8761
|
+
for (const m of models) for (const r of m.rules) for (const c of r.conditions) {
|
|
8762
|
+
const slot = byInput.get(c.input);
|
|
8763
|
+
if (!slot || slot.kind === "yesno" || typeof c.value !== "number") continue;
|
|
8764
|
+
for (const v of [c.value - 1, c.value, c.value + 1, c.value - 0.01, c.value + 0.01]) slot.values.add(Math.round(v * 100) / 100);
|
|
8765
|
+
}
|
|
8766
|
+
for (const slot of byInput.values()) if (slot.kind !== "yesno") slot.values.add(0);
|
|
8767
|
+
return [...byInput.entries()].map(([id2, s]) => [id2, [...s.values].sort((a, b) => a > b ? 1 : a < b ? -1 : 0)]);
|
|
8768
|
+
}
|
|
8769
|
+
function* product(axes, i = 0, acc = {}) {
|
|
8770
|
+
if (i === axes.length) {
|
|
8771
|
+
yield { ...acc };
|
|
8772
|
+
return;
|
|
8773
|
+
}
|
|
8774
|
+
const [id2, values] = axes[i];
|
|
8775
|
+
for (const v of values) {
|
|
8776
|
+
acc[id2] = v;
|
|
8777
|
+
yield* product(axes, i + 1, acc);
|
|
8778
|
+
}
|
|
8779
|
+
}
|
|
8780
|
+
function compareRules(oldItem, newItem) {
|
|
8781
|
+
let a, b;
|
|
8782
|
+
try {
|
|
8783
|
+
a = plainFromReading(oldItem);
|
|
8784
|
+
b = plainFromReading(newItem);
|
|
8785
|
+
} catch {
|
|
8786
|
+
a = b = null;
|
|
8787
|
+
}
|
|
8788
|
+
if (!a || !b) return null;
|
|
8789
|
+
const key = (i) => `${nameKey(i.label)}:${i.kind}`;
|
|
8790
|
+
const toA = new Map(a.inputs.map((i) => [key(i), i.id]));
|
|
8791
|
+
if (a.inputs.length !== b.inputs.length || !b.inputs.every((i) => toA.has(key(i)))) {
|
|
8792
|
+
return { same: false, tried: 0, reason: `They need different facts: ${a.inputs.map((i) => i.label).join(", ")} versus ${b.inputs.map((i) => i.label).join(", ")}.` };
|
|
8793
|
+
}
|
|
8794
|
+
const bAsA = { ...b, inputs: b.inputs.map((i) => ({ ...i, id: toA.get(key(i)) })), rules: b.rules.map((r) => ({ ...r, conditions: r.conditions.map((c) => ({ ...c, input: toA.get(key(b.inputs.find((i) => i.id === c.input))) })) })) };
|
|
8795
|
+
let tried = 0;
|
|
8796
|
+
for (const values of product(caseValues([a, bAsA]))) {
|
|
8797
|
+
if (++tried > MAX_CASES) {
|
|
8798
|
+
tried--;
|
|
8799
|
+
break;
|
|
8800
|
+
}
|
|
8801
|
+
const x = explainPlain(a, values).outcome, y = explainPlain(bAsA, values).outcome;
|
|
8802
|
+
if (x !== y) return { same: false, tried, counterexample: { values: { ...values }, facts: a.inputs.map((i) => `${i.label} ${i.kind === "yesno" ? values[i.id] ? i.yes ?? "yes" : i.no ?? "no" : values[i.id]}`).join(", "), old: x, new: y } };
|
|
8803
|
+
}
|
|
8804
|
+
return { same: true, tried };
|
|
8805
|
+
}
|
|
8806
|
+
var flatSteps = (steps, depth = 0) => (steps || []).flatMap((s) => [
|
|
8807
|
+
{ sig: `${depth}:${s.restates ? "code" : s.kind}:${s.restates || s.kind === "other" ? "" : norm4(s.says)}`, text: s.restates || s.kind === "other" ? `\`${s.code ?? s.says}\`` : s.says },
|
|
8808
|
+
...flatSteps(s.children, depth + 1)
|
|
8809
|
+
]);
|
|
8810
|
+
function compareItems(o, n) {
|
|
8811
|
+
const where = { old: { file: o.file, line: o.line, language: o.language }, new: { file: n.file, line: n.line, language: n.language } };
|
|
8812
|
+
if (o.element === "not-read" || n.element === "not-read") return { status: "cannot-check", reason: "Thunder cannot read one side yet, so it cannot confirm they mean the same.", ...where };
|
|
8813
|
+
if (o.kind !== n.kind) return { status: "different", reason: `One is a ${o.kind === "decision" ? "rule" : "list of steps"}, the other is a ${n.kind === "decision" ? "rule" : "list of steps"}.`, ...where };
|
|
8814
|
+
if ((o.route?.method || "") !== (n.route?.method || "") || (o.route?.path || "") !== (n.route?.path || "")) {
|
|
8815
|
+
return { status: "different", reason: `The address changed: ${o.route ? `${o.route.method} ${o.route.path}` : "none"} became ${n.route ? `${n.route.method} ${n.route.path}` : "none"}.`, ...where };
|
|
8816
|
+
}
|
|
8817
|
+
if (o.kind === "decision") {
|
|
8818
|
+
const r = compareRules(o, n);
|
|
8819
|
+
if (!r) return { status: "cannot-check", reason: "One rule could not be drawn as a card, so its answers could not be compared.", ...where };
|
|
8820
|
+
if (r.same) return { status: "same", reason: `Same answer on all ${r.tried} edge cases.`, ...where };
|
|
8821
|
+
if (r.counterexample) {
|
|
8822
|
+
const facts = r.counterexample.facts;
|
|
8823
|
+
return { status: "different", reason: `Different answer for ${facts}: ${r.counterexample.old} before, ${r.counterexample.new} after.`, counterexample: r.counterexample, ...where };
|
|
8824
|
+
}
|
|
8825
|
+
return { status: "different", reason: r.reason, ...where };
|
|
8826
|
+
}
|
|
8827
|
+
const so = o.flat, sn = n.flat;
|
|
8828
|
+
const at = so.findIndex((s, i2) => s.sig !== sn[i2]?.sig);
|
|
8829
|
+
if (at === -1 && so.length === sn.length) return { status: "same", reason: `Same ${so.length} steps.`, ...where };
|
|
8830
|
+
const i = at === -1 ? Math.min(so.length, sn.length) : at;
|
|
8831
|
+
return { status: "different", reason: `Steps differ from step ${i + 1}: "${so[i]?.text ?? "(nothing)"}" became "${sn[i]?.text ?? "(nothing)"}".`, ...where };
|
|
8832
|
+
}
|
|
8833
|
+
function sameMeaning(oldFiles, newFiles) {
|
|
8834
|
+
const A = readAll(oldFiles), B = readAll(newFiles);
|
|
8835
|
+
const items = [], used = /* @__PURE__ */ new Set();
|
|
8836
|
+
const partner = (key, o) => {
|
|
8837
|
+
if (B.items.has(key) && !used.has(key)) return key;
|
|
8838
|
+
const n = nameKey(o.name), a = A.byName.get(n), b = B.byName.get(n);
|
|
8839
|
+
return a && b && !used.has(b) ? b : null;
|
|
8840
|
+
};
|
|
8841
|
+
for (const [key, o] of A.items) {
|
|
8842
|
+
const k = partner(key, o);
|
|
8843
|
+
if (k) used.add(k);
|
|
8844
|
+
const n = k && B.items.get(k);
|
|
8845
|
+
items.push({ name: o.name, ...n ? compareItems(o, n) : { status: "only-old", reason: "Not found in the new code.", old: { file: o.file, line: o.line, language: o.language } } });
|
|
8846
|
+
}
|
|
8847
|
+
for (const [key, n] of B.items) if (!used.has(key)) items.push({ name: n.name, status: "only-new", reason: "New: not in the old code.", new: { file: n.file, line: n.line, language: n.language } });
|
|
8848
|
+
const counts = { same: 0, different: 0, "only-old": 0, "only-new": 0, "cannot-check": 0 };
|
|
8849
|
+
for (const it of items) counts[it.status]++;
|
|
8850
|
+
const verdict = counts.different || counts["only-old"] || counts["only-new"] ? "different" : counts["cannot-check"] ? "partly-checked" : "same";
|
|
8851
|
+
return { schema: SAME_SCHEMA, verdict, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
|
|
8852
|
+
}
|
|
8853
|
+
function renderSame(r) {
|
|
8854
|
+
const head = r.verdict === "same" ? "Same meaning." : r.verdict === "partly-checked" ? "No differences found, but some parts could not be checked." : "Different meaning.";
|
|
8855
|
+
const lines = [`${head} ${r.counts.same} same, ${r.counts.different} different, ${r.counts["only-old"]} only in the old code, ${r.counts["only-new"]} only in the new code, ${r.counts["cannot-check"]} not checked.`];
|
|
8856
|
+
const order = ["different", "only-old", "only-new", "cannot-check", "same"];
|
|
8857
|
+
const label = { different: "different", "only-old": "only old", "only-new": "only new", "cannot-check": "not checked", same: "same" };
|
|
8858
|
+
for (const st of order) for (const it of r.items.filter((x) => x.status === st)) {
|
|
8859
|
+
const loc = [it.old && `${it.old.file}:${it.old.line}`, it.new && `${it.new.file}:${it.new.line}`].filter(Boolean).join(" \u2192 ");
|
|
8860
|
+
lines.push(` ${label[st].padEnd(11)} ${it.name} (${loc}) ${it.reason}`);
|
|
8861
|
+
}
|
|
8862
|
+
return `${lines.join("\n")}
|
|
8863
|
+
`;
|
|
8864
|
+
}
|
|
8865
|
+
|
|
8866
|
+
// src/intellisense.mjs
|
|
8867
|
+
var SEMANTIC_TYPES3 = [
|
|
8868
|
+
"Email",
|
|
8869
|
+
"Money(USD)",
|
|
8870
|
+
"Currency",
|
|
8871
|
+
"Url",
|
|
8872
|
+
"UserId",
|
|
8873
|
+
"AccountId",
|
|
8874
|
+
"OrderId",
|
|
8875
|
+
"InvoiceId",
|
|
8876
|
+
"PaymentId",
|
|
8877
|
+
"Secret",
|
|
8878
|
+
"Token",
|
|
8879
|
+
"Jwt",
|
|
8880
|
+
"IdempotencyKey",
|
|
8881
|
+
"Date",
|
|
8882
|
+
"DateTime",
|
|
8883
|
+
"Duration",
|
|
8884
|
+
"Percentage",
|
|
8885
|
+
"TraceId",
|
|
8886
|
+
"CorrelationId"
|
|
8887
|
+
];
|
|
8888
|
+
var TYPE_INFO = {
|
|
8889
|
+
Email: { description: "A validated email address. Prefer this over a raw string so tools can reason about PII and format.", examples: ["user@company.com"] },
|
|
8890
|
+
Money: { description: "A monetary amount with a currency, for example Money(USD). Avoids float rounding bugs and ambiguous units.", examples: ["Money(USD) 100.00"] },
|
|
8891
|
+
"Money(USD)": { description: "A monetary amount in US dollars. Prefer a typed money value over a number to avoid rounding and currency bugs.", examples: ["100.00"] },
|
|
8892
|
+
Secret: { description: "Sensitive value that must never be logged, returned to a client, or placed in events, proof, or AI context.", examples: ["paymentToken: Secret"] },
|
|
8893
|
+
Token: { description: "An opaque credential. Treat like a Secret: never log or return it.", examples: ["resetToken: Token"] },
|
|
8894
|
+
Jwt: { description: "A JSON Web Token credential. Sensitive; never log or expose it.", examples: [] },
|
|
8895
|
+
IdempotencyKey: { description: "A retry key. The same key must return the same result instead of creating a duplicate action.", examples: ["Use it to prevent duplicate invoices when checkout retries."], relatedSuggestions: ["Add a duplicate prevention guarantee", "Add a repeated-order verification test"] },
|
|
8896
|
+
OrderId: { description: "The stable identity of a placed order.", examples: ["A1"] },
|
|
8897
|
+
InvoiceId: { description: "The stable identity of an issued invoice.", examples: ["INV-1"] },
|
|
8898
|
+
TraceId: { description: "A distributed-tracing identifier used to correlate work across services.", examples: [] },
|
|
8899
|
+
CorrelationId: { description: "An identifier that correlates related requests or events.", examples: [] }
|
|
8900
|
+
};
|
|
8901
|
+
var LENS_INFO = {
|
|
8902
|
+
pm: "Business meaning for product and non-technical stakeholders.",
|
|
8903
|
+
beginner: "Plain-English explanation for someone new to programming.",
|
|
8904
|
+
qa: "How to test or verify this behavior.",
|
|
8905
|
+
risk: "What goes wrong if this fails.",
|
|
8906
|
+
security: "Privacy, secrets, auth, or data-exposure meaning.",
|
|
8907
|
+
support: "What support needs to know to help customers.",
|
|
8908
|
+
reviewer: "What a reviewer should check before approving.",
|
|
8909
|
+
ops: "What production signal or failure mode to watch.",
|
|
8910
|
+
non_goal: "What this mission intentionally does not do.",
|
|
8911
|
+
term: "Defines an unfamiliar term for readers."
|
|
8912
|
+
};
|
|
8913
|
+
var BLOCK_KEYWORDS = ["goal", "why", "input", "output", "guarantees", "never", "verify", "target", "examples", "note"];
|
|
8914
|
+
var SENSITIVE2 = /payment token|secret|token|password|jwt|credential|ssn|pii|email/i;
|
|
8915
|
+
var item = (id2, label, insertText, detail, sortText = "050", kind = "snippet") => ({ id: id2, label, kind, detail, insertText, sortText, source: "compiler", confidence: "high" });
|
|
8916
|
+
var noteItem = (lens) => item(`completion_note_${lens}`, `note ${lens}:`, `note ${lens}:
|
|
8917
|
+
\${1:${LENS_INFO[lens]}}`, LENS_INFO[lens], "010");
|
|
8918
|
+
var typeItem = (t) => item(`completion_type_${t}`, t, t, `Semantic type: ${TYPE_INFO[t]?.description || TYPE_INFO[t.replace(/\(.*/, "")]?.description || "A semantic type."}`, "020", "type");
|
|
8919
|
+
function enclosingBlock(lines, idx) {
|
|
8920
|
+
const curIndent = lines[idx].length - lines[idx].trimStart().length;
|
|
8921
|
+
if (curIndent === 0) return null;
|
|
8922
|
+
for (let i = idx; i >= 0; i--) {
|
|
8923
|
+
const l = lines[i];
|
|
8924
|
+
if (!l.trim()) continue;
|
|
8925
|
+
const ind = l.length - l.trimStart().length;
|
|
8926
|
+
if (ind < curIndent) return l.trim().split(/\s+/)[0].toLowerCase();
|
|
8927
|
+
}
|
|
8928
|
+
return null;
|
|
8929
|
+
}
|
|
8930
|
+
function getCompletions(source, position = {}) {
|
|
8931
|
+
const lines = source.split("\n");
|
|
8932
|
+
const idx = Math.max(0, Math.min((position.line || 1) - 1, lines.length - 1));
|
|
8933
|
+
const cur = lines[idx] ?? "";
|
|
8934
|
+
const items = [];
|
|
8935
|
+
const meaningful = lines.filter((l) => l.trim() && !l.trim().startsWith("#"));
|
|
8936
|
+
if (meaningful.length === 0) {
|
|
8937
|
+
items.push(item(
|
|
8938
|
+
"completion_mission_starter",
|
|
8939
|
+
"mission starter",
|
|
8940
|
+
"mission ${1:MissionName}\n note pm:\n ${2:Plain-English business meaning.}\n\n goal\n ${3:What should this accomplish?}\n\n why\n ${4:Why does this matter?}\n\n input\n ${5:field}: ${6:SemanticType}\n\n output\n ${7:result}: ${8:ResultType}\n\n guarantees\n ${9:Something that must always be true}\n\n never\n ${10:Something that must never happen}\n\n verify\n test ${11:expected behavior}\n",
|
|
8941
|
+
"Start a new mission with goal, why, input, output, guarantees, never, verify.",
|
|
8942
|
+
"001"
|
|
8943
|
+
));
|
|
8944
|
+
return { items };
|
|
8945
|
+
}
|
|
8946
|
+
if (/(^|\s)note\s+\w*$/.test(cur)) {
|
|
8947
|
+
for (const lens of KNOWN_LENSES) items.push(noteItem(lens));
|
|
8948
|
+
return { items };
|
|
8949
|
+
}
|
|
8950
|
+
const ctx = enclosingBlock(lines, idx);
|
|
8951
|
+
if (SENSITIVE2.test(cur) || SENSITIVE2.test(lines[idx - 1] || "")) {
|
|
8952
|
+
items.push(item(
|
|
8953
|
+
"completion_note_security",
|
|
8954
|
+
"note security:",
|
|
8955
|
+
"note security:\n ${1:This value must not appear in logs, events, responses, proof artifacts, or AI context.}",
|
|
8956
|
+
"Flag sensitive data handling for security readers.",
|
|
8957
|
+
"005"
|
|
8958
|
+
));
|
|
8959
|
+
}
|
|
8960
|
+
if (ctx === "input" || ctx === "output") {
|
|
8961
|
+
for (const t of SEMANTIC_TYPES3) items.push(typeItem(t));
|
|
8962
|
+
for (const l of ["beginner", "pm", "qa"]) items.push(noteItem(l));
|
|
8963
|
+
} else if (ctx === "guarantees" || ctx === "guarantee") {
|
|
8964
|
+
for (const l of ["pm", "risk", "qa"]) items.push(noteItem(l));
|
|
8965
|
+
items.push(item("completion_verify", "verify:", "verify\n test ${1:expected behavior}", "Add verification evidence.", "015"));
|
|
8966
|
+
} else if (ctx === "never") {
|
|
8967
|
+
for (const l of ["security", "risk", "reviewer"]) items.push(noteItem(l));
|
|
8968
|
+
items.push(item("completion_verify", "verify:", "verify\n ${1:security scan}", "Add verification evidence.", "015"));
|
|
8969
|
+
} else {
|
|
8970
|
+
for (const kw of BLOCK_KEYWORDS) {
|
|
8971
|
+
if (kw === "note") {
|
|
8972
|
+
items.push(noteItem("pm"), noteItem("beginner"));
|
|
8973
|
+
continue;
|
|
8974
|
+
}
|
|
8975
|
+
items.push(item(`completion_block_${kw}`, `${kw}`, `${kw}
|
|
8976
|
+
\${1:...}`, `Add a ${kw} block.`, "030", "keyword"));
|
|
8977
|
+
}
|
|
8978
|
+
}
|
|
8979
|
+
return { items };
|
|
8980
|
+
}
|
|
8981
|
+
function getHover(source, position = {}) {
|
|
8982
|
+
const lines = source.split("\n");
|
|
8983
|
+
const idx = Math.max(0, Math.min((position.line || 1) - 1, lines.length - 1));
|
|
8984
|
+
const cur = lines[idx] ?? "";
|
|
8985
|
+
const col = Math.max(0, (position.column || 1) - 1);
|
|
8986
|
+
let s = col, e = col;
|
|
8987
|
+
while (s > 0 && /[A-Za-z0-9_()]/.test(cur[s - 1])) s--;
|
|
8988
|
+
while (e < cur.length && /[A-Za-z0-9_()]/.test(cur[e])) e++;
|
|
8989
|
+
const word = cur.slice(s, e);
|
|
8990
|
+
if (!word) return { hover: null };
|
|
8991
|
+
const noteMatch = cur.match(/^\s*note\s+([A-Za-z_]+)/);
|
|
8992
|
+
if (noteMatch && (word === noteMatch[1] || word === "note")) {
|
|
8993
|
+
const lens = noteMatch[1];
|
|
8994
|
+
return {
|
|
8995
|
+
hover: {
|
|
8996
|
+
target: lens,
|
|
8997
|
+
kind: "note_lens",
|
|
8998
|
+
title: `note ${lens}`,
|
|
8999
|
+
description: LENS_INFO[lens] || "An ThunderLens reader lens.",
|
|
9000
|
+
examples: [],
|
|
9001
|
+
relatedSuggestions: []
|
|
9002
|
+
}
|
|
9003
|
+
};
|
|
9004
|
+
}
|
|
9005
|
+
const base = word.replace(/\(.*\)/, "");
|
|
9006
|
+
const isKnownType = SEMANTIC_TYPES3.some((t) => t === word || t.replace(/\(.*/, "") === base);
|
|
9007
|
+
const info = TYPE_INFO[word] || TYPE_INFO[base];
|
|
9008
|
+
if (info || isKnownType || /^[A-Z][a-z]/.test(word)) {
|
|
9009
|
+
return {
|
|
9010
|
+
hover: {
|
|
9011
|
+
target: word,
|
|
9012
|
+
kind: "semantic_type",
|
|
9013
|
+
title: word,
|
|
9014
|
+
description: info?.description || "A semantic type. Prefer semantic types over raw string or number so tools can reason about meaning.",
|
|
9015
|
+
examples: info?.examples || [],
|
|
9016
|
+
relatedSuggestions: info?.relatedSuggestions || []
|
|
9017
|
+
}
|
|
9018
|
+
};
|
|
9019
|
+
}
|
|
9020
|
+
return { hover: null };
|
|
9021
|
+
}
|
|
9022
|
+
var HEADER_ALIASES = { goals: "goal", nevers: "never" };
|
|
9023
|
+
var TOP_HEADERS = /* @__PURE__ */ new Set([
|
|
9024
|
+
"goal",
|
|
9025
|
+
"why",
|
|
9026
|
+
"requires",
|
|
9027
|
+
"input",
|
|
9028
|
+
"output",
|
|
9029
|
+
"guarantees",
|
|
9030
|
+
"never",
|
|
9031
|
+
"constraints",
|
|
9032
|
+
"assumptions",
|
|
9033
|
+
"risks",
|
|
9034
|
+
"target",
|
|
9035
|
+
"style",
|
|
9036
|
+
"verify",
|
|
9037
|
+
"errors",
|
|
9038
|
+
"examples"
|
|
9039
|
+
]);
|
|
9040
|
+
function autocorrectSource(source) {
|
|
9041
|
+
const lines = String(source).split("\n");
|
|
9042
|
+
const changes = [];
|
|
9043
|
+
const out = lines.map((line, i) => {
|
|
9044
|
+
const m = line.match(/^(\s*)([A-Za-z]+)(:?)\s*$/);
|
|
9045
|
+
if (!m) return line;
|
|
9046
|
+
const [, indent, word, colon] = m;
|
|
9047
|
+
const alias = HEADER_ALIASES[word.toLowerCase()];
|
|
9048
|
+
const target = alias || word;
|
|
9049
|
+
const isHeader = TOP_HEADERS.has(target.toLowerCase());
|
|
9050
|
+
const dropColon = Boolean(colon) && isHeader;
|
|
9051
|
+
if (target === word && !dropColon) return line;
|
|
9052
|
+
const rule = alias ? "header-alias" : "strip-colon";
|
|
9053
|
+
const fixed = `${indent}${target}`;
|
|
9054
|
+
changes.push({ line: i + 1, from: line.trim(), to: fixed.trim(), rule, safety: "safe" });
|
|
9055
|
+
return fixed;
|
|
9056
|
+
});
|
|
9057
|
+
return { fixed: out.join("\n"), changes };
|
|
9058
|
+
}
|
|
9059
|
+
function getCodeActions(source, diagnostics = []) {
|
|
9060
|
+
const actions = [];
|
|
9061
|
+
for (const c of autocorrectSource(source).changes) {
|
|
9062
|
+
actions.push({ title: `Normalize "${c.from}" to "${c.to}"`, kind: "autocorrect", safety: "safe", line: c.line, rule: c.rule });
|
|
9063
|
+
}
|
|
9064
|
+
for (const d of diagnostics) {
|
|
9065
|
+
for (const f of d.fix || []) {
|
|
9066
|
+
actions.push({ title: f.label, kind: "quickfix", safety: "reviewable", code: d.code, line: d.line ?? null, insert: f.insert, block: f.block });
|
|
9067
|
+
}
|
|
9068
|
+
}
|
|
9069
|
+
return actions;
|
|
9070
|
+
}
|
|
9071
|
+
|
|
9072
|
+
// src/intent-schema.mjs
|
|
9073
|
+
var SCHEMA_VERSION = "intent-graph-v1";
|
|
9074
|
+
var NODE_TYPES = [
|
|
9075
|
+
"Mission",
|
|
9076
|
+
"Actor",
|
|
9077
|
+
"Persona",
|
|
9078
|
+
"Evidence",
|
|
9079
|
+
"Opportunity",
|
|
9080
|
+
"Outcome",
|
|
9081
|
+
"Metric",
|
|
9082
|
+
"Requirement",
|
|
9083
|
+
"Constraint",
|
|
9084
|
+
"Invariant",
|
|
9085
|
+
"Guarantee",
|
|
9086
|
+
"Never",
|
|
9087
|
+
"Conflict",
|
|
9088
|
+
"Journey",
|
|
9089
|
+
"ExperienceContract",
|
|
9090
|
+
"ExperienceState",
|
|
9091
|
+
"Pattern",
|
|
9092
|
+
"DesignArtifact",
|
|
9093
|
+
"DesignComponent",
|
|
9094
|
+
"StyleIntent",
|
|
9095
|
+
"Capability",
|
|
9096
|
+
"SystemContract",
|
|
9097
|
+
"ImplementationMapping",
|
|
9098
|
+
"VerificationRule",
|
|
9099
|
+
"VerificationResult",
|
|
9100
|
+
"Approval",
|
|
9101
|
+
"Release",
|
|
9102
|
+
"OutcomeContract",
|
|
9103
|
+
"OutcomeResult",
|
|
9104
|
+
"LearningArtifact",
|
|
9105
|
+
"Unknown",
|
|
9106
|
+
"Assumption",
|
|
9107
|
+
"Question",
|
|
9108
|
+
"Lifecycle",
|
|
9109
|
+
"LifecycleState",
|
|
9110
|
+
"Temporal",
|
|
9111
|
+
"Command",
|
|
9112
|
+
"Event",
|
|
9113
|
+
"FailureHandler",
|
|
9114
|
+
"Decision",
|
|
9115
|
+
"Rule",
|
|
9116
|
+
"Skill"
|
|
9117
|
+
];
|
|
9118
|
+
var RELATIONSHIP_TYPES = [
|
|
9119
|
+
"supported_by",
|
|
9120
|
+
"derived_from",
|
|
9121
|
+
"addresses",
|
|
9122
|
+
"targets",
|
|
9123
|
+
"measured_by",
|
|
9124
|
+
"requires",
|
|
9125
|
+
"constrained_by",
|
|
9126
|
+
"implemented_by",
|
|
9127
|
+
"represented_by",
|
|
9128
|
+
"verified_by",
|
|
9129
|
+
"approved_by",
|
|
9130
|
+
"released_in",
|
|
9131
|
+
"resulted_in",
|
|
9132
|
+
"contradicts",
|
|
9133
|
+
"supersedes",
|
|
9134
|
+
"depends_on",
|
|
9135
|
+
"blocks",
|
|
9136
|
+
"teaches",
|
|
9137
|
+
"generated_from",
|
|
9138
|
+
"transitions_to",
|
|
9139
|
+
"requires_skill"
|
|
9140
|
+
];
|
|
9141
|
+
var NODE_STATUSES = [
|
|
9142
|
+
"draft",
|
|
9143
|
+
"proposed",
|
|
9144
|
+
"approval-required",
|
|
9145
|
+
"unresolved",
|
|
9146
|
+
"unvalidated",
|
|
9147
|
+
"open",
|
|
9148
|
+
"required",
|
|
9149
|
+
"verify-declared",
|
|
9150
|
+
"unverified",
|
|
9151
|
+
"verified",
|
|
9152
|
+
"recoverable",
|
|
9153
|
+
"defined",
|
|
9154
|
+
"redundant"
|
|
9155
|
+
];
|
|
9156
|
+
function intentGraphJsonSchema() {
|
|
9157
|
+
return {
|
|
9158
|
+
$schema: "http://json-schema.org/draft-07/schema#",
|
|
9159
|
+
$id: `https://thunderlang.dev/schema/${SCHEMA_VERSION}.json`,
|
|
9160
|
+
title: "Intent Graph",
|
|
9161
|
+
type: "object",
|
|
9162
|
+
required: ["schema", "missionId", "nodes", "relationships"],
|
|
9163
|
+
properties: {
|
|
9164
|
+
schema: { const: SCHEMA_VERSION },
|
|
9165
|
+
missionId: { type: "string" },
|
|
9166
|
+
nodes: { type: "array", items: { $ref: "#/definitions/node" } },
|
|
9167
|
+
relationships: { type: "array", items: { $ref: "#/definitions/relationship" } },
|
|
9168
|
+
summary: { type: "object" }
|
|
9169
|
+
},
|
|
9170
|
+
definitions: {
|
|
9171
|
+
node: {
|
|
9172
|
+
type: "object",
|
|
9173
|
+
required: ["id", "type"],
|
|
9174
|
+
properties: {
|
|
9175
|
+
id: { type: "string" },
|
|
9176
|
+
type: { enum: NODE_TYPES },
|
|
9177
|
+
title: { type: ["string", "null"] },
|
|
9178
|
+
description: { type: ["string", "null"] },
|
|
9179
|
+
status: { type: ["string", "null"] },
|
|
9180
|
+
owner: { type: ["string", "null"] },
|
|
9181
|
+
classification: { type: ["string", "null"], enum: [...CLASSIFICATIONS, null] },
|
|
9182
|
+
confidence: { type: ["string", "null"], enum: [...CONFIDENCE, null] },
|
|
9183
|
+
source: { type: ["string", "null"] },
|
|
9184
|
+
tags: { type: "array", items: { type: "string" } },
|
|
9185
|
+
createdTime: { type: ["string", "null"] },
|
|
9186
|
+
updatedTime: { type: ["string", "null"] }
|
|
9187
|
+
}
|
|
9188
|
+
},
|
|
9189
|
+
relationship: {
|
|
9190
|
+
type: "object",
|
|
9191
|
+
required: ["from", "type", "to"],
|
|
9192
|
+
properties: {
|
|
9193
|
+
from: { type: "string" },
|
|
9194
|
+
type: { enum: RELATIONSHIP_TYPES },
|
|
9195
|
+
to: { type: "string" }
|
|
9196
|
+
}
|
|
9197
|
+
}
|
|
9198
|
+
}
|
|
9199
|
+
};
|
|
9200
|
+
}
|
|
9201
|
+
var IL_AUTHOR_RULE_ROWS = [
|
|
9202
|
+
{ ruleId: "IL-PM-001", area: "product", severity: "warning", blocks: ["release"], summary: "Metric has no measurement window." },
|
|
9203
|
+
{ ruleId: "IL-PM-003", area: "product", severity: "warning", blocks: [], summary: "Outcome has no metric." },
|
|
9204
|
+
{ ruleId: "IL-EV-001", area: "evidence", severity: "info", blocks: [], summary: "Evidence has no classification." },
|
|
9205
|
+
{ ruleId: "IL-EV-002", area: "evidence", severity: "warning", blocks: [], summary: "Evidence has an unknown classification." },
|
|
9206
|
+
{ ruleId: "IL-GRAPH-010", area: "graph", severity: "blocker", blocks: ["<declared-phase>"], summary: "Unresolved unknown blocks a phase." },
|
|
9207
|
+
{ ruleId: "IL-GRAPH-011", area: "graph", severity: "blocker", blocks: ["<declared-phase>"], summary: "Open question blocks a phase." },
|
|
9208
|
+
{ ruleId: "IL-EXP-001", area: "experience", severity: "info", blocks: [], summary: "Experience declares no states." },
|
|
9209
|
+
{ ruleId: "IL-EXP-004", area: "experience", severity: "blocker", blocks: ["experience-approval", "release"], summary: "Failure state has no recovery path." },
|
|
9210
|
+
{ ruleId: "IL-CONFLICT-001", area: "conflict", severity: "blocker", blocks: ["<declared-phase>"], summary: "Declared conflict is unresolved." },
|
|
9211
|
+
{ ruleId: "IL-CONFLICT-010", area: "conflict", severity: "blocker", blocks: ["implementation"], summary: "Scope includes and excludes the same item." },
|
|
9212
|
+
{ ruleId: "IL-CONFLICT-011", area: "conflict", severity: "info", blocks: [], summary: "Redundant constraint from multiple roles." },
|
|
9213
|
+
{ ruleId: "IL-CONFLICT-012", area: "conflict", severity: "blocker", blocks: ["implementation"], summary: "Directly contradictory constraints." },
|
|
9214
|
+
{ ruleId: "IL-GOV-001", area: "governance", severity: "error", blocks: [], summary: "Waiver names no diagnostic code." },
|
|
9215
|
+
{ ruleId: "IL-GOV-002", area: "governance", severity: "error", blocks: [], summary: "Waiver has no reason." },
|
|
9216
|
+
{ ruleId: "IL-GOV-003", area: "governance", severity: "error", blocks: [], summary: "Waiver names no approver." },
|
|
7286
9217
|
{ ruleId: "IL-GOV-004", area: "governance", severity: "warning", blocks: [], summary: "Waiver matches no current diagnostic (stale)." },
|
|
7287
9218
|
{ ruleId: "IL-GOV-005", area: "governance", severity: "error", blocks: [], summary: "Waiver has expired." },
|
|
7288
9219
|
{ ruleId: "IL-DATA-001", area: "privacy", severity: "blocker", blocks: ["release"], summary: "Sensitive data held with no stated purpose." },
|
|
@@ -7735,11 +9666,11 @@ function buildIntentGraph(ast) {
|
|
|
7735
9666
|
relationships.push(rel(mId, "constrained_by", id2));
|
|
7736
9667
|
}
|
|
7737
9668
|
const nodeIds = new Set(nodes2.map((n) => n.id));
|
|
7738
|
-
for (const
|
|
7739
|
-
const id2 = `capability.${slug(
|
|
7740
|
-
nodes2.push(node(id2, "Capability",
|
|
9669
|
+
for (const cap2 of ast.capabilities || []) {
|
|
9670
|
+
const id2 = `capability.${slug(cap2.name || "capability")}`;
|
|
9671
|
+
nodes2.push(node(id2, "Capability", cap2.name, { description: cap2.description || null }));
|
|
7741
9672
|
relationships.push(rel(mId, "requires", id2));
|
|
7742
|
-
for (const m of
|
|
9673
|
+
for (const m of cap2.implements || []) {
|
|
7743
9674
|
const target = [`command.${slug(m)}`, `decision.${slug(m)}`, `mission.${slug(m)}`].find((cand) => nodeIds.has(cand));
|
|
7744
9675
|
if (target) relationships.push(rel(id2, "implemented_by", target));
|
|
7745
9676
|
}
|
|
@@ -8004,10 +9935,10 @@ function graphToSource(graph) {
|
|
|
8004
9935
|
const m = String(h.description || "").match(/compensate (.+)$/);
|
|
8005
9936
|
if (m) for (const step of m[1].split(",")) push(` compensate ${step.trim()}`);
|
|
8006
9937
|
}
|
|
8007
|
-
for (const
|
|
8008
|
-
push(`capability ${title(
|
|
8009
|
-
if (
|
|
8010
|
-
for (const m of out(
|
|
9938
|
+
for (const cap2 of byType("Capability")) {
|
|
9939
|
+
push(`capability ${title(cap2)}`);
|
|
9940
|
+
if (cap2.description) push(` description "${cap2.description}"`);
|
|
9941
|
+
for (const m of out(cap2.id, "implemented_by")) push(` implements ${title(m)}`);
|
|
8011
9942
|
}
|
|
8012
9943
|
for (const iface of byType("SystemContract")) {
|
|
8013
9944
|
push(`interface ${title(iface)}`);
|
|
@@ -8394,9 +10325,9 @@ function removeRule(lines, keyword, pluralKeyword, match) {
|
|
|
8394
10325
|
if (s > 0 && out[s - 1] !== void 0 && out[s - 1].trim() === "" && (out[s] === void 0 || out[s].trim() === "")) out.splice(s - 1, 1);
|
|
8395
10326
|
return { ok: true, lines: out };
|
|
8396
10327
|
}
|
|
8397
|
-
const
|
|
8398
|
-
if (
|
|
8399
|
-
for (let i =
|
|
10328
|
+
const plural2 = bs.find((b) => b.keyword === pluralKeyword);
|
|
10329
|
+
if (plural2) {
|
|
10330
|
+
for (let i = plural2.start + 1; i <= plural2.end; i++) {
|
|
8400
10331
|
if (lines[i].trim() && !lines[i].trim().startsWith("#") && lines[i].toLowerCase().includes(needle)) {
|
|
8401
10332
|
return { ok: true, lines: [...lines.slice(0, i), ...lines.slice(i + 1)] };
|
|
8402
10333
|
}
|
|
@@ -8733,7 +10664,7 @@ var IR_ONLY_REL_TYPES = [
|
|
|
8733
10664
|
"conflicts_with"
|
|
8734
10665
|
];
|
|
8735
10666
|
var IR_RELATIONSHIP_TYPES = [.../* @__PURE__ */ new Set([...RELATIONSHIP_TYPES, ...IR_ONLY_REL_TYPES])];
|
|
8736
|
-
var
|
|
10667
|
+
var PROVENANCE2 = [
|
|
8737
10668
|
"user-authored",
|
|
8738
10669
|
"imported",
|
|
8739
10670
|
"deterministically-discovered",
|
|
@@ -8828,7 +10759,7 @@ function validateIR(ir) {
|
|
|
8828
10759
|
else if (ids.has(n.id)) err(`nodes[${i}].id`, `duplicate node id "${n.id}"`);
|
|
8829
10760
|
else ids.add(n.id);
|
|
8830
10761
|
if (!NODE_SET.has(n.type)) err(`nodes[${i}].type`, `unknown node type "${n.type}"`);
|
|
8831
|
-
if (n.provenance && !
|
|
10762
|
+
if (n.provenance && !PROVENANCE2.includes(n.provenance)) err(`nodes[${i}].provenance`, `unknown provenance "${n.provenance}"`);
|
|
8832
10763
|
if (n.confidence && !IR_CONFIDENCE.includes(n.confidence)) err(`nodes[${i}].confidence`, `unknown confidence "${n.confidence}"`);
|
|
8833
10764
|
if (n.sensitivity && !SENSITIVITY.includes(n.sensitivity)) err(`nodes[${i}].sensitivity`, `unknown sensitivity "${n.sensitivity}"`);
|
|
8834
10765
|
if (n.provenance && !isFactualProvenance(n.provenance)) {
|
|
@@ -8932,9 +10863,9 @@ var SECRET_TYPES3 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jw
|
|
|
8932
10863
|
var SECRET_NAME = /pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card/i;
|
|
8933
10864
|
var isSecretField = (f) => f && (SECRET_TYPES3.has(String(f.type || "").toLowerCase()) || SECRET_NAME.test(f.name || ""));
|
|
8934
10865
|
function pascalish(text) {
|
|
8935
|
-
const
|
|
8936
|
-
if (
|
|
8937
|
-
return
|
|
10866
|
+
const words6 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
|
|
10867
|
+
if (words6.length === 1) return words6[0].charAt(0).toUpperCase() + words6[0].slice(1);
|
|
10868
|
+
return words6.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
|
|
8938
10869
|
}
|
|
8939
10870
|
var normRules = (list) => (Array.isArray(list) ? list : []).map((r) => typeof r === "string" ? { statement: r } : { ...r }).filter((r) => r.statement);
|
|
8940
10871
|
function draftIntent(brief = {}) {
|
|
@@ -10603,152 +12534,6 @@ function translateDecisions(ast, lang) {
|
|
|
10603
12534
|
}
|
|
10604
12535
|
return out.join("\n");
|
|
10605
12536
|
}
|
|
10606
|
-
|
|
10607
|
-
// src/read-repo.mjs
|
|
10608
|
-
var READ_REPO_SCHEMA = "thunder-repo-reading-v1";
|
|
10609
|
-
var EXT_LANG = [
|
|
10610
|
-
[/\.d\.ts$/i, null],
|
|
10611
|
-
[/\.min\.js$/i, null],
|
|
10612
|
-
[/\.(ts|tsx|mts|cts)$/i, "typescript"],
|
|
10613
|
-
[/\.(js|jsx|mjs|cjs)$/i, "javascript"],
|
|
10614
|
-
[/\.pyi?$/i, "python"],
|
|
10615
|
-
[/\.go$/i, "go"],
|
|
10616
|
-
[/\.rs$/i, "rust"],
|
|
10617
|
-
[/\.cs$/i, "csharp"],
|
|
10618
|
-
[/\.java$/i, "java"],
|
|
10619
|
-
[/\.kts?$/i, "kotlin"],
|
|
10620
|
-
[/\.php$/i, "php"],
|
|
10621
|
-
[/\.rb$/i, "ruby"]
|
|
10622
|
-
];
|
|
10623
|
-
var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
10624
|
-
"node_modules",
|
|
10625
|
-
".git",
|
|
10626
|
-
"dist",
|
|
10627
|
-
"build",
|
|
10628
|
-
"out",
|
|
10629
|
-
".next",
|
|
10630
|
-
".nuxt",
|
|
10631
|
-
".vercel",
|
|
10632
|
-
".turbo",
|
|
10633
|
-
"coverage",
|
|
10634
|
-
"vendor",
|
|
10635
|
-
"target",
|
|
10636
|
-
"bin",
|
|
10637
|
-
"obj",
|
|
10638
|
-
"__pycache__",
|
|
10639
|
-
".venv",
|
|
10640
|
-
"venv",
|
|
10641
|
-
"env",
|
|
10642
|
-
".tox",
|
|
10643
|
-
".mypy_cache",
|
|
10644
|
-
".gradle",
|
|
10645
|
-
".idea",
|
|
10646
|
-
".vscode",
|
|
10647
|
-
".intent",
|
|
10648
|
-
"third_party",
|
|
10649
|
-
"Pods",
|
|
10650
|
-
".terraform"
|
|
10651
|
-
]);
|
|
10652
|
-
function readableLanguage(path) {
|
|
10653
|
-
const p = String(path).replace(/\\/g, "/");
|
|
10654
|
-
if (p.split("/").some((seg) => READ_SKIP_DIRS.has(seg))) return null;
|
|
10655
|
-
for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
|
|
10656
|
-
return null;
|
|
10657
|
-
}
|
|
10658
|
-
function looksGenerated(source) {
|
|
10659
|
-
const lines = source.split("\n");
|
|
10660
|
-
if (/^\s*(\/\/|#)\s*(Code generated|@generated|<auto-generated)/im.test(lines.slice(0, 5).join("\n"))) return true;
|
|
10661
|
-
const long = lines.filter((l) => l.length > 400).length;
|
|
10662
|
-
return long > 3 && long / lines.length > 0.2;
|
|
10663
|
-
}
|
|
10664
|
-
var topFolder = (path) => {
|
|
10665
|
-
const parts = String(path).replace(/\\/g, "/").split("/");
|
|
10666
|
-
return parts.length > 1 ? parts[0] : ".";
|
|
10667
|
-
};
|
|
10668
|
-
function readRepo(files, { maxFileBytes = 4e5, maxFiles = 5e3 } = {}) {
|
|
10669
|
-
const items = [], fileSummaries = [], skipped = [];
|
|
10670
|
-
let considered = 0;
|
|
10671
|
-
for (const f of files || []) {
|
|
10672
|
-
const path = String(f.path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
10673
|
-
const language = readableLanguage(path);
|
|
10674
|
-
if (!language) continue;
|
|
10675
|
-
considered++;
|
|
10676
|
-
if (considered > maxFiles) {
|
|
10677
|
-
skipped.push({ path, reason: `More than ${maxFiles} files; read a smaller folder to include this one.` });
|
|
10678
|
-
continue;
|
|
10679
|
-
}
|
|
10680
|
-
const source = String(f.source ?? "");
|
|
10681
|
-
if (source.length > maxFileBytes || (f.size ?? 0) > maxFileBytes) {
|
|
10682
|
-
skipped.push({ path, reason: `Larger than ${Math.round(maxFileBytes / 1e3)} KB.` });
|
|
10683
|
-
continue;
|
|
10684
|
-
}
|
|
10685
|
-
if (looksGenerated(source)) {
|
|
10686
|
-
skipped.push({ path, reason: "Looks generated or minified." });
|
|
10687
|
-
continue;
|
|
10688
|
-
}
|
|
10689
|
-
let reading;
|
|
10690
|
-
try {
|
|
10691
|
-
reading = readCode(source, { language, file: path });
|
|
10692
|
-
} catch (e) {
|
|
10693
|
-
skipped.push({ path, reason: e instanceof Error ? e.message : "Could not be read." });
|
|
10694
|
-
continue;
|
|
10695
|
-
}
|
|
10696
|
-
for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
|
|
10697
|
-
fileSummaries.push({ path, language, counts: reading.counts });
|
|
10698
|
-
}
|
|
10699
|
-
return { schema: READ_REPO_SCHEMA, ...summarize(items, fileSummaries), skipped };
|
|
10700
|
-
}
|
|
10701
|
-
function summarize(items, files) {
|
|
10702
|
-
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
10703
|
-
const languages = {}, folders = {}, answers = /* @__PURE__ */ new Map(), inputs = /* @__PURE__ */ new Map();
|
|
10704
|
-
for (const f of files) {
|
|
10705
|
-
languages[f.language] = (languages[f.language] || 0) + 1;
|
|
10706
|
-
const top = topFolder(f.path);
|
|
10707
|
-
folders[top] = (folders[top] || 0) + 1;
|
|
10708
|
-
}
|
|
10709
|
-
for (const it of items) {
|
|
10710
|
-
counts[it.kind]++;
|
|
10711
|
-
if (it.status === "partial") counts.partial++;
|
|
10712
|
-
if (it.guards?.length) counts.guarded++;
|
|
10713
|
-
if (it.route) counts.route++;
|
|
10714
|
-
const guardAnswers = (it.guards || []).filter((g) => ["fails", "responds", "returns"].includes(g.effect.kind)).map((g) => g.effect.name);
|
|
10715
|
-
if (it.kind !== "decision" && !guardAnswers.length) continue;
|
|
10716
|
-
for (const result of new Set([...(it.rules || []).map((r) => r.result), it.otherwise?.result, ...guardAnswers].filter(Boolean))) {
|
|
10717
|
-
if (!answers.has(result)) answers.set(result, []);
|
|
10718
|
-
answers.get(result).push(it.id);
|
|
10719
|
-
}
|
|
10720
|
-
if (it.kind !== "decision") continue;
|
|
10721
|
-
for (const p of it.inputs || []) {
|
|
10722
|
-
if (!inputs.has(p.name)) inputs.set(p.name, []);
|
|
10723
|
-
inputs.get(p.name).push(it.id);
|
|
10724
|
-
}
|
|
10725
|
-
}
|
|
10726
|
-
const byUse = (m) => [...m].map(([name, ids]) => ({ name, decisions: ids })).sort((a, b) => b.decisions.length - a.decisions.length || a.name.localeCompare(b.name));
|
|
10727
|
-
return { files, items, counts, languages, folders, answers: byUse(answers), inputs: byUse(inputs) };
|
|
10728
|
-
}
|
|
10729
|
-
function searchRepo(index, { query = "", kinds = [], status = [], languages = [], path = "", answer = "", input = "" } = {}) {
|
|
10730
|
-
const terms = String(query).trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
10731
|
-
const prefix = String(path).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
10732
|
-
return index.items.filter((it) => {
|
|
10733
|
-
if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes("guard") && it.guards?.length) && !(kinds.includes("route") && it.route)) return false;
|
|
10734
|
-
if (status.length && !status.includes(it.status)) return false;
|
|
10735
|
-
if (languages.length && !languages.includes(it.language)) return false;
|
|
10736
|
-
if (prefix && !it.file.startsWith(prefix)) return false;
|
|
10737
|
-
if (answer && !((it.rules || []).some((r) => r.result === answer) || it.otherwise?.result === answer || (it.guards || []).some((g) => g.effect.name === answer))) return false;
|
|
10738
|
-
if (input && !(it.inputs || []).some((p) => p.name === input)) return false;
|
|
10739
|
-
if (!terms.length) return true;
|
|
10740
|
-
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].filter(Boolean).join(" ").toLowerCase();
|
|
10741
|
-
return terms.every((t) => hay.includes(t));
|
|
10742
|
-
});
|
|
10743
|
-
}
|
|
10744
|
-
function groupByFile(items) {
|
|
10745
|
-
const groups = /* @__PURE__ */ new Map();
|
|
10746
|
-
for (const it of items) {
|
|
10747
|
-
if (!groups.has(it.file)) groups.set(it.file, []);
|
|
10748
|
-
groups.get(it.file).push(it);
|
|
10749
|
-
}
|
|
10750
|
-
return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
|
|
10751
|
-
}
|
|
10752
12537
|
// Annotate the CommonJS export names for ESM import in node:
|
|
10753
12538
|
0 && (module.exports = {
|
|
10754
12539
|
ACCESSIBILITY_CLASSIFICATION,
|
|
@@ -10789,6 +12574,7 @@ function groupByFile(items) {
|
|
|
10789
12574
|
IR_RELATIONSHIP_TYPES,
|
|
10790
12575
|
IR_SCHEMA,
|
|
10791
12576
|
KNOWN_LENSES,
|
|
12577
|
+
MODEL_SCHEMA,
|
|
10792
12578
|
MODE_VALUES,
|
|
10793
12579
|
NODE_FIELDS,
|
|
10794
12580
|
NODE_STATUSES,
|
|
@@ -10813,10 +12599,12 @@ function groupByFile(items) {
|
|
|
10813
12599
|
RULE_OWNERS,
|
|
10814
12600
|
RULE_PHASES,
|
|
10815
12601
|
RUNTIME_SCHEMA,
|
|
12602
|
+
SAME_SCHEMA,
|
|
10816
12603
|
SCAN_SCHEMA,
|
|
10817
12604
|
SCHEMA_VERSION,
|
|
10818
12605
|
SCOPE_TYPES,
|
|
10819
12606
|
SEED_SCHEMA,
|
|
12607
|
+
SEMANTIC_TYPES,
|
|
10820
12608
|
SENSITIVITY,
|
|
10821
12609
|
STEPS_SCHEMA,
|
|
10822
12610
|
STYLE_ADDRESS_SPACE,
|
|
@@ -10824,6 +12612,10 @@ function groupByFile(items) {
|
|
|
10824
12612
|
SUPPORTED_LANGUAGES,
|
|
10825
12613
|
SYNC_SCHEMA,
|
|
10826
12614
|
TEST_SCHEMA,
|
|
12615
|
+
THING_LANGUAGES,
|
|
12616
|
+
THUNDERIZE_SCHEMA,
|
|
12617
|
+
THUNDER_TEXT_EXT,
|
|
12618
|
+
THUNDER_VISUAL,
|
|
10827
12619
|
TOKEN_PATHS,
|
|
10828
12620
|
TRANSLATE_LANGUAGES,
|
|
10829
12621
|
TWELVE_FACTOR_SCHEMA,
|
|
@@ -10831,11 +12623,14 @@ function groupByFile(items) {
|
|
|
10831
12623
|
VERIFICATION_RULES,
|
|
10832
12624
|
VIEWS,
|
|
10833
12625
|
VIEW_SCHEMA,
|
|
12626
|
+
VISUAL_SCHEMA,
|
|
10834
12627
|
WRITE_SCHEMA,
|
|
10835
12628
|
analyzeStyle,
|
|
10836
12629
|
anchorReport,
|
|
10837
12630
|
applyEdits,
|
|
12631
|
+
askAsQuestion,
|
|
10838
12632
|
atlasNode,
|
|
12633
|
+
autocorrectSource,
|
|
10839
12634
|
blocksProduction,
|
|
10840
12635
|
buildArchitectureGraph,
|
|
10841
12636
|
buildAtlas,
|
|
@@ -10851,25 +12646,33 @@ function groupByFile(items) {
|
|
|
10851
12646
|
checkDecisionCases,
|
|
10852
12647
|
classify,
|
|
10853
12648
|
classifyStatement,
|
|
12649
|
+
compareRules,
|
|
10854
12650
|
compileExpr,
|
|
10855
12651
|
compileGuard,
|
|
10856
12652
|
compileHumanContract,
|
|
10857
12653
|
compilePlainContract,
|
|
10858
12654
|
compileSource,
|
|
12655
|
+
completenessOf,
|
|
10859
12656
|
comprehensionLevel,
|
|
10860
12657
|
comprehensionReport,
|
|
12658
|
+
conditionText,
|
|
10861
12659
|
confidenceFromClassification,
|
|
10862
12660
|
contradictionsView,
|
|
10863
12661
|
coverageView,
|
|
10864
12662
|
detectLanguage,
|
|
10865
12663
|
diffGraphs,
|
|
12664
|
+
displayLabel,
|
|
10866
12665
|
draftIntent,
|
|
10867
12666
|
editStep,
|
|
10868
12667
|
evalExpr,
|
|
10869
12668
|
evaluateDecision,
|
|
10870
12669
|
expandNode,
|
|
10871
12670
|
explainPlain,
|
|
12671
|
+
flowOf,
|
|
10872
12672
|
gapsView,
|
|
12673
|
+
getCodeActions,
|
|
12674
|
+
getCompletions,
|
|
12675
|
+
getHover,
|
|
10873
12676
|
graphToIR,
|
|
10874
12677
|
graphToSource,
|
|
10875
12678
|
groupByFile,
|
|
@@ -10889,10 +12692,12 @@ function groupByFile(items) {
|
|
|
10889
12692
|
makeEvent,
|
|
10890
12693
|
makeScope,
|
|
10891
12694
|
mergeGraphs,
|
|
12695
|
+
modelText,
|
|
10892
12696
|
normalizeSeeds,
|
|
10893
12697
|
parseIntent,
|
|
10894
12698
|
parsePlainContract,
|
|
10895
12699
|
parseToStructured,
|
|
12700
|
+
plainFromReading,
|
|
10896
12701
|
plainToThunder,
|
|
10897
12702
|
previewHumanContract,
|
|
10898
12703
|
previewPlainContract,
|
|
@@ -10909,14 +12714,17 @@ function groupByFile(items) {
|
|
|
10909
12714
|
renderMermaid,
|
|
10910
12715
|
renderPlainContract,
|
|
10911
12716
|
renderReviewBrief,
|
|
12717
|
+
renderSame,
|
|
10912
12718
|
renderTestplan,
|
|
10913
12719
|
replaceSpan,
|
|
10914
12720
|
resolveObligations,
|
|
10915
12721
|
reviewAtlasExitCode,
|
|
10916
12722
|
risksView,
|
|
12723
|
+
ruleFlow,
|
|
10917
12724
|
ruleNamespace,
|
|
10918
12725
|
ruleParts,
|
|
10919
12726
|
runTests,
|
|
12727
|
+
sameMeaning,
|
|
10920
12728
|
scanIntent,
|
|
10921
12729
|
scanProject,
|
|
10922
12730
|
searchAtlas,
|
|
@@ -10930,8 +12738,14 @@ function groupByFile(items) {
|
|
|
10930
12738
|
slug,
|
|
10931
12739
|
spanRange,
|
|
10932
12740
|
spanText,
|
|
12741
|
+
stepDoes,
|
|
10933
12742
|
styleDiagnostics,
|
|
10934
12743
|
subjectName,
|
|
12744
|
+
thunderModel,
|
|
12745
|
+
thunderText,
|
|
12746
|
+
thunderTokens,
|
|
12747
|
+
thunderizeFile,
|
|
12748
|
+
thunderizeFiles,
|
|
10935
12749
|
toCSharp,
|
|
10936
12750
|
toCss,
|
|
10937
12751
|
toDesignTokens,
|
|
@@ -10947,5 +12761,7 @@ function groupByFile(items) {
|
|
|
10947
12761
|
unverifiedView,
|
|
10948
12762
|
validateIR,
|
|
10949
12763
|
validateProof,
|
|
12764
|
+
visualFor,
|
|
12765
|
+
visualForStep,
|
|
10950
12766
|
writeRule
|
|
10951
12767
|
});
|