@skillstech/thunderlang 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +10 -3
  3. package/dist/core.cjs +234 -20
  4. package/dist/index.cjs +8853 -1045
  5. package/dist/learn.cjs +1339 -69
  6. package/package.json +1 -1
  7. package/src/cli-main.mjs +312 -115
  8. package/src/core/check.mjs +312 -6
  9. package/src/core/cli.mjs +60 -8
  10. package/src/core/csharp-run.mjs +2 -2
  11. package/src/core/diagnostics.mjs +9 -0
  12. package/src/core/engine-core.mjs +141 -19
  13. package/src/core/engine-values.mjs +1 -0
  14. package/src/core/engine.mjs +131 -7
  15. package/src/core/go-run.mjs +2 -2
  16. package/src/core/index.mjs +6 -2
  17. package/src/core/java-run.mjs +2 -2
  18. package/src/core/kind.mjs +3 -0
  19. package/src/core/lexer.mjs +16 -2
  20. package/src/core/parser.mjs +200 -15
  21. package/src/core/project-root.mjs +18 -0
  22. package/src/core/project.mjs +15 -18
  23. package/src/core/react-run.mjs +2 -2
  24. package/src/core/runtime-go/thunder_runtime.go +269 -1
  25. package/src/core/runtime-python.mjs +365 -3
  26. package/src/core/runtime-typescript.mjs +150 -5
  27. package/src/core/rust-run.mjs +2 -2
  28. package/src/core/serving.mjs +12 -0
  29. package/src/core/store-format.mjs +110 -0
  30. package/src/core/target-go.mjs +10 -3
  31. package/src/core/target-python.mjs +38 -5
  32. package/src/core/target-typescript.mjs +62 -6
  33. package/src/core/typescript-run.mjs +6 -4
  34. package/src/core-changes-fs.mjs +28 -0
  35. package/src/core-changes.d.mts +67 -0
  36. package/src/core-changes.mjs +603 -0
  37. package/src/core-rules.mjs +146 -0
  38. package/src/core-services.d.mts +4 -0
  39. package/src/core-services.mjs +49 -0
  40. package/src/emit.mjs +1 -1
  41. package/src/evidence.mjs +28 -0
  42. package/src/examples.d.mts +21 -0
  43. package/src/examples.mjs +175 -0
  44. package/src/index.d.ts +4 -0
  45. package/src/index.mjs +4 -0
  46. package/src/mcp.mjs +42 -3
  47. package/src/program.d.mts +4 -0
  48. package/src/program.mjs +4 -0
  49. package/src/read-repo-fs.mjs +2 -1
  50. package/src/review.mjs +69 -3
  51. package/src/system.mjs +1 -1
  52. package/src/trace-cli.mjs +8 -3
  53. package/src/trace-fs.mjs +29 -3
  54. package/src/trace.mjs +23 -7
