@skillstech/thunderlang 0.5.9 → 0.5.10

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/dist/core.cjs CHANGED
@@ -190,9 +190,11 @@ __export(core_exports, {
190
190
  promoteDecision: () => promoteDecision,
191
191
  proposeIntent: () => proposeIntent,
192
192
  readCode: () => readCode,
193
+ readFiles: () => readFiles,
193
194
  readLevel: () => readLevel,
194
195
  readRepo: () => readRepo,
195
196
  readableLanguage: () => readableLanguage,
197
+ readingOf: () => readingOf,
196
198
  renderExampleTable: () => renderExampleTable,
197
199
  renderHumanContract: () => renderHumanContract,
198
200
  renderLensDoc: () => renderLensDoc,
@@ -1996,10 +1998,453 @@ function renderExampleTable(inputs, rows) {
1996
1998
  return [header, header.map(() => "---"), ...values].map((row) => `| ${row.map(cell).join(" | ")} |`).join("\n");
1997
1999
  }
1998
2000
 
2001
+ // src/sql.mjs
2002
+ var words2 = (s) => String(s).replace(/^["`[]|["`\]]$/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
2003
+ var unquote = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/, "$1");
2004
+ var bare = (name) => unquote(String(name).split(".").pop());
2005
+ var singular = (w) => w.replace(/ies$/, "y").replace(/(ss|sh|ch|x)es$/, "$1").replace(/([^s])s$/, "$1");
2006
+ var article = (w) => /^[aeiou]/i.test(w) ? `an ${w}` : `a ${w}`;
2007
+ function lineFinder(src) {
2008
+ const starts = [0];
2009
+ for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
2010
+ return (idx) => {
2011
+ let lo = 0, hi = starts.length - 1;
2012
+ while (lo < hi) {
2013
+ const mid = lo + hi + 1 >> 1;
2014
+ if (starts[mid] <= idx) lo = mid;
2015
+ else hi = mid - 1;
2016
+ }
2017
+ return lo + 1;
2018
+ };
2019
+ }
2020
+ function mask(src) {
2021
+ let out = "";
2022
+ for (let i = 0; i < src.length; i++) {
2023
+ const c = src[i];
2024
+ if (c === "-" && src[i + 1] === "-") {
2025
+ const n = src.indexOf("\n", i);
2026
+ const end = n < 0 ? src.length : n;
2027
+ out += " ".repeat(end - i);
2028
+ i = end - 1;
2029
+ continue;
2030
+ }
2031
+ if (c === "/" && src[i + 1] === "*") {
2032
+ const n = src.indexOf("*/", i + 2);
2033
+ const end = n < 0 ? src.length : n + 2;
2034
+ out += src.slice(i, end).replace(/[^\n]/g, " ");
2035
+ i = end - 1;
2036
+ continue;
2037
+ }
2038
+ if (c === "'") {
2039
+ let j = i + 1;
2040
+ for (; j < src.length; j++) {
2041
+ if (src[j] === "'" && src[j + 1] === "'") {
2042
+ j++;
2043
+ continue;
2044
+ }
2045
+ if (src[j] === "'") break;
2046
+ }
2047
+ out += "'" + src.slice(i + 1, j).replace(/[^\n]/g, "x") + (j < src.length ? "'" : "");
2048
+ i = j;
2049
+ continue;
2050
+ }
2051
+ out += c;
2052
+ }
2053
+ return out;
2054
+ }
2055
+ function parenEnd(m, open) {
2056
+ for (let i = open, d = 0; i < m.length; i++) {
2057
+ if (m[i] === "(") d++;
2058
+ else if (m[i] === ")" && --d === 0) return i;
2059
+ }
2060
+ return -1;
2061
+ }
2062
+ function splitTop(text, masked = mask(text)) {
2063
+ const out = [];
2064
+ let d = 0, start = 0;
2065
+ for (let i = 0; i < masked.length; i++) {
2066
+ if (masked[i] === "(") d++;
2067
+ else if (masked[i] === ")") d--;
2068
+ else if (masked[i] === "," && d === 0) {
2069
+ out.push({ text: text.slice(start, i), at: start });
2070
+ start = i + 1;
2071
+ }
2072
+ }
2073
+ out.push({ text: text.slice(start), at: start });
2074
+ return out.filter((p) => p.text.trim());
2075
+ }
2076
+ function docAbove(src, idx) {
2077
+ const lines = src.slice(0, idx).split("\n");
2078
+ lines.pop();
2079
+ const run = [];
2080
+ for (let k = lines.length - 1; k >= 0 && /^\s*--/.test(lines[k]); k--) run.unshift(lines[k].replace(/^\s*--+\s?/, "").trim());
2081
+ const text = run.filter(Boolean).join(" ");
2082
+ return text || null;
2083
+ }
2084
+ var TYPE_WORDS = [
2085
+ [/^(small|big)?serial\b|^serial\d/i, "a number, given automatically"],
2086
+ [/^(int|integer|smallint|bigint|tinyint|mediumint|numeric|decimal|real|float|double|money|number)\b|^int\d/i, "a number"],
2087
+ [/^(text|varchar|char|character|nvarchar|nchar|citext|string|clob)\b/i, "words"],
2088
+ [/^(bool|boolean|bit)\b/i, "yes or no"],
2089
+ [/^(date|time|timestamp|timestamptz|datetime|datetime2|interval)\b/i, "a date"],
2090
+ [/^uuid\b|^uniqueidentifier\b/i, "an id"],
2091
+ [/^jsonb?\b/i, "structured data"],
2092
+ [/^(bytea|blob|binary|varbinary)\b/i, "a file or bytes"]
2093
+ ];
2094
+ var typeWords = (t) => {
2095
+ for (const [re, w] of TYPE_WORDS) if (re.test(String(t).trim())) return w;
2096
+ return /\[\]$/.test(String(t).trim()) ? "a list" : null;
2097
+ };
2098
+ function defaultWords(v) {
2099
+ const e = String(v).trim().replace(/::\w+(\[\])?$/, "");
2100
+ if (/^null$/i.test(e)) return "nothing at first";
2101
+ if (/^(true|false)$/i.test(e)) return `${/^true$/i.test(e) ? "yes" : "no"} at first`;
2102
+ if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
2103
+ if (/^'.*'$/s.test(e)) return `"${e.slice(1, -1).replace(/''/g, "'")}" at first`;
2104
+ if (/^(now\(\)|current_timestamp|current_date|getdate\(\)|sysdate|localtimestamp|transaction_timestamp\(\))$/i.test(e)) return "the moment it is saved";
2105
+ if (/gen_random_uuid|uuid_generate|newid\(\)/i.test(e)) return "a new id";
2106
+ return "worked out when it is saved";
2107
+ }
2108
+ function sqlCondition(cond, { aliases = {}, vars = false } = {}) {
2109
+ let c = String(cond).trim().replace(/\s+/g, " ");
2110
+ while (/^\(.*\)$/.test(c) && parenEnd(mask(c), 0) === c.length - 1) c = c.slice(1, -1).trim();
2111
+ c = c.replace(/'((?:[^']|'')*)'/g, (m, v) => `"${v.replace(/''/g, "'")}"`);
2112
+ const plain = (x) => words2(vars ? String(x).replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, "") : x);
2113
+ const name = (x) => {
2114
+ const p = String(x).split(".");
2115
+ if (p.length < 2) return plain(x);
2116
+ const table = aliases[p[0].toLowerCase()] ?? p[0];
2117
+ return `the ${singular(words2(table))}'s ${words2(p[1])}`;
2118
+ };
2119
+ return c.replace(/\b(NEW|OLD)\.(\w+)/g, (m, which, col) => `the ${which === "NEW" ? "new" : "old"} ${words2(col)}`).replace(/([\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is not one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => /^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`).replace(/([\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is empty`).replace(/([\w.]+)\s+NOT\s+LIKE\s+"([^"]*)"/gi, (m, a, p) => `${name(a)} does not match "${p.replace(/%/g, "\u2026")}"`).replace(/([\w.]+)\s+I?LIKE\s+"([^"]*)"/gi, (m, a, p) => /^[^%]+%$/.test(p) ? `${name(a)} starts with "${p.slice(0, -1)}"` : /^%[^%]+%$/.test(p) ? `${name(a)} contains "${p.slice(1, -1)}"` : `${name(a)} matches "${p.replace(/%/g, "\u2026")}"`).replace(/([\w."]+)\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)/gi, (m, a, lo, hi) => `${name(a)} is from ${lo} to ${hi}`).replace(/\s*(<>|!=)\s*/g, " is not ").replace(/\s*>=\s*/g, " is at least ").replace(/\s*<=\s*/g, " is at most ").replace(/\s*>\s*/g, " is more than ").replace(/\s*<\s*/g, " is less than ").replace(/\s*=\s*/g, " is ").replace(/\bAND\b/gi, "and").replace(/\bOR\b/gi, "or").replace(/\bNOT\s+/gi, "not ").replace(/\b(?:length|char_length)\s*\(\s*([\w."]+)\s*\)/gi, (m, a) => `the length of ${name(a)}`).replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b)([a-z_][\w]*\.)?([a-z_][\w]*)\b(?![^"]*"(?:[^"]*"[^"]*")*[^"]*$)/gi, (m, t, col) => t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)).replace(/\s+/g, " ").trim();
2120
+ }
2121
+ function readSchema(src) {
2122
+ const m = mask(src);
2123
+ const lineAt2 = lineFinder(src);
2124
+ const tables = [], choices = [], rules = [];
2125
+ const docs = /* @__PURE__ */ new Map();
2126
+ for (const c of src.matchAll(/COMMENT\s+ON\s+TABLE\s+([\w."]+)\s+IS\s+'((?:[^']|'')*)'/gi)) docs.set(bare(c[1]).toLowerCase(), c[2].replace(/''/g, "'"));
2127
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."[\]`]+)\s*\(/gi)) {
2128
+ const open = t.index + t[0].length - 1;
2129
+ const close = parenEnd(m, open);
2130
+ if (close < 0) continue;
2131
+ const name = bare(src.slice(t.index, open).match(/([\w."[\]`]+)\s*$/)[1]);
2132
+ const table = { name, lines: [lineAt2(t.index), lineAt2(close)], doc: docs.get(name.toLowerCase()) ?? docAbove(src, t.index), columns: [], checks: [], uniques: [], refs: [] };
2133
+ for (const part of splitTop(src.slice(open + 1, close), m.slice(open + 1, close))) {
2134
+ const text = part.text.trim().replace(/\s+/g, " ");
2135
+ const line = lineAt2(open + 1 + part.at + (part.text.length - part.text.trimStart().length));
2136
+ let x;
2137
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"]+)\s+)?CHECK\s*\((.*)\)$/i)) {
2138
+ table.checks.push({ name: x[1] && unquote(x[1]), cond: x[2], line });
2139
+ continue;
2140
+ }
2141
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"`]+)\s+)?UNIQUE(?:\s+(?:KEY|INDEX))?(?:\s+([\w"`]+))?\s*\(([^)]*)\)/i)) {
2142
+ table.uniques.push({ name: (x[1] || x[2]) && unquote(x[1] || x[2]), cols: x[3].split(",").map((c) => unquote(c.trim())), line });
2143
+ continue;
2144
+ }
2145
+ if (x = text.match(/^(?:CONSTRAINT\s+[\w"]+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s+REFERENCES\s+([\w."]+)/i)) {
2146
+ for (const c of x[1].split(",")) table.refs.push({ col: unquote(c.trim()), to: bare(x[2]) });
2147
+ continue;
2148
+ }
2149
+ if (/^(?:CONSTRAINT\s+[\w"]+\s+)?(PRIMARY\s+KEY|INDEX|KEY|EXCLUDE)\b/i.test(text)) continue;
2150
+ const col = text.match(/^([\w"`[\]]+)\s+([\w]+(?:\s*\([^)]*\))?(?:\s+(?:varying|precision|with(?:out)?\s+time\s+zone))*(?:\[\])?)(.*)$/i);
2151
+ if (!col || /^(LIKE|PERIOD)$/i.test(col[1])) continue;
2152
+ const rest2 = col[3] || "";
2153
+ const ref = rest2.match(/\bREFERENCES\s+([\w."]+)/i);
2154
+ const def = rest2.match(/\bDEFAULT\s+('(?:[^']|'')*'|\([^)]*\)|[\w.:]+(?:\(\))?)/i);
2155
+ const column = { name: unquote(col[1]), type: col[2], line, primary: /\bPRIMARY\s+KEY\b/i.test(rest2), notNull: /\bNOT\s+NULL\b/i.test(rest2), ...def ? { default: def[1] } : {}, ...ref ? { ref: bare(ref[1]) } : {} };
2156
+ table.columns.push(column);
2157
+ const check = rest2.match(/\bCHECK\s*\((.*)\)/i);
2158
+ if (check) table.checks.push({ cond: check[1], line });
2159
+ if (/\bUNIQUE\b/i.test(rest2)) table.uniques.push({ cols: [column.name], line });
2160
+ }
2161
+ tables.push(table);
2162
+ }
2163
+ for (const e of m.matchAll(/\bCREATE\s+TYPE\s+([\w."]+)\s+AS\s+ENUM\s*\(/gi)) {
2164
+ const open = e.index + e[0].length - 1;
2165
+ const close = parenEnd(m, open);
2166
+ if (close < 0) continue;
2167
+ const values = [...src.slice(open + 1, close).matchAll(/'((?:[^']|'')*)'/g)].map((v) => v[1].replace(/''/g, "'").replace(/_/g, " "));
2168
+ choices.push({ name: bare(e[1]), lines: [lineAt2(e.index), lineAt2(close)], doc: docAbove(src, e.index), values });
2169
+ }
2170
+ for (const t of tables) {
2171
+ for (const c of t.checks) rules.push({ table: t.name, kind: "check", ...c });
2172
+ for (const u of t.uniques) rules.push({ table: t.name, kind: "unique", ...u });
2173
+ }
2174
+ return { tables, choices, rules };
2175
+ }
2176
+ function sqlThings(src, file) {
2177
+ const { tables, choices } = readSchema(src);
2178
+ const enums = new Set(choices.map((c) => c.name.toLowerCase()));
2179
+ const out = [];
2180
+ for (const t of tables) {
2181
+ const refs = new Map(t.refs.map((r) => [r.col, r.to]));
2182
+ const knows = t.columns.map((c) => {
2183
+ const to = c.ref ?? refs.get(c.name);
2184
+ const kind = to ? `${article(singular(words2(to)))} (by its id)` : c.primary ? `${typeWords(c.type) ?? "a value"}, the id` : enums.has(bare(c.type).toLowerCase()) ? article(words2(bare(c.type))) : typeWords(c.type);
2185
+ return { name: c.name, label: words2(c.name), kind: kind && c.notNull && !c.primary ? `${kind}, always set` : kind, start: c.default != null ? defaultWords(c.default) : null, line: c.line };
2186
+ });
2187
+ out.push({ kind: t.checks.length || t.uniques.length ? "thing" : "record", name: t.name, file, lines: t.lines, ...t.doc ? { doc: t.doc } : {}, knows, choices: [] });
2188
+ }
2189
+ for (const c of choices) out.push({ kind: "choices", name: c.name, file, lines: c.lines, ...c.doc ? { doc: c.doc } : {}, knows: [], choices: c.values });
2190
+ return out;
2191
+ }
2192
+ var colWords = (expr) => {
2193
+ const e = expr.trim();
2194
+ const as = e.match(/\s+(?:AS\s+)?([\w"]+)$/i);
2195
+ if (as && !/^(DESC|ASC|END)$/i.test(as[1]) && /[\s)]/.test(e.slice(0, as.index + 1))) return words2(unquote(as[1]));
2196
+ const agg = e.match(/^(count|sum|avg|min|max)\s*\(\s*(distinct\s+)?([^)]*)\)$/i);
2197
+ if (agg) {
2198
+ const what = agg[3].trim() === "*" ? "rows" : words2(bare(agg[3]));
2199
+ return { count: `how many ${what === "rows" ? "rows" : what}`, sum: `the total of ${what}`, avg: `the average ${what}`, min: `the lowest ${what}`, max: `the highest ${what}` }[agg[1].toLowerCase()];
2200
+ }
2201
+ if (e === "*") return "every column";
2202
+ if (/^\w+\.\*$/.test(e)) return `every column of ${words2(e.split(".")[0])}`;
2203
+ return /^[\w."]+$/.test(e) ? words2(bare(e)) : "a worked-out value";
2204
+ };
2205
+ var listWords = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
2206
+ function selectSteps(sql, line, { give = true, vars = false } = {}) {
2207
+ const s = sql.replace(/\s+/g, " ").trim().replace(/;$/, "");
2208
+ const m = mask(s);
2209
+ const at = (kw) => {
2210
+ const r = new RegExp(`\\b${kw}\\b`, "i").exec(m);
2211
+ return r ? r.index : -1;
2212
+ };
2213
+ const clauses = ["SELECT", "FROM", "WHERE", "GROUP BY", "HAVING", "ORDER BY", "LIMIT", "OFFSET", "INTO"].map((k) => [k, at(k)]).filter(([, i]) => i >= 0).sort((a, b) => a[1] - b[1]);
2214
+ const part = (k) => {
2215
+ const i = clauses.findIndex(([n]) => n === k);
2216
+ if (i < 0) return null;
2217
+ const start = clauses[i][1] + k.length;
2218
+ const end = clauses[i + 1]?.[1] ?? s.length;
2219
+ return s.slice(start, end).trim();
2220
+ };
2221
+ const steps = [];
2222
+ const code = s;
2223
+ const from = part("FROM");
2224
+ const aliases = {};
2225
+ for (const a of (from || "").matchAll(/([\w."]+)\s+(?:AS\s+)?([a-z_]\w*)\b(?=\s*(?:,|$|\bON\b|\bJOIN\b|\bLEFT\b|\bRIGHT\b|\bINNER\b|\bFULL\b|\bCROSS\b|\bWHERE\b))/gi)) {
2226
+ if (!/^(ON|JOIN|LEFT|RIGHT|INNER|FULL|CROSS|OUTER|WHERE|AS)$/i.test(a[2])) aliases[a[2].toLowerCase()] = bare(a[1]);
2227
+ }
2228
+ const cond = (text) => sqlCondition(text, { aliases, vars });
2229
+ if (from) {
2230
+ const [first, ...joins] = from.split(/\b(?:(?:LEFT|RIGHT|INNER|FULL|CROSS)\s+(?:OUTER\s+)?)?JOIN\b/i);
2231
+ const base = bare(first.trim().split(/\s+/)[0]);
2232
+ steps.push({ kind: "call", callee: "find", says: `Finds the ${words2(base)}`, code, line });
2233
+ for (const j of joins) {
2234
+ const jt = bare(j.trim().split(/\s+/)[0]);
2235
+ const left = /\bLEFT\b/i.test(from.slice(0, from.indexOf(j)).slice(-20));
2236
+ steps.push({ kind: "call", callee: "find", says: `${left ? "Adds, when there is one," : "Adds"} the matching ${words2(singular(jt))} to each`, code, line });
2237
+ }
2238
+ }
2239
+ const where = part("WHERE");
2240
+ if (where) steps.push({ kind: "call", callee: "filter", says: `Keeps only those where ${cond(where)}`, code, line });
2241
+ const group = part("GROUP BY");
2242
+ if (group) steps.push({ kind: "set", says: `Groups them by ${listWords(splitTop(group).map((p) => words2(bare(p.text.trim()))))}`, code, line });
2243
+ const having = part("HAVING");
2244
+ if (having) steps.push({ kind: "call", callee: "filter", says: `Keeps only groups where ${cond(having.replace(/\b(count|sum|avg|min|max)\s*\(([^)]*)\)/gi, (x) => colWords(x).replace(/ /g, "_")))}`.replace(/_/g, " "), code, line });
2245
+ const order = part("ORDER BY");
2246
+ if (order) steps.push({ kind: "set", says: `Sorts them by ${listWords(splitTop(order).map((p) => {
2247
+ const t = p.text.trim();
2248
+ return `${colWords(t.replace(/\s+(ASC|DESC)(\s+NULLS\s+(FIRST|LAST))?$/i, ""))}${/\bDESC\b/i.test(t) ? ", highest first" : ""}`;
2249
+ }))}`, code, line });
2250
+ const limit = part("LIMIT");
2251
+ if (limit && /^\d+/.test(limit)) steps.push({ kind: "set", says: `Takes the first ${limit.match(/^\d+/)[0]}`, code, line });
2252
+ const cols = part("SELECT");
2253
+ if (give && cols) {
2254
+ const names = splitTop(cols.replace(/^DISTINCT\s+/i, "")).map((p) => colWords(p.text));
2255
+ steps.push({ kind: "return", says: `Returns ${listWords(names.length > 8 ? [...names.slice(0, 7), "more"] : names)}`, code, line });
2256
+ }
2257
+ return steps;
2258
+ }
2259
+ function bodyStatement(text, line) {
2260
+ const cnd = (x2) => sqlCondition(x2, { vars: true });
2261
+ const v = (x2) => words2(String(x2).replace(/^(?:p|v|l|var)_(?=\w)/i, ""));
2262
+ const t = text.replace(/\s+/g, " ").trim().replace(/;$/, "");
2263
+ const code = t;
2264
+ let x;
2265
+ if (x = t.match(/^RAISE\s+(?:EXCEPTION|ERROR)\s+'((?:[^']|'')*)'/i)) {
2266
+ const msg = x[1].replace(/''/g, "'").replace(/%/g, "\u2026");
2267
+ return { kind: "fail", says: `Fails with an error: "${msg}"`, error: "an error", message: msg, code, line };
2268
+ }
2269
+ if ((x = t.match(/^(?:RAISERROR|THROW)\s*\(?\s*(?:\d+\s*,\s*)?N?'((?:[^']|'')*)'/i)) || (x = t.match(/^SIGNAL\s+SQLSTATE\s+'\w+'\s+SET\s+MESSAGE_TEXT\s*=\s*'((?:[^']|'')*)'/i))) return { kind: "fail", says: `Fails with an error: "${x[1].replace(/''/g, "'")}"`, error: "an error", message: x[1].replace(/''/g, "'"), code, line };
2270
+ if (x = t.match(/^RETURN\s+QUERY\s+(SELECT\b.*)$/i)) return { kind: "return", says: selectSteps(x[1], line).at(-1)?.says ?? "Returns the rows a query finds", code, line, query: selectSteps(x[1], line, { give: false }) };
2271
+ if (x = t.match(/^RETURN\s+(NEW|OLD)$/i)) return { kind: "return", says: x[1].toUpperCase() === "NEW" ? "Lets the change go ahead" : "Keeps the old row", code, line };
2272
+ if (x = t.match(/^RETURN\s*(.*)$/i)) return { kind: "return", says: x[1] ? /^'(.*)'$/.test(x[1]) ? `Returns "${x[1].slice(1, -1)}"` : /^(true|false)$/i.test(x[1]) ? `Returns ${x[1].toLowerCase() === "true" ? "yes" : "no"}` : `Returns ${cnd(x[1])}` : "Stops here", code, line };
2273
+ if (x = t.match(/^INSERT\s+INTO\s+([\w."]+)(?:\s*\(([^)]*)\))?/i)) return { kind: "call", says: `Records a new ${singular(words2(bare(x[1])))}${x[2] ? ` with ${listWords(x[2].split(",").map((c) => words2(c.trim())))}` : ""}`, code, line };
2274
+ if (x = t.match(/^UPDATE\s+([\w."]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/i)) {
2275
+ const sets = splitTop(x[2]).map((p) => {
2276
+ const kv = p.text.match(/^\s*([\w."]+)\s*=\s*(.*)$/s);
2277
+ return kv ? `${words2(bare(kv[1]))} to ${/^'.*'$/.test(kv[2].trim()) ? `"${kv[2].trim().slice(1, -1)}"` : cnd(kv[2])}` : null;
2278
+ }).filter(Boolean);
2279
+ return { kind: "call", says: `Records the change in ${words2(bare(x[1]))}: sets ${listWords(sets)}${x[3] ? ` where ${cnd(x[3])}` : ""}`, code, line };
2280
+ }
2281
+ if (x = t.match(/^DELETE\s+FROM\s+([\w."]+)(?:\s+WHERE\s+(.*))?$/i)) return { kind: "call", says: `Removes ${words2(bare(x[1]))}${x[2] ? ` where ${cnd(x[2])}` : ""}`, code, line };
2282
+ if (x = t.match(/^SELECT\s+(.*?)\s+INTO\s+(?:STRICT\s+)?([\w,\s]+?)\s+FROM\s+(.*)$/i)) {
2283
+ const from = x[3].match(/^([\w."]+)(?:\s+(?:AS\s+)?\w+)?(?:\s+WHERE\s+(.*))?$/i);
2284
+ const what = listWords(x[2].split(",").map((n) => v(n.trim())));
2285
+ if (from) return { kind: "call", callee: "find", says: `Finds ${what} in the ${words2(bare(from[1]))}${from[2] ? ` where ${cnd(from[2])}` : ""}`, code, line };
2286
+ const found = selectSteps(`SELECT ${x[1]} FROM ${x[3]}`, line, { give: false, vars: true });
2287
+ return { kind: "call", callee: "find", says: `Finds ${what}: ${found.map((f) => f.says.charAt(0).toLowerCase() + f.says.slice(1)).join(", ")}`, code, line };
2288
+ }
2289
+ if (x = t.match(/^(?:PERFORM|CALL|EXEC(?:UTE)?)\s+([\w.]+)\s*\(/i)) return { kind: "call", says: `Runs ${words2(bare(x[1]))}`, code, line };
2290
+ if (x = t.match(/^(?:SET\s+)?@?([\w.]+)\s*:?=\s*(.+)$/i)) return { kind: "set", says: `Sets ${v(bare(x[1]))} to ${/^'.*'$/.test(x[2].trim()) ? `"${x[2].trim().slice(1, -1)}"` : cnd(x[2])}`, code, line };
2291
+ return { kind: "other", says: code, code, line, restates: code };
2292
+ }
2293
+ function procSteps(body, firstLine) {
2294
+ const m = mask(body);
2295
+ const stmts = [];
2296
+ let start = 0;
2297
+ const re = /;|\bTHEN\b|\bELSE\b(?!\s*IF)|\bELSIF\b|\bELSEIF\b|\bEND\s+IF\b|\bBEGIN\b|\bEND\b(?!\s+IF)/gi;
2298
+ const lineAt2 = lineFinder(body);
2299
+ let r;
2300
+ while (r = re.exec(m)) {
2301
+ const kw = r[0].toUpperCase().replace(/\s+/g, " ");
2302
+ if (kw === ";") {
2303
+ const text = body.slice(start, r.index).trim();
2304
+ if (text) stmts.push({ text, line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1 });
2305
+ start = r.index + 1;
2306
+ continue;
2307
+ }
2308
+ if (kw === "THEN") {
2309
+ stmts.push({ text: body.slice(start, r.index).trim(), line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1, then: true });
2310
+ start = r.index + r[0].length;
2311
+ continue;
2312
+ }
2313
+ const before = body.slice(start, r.index).trim();
2314
+ if (before) stmts.push({ text: before, line: firstLine + lineAt2(start) - 1 });
2315
+ stmts.push({ keyword: kw === "ELSEIF" ? "ELSIF" : kw });
2316
+ start = r.index + r[0].length;
2317
+ }
2318
+ const tail = body.slice(start).trim();
2319
+ if (tail) stmts.push({ text: tail, line: firstLine + lineAt2(start) - 1 });
2320
+ let i = 0;
2321
+ const block = (stop) => {
2322
+ const out = [];
2323
+ while (i < stmts.length) {
2324
+ const s = stmts[i];
2325
+ if (s.keyword && stop.includes(s.keyword)) return out;
2326
+ i++;
2327
+ if (s.keyword === "BEGIN" || s.keyword === "END") continue;
2328
+ if (s.then && /^(IF|ELSIF)\b/i.test(s.text)) {
2329
+ const cond = s.text.replace(/^(IF|ELSIF)\s+/i, "");
2330
+ const step = { kind: "branch", says: `If ${sqlCondition(cond, { vars: true })}`, code: s.text, line: s.line, children: block(["ELSIF", "ELSE", "END IF"]) };
2331
+ let tail2 = step;
2332
+ while (stmts[i]?.keyword === "ELSIF") {
2333
+ i++;
2334
+ const h = stmts[i++];
2335
+ const next = { kind: "branch", says: `If ${sqlCondition(h.text.replace(/^ELSIF\s+/i, ""), { vars: true })}`, code: h.text, line: h.line, children: block(["ELSIF", "ELSE", "END IF"]) };
2336
+ tail2.otherwise = [next];
2337
+ tail2 = next;
2338
+ }
2339
+ if (stmts[i]?.keyword === "ELSE") {
2340
+ i++;
2341
+ tail2.otherwise = block(["END IF"]);
2342
+ }
2343
+ if (stmts[i]?.keyword === "END IF") i++;
2344
+ out.push(step);
2345
+ continue;
2346
+ }
2347
+ if (s.text && !/^(DECLARE|LANGUAGE|AS)\b/i.test(s.text) && !/^\w+\s+[\w(),]+(\s*:=.*)?$/.test(s.text) || /:=/.test(s.text ?? "")) {
2348
+ if (s.text && !/^DECLARE\b/i.test(s.text)) out.push(bodyStatement(s.text.replace(/^DECLARE\s+/i, ""), s.line));
2349
+ }
2350
+ }
2351
+ return out;
2352
+ };
2353
+ return block([]);
2354
+ }
2355
+ function sqlItems(src) {
2356
+ const m = mask(src);
2357
+ const lineAt2 = lineFinder(src);
2358
+ const items = [];
2359
+ const push = (name, line, steps, extra = {}) => {
2360
+ const code = steps.filter((s) => s.kind === "other").length;
2361
+ items.push({
2362
+ id: `${name}:${line}`,
2363
+ name,
2364
+ label: words2(name).charAt(0).toUpperCase() + words2(name).slice(1),
2365
+ line,
2366
+ inputs: extra.inputs ?? [],
2367
+ returns: extra.returns ?? null,
2368
+ ...extra.doc ? { doc: extra.doc } : {},
2369
+ provenance: "inferred-from-code",
2370
+ kind: "function",
2371
+ status: "signature-only",
2372
+ steps,
2373
+ stepsMore: 0,
2374
+ stepsReadable: steps.length ? Math.round((steps.length - code) / steps.length * 100) / 100 : 0,
2375
+ says: extra.says ?? `${words2(name)} has ${steps.length} step${steps.length === 1 ? "" : "s"}.`,
2376
+ headline: extra.headline ?? `${words2(name)}.`,
2377
+ guards: [],
2378
+ unread: []
2379
+ });
2380
+ };
2381
+ for (const v of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)(?:\s*\([^)]*\))?\s+AS\s+/gi)) {
2382
+ const end = m.indexOf(";", v.index);
2383
+ const query = src.slice(v.index + v[0].length, end < 0 ? src.length : end);
2384
+ const name = bare(v[1]);
2385
+ push(name, lineAt2(v.index), selectSteps(query, lineAt2(v.index + v[0].length)), { doc: docAbove(src, v.index), says: `${words2(name)} is a saved query.`, headline: `${words2(name)}: a saved query.` });
2386
+ }
2387
+ for (const f of m.matchAll(/\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:DEFINER\s*=\s*\S+\s+)?(FUNCTION|PROCEDURE|PROC)\s+([\w."[\]]+)\s*\(/gi)) {
2388
+ const open = f.index + f[0].length - 1;
2389
+ const close = parenEnd(m, open);
2390
+ if (close < 0) continue;
2391
+ const name = bare(f[2]);
2392
+ const inputs = splitTop(src.slice(open + 1, close)).map((p) => {
2393
+ const pm = p.text.trim().match(/^(?:IN\s+|OUT\s+|INOUT\s+)?@?([\w"]+)\s+(.+?)(?:\s+(?:DEFAULT|=)\s+.+)?$/i);
2394
+ return pm ? { name: unquote(pm[1]).replace(/^p_|^_/, ""), type: pm[2].trim() } : null;
2395
+ }).filter(Boolean);
2396
+ const after = src.slice(close + 1);
2397
+ const ret = after.match(/^\s*RETURNS\s+(TABLE\s*\([^)]*\)|SETOF\s+[\w.]+|[\w.]+(?:\[\])?)/i);
2398
+ const dollar = after.match(/\$(\w*)\$([\s\S]*?)\$\1\$/);
2399
+ const beginAt = mask(after).search(/\bBEGIN\b/i);
2400
+ const bodyText = dollar ? dollar[2] : beginAt >= 0 ? after.slice(beginAt) : "";
2401
+ const bodyStart = close + 1 + (dollar ? dollar.index + dollar[0].indexOf(dollar[2]) : Math.max(beginAt, 0));
2402
+ const isTrigger = ret && /^trigger$/i.test(ret[1]);
2403
+ const steps = procSteps(bodyText, lineAt2(bodyStart));
2404
+ const returns = ret && !isTrigger ? typeWords(ret[1]) ?? (/^(SETOF|TABLE)\b/i.test(ret[1]) ? "rows" : words2(ret[1])) : null;
2405
+ push(name, lineAt2(f.index), steps, {
2406
+ inputs,
2407
+ returns,
2408
+ doc: docAbove(src, f.index),
2409
+ says: `${words2(name)} takes ${inputs.length ? inputs.map((p) => words2(p.name)).join(", ") : "no inputs"}${returns ? ` and returns ${returns}` : ""}.`,
2410
+ headline: `${words2(name)} takes ${inputs.length ? inputs.map((p) => words2(p.name)).join(", ") : "no inputs"}.`
2411
+ });
2412
+ }
2413
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+([\w."]+)\s+(BEFORE|AFTER|INSTEAD\s+OF)\s+([\w\s,]+?)\s+ON\s+([\w."]+)[\s\S]*?EXECUTE\s+(?:FUNCTION|PROCEDURE)\s+([\w.]+)/gi)) {
2414
+ const events = t[3].split(/\s+OR\s+/i).map((e) => ({ INSERT: "added", UPDATE: "changed", DELETE: "removed", TRUNCATE: "emptied" })[e.trim().split(/\s+/)[0].toUpperCase()] || words2(e)).filter(Boolean);
2415
+ const what = article(singular(words2(bare(t[4]))));
2416
+ const when = `${t[2].toUpperCase() === "BEFORE" ? "Before" : t[2].toUpperCase() === "AFTER" ? "After" : "Instead of when"} ${what} is ${events.join(" or ")}`;
2417
+ push(bare(t[1]), lineAt2(t.index), [{ kind: "call", says: `${when}, runs ${words2(bare(t[5]))}`, code: t[0].replace(/\s+/g, " "), line: lineAt2(t.index) }], { says: `${when}, the database runs ${words2(bare(t[5]))}.`, headline: `${when}.`, doc: docAbove(src, t.index) });
2418
+ }
2419
+ for (const r of readSchema(src).rules) {
2420
+ const table = words2(r.table);
2421
+ if (r.kind === "check") {
2422
+ const cond = sqlCondition(r.cond);
2423
+ const name = r.name || `${(r.cond.match(/[a-z_]\w*/i) || ["value"])[0]}_check`;
2424
+ push(
2425
+ name,
2426
+ r.line,
2427
+ [{ kind: "branch", says: `If not: ${cond}`, code: `CHECK (${r.cond})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "The ${singular(table)} needs ${cond.replace(/"/g, "'")}"`, error: "Refused by the database", message: `The ${singular(table)} needs ${cond.replace(/"/g, "'")}`, code: `CHECK (${r.cond})`, line: r.line }] }],
2428
+ { says: `Every ${singular(table)} must have ${cond}.`, headline: `Every ${singular(table)} must have ${cond}.` }
2429
+ );
2430
+ } else {
2431
+ const cols = listWords(r.cols.map(words2));
2432
+ push(
2433
+ r.name || `unique_${r.cols.join("_and_")}`,
2434
+ r.line,
2435
+ [{ kind: "branch", says: `If not: no other ${singular(table)} has the same ${cols}`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "Each ${cols} can be used only once"`, error: "Refused by the database", message: `Each ${cols} can be used only once`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line }] }],
2436
+ { says: `Each ${cols} can be used by only one ${singular(table)}.`, headline: `Each ${cols} can be used by only one ${singular(table)}.` }
2437
+ );
2438
+ }
2439
+ }
2440
+ items.sort((a, b) => a.line - b.line);
2441
+ return items;
2442
+ }
2443
+
1999
2444
  // src/steps.mjs
2000
2445
  var STEPS_SCHEMA = "thunder-steps-v1";
2001
2446
  var MAX_STEPS = 14;
2002
- var words2 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
2447
+ var words3 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
2003
2448
  var clip = (s, n = 70) => {
2004
2449
  const t = String(s).replace(/\s+/g, " ").trim();
2005
2450
  return t.length > n ? `${t.slice(0, n - 1)}\u2026` : t;
@@ -2015,24 +2460,24 @@ var KNOWN_CALLS = [
2015
2460
  ];
2016
2461
  var possessiveWords = (path) => {
2017
2462
  const parts = String(path).replace(/^\$/, "").replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, ".$1").split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x));
2018
- return parts.length > 1 ? `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}` : words2(parts[0] || path);
2463
+ return parts.length > 1 ? `the ${words3(parts[parts.length - 2])}'s ${words3(parts[parts.length - 1])}` : words3(parts[0] || path);
2019
2464
  };
2020
- 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);
2465
+ 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() ? words3(v) : m);
2021
2466
  function sayCodeCondition(cond) {
2022
2467
  let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, "").trim();
2023
2468
  while (c.startsWith("(") && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
2024
2469
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
2025
2470
  const plural2 = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
2026
- if (prop && plural2(words2(prop[3]), !!prop[4])) return `${words2(prop[2])} ${prop[1] ? "has no" : "has"} ${words2(prop[3])}`;
2471
+ if (prop && plural2(words3(prop[3]), !!prop[4])) return `${words3(prop[2])} ${prop[1] ? "has no" : "has"} ${words3(prop[3])}`;
2027
2472
  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));
2028
- if (prop && yesNo(words2(prop[3]), !!prop[4])) {
2473
+ if (prop && yesNo(words3(prop[3]), !!prop[4])) {
2029
2474
  const neg = !!prop[1];
2030
- const w = words2(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
2475
+ const w = words3(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
2031
2476
  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}`;
2032
- return `${words2(prop[2])} ${verb}`;
2477
+ return `${words3(prop[2])} ${verb}`;
2033
2478
  }
2034
2479
  let pred;
2035
- if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words2(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words2(pred[3])}`;
2480
+ if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words3(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words3(pred[3])}`;
2036
2481
  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)}`);
2037
2482
  c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
2038
2483
  let call;
@@ -2042,14 +2487,14 @@ function sayCodeCondition(cond) {
2042
2487
  return call[2] === "isset" || call[2] === "is_null" ? `${what} is ${call[2] === "isset" === !call[1] ? "" : "not "}set` : `${what} is ${neg ? "not " : ""}empty`;
2043
2488
  }
2044
2489
  if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
2045
- const w = words2(call[2]);
2490
+ const w = words3(call[2]);
2046
2491
  return call[1] ? `not: ${w}` : w;
2047
2492
  }
2048
- const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
2049
- if (bare && !/^(true|false|True|False|None|null|nil)$/.test(bare[2])) {
2050
- const parts = bare[2].split(".");
2051
- const what = parts.length > 1 ? `the ${words2(parts[0])}'s ${words2(parts[1])}` : words2(parts[0]);
2052
- return `${what} is ${bare[1] ? "not " : ""}set`;
2493
+ const bare2 = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
2494
+ if (bare2 && !/^(true|false|True|False|None|null|nil)$/.test(bare2[2])) {
2495
+ const parts = bare2[2].split(".");
2496
+ const what = parts.length > 1 ? `the ${words3(parts[0])}'s ${words3(parts[1])}` : words3(parts[0]);
2497
+ return `${what} is ${bare2[1] ? "not " : ""}set`;
2053
2498
  }
2054
2499
  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);
2055
2500
  }
@@ -2061,11 +2506,11 @@ function matchingClose(str, open) {
2061
2506
  }
2062
2507
  return -1;
2063
2508
  }
2064
- var lastWords = (path) => words2(String(path).split(".").pop());
2509
+ var lastWords = (path) => words3(String(path).split(".").pop());
2065
2510
  function targetWords(path) {
2066
2511
  const parts = String(path).replace(/^[@$]+/, "").replace(/#/g, "").replace(/\[.*$/, "").split(".").filter((p) => !/^(this|self)$/.test(p));
2067
- if (parts.length <= 1) return words2(parts[0] || path);
2068
- return `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}`;
2512
+ if (parts.length <= 1) return words3(parts[0] || path);
2513
+ return `the ${words3(parts[parts.length - 2])}'s ${words3(parts[parts.length - 1])}`;
2069
2514
  }
2070
2515
  function callee(text) {
2071
2516
  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*\(/);
@@ -2097,10 +2542,16 @@ function sayValue(expr) {
2097
2542
  if (/^new\s/.test(e)) return `a new ${c.split(".").pop()}`;
2098
2543
  return `the result of ${lastWords(c)}`;
2099
2544
  }
2100
- if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words2(e.replace(/^\$/, "").split(".").pop());
2545
+ if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words3(e.replace(/^\$/, "").split(".").pop());
2101
2546
  if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
2102
2547
  return null;
2103
2548
  }
2549
+ function sayArithmetic(expr) {
2550
+ const ar = String(expr).trim().match(/^([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)\s*([-+*/])\s*([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)$/);
2551
+ if (!ar || ar[2] === "+" && !/^\d/.test(ar[1]) && !/^\d/.test(ar[3])) return null;
2552
+ const side = (x) => /^\d/.test(x) ? x : possessiveWords(x);
2553
+ return `${side(ar[1])} ${{ "+": "plus", "-": "minus", "*": "times", "/": "divided by" }[ar[2]]} ${side(ar[3])}`;
2554
+ }
2104
2555
  var PY_SUMMARY = [
2105
2556
  { re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ""} matches` },
2106
2557
  { re: /^all$/, say: (src, cond) => `whether every item in ${src}${cond ? ` where ${cond}` : ""} matches` },
@@ -2109,7 +2560,7 @@ var PY_SUMMARY = [
2109
2560
  { re: /^max$/, say: (src) => `the largest in ${src}` },
2110
2561
  { re: /^(?:sorted)$/, say: (src) => `${src}, sorted` }
2111
2562
  ];
2112
- var lastSeg = (x) => words2(String(x).trim().replace(/\(\)$/, "").split(".").pop());
2563
+ var lastSeg = (x) => words3(String(x).trim().replace(/\(\)$/, "").split(".").pop());
2113
2564
  function sayPython(value) {
2114
2565
  const e = String(value).trim();
2115
2566
  let m = e.match(/^\[\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\]$/);
@@ -2117,7 +2568,7 @@ function sayPython(value) {
2117
2568
  const [, expr, v, src, cond] = m;
2118
2569
  const vars = v.replace(/[()]/g, "").split(/\s*,\s*/);
2119
2570
  const bareCond = cond && cond.replace(new RegExp(`\\b(?:${vars.join("|")})\\.`, "g"), "");
2120
- const condSaid = cond ? /^\w+$/.test(bareCond) ? words2(bareCond) : sayCodeCondition(bareCond) : null;
2571
+ const condSaid = cond ? /^\w+$/.test(bareCond) ? words3(bareCond) : sayCodeCondition(bareCond) : null;
2121
2572
  if (vars.includes(expr.trim())) return condSaid ? `the items in ${lastSeg(src)} where ${condSaid}` : `the items in ${lastSeg(src)}`;
2122
2573
  return `one ${lastSeg(expr.replace(/\(.*$/, ""))} for each item in ${lastSeg(src)}${condSaid ? ` where ${condSaid}` : ""}`;
2123
2574
  }
@@ -2137,9 +2588,11 @@ function sayPython(value) {
2137
2588
  function sayCommon(value) {
2138
2589
  const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, "");
2139
2590
  let m;
2140
- const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
2591
+ const side = (x) => sayValue(x) ?? sayArithmetic(x) ?? possessiveWords(x.trim());
2141
2592
  if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
2142
- if (m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
2593
+ if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) && !/^(?:if|unless)\b/.test(e)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
2594
+ const ifValue = ifAsValue(e);
2595
+ if (ifValue) return `${side(ifValue.yes)} if ${sayCodeCondition(ifValue.cond)}, otherwise ${side(ifValue.no)}`;
2143
2596
  if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
2144
2597
  if (m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/)) return `a new ${m[1]}`;
2145
2598
  if (m = e.match(/^&([A-Z]\w*)$/)) return `a new ${m[1]}`;
@@ -2162,6 +2615,20 @@ function sayCommon(value) {
2162
2615
  if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
2163
2616
  return null;
2164
2617
  }
2618
+ function ifAsValue(e) {
2619
+ let m;
2620
+ if (m = e.match(/^if\s*\(/)) {
2621
+ const close = matchingClose(e, e.indexOf("("));
2622
+ if (close < 0) return null;
2623
+ const rest2 = e.slice(close + 1).match(/^\s*(?:\{\s*([^{};]+?)\s*\}|([^{};]+?))\s+else\s+(?:\{\s*([^{};]+?)\s*\}|([^{};]+))$/);
2624
+ if (rest2) return { cond: e.slice(e.indexOf("(") + 1, close), yes: rest2[1] ?? rest2[2], no: rest2[3] ?? rest2[4] };
2625
+ return null;
2626
+ }
2627
+ if (m = e.match(/^if\s+([^{}]+?)\s*\{\s*([^{};]+?)\s*\}\s*else\s*\{\s*([^{};]+?)\s*\}$/)) return { cond: m[1], yes: m[2], no: m[3] };
2628
+ if (m = e.match(/^if\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[2], no: m[3] };
2629
+ if (m = e.match(/^unless\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[3], no: m[2] };
2630
+ return null;
2631
+ }
2165
2632
  var LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
2166
2633
  function sayWhether(expr) {
2167
2634
  const e = String(expr).trim();
@@ -2186,7 +2653,7 @@ function sayChain(value) {
2186
2653
  const m = value.match(c.re);
2187
2654
  if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c };
2188
2655
  }
2189
- return hit ? hit.c.say(words2(src.split(".").pop().replace(/^#/, ""))) : null;
2656
+ return hit ? hit.c.say(words3(src.split(".").pop().replace(/^#/, ""))) : null;
2190
2657
  }
2191
2658
  var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
2192
2659
  function httpErrorOf(head) {
@@ -2202,9 +2669,9 @@ function redirectTarget(arg) {
2202
2669
  const a = String(arg || "").trim().replace(/^(?:url|to|location|redirect_to)\s*=\s*/, "");
2203
2670
  let m;
2204
2671
  if (m = a.match(/^(?:new\s+URL\(\s*)?["'`](\/[^"'`$?#]*|https?:\/\/[^"'`$/?#]+[^"'`$?#]*)/)) return m[1];
2205
- if (m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
2206
- if (m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/)) return `the ${words2(m[1].split(/[.:]/).pop())} page`;
2207
- if (m = a.match(/^([A-Za-z_][\w.]*)$/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
2672
+ if (m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/)) return `the ${words3(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
2673
+ if (m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/)) return `the ${words3(m[1].split(/[.:]/).pop())} page`;
2674
+ if (m = a.match(/^([A-Za-z_][\w.]*)$/)) return `the ${words3(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
2208
2675
  return "another page";
2209
2676
  }
2210
2677
  function redirectOf(head) {
@@ -2215,28 +2682,82 @@ function redirectOf(head) {
2215
2682
  const to = redirectTarget(m[1]);
2216
2683
  return { kind: isReturn ? "return" : "call", says: `Sends the person to ${to}`, redirect: to };
2217
2684
  }
2685
+ function objectKeys(expr) {
2686
+ const open = expr.indexOf("{");
2687
+ if (open < 0) return [];
2688
+ let close = -1;
2689
+ for (let i = open, d = 0; i < expr.length; i++) {
2690
+ const c = expr[i];
2691
+ if (c === '"' || c === "'" || c === "`") {
2692
+ for (i++; i < expr.length && expr[i] !== c; i++) if (expr[i] === "\\") i++;
2693
+ continue;
2694
+ }
2695
+ if (c === "{") d++;
2696
+ else if (c === "}" && --d === 0) {
2697
+ close = i;
2698
+ break;
2699
+ }
2700
+ }
2701
+ if (close < 0) return [];
2702
+ const inner = expr.slice(open + 1, close);
2703
+ const keys = [];
2704
+ let depth = 0, cur = "";
2705
+ const take = (part) => {
2706
+ const m = part.trim().match(/^(?:["'](\w+)["']|(\w+))\s*(?::|$|\()/);
2707
+ if (m && !part.trim().startsWith("...")) keys.push(m[1] || m[2]);
2708
+ };
2709
+ for (const c of inner) {
2710
+ if ("([{".includes(c)) depth++;
2711
+ if (")]}".includes(c)) depth--;
2712
+ if (c === "," && depth === 0) {
2713
+ take(cur);
2714
+ cur = "";
2715
+ } else cur += c;
2716
+ }
2717
+ if (cur.trim()) take(cur);
2718
+ return keys.length > 8 ? [...keys.slice(0, 7), "more"] : keys;
2719
+ }
2720
+ var listWords2 = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
2218
2721
  function classifyStatement(raw, { inner = 0 } = {}) {
2219
2722
  const text = String(raw).trim();
2220
- 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");
2723
+ let first = text.split("\n")[0].trim();
2724
+ if (/^(?:if|else\s+if|while|for|switch)\s*\($/.test(first.replace(/\s*\{$/, "")) || /^(?:if|else\s+if|while)\s*\(/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ""))) {
2725
+ const o = text.indexOf("("), c2 = matchingClose(text, o);
2726
+ if (c2 > 0 && c2 < 2e3) first = `${text.slice(0, c2 + 1)}${text.slice(c2 + 1).split("\n")[0]}`.replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
2727
+ }
2728
+ const head = first.replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1$2").replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1($2)").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");
2221
2729
  const code = clip(head, 90);
2222
2730
  let m;
2223
2731
  const innerNote = inner ? ` (${inner} step${inner === 1 ? "" : "s"} inside)` : "";
2224
2732
  let inl;
2225
- if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
2733
+ if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?|[\w$.]+(?:\+\+|--);?|(?:\+\+|--)[\w$.]+;?)$/)) && balanced(inl[2])) {
2226
2734
  return { kind: "branch", says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
2227
2735
  }
2228
- 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])) {
2736
+ if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && !/^(?: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])) {
2229
2737
  const cond = sayCodeCondition(inl[3]);
2230
2738
  return { kind: "branch", says: inl[2] === "unless" ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === "unless", code, inline: inl[1] };
2231
2739
  }
2232
- 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 };
2740
+ if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words3(inl[1])} yet`, code };
2233
2741
  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 };
2234
- 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 };
2742
+ if (inl = head.match(/^([\w$.]+)\s*:?=\s*func\s*\(/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
2743
+ if (inl = head.match(/^delete\s+([\w$.]+)(?:\[\s*([^\]]+?)\s*\]|\.([\w$]+));?$/)) return { kind: "call", says: `Removes ${words3(String(inl[2] ?? inl[3]).replace(/["'`]/g, ""))} from ${targetWords(inl[1])}`, code };
2744
+ if (/^fallthrough\b/.test(head)) return { kind: "call", says: "Carries on into the next case too", code };
2745
+ if (inl = head.match(/^goto\s+case\s+(.+?);?$/)) return { kind: "call", says: `Carries on into the case for ${words3(plainEnums(inl[1]))}`, code };
2746
+ if (/^do\s*\{?$/.test(head)) {
2747
+ const dw = text.match(/\}\s*while\s*\(([\s\S]*)\)\s*;?\s*$/);
2748
+ if (dw) return { kind: "loop", says: `Runs once, then repeats while ${sayCodeCondition(dw[1].replace(/\s+/g, " "))}${innerNote}`, code };
2749
+ }
2750
+ if ((inl = head.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/)) && !/[{]\s*$/.test(head) && !/^when\s*\(/.test(head)) {
2751
+ return { kind: "check", says: armSays(inl[1]), code, caseLabel: true, ...inl[2] ? { inline: inl[2] } : {} };
2752
+ }
2753
+ if (inl = head.match(/^when\s*(?:\((.+)\))?\s*\{$/)) return { kind: "branch", says: inl[1] ? `Chooses by ${words3(clip(inl[1], 40))}${innerNote}` : `Checks these cases in order${innerNote}`, code };
2754
+ if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) && /(?:[<>]=?|[!=]==?|&&|\|\|)/.test(m[1].replace(/<-|->/g, "")) && !/^["']/.test(m[1])) return { kind: "check", says: `When ${sayCodeCondition(m[1])}`, code, caseLabel: true };
2755
+ 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*\./, "")) ? words3(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
2235
2756
  if (/^default\s*(?::|->)/.test(head)) return { kind: "check", says: "Otherwise", code, caseLabel: true };
2236
2757
  if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
2237
2758
  const name = m?.[1] ? m[1].split(".").pop() : null;
2238
2759
  const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
2239
- const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
2760
+ const said = name && /^[a-z]/.test(name) ? `the error made by ${words3(name)}` : name;
2240
2761
  return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
2241
2762
  }
2242
2763
  const httpFail = httpErrorOf(head);
@@ -2257,26 +2778,30 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2257
2778
  }
2258
2779
  const chain = sayChain(expr);
2259
2780
  if (chain) return { kind: "return", says: `Returns ${chain}`, code };
2260
- if (/^\(?\s*\{/.test(expr)) return { kind: "return", says: "Returns an object", code };
2781
+ if (/^\(?\s*\{/.test(expr)) {
2782
+ const keys = objectKeys(expr);
2783
+ return { kind: "return", says: keys.length ? `Returns ${listWords2(keys.map(words3))}` : "Returns an object", code, ...keys.length ? { keys } : {} };
2784
+ }
2261
2785
  if (/^\(?\s*</.test(expr)) return { kind: "return", says: "Returns what to show on screen", code };
2262
2786
  const v = sayValue(expr) || sayWhether(expr);
2263
2787
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a computed value", code, ...v ? {} : { value: clip(expr, 60) } };
2264
2788
  }
2265
2789
  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*$/)) {
2266
- return { kind: "loop", says: `Counts ${words2(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
2790
+ return { kind: "loop", says: `Counts ${words3(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
2267
2791
  }
2792
+ if (m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
2268
2793
  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*$/)) {
2269
2794
  const src = stripTail(m[3]).replace(/\($/, "()").replace(/^Object\.entries\((.+)\)$/, "$1").replace(/\.(?:items|entries)\(\)$/, "");
2270
- return { kind: "loop", says: `For each ${words2(m[1])} and ${words2(m[2])} in ${words2(src.split(".").pop())}${innerNote}`, code };
2795
+ return { kind: "loop", says: `For each ${words3(m[1])} and ${words3(m[2])} in ${words3(src.split(".").pop())}${innerNote}`, code };
2271
2796
  }
2272
2797
  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*$/)) {
2273
- return { kind: "loop", says: `For each ${words2(m[1].split(",").pop().trim())} in ${words2(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
2798
+ return { kind: "loop", says: `For each ${words3(m[1].split(",").pop().trim())} in ${words3(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
2274
2799
  }
2275
- 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 };
2276
- if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[1])} in ${words2(m[2].split(".").pop())}${innerNote}`, code };
2277
- 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 };
2278
- 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 };
2279
- 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 };
2800
+ if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words3(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
2801
+ if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words3(m[1])} in ${words3(m[2].split(".").pop())}${innerNote}`, code };
2802
+ if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words3(m[2])} in ${words3(m[1].split(".").pop())}${innerNote}`, code };
2803
+ if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words3(m[2])} in ${words3(m[1].split(".").pop())}${innerNote}`, code };
2804
+ if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words3(m[1].split(".").pop())}${innerNote}`, code };
2280
2805
  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 };
2281
2806
  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 };
2282
2807
  if (m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/)) {
@@ -2287,20 +2812,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2287
2812
  const cond = sayCodeCondition(m[1]);
2288
2813
  return { kind: "branch", says: `If ${/^unless\b/.test(head) ? "not: " : ""}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, "$1"), code, negate: /^unless\b/.test(head) };
2289
2814
  }
2290
- if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words2(clip(m[1], 40)) || "value"}${innerNote}`, code };
2815
+ if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: "branch", says: `Checks these cases in order${innerNote}`, code };
2816
+ if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words3(clip(m[1], 40)) || "value"}${innerNote}`, code };
2291
2817
  if (/^(?:try|begin)\b/.test(head)) return { kind: "try", says: `Tries the next steps and handles any error${innerNote}`, code };
2292
2818
  if (m = head.match(/^assert\b\s*(.*?)\s*;?$/)) return { kind: "check", says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, "")) : "a condition holds"}`, code };
2293
2819
  if (m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
2294
2820
  if (m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
2295
- if (m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
2296
- const what = /^open\s*\(/.test(m[1]) ? "a file" : words2(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
2297
- return { kind: "set", says: `Opens ${what} as ${words2(m[2].replace(/[()]/g, ""))}`, code };
2821
+ if (m = head.match(/^(?:async\s+)?with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
2822
+ const what = /^open\s*\(/.test(m[1]) ? "a file" : words3(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
2823
+ return { kind: "set", says: `Opens ${what} as ${words3(m[2].replace(/[()]/g, ""))}`, code };
2298
2824
  }
2299
2825
  if (m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/)) return { kind: "set", says: `Uses ${clip(m[1], 50)}`, code };
2300
2826
  if (/^defer\b/.test(head)) return { kind: "call", says: `At the end, ${clip(head.replace(/^defer\s+/, ""), 60)}`, code };
2301
2827
  if (/^super\b/.test(head)) return { kind: "call", says: "Runs the parent version first", code };
2302
2828
  if (/^yield\b/.test(head)) return { kind: "call", says: "Hands control to the given block", code };
2303
- if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words2(m[1])}`, code };
2829
+ if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words3(m[1])}`, code };
2304
2830
  if (m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/)) return { kind: "return", says: `Returns ${m[1]}`, code };
2305
2831
  if (/^vec!?\[/.test(head)) return { kind: "return", says: "Returns a list", code };
2306
2832
  if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
@@ -2308,21 +2834,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2308
2834
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a value", code };
2309
2835
  }
2310
2836
  if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: "set", says: `${/\+\+/.test(head) ? "Adds one to" : "Subtracts one from"} ${targetWords(m[1].replace(/#/g, ""))}`, code };
2311
- if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words2(m[1])}`, code };
2312
- if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
2313
- if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
2837
+ if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words3(m[1])}`, code };
2838
+ if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words3(m[1])}`, code };
2839
+ if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words3(m[1])}`, code };
2314
2840
  if (m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/)) {
2315
- const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words2);
2841
+ const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words3);
2316
2842
  const value = stripTail(m[3]);
2317
2843
  const c2 = callee(value);
2318
- const from = c2 ? lastWords(c2) : sayValue(value) || words2(value.split(".").pop());
2844
+ const from = c2 ? lastWords(c2) : sayValue(value) || words3(value.split(".").pop());
2319
2845
  return { kind: "set", says: `Takes ${names.slice(0, 4).join(", ")}${names.length > 4 ? ", \u2026" : ""} from ${from}`, code };
2320
2846
  }
2321
2847
  if (m = head.match(/^(?:var|const)\s*\($/)) return { kind: "set", says: "Declares some values", code };
2322
- if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words2).join(", ")}`, code };
2848
+ if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words3).join(", ")}`, code };
2323
2849
  if (m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/)) {
2324
2850
  const value = stripTail(m[3]);
2325
- const target = words2(m[2]);
2851
+ const target = words3(m[2]);
2326
2852
  const c2 = value ? callee(value) : null;
2327
2853
  const everyday = value ? sayPython(value) || sayCommon(value) : null;
2328
2854
  if (everyday) return { kind: "set", says: `Sets ${target} to ${everyday}`, code };
@@ -2338,14 +2864,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2338
2864
  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)) {
2339
2865
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== "_").map(targetWords).join(", ") || targetWords(m[1]);
2340
2866
  const value = stripTail(m[3]);
2341
- 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 };
2342
- 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 };
2867
+ if (m[2] === "=" && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.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 };
2868
+ 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 ${words3(value)} it is given`, code };
2343
2869
  const chain = value ? sayPython(value) || sayChain(value) : null;
2344
2870
  if (chain) return { kind: "set", says: `Works out ${target}: ${chain}`, code };
2345
2871
  const common = value ? sayCommon(m[3].trim().replace(/;$/, "")) || sayCommon(value) : null;
2346
2872
  if (common) return { kind: "set", says: `Sets ${target} to ${common}`, code };
2347
2873
  const keyed = m[2] === "=" && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
2348
- if (keyed) return { kind: "set", says: `Records ${words2(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
2874
+ if (keyed) return { kind: "set", says: `Records ${words3(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
2349
2875
  const c2 = callee(value);
2350
2876
  if (c2) {
2351
2877
  const known = sayCall(c2, firstArgs(value));
@@ -2355,7 +2881,7 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2355
2881
  }
2356
2882
  if (!value) return { kind: "set", says: `Works out ${target}`, code };
2357
2883
  if (m[2] === "+=" || m[2] === "-=") {
2358
- const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words2).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
2884
+ const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words3).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
2359
2885
  return { kind: "set", says: what ? `${m[2] === "+=" ? "Adds" : "Subtracts"} ${what}${m[2] === "+=" ? "to" : "from"} ${target}` : `${m[2] === "+=" ? "Adds to" : "Subtracts from"} ${target}`, code };
2360
2886
  }
2361
2887
  const v = sayValue(value);
@@ -2364,14 +2890,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2364
2890
  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` };
2365
2891
  if ((m = head.match(/^([\w$.]+)\.(?:remove|Remove|discard|delete|pop)\(\s*([\w$]+)\s*\)/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
2366
2892
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
2367
- const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
2368
- return { kind: "call", says: `Removes ${words2(m[2])} from ${where}`, code, callee: m[1] };
2893
+ const where = owner.length > 1 ? `${words3(owner[owner.length - 2])}'s ${words3(owner[owner.length - 1])}` : words3(owner[0] || m[1]);
2894
+ return { kind: "call", says: `Removes ${words3(m[2])} from ${where}`, code, callee: m[1] };
2369
2895
  }
2370
2896
  if ((m = head.match(/^([\w$.]+)\.(?:append|push|add|Add|insert|appendleft|extend)\(\s*([\w$.]*)\s*\)?/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
2371
2897
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
2372
- const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
2898
+ const where = owner.length > 1 ? `${words3(owner[owner.length - 2])}'s ${words3(owner[owner.length - 1])}` : words3(owner[0] || m[1]);
2373
2899
  const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf("(") + 1))?.[1];
2374
- 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] };
2900
+ return { kind: "call", says: added ? `Adds a new ${words3(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words3(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
2375
2901
  }
2376
2902
  const c = callee(head);
2377
2903
  if (c) {
@@ -2382,12 +2908,20 @@ function classifyStatement(raw, { inner = 0 } = {}) {
2382
2908
  if (/^assert/.test(m[1])) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
2383
2909
  const known = sayCall(m[1], m[2]);
2384
2910
  const named = /^[:'"]([\w ]+)['"]?/.exec(m[2].trim())?.[1];
2385
- return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words2(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
2911
+ return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words3(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
2386
2912
  }
2387
2913
  return { kind: "other", says: clip(head, 70), code };
2388
2914
  }
2389
2915
  var spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...s.start != null && s.end != null ? { start: s.start, end: s.end } : {} });
2390
2916
  var BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
2917
+ var bracketsClosed = (x) => {
2918
+ let d = 0;
2919
+ for (const ch of x) {
2920
+ if ("([{".includes(ch)) d++;
2921
+ else if (")]}".includes(ch)) d--;
2922
+ }
2923
+ return d === 0;
2924
+ };
2391
2925
  var balanced = (x) => {
2392
2926
  let d = 0;
2393
2927
  for (const ch of x) {
@@ -2424,12 +2958,195 @@ function attachClause(step, clause) {
2424
2958
  step.always = { line: clause.line, steps: kids2 };
2425
2959
  }
2426
2960
  }
2961
+ function orList(names) {
2962
+ const n = [...new Set(names)];
2963
+ if (n.length <= 3) return n.length > 1 ? `${n.slice(0, -1).join(", ")} or ${n[n.length - 1]}` : n[0] || "";
2964
+ return `${n.slice(0, 3).join(", ")} or ${n.length - 3} other value${n.length - 3 === 1 ? "" : "s"}`;
2965
+ }
2966
+ function depsOf(after) {
2967
+ const a = String(after || "");
2968
+ if (/^\s*\)/.test(a)) return null;
2969
+ const m = a.match(/^\s*,\s*\[([^\]]*)\]/);
2970
+ if (!m) return "unknown";
2971
+ return m[1].split(",").map((x) => x.trim().replace(/\?\./g, ".").replace(/\(\)$/, "")).filter(Boolean).map((x) => words3(x.split(".").pop()));
2972
+ }
2973
+ var changesWords = (deps) => `${orList(deps)} ${deps.length > 3 ? "change" : "changes"}`;
2974
+ function effectSays(deps) {
2975
+ if (deps === null) return "Every time this is drawn on screen";
2976
+ if (deps === "unknown") return "When this first shows on screen, and whenever what it watches changes";
2977
+ if (!deps.length) return "When this first shows on screen";
2978
+ return `When this first shows on screen, and whenever ${changesWords(deps)}`;
2979
+ }
2980
+ var HOOK = /^(?:(?:const|let|var)\s+([\w$]+)(?:\s*:[^=]+?)?\s*=\s*)?(?:React\.)?(use[A-Z]\w*)\s*(?:<[^(]*?>)?\(/;
2981
+ var TRAILING_LAMBDA = /^(?:(?:val|var)\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*)?([a-z_$][\w$]*(?:\??\.[\w$]+)*)\s*(\([^{}]*\))?\s*\{\s*(?:\(?[\w$, ]+\)?\s*->)?\s*$/;
2982
+ var RUBY_DO = /^(?:[@$]?[\w]+\s*=\s*)?([a-z_][\w.?!]*)(?:\(.*\)|\s+[^|]*?)?\s+do\s*(?:\|[^|]*\|)?\s*$/;
2983
+ var NOT_A_CALL = /^(?:if|else|for|while|when|return|object|init|companion|class|interface|fun|try|catch|finally|do|loop|unsafe|match|switch|select|synchronized|lock|using|get|set)$/;
2984
+ function thenSays(text) {
2985
+ const m = String(text).match(/^(?:await\s+)?([^{};\n]*?)\.(then|catch)\(\s*(?:async\s+)?(?:function\b|\(|[\w$]+\s*=>)/);
2986
+ if (!m) return null;
2987
+ const recvText = m[1].trim().replace(/^\(\s*([\w$.]+)\s+as\s+[^()]*\)$/, "$1");
2988
+ const recv = recvText.match(/^([\w$.]+)\(.*\)$/s) || recvText.match(/^([\w$.]+)$/);
2989
+ const what = recv ? lastWords(recv[1]) : "that";
2990
+ return m[2] === "then" ? `When ${what} is done` : `If ${what} goes wrong`;
2991
+ }
2992
+ function nestedStep(s, base) {
2993
+ const text = String(s.text || "").trim();
2994
+ const head = text.split("\n")[0].trim();
2995
+ const kids2 = () => stepsFrom(s.children || []).steps;
2996
+ const own = (step, children) => children.length ? { ...step, children, nested: true } : step;
2997
+ let m;
2998
+ if (s.fn && s.fn.depth === 1 && (m = text.match(HOOK))) {
2999
+ const [, name, hook] = m;
3000
+ const deps = depsOf(s.fn.after);
3001
+ if (/^use\w*Effect$/.test(hook)) {
3002
+ for (const c of s.children || []) if (c.fn && /^return\b/.test(c.text.trim())) c.cleanup = deps && deps !== "unknown" && !deps.length ? "When this is taken off the screen, cleans up" : "Cleans up before it runs again, and when this is taken off the screen";
3003
+ return own({ kind: "call", says: effectSays(deps), code: base.code, callee: hook }, kids2());
3004
+ }
3005
+ if (hook === "useMemo" && name) {
3006
+ let children = kids2();
3007
+ if (s.fn.expr && children.length === 1) {
3008
+ const v = classifyStatement(`return ${s.children[0].text}`);
3009
+ children = [{ ...children[0], kind: v.kind, says: v.says }];
3010
+ }
3011
+ const says = deps === null ? `Works out ${words3(name)}` : Array.isArray(deps) && !deps.length ? `Works out ${words3(name)} once and remembers it` : Array.isArray(deps) ? `Works out ${words3(name)} and remembers it until ${changesWords(deps)}` : `Works out ${words3(name)} and remembers it until what it watches changes`;
3012
+ return own({ kind: "set", says, code: base.code, callee: hook }, children);
3013
+ }
3014
+ if (/^use\w*Callback$/.test(hook) && name) return own({ kind: "set", says: `Defines how ${words3(name)} works`, code: base.code, callee: hook }, kids2());
3015
+ }
3016
+ if (s.cleanup) return own({ kind: "call", says: s.cleanup, code: base.code }, kids2());
3017
+ if (s.fn && !s.fn.expr) {
3018
+ if (s.fn.depth === 0 && /^go\s+func\b/.test(head)) return own({ kind: "call", says: "Starts these steps running alongside, without waiting for them", code: base.code }, kids2());
3019
+ if (s.fn.depth === 0 && /^defer\s+func\b/.test(head)) return own({ kind: "call", says: "At the end, runs these steps", code: base.code }, kids2());
3020
+ if (/^return\b/.test(head) || base.kind === "return" || base.kind === "other" || base.kind === "branch" || base.kind === "fail") return null;
3021
+ if (base.kind === "loop") return null;
3022
+ let said = base.says;
3023
+ if (base.kind !== "call") {
3024
+ } else if (m = text.match(/^(?:window\.|globalThis\.)?(setTimeout|setInterval)\(/)) {
3025
+ const ms = (s.fn.after.match(/^\s*,\s*(\d+)\s*\)/) || [])[1];
3026
+ said = m[1] === "setTimeout" ? ms ? `After ${ms} milliseconds` : "After a wait" : ms ? `Every ${ms} milliseconds` : "Again and again, with a wait in between";
3027
+ } else if (m = text.match(/\.(addEventListener|on|once)\(\s*['"`]([\w:.-]+)['"`]\s*,/)) {
3028
+ said = m[1] === "once" ? `The first time "${m[2]}" happens` : `Whenever "${m[2]}" happens`;
3029
+ } else if (thenSays(text)) {
3030
+ said = thenSays(text);
3031
+ } else if (/^Calls [\w ]+$/.test(said)) said = `${said} with these steps`;
3032
+ return own({ ...base, kind: base.kind === "set" ? "set" : "call", says: said }, kids2());
3033
+ }
3034
+ if (!s.children?.length) return null;
3035
+ const raw = String(s.text || "").split("\n")[0].trim();
3036
+ if (!s.fn && !BLOCK_HEAD.test(raw) && (m = raw.match(TRAILING_LAMBDA)) && !NOT_A_CALL.test(m[1])) {
3037
+ const safe = m[1].match(/^(.+?)\?\.(?:let|also|run|apply)$/);
3038
+ if (safe) return own({ kind: "branch", says: `If ${words3(safe[1].split(/\??\./).pop())} is set`, code: clip(raw, 90) }, kids2());
3039
+ if (m = raw.match(/^repeat\s*\(\s*(.+?)\s*\)\s*\{/)) return own({ kind: "loop", says: `Repeats ${/^\d+$/.test(m[1]) ? m[1] : words3(m[1])} times`, code: base.code }, kids2());
3040
+ if (base.kind === "loop") return null;
3041
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says} with these steps` }, kids2());
3042
+ if (base.kind === "set" || base.kind === "call") return own(base, kids2());
3043
+ return null;
3044
+ }
3045
+ if ((m = raw.match(RUBY_DO)) && base.kind !== "loop" && !/^(?:if|unless|while|until|for|case|begin)\b/.test(raw)) {
3046
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says.replace(/: .*$/, "")} with these steps` }, kids2());
3047
+ if (base.kind === "call" || base.kind === "set") return own(base, kids2());
3048
+ }
3049
+ return null;
3050
+ }
3051
+ function valueChoice(s) {
3052
+ const head = headLine(s.text || "");
3053
+ let m = head.match(/^(?:(?:const|let|var|val|my)\s+(?:mut\s+)?)?([@$]?[\w$.]+)(?:\s*:\s*[^=]+?)?\s*=\s*((?:if|unless|match|when|case)\b.*|[\w.]+\s+switch\s*\{\s*)$/);
3054
+ if (m && !/^(?:if|for|while|return)$/.test(m[1])) return { target: targetWords(m[1]), rest: m[2] };
3055
+ if (m = head.match(/^return\s+((?:if|match|when)\b.*|[\w.]+\s+switch\s*\{\s*)$/)) return { target: null, rest: m[1] };
3056
+ return null;
3057
+ }
3058
+ function armsSubject(rest2) {
3059
+ const r = rest2.replace(/\{\s*$/, "").trim();
3060
+ const m = r.match(/^match\s*\((.+)\)$/) || r.match(/^match\s+(.+)$/) || r.match(/^when\s*\((.+)\)$/) || r.match(/^([\w.]+)\s+switch$/);
3061
+ return m ? m[1].trim() : null;
3062
+ }
3063
+ function armSays(pattern) {
3064
+ let p = String(pattern).trim();
3065
+ if (/^(?:_|else|default)$/.test(p)) return "Otherwise";
3066
+ let guard = null;
3067
+ const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
3068
+ if (g) {
3069
+ p = g[1];
3070
+ guard = g[2];
3071
+ }
3072
+ if (LOGIC.test(p) && !/^(?:!?in|!?is)\s/.test(p) && !/\.\./.test(p) && !/\|/.test(p.replace(/\|\|/g, ""))) return `When ${sayCodeCondition(p)}`;
3073
+ const parts = [];
3074
+ let depth = 0, from = 0;
3075
+ for (let i = 0; i <= p.length; i++) {
3076
+ const c = p[i];
3077
+ if (c === "(" || c === "[" || c === "{") depth++;
3078
+ else if (c === ")" || c === "]" || c === "}") depth--;
3079
+ if (i === p.length || depth === 0 && (c === "|" && p[i + 1] !== "|" && p[i - 1] !== "|" || c === ",")) {
3080
+ parts.push(p.slice(from, i).trim());
3081
+ from = i + 1;
3082
+ }
3083
+ }
3084
+ const one = (x) => {
3085
+ let m;
3086
+ if ((m = x.match(/^(!?)in\s+(.+?)\.\.(=?)(.+)$/)) || (m = x.match(/^()(-?[\w.]+)\.\.(=)(-?[\w.]+)$/))) return `${m[1] ? "not " : ""}from ${m[2].trim()} to ${m[4].trim()}`;
3087
+ if (m = x.match(/^(!?)is\s+([\w.<>?]+)$/)) return `${m[1] ? "not " : ""}a ${m[2].split(".").pop()}`;
3088
+ if (m = x.match(/^(?:[A-Z]\w*(?:::|\.))+([A-Z]\w*)$/)) return words3(m[1]);
3089
+ if (/^[A-Z][A-Z0-9_]+$/.test(x)) return words3(x);
3090
+ return x;
3091
+ };
3092
+ return `When it is ${orList(parts.filter(Boolean).map(one))}${guard ? `, and ${sayCodeCondition(guard)}` : ""}`;
3093
+ }
3094
+ function giveValue(list, target) {
3095
+ if (!list?.length) return;
3096
+ if (list.some((x) => x.caseLabel)) {
3097
+ for (const x of list) if (x.caseLabel) giveValue(x.children, target);
3098
+ return;
3099
+ }
3100
+ const i = list.length - 1;
3101
+ const last = list[i];
3102
+ if (last.kind === "branch" && !Object.hasOwn(last, "valueOf")) {
3103
+ giveValue(last.children, target);
3104
+ giveValue(last.otherwise, target);
3105
+ return;
3106
+ }
3107
+ if (last.kind === "fail" || /^(?:return|break|continue|throw|raise)\b/.test(last.code || "")) return;
3108
+ const v = classifyStatement(`return ${String(last.code || "").replace(/,$/, "")}`);
3109
+ if (v.kind !== "return") return;
3110
+ const said = v.says.replace(/^Returns /, "");
3111
+ list[i] = target ? { ...last, kind: "set", says: v.value ? `Sets ${target} to a computed value` : `Sets ${target} to ${said}` } : { ...last, kind: "return", says: v.says };
3112
+ delete list[i].callee;
3113
+ if (list[i].says && restates(list[i])) list[i].restates = true;
3114
+ else delete list[i].restates;
3115
+ }
3116
+ function selectCaseSays(code) {
3117
+ const c = String(code).trim();
3118
+ if (/^default\s*:/.test(c)) return "If none is ready yet";
3119
+ let m = c.match(/^case\s+(?:([\w$]+)(?:\s*,\s*([\w$]+))?\s*:?=\s*)?<-\s*(.+?)\s*:\s*$/);
3120
+ if (m) {
3121
+ const [, name, ok, ch] = m;
3122
+ let d;
3123
+ if (/\.Done\(\)$/.test(ch)) return `When ${lastWords(ch.replace(/\.Done\(\)$/, ""))} is cancelled or times out`;
3124
+ if (d = ch.match(/^time\.After\((.+)\)$/)) {
3125
+ const t = d[1].trim();
3126
+ const u = t.match(/^(\d+)\s*\*\s*time\.(Millisecond|Second|Minute|Hour)$/) || t.match(/^time\.(Millisecond|Second|Minute|Hour)$/);
3127
+ const dur = u ? u.length === 3 ? `${u[1]} ${u[2].toLowerCase()}${u[1] === "1" ? "" : "s"}` : `1 ${u[1].toLowerCase()}` : words3(t.split(".").pop());
3128
+ return `When ${dur} ${/s$/.test(dur) && !/^1 /.test(dur) ? "have" : "has"} passed`;
3129
+ }
3130
+ if (/\.C$/.test(ch)) return `When ${lastWords(ch.replace(/\.C$/, ""))} ticks`;
3131
+ const from = lastWords(ch.replace(/\(\)$/, ""));
3132
+ return name && name !== "_" ? `When ${words3(name)} arrives from ${from}${ok ? ` (or ${from} is closed)` : ""}` : `When something arrives from ${from}`;
3133
+ }
3134
+ if (m = c.match(/^case\s+(.+?)\s*<-\s*(.+?)\s*:\s*$/)) return `When ${words3(m[2].split(".").pop())} can be sent to ${lastWords(m[1])}`;
3135
+ return null;
3136
+ }
2427
3137
  function stepsFrom(statements) {
2428
3138
  const steps = [];
2429
3139
  const skipped = [];
2430
3140
  let into = null, intoAlways = false;
2431
3141
  for (const s of statements) {
2432
3142
  const t0 = (s.text || "").trim();
3143
+ if (s.arm != null) {
3144
+ const arm = { kind: "check", says: armSays(s.arm), code: clip(t0.split("\n")[0].trim(), 90), caseLabel: true, line: s.line, span: spanOf(s) };
3145
+ const kids2 = stepsFrom(s.children || []).steps;
3146
+ if (kids2.length) arm.children = kids2;
3147
+ steps.push(arm);
3148
+ continue;
3149
+ }
2433
3150
  if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
2434
3151
  const st = stepsFrom([s]).steps;
2435
3152
  into.push(...st);
@@ -2447,7 +3164,9 @@ function stepsFrom(statements) {
2447
3164
  if (prev2 && (prev2.kind === "branch" || prev2.kind === "try")) {
2448
3165
  const prev3 = prev2;
2449
3166
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? "elif" : /^else\b/.test(t0) ? "else" : /^(?:finally|ensure)\b/.test(t0) ? "finally" : "catch";
2450
- attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: s.children || [] });
3167
+ const inlineElse = kw === "else" && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
3168
+ const clauseKids = inlineElse ? [{ text: inlineElse[1], line: s.line, endLine: s.line }, ...s.children || []] : s.children || [];
3169
+ attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: clauseKids });
2451
3170
  intoAlways = kw === "finally";
2452
3171
  into = s.children?.length ? null : kw === "catch" ? prev3.handlers?.[prev3.handlers.length - 1]?.steps ?? null : kw === "finally" ? prev3.always?.steps ?? null : null;
2453
3172
  prev3.span = { ...prev3.span, endLine: Math.max(prev3.span.endLine, s.endLine ?? s.line) };
@@ -2456,7 +3175,7 @@ function stepsFrom(statements) {
2456
3175
  skipped.push(spanOf(s));
2457
3176
  continue;
2458
3177
  }
2459
- if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) {
3178
+ if (!t0 || /^(?:end\b|\}|pass$|break;?$|continue;?$|#)/.test(t0)) {
2460
3179
  if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s));
2461
3180
  continue;
2462
3181
  }
@@ -2468,16 +3187,54 @@ function stepsFrom(statements) {
2468
3187
  skipped.push(spanOf(s));
2469
3188
  continue;
2470
3189
  }
2471
- const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
3190
+ const head0 = headLine(s.text);
3191
+ if (/^\{/.test(t0) && s.children?.length) {
3192
+ steps.push(...stepsFrom(s.children).steps);
3193
+ continue;
3194
+ }
3195
+ const choice = s.children?.length || s.clauses || s.arms ? valueChoice(s) : null;
3196
+ if (s.arms) {
3197
+ const subject = armsSubject(choice ? choice.rest : head0);
3198
+ const kids2 = stepsFrom(s.children || []).steps;
3199
+ const chooser = { kind: "branch", says: subject ? `Chooses by ${words3(clip(subject, 40))}` : "Checks these cases in order", code: clip(head0, 90), line: s.line, span: spanOf(s), ...kids2.length ? { children: kids2 } : {}, ...choice ? { valueOf: choice.target } : {} };
3200
+ steps.push(chooser);
3201
+ continue;
3202
+ }
3203
+ let step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
3204
+ if (choice && /^(?:if|unless|case)\b/.test(choice.rest) && (s.endLine ?? s.line) > s.line) {
3205
+ step = { ...classifyStatement(choice.rest, { inner: s.inner || 0 }), code: step.code, line: s.line, span: spanOf(s), valueOf: choice.target };
3206
+ } else {
3207
+ const nest = nestedStep(s, step);
3208
+ if (!nest && step.kind === "return" && s.fn && !s.fn.expr && s.fn.depth >= 1 && s.children?.length) {
3209
+ const kids2 = stepsFrom(s.children).steps;
3210
+ if (kids2.length) {
3211
+ let m;
3212
+ const body = s.text.trim().replace(/^return\s+/, "");
3213
+ const said = (m = body.match(/^new\s+([A-Z]\w*)/)) ? `Makes a new ${m[1]} with these steps` : thenSays(body) ? thenSays(body) : callee(body) ? `Calls ${lastWords(callee(body))} with these steps` : null;
3214
+ if (said) steps.push({ kind: "call", says: said, code: step.code, line: s.line, span: spanOf(s), children: kids2, nested: true });
3215
+ }
3216
+ }
3217
+ if (nest) {
3218
+ step = { ...nest, line: s.line, span: spanOf(s) };
3219
+ for (const c of s.clauses || []) attachClause(step, c);
3220
+ steps.push(step);
3221
+ continue;
3222
+ }
3223
+ }
2472
3224
  if (step.inline && !/^\{/.test(step.inline.trim())) {
2473
3225
  const kid = classifyStatement(step.inline);
2474
3226
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
2475
3227
  delete step.inline;
2476
- } else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
3228
+ } else if (s.children?.length && (["branch", "loop", "try"].includes(step.kind) || step.kind === "check" && step.caseLabel || /^(?:Defines a helper|Defines how|Opens |Uses )/.test(step.says))) {
2477
3229
  const kids2 = stepsFrom(s.children).steps;
2478
3230
  if (kids2.length) {
2479
3231
  step.children = kids2;
2480
3232
  step.says = step.says.replace(/ \(\d+ steps? inside\)$/, "");
3233
+ if (/^Defines/.test(step.says)) step.nested = true;
3234
+ }
3235
+ if (/^select\s*\{/.test(head0) && step.children) {
3236
+ for (const k of step.children) if (k.caseLabel) k.says = selectCaseSays(k.code) ?? k.says;
3237
+ step.says = step.children.some((k) => /^default\b/.test(k.code || "")) ? "Checks which of these is ready, without waiting" : "Waits for whichever of these is ready first";
2481
3238
  }
2482
3239
  }
2483
3240
  if (step.inline && !step.children) {
@@ -2485,10 +3242,16 @@ function stepsFrom(statements) {
2485
3242
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
2486
3243
  delete step.inline;
2487
3244
  } else delete step.inline;
2488
- for (const c of s.clauses || []) attachClause(step, c);
3245
+ if (step.kind === "branch" || step.kind === "try") for (const c of s.clauses || []) attachClause(step, c);
2489
3246
  steps.push(step);
2490
3247
  }
2491
3248
  for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
3249
+ for (const st of steps) if (Object.hasOwn(st, "valueOf")) {
3250
+ const t = st.valueOf;
3251
+ delete st.valueOf;
3252
+ giveValue(st.children, t);
3253
+ giveValue(st.otherwise, t);
3254
+ }
2492
3255
  const more = Math.max(0, steps.length - MAX_STEPS);
2493
3256
  for (const st of steps) if (restates(st)) st.restates = true;
2494
3257
  return { steps, more, skipped, readable: readableShare(steps) };
@@ -2497,7 +3260,7 @@ var GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec|m
2497
3260
  function restates(st) {
2498
3261
  const s = st.says || "";
2499
3262
  if (st.kind === "other") return false;
2500
- if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
3263
+ if (/^Works out [^:]+$/.test(s) && !/ from | remembers it/.test(s)) return true;
2501
3264
  const same = s.match(/^Works out (.+) from (.+)$/);
2502
3265
  if (same && same[1].trim() === same[2].trim()) return true;
2503
3266
  if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
@@ -2519,22 +3282,225 @@ var blockEnd = (text, open) => {
2519
3282
  }
2520
3283
  return -1;
2521
3284
  };
3285
+ var headLine = (text) => String(text).trim().replace(/^([^\n]*?=)[ \t]*\r?\n\s*/, "$1 ").split("\n")[0].trim();
3286
+ var skipQuoted = (text, i) => {
3287
+ const q = text[i];
3288
+ for (i++; i < text.length && text[i] !== q; i++) if (text[i] === "\\") i++;
3289
+ return i;
3290
+ };
3291
+ var BLOCK_HEAD = /^(?:if|else|for|foreach|while|until|switch|try|catch|finally|do|match|loop|unsafe|select|using|lock|synchronized|when|case|default|elif|with|class|struct|interface|enum|impl|fn|fun|func|def)\b/;
3292
+ function fnLiteral(text) {
3293
+ let depth = 0;
3294
+ const bodyAt = (j, d) => {
3295
+ while (j < text.length && /\s/.test(text[j])) j++;
3296
+ if (text[j] !== "{") return null;
3297
+ const close = blockEnd(text, j);
3298
+ return close < 0 ? null : { open: j, close, depth: d };
3299
+ };
3300
+ for (let i = 0; i < text.length; i++) {
3301
+ const c = text[i];
3302
+ if (c === '"' || c === "'" || c === "`") {
3303
+ i = skipQuoted(text, i);
3304
+ continue;
3305
+ }
3306
+ if (c === "(" || c === "[") {
3307
+ depth++;
3308
+ continue;
3309
+ }
3310
+ if (c === ")" || c === "]") {
3311
+ depth--;
3312
+ continue;
3313
+ }
3314
+ if (c === "{") {
3315
+ const e = blockEnd(text, i);
3316
+ if (e < 0) return null;
3317
+ i = e;
3318
+ continue;
3319
+ }
3320
+ if (c === "=" && text[i + 1] === ">") {
3321
+ const before = text.slice(Math.max(0, i - 80), i).trimEnd();
3322
+ if (!/(?:\)|[A-Za-z_$][\w$]*)(?:\s*:\s*[^=()]+)?$/.test(before) || /["']$/.test(before)) {
3323
+ i++;
3324
+ continue;
3325
+ }
3326
+ const body = bodyAt(i + 2, depth);
3327
+ if (body) return body;
3328
+ if (depth < 1) {
3329
+ i++;
3330
+ continue;
3331
+ }
3332
+ let j = i + 2, d = 0;
3333
+ for (; j < text.length; j++) {
3334
+ const ch = text[j];
3335
+ if (ch === '"' || ch === "'" || ch === "`") {
3336
+ j = skipQuoted(text, j);
3337
+ continue;
3338
+ }
3339
+ if (ch === "(" || ch === "[" || ch === "{") d++;
3340
+ else if (ch === ")" || ch === "]" || ch === "}") {
3341
+ if (--d < 0) break;
3342
+ } else if (ch === "," && d === 0) break;
3343
+ }
3344
+ return { expr: [i + 2, j], depth };
3345
+ }
3346
+ if (c === "-" && text[i + 1] === ">" && depth >= 1) {
3347
+ const body = bodyAt(i + 2, depth);
3348
+ if (body) return body;
3349
+ i++;
3350
+ continue;
3351
+ }
3352
+ if (c === "f" && /\b(?:function|func)\b/y.test(text.slice(i, i + 9)) && !/[\w$.]/.test(text[i - 1] || "")) {
3353
+ const m = text.slice(i, i + 120).match(/^(?:function\s*\*?\s*[\w$]*|func)\s*\(/);
3354
+ if (!m) continue;
3355
+ let p = i + m[0].length - 1, pd = 0;
3356
+ for (; p < text.length; p++) {
3357
+ if (text[p] === "(") pd++;
3358
+ else if (text[p] === ")" && --pd === 0) break;
3359
+ }
3360
+ let j = p + 1;
3361
+ const use = text.slice(j, j + 24).match(/^\s*use\s*\(/);
3362
+ if (use) {
3363
+ j += use[0].length - 1;
3364
+ for (let ud = 0; j < text.length; j++) {
3365
+ if (text[j] === "(") ud++;
3366
+ else if (text[j] === ")" && --ud === 0) {
3367
+ j++;
3368
+ break;
3369
+ }
3370
+ }
3371
+ }
3372
+ for (; j < text.length && j < p + 200; j++) {
3373
+ if (text[j] === "{") {
3374
+ if (/(?:interface|struct)\s*$/.test(text.slice(Math.max(0, j - 12), j))) {
3375
+ j = blockEnd(text, j);
3376
+ continue;
3377
+ }
3378
+ break;
3379
+ }
3380
+ if (text[j] === "\n" && /^\s*$/.test(text.slice(p + 1, j))) break;
3381
+ }
3382
+ const body = text[j] === "{" ? bodyAt(j, depth) : null;
3383
+ if (body) return body;
3384
+ continue;
3385
+ }
3386
+ if (c === "|" && depth >= 1 && /[(,]\s*(?:move\s+)?$/.test(text.slice(Math.max(0, i - 8), i))) {
3387
+ const m = text.slice(i, i + 200).match(/^\|[^|]*\|\s*(?:->\s*[\w<>&' ]+?\s*)?(?=\{)/);
3388
+ if (m) {
3389
+ const body = bodyAt(i + m[0].length, depth);
3390
+ if (body) return body;
3391
+ }
3392
+ }
3393
+ }
3394
+ return null;
3395
+ }
3396
+ var LAMBDA_PARAMS = /^\s*(?:\(?[\w$]+(?:\s*:\s*[\w<>?.]+)?(?:\s*,\s*[\w$]+(?:\s*:\s*[\w<>?.]+)?)*\)?|_)\s*->(?![^\n]*->)/;
3397
+ function armsOf(body) {
3398
+ const arms = [];
3399
+ let i = 0;
3400
+ while (i < body.length) {
3401
+ while (i < body.length && /[\s,;]/.test(body[i])) i++;
3402
+ if (i >= body.length) break;
3403
+ const at = i;
3404
+ let depth = 0, arrow = -1, end = -1;
3405
+ for (; i < body.length; i++) {
3406
+ const c = body[i];
3407
+ if (c === '"' || c === "'" || c === "`") {
3408
+ i = skipQuoted(body, i);
3409
+ continue;
3410
+ }
3411
+ if (c === "(" || c === "[" || c === "{") {
3412
+ depth++;
3413
+ continue;
3414
+ }
3415
+ if (c === ")" || c === "]" || c === "}") {
3416
+ depth--;
3417
+ if (depth === 0 && c === "}" && arrow >= 0 && /^\{/.test(body.slice(arrow + 2).trimStart())) {
3418
+ i++;
3419
+ end = i;
3420
+ break;
3421
+ }
3422
+ continue;
3423
+ }
3424
+ if (depth !== 0) continue;
3425
+ if (arrow < 0 && (c === "=" || c === "-") && body[i + 1] === ">") {
3426
+ arrow = i;
3427
+ i++;
3428
+ continue;
3429
+ }
3430
+ if (arrow >= 0 && (c === "," || c === ";")) {
3431
+ end = i;
3432
+ break;
3433
+ }
3434
+ if (arrow >= 0 && c === "\n") {
3435
+ const before = body.slice(arrow + 2, i).trim();
3436
+ let j = i + 1;
3437
+ while (j < body.length && /\s/.test(body[j])) j++;
3438
+ const after = body.slice(j, j + 12);
3439
+ if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}+\-*/%&|^=<>?:,]/.test(after) && !/^else\b(?!\s*->)/.test(after)) {
3440
+ end = i;
3441
+ break;
3442
+ }
3443
+ }
3444
+ }
3445
+ if (end < 0) end = i;
3446
+ if (arrow < 0) return null;
3447
+ const pattern = body.slice(at, arrow).trim();
3448
+ let bodyAt = arrow + 2;
3449
+ while (bodyAt < end && /\s/.test(body[bodyAt])) bodyAt++;
3450
+ if (!pattern) return null;
3451
+ arms.push({ pattern, at, end, bodyAt, body: body.slice(bodyAt, end).trim() });
3452
+ i = end + 1;
3453
+ }
3454
+ return arms.length ? arms : null;
3455
+ }
3456
+ var ARMS_HEAD = /(?:^|=\s*|return\s+)(?:[\w.]+\s+(?=switch))?(?:match\b\s*[^{\s][^{]*|when\s*(?:\([^{]*\))?|switch)\s*\{\s*$/;
2522
3457
  function braceStatements(stmts, split = null) {
2523
3458
  return stmts.map((s) => {
2524
3459
  const text = s.text;
2525
- const open = text.indexOf("{");
3460
+ const head0 = headLine(text);
3461
+ const lit2 = BLOCK_HEAD.test(head0) && !/^func\s*\(/.test(head0) ? null : fnLiteral(text);
3462
+ let open = lit2?.open ?? text.indexOf("{");
2526
3463
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
2527
3464
  const read = (o, e) => {
2528
- const body = e > o ? text.slice(o + 1, e) : "";
2529
- const base = s.start != null ? s.start + o + 1 : null;
3465
+ let from = o + 1;
3466
+ const params = text.slice(from, e).match(LAMBDA_PARAMS);
3467
+ if (params && !ARMS_HEAD.test(head0)) from += params[0].length;
3468
+ const body = e > from ? text.slice(from, e) : "";
3469
+ const base = s.start != null ? s.start + from : null;
2530
3470
  if (!body || !split) return [];
2531
- 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 } : {} }));
3471
+ const kids2 = split(body, lineAtPos(from)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
2532
3472
  return braceStatements(kids2, split);
2533
3473
  };
3474
+ const readArms = (o, e) => {
3475
+ const body = e > o ? text.slice(o + 1, e) : "";
3476
+ const arms = body ? armsOf(body) : null;
3477
+ if (!arms || !split) return null;
3478
+ return arms.map((a) => {
3479
+ const at = o + 1 + a.at, bodyAt = o + 1 + a.bodyAt, end = o + 1 + a.end;
3480
+ const pos = (p) => s.start != null ? { start: s.start + p } : {};
3481
+ let kids2 = [];
3482
+ if (a.body.startsWith("{")) kids2 = read(bodyAt, blockEnd(text, bodyAt));
3483
+ else if (a.body) kids2 = braceStatements([{ text: a.body.replace(/,$/, ""), line: lineAtPos(bodyAt), endLine: lineAtPos(Math.max(bodyAt, end - 1)), ...s.start != null ? { start: s.start + bodyAt, end: s.start + bodyAt + a.body.replace(/,$/, "").length } : {} }], split);
3484
+ return { text: text.slice(at, end).trim(), arm: a.pattern, line: lineAtPos(at), endLine: lineAtPos(Math.max(at, end - 1)), ...pos(at), ...s.start != null ? { end: s.start + end } : {}, inner: kids2.length, children: kids2 };
3485
+ });
3486
+ };
2534
3487
  let children = [], inner = 0;
2535
3488
  const clauses = [];
3489
+ if (lit2?.expr) {
3490
+ const [f, t] = lit2.expr;
3491
+ const raw = text.slice(f, t);
3492
+ const lead = raw.length - raw.trimStart().length;
3493
+ const expr = raw.trim();
3494
+ if (expr) children = braceStatements([{ text: expr, line: lineAtPos(f + lead), endLine: lineAtPos(f + lead + expr.length - 1), ...s.start != null ? { start: s.start + f + lead, end: s.start + f + lead + expr.length } : {} }], split);
3495
+ inner = children.length;
3496
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, fn: { depth: lit2.depth, expr: true, after: text.slice(t) } };
3497
+ }
2536
3498
  if (open >= 0) {
2537
3499
  const end = blockEnd(text, open);
3500
+ if (!lit2 && ARMS_HEAD.test(head0)) {
3501
+ const arms = readArms(open, end);
3502
+ if (arms) return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner: arms.length, children: arms, arms: true };
3503
+ }
2538
3504
  const body = end > open ? text.slice(open + 1, end) : "";
2539
3505
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
2540
3506
  children = read(open, end);
@@ -2553,7 +3519,7 @@ function braceStatements(stmts, split = null) {
2553
3519
  pos = e + 1;
2554
3520
  }
2555
3521
  }
2556
- return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {} };
3522
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {}, ...lit2 ? { fn: { depth: lit2.depth, after: text.slice(lit2.close + 1) } } : {} };
2557
3523
  });
2558
3524
  }
2559
3525
  function indentStatements(body, { depthKey = "indent" } = {}) {
@@ -3505,7 +4471,7 @@ function notesSummary(ast) {
3505
4471
  byLens
3506
4472
  };
3507
4473
  }
3508
- var COMPILER_VERSION = "0.5.9";
4474
+ var COMPILER_VERSION = "0.5.10";
3509
4475
  var PROOF_SCHEMA_VERSION = "0.1.0";
3510
4476
  var SOURCE_PRODUCT = "skillstech-compiler";
3511
4477
  function buildContractGraph(ast, generatedAt) {
@@ -4100,11 +5066,11 @@ function normalizeSeeds(seeds) {
4100
5066
  }
4101
5067
  return out;
4102
5068
  }
4103
- function words3(name) {
5069
+ function words4(name) {
4104
5070
  return String(name).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
4105
5071
  }
4106
5072
  function pascal(name) {
4107
- return words3(name).split(/\s+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
5073
+ return words4(name).split(/\s+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
4108
5074
  }
4109
5075
  function parseParams(raw) {
4110
5076
  if (!raw.trim()) return [];
@@ -4690,7 +5656,7 @@ function inferIntent(facts) {
4690
5656
  sensitive: SENSITIVE.test(`${p.name} ${p.type || ""}`)
4691
5657
  }));
4692
5658
  const guarantees = facts.tests.map((t) => ({
4693
- statement: words3(t.name),
5659
+ statement: words4(t.name),
4694
5660
  evidence: `test ${t.name}`,
4695
5661
  confidence: "high",
4696
5662
  sourceSpan: { file: t.file, line: t.line }
@@ -4698,7 +5664,7 @@ function inferIntent(facts) {
4698
5664
  const variantErrors = facts.errors.map((e) => e.name);
4699
5665
  const errorNames = [...new Set(variantErrors.length ? variantErrors : error ? [error] : [])].filter((n) => n && !/^(string|number|boolean|void|Error)$/i.test(n));
4700
5666
  const neverRules = errorNames.map((n) => ({
4701
- statement: `cause ${words3(n)}`,
5667
+ statement: `cause ${words4(n)}`,
4702
5668
  evidence: `${n} error`,
4703
5669
  confidence: "medium"
4704
5670
  }));
@@ -4720,7 +5686,7 @@ function inferIntent(facts) {
4720
5686
  ...facts.tests.slice(0, 5).map((t) => `test ${t.name}`),
4721
5687
  ...errorNames.slice(0, 5).map((n) => `error ${n}`)
4722
5688
  ],
4723
- goal: `${words3(primary.name)} (inferred from the ${primary.name} signature)`,
5689
+ goal: `${words4(primary.name)} (inferred from the ${primary.name} signature)`,
4724
5690
  inputs,
4725
5691
  output: output && !/^(void|undefined|null)$/i.test(output) ? { name: "result", type: output, evidence: "return type" } : null,
4726
5692
  guarantees,
@@ -4922,8 +5888,8 @@ function liftSource(source, { language = "typescript", file = "", seeds = void 0
4922
5888
 
4923
5889
  // src/read.mjs
4924
5890
  var READ_SCHEMA = "thunder-reading-v1";
4925
- var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby"];
4926
- var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
5891
+ var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby", "sql"];
5892
+ var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "synchronized", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
4927
5893
  function detectLanguage(source, file = "") {
4928
5894
  if (file) return languageForFile(file);
4929
5895
  const s = String(source);
@@ -5476,7 +6442,7 @@ function kotlinTerminate(body) {
5476
6442
  else if (")]}".includes(c)) depth--;
5477
6443
  else if (c === "\n" && depth === 0) {
5478
6444
  const line = src.slice(src.lastIndexOf("\n", i - 1) + 1, i);
5479
- const next = src.slice(i + 1);
6445
+ const next = src.slice(i + 1, i + 400);
5480
6446
  if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
5481
6447
  out += src.slice(last, i) + ";";
5482
6448
  last = i;
@@ -5613,7 +6579,7 @@ function lex(text) {
5613
6579
  }
5614
6580
  return out;
5615
6581
  }
5616
- var unquote = (t) => t.slice(1, -1);
6582
+ var unquote2 = (t) => t.slice(1, -1);
5617
6583
  function toThunderCondition(text, inputs = []) {
5618
6584
  const toks = lex(text);
5619
6585
  if (!toks || !toks.length) return null;
@@ -5659,7 +6625,7 @@ function toThunderCondition(text, inputs = []) {
5659
6625
  }
5660
6626
  if (/^["']/.test(t)) {
5661
6627
  if (t[0] === '"' && /#\{|\$\{|\$[A-Za-z_]/.test(t)) return null;
5662
- out.push(JSON.stringify(unquote(t)));
6628
+ out.push(JSON.stringify(unquote2(t)));
5663
6629
  continue;
5664
6630
  }
5665
6631
  if (/^\d/.test(t)) {
@@ -5761,7 +6727,7 @@ function toThunderOutcome(text) {
5761
6727
  }
5762
6728
  var lastSeg2 = (s) => String(s).split(/\.|::/).pop();
5763
6729
  var firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
5764
- function splitTop(str, delim) {
6730
+ function splitTop2(str, delim) {
5765
6731
  const out = [];
5766
6732
  let depth = 0, cur = "";
5767
6733
  for (let i = 0; i < str.length; i++) {
@@ -5806,7 +6772,7 @@ function terminatorEffect(stmt, language) {
5806
6772
  if (!(m = s.match(/^return\s+([\s\S]+)$/))) return null;
5807
6773
  const v = m[1].trim();
5808
6774
  if (language === "go") {
5809
- const parts = splitTop(v, ",").map((x) => x.trim());
6775
+ const parts = splitTop2(v, ",").map((x) => x.trim());
5810
6776
  const last = parts[parts.length - 1];
5811
6777
  if (last === "err" || /^fmt\.Errorf\([^)]*%w/.test(last)) return { kind: "passes-error" };
5812
6778
  if (m = last.match(/^(?:errors\.New|fmt\.Errorf)\(\s*"([^"]*)"/)) return { kind: "fails", name: "error", detail: m[1] };
@@ -5838,7 +6804,7 @@ function sayGuard(effect, condText) {
5838
6804
  }
5839
6805
  }
5840
6806
  function makeGuard(cond, branch, language, inputs, line) {
5841
- const stmts = splitTop(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
6807
+ const stmts = splitTop2(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
5842
6808
  if (stmts.length !== 1 || /\n\s*\S[\s\S]*\n/.test(stmts[0]) && !/^(throw|raise|return)/.test(stmts[0])) return null;
5843
6809
  const effect = terminatorEffect(stmts[0], language);
5844
6810
  if (!effect) return null;
@@ -5884,7 +6850,7 @@ function patternCondition(pattern, subject, inputs, language) {
5884
6850
  const v2 = toThunderOutcome(m[1]);
5885
6851
  return v2 ? `${subject} != ${/^[A-Za-z_]/.test(v2) && !/^(true|false)$/.test(v2) ? v2 : v2}` : null;
5886
6852
  }
5887
- const parts = splitTop(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
6853
+ const parts = splitTop2(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
5888
6854
  if (parts.length > 1) {
5889
6855
  const each = parts.map((x) => patternCondition(x, subject, inputs, language));
5890
6856
  return each.every(Boolean) ? each.map((c) => /\s(and|or)\s/.test(c) ? `(${c})` : c).join(" or ") : null;
@@ -6090,8 +7056,9 @@ function splitStatements(body, baseLine) {
6090
7056
  }
6091
7057
  i = close;
6092
7058
  if (depth === 0) {
6093
- const rest2 = src.slice(i + 1).match(/^\s*else\b/);
6094
- if (!rest2) {
7059
+ const next = src.slice(i + 1, i + 40);
7060
+ const goes = /^\s*else\b/.test(next) || /^do\b/.test(prefix) && /^\s*while\b/.test(next) || /^\(/.test(next) && /^(?:go\s+|defer\s+)?func\s*\(/.test(prefix);
7061
+ if (!goes) {
6095
7062
  i++;
6096
7063
  break;
6097
7064
  }
@@ -6105,6 +7072,10 @@ function splitStatements(body, baseLine) {
6105
7072
  let j = i + 1;
6106
7073
  while (j < src.length && (src[j] === " " || src[j] === " " || src[j] === "\n" || src[j] === "\r")) j++;
6107
7074
  const after = src.slice(j, j + 24);
7075
+ if (/^(?:case\b[^\n]*|default\s*):$/.test(before)) {
7076
+ i++;
7077
+ break;
7078
+ }
6108
7079
  if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) {
6109
7080
  i++;
6110
7081
  break;
@@ -6239,7 +7210,7 @@ function readBraceStatements(stmts, language, inputs) {
6239
7210
  continue;
6240
7211
  }
6241
7212
  if (language === "php" && (m = t.match(/^abort_(if|unless)\s*\(([\s\S]*)\)\s*;?$/))) {
6242
- const args = splitTop(m[2], ",").map((x) => x.trim());
7213
+ const args = splitTop2(m[2], ",").map((x) => x.trim());
6243
7214
  if (args.length >= 2 && /^\d{3}$/.test(args[1])) {
6244
7215
  const cond = m[1] === "if" ? args[0] : `!(${args[0]})`;
6245
7216
  const when = toThunderCondition(cond, inputs);
@@ -6527,8 +7498,8 @@ function findRubyFunctions(src) {
6527
7498
  var RB_PREDICATE_NOT_FIELD = /^(nil|empty|zero|blank|present|any|none|all|include|key|is_a|kind_of|respond_to|start_with|end_with|between|positive|negative|even|odd)$/;
6528
7499
  function rbExpr(text) {
6529
7500
  let bad = false;
6530
- const bare = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
6531
- if (/===/.test(bare) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare)) return null;
7501
+ const bare2 = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
7502
+ if (/===/.test(bare2) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare2.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare2)) return null;
6532
7503
  const out = mapCode(String(text), (code) => code.replace(/@(?=[A-Za-z_])/g, "").replace(/(^|[\s(,=!<>[])::?([A-Za-z_]\w*)\b(?!:)/g, (all, pre, name) => all.includes("::") ? all : `${pre}"${name}"`).replace(/\.(\w+)\?/g, (all, name) => {
6533
7504
  if (RB_PREDICATE_NOT_FIELD.test(name)) bad = true;
6534
7505
  return `.${name}`;
@@ -6828,9 +7799,10 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
6828
7799
  function readCode(source, { language, file = "" } = {}) {
6829
7800
  const src = String(source ?? "");
6830
7801
  if (src.length > 4e5) throw new Error("Source is larger than 400 KB. Read one file or module at a time.");
6831
- const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, "typescript").replace(/^js$/, "javascript").replace(/^py$/, "python").replace(/^(cs|c#)$/, "csharp").replace(/^rs$/, "rust").replace(/^golang$/, "go").replace(/^kts?$/, "kotlin").replace(/^rb$/, "ruby");
7802
+ const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, "typescript").replace(/^js$/, "javascript").replace(/^py$/, "python").replace(/^(cs|c#)$/, "csharp").replace(/^rs$/, "rust").replace(/^golang$/, "go").replace(/^kts?$/, "kotlin").replace(/^rb$/, "ruby").replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, "sql");
6832
7803
  if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(", ")}. Got "${lang}".`);
6833
7804
  READING_RUST = lang === "rust";
7805
+ if (lang === "sql") return sqlReading(src);
6834
7806
  const code = lang === "php" ? normalizePhp(src) : src;
6835
7807
  const items = [];
6836
7808
  const srcLines = src.split("\n");
@@ -6929,6 +7901,22 @@ function searchReading(reading, { query = "", kinds = [], status = [] } = {}) {
6929
7901
  return terms.every((t) => hay.includes(t));
6930
7902
  });
6931
7903
  }
7904
+ function sqlReading(src) {
7905
+ const items = sqlItems(src);
7906
+ for (const it of items) it.completeness = completenessOf(it);
7907
+ const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
7908
+ return {
7909
+ schema: READ_SCHEMA,
7910
+ language: "sql",
7911
+ detected: false,
7912
+ items,
7913
+ counts,
7914
+ limitations: [
7915
+ "Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.",
7916
+ "Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps."
7917
+ ]
7918
+ };
7919
+ }
6932
7920
 
6933
7921
  // src/anchor.mjs
6934
7922
  var ANCHOR_SCHEMA = "thunder-anchor-v1";
@@ -7432,7 +8420,7 @@ function changedCases(before, after) {
7432
8420
  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.` };
7433
8421
  }
7434
8422
  var CMP_WORDS = { "<=": "at most", "<": "less than", ">=": "at least", ">": "more than", "==": "is", "!=": "is not" };
7435
- var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words6]) => ({ op, words: words6 }));
8423
+ var COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words7]) => ({ op, words: words7 }));
7436
8424
  function ruleParts(when) {
7437
8425
  return tokenize(when).map((t) => {
7438
8426
  if (t.t === "num") return { kind: "number", value: t.v };
@@ -7556,8 +8544,8 @@ function parsePlainContract(source) {
7556
8544
  const input = parseInputLine(text, line);
7557
8545
  if (RESERVED.has(input.id) || !input.id) fail2(line, "Choose a different name for this input.");
7558
8546
  if (model.inputs.some((i) => i.id === input.id)) fail2(line, `${input.label} is listed twice.`);
7559
- const words6 = model.inputs.flatMap((i) => i.kind === "yesno" ? [i.yes, i.no] : []);
7560
- if (input.kind === "yesno" && (words6.includes(input.yes) || words6.includes(input.no))) fail2(line, "Each yes/no word must be unique across inputs.");
8547
+ const words7 = model.inputs.flatMap((i) => i.kind === "yesno" ? [i.yes, i.no] : []);
8548
+ if (input.kind === "yesno" && (words7.includes(input.yes) || words7.includes(input.no))) fail2(line, "Each yes/no word must be unique across inputs.");
7561
8549
  model.inputs.push(input);
7562
8550
  } else if (section === "decision") {
7563
8551
  let m;
@@ -7892,7 +8880,7 @@ var LANGUAGES = {
7892
8880
  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)" },
7893
8881
  php: { name: "PHP", status: "available", action: "#[Route] (Symfony)", decision: "a function that returns fixed answers", doc: "/** PHPDoc */", "data-shape": "class, enum (planned)" },
7894
8882
  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)" },
7895
- 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" }
8883
+ sql: { name: "SQL", status: "available", action: "(none: SQL is reached through the app)", decision: "CHECK and UNIQUE constraints; IF in functions and 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" }
7896
8884
  };
7897
8885
  var RULES = [
7898
8886
  "Show the picture first, Thunder Text second, and the original code one click away.",
@@ -7904,7 +8892,7 @@ var RULES = [
7904
8892
  "Say the action that is really possible: Propose rule change until a change is written back and checked; never Update code.",
7905
8893
  "Use the reader's words: plain names, no syntax. A step that would only restate the code shows the code instead."
7906
8894
  ];
7907
- var words4 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
8895
+ var words5 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
7908
8896
  function visualFor(item2) {
7909
8897
  if (!item2 || typeof item2 !== "object") throw new Error("visualFor needs a reader item.");
7910
8898
  const base = { provenance: item2.provenance === "confirmed" ? "confirmed" : "from-code", ...item2.doc ? { doc: { text: item2.doc, provenance: "authors-note" } } : {} };
@@ -7913,11 +8901,11 @@ function visualFor(item2) {
7913
8901
  const badge = item2.route ? { kind: "route", text: `${item2.route.method} ${item2.route.path}`.trim() } : void 0;
7914
8902
  if (item2.kind === "decision") {
7915
8903
  const card = safePlain(item2);
7916
- 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 };
8904
+ return { element: "decision", shape: "card", line: item2.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words5(item2.name)} decides`, ...badge ? { badge } : {}, ...item2.status === "partial" ? { note: "Partly read" } : {}, ...base };
7917
8905
  }
7918
8906
  const readable = (item2.stepsReadable ?? 0) >= 0.5 && item2.steps?.length;
7919
- if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words4(item2.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
7920
- 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 };
8907
+ if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words5(item2.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
8908
+ return { element: item2.route ? "action" : "function", shape: "steps-card", line: "solid", title: item2.route ? `When someone calls ${badge.text}` : `What ${words5(item2.name)} does`, ...badge ? { badge } : {}, ...base };
7921
8909
  }
7922
8910
  function visualForStep(step) {
7923
8911
  const key = step?.restates ? "restates" : STEP_MARKS[step?.kind] ? step.kind : "other";
@@ -7944,7 +8932,7 @@ function thunderText(item2) {
7944
8932
  }
7945
8933
  const out = [v.title];
7946
8934
  if (item2.doc) out.push(` Author's note: "${item2.doc}"`);
7947
- if (item2.inputs?.length) out.push(` Takes ${item2.inputs.map((p) => words4(p.name)).join(", ")}`);
8935
+ if (item2.inputs?.length) out.push(` Takes ${item2.inputs.map((p) => words5(p.name)).join(", ")}`);
7948
8936
  const steps = item2.steps || [];
7949
8937
  const lines = (list, depth) => {
7950
8938
  for (const st of list) {
@@ -8029,7 +9017,7 @@ function thunderTokens(line) {
8029
9017
  push(m[2]);
8030
9018
  push(m[3], "failure");
8031
9019
  push(m[4]);
8032
- words6(m[5]);
9020
+ words7(m[5]);
8033
9021
  } else if (m = rest2.match(/^(Answer:|Gives back|Returns)(\s*)(.*)$/)) {
8034
9022
  push(m[1], "structure");
8035
9023
  push(m[2]);
@@ -8037,7 +9025,7 @@ function thunderTokens(line) {
8037
9025
  } else if (m = rest2.match(/^(Ask:)(\s*)(.*)$/)) {
8038
9026
  push(m[1], "structure");
8039
9027
  push(m[2]);
8040
- words6(m[3], "question");
9028
+ words7(m[3], "question");
8041
9029
  } else if (m = rest2.match(/^`(.*)`(.*)$/)) {
8042
9030
  push(`\`${m[1]}\``, "unread");
8043
9031
  push(m[2], "unread");
@@ -8045,12 +9033,12 @@ function thunderTokens(line) {
8045
9033
  const s = rest2.match(STRUCTURE_WORDS);
8046
9034
  if (s) {
8047
9035
  push(s[0], "structure");
8048
- words6(rest2.slice(s[0].length));
8049
- } else words6(rest2);
9036
+ words7(rest2.slice(s[0].length));
9037
+ } else words7(rest2);
8050
9038
  }
8051
9039
  push(tail, "unread");
8052
9040
  return out;
8053
- function words6(text, base = null) {
9041
+ function words7(text, base = null) {
8054
9042
  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;
8055
9043
  let last = 0, x;
8056
9044
  while (x = re.exec(text)) {
@@ -8079,7 +9067,8 @@ var EXT_LANG = [
8079
9067
  [/\.java$/i, "java"],
8080
9068
  [/\.kts?$/i, "kotlin"],
8081
9069
  [/\.php$/i, "php"],
8082
- [/\.rb$/i, "ruby"]
9070
+ [/\.rb$/i, "ruby"],
9071
+ [/\.sql$/i, "sql"]
8083
9072
  ];
8084
9073
  var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
8085
9074
  "node_modules",
@@ -8210,43 +9199,446 @@ function groupByFile(items) {
8210
9199
  }
8211
9200
  return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
8212
9201
  }
9202
+ function readFiles(files) {
9203
+ return files.map((f) => {
9204
+ const language = readableLanguage(f.path);
9205
+ if (!language || !f.source || f.reading) return f;
9206
+ try {
9207
+ return { ...f, reading: readCode(f.source, { language, file: f.path }) };
9208
+ } catch (e) {
9209
+ return { ...f, readError: e.message };
9210
+ }
9211
+ });
9212
+ }
9213
+ function readingOf(f, language = readableLanguage(f.path)) {
9214
+ if (f.readError) throw new Error(f.readError);
9215
+ return f.reading ?? readCode(f.source, { language, file: f.path });
9216
+ }
9217
+
9218
+ // src/things-langs.mjs
9219
+ function braceEnd(src, open) {
9220
+ let depth = 0;
9221
+ for (let i = open; i < src.length; i++) {
9222
+ const c = src[i];
9223
+ if (c === "/" && src[i + 1] === "/") {
9224
+ const n = src.indexOf("\n", i);
9225
+ if (n < 0) return -1;
9226
+ i = n;
9227
+ continue;
9228
+ }
9229
+ if (c === "/" && src[i + 1] === "*") {
9230
+ const n = src.indexOf("*/", i + 2);
9231
+ if (n < 0) return -1;
9232
+ i = n + 1;
9233
+ continue;
9234
+ }
9235
+ if (c === '"' || c === "`") {
9236
+ const q = c;
9237
+ for (i++; i < src.length && src[i] !== q; i++) if (src[i] === "\\") i++;
9238
+ continue;
9239
+ }
9240
+ if (c === "'" && /^'(?:\\.|[^\\'])'/.test(src.slice(i, i + 4))) {
9241
+ i = src.indexOf("'", i + 1 + (src[i + 1] === "\\" ? 1 : 0));
9242
+ continue;
9243
+ }
9244
+ if (c === "{") depth++;
9245
+ else if (c === "}" && --depth === 0) return i;
9246
+ }
9247
+ return -1;
9248
+ }
9249
+ function lineFinder2(src) {
9250
+ const starts = [0];
9251
+ for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
9252
+ return (idx) => {
9253
+ let lo = 0, hi = starts.length - 1;
9254
+ while (lo < hi) {
9255
+ const mid = lo + hi + 1 >> 1;
9256
+ if (starts[mid] <= idx) lo = mid;
9257
+ else hi = mid - 1;
9258
+ }
9259
+ return lo + 1;
9260
+ };
9261
+ }
9262
+ function docAbove2(src, idx) {
9263
+ let before = src.slice(Math.max(0, idx - 1200), idx).trimEnd();
9264
+ for (let n = 0; n < 20; n++) {
9265
+ const next = before.replace(/(?:@\w+(?:\([^)]*\))?|#\[[^\]]*\]|\[[A-Z]\w*(?:\([^)]*\))?\])$/, "").trimEnd();
9266
+ if (next === before) break;
9267
+ before = next;
9268
+ }
9269
+ let m = /\*\/\s*$/.test(before) ? before.slice(before.lastIndexOf("/**")).match(/^\/\*\*([\s\S]*?)\*\/\s*$/) : null;
9270
+ if (m) return m[1].split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim()).filter((l) => l && !l.startsWith("@")).join(" ").split(/\s{2,}/)[0] || null;
9271
+ const lines = before.split("\n");
9272
+ const run = [];
9273
+ for (let k = lines.length - 1; k >= 0 && /^\s*(?:\/\/\/?|#(?!\[))/.test(lines[k]); k--) run.unshift(lines[k]);
9274
+ if (run.length) {
9275
+ const text = run.map((l) => l.replace(/^\s*(?:\/\/\/?|#)\s?/, "").trim()).filter(Boolean).join(" ").replace(/<\/?summary>/g, "").trim();
9276
+ return text && !/^(frozen_string_literal|!|typed:)/.test(text) ? text : null;
9277
+ }
9278
+ return null;
9279
+ }
9280
+ function ownLevel(body) {
9281
+ let depth = 0, own = "";
9282
+ for (const c of body) {
9283
+ if (c === "{") depth++;
9284
+ if (depth === 0) own += c;
9285
+ if (c === "}") depth--;
9286
+ }
9287
+ return own;
9288
+ }
9289
+ function splitParams(s) {
9290
+ const out = [];
9291
+ let depth = 0, cur = "";
9292
+ for (const c of String(s)) {
9293
+ if ("(<[{".includes(c)) depth++;
9294
+ if (")>]}".includes(c)) depth--;
9295
+ if (c === "," && depth === 0) {
9296
+ out.push(cur.trim());
9297
+ cur = "";
9298
+ } else cur += c;
9299
+ }
9300
+ if (cur.trim()) out.push(cur.trim());
9301
+ return out;
9302
+ }
9303
+ function goDoc(src, at, name) {
9304
+ const d = docAbove2(src, at);
9305
+ if (!d) return null;
9306
+ const t = d.replace(new RegExp(`^${name}\\s+(?:is|holds|represents)\\s+`), "").replace(new RegExp(`^${name}\\s+`), "");
9307
+ return t.charAt(0).toUpperCase() + t.slice(1);
9308
+ }
9309
+ function makeThingReaders({ words: words7, kindWords: kindWords2, startValue: startValue2 }) {
9310
+ const know = (name, type, start, params, line = null) => ({ name, label: words7(name.replace(/^[_$]+|_$/g, "")), kind: type ? kindWords2(type) : null, start: start != null && start !== "" ? startValue2(start, params) : null, line });
9311
+ function curlyThings(src, file, language) {
9312
+ const lineAt2 = lineFinder2(src);
9313
+ const out = [];
9314
+ const kw = {
9315
+ java: /(?:^|\n)[ \t]*(?:@\w+(?:\([^)]*\))?\s*)*(?:(?:public|private|protected|static|final|abstract|sealed|non-sealed)\s+)*(class|enum|record)\s+(\w+)\s*(?:<[^>{]*>)?\s*(\([^)]*\))?[^{;]*\{/g,
9316
+ csharp: /(?:^|\n)[ \t]*(?:\[[^\]]*\]\s*)*(?:(?:public|private|protected|internal|static|sealed|abstract|partial|readonly|file)\s+)*(class|struct|enum|record(?:\s+(?:class|struct))?)\s+(\w+)\s*(?:<[^>{(]*>)?\s*(\([^)]*\))?[^{;]*(?:\{|;)/g,
9317
+ kotlin: /(?:^|\n)[ \t]*(?:@\w+(?:\([^)]*\))?\s*)*(?:(?:public|private|protected|internal|open|abstract|sealed|final|data|enum|value|inline)\s+)*(class|object)\s+(\w+)\s*(?:<[^>{(]*>)?\s*(?:(?:private|internal|public)?\s*constructor\s*)?(\((?:[^()]|\([^()]*\))*\))?[^{\n]*(\{)?/g,
9318
+ php: /(?:^|\n)[ \t]*(?:#\[[^\]]*\]\s*)*(?:(?:final|abstract|readonly)\s+)*(class|enum)\s+(\w+)(?:\s*:\s*\w+)?[^{;]*\{/g
9319
+ }[language];
9320
+ if (!kw) return out;
9321
+ let m;
9322
+ while (m = kw.exec(src)) {
9323
+ const declAt = m.index + (m[0].startsWith("\n") ? 1 : 0);
9324
+ const head = m[0];
9325
+ const kindWord = m[1];
9326
+ const name = m[2];
9327
+ const ctorParams = m[3] && m[3].startsWith("(") ? m[3].slice(1, -1) : "";
9328
+ const isData = language === "kotlin" ? /\bdata\s+class\b|\bvalue\s+class\b/.test(head) : false;
9329
+ const isEnum = kindWord === "enum" || language === "kotlin" && /\benum\s+class\b/.test(head);
9330
+ const isRecord = !isEnum && (/^record/.test(kindWord) || isData || language === "csharp" && kindWord === "struct");
9331
+ const open = head.trimEnd().endsWith("{") ? m.index + head.trimEnd().length - 1 : -1;
9332
+ const close = open >= 0 ? braceEnd(src, open) : -1;
9333
+ if (open >= 0 && close < 0) continue;
9334
+ const body = open >= 0 ? src.slice(open + 1, close) : "";
9335
+ const thing = {
9336
+ kind: isEnum ? "choices" : isRecord ? "record" : "thing",
9337
+ name,
9338
+ file,
9339
+ lines: [lineAt2(declAt), lineAt2(close >= 0 ? close : m.index + head.length)],
9340
+ ...docAbove2(src, declAt) ? { doc: docAbove2(src, declAt) } : {},
9341
+ knows: [],
9342
+ choices: []
9343
+ };
9344
+ const params = {};
9345
+ for (const p of splitParams(ctorParams)) {
9346
+ let pm;
9347
+ if (language === "kotlin" && (pm = p.match(/^(?:@\w+\s+)*(?:(?:private|public|protected|internal|override|open)\s+)*(val|var)?\s*(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/))) {
9348
+ params[pm[2]] = pm[4] ?? null;
9349
+ if (pm[1]) thing.knows.push(know(pm[2], pm[3], pm[4], {}, null));
9350
+ } else if (pm = p.match(/^(?:@\w+\s+)*(?:final\s+)?([\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/)) {
9351
+ params[pm[2]] = pm[3] ?? null;
9352
+ if (/^record/.test(kindWord) || language === "csharp" && /^record/.test(kindWord)) thing.knows.push(know(pm[2], pm[1], pm[3], {}, null));
9353
+ }
9354
+ }
9355
+ if (isEnum) {
9356
+ const own2 = ownLevel(body.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, ""));
9357
+ const list = language === "php" ? [...own2.matchAll(/\bcase\s+(\w+)(?:\s*=\s*([^;]+))?;/g)].map((x) => [x[1], x[2]]) : own2.split(";")[0].split(",").map((x) => x.trim().match(/^(?:@\w+\s+)*(\w+)\s*(?:\((.*)\))?(?:\s*=\s*(.+))?/s)).filter(Boolean).map((x) => [x[1], x[2] ?? x[3]]);
9358
+ for (const [n, v] of list) if (n && !/^(public|private|protected|fun|val|var|companion)$/.test(n)) thing.choices.push(v && /^\s*["']/.test(v) ? v.trim().replace(/^["'](.*)["']$/s, "$1") : words7(n));
9359
+ out.push(thing);
9360
+ continue;
9361
+ }
9362
+ const own = ownLevel(body);
9363
+ for (const raw of own.split(/[;\n]/)) {
9364
+ const l = raw.trim().replace(/^(?:@\w+(?:\([^)]*\))?\s*)+/, "").replace(/^#\[[^\]]*\]\s*/, "");
9365
+ if (!l || /^(\/\/|\/\*|\*|import|package|use|return|case|default|enum\s|class\s|interface\s|fun\s|function\s|def\s|init\b|constructor|companion|object\s)/.test(l) || /\)\s*$/.test(l) && !/=/.test(l)) continue;
9366
+ let f;
9367
+ if (language === "kotlin" && (f = l.match(/^(?:(?:private|public|protected|internal|override|open|lateinit|const)\s+)*(?:val|var)\s+(\w+)\s*(?::\s*([^=]+?))?\s*(?:=\s*(.+))?$/))) {
9368
+ thing.knows.push(know(f[1], f[2], f[3], params));
9369
+ } else if (language === "php" && (f = l.match(/^(?:(?:public|private|protected|static|readonly)\s+)+(?:\??[\w\\]+\s+)?\$(\w+)(?:\s*=\s*(.+))?$/))) {
9370
+ const type = l.match(/^(?:(?:public|private|protected|static|readonly)\s+)+(\??[\w\\]+)\s+\$/)?.[1];
9371
+ thing.knows.push(know(f[1], type, f[2], params));
9372
+ } else if (language === "csharp" && (f = l.match(/^(?:(?:public|private|protected|internal|static|readonly|required|virtual|override|const)\s+)*([\w.<>[\],? ]+?)\s+(\w+)\s*\{\s*(?:get|init|set)[^}]*\}(?:\s*=\s*(.+))?$/))) {
9373
+ thing.knows.push(know(f[2], f[1], f[3], params));
9374
+ } else if ((language === "java" || language === "csharp") && (f = l.match(/^(?:(?:public|private|protected|internal|static|final|readonly|transient|volatile|const)\s+)*([\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/)) && !/^(new|return|throw|if|for|while)$/.test(f[1].trim())) {
9375
+ if (/\bstatic\b/.test(l) && /\bfinal\b|\bconst\b/.test(l)) continue;
9376
+ thing.knows.push(know(f[2], f[1], f[3], params));
9377
+ }
9378
+ }
9379
+ const ctorRe = language === "php" ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === "kotlin" ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
9380
+ const ctor = body.match(ctorRe);
9381
+ if (ctor) {
9382
+ for (const p of splitParams(ctor[1] || "")) {
9383
+ const pm = language === "php" ? p.match(/^(?:(public|private|protected)(?:\s+readonly)?\s+)?(?:\??[\w\\]+\s+)?\$(\w+)(?:\s*=\s*(.+))?$/) : p.match(/^(?:final\s+)?(?:[\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/);
9384
+ if (!pm) continue;
9385
+ if (language === "php") {
9386
+ params[pm[2]] = pm[3] ?? null;
9387
+ if (pm[1] && !thing.knows.some((k) => k.name === pm[2])) thing.knows.push(know(pm[2], p.match(/(\??[\w\\]+)\s+\$/)?.[1], pm[3], {}));
9388
+ } else params[pm[1]] = pm[2] ?? null;
9389
+ }
9390
+ const cOpen = body.indexOf("{", ctor.index + ctor[0].length - 1);
9391
+ const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
9392
+ const assign = language === "php" ? /\$this->(\w+)\s*=\s*([^;\n]+)/g : language === "kotlin" ? /(?:this\.)?(\w+)\s*=\s*([^\n;]+)/g : /(?:this\.)?(\w+)\s*=\s*([^;\n]+);/g;
9393
+ for (const a of cBody.matchAll(assign)) {
9394
+ const k = thing.knows.find((x) => x.name === a[1] || x.name === `_${a[1]}` || x.name.replace(/^_/, "") === a[1]);
9395
+ const value = a[2].trim().replace(/^\$/, "");
9396
+ if (k) {
9397
+ if (!k.start) k.start = startValue2(value, params);
9398
+ } else if (language === "php" || /^this\./.test(a[0])) thing.knows.push(know(a[1], null, value, params));
9399
+ }
9400
+ }
9401
+ out.push(thing);
9402
+ }
9403
+ return out;
9404
+ }
9405
+ function goThings(src, file) {
9406
+ const lineAt2 = lineFinder2(src);
9407
+ const out = [];
9408
+ const byName = /* @__PURE__ */ new Map();
9409
+ for (const m of src.matchAll(/(?:^|\n)type\s+(\w+)\s+struct\s*\{/g)) {
9410
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
9411
+ const open = m.index + m[0].length - 1;
9412
+ const close = braceEnd(src, open);
9413
+ if (close < 0) continue;
9414
+ const t = { kind: "record", name: m[1], file, lines: [lineAt2(at), lineAt2(close)], ...goDoc(src, at, m[1]) ? { doc: goDoc(src, at, m[1]) } : {}, knows: [], choices: [], memberRanges: [] };
9415
+ for (const raw of src.slice(open + 1, close).split("\n")) {
9416
+ const f = raw.replace(/\/\/.*$/, "").replace(/`[^`]*`/g, "").trim().match(/^([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*)\s+(\S.*)$/);
9417
+ if (f) for (const n of f[1].split(",")) t.knows.push(know(n.trim(), f[2].trim(), null, {}));
9418
+ }
9419
+ out.push(t);
9420
+ byName.set(m[1], t);
9421
+ }
9422
+ for (const m of src.matchAll(/(?:^|\n)func\s*\(\s*\w*\s*\*?\s*(\w+)(?:\[[^\]]*\])?\s*\)\s*\w+/g)) {
9423
+ const t = byName.get(m[1]);
9424
+ if (!t) continue;
9425
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
9426
+ const open = src.indexOf("{", at);
9427
+ const close = open >= 0 ? braceEnd(src, open) : -1;
9428
+ t.kind = "thing";
9429
+ t.memberRanges.push([lineAt2(at), lineAt2(close >= 0 ? close : at)]);
9430
+ }
9431
+ for (const m of src.matchAll(/func\s+New(\w+)\s*\(([^)]*)\)[^{]*\{/g)) {
9432
+ const t = byName.get(m[1]);
9433
+ if (!t) continue;
9434
+ const open = m.index + m[0].length - 1;
9435
+ const body = src.slice(open, braceEnd(src, open) + 1);
9436
+ const params = Object.fromEntries(splitParams(m[2]).map((p) => [p.split(/\s+/)[0], null]));
9437
+ const litAt = body.search(new RegExp(`&?${m[1]}\\s*\\{`));
9438
+ const litOpen = litAt >= 0 ? body.indexOf("{", litAt) : -1;
9439
+ const litBody = litOpen >= 0 ? body.slice(litOpen + 1, braceEnd(body, litOpen)) : "";
9440
+ for (const kv of splitParams(litBody.replace(/\n/g, ","))) {
9441
+ const f = kv.match(/^(\w+)\s*:\s*(.+)$/);
9442
+ const k = f && t.knows.find((x) => x.name === f[1]);
9443
+ if (k && !k.start) k.start = startValue2(f[2].trim(), params);
9444
+ }
9445
+ }
9446
+ for (const m of src.matchAll(/(?:^|\n)type\s+(\w+)\s+(?:int|int8|int16|int32|uint|uint8|string)\b/g)) {
9447
+ const name = m[1];
9448
+ const block = src.match(new RegExp(`const\\s*\\(([^)]*\\b${name}\\b[^)]*)\\)`));
9449
+ if (!block) continue;
9450
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
9451
+ const choices = [];
9452
+ let inType = false;
9453
+ for (const raw of block[1].split("\n")) {
9454
+ const l = raw.replace(/\/\/.*$/, "").trim();
9455
+ if (!l) continue;
9456
+ const f = l.match(/^(\w+)(?:\s+(\w+))?(?:\s*=\s*(.+))?$/);
9457
+ if (!f) continue;
9458
+ if (f[2]) inType = f[2] === name;
9459
+ if (!inType) continue;
9460
+ const label = f[3] && /^"/.test(f[3].trim()) ? f[3].trim().slice(1, -1) : words7(f[1].replace(new RegExp(`^${name}`), "") || f[1]);
9461
+ choices.push(label);
9462
+ }
9463
+ if (choices.length) out.push({ kind: "choices", name, file, lines: [lineAt2(at), lineAt2(at)], ...goDoc(src, at, name) ? { doc: goDoc(src, at, name) } : {}, knows: [], choices });
9464
+ }
9465
+ return out;
9466
+ }
9467
+ function rustThings(src, file) {
9468
+ const lineAt2 = lineFinder2(src);
9469
+ const out = [];
9470
+ const byName = /* @__PURE__ */ new Map();
9471
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?(struct|enum)\s+(\w+)\s*(?:<[^>{]*>)?\s*(?:where[^{]*)?(\{|\(|;)/g)) {
9472
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
9473
+ const doc = docAbove2(src, at);
9474
+ if (m[3] !== "{") {
9475
+ const t2 = { kind: "record", name: m[2], file, lines: [lineAt2(at), lineAt2(at)], ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
9476
+ out.push(t2);
9477
+ byName.set(m[2], t2);
9478
+ continue;
9479
+ }
9480
+ const open = m.index + m[0].length - 1;
9481
+ const close = braceEnd(src, open);
9482
+ if (close < 0) continue;
9483
+ const body = ownLevel(src.slice(open + 1, close));
9484
+ const t = { kind: m[1] === "enum" ? "choices" : "record", name: m[2], file, lines: [lineAt2(at), lineAt2(close)], ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
9485
+ if (m[1] === "enum") {
9486
+ for (const v of splitParams(body.replace(/\/\/[^\n]*/g, "").replace(/#\[[^\]]*\]/g, ""))) {
9487
+ const n = v.trim().match(/^(\w+)/);
9488
+ if (n) t.choices.push(words7(n[1]));
9489
+ }
9490
+ } else {
9491
+ for (const f of splitParams(body.replace(/\/\/[^\n]*/g, "").replace(/#\[[^\]]*\]/g, ""))) {
9492
+ const fm = f.trim().match(/^(?:pub(?:\([^)]*\))?\s+)?(\w+)\s*:\s*(.+)$/s);
9493
+ if (fm) t.knows.push(know(fm[1], fm[2].trim(), null, {}));
9494
+ }
9495
+ }
9496
+ out.push(t);
9497
+ byName.set(m[2], t);
9498
+ }
9499
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*impl(?:\s*<[^>]*>)?\s+(?:[\w:]+(?:<[^>]*>)?\s+for\s+)?(\w+)(?:<[^>]*>)?\s*(?:where[^{]*)?\{/g)) {
9500
+ const t = byName.get(m[1]);
9501
+ if (!t) continue;
9502
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
9503
+ const close = braceEnd(src, m.index + m[0].length - 1);
9504
+ if (close < 0) continue;
9505
+ if (/\bfn\s+\w+\s*(?:<[^>]*>)?\s*\(\s*&?(?:mut\s+)?self\b/.test(src.slice(at, close))) {
9506
+ if (t.kind === "record") t.kind = "thing";
9507
+ }
9508
+ t.memberRanges.push([lineAt2(at), lineAt2(close)]);
9509
+ const block = src.slice(at, close);
9510
+ const fnNew = block.match(/fn\s+new\s*\(([^)]*)\)[^{;]*\{/);
9511
+ const fnOpen = fnNew ? fnNew.index + fnNew[0].length - 1 : -1;
9512
+ const fnBody = fnOpen >= 0 ? block.slice(fnOpen + 1, braceEnd(block, fnOpen)) : "";
9513
+ const litAt = fnBody.search(new RegExp(`\\b(?:Self|${m[1]})\\s*\\{`));
9514
+ const litOpen = litAt >= 0 ? fnBody.indexOf("{", litAt) : -1;
9515
+ const ctor = litOpen >= 0 ? [null, fnNew[1], fnBody.slice(litOpen + 1, braceEnd(fnBody, litOpen))] : null;
9516
+ if (ctor) {
9517
+ const params = Object.fromEntries(splitParams(ctor[1]).map((p) => [p.split(":")[0].trim(), null]));
9518
+ for (const kv of splitParams(ctor[2].replace(/\n/g, ","))) {
9519
+ const f = kv.match(/^(\w+)(?:\s*:\s*(.+))?$/);
9520
+ const k = f && t.knows.find((x) => x.name === f[1]);
9521
+ if (k && !k.start) k.start = startValue2((f[2] ?? f[1]).trim().replace(/^Vec::new\(\)$|^vec!\[\]$|^HashMap::new\(\)$|^String::new\(\)$/, "[]"), params);
9522
+ }
9523
+ }
9524
+ }
9525
+ return out;
9526
+ }
9527
+ function rubyThings(src, file) {
9528
+ const lines = src.split("\n");
9529
+ const out = [];
9530
+ for (let i = 0; i < lines.length; i++) {
9531
+ const struct = lines[i].match(/^\s*(\w+)\s*=\s*(?:Struct|Data)\.(?:new|define)\(([^)]*)\)/);
9532
+ if (struct) {
9533
+ const t2 = { kind: "record", name: struct[1], file, lines: [i + 1, i + 1], knows: [], choices: [] };
9534
+ for (const s of struct[2].split(",")) {
9535
+ const n = s.trim().match(/^:(\w+)/);
9536
+ if (n) t2.knows.push(know(n[1], null, null, {}, i + 1));
9537
+ }
9538
+ out.push(t2);
9539
+ continue;
9540
+ }
9541
+ const m = lines[i].match(/^(\s*)class\s+(\w+)/);
9542
+ if (!m) continue;
9543
+ const indent = m[1].length;
9544
+ let end = i;
9545
+ for (let j = i + 1; j < lines.length; j++) if (new RegExp(`^\\s{${indent}}end\\b`).test(lines[j]) && lines[j].match(/^\s*/)[0].length === indent) {
9546
+ end = j;
9547
+ break;
9548
+ }
9549
+ if (end === i) continue;
9550
+ const doc = (() => {
9551
+ const d = [];
9552
+ for (let k = i - 1; k >= 0 && /^\s*#/.test(lines[k]); k--) d.unshift(lines[k].replace(/^\s*#\s?/, "").trim());
9553
+ return d.join(" ").trim() || null;
9554
+ })();
9555
+ const t = { kind: "thing", name: m[2], file, lines: [i + 1, end + 1], ...doc && !/frozen_string_literal/.test(doc) ? { doc } : {}, knows: [], choices: [] };
9556
+ const body = lines.slice(i + 1, end);
9557
+ for (let k = 0; k < body.length; k++) {
9558
+ const a = body[k].match(/^\s*attr_(?:reader|accessor|writer)\s+(.+)$/);
9559
+ if (a) for (const s of a[1].split(",")) {
9560
+ const n = s.trim().match(/^:(\w+)/);
9561
+ if (n && !t.knows.some((x) => x.name === n[1])) t.knows.push(know(n[1], null, null, {}, i + 2 + k));
9562
+ }
9563
+ }
9564
+ const init = body.findIndex((l) => /^\s*def\s+initialize\b/.test(l));
9565
+ if (init >= 0) {
9566
+ const sig = body[init].match(/def\s+initialize\s*\(?([^)]*)\)?/);
9567
+ const params = {};
9568
+ for (const p of splitParams(sig?.[1] || "")) {
9569
+ const pm = p.match(/^(\w+):?\s*(?:=\s*)?(.*)$/);
9570
+ if (pm) params[pm[1]] = pm[2] || null;
9571
+ }
9572
+ const ii = body[init].match(/^\s*/)[0].length;
9573
+ for (let k = init + 1; k < body.length; k++) {
9574
+ if (body[k].trim() && body[k].match(/^\s*/)[0].length <= ii) break;
9575
+ const a = body[k].trim().match(/^@(\w+)\s*=\s*(.+)$/);
9576
+ if (!a) continue;
9577
+ const kn = t.knows.find((x) => x.name === a[1]);
9578
+ if (kn) {
9579
+ if (!kn.start) kn.start = startValue2(a[2], params);
9580
+ } else t.knows.push(know(a[1], null, a[2], params, i + 2 + k));
9581
+ }
9582
+ }
9583
+ if (!t.knows.length && !body.some((l) => /^\s*def\s/.test(l))) t.kind = "record";
9584
+ out.push(t);
9585
+ }
9586
+ return out;
9587
+ }
9588
+ return function thingsFor2(language, src, file) {
9589
+ if (language === "go") return goThings(src, file);
9590
+ if (language === "rust") return rustThings(src, file);
9591
+ if (language === "ruby") return rubyThings(src, file);
9592
+ if (["java", "csharp", "kotlin", "php"].includes(language)) return curlyThings(src, file, language);
9593
+ return [];
9594
+ };
9595
+ }
8213
9596
 
8214
9597
  // src/model.mjs
8215
9598
  var MODEL_SCHEMA = "thunder-model-v1";
8216
- var THING_LANGUAGES = ["python", "typescript", "javascript"];
8217
- var words5 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
9599
+ var THING_LANGUAGES = ["python", "typescript", "javascript", "java", "csharp", "kotlin", "php", "go", "rust", "ruby", "sql"];
9600
+ var words6 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
8218
9601
  var cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
8219
9602
  var stripQuotes2 = (v) => v.replace(/^[rbuf]*(["'`])(.*)\1$/s, "$2");
8220
9603
  function startValue(expr, params = {}) {
8221
9604
  const e = String(expr ?? "").trim();
8222
9605
  if (!e) return null;
8223
9606
  if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, "")} unless told otherwise` : "given when it starts";
8224
- if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+)$/.test(e)) return "empty at first";
8225
- if (/^(None|null|undefined)$/.test(e)) return "nothing at first";
9607
+ if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+|array\(\)|new \w*(?:List|Map|Set|Dictionary|HashMap|HashSet|ArrayList|LinkedList)(?:<[^>]*>)?\(\)|(?:mutable)?(?:List|Map|Set|listOf|mapOf|setOf|mutableListOf|mutableMapOf|mutableSetOf|emptyList|emptyMap|arrayListOf)(?:<[^>]*>)?\(\)|(?:List|Set|Map)\.of\(\)|Vec::new\(\)|vec!\[\]|HashMap::new\(\)|String::new\(\)|\[\]\w+\{\}|make\(\[\][^)]*\)|new\(\)|Hash\.new|\{\s*\})$/.test(e)) return "empty at first";
9608
+ if (/^(None|null|undefined|nil|NULL|Option::None)$/.test(e)) return "nothing at first";
8226
9609
  if (/^(True|true)$/.test(e)) return "yes at first";
8227
9610
  if (/^(False|false)$/.test(e)) return "no at first";
8228
9611
  if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
8229
9612
  if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes2(e)}" at first`;
8230
- const en = e.match(/^[A-Z]\w*\.([A-Z][A-Z0-9_]+)$/);
8231
- if (en) return `${words5(en[1])} at first`;
9613
+ const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/);
9614
+ if (en) return `${words6(en[1])} at first`;
8232
9615
  return "worked out when it starts";
8233
9616
  }
8234
9617
  var KIND_WORDS = [
8235
- [/^(int|float|number|double|long|decimal|Decimal|bigint)$/i, "a number"],
8236
- [/^(str|string|String|text)$/i, "words"],
8237
- [/^(bool|boolean)$/i, "yes or no"],
8238
- [/^(date|datetime|Date|LocalDate|Instant)$/i, "a date"]
9618
+ [/^(int|float|number|double|long|short|decimal|Decimal|bigint|BigDecimal|BigInteger|Integer|Int|Long|Double|Float|Short|Byte|byte|uint|usize|isize|[iuf](?:8|16|32|64|128)|int(?:8|16|32|64)|uint(?:8|16|32|64)|float(?:32|64)|Number)$/, "a number"],
9619
+ [/^(str|string|String|text|&str|&'static str|char|Char|Character|rune)$/, "words"],
9620
+ [/^(bool|boolean|Boolean|Bool)$/, "yes or no"],
9621
+ [/^(date|datetime|Date|LocalDate|LocalDateTime|Instant|DateTime|DateTimeOffset|ZonedDateTime|time\.Time|NaiveDate|NaiveDateTime|DateTimeImmutable)$/, "a date"]
8239
9622
  ];
8240
9623
  function kindWords(type) {
8241
9624
  const t = String(type ?? "").trim();
8242
9625
  if (!t) return null;
8243
9626
  for (const [re, w] of KIND_WORDS) if (re.test(t)) return w;
8244
- const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^Array<(.+)>$|^(.+)\[\]$/);
8245
- if (list) return `a list of ${(list[1] || list[2] || list[3]).trim()}s`;
8246
- const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
8247
- if (opt) return `${kindWords(opt[1] || opt[2] || opt[3]) ?? `a ${opt[1] || opt[2] || opt[3]}`}, or nothing`;
9627
+ const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^(?:Array|List|ArrayList|LinkedList|Vec|VecDeque|IList|IEnumerable|ICollection|IReadOnlyList|Collection|Set|HashSet|MutableList|MutableSet|Sequence|Iterable)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
9628
+ if (list) {
9629
+ const inner = (list[1] || list[2] || list[3] || list[4]).trim();
9630
+ return `a list of ${kindWords(inner)?.replace(/^an? /, "") ?? inner}s`.replace(/wordss$/, "words").replace(/ys$/, "ies").replace(/(yes or no)s$/, "$1 answers");
9631
+ }
9632
+ const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
9633
+ if (opt) {
9634
+ const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7];
9635
+ return `${kindWords(inner) ?? `a ${inner}`}, or nothing`;
9636
+ }
9637
+ const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
9638
+ if (map) return "a lookup table";
8248
9639
  return /^[A-Z]/.test(t) ? `a ${t}` : null;
8249
9640
  }
9641
+ var thingsFor = makeThingReaders({ words: (x) => words6(x), kindWords: (x) => kindWords(x), startValue: (x, p) => startValue(x, p) });
8250
9642
  function pythonThings(src, file) {
8251
9643
  const lines = src.split("\n");
8252
9644
  const out = [];
@@ -8275,8 +9667,8 @@ function pythonThings(src, file) {
8275
9667
  const t = l.text.trim();
8276
9668
  if (/^(def|async def|class|@|"""|'''|#)/.test(t)) continue;
8277
9669
  let f;
8278
- 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]));
8279
- 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 });
9670
+ if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes2(f[2].trim()) : words6(f[1]));
9671
+ else if (f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/)) thing.knows.push({ name: f[1], label: words6(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
8280
9672
  }
8281
9673
  const init = body.findIndex((l) => /^\s*def\s+__init__\s*\(/.test(l));
8282
9674
  if (init >= 0) {
@@ -8293,7 +9685,7 @@ function pythonThings(src, file) {
8293
9685
  const a = ln.trim().match(/^self\.(\w+)\s*(?::\s*([^=]+))?=\s*(.+)$/);
8294
9686
  if (a && !thing.knows.some((x) => x.name === a[1])) {
8295
9687
  const pType = /^\w+$/.test(a[3].trim()) ? (sig?.[1] || "").match(new RegExp(`\\b${a[3].trim()}\\s*:\\s*([\\w\\[\\]. |]+)`))?.[1] : void 0;
8296
- 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 });
9688
+ thing.knows.push({ name: a[1], label: words6(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? "a list" : null), start: startValue(a[3], params), line: i + 2 + k });
8297
9689
  }
8298
9690
  }
8299
9691
  }
@@ -8301,7 +9693,7 @@ function pythonThings(src, file) {
8301
9693
  }
8302
9694
  return out;
8303
9695
  }
8304
- function braceEnd(src, open) {
9696
+ function braceEnd2(src, open) {
8305
9697
  let depth = 0;
8306
9698
  for (let i = open; i < src.length; i++) {
8307
9699
  const c = src[i];
@@ -8322,7 +9714,7 @@ function tsThings(src, file) {
8322
9714
  let m;
8323
9715
  while (m = re.exec(src)) {
8324
9716
  const open = m.index + m[0].length - 1;
8325
- const close = braceEnd(src, open);
9717
+ const close = braceEnd2(src, open);
8326
9718
  if (close < 0) continue;
8327
9719
  const body = src.slice(open + 1, close);
8328
9720
  const startLine = lineOf2(src, m.index + (m[0].startsWith("\n") ? 1 : 0));
@@ -8333,7 +9725,7 @@ function tsThings(src, file) {
8333
9725
  if (m[1] === "enum") {
8334
9726
  for (const part of body.split(",")) {
8335
9727
  const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s);
8336
- if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes2(e[2].trim()) : words5(e[1]));
9728
+ if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes2(e[2].trim()) : words6(e[1]));
8337
9729
  }
8338
9730
  } else {
8339
9731
  let depth = 0, own = "";
@@ -8347,7 +9739,7 @@ function tsThings(src, file) {
8347
9739
  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*(.+)$/);
8348
9740
  if (!f || /\(/.test(f[1])) continue;
8349
9741
  const hasType = f.length > 4 && f[3] && !l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*\w+\s*=/);
8350
- 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 });
9742
+ thing.knows.push({ name: f[1], label: words6(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? f[4] ? startValue(f[4]) : null : startValue(f[3]), line: null });
8351
9743
  }
8352
9744
  const ctor = body.match(/constructor\s*\(([^)]*)\)\s*\{/);
8353
9745
  if (ctor) {
@@ -8357,9 +9749,9 @@ function tsThings(src, file) {
8357
9749
  if (pm) params[pm[1]] = pm[2] ?? null;
8358
9750
  }
8359
9751
  const cOpen = body.indexOf("{", ctor.index + ctor[0].length - 1);
8360
- const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
9752
+ const cBody = body.slice(cOpen + 1, braceEnd2(body, cOpen));
8361
9753
  for (const a of cBody.matchAll(/this\.(\w+)\s*=\s*([^;\n]+)/g)) {
8362
- 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 });
9754
+ if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words6(a[1]), kind: null, start: startValue(a[2], params), line: null });
8363
9755
  else {
8364
9756
  const k = thing.knows.find((x) => x.name === a[1]);
8365
9757
  if (!k.start) k.start = startValue(a[2], params);
@@ -8387,8 +9779,8 @@ function stepDoes(step) {
8387
9779
  if (step.kind === "set") return "calculate";
8388
9780
  return "do";
8389
9781
  }
8390
- 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));
8391
- var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : cap(words5(r));
9782
+ var possessive = (text) => String(text).replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => /^(self|this)$/.test(a) ? `the ${words6(b)}` : `the ${words6(a)}'s ${words6(b)}`).replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words6(m));
9783
+ var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : cap(words6(r));
8392
9784
  function askAsQuestion(step, ruleLabel) {
8393
9785
  let c = String(step.says).replace(/^If /, "").replace(/ \(\d+ steps? inside\)$/, "").trim();
8394
9786
  let flip = false;
@@ -8534,7 +9926,7 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
8534
9926
  }
8535
9927
  var idOf = (...parts) => parts.join("#").replace(/\s+/g, "");
8536
9928
  function youGiveOf(item2) {
8537
- const given = (item2.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words5(p.name));
9929
+ const given = (item2.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words6(p.name));
8538
9930
  const codes = [];
8539
9931
  const walk = (steps) => {
8540
9932
  for (const s of steps || []) {
@@ -8549,7 +9941,7 @@ function youGiveOf(item2) {
8549
9941
  if (!m) continue;
8550
9942
  for (const part of m[1].split(",")) {
8551
9943
  const name = part.split(/[:=]/)[0].replace(/^\.\.\./, "").trim();
8552
- if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words5(name))) given.push(words5(name));
9944
+ if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words6(name))) given.push(words6(name));
8553
9945
  }
8554
9946
  }
8555
9947
  return given;
@@ -8561,14 +9953,14 @@ function thunderModel(files, { name = "app" } = {}) {
8561
9953
  if (!language || !f.source) continue;
8562
9954
  let reading;
8563
9955
  try {
8564
- reading = readCode(f.source, { language, file: f.path });
9956
+ reading = readingOf(f, language);
8565
9957
  } catch (e) {
8566
9958
  unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` });
8567
9959
  continue;
8568
9960
  }
8569
9961
  let fileThings = [];
8570
9962
  try {
8571
- fileThings = language === "python" ? pythonThings(f.source, f.path) : THING_LANGUAGES.includes(language) ? tsThings(f.source, f.path) : [];
9963
+ fileThings = language === "python" ? pythonThings(f.source, f.path) : language === "typescript" || language === "javascript" ? tsThings(f.source, f.path) : language === "sql" ? sqlThings(f.source, f.path) : thingsFor(language, f.source, f.path);
8572
9964
  } catch (e) {
8573
9965
  unknowns.push({ file: f.path, line: 1, why: `Classes in this file could not be drawn as Things: ${e.message}` });
8574
9966
  }
@@ -8577,17 +9969,18 @@ function thunderModel(files, { name = "app" } = {}) {
8577
9969
  }
8578
9970
  for (const t of fileThings) {
8579
9971
  t.id = idOf(f.path, t.name);
8580
- t.label = cap(words5(t.name));
9972
+ t.label = cap(words6(t.name));
8581
9973
  t.can = [];
8582
9974
  things.push(t);
8583
9975
  }
8584
9976
  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, " ") : "";
8585
9977
  fileInfo.push({ path: f.path, language, ...moduleDoc ? { purpose: moduleDoc } : {} });
8586
9978
  const fns = reading.items.filter((i) => i.kind === "function" || i.kind === "decision");
8587
- const fileMembers = fns.map((item2) => {
8588
- 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];
9979
+ const declaredThing = (item2) => fileThings.some((t) => t.name === item2.name && t.lines[0] === item2.line);
9980
+ const fileMembers = fns.filter((item2) => !declaredThing(item2)).map((item2) => {
9981
+ const owner = fileThings.filter((t) => item2.line > t.lines[0] && item2.line <= t.lines[1] || (t.memberRanges || []).some(([a, b]) => item2.line >= a && item2.line <= b)).sort((a, b) => b.lines[0] - a.lines[0])[0];
8589
9982
  const v = visualFor(item2);
8590
- const setup = /^(__init__|constructor|init|New)$/.test(item2.name) && owner;
9983
+ const setup = (/^(__init__|constructor|init|New|__construct|initialize|new)$/.test(item2.name) || owner && item2.name === owner.name) && owner;
8591
9984
  const kind = setup ? "setup" : v.element === "action" ? "action" : v.element === "decision" ? "rule" : v.element === "not-read" ? "not-read" : "steps";
8592
9985
  const bodyEnd2 = item2.anchor?.bodyLines?.[1] ?? Math.max(item2.line, ...(item2.rules || []).map((r) => r.line || 0), item2.otherwise?.line || 0);
8593
9986
  let rule = null;
@@ -8602,7 +9995,7 @@ function thunderModel(files, { name = "app" } = {}) {
8602
9995
  id: idOf(f.path, owner?.name ?? "", item2.name, item2.line),
8603
9996
  kind,
8604
9997
  name: item2.name,
8605
- label: setup ? `A new ${owner.label} starts with` : cap(words5(item2.name.replace(/^__|__$/g, ""))),
9998
+ label: setup ? `A new ${owner.label} starts with` : cap(words6(item2.name.replace(/^__|__$/g, ""))),
8606
9999
  ...owner ? { owner: owner.id } : {},
8607
10000
  file: f.path,
8608
10001
  language,
@@ -8632,6 +10025,14 @@ function thunderModel(files, { name = "app" } = {}) {
8632
10025
  members.push(m);
8633
10026
  }
8634
10027
  }
10028
+ for (const t of things) delete t.memberRanges;
10029
+ const owners = new Set(members.map((x) => x.owner).filter(Boolean));
10030
+ for (let i = things.length - 1; i >= 0; i--) {
10031
+ const t = things[i];
10032
+ if (t.kind !== "thing" || t.knows.length || owners.has(t.id)) continue;
10033
+ if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1);
10034
+ else t.kind = "record";
10035
+ }
8635
10036
  return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
8636
10037
  }
8637
10038
  function flowLines(flow, depth = 1) {
@@ -8735,6 +10136,10 @@ var CHANGES = /^(Sets|Adds|Removes|Subtracts|Clears|Marks|Saves|Deletes|Updates|
8735
10136
  function pathsOf(flow) {
8736
10137
  const byId = new Map(flow.nodes.map((n) => [n.id, n]));
8737
10138
  const out = [];
10139
+ const ends = (blocks2) => {
10140
+ const last = byId.get((blocks2 || []).at(-1)?.id);
10141
+ return !!last && (last.kind === "stop" || last.kind === "end");
10142
+ };
8738
10143
  const walk = (blocks2, when) => {
8739
10144
  for (const b of blocks2 || []) {
8740
10145
  const n = byId.get(b.id);
@@ -8749,6 +10154,11 @@ function pathsOf(flow) {
8749
10154
  walk(h.blocks, [...when, { question: (hn?.text ?? "").replace(/\?$/, ""), answer: "Yes" }]);
8750
10155
  }
8751
10156
  if (b.always) walk(b.always.blocks, when);
10157
+ if (n?.kind === "decision" && (b.yes || b.no)) {
10158
+ const yesEnds = ends(b.yes), noEnds = ends(b.no);
10159
+ if (yesEnds && !noEnds) when = [...when, { question: q, answer: "No" }];
10160
+ else if (noEnds && !yesEnds) when = [...when, { question: q, answer: "Yes" }];
10161
+ }
8752
10162
  }
8753
10163
  };
8754
10164
  walk(flow.blocks, []);
@@ -8889,8 +10299,7 @@ function readLevel(model, level, focus) {
8889
10299
  var THUNDERIZE_SCHEMA = "thunderize-v1";
8890
10300
  var THUNDER_TEXT_EXT = ".thunder-text";
8891
10301
  var LANGUAGE_NAMES = { typescript: "TypeScript", javascript: "JavaScript", python: "Python", go: "Go", rust: "Rust", csharp: "C#", java: "Java", kotlin: "Kotlin", php: "PHP", ruby: "Ruby" };
8892
- function thunderizeFile(path, source, language = readableLanguage(path)) {
8893
- const reading = readCode(source, { language, file: path });
10302
+ function thunderizeFile(path, source, language = readableLanguage(path), reading = readCode(source, { language, file: path })) {
8894
10303
  const main = reading.items.filter((i) => i.kind === "decision" || i.kind === "function");
8895
10304
  const failures = [...new Set(reading.items.filter((i) => i.kind === "error").map((i) => i.name))];
8896
10305
  const counts = { actions: 0, rules: 0, functions: 0, notReadYet: 0, failures: failures.length };
@@ -8931,7 +10340,7 @@ function thunderizeFiles(files, { name = "app" } = {}) {
8931
10340
  continue;
8932
10341
  }
8933
10342
  try {
8934
- out.push(thunderizeFile(f.path, f.source, language));
10343
+ out.push(thunderizeFile(f.path, f.source, language, readingOf(f, language)));
8935
10344
  } catch (e) {
8936
10345
  skipped.push({ path: f.path, reason: `could not be read: ${e.message}` });
8937
10346
  }
@@ -8984,7 +10393,7 @@ function readAll(files) {
8984
10393
  if (!language || !f.source) continue;
8985
10394
  let reading;
8986
10395
  try {
8987
- reading = readCode(f.source, { language, file: f.path });
10396
+ reading = readingOf(f, language);
8988
10397
  } catch (e) {
8989
10398
  unreadable.push({ path: f.path, reason: e.message });
8990
10399
  continue;
@@ -11044,7 +12453,7 @@ var GUARD_SCHEMA = "intent-guard-v1";
11044
12453
  var SECRET_TYPES2 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jwt", "token", "apikey", "api_key", "privatekey", "private_key", "credential", "cvv"]);
11045
12454
  var SENSITIVE_NAME = /^(.*[._-])?(pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card(number)?|cvc)([._-].*)?$/i;
11046
12455
  var DENY_RE = /^(deny|denied|block|blocked|refuse|refused|reject|rejected|forbid|forbidden|escalate|escalated|review|needsreview|no)$/i;
11047
- function buildGuard(ast, { denyResults, mask = "[redacted]" } = {}) {
12456
+ function buildGuard(ast, { denyResults, mask: mask2 = "[redacted]" } = {}) {
11048
12457
  const secretFields = /* @__PURE__ */ new Set();
11049
12458
  const consider = (f) => {
11050
12459
  if (!f || !f.name) return;
@@ -11071,7 +12480,7 @@ function buildGuard(ast, { denyResults, mask = "[redacted]" } = {}) {
11071
12480
  if (seen.has(value)) return value;
11072
12481
  seen.add(value);
11073
12482
  const out = {};
11074
- for (const [k, v] of Object.entries(value)) out[k] = isSecretKey(k) ? mask : redact(v, seen, depth + 1);
12483
+ for (const [k, v] of Object.entries(value)) out[k] = isSecretKey(k) ? mask2 : redact(v, seen, depth + 1);
11075
12484
  return out;
11076
12485
  }
11077
12486
  return value;
@@ -11117,9 +12526,9 @@ var SECRET_TYPES3 = /* @__PURE__ */ new Set(["secret", "password", "passwd", "jw
11117
12526
  var SECRET_NAME = /pass(word|wd)?|secret|token|jwt|ssn|api[-_]?key|apikey|credential|cvv|private[-_]?key|card/i;
11118
12527
  var isSecretField = (f) => f && (SECRET_TYPES3.has(String(f.type || "").toLowerCase()) || SECRET_NAME.test(f.name || ""));
11119
12528
  function pascalish(text) {
11120
- const words6 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
11121
- if (words6.length === 1) return words6[0].charAt(0).toUpperCase() + words6[0].slice(1);
11122
- return words6.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
12529
+ const words7 = String(text || "Mission").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/);
12530
+ if (words7.length === 1) return words7[0].charAt(0).toUpperCase() + words7[0].slice(1);
12531
+ return words7.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
11123
12532
  }
11124
12533
  var normRules = (list) => (Array.isArray(list) ? list : []).map((r) => typeof r === "string" ? { statement: r } : { ...r }).filter((r) => r.statement);
11125
12534
  function draftIntent(brief = {}) {
@@ -12960,9 +14369,11 @@ function translateDecisions(ast, lang) {
12960
14369
  promoteDecision,
12961
14370
  proposeIntent,
12962
14371
  readCode,
14372
+ readFiles,
12963
14373
  readLevel,
12964
14374
  readRepo,
12965
14375
  readableLanguage,
14376
+ readingOf,
12966
14377
  renderExampleTable,
12967
14378
  renderHumanContract,
12968
14379
  renderLensDoc,