@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
@@ -123,6 +123,9 @@ function collectNames(nodes, names) {
123
123
  } else if (w0 === 'keep') {
124
124
  const k = splitTop(ts, (t) => isWord(t, 'at'));
125
125
  add('const', stripArticle(ts.slice(1, k < 0 ? ts.length : k)));
126
+ } else if (w0 === 'store' && ts.some((t) => isWord(t, 'as'))) {
127
+ const k = splitTop(ts, (t) => isWord(t, 'as'));
128
+ add('const', stripArticle(ts.slice(1, k)));
126
129
  } else if (w0 === 'receive') {
127
130
  for (const p of paramGroups(ts.slice(1))) add('var', p.words);
128
131
  } else if (w0 === 'for' && isWord(ts[1], 'each')) {
@@ -139,6 +142,22 @@ function collectNames(nodes, names) {
139
142
  for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(' '), defaultTokens: p.defaultTokens });
140
143
  }
141
144
  names.funcInputs.set(keyOf(ts.slice(1, -1)), inputs);
145
+ } else if ((w0 === 'a' || w0 === 'an') && isOneOf(ts)) {
146
+ // A Payment is one of: its alternatives (Successful with amount as money) and their fields, and "which".
147
+ const words = ts.slice(1, -4);
148
+ add('record', words);
149
+ const own = ['which'];
150
+ const alts = [];
151
+ for (const c of n.children) {
152
+ const at = c.tokens.findIndex((t) => isWord(t, 'with'));
153
+ const altWords = stripArticle(at < 0 ? c.tokens : c.tokens.slice(0, at));
154
+ if (altWords.length) { alts.push(keyOf(altWords)); names.alts.set(keyOf(altWords), [...(names.alts.get(keyOf(altWords)) ?? []), keyOf(words)]); }
155
+ if (at >= 0) for (const g of paramGroups(c.tokens.slice(at + 1))) if (g.words.length) { names.fields.add(keyOf(g.words)); own.push(keyOf(g.words)); }
156
+ }
157
+ names.fields.add('which');
158
+ names.recordFields.set(keyOf(words), [...new Set(own)]);
159
+ names.recordText.set(keyOf(words), words.map((x) => x.text).join(' '));
160
+ names.altsOf.set(keyOf(words), alts);
142
161
  } else if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has')) {
143
162
  const words = ts.slice(1, -2);
144
163
  add('record', words);
@@ -180,6 +199,12 @@ function rememberName(ts) {
180
199
  }
181
200
 
182
201
  // "total and member", "total as money, member as yes/no", "price and rate (7% if not given)"
202
+ /** "A Payment is one of:": a data type with alternatives. */
203
+ function isOneOf(ts) {
204
+ const n = ts.length;
205
+ return n >= 6 && isSym(ts[n - 1], ':') && isWord(ts[n - 2], 'of') && isWord(ts[n - 3], 'one') && isWord(ts[n - 4], 'is');
206
+ }
207
+
183
208
  function paramGroups(ts) {
184
209
  const groups = [];
185
210
  let cur = [];
@@ -280,6 +305,15 @@ export class ExprParser {
280
305
  }
281
306
  if (s.word('in')) return wrap({ k: 'contains', l: this.add(s, o), r: l, line });
282
307
  if (s.done()) s.fail('Something is missing after "is".', 'For example: is 10, is at least 18, is nothing, is empty.', 'TC108');
308
+ // payment is successful: which alternative of a data type it is (a name of a value comes first).
309
+ if (this.names.alts?.size && s.peek()?.t === 'word') {
310
+ const run = []; for (let j = s.i; s.ts[j]?.t === 'word' && !RESERVED.has(s.ts[j].lower); j++) run.push(s.ts[j]);
311
+ const ak = this.longest(run, (key) => this.names.alts.has(key));
312
+ if (ak && !this.longest(run, (key) => this.names.known.has(key))) {
313
+ s.i += ak;
314
+ return wrap({ k: 'isAlt', e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(' '), line });
315
+ }
316
+ }
283
317
  return { k: 'cmp', op: neg ? '!=' : '==', l, r: this.add(s, o), line };
284
318
  }