@@ -12,12 +12,19 @@ const VALUES_SOURCE = readFileSync(new URL('./engine-values.mjs', import.meta.ur
12
12
  // npm packages (Use "<package>" from npm): the boundary between Thunder values and JavaScript values. Its import
13
13
  // line is dropped: in thunder_runtime.mjs the names it uses are the runtime's own.
14
14
  const NPM_SOURCE = readFileSync(new URL('./runtime-npm.mjs', import.meta.url), 'utf8').replace(/^import [^\n]*\n/m, '');
15
+ // Stored lists (Store habits as a list of Habit): the file format the Thunder engine and Python use, byte for byte,
16
+ // so the three read and write the same data/<name>.json. Its import and re-export lines are dropped (the runtime has
17
+ // those names already).
18
+ const STORE_SOURCE = readFileSync(new URL('./store-format.mjs', import.meta.url), 'utf8')
19
+ .replace(/^import [^\n]*\n/m, '').replace(/^export \{ RecordVal \};\n/m, '');
15
20
 
16
21
  /** The Node part: everything here is about running, not about what a value means. */
17
22
  const NODE_PART = `
18
23
  // ── Running compiled TypeScript: frames (for error lines), output, files, and the program or its tests ───────────
19
- import { readFileSync as nodeReadFile, realpathSync as nodeRealpath } from 'node:fs';
20
- import { resolve as nodeResolve } from 'node:path';
24
+ import { readFileSync as nodeReadFile, realpathSync as nodeRealpath, writeFileSync as nodeWriteFile, mkdirSync as nodeMkdir, renameSync as nodeRename } from 'node:fs';
25
+ import { resolve as nodeResolve, dirname as nodeDirname } from 'node:path';
26
+ import { spawnSync as nodeSpawnSync } from 'node:child_process';
27
+ import { createServer as nodeCreateServer } from 'node:http';
21
28
 
22
29
  const frames = [];
23
30
  let aborted = false;
@@ -80,7 +87,145 @@ export function isEntry(url) {
80
87
  const strip = (p) => real(p).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');
81
88
  return strip(decodeURIComponent(new URL(url).pathname)) === strip(nodeResolve(arg));
82
89
  }
83
- export function run(main) { if (aborted) return; try { main(); } catch (e) { report(e); } }
90
+ /** Stored lists: empty until the program runs (run fills them from data/<name>.json), saved when it finishes well. */
91
+ const STORES = [];
92
+ export function newStore(file, line, name, cls, fields) { const items = []; STORES.push({ file, line, name, cls, kinds: { fields }, items }); return items; }
93
+ function fillStores() {
94
+ for (const st of STORES) {
95
+ const path = \`data/\${st.name}.json\`;
96
+ let text;
97
+ try { text = nodeReadFile(nodeResolve(process.cwd(), path), 'utf8'); } catch (e) { if (e.code === 'ENOENT') continue; throw e; }
98
+ withFrame({ file: st.file, line: st.line }, () => { st.items.splice(0, st.items.length, ...storeFromText(text, st.kinds, path, (given) => newRecordWith(setAttr, st.cls, given))); });
99
+ }
100
+ }
101
+ /** A save writes a new file next to the old one, then renames it, so a file is never left half written. */
102
+ function saveStores() {
103
+ for (const st of STORES) {
104
+ const path = nodeResolve(process.cwd(), \`data/\${st.name}.json\`);
105
+ nodeMkdir(nodeDirname(path), { recursive: true });
106
+ nodeWriteFile(\`\${path}.saving\`, storeToText(st.items, st.kinds));
107
+ nodeRename(\`\${path}.saving\`, path);
108
+ }
109
+ }
110
+ // ── HTTP (When someone calls GET /habits: and the answer from GET "…"): data in the stored-list format ──────────
111
+ let answeredStatus = null;
112
+ /** Give … with status 201: the status this request answers with (a direct call in a test ignores it). */
113
+ export function answerStatus(status) { answeredStatus = status; }
114
+ /** Stop with "…" and status 404: a Stop that an endpoint answers with that status. */
115
+ export function stopWith(message, status) { const e = Stop(message); e.status = status; return e; }
116
+
117
+ // A call to another service waits for its answer, as every step of a Thunder program does: Node's fetch runs in a
118
+ // child process and the program reads what it printed.
119
+ const FETCH = "let d='';process.stdin.on('data',(c)=>d+=c).on('end',async()=>{const q=JSON.parse(d);try{const r=await fetch(q.url,{method:q.method,headers:q.body==null?{accept:'application/json'}:{accept:'application/json','content-type':'application/json'},body:q.body??undefined,signal:AbortSignal.timeout(30000)});process.stdout.write(JSON.stringify({status:r.status,text:await r.text()}))}catch(e){process.stdout.write(JSON.stringify({error:String(e.cause?.code??e.cause?.message??e.message),name:e.name}))}})";
120
+ /** the answer from GET "…": the answer's text, or records read from it (as = { cls, fields, many }). */
121
+ export function httpCall(method, url, body, as) {
122
+ const where = \`The answer from \${method} \${url}\`;
123
+ const r = nodeSpawnSync(process.execPath, ['-e', FETCH], { input: JSON.stringify({ method, url, body: body === null || body === undefined ? null : dataJson(body) }), encoding: 'utf8' });
124
+ let out;
125
+ try { out = JSON.parse(r.stdout); } catch { throw CallFailed(\`\${method} \${url} could not be reached.\`); }
126
+ if (out.error) throw CallFailed(\`\${method} \${url} could not be reached (\${unreachableReason(out)}).\`);
127
+ if (out.status < 200 || out.status > 299) throw CallFailed(\`\${method} \${url} answered \${out.status}: \${out.text.trim().slice(0, 300)}\`);
128
+ if (!as) return out.text;
129
+ let data;
130
+ try { data = JSON.parse(out.text); } catch { throw ConversionFailed(\`\${where} is not JSON Thunder can read.\`); }
131
+ const kind = { fields: as.fields };
132
+ const make = (given) => newRecordWith(setAttr, as.cls, given);
133
+ if (as.many) {
134
+ if (!Array.isArray(data)) throw ConversionFailed(\`\${where} should be a list, written [ … ].\`);
135
+ return data.map((row, i) => recordFrom(row, kind, \`\${where}, item \${i + 1}\`, make, 'it has'));
136
+ }
137
+ return recordFrom(data, kind, where, make, 'it has');
138
+ }
139
+
140
+ const kindName = { whole: 'a whole number', number: 'a number', money: 'money', text: 'text', bool: 'yes or no', date: 'a date' };
141
+ /** Answer requests on this machine, one at a time, until stopped (Ctrl+C). Stored lists are saved after each request that finishes well. */
142
+ function serve(routes) {
143
+ const host = process.env.THUNDER_HOST || '127.0.0.1';
144
+ const port = Number(process.env.THUNDER_PORT || 8080);
145
+ const table = routes.map((r) => ({ ...r, parts: r.path.split('/').filter(Boolean) }));
146
+ const match = (parts, got) => {
147
+ if (parts.length !== got.length) return null;
148
+ const found = {};
149
+ for (let i = 0; i < parts.length; i++) {
150
+ const m = parts[i].match(/^\\{(.+)\\}$/);
151
+ if (m) found[m[1].trim().toLowerCase()] = decodeURIComponent(got[i]);
152
+ else if (parts[i] !== got[i]) return null;
153
+ }
154
+ return found;
155
+ };
156
+ const server = nodeCreateServer((req, res) => {
157
+ const chunks = [];
158
+ req.on('data', (c) => chunks.push(c));
159
+ req.on('end', () => {
160
+ const send = (status, value) => {
161
+ // A problem the server words itself is plain JSON; a value the program gave is written by its kind.
162
+ let data;
163
+ if (value && value.problem !== undefined && Object.getPrototypeOf(value) === Object.prototype) data = JSON.stringify(value);
164
+ else { try { data = dataJson(value); } catch (e) { status = 500; data = JSON.stringify({ problem: explain(asPyErr(e)) }); } }
165
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(data) });
166
+ res.end(data);
167
+ process.stdout.write(\`\${req.method} \${req.url} -> \${status}\n\`);
168
+ };
169
+ const url = new URL(req.url, 'http://localhost');
170
+ const got = url.pathname.split('/').filter(Boolean);
171
+ const query = Object.fromEntries(url.searchParams);
172
+ let chosen = null;
173
+ const methods = [];
174
+ for (const r of table) {
175
+ const found = match(r.parts, got);
176
+ if (!found) continue;
177
+ methods.push(r.method);
178
+ if (r.method === req.method) chosen = { r, found };
179
+ }
180
+ if (!chosen) {
181
+ if (methods.length) return send(405, { problem: \`\${url.pathname} answers only \${methods.join(', ')}.\` });
182
+ return send(404, { problem: \`Nothing here answers \${req.method} \${url.pathname}.\` });
183
+ }
184
+ const { r, found } = chosen;
185
+ let body = {};
186
+ const raw = Buffer.concat(chunks).toString('utf8');
187
+ if (raw) {
188
+ try { body = JSON.parse(raw); } catch { return send(400, { problem: "The request's body is not JSON Thunder can read." }); }
189
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return send(400, { problem: "The request's body should be a JSON object, written { … }." });
190
+ }
191
+ const args = [];
192
+ try {
193
+ for (const inp of r.inputs) {
194
+ const key = inp.text.toLowerCase();
195
+ const where = \`"\${inp.text}"\`;
196
+ if (inp.path) args.push(inputValue(found[key], inp.type, where, true));
197
+ else if (key in query || (inp.py && inp.py in query)) args.push(inputValue(key in query ? query[key] : query[inp.py], inp.type, where, true));
198
+ else if (inp.text in body || key in body || (inp.py && inp.py in body)) args.push(inputValue(inp.text in body ? body[inp.text] : key in body ? body[key] : body[inp.py], inp.type, where, false));
199
+ else if (inp.dflt) args.push(undefined); // its default applies
200
+ else if (inp.type.k === 'optional') args.push(null);
201
+ else return send(400, { problem: \`\${r.method} \${r.path} needs \${inp.text} (\${kindName[inp.type.k] ?? inp.type.k}).\` });
202
+ }
203
+ } catch (e) { return send(400, { problem: explain(asPyErr(e)) }); }
204
+ answeredStatus = null;
205
+ let value;
206
+ try { value = r.handler(...args); } catch (e0) {
207
+ const e = asPyErr(e0);
208
+ if (e.pyType === 'Stop') return send(e.status ?? 400, { problem: explain(e) });
209
+ if (e.pyType === 'RuleBroken') return send(422, { problem: explain(e) });
210
+ process.stderr.write(\`\${describeError(e)}\n\`);
211
+ return send(500, { problem: explain(e) });
212
+ }
213
+ try { saveStores(); dataJson(value); } catch (e0) { const e = asPyErr(e0); process.stderr.write(\`\${describeError(e)}\n\`); return send(500, { problem: explain(e) }); }
214
+ return send(answeredStatus ?? 200, value);
215
+ });
216
+ });
217
+ server.listen(port, host, () => {
218
+ process.stdout.write(\`Thunder is answering on http://\${host}:\${port}\n\${routes.map((r) => \` \${r.method} \${r.path}\n\`).join('')}Press Ctrl+C to stop.\n\`);
219
+ });
220
+ process.on('SIGINT', () => { process.stdout.write('Stopped answering.\\n'); server.close(); process.exit(0); });
221
+ }
222
+
223
+ /** Run the program: stored lists are filled first and saved only when it finishes well; with endpoints, then answer requests. */
224
+ export function run(main, routes) {
225
+ if (aborted) return;
226
+ try { fillStores(); main(); saveStores(); } catch (e) { report(e); return; }
227
+ if (routes && routes.length) serve(routes);
228
+ }
84
229
  /** Every Test block, the way run_tests.py runs them: one line per test, then the totals. */
85
230
  export function runTests(modules) {
86
231
  if (aborted) return;
@@ -97,14 +242,14 @@ export function runTests(modules) {
97
242
  }
98
243
  `;
99
244
 
100
- const NODE_EXPORTS = { functions: ['enterFrame', 'enterCall', 'leave', 'topFrame', 'fail', 'keyAt', 'say', 'readText', 'recordKind', 'setAttr', 'setField', 'newRecord', 'init', 'isEntry', 'run', 'runTests', 'toJs', 'fromJs', 'library', 'callLibrary', 'getLibrary'] };
245
+ const NODE_EXPORTS = { functions: ['enterFrame', 'enterCall', 'leave', 'topFrame', 'fail', 'keyAt', 'say', 'readText', 'recordKind', 'setAttr', 'setField', 'newRecord', 'init', 'isEntry', 'run', 'runTests', 'newStore', 'answerStatus', 'stopWith', 'httpCall', 'toJs', 'fromJs', 'library', 'callLibrary', 'getLibrary'] };
101
246
 
102
247
  const HEADER = `// thunder_runtime.mjs: written by the Thunder compiler next to compiled TypeScript. Standard library only.
103
248
  // The values and rules here are the Thunder engine's own (engine-values.mjs), so compiled TypeScript, the Thunder
104
249
  // engine, and compiled Python say the same thing for the same program.
105
250
  `;
106
251
 
107
- export const TS_RUNTIME = `${HEADER}\n${VALUES_SOURCE.trimEnd()}\n${NODE_PART}\n${NPM_SOURCE}`;
252
+ export const TS_RUNTIME = `${HEADER}\n${VALUES_SOURCE.trimEnd()}\n${STORE_SOURCE.trimEnd()}\n${NODE_PART}\n${NPM_SOURCE}`;
108
253
 
109
254
  const isClass = (v) => typeof v === 'function' && /^class\b/.test(Function.prototype.toString.call(v));
110
255
 
@@ -10,7 +10,7 @@ import { createHash } from 'node:crypto';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { toRust, pythonOnlyUses, exportedRustNames, rs } from './target-rust.mjs';
13
- import { npmRefusals, dotnetRefusals } from './target-typescript.mjs';
13
+ import { npmRefusals, dotnetRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
14
14
  import { diag } from './diagnostics.mjs';
15
15
 
16
16
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -22,7 +22,7 @@ export const rustModule = (m) => `m_${m}`;
22
22
 
23
23
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
24
24
  export function rustDiagnostics(result) {
25
- return [...npmRefusals(result.info, 'Rust', diag), ...dotnetRefusals(result.info, 'Rust', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
25
+ return [...npmRefusals(result.info, 'Rust', diag), ...dotnetRefusals(result.info, 'Rust', diag), ...storeRefusals(result.info, 'Rust', diag), ...httpRefusals(result.info, 'Rust', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
26
26
  `"${u.module}" is a Python module, and this program is compiled to Rust, which cannot use it.`,
27
27
  'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
28
28
  }
@@ -0,0 +1,12 @@
1
+ // A program that answers requests (When someone calls …) runs until it is stopped. The thunder command starts it
2
+ // without waiting, and passes Ctrl+C or a stop signal on to it, so stopping thunder always stops the server too
3
+ // (a terminal sends Ctrl+C to both; a test, a process manager, or a container stops only thunder).
4
+ import { spawn } from 'node:child_process';
5
+
6
+ export function spawnServing(cmd, args, opts = {}) {
7
+ const child = spawn(cmd, args, { ...opts, stdio: 'inherit' });
8
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => { if (child.exitCode === null) child.kill(sig); });
9
+ child.on('exit', (code, signal) => { process.exitCode = code ?? (signal === 'SIGINT' || signal === 'SIGTERM' ? 0 : 1); });
10
+ child.on('error', (e) => { process.stderr.write(`thunder run: ${e.message}\n`); process.exitCode = 2; });
11
+ return { status: 0, serving: true };
12
+ }
@@ -0,0 +1,110 @@
1
+ // The file a stored list is saved in (Store habits as a list of Habit -> data/habits.json): a JSON list of objects,
2
+ // one per record, each field written by its kind so the file says exactly what the value is:
3
+ // whole number -> a JSON integer (text when too large for one) number -> text ("2.5", exact)
4
+ // money -> text ("1.50", the amount, exact) text -> text yes/no -> true/false date -> "2026-11-27"
5
+ // or nothing -> null
6
+ // The same format on every target (the Thunder engine here; runtime-python's load/save mirror it), so a program's
7
+ // data means the same whichever language runs it. Browser-safe: reading and writing the file is the caller's job.
8
+
9
+ import { Dec, Money, PyDate, RecordVal, PyDict, Tuple, ConversionFailed, KindMismatch, show } from './engine-values.mjs';
10
+
11
+ const kindWords = { whole: 'a whole number', number: 'a number', money: 'money', text: 'text', bool: 'yes or no', date: 'a date' };
12
+
13
+ function encode(v, t) {
14
+ if (t.k === 'optional') return v === null || v === undefined ? null : encode(v, t.of);
15
+ if (v === null || v === undefined) return null;
16
+ switch (t.k) {
17
+ case 'whole': return typeof v === 'bigint' && v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
18
+ case 'number': return String(v);
19
+ case 'money': return v instanceof Money ? v.toString().replace('$', '') : String(v);
20
+ case 'date': return v instanceof PyDate ? v.iso() : String(v);
21
+ default: return v;
22
+ }
23
+ }
24
+
25
+ function decode(x, t, where, has = 'the file has') {
26
+ if (t.k === 'optional') return x === null ? null : decode(x, t.of, where, has);
27
+ const bad = () => ConversionFailed(`${where} should be ${kindWords[t.k] ?? 'a value'}, but ${has} ${JSON.stringify(x)}.`);
28
+ switch (t.k) {
29
+ case 'whole': if (typeof x === 'number' && Number.isInteger(x)) return BigInt(x); if (typeof x === 'string' && /^-?\d+$/.test(x)) return BigInt(x); throw bad();
30
+ case 'number': { if (typeof x === 'number' && Number.isInteger(x)) return BigInt(x); const d = typeof x === 'string' ? Dec.parse(x) : null; if (!d) throw bad(); return /^-?\d+$/.test(x) ? BigInt(x) : d; }
31
+ case 'money': { const d = typeof x === 'string' ? Dec.parse(x) : typeof x === 'number' ? Dec.parse(String(x)) : null; if (!d) throw bad(); return new Money(d); }
32
+ case 'text': if (typeof x === 'string') return x; throw bad();
33
+ case 'bool': if (typeof x === 'boolean') return x; throw bad();
34
+ case 'date': { const d = typeof x === 'string' ? PyDate.parse(x) : null; if (!d) throw bad(); return d; }
35
+ default: return x;
36
+ }
37
+ }
38
+
39
+ /** A stored list as the text of its file. `cls` is the record kind (its fields carry their kinds). */
40
+ export function storeToText(list, cls) {
41
+ const rows = list.map((rec) => Object.fromEntries(cls.fields.map((f) => [f.py, encode(rec.f.get(f.py), f.type ?? { k: 'text' })])));
42
+ return `${JSON.stringify(rows, null, 2)}\n`;
43
+ }
44
+
45
+ /**
46
+ * The records in a store's file. `name` is the file's name as a person sees it (data/habits.json); `make(given)`
47
+ * builds a record from a Map of field values (so the record's Never rules are checked, as in the program).
48
+ */
49
+ export function storeFromText(text, cls, name, make) {
50
+ let rows;
51
+ try { rows = JSON.parse(text); } catch (e) { throw ConversionFailed(`${name} is not a list Thunder can read (${e.message}).`); }
52
+ if (!Array.isArray(rows)) throw ConversionFailed(`${name} should hold a list, written [ … ].`);
53
+ return rows.map((row, i) => recordFrom(row, cls, `${name}, item ${i + 1}`, make));
54
+ }
55
+
56
+ /** A record from a JSON object, each field read by its kind; a problem says where it is and which field. */
57
+ export function recordFrom(row, cls, where, make, has = 'the file has') {
58
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw ConversionFailed(`${where} should be a record, written { … }.`);
59
+ const given = new Map();
60
+ for (const f of cls.fields) {
61
+ const t = f.type ?? { k: 'text' };
62
+ if (!(f.py in row)) { if (t.k === 'optional') { given.set(f.py, null); continue; } throw ConversionFailed(`${where} has no "${f.py}".`); }
63
+ given.set(f.py, decode(row[f.py], t, `${where}, "${f.py}"`, has));
64
+ }
65
+ return make(given);
66
+ }
67
+
68
+ /** A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false. */
69
+ export function inputValue(raw, t, where, fromText) {
70
+ const plain = t.k === 'optional' ? t.of : t;
71
+ if (fromText && plain.k === 'bool' && typeof raw === 'string' && /^(yes|no|true|false)$/i.test(raw)) raw = /^(yes|true)$/i.test(raw);
72
+ return decode(raw, t, where, 'the request has');
73
+ }
74
+
75
+ /**
76
+ * A value as JSON data (HTTP answers and requests), written by its kind as in a stored list: whole numbers as
77
+ * numbers (text when too large), numbers and money as exact text, dates as "2026-11-28", records as objects.
78
+ */
79
+ export function dataReady(v) {
80
+ if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'string') return v ?? null;
81
+ if (typeof v === 'bigint') return v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
82
+ if (v instanceof Dec) return String(v);
83
+ if (v instanceof Money) return v.toString().replace('$', '');
84
+ if (v instanceof PyDate) return v.iso();
85
+ if (Array.isArray(v)) return v.map(dataReady);
86
+ if (v instanceof Tuple) return v.items.map(dataReady);
87
+ if (v instanceof PyDict) {
88
+ const out = {};
89
+ for (const [k, x] of v.m.values()) { if (typeof k !== 'string') throw KindMismatch(`A JSON object's keys are text, but one is ${show(k)}.`); out[k] = dataReady(x); }
90
+ return out;
91
+ }
92
+ if (v instanceof RecordVal) {
93
+ // An alternative of a data type: "which" and the fields it has, not the other alternatives' fields.
94
+ const keep = v.cls.alts ? ['which', ...(v.cls.alts[v.f.get('which')] ?? [])] : v.cls.fields.map((f) => f.py);
95
+ return Object.fromEntries(keep.map((py) => [py, dataReady(v.f.get(py))]));
96
+ }
97
+ throw KindMismatch(`${show(v)} can't be sent as JSON.`);
98
+ }
99
+ export const dataJson = (v) => JSON.stringify(dataReady(v));
100
+
101
+ /** Why a service could not be reached, in words that are the same on every target ({ error: code, name } from fetch). */
102
+ export function unreachableReason(out) {
103
+ if (out.name === 'TimeoutError' || out.name === 'AbortError') return 'no answer within 30 seconds';
104
+ if (out.error === 'ECONNREFUSED') return 'nothing is answering there';
105
+ if (out.error === 'ENOTFOUND' || out.error === 'EAI_AGAIN') return 'the address could not be found';
106
+ return out.error;
107
+ }
108
+
109
+ export const storeFile = (s) => `data/${s.py.toLowerCase()}.json`;
110
+ export { RecordVal };
@@ -90,6 +90,13 @@ class Gen {
90
90
  this.emit('}');
91
91
  }
92
92
  for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
93
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime Run).
94
+ const stores = (this.info.stores ?? []).filter(own);
95
+ if (stores.length) {
96
+ this.blank();
97
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
98
+ for (const s of stores) this.emit(`var ${this.g(s.py)} = T.NewStore(${this.file}, ${s.line}, ${goStr(s.py.toLowerCase())}, ${this.g(s.record.py)}, []T.StoreField{${s.record.fields.map((f) => `{Py: ${goStr(f.py)}, Kind: ${goStr(kind(f.type))}}`).join(', ')}})`, s.line);
99
+ }
93
100
  const consts = this.info.consts.filter(own);
94
101
  this.blank();
95
102
  for (const k of consts) this.emit(`var ${this.g(k.py)} T.V`, k.line);
@@ -201,7 +208,7 @@ class Gen {
201
208
  }
202
209
  };
203
210
  visit(body);
204
- const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
211
+ const globals = new Set([...this.info.consts, ...(this.info.stores ?? []), ...this.info.funcs, ...this.info.records].map((x) => x.py));
205
212
  return [...names].filter((n) => !globals.has(n));
206
213
  }
207
214
 
@@ -536,14 +543,14 @@ const own = (r) => (s) => !r.info.imported?.has(s);
536
543
  */
537
544
  export function goNamespaces(results) {
538
545
  const defs = new Map();
539
- for (const r of results) for (const s of [...r.info.records, ...r.info.funcs, ...r.info.consts].filter(own(r))) (defs.get(s.py) ?? defs.set(s.py, []).get(s.py)).push(r.module);
546
+ for (const r of results) for (const s of [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.stores ?? [])].filter(own(r))) (defs.get(s.py) ?? defs.set(s.py, []).get(s.py)).push(r.module);
540
547
  const goName = (module, py) => ((defs.get(py)?.length ?? 0) > 1 ? `${module}_${py}` : id(py));
541
548
  const out = new Map();
542
549
  for (const r of results) {
543
550
  const visible = new Map();
544
551
  const funcs = new Map();
545
552
  const take = (x) => {
546
- for (const s of [...x.info.records, ...x.info.funcs, ...x.info.consts].filter(own(x))) visible.set(s.py, goName(x.module, s.py));
553
+ for (const s of [...x.info.records, ...x.info.funcs, ...x.info.consts, ...(x.info.stores ?? [])].filter(own(x))) visible.set(s.py, goName(x.module, s.py));
547
554
  for (const f of x.info.funcs.filter(own(x))) funcs.set(f.py, f.params.length);
548
555
  };
549
556
  // A test file sees every src file's names (as the Python target's `from <module> import *`), later ones winning.
@@ -61,6 +61,13 @@ class Gen {
61
61
  for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
62
62
  const consts = this.info.consts.filter(own);
63
63
  if (consts.length) { this.blank(); for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line); }
64
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime run()).
65
+ const stores = (this.info.stores ?? []).filter(own);
66
+ if (stores.length) {
67
+ this.blank();
68
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
69
+ for (const s of stores) this.emit(`${s.py} = ${this.R('new_store')}(THUNDER_SOURCE, ${s.line}, ${py(s.py.toLowerCase())}, ${s.record.py}, {${s.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(', ')}})`, s.line);
70
+ }
64
71
  const tests = this.info.tests;
65
72
  for (const t of tests) {
66
73
  this.blank();
@@ -73,14 +80,27 @@ class Gen {
73
80
  for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
74
81
  this.emit(']');
75
82
  }
83
+ // Endpoints (When someone calls …): the routes the server answers, each with its inputs (name, kind, where from).
84
+ const endpoints = (this.info.endpoints ?? []).filter(own);
85
+ if (endpoints.length) {
86
+ this.blank();
87
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
88
+ this.emit('THUNDER_ROUTES = [');
89
+ for (const f of endpoints) {
90
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
91
+ const ins = f.params.map((p) => `(${py(p.text)}, ${py(p.py)}, ${py(kind(p.type))}, ${fromPath.has(p.name) ? '"path"' : '"request"'}, ${p.dflt ? 'True' : 'False'})`);
92
+ this.emit(` (${py(f.endpoint.method)}, ${py(f.endpoint.path)}, ${f.py}, [${ins.join(', ')}]),`, f.line);
93
+ }
94
+ this.emit(']');
95
+ }
76
96
  const main = this.p.main ?? [];
77
97
  this.blank();
78
- if (main.length) {
98
+ if (main.length || endpoints.length) {
79
99
  this.emit('def main():');
80
- this.ind++; this.block(main); this.ind--;
100
+ this.ind++; if (main.length) this.block(main); else this.emit('pass'); this.ind--;
81
101
  this.blank();
82
102
  this.emit('if __name__ == "__main__":');
83
- this.emit(` ${this.R('run')}(main, __file__)`);
103
+ this.emit(` ${this.R('run')}(main, __file__${endpoints.length ? ', routes=THUNDER_ROUTES' : ''})`);
84
104
  }
85
105
  body.push(...this.out);
86
106
 
@@ -115,6 +135,8 @@ class Gen {
115
135
  this.emit(`${f.py}: ${t}${dflt}`, f.line);
116
136
  }
117
137
  if (!r.fields.length) this.emit('pass');
138
+ // A data type with alternatives: each alternative's own fields, so JSON carries only the fields it has.
139
+ if (r.alts) this.emit(`__thunder_alts__ = {${r.alts.map((a) => `${py(a.name)}: (${a.fields.map((f) => `${py(f.py)}, `).join('')})`).join(', ')}}`, r.line);
118
140
  const rules = r.rulesToCheck ?? [];
119
141
  if (rules.length) {
120
142
  this.out.push('');
@@ -205,8 +227,13 @@ class Gen {
205
227
  this.store(t, v, L);
206
228
  return;
207
229
  }
208
- case 'give': this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
209
- case 'stop': this.emit(`raise ${this.R('Stop')}(${s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`})`, L); return;
230
+ case 'give':
231
+ if (s.status != null) this.emit(`${this.R('answer_status')}(${s.status})`, L);
232
+ this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
233
+ case 'stop': {
234
+ const msg = s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`;
235
+ this.emit(s.status != null ? `raise ${this.R('stop_with')}(${msg}, ${s.status})` : `raise ${this.R('Stop')}(${msg})`, L); return;
236
+ }
210
237
  case 'if':
211
238
  s.branches.forEach((b, k) => {
212
239
  this.emit(`${k === 0 ? 'if' : 'elif'} ${this.yn(b.cond).c}:`, b.line);
@@ -357,6 +384,12 @@ class Gen {
357
384
  case 'bool': return A(e.v ? 'True' : 'False');
358
385
  case 'nothing': return A('None');
359
386
  case 'paren': return sub(e.e);
387
+ // the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
388
+ case 'httpCall': {
389
+ const kind = (t) => (t.k === 'optional' ? `?${kind(t.of)}` : t.k);
390
+ const as = e.record ? `(${e.record.py}, {${e.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(', ')}}, ${e.as.k === 'list' ? 'True' : 'False'})` : 'None';
391
+ return A(`${this.R('http_call')}(${py(e.method)}, ${sub(e.url).c}, ${e.body ? sub(e.body).c : 'None'}, ${as})`);
392
+ }
360
393
  case 'today': this.needDate = true; return A('date.today()');
361
394
  case 'date': this.needDate = true; return A(`date.fromisoformat(${py(e.text)})`);
362
395
  case 'str': return A(this.str(e, ctx));
@@ -75,6 +75,24 @@ export function dotnetRefusals(info, targetName, diag) {
75
75
  'Build for C# to use .NET libraries: --target csharp, or target = "csharp" under [build] in thunder.toml. Thunder never swaps in a different library.'));
76
76
  }
77
77
 
78
+ /** TC411 for endpoints and calls to other services: HTTP runs on Python, TypeScript, and the Thunder engine for now. */
79
+ export function httpRefusals(info, targetName, diag) {
80
+ const own = (s) => !info.imported?.has(s);
81
+ const out = (info.endpoints ?? []).filter(own).map((f) => diag('TC411', f.line,
82
+ `"${f.text}" is an endpoint, and HTTP works only on Python, TypeScript, and the Thunder engine for now, not on ${targetName}.`,
83
+ 'Run it with Python (the default target), --target typescript, or --engine thunder.'));
84
+ if (info.usesHttp && !out.length) out.push(diag('TC411', 1, `This program calls another service ("the answer from …"), and HTTP works only on Python, TypeScript, and the Thunder engine for now, not on ${targetName}.`,
85
+ 'Run it with Python (the default target), --target typescript, or --engine thunder.'));
86
+ return out;
87
+ }
88
+
89
+ /** TC410 for every stored list (Store … as a list of …) when compiling for `target`: saved data runs on Python, TypeScript, Go, and the Thunder engine for now. */
90
+ export function storeRefusals(info, targetName, diag) {
91
+ return (info.stores ?? []).filter((s) => !info.imported?.has(s)).map((s) => diag('TC410', s.line,
92
+ `"${s.text}" is a stored list, and saved data works only on Python, TypeScript, Go, and the Thunder engine for now, not on ${targetName}.`,
93
+ 'Run it with Python (the default target), --target typescript, --target go, or --engine thunder. Thunder never swaps in a different way of saving.'));
94
+ }
95
+
78
96
  /** The name of an npm package's namespace import (import * as <it> from "<package>"). */
79
97
  const npmNs = (m) => `$npm_${m.py}`;
80
98
 
@@ -114,6 +132,13 @@ export class Gen {
114
132
  this.ind--;
115
133
  this.emit('});');
116
134
  }
135
+ // Stored lists: filled from data/<name>.json when the program runs, saved when it finishes well (runtime run()).
136
+ const stores = (this.info.stores ?? []).filter(own);
137
+ if (stores.length) {
138
+ this.blank();
139
+ const kind = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${kind(t.of)} }` : `{ k: ${js(t.k)} }`);
140
+ for (const s of stores) this.emit(`export const ${id(s.py)}: any = T.newStore(FILE, ${s.line}, ${js(s.py.toLowerCase())}, ${id(s.record.py)}, [${s.record.fields.map((f) => `{ py: ${js(f.py)}, type: ${kind(f.type)} }`).join(', ')}]);`, s.line);
141
+ }
117
142
  const tests = this.info.tests;
118
143
  for (const t of tests) {
119
144
  this.blank();
@@ -127,21 +152,40 @@ export class Gen {
127
152
  this.emit('export const THUNDER_TESTS: [string, () => void, number][] = [');
128
153
  for (const t of tests) this.emit(` [${js(t.title)}, ${id(t.py)}, ${t.line}],`);
129
154
  this.emit('];');
155
+ // Endpoints (When someone calls …): the routes the server answers, each with its inputs and where they come from.
156
+ const endpoints = (this.info.endpoints ?? []).filter(own);
157
+ const tyOf = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${tyOf(t.of)} }` : `{ k: ${js(t.k)} }`);
158
+ if (endpoints.length) {
159
+ this.blank();
160
+ this.emit('export const THUNDER_ROUTES: any[] = [');
161
+ for (const f of endpoints) {
162
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
163
+ const ins = f.params.map((p) => `{ text: ${js(p.text)}, py: ${js(p.py)}, type: ${tyOf(p.type)}, path: ${fromPath.has(p.name)}, dflt: ${!!p.dflt} }`);
164
+ this.emit(` { method: ${js(f.endpoint.method)}, path: ${js(f.endpoint.path)}, handler: ${id(f.py)}, inputs: [${ins.join(', ')}] },`, f.line);
165
+ }
166
+ this.emit('];');
167
+ }
130
168
  const main = this.p.main ?? [];
131
- if (main.length) {
169
+ if (main.length || endpoints.length) {
132
170
  this.blank();
133
171
  this.emit('export function main(): void {');
134
172
  this.ind++;
135
- this.frameBody('T.enterFrame(FILE, 0)', main, [], true);
173
+ if (main.length) this.frameBody('T.enterFrame(FILE, 0)', main, [], true);
136
174
  this.ind--;
137
175
  this.emit('}');
138
176
  this.blank();
139
- this.emit('if (T.isEntry(import.meta.url)) T.run(main);');
177
+ this.emit(`if (T.isEntry(import.meta.url)) T.run(main${endpoints.length ? ', THUNDER_ROUTES' : ''});`);
140
178
  }
141
179
  return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
142
180
  }
143
181
 
144
182
  record(r) {
183
+ this.recordKind(r);
184
+ // A data type with alternatives: each alternative's own fields, so JSON carries only the fields it has.
185
+ if (r.alts) this.emit(`(${id(r.py)} as any).alts = {${r.alts.map((a) => `${js(a.name)}: [${a.fields.map((f) => js(f.py)).join(', ')}]`).join(', ')}};`, r.line);
186
+ }
187
+
188
+ recordKind(r) {
145
189
  const fields = r.fields.map((f) => `{ py: ${js(f.py)}, type: { k: ${js(f.type?.k ?? 'any')} } }`).join(', ');
146
190
  const rules = r.rulesToCheck ?? [];
147
191
  if (!rules.length) { this.emit(`export const ${id(r.py)} = T.recordKind(${js(r.py)}, [${fields}]);`, r.line); return; }
@@ -206,7 +250,7 @@ export class Gen {
206
250
  }
207
251
  };
208
252
  visit(body);
209
- const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
253
+ const globals = new Set([...this.info.consts, ...(this.info.stores ?? []), ...this.info.funcs, ...this.info.records].map((x) => x.py));
210
254
  return [...names].filter((n) => !globals.has(n));
211
255
  }
212
256
 
@@ -251,8 +295,14 @@ export class Gen {
251
295
  this.line(L, `{ const ${v} = ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
252
296
  return;
253
297
  }
254
- case 'give': this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
255
- case 'stop': { const v = this.x(s.e); this.line(L, `throw T.Stop(${s.e.type?.k === 'text' ? `T.pyStr(${v})` : `T.show(${v})`});`); return; }
298
+ case 'give':
299
+ if (s.status != null) this.line(L, `T.answerStatus(${s.status});`);
300
+ this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
301
+ case 'stop': {
302
+ const v = this.x(s.e);
303
+ const msg = s.e.type?.k === 'text' ? `T.pyStr(${v})` : `T.show(${v})`;
304
+ this.line(L, s.status != null ? `throw T.stopWith(${msg}, ${s.status});` : `throw T.Stop(${msg});`); return;
305
+ }
256
306
  case 'if': {
257
307
  this.emit(`F.line = ${L};`, L);
258
308
  s.branches.forEach((b, k) => {
@@ -412,6 +462,12 @@ export class Gen {
412
462
  case 'bool': return e.v ? 'true' : 'false';
413
463
  case 'nothing': case 'hole': return 'null';
414
464
  case 'paren': return sub(e.e);
465
+ // the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
466
+ case 'httpCall': {
467
+ const tyOf = (t) => (t.k === 'optional' ? `{ k: 'optional', of: ${tyOf(t.of)} }` : `{ k: ${js(t.k)} }`);
468
+ const as = e.record ? `{ cls: ${id(e.record.py)}, fields: [${e.record.fields.map((f) => `{ py: ${js(f.py)}, type: ${tyOf(f.type)} }`).join(', ')}], many: ${e.as.k === 'list'} }` : 'null';
469
+ return `T.httpCall(${js(e.method)}, ${sub(e.url)}, ${e.body ? sub(e.body) : 'null'}, ${as})`;
470
+ }
415
471
  case 'today': return 'T.today()';
416
472
  case 'date': return `T.date(${js(e.text)})`;
417
473
  case 'str': return this.str(e, ctx);
@@ -6,6 +6,7 @@
6
6
  import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync } from 'node:fs';
7
7
  import { join, dirname } from 'node:path';
8
8
  import { spawnSync } from 'node:child_process';
9
+ import { spawnServing } from './serving.mjs';
9
10
  import { createRequire } from 'node:module';
10
11
  import { fileURLToPath } from 'node:url';
11
12
  import { toTypeScript, pythonOnlyUses, npmUses, dotnetRefusals } from './target-typescript.mjs';
@@ -13,7 +14,7 @@ import { TS_RUNTIME, TS_RUNTIME_DTS } from './runtime-typescript.mjs';
13
14
  import { diag } from './diagnostics.mjs';
14
15
 
15
16
  /** The names a src file gives a test file (its records, functions, and kept values). */
16
- const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.modules ?? []).filter((m) => m.ecosystem === 'npm')].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
17
+ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts, ...(r.info.stores ?? []), ...(r.info.modules ?? []).filter((m) => m.ecosystem === 'npm')].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
17
18
 
18
19
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
19
20
  export function typescriptDiagnostics(result) {
@@ -82,11 +83,12 @@ export function typescriptRunner({ nodeVersion = process.versions.node, searchFr
82
83
  * Run a compiled module (`entry`, e.g. "main.ts" or "run_tests.ts") in `outDir`, in the folder `cwd`.
83
84
  * Returns spawnSync's result ({ status, stdout, stderr }), or { status: 2, stderr } when TypeScript cannot run here.
84
85
  */
85
- export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', searchFrom = [] } = {}) {
86
+ export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', searchFrom = [], serving = false } = {}) {
87
+ const run = serving ? spawnServing : spawnSync; // a program with endpoints keeps answering until stopped
86
88
  const runner = typescriptRunner({ searchFrom: [outDir, cwd, ...searchFrom] });
87
89
  if (runner.error) return { status: 2, stdout: '', stderr: `${runner.error}\n`, error: runner.error };
88
90
  const env = { ...process.env, NODE_NO_WARNINGS: '1' };
89
- if (runner.args) return spawnSync(process.execPath, [...runner.args, join(outDir, entry)], { cwd, stdio, encoding: 'utf8', env });
91
+ if (runner.args) return run(process.execPath, [...runner.args, join(outDir, entry)], { cwd, stdio, encoding: 'utf8', env });
90
92
  // Older Node: remove the types with the typescript package, into .run/ next to the TypeScript.
91
93
  const ts = runner.ts;
92
94
  const runDir = join(outDir, '.run');
@@ -97,7 +99,7 @@ export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', sea
97
99
  writeFileSync(join(runDir, f.replace(/\.ts$/, '.mjs')), js.replace(/(from\s+['"]\.\/[^'"]+)\.ts(['"])/g, '$1.mjs$2'));
98
100
  }
99
101
  writeFileSync(join(runDir, 'thunder_runtime.mjs'), readFileSync(join(outDir, 'thunder_runtime.mjs'), 'utf8'));
100
- return spawnSync(process.execPath, [join(runDir, entry.replace(/\.ts$/, '.mjs'))], { cwd, stdio, encoding: 'utf8', env });
102
+ return run(process.execPath, [join(runDir, entry.replace(/\.ts$/, '.mjs'))], { cwd, stdio, encoding: 'utf8', env });
101
103
  }
102
104
 
103
105
  function readdirTs(dir) {