285
319
  return l;
@@ -415,9 +449,52 @@ export class ExprParser {
415
449
  return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, '') };
416
450
  }
417
451
 
452
+ /** The fields a record is built with: with name "Ann" and balance $10 (none without "with"). */
453
+ recordFields(s, line) {
454
+ const fields = [];
455
+ if (s.word('with')) {
456
+ do {
457
+ const fr = this.wordRun(s);
458
+ if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
459
+ const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
460
+ s.i -= fr.length - fk;
461
+ fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
462
+ } while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
463
+ }
464
+ return fields;
465
+ }
466
+
418
467
  primary(s, o) {
419
468
  const t = s.peek();
420
469
  const line = s.line;
470
+ const METHODS = ['get', 'post', 'put', 'patch', 'delete'];
471
+ // the answer from GET "https://…" [with <value>] [as <Kind>]: call another service over HTTP.
472
+ if (isWord(t, 'answer') && isWord(s.peek(1), 'from') && METHODS.includes(s.peek(2)?.lower)) {
473
+ s.i += 2;
474
+ const method = s.next().text.toUpperCase();
475
+ const url = this.primary(s, { ...o, noAnd: true });
476
+ let body = null, as = null;
477
+ if (s.word('with')) {
478
+ body = this.expr(s, { ...o, noAnd: true });
479
+ // "with charge as Receipt": the "as" belongs to the call (what the answer is), not to the value sent.
480
+ if (body.k === 'conv' && body.type) { as = body.type; body = body.e; }
481
+ }
482
+ if (!as && s.word('as')) as = this.typeRef(s);
483
+ return { k: 'httpCall', method, url, body, as, line };
484
+ }
485
+ // calling GET /habits/walk [with name "run" and …]: an endpoint of this program, called directly (in tests).
486
+ if (isWord(t, 'calling') && METHODS.includes(s.peek(1)?.lower) && isSym(s.peek(2), '/')) {
487
+ s.i += 2;
488
+ const method = s.ts[s.i - 1].text.toUpperCase();
489
+ // The path is the tokens written against each other: / habits / walk (a space ends it).
490
+ let path = '';
491
+ let prev = null;
492
+ while (s.peek() && (prev === null ? isSym(s.peek(), '/') : s.peek().col === prev.col + String(prev.text).length && (isSym(s.peek(), '/') || isSym(s.peek(), '-') || s.peek().t === 'word' || s.peek().t === 'num'))) {
493
+ prev = s.next();
494
+ path += prev.text;
495
+ }
496
+ return { k: 'callEndpoint', method, path, fields: this.recordFields(s, line), line };
497
+ }
421
498
  if (!t) s.fail('A value is missing at the end of this line.', null, 'TC108');
422
499
  if (t.t === 'num') { s.next(); return { k: 'num', text: t.text, whole: t.whole, line }; }
423
500
  if (t.t === 'money') { s.next(); return { k: 'money', text: t.text, line }; }
@@ -431,6 +508,16 @@ export class ExprParser {
431
508
  s.next();
432
509
  return { k: 'str', parts: t.parts.map((p) => (typeof p === 'string' ? p : { e: this.parse(p.tokens, line), source: p.source })), line };
433
510
  }
511
+ // A hole in a draft: ? alone, or ?number / ?money / ?Habit with the kind written right after it. It never runs;
512
+ // the checker says what could go here and asks (TC120).
513
+ if (isSym(t, '?')) {
514
+ s.next();
515
+ const next = s.peek();
516
+ let want = null;
517
+ // A word right against the ? is its kind, so a misspelt kind is reported as one.
518
+ if (next && next.t === 'word' && t.col != null && next.col === t.col + 1) want = this.typeRef(s);
519
+ return { k: 'draftHole', want, line, col: t.col };
520
+ }
434
521
  if (isSym(t, '(')) { s.next(); const e = this.expr(s, {}); s.expectSym(')', 'to close the parenthesis'); return { k: 'paren', e, line }; }
435
522
  if (isSym(t, '[')) {
436
523
  s.next();
@@ -476,6 +563,26 @@ export class ExprParser {
476
563
  if (RESERVED.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, 'TC105');
477
564
 
478
565
  const run = this.wordRun(s);
566
+ // an alternative of a data type: "a successful Payment with amount $5", "a pending Payment"
567
+ if (o.article && this.names.alts?.size) {
568
+ for (let i = 1; i < run.length; i++) {
569
+ const alt = keyOf(run.slice(0, i));
570
+ const recs = this.names.alts.get(alt);
571
+ if (!recs) continue;
572
+ const rk = this.longest(run.slice(i), (key) => recs.includes(key));
573
+ if (!rk || i + rk !== run.length) continue;
574
+ s.i -= run.length - i - rk;
575
+ const node = { k: 'new', record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(' '), fields: this.recordFields(s, line), line };
576
+ return node;
577
+ }
578
+ // "a refunded Payment": words before a data type that has alternatives, but not one of them (the checker says so).
579
+ for (let i = 1; i < run.length; i++) {
580
+ const rk = this.longest(run.slice(i), (key) => this.names.altsOf.has(key));
581
+ if (!rk || i + rk !== run.length) continue;
582
+ s.i -= run.length - i - rk;
583
+ return { k: 'new', record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(' '), fields: this.recordFields(s, line), line };
584
+ }
585
+ }
479
586
  // a record: "a Customer with name "Ann" and balance $10", "a new Customer"
480
587
  let off = run[0]?.lower === 'new' && run.length > 1 ? 1 : 0;
481
588
  const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
@@ -483,16 +590,7 @@ export class ExprParser {
483
590
  if (recK && wantsRecord && (recK + off === run.length)) {
484
591
  s.i -= run.length - off - recK;
485
592
  const name = keyOf(run.slice(off, off + recK));
486
- const fields = [];
487
- if (s.word('with')) {
488
- do {
489
- const fr = this.wordRun(s);
490
- if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
491
- const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
492
- s.i -= fr.length - fk;
493
- fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
494
- } while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
495
- }
593
+ const fields = this.recordFields(s, line);
496
594
  const node = { k: 'new', record: name, fields, line };
497
595
  if (!fields.length && this.open) this.open.push(node); // a block of "field: value" lines may fill it
498
596
  return node;
@@ -529,7 +627,7 @@ export class ExprParser {
529
627
  export function parseCore(source, { seed = null } = {}) {
530
628
  const { lines, diagnostics } = lex(source);
531
629
  const tree = buildBlocks(lines, diagnostics);
532
- const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: new Map(), screens: new Map() };
630
+ const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: new Map(), screens: new Map(), alts: new Map(seed?.alts ?? []), altsOf: new Map(seed?.altsOf ?? []) };
533
631
  collectNames(tree, names);
534
632
  const ep = new ExprParser(names);
535
633
  const body = parseBlock(tree, ep, names, diagnostics, { top: true });
@@ -562,14 +660,14 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
562
660
  }
563
661
 
564
662
  // Statements whose ":" opens a block of statements (never a block of "name: value" lines).
565
- const BLOCK_STATEMENTS = new Set(['when', 'if', 'otherwise', 'for', 'repeat', 'to', 'test', 'receive', 'never', 'use', 'screen']);
663
+ const BLOCK_STATEMENTS = new Set(['when', 'if', 'otherwise', 'for', 'repeat', 'to', 'test', 'receive', 'never', 'use', 'screen', 'depending']);
566
664
 
567
665
  /** The "name: value" lines under a statement that is not itself a block statement, or null. */
568
666
  function fieldBlock(n, diagnostics = []) {
569
667
  const ts = n.tokens;
570
668
  if (!n.children.length || !isSym(ts[ts.length - 1], ':')) return null;
571
669
  const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
572
- if (BLOCK_STATEMENTS.has(w0) || ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has'))) return null;
670
+ if (BLOCK_STATEMENTS.has(w0) || ((w0 === 'a' || w0 === 'an') && (isWord(ts[ts.length - 2], 'has') || isOneOf(ts)))) return null;
573
671
  return n.children.map((c) => {
574
672
  const colon = c.tokens.findIndex((t) => isSym(t, ':'));
575
673
  const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
@@ -662,6 +760,25 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
662
760
  const w0 = ts[0].t === 'word' ? ts[0].lower : '';
663
761
  const rest = ts.slice(1);
664
762
 
763
+ // When someone calls GET /habits/{name}: an endpoint. Underneath it is a function whose inputs are its Receive
764
+ // lines; the server (and "calling GET /habits/walk" in a test) passes the path parts and the body to them.
765
+ if (w0 === 'when' && isWord(ts[1], 'someone') && isWord(ts[2], 'calls') && ts[4]?.t === 'path') {
766
+ if (!ctx.top) fail('TC402', 'An endpoint ("When someone calls …") must be written at the left edge, not inside another block.');
767
+ const method = ts[3].text.toUpperCase();
768
+ const path = ts[4].text;
769
+ const segments = path.split('/').filter(Boolean).map((seg) => { const m = seg.match(/^\{([^{}]+)\}$/); return m ? { param: m[1].trim().toLowerCase(), text: m[1].trim() } : { lit: seg }; });
770
+ const kids = n.children;
771
+ const params = [];
772
+ let r = 0;
773
+ while (kids[r] && isWord(kids[r].tokens[0], 'receive')) {
774
+ const kid = kids[r];
775
+ params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
776
+ r++;
777
+ }
778
+ const words = ['answer', method.toLowerCase(), ...segments.map((g) => (g.param ? g.param : g.lit.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim())).filter(Boolean)];
779
+ const name = words.join(' ');
780
+ return { k: 'func', name, text: `${method} ${path}`, params, body: parseBlock(kids.slice(r), ep, names, diagnostics, { inFunc: true, inEndpoint: true }), line, endpoint: { method, path, segments, line } };
781
+ }
665
782
  if (w0 === 'say' || w0 === 'print') return { k: 'say', e: E(rest), line };
666
783
  if (w0 === 'set') {
667
784
  const at = splitTop(rest, (t) => isWord(t, 'to'));
@@ -672,20 +789,41 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
672
789
  if (!['name', 'field', 'at'].includes(target.k)) fail('TC305', 'Only a name, a field (customer\'s balance), or an entry (counts at word) can be set.');
673
790
  return { k: 'set', target, e: E(rest.slice(at + 1)), line };
674
791
  }
792
+ // Store <name> as a list of <Record>: a list that is saved between runs (data/<name>.json).
793
+ if (w0 === 'store' && rest.some((t) => isWord(t, 'as'))) {
794
+ if (!ctx.top) fail('TC402', 'A "Store" line must be written at the left edge of the file.');
795
+ const as = splitTop(rest, (t) => isWord(t, 'as'));
796
+ const typeTokens = stripArticle(rest.slice(as + 1));
797
+ if (!typeTokens.length) fail('TC108', 'Write what the store holds: Store habits as a list of Habit.');
798
+ return { k: 'store', ...nameWords(rest.slice(0, as), line, '"Store"'), type: typeOf(ep, typeTokens, line), line };
799
+ }
675
800
  if (w0 === 'keep') {
676
801
  const at = splitTop(rest, (t) => isWord(t, 'at'));
677
802
  if (at < 0) fail('TC108', '"Keep" needs "at": Keep tax rate at 7%.');
678
803
  return { k: 'keep', ...nameWords(rest.slice(0, at), line, '"Keep"'), e: E(rest.slice(at + 1)), line };
679
804
  }
805
+ // "… with status 201" (Give) and "… and status 404" (Stop): the HTTP status an endpoint answers with.
806
+ // A Stop's status may be set in any function (a helper like "find order" says 404; it matters only when an
807
+ // endpoint answers with it). Give's status only in the endpoint itself, where the answer is made.
808
+ const statusAt = (r, joiner) => {
809
+ const n = r.length;
810
+ if (n >= 3 && isWord(r[n - 3], joiner) && isWord(r[n - 2], 'status') && r[n - 1].t === 'num') {
811
+ if (joiner === 'with' && !ctx.inEndpoint) fail('TC218', `"with status" sets the HTTP status of an endpoint's answer, so it goes inside "When someone calls …".`, 'Outside an endpoint, Give the value; the endpoint that gives it sets the status.');
812
+ return { status: Number(r[n - 1].text), r: r.slice(0, -3) };
813
+ }
814
+ return { status: null, r };
815
+ };
680
816
  if (w0 === 'give') {
681
817
  let r = rest;
682
818
  if (isWord(r[0], 'back')) r = r.slice(1);
683
- return { k: 'give', e: r.length ? E(r) : { k: 'nothing', line }, line };
819
+ const st = statusAt(r, 'with');
820
+ return { k: 'give', e: st.r.length ? E(st.r) : { k: 'nothing', line }, status: st.status, line };
684
821
  }
685
822
  if (w0 === 'stop') {
686
823
  let r = rest;
687
824
  if (isWord(r[0], 'with') || isSym(r[0], ':')) r = r.slice(1);
688
- return { k: 'stop', e: r.length ? E(r) : { k: 'str', parts: ['Stopped'], line }, line };
825
+ const st = statusAt(r, 'and');
826
+ return { k: 'stop', e: st.r.length ? E(st.r) : { k: 'str', parts: ['Stopped'], line }, status: st.status, line };
689
827
  }
690
828
  if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
691
829
  header();
@@ -694,6 +832,23 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
694
832
  siblings.pop();
695
833
  return { k: 'tryFail', stmt: prev, handler: children(), line };
696
834
  }
835
+ // Depending on payment: / Successful: … / Declined: … / Otherwise: …
836
+ if (w0 === 'depending' && isWord(ts[1], 'on')) {
837
+ const subject = E(header().slice(2));
838
+ const cases = [];
839
+ let otherwise = null;
840
+ for (const c of n.children) {
841
+ try {
842
+ const ct = c.tokens;
843
+ if (!isSym(ct[ct.length - 1], ':') || ct.length < 2) throw new CoreError(diag('TC108', c.line, 'Under "Depending on", each case is an alternative and a colon, for example: Successful:'));
844
+ const sub = parseBlock(c.children, ep, names, diagnostics, ctx);
845
+ if (ct.length === 2 && isWord(ct[0], 'otherwise')) { otherwise = sub; continue; }
846
+ const { name, text } = nameWords(ct.slice(0, -1), c.line, 'A case');
847
+ cases.push({ alt: name, text, body: sub, line: c.line });
848
+ } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
849
+ }
850
+ return { k: 'depending', subject, cases, otherwise, line };
851
+ }
697
852
  if (w0 === 'when' || w0 === 'if') {
698
853
  const cond = E(header().slice(1));
699
854
  return { k: 'if', branches: [{ cond, body: children(), line }], otherwise: null, line };
@@ -758,6 +913,36 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
758
913
  }
759
914
  if (w0 === 'remember') fail('TC119', '"Remember" goes at the top of a "Screen", after its "Receive" lines.', 'A function keeps nothing between calls; a screen remembers values while it is shown.');
760
915
  if (w0 === 'show') fail('TC118', '"Show" is used inside a "Screen" (a screen shows things). In a program, write: Say …');
916
+ // A Payment is one of:
917
+ // Successful with amount as money
918
+ // Declined with reason as text
919
+ // Pending
920
+ // A record underneath: "which" (the alternative's name) and every alternative's fields, each optional. The checker
921
+ // makes sure a field is only read where the alternative is known, and that "Depending on" covers every one.
922
+ if ((w0 === 'a' || w0 === 'an') && isOneOf(ts)) {
923
+ if (!ctx.top) fail('TC402', 'A data type ("A … is one of:") must be written at the left edge, not inside another block.');
924
+ const { name, text } = nameWords(ts.slice(1, -4), line, 'A data type');
925
+ const alts = [];
926
+ for (const c of n.children) {
927
+ try {
928
+ const at = c.tokens.findIndex((t) => isWord(t, 'with'));
929
+ const alt = nameWords(at < 0 ? c.tokens : c.tokens.slice(0, at), c.line, 'An alternative');
930
+ const fields = [];
931
+ if (at >= 0) {
932
+ for (const g of paramGroups(c.tokens.slice(at + 1))) {
933
+ if (!g.typeTokens) throw new CoreError(diag('TC108', c.line, `Write each field with its kind: ${alt.text} with ${g.words.map((x) => x.text).join(' ') || 'amount'} as money.`));
934
+ fields.push({ ...nameWords(g.raw, c.line, 'A field'), type: typeOf(ep, g.typeTokens, c.line), line: c.line });
935
+ }
936
+ }
937
+ alts.push({ ...alt, fields, line: c.line });
938
+ } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
939
+ }
940
+ if (!alts.length) fail('TC108', `Write the alternatives under it, one per line, for example: Successful with amount as money.`);
941
+ const opt = (t) => (t.k === 'optional' ? t : { k: 'optional', of: t });
942
+ const fields = [{ name: 'which', text: 'which', type: { k: 'text' }, line, hidden: true }];
943
+ for (const a of alts) for (const f of a.fields) if (!fields.some((x) => x.name === f.name)) fields.push({ ...f, type: opt(f.type) });
944
+ return { k: 'record', name, text, fields, rules: [], alts, line };
945
+ }
761
946
  if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
762
947
  if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
763
948
  const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
@@ -0,0 +1,18 @@
1
+ // Where a Thunder Core project starts: the nearest thunder.toml. Its own small file so the thunder command can
2
+ // find a project (for example to word a "no such file" message) without loading the whole of Thunder Core.
3
+ import { existsSync, statSync } from 'node:fs';
4
+ import { join, dirname, resolve } from 'node:path';
5
+
6
+ export const PROJECT_FILE = 'thunder.toml';
7
+
8
+ /** The nearest folder at or above `start` that holds a thunder.toml, or null. */
9
+ export function findProjectRoot(start) {
10
+ let dir = resolve(start);
11
+ if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
12
+ for (;;) {
13
+ if (existsSync(join(dir, PROJECT_FILE))) return dir;
14
+ const up = dirname(dir);
15
+ if (up === dir) return null;
16
+ dir = up;
17
+ }
18
+ }
@@ -3,6 +3,7 @@
3
3
  // Source ownership: in a Thunder project the .thunder files are the source. generated/ is a build artifact,
4
4
  // rewritten by every build; it is never read back.
5
5
 
6
+ import { spawnServing } from './serving.mjs';
6
7
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, rmSync } from 'node:fs';
7
8
  import { join, dirname, relative, resolve, basename } from 'node:path';
8
9
  import { spawnSync } from 'node:child_process';
@@ -23,7 +24,9 @@ export const TARGETS = ['python', 'typescript', 'csharp', 'rust', 'go', 'java',
23
24
  /** How a target is named to people. */
24
25
  export const TARGET_NAMES = { python: 'Python', typescript: 'TypeScript', csharp: 'C#', rust: 'Rust', go: 'Go', java: 'Java', react: 'React' };
25
26
 
26
- export const PROJECT_FILE = 'thunder.toml';
27
+ import { PROJECT_FILE, findProjectRoot } from './project-root.mjs';
28
+
29
+ export { PROJECT_FILE, findProjectRoot };
27
30
 
28
31
  /** A tiny TOML subset: [sections], key = "text" | number | true | false, and # comments. */
29
32
  export function parseToml(text) {
@@ -42,18 +45,6 @@ export function parseToml(text) {
42
45
  return out;
43
46
  }
44
47
 
45
- /** The nearest folder at or above `start` that holds a thunder.toml, or null. */
46
- export function findProjectRoot(start) {
47
- let dir = resolve(start);
48
- if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
49
- for (;;) {
50
- if (existsSync(join(dir, PROJECT_FILE))) return dir;
51
- const up = dirname(dir);
52
- if (up === dir) return null;
53
- dir = up;
54
- }
55
- }
56
-
57
48
  export function loadProject(root) {
58
49
  const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
59
50
  const build = toml.build ?? {};
@@ -93,8 +84,10 @@ export function buildProject({ root, single = null, includeTests = false, write
93
84
  const tgt = target ?? cfg?.target ?? 'python';
94
85
  if (!TARGETS.includes(tgt)) throw new Error(`there is no target "${tgt}". Thunder Core builds ${TARGETS.join(', ')} (python is the default).`);
95
86
  const srcFiles = cfg ? thunderFiles(join(cfg.root, cfg.src)) : [];
96
- if (single && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
97
- const testFiles = includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
87
+ // A single file in the project's tests/ is a test: it is checked against src/, as in a whole-project run.
88
+ const singleTest = single && cfg && thunderFiles(join(cfg.root, cfg.tests)).includes(resolve(single)) ? resolve(single) : null;
89
+ if (single && !singleTest && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
90
+ const testFiles = singleTest ? [singleTest] : includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
98
91
  const outDir = join(base, cfg && (target == null || target === cfg.target) ? cfg.out : `generated/${tgt}`);
99
92
  const results = [];
100
93
  const used = new Set();
@@ -105,7 +98,9 @@ export function buildProject({ root, single = null, includeTests = false, write
105
98
  results.push({ ...r, path: f, rel, module: uniqueModule(f), kind: 'src' });
106
99
  }
107
100
  const srcOk = results.filter((r) => r.ok);
108
- for (const f of testFiles) {
101
+ // Tests are built against src/. While src/ has problems they would only repeat them as names they can't find,
102
+ // so the problems in src/ are reported alone; the tests are checked once src/ is fixed.
103
+ for (const f of srcOk.length === results.length ? testFiles : []) {
109
104
  const rel = relative(base, f).split('\\').join('/');
110
105
  const r = compileCore(readFileSync(f, 'utf8'), { file: rel, imported: srcOk, srcModules: srcOk.map((x) => x.module) });
111
106
  results.push({ ...r, path: f, rel, module: uniqueModule(f, 'tests_'), kind: 'test' });
@@ -163,8 +158,10 @@ export function findPython() {
163
158
  return { error: 'Thunder needs Python 3.10 or newer to run this program, and I could not find it (tried THUNDER_PYTHON, python3, python). Install it from https://www.python.org/downloads/ or set THUNDER_PYTHON to its path. "thunder build" still works without Python.' };
164
159
  }
165
160
 
166
- export function runPython(python, outDir, script, cwd) {
167
- return spawnSync(python.cmd, [join(outDir, script)], { cwd, stdio: 'inherit', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' } });
161
+ export function runPython(python, outDir, script, cwd, { serving = false } = {}) {
162
+ const opts = { cwd, stdio: 'inherit', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' } };
163
+ // A program with endpoints keeps answering until stopped: started without waiting, with stop signals passed on.
164
+ return (serving ? spawnServing : spawnSync)(python.cmd, [join(outDir, script)], opts);
168
165
  }
169
166
 
170
167
  export function newProject(dir, { force = false } = {}) {
@@ -5,13 +5,13 @@
5
5
  import { writeFileSync, mkdirSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { toReact, hasScreens } from './target-react.mjs';
8
- import { pythonOnlyUses, npmRefusals, dotnetRefusals } from './target-typescript.mjs';
8
+ import { pythonOnlyUses, npmRefusals, dotnetRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
9
9
  import { REACT_RUNTIME, REACT_RUNTIME_DTS } from './runtime-react.mjs';
10
10
  import { diag } from './diagnostics.mjs';
11
11
 
12
12
  /** What stops a file from becoming a React app: a Python module (TC405), or steps outside a screen (TC406). */
13
13
  export function reactDiagnostics(result, { entry = false } = {}) {
14
- const out = [...npmRefusals(result.info, 'a React app', diag), ...dotnetRefusals(result.info, 'a React app', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
14
+ const out = [...npmRefusals(result.info, 'a React app', diag), ...dotnetRefusals(result.info, 'a React app', diag), ...storeRefusals(result.info, 'a React app', diag), ...httpRefusals(result.info, 'a React app', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
15
15
  `"${u.module}" is a Python module, and this program is built as a React app, which cannot use it.`,
16
16
  'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
17
17
  const main = result.program.main ?? [];