@skillstech/thunderlang 1.6.1 → 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.
- package/CHANGELOG.md +121 -0
- package/README.md +10 -3
- package/dist/core.cjs +264 -47
- package/dist/index.cjs +9118 -1077
- package/dist/learn.cjs +1419 -90
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +3015 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +316 -10
- package/src/core/cli.mjs +67 -10
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +12 -1
- package/src/core/engine-core.mjs +161 -20
- package/src/core/engine-values.mjs +1 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/go-run.mjs +3 -2
- package/src/core/index.mjs +6 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +45 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +254 -22
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +18 -18
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-go/thunder_runtime.go +269 -1
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +155 -6
- package/src/core/rust-run.mjs +3 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +11 -4
- package/src/core/target-python.mjs +39 -6
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +95 -7
- package/src/core/typescript-run.mjs +14 -7
- package/src/core-changes-fs.mjs +28 -0
- package/src/core-changes.d.mts +67 -0
- package/src/core-changes.mjs +603 -0
- package/src/core-rules.mjs +146 -0
- package/src/core-services.d.mts +4 -0
- package/src/core-services.mjs +49 -0
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/evidence.mjs +28 -0
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/focus.mjs +2 -1
- package/src/index.d.ts +4 -0
- package/src/index.mjs +4 -0
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +52 -6
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/program.d.mts +4 -0
- package/src/program.mjs +4 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +71 -4
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +3 -2
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-cli.mjs +8 -3
- package/src/trace-data.mjs +3 -2
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +27 -10
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/src/core/lexer.mjs
CHANGED
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
// money $200, $0.10 { t: 'money', text }
|
|
11
11
|
// percent 20%, 12.5% { t: 'percent', text }
|
|
12
12
|
// str "Hello, {name}!" (parts: strings and { tokens } holes) { t: 'str', parts }
|
|
13
|
-
// sym + - * / ( ) [ ] , : . = == != <> < <= > >=
|
|
13
|
+
// sym + - * / ( ) [ ] , : . = == != <> < <= > >= ? { t: 'sym', text } (? is a hole: ?number)
|
|
14
14
|
|
|
15
15
|
import { diag, CoreError } from './diagnostics.mjs';
|
|
16
16
|
|
|
17
|
-
const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>'];
|
|
17
|
+
const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>', '?'];
|
|
18
18
|
const WORD_START = /[\p{L}_]/u;
|
|
19
19
|
const WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
20
20
|
|
|
@@ -22,6 +22,20 @@ const WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
|
22
22
|
export function tokenizeLine(text, line, colOffset = 0) {
|
|
23
23
|
const toks = [];
|
|
24
24
|
let i = 0;
|
|
25
|
+
// When someone calls GET /habits/{name}: the path is one token (it may hold {name} parts and other characters).
|
|
26
|
+
const ep = text.match(/^(when)(\s+)(someone)(\s+)(calls)(\s+)([A-Za-z]+)(\s+)(\/\S*?)(\s*)(:)(\s*(#.*)?)$/i);
|
|
27
|
+
if (ep) {
|
|
28
|
+
let col = colOffset + 1;
|
|
29
|
+
const out = [];
|
|
30
|
+
const parts = ep.slice(1, 12);
|
|
31
|
+
parts.forEach((part, k) => {
|
|
32
|
+
if (k === 8) out.push({ t: 'path', text: part, col, line });
|
|
33
|
+
else if (k === 10) out.push({ t: 'sym', text: ':', col, line });
|
|
34
|
+
else if (part && !/^\s*$/.test(part)) out.push({ t: 'word', text: part, lower: part.toLowerCase(), col, line });
|
|
35
|
+
col += part.length;
|
|
36
|
+
});
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
25
39
|
const at = (k = 0) => text[i + k];
|
|
26
40
|
while (i < text.length) {
|
|
27
41
|
const c = at();
|
package/src/core/parser.mjs
CHANGED
|
@@ -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 = [];
|
|
@@ -201,7 +226,8 @@ function paramGroups(ts) {
|
|
|
201
226
|
if (n > 3 && isWord(inner[n - 3], 'if') && isWord(inner[n - 2], 'not') && isWord(inner[n - 1], 'given')) { defaultTokens = inner.slice(0, -3); g = g.slice(0, open); }
|
|
202
227
|
}
|
|
203
228
|
const k = g.findIndex((t) => isWord(t, 'as'));
|
|
204
|
-
|
|
229
|
+
const raw = k < 0 ? g : g.slice(0, k);
|
|
230
|
+
return { words: stripArticle(raw), raw, typeTokens: k < 0 ? null : g.slice(k + 1), defaultTokens };
|
|
205
231
|
});
|
|
206
232
|
}
|
|
207
233
|
|
|
@@ -279,6 +305,15 @@ export class ExprParser {
|
|
|
279
305
|
}
|
|
280
306
|
if (s.word('in')) return wrap({ k: 'contains', l: this.add(s, o), r: l, line });
|
|
281
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
|
+
}
|
|
282
317
|
return { k: 'cmp', op: neg ? '!=' : '==', l, r: this.add(s, o), line };
|
|
283
318
|
}
|
|
284
319
|
return l;
|
|
@@ -414,9 +449,52 @@ export class ExprParser {
|
|
|
414
449
|
return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, '') };
|
|
415
450
|
}
|
|
416
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
|
+
|
|
417
467
|
primary(s, o) {
|
|
418
468
|
const t = s.peek();
|
|
419
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
|
+
}
|
|
420
498
|
if (!t) s.fail('A value is missing at the end of this line.', null, 'TC108');
|
|
421
499
|
if (t.t === 'num') { s.next(); return { k: 'num', text: t.text, whole: t.whole, line }; }
|
|
422
500
|
if (t.t === 'money') { s.next(); return { k: 'money', text: t.text, line }; }
|
|
@@ -430,6 +508,16 @@ export class ExprParser {
|
|
|
430
508
|
s.next();
|
|
431
509
|
return { k: 'str', parts: t.parts.map((p) => (typeof p === 'string' ? p : { e: this.parse(p.tokens, line), source: p.source })), line };
|
|
432
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
|
+
}
|
|
433
521
|
if (isSym(t, '(')) { s.next(); const e = this.expr(s, {}); s.expectSym(')', 'to close the parenthesis'); return { k: 'paren', e, line }; }
|
|
434
522
|
if (isSym(t, '[')) {
|
|
435
523
|
s.next();
|
|
@@ -475,6 +563,26 @@ export class ExprParser {
|
|
|
475
563
|
if (RESERVED.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, 'TC105');
|
|
476
564
|
|
|
477
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
|
+
}
|
|
478
586
|
// a record: "a Customer with name "Ann" and balance $10", "a new Customer"
|
|
479
587
|
let off = run[0]?.lower === 'new' && run.length > 1 ? 1 : 0;
|
|
480
588
|
const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
|
|
@@ -482,16 +590,7 @@ export class ExprParser {
|
|
|
482
590
|
if (recK && wantsRecord && (recK + off === run.length)) {
|
|
483
591
|
s.i -= run.length - off - recK;
|
|
484
592
|
const name = keyOf(run.slice(off, off + recK));
|
|
485
|
-
const fields =
|
|
486
|
-
if (s.word('with')) {
|
|
487
|
-
do {
|
|
488
|
-
const fr = this.wordRun(s);
|
|
489
|
-
if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
|
|
490
|
-
const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
|
|
491
|
-
s.i -= fr.length - fk;
|
|
492
|
-
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 });
|
|
493
|
-
} while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
|
|
494
|
-
}
|
|
593
|
+
const fields = this.recordFields(s, line);
|
|
495
594
|
const node = { k: 'new', record: name, fields, line };
|
|
496
595
|
if (!fields.length && this.open) this.open.push(node); // a block of "field: value" lines may fill it
|
|
497
596
|
return node;
|
|
@@ -528,7 +627,7 @@ export class ExprParser {
|
|
|
528
627
|
export function parseCore(source, { seed = null } = {}) {
|
|
529
628
|
const { lines, diagnostics } = lex(source);
|
|
530
629
|
const tree = buildBlocks(lines, diagnostics);
|
|
531
|
-
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 ?? []) };
|
|
532
631
|
collectNames(tree, names);
|
|
533
632
|
const ep = new ExprParser(names);
|
|
534
633
|
const body = parseBlock(tree, ep, names, diagnostics, { top: true });
|
|
@@ -561,14 +660,14 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
|
561
660
|
}
|
|
562
661
|
|
|
563
662
|
// Statements whose ":" opens a block of statements (never a block of "name: value" lines).
|
|
564
|
-
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']);
|
|
565
664
|
|
|
566
665
|
/** The "name: value" lines under a statement that is not itself a block statement, or null. */
|
|
567
666
|
function fieldBlock(n, diagnostics = []) {
|
|
568
667
|
const ts = n.tokens;
|
|
569
668
|
if (!n.children.length || !isSym(ts[ts.length - 1], ':')) return null;
|
|
570
669
|
const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
|
|
571
|
-
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;
|
|
572
671
|
return n.children.map((c) => {
|
|
573
672
|
const colon = c.tokens.findIndex((t) => isSym(t, ':'));
|
|
574
673
|
const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
|
|
@@ -638,7 +737,12 @@ function fillBlock(open, lines, n, ep, names) {
|
|
|
638
737
|
|
|
639
738
|
function nameWords(ts, line, what) {
|
|
640
739
|
const words = stripArticle(ts);
|
|
641
|
-
if (!words.length)
|
|
740
|
+
if (!words.length) {
|
|
741
|
+
// The name was only "a", "an", or "the": Thunder skips those words in a name ("the total" is "total").
|
|
742
|
+
const only = ts.length === 1 && ts[0].t === 'word' ? ts[0].text : null;
|
|
743
|
+
if (only) throw new CoreError(diag('TC108', line, `"${only}" can't be a name on its own: Thunder skips "a", "an", and "the" in names ("the total" is "total").`, `Use a word that says what it holds, like "first number" or "amount".`));
|
|
744
|
+
throw new CoreError(diag('TC108', line, `${what} is missing a name.`));
|
|
745
|
+
}
|
|
642
746
|
for (const t of words) {
|
|
643
747
|
if (t.t !== 'word') throw new CoreError(diag('TC105', line, `A name can only use words, but "${show(t)}" is not a word.`));
|
|
644
748
|
if (RESERVED.has(t.lower)) throw new CoreError(diag('TC202', line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
|
|
@@ -656,6 +760,25 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
656
760
|
const w0 = ts[0].t === 'word' ? ts[0].lower : '';
|
|
657
761
|
const rest = ts.slice(1);
|
|
658
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
|
+
}
|
|
659
782
|
if (w0 === 'say' || w0 === 'print') return { k: 'say', e: E(rest), line };
|
|
660
783
|
if (w0 === 'set') {
|
|
661
784
|
const at = splitTop(rest, (t) => isWord(t, 'to'));
|
|
@@ -666,20 +789,41 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
666
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.');
|
|
667
790
|
return { k: 'set', target, e: E(rest.slice(at + 1)), line };
|
|
668
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
|
+
}
|
|
669
800
|
if (w0 === 'keep') {
|
|
670
801
|
const at = splitTop(rest, (t) => isWord(t, 'at'));
|
|
671
802
|
if (at < 0) fail('TC108', '"Keep" needs "at": Keep tax rate at 7%.');
|
|
672
803
|
return { k: 'keep', ...nameWords(rest.slice(0, at), line, '"Keep"'), e: E(rest.slice(at + 1)), line };
|
|
673
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
|
+
};
|
|
674
816
|
if (w0 === 'give') {
|
|
675
817
|
let r = rest;
|
|
676
818
|
if (isWord(r[0], 'back')) r = r.slice(1);
|
|
677
|
-
|
|
819
|
+
const st = statusAt(r, 'with');
|
|
820
|
+
return { k: 'give', e: st.r.length ? E(st.r) : { k: 'nothing', line }, status: st.status, line };
|
|
678
821
|
}
|
|
679
822
|
if (w0 === 'stop') {
|
|
680
823
|
let r = rest;
|
|
681
824
|
if (isWord(r[0], 'with') || isSym(r[0], ':')) r = r.slice(1);
|
|
682
|
-
|
|
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 };
|
|
683
827
|
}
|
|
684
828
|
if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
|
|
685
829
|
header();
|
|
@@ -688,6 +832,23 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
688
832
|
siblings.pop();
|
|
689
833
|
return { k: 'tryFail', stmt: prev, handler: children(), line };
|
|
690
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
|
+
}
|
|
691
852
|
if (w0 === 'when' || w0 === 'if') {
|
|
692
853
|
const cond = E(header().slice(1));
|
|
693
854
|
return { k: 'if', branches: [{ cond, body: children(), line }], otherwise: null, line };
|
|
@@ -735,7 +896,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
735
896
|
let r = 0;
|
|
736
897
|
while (kids[r] && isWord(kids[r].tokens[0], 'receive')) {
|
|
737
898
|
const kid = kids[r];
|
|
738
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.
|
|
899
|
+
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 })));
|
|
739
900
|
r++;
|
|
740
901
|
}
|
|
741
902
|
bodyNodes = kids.slice(r);
|
|
@@ -752,6 +913,36 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
752
913
|
}
|
|
753
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.');
|
|
754
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
|
+
}
|
|
755
946
|
if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
|
|
756
947
|
if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
|
|
757
948
|
const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
|
|
@@ -770,12 +961,53 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
770
961
|
if (w0 === 'never') return parseNever(ts, line, ep);
|
|
771
962
|
if (w0 === 'use') {
|
|
772
963
|
if (!ctx.top) fail('TC402', '"Use" must be written at the left edge of the file.');
|
|
964
|
+
// Use <python module> [from Python] [as <name>] or Use "<npm package>" from npm as <name>
|
|
965
|
+
// or Use "<.NET type>" from .NET as <name> or Use "<.NET type>" from NuGet "<package>" version "<v>" as <name>
|
|
773
966
|
const asAt = rest.findIndex((t) => isWord(t, 'as'));
|
|
774
|
-
|
|
967
|
+
let modTs = asAt < 0 ? rest : rest.slice(0, asAt);
|
|
968
|
+
const fromAt = modTs.findIndex((t) => isWord(t, 'from'));
|
|
969
|
+
let ecosystem = 'python';
|
|
970
|
+
if (fromAt >= 0) {
|
|
971
|
+
const eco = modTs.slice(fromAt + 1);
|
|
972
|
+
const plain = (t) => t && typeof t.parts === 'undefined' ? null : t && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
973
|
+
const word0 = eco[0]?.t === 'word' ? eco[0].text.toLowerCase() : '';
|
|
974
|
+
let said = eco.length === 1 && eco[0].t === 'word' ? word0 : '';
|
|
975
|
+
// ".NET" is read as a dot and the word NET.
|
|
976
|
+
if (eco.length === 2 && eco[0].t === 'sym' && eco[0].text === '.' && eco[1].t === 'word' && eco[1].text.toLowerCase() === 'net') said = 'dotnet';
|
|
977
|
+
if (word0 === 'nuget') {
|
|
978
|
+
// NuGet "<package>" version "<version>": the package and its exact version, so every build gets the same code.
|
|
979
|
+
const pkg = eco[1]?.t === 'str' ? plain(eco[1]) : null;
|
|
980
|
+
const ver = isWord(eco[2], 'version') && eco[3]?.t === 'str' ? plain(eco[3]) : null;
|
|
981
|
+
if (!pkg || !ver || eco.length !== 4 || !/^[A-Za-z0-9_.-]+$/.test(pkg) || !/^\d+(\.\d+){1,3}([-+][\w.-]+)?$/.test(ver)) fail('TC108', 'Name the NuGet package and its version: Use "Humanizer.NumberToWordsExtension" from NuGet "Humanizer.Core" version "2.14.1" as words.');
|
|
982
|
+
said = 'nuget';
|
|
983
|
+
modTs = modTs.slice(0, fromAt);
|
|
984
|
+
ecosystem = said;
|
|
985
|
+
var nuget = { package: pkg, version: ver };
|
|
986
|
+
} else {
|
|
987
|
+
if (!['python', 'npm', 'dotnet'].includes(said)) fail('TC108', `A library comes from Python, npm, .NET, or NuGet, for example: Use csv from Python as csv, Use "date-fns" from npm as dates, or Use "System.IO.Path" from .NET as paths.`);
|
|
988
|
+
ecosystem = said;
|
|
989
|
+
modTs = modTs.slice(0, fromAt);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
if (ecosystem === 'dotnet' || ecosystem === 'nuget') {
|
|
993
|
+
const t = modTs[0];
|
|
994
|
+
const type = modTs.length === 1 && t.t === 'str' && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
995
|
+
if (type == null || !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)+$/.test(type)) fail('TC108', 'Write a .NET type with its namespace, in quotes, for example: Use "System.IO.Path" from .NET as paths.');
|
|
996
|
+
if (asAt < 0) fail('TC108', `Give the type a name to use in Thunder: Use "${type}" from ${ecosystem === 'nuget' ? 'NuGet' : '.NET'} … as <name>.`);
|
|
997
|
+
return { k: 'use', module: type, ecosystem, ...(ecosystem === 'nuget' ? nuget : {}), ...nameWords(rest.slice(asAt + 1), line, '"Use"'), line };
|
|
998
|
+
}
|
|
999
|
+
if (ecosystem === 'npm' || modTs[0]?.t === 'str') {
|
|
1000
|
+
const t = modTs[0];
|
|
1001
|
+
const pkg = modTs.length === 1 && t.t === 'str' && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
1002
|
+
if (pkg == null || !/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(\/[\w.-]+)*$|^node:[a-z_/]+$/i.test(pkg)) fail('TC108', 'Write an npm package in quotes, for example: Use "date-fns" from npm as dates.');
|
|
1003
|
+
if (ecosystem !== 'npm') fail('TC108', `Say where "${pkg}" comes from: Use "${pkg}" from npm as <name>.`);
|
|
1004
|
+
if (asAt < 0) fail('TC108', `Give the package a name to use in Thunder: Use "${pkg}" from npm as <name>.`);
|
|
1005
|
+
return { k: 'use', module: pkg, ecosystem, ...nameWords(rest.slice(asAt + 1), line, '"Use"'), line };
|
|
1006
|
+
}
|
|
775
1007
|
const module = modTs.map((t) => (t.t === 'word' ? t.text : t.t === 'sym' && t.text === '.' ? '.' : '\u0000')).join('');
|
|
776
|
-
if (!module || module.includes('\u0000') || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module)) fail('TC108', 'Write "Use <python module> as <name>", for example: Use csv as csv.');
|
|
1008
|
+
if (!module || module.includes('\u0000') || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module)) fail('TC108', 'Write "Use <python module> as <name>", for example: Use csv as csv. For npm: Use "date-fns" from npm as dates.');
|
|
777
1009
|
const alias = asAt < 0 ? { name: module.split('.')[0].toLowerCase(), text: module.split('.')[0] } : nameWords(rest.slice(asAt + 1), line, '"Use"');
|
|
778
|
-
return { k: 'use', module, ...alias, line };
|
|
1010
|
+
return { k: 'use', module, ecosystem, ...alias, line };
|
|
779
1011
|
}
|
|
780
1012
|
if (w0 === 'test') {
|
|
781
1013
|
if (!ctx.top) fail('TC402', 'A "Test" block must be written at the left edge of the file.');
|
|
@@ -901,7 +1133,7 @@ function parseScreen(n, ep, names, diagnostics) {
|
|
|
901
1133
|
while (kids[k] && isWord(kids[k].tokens[0], 'receive')) {
|
|
902
1134
|
const kid = kids[k];
|
|
903
1135
|
try {
|
|
904
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.
|
|
1136
|
+
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 })));
|
|
905
1137
|
} catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
906
1138
|
k++;
|
|
907
1139
|
}
|
|
@@ -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
|
+
}
|
package/src/core/project.mjs
CHANGED
|
@@ -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';
|
|
@@ -16,13 +17,16 @@ import { writeJava, javaDiagnostics } from './java-run.mjs';
|
|
|
16
17
|
import { writeReact, reactDiagnostics } from './react-run.mjs';
|
|
17
18
|
import { hasScreens } from './target-react.mjs';
|
|
18
19
|
import { diag } from './diagnostics.mjs';
|
|
20
|
+
import { npmRefusals, dotnetRefusals } from './target-typescript.mjs';
|
|
19
21
|
|
|
20
22
|
/** The languages a Thunder Core project can be compiled to. */
|
|
21
23
|
export const TARGETS = ['python', 'typescript', 'csharp', 'rust', 'go', 'java', 'react'];
|
|
22
24
|
/** How a target is named to people. */
|
|
23
25
|
export const TARGET_NAMES = { python: 'Python', typescript: 'TypeScript', csharp: 'C#', rust: 'Rust', go: 'Go', java: 'Java', react: 'React' };
|
|
24
26
|
|
|
25
|
-
|
|
27
|
+
import { PROJECT_FILE, findProjectRoot } from './project-root.mjs';
|
|
28
|
+
|
|
29
|
+
export { PROJECT_FILE, findProjectRoot };
|
|
26
30
|
|
|
27
31
|
/** A tiny TOML subset: [sections], key = "text" | number | true | false, and # comments. */
|
|
28
32
|
export function parseToml(text) {
|
|
@@ -41,18 +45,6 @@ export function parseToml(text) {
|
|
|
41
45
|
return out;
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
/** The nearest folder at or above `start` that holds a thunder.toml, or null. */
|
|
45
|
-
export function findProjectRoot(start) {
|
|
46
|
-
let dir = resolve(start);
|
|
47
|
-
if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
|
|
48
|
-
for (;;) {
|
|
49
|
-
if (existsSync(join(dir, PROJECT_FILE))) return dir;
|
|
50
|
-
const up = dirname(dir);
|
|
51
|
-
if (up === dir) return null;
|
|
52
|
-
dir = up;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
48
|
export function loadProject(root) {
|
|
57
49
|
const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
|
|
58
50
|
const build = toml.build ?? {};
|
|
@@ -92,8 +84,10 @@ export function buildProject({ root, single = null, includeTests = false, write
|
|
|
92
84
|
const tgt = target ?? cfg?.target ?? 'python';
|
|
93
85
|
if (!TARGETS.includes(tgt)) throw new Error(`there is no target "${tgt}". Thunder Core builds ${TARGETS.join(', ')} (python is the default).`);
|
|
94
86
|
const srcFiles = cfg ? thunderFiles(join(cfg.root, cfg.src)) : [];
|
|
95
|
-
|
|
96
|
-
const
|
|
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)) : [];
|
|
97
91
|
const outDir = join(base, cfg && (target == null || target === cfg.target) ? cfg.out : `generated/${tgt}`);
|
|
98
92
|
const results = [];
|
|
99
93
|
const used = new Set();
|
|
@@ -104,7 +98,9 @@ export function buildProject({ root, single = null, includeTests = false, write
|
|
|
104
98
|
results.push({ ...r, path: f, rel, module: uniqueModule(f), kind: 'src' });
|
|
105
99
|
}
|
|
106
100
|
const srcOk = results.filter((r) => r.ok);
|
|
107
|
-
|
|
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 : []) {
|
|
108
104
|
const rel = relative(base, f).split('\\').join('/');
|
|
109
105
|
const r = compileCore(readFileSync(f, 'utf8'), { file: rel, imported: srcOk, srcModules: srcOk.map((x) => x.module) });
|
|
110
106
|
results.push({ ...r, path: f, rel, module: uniqueModule(f, 'tests_'), kind: 'test' });
|
|
@@ -114,6 +110,8 @@ export function buildProject({ root, single = null, includeTests = false, write
|
|
|
114
110
|
if (tgt === 'csharp') for (const r of results.filter((x) => x.ok)) { const d = csharpDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
115
111
|
if (tgt === 'rust') for (const r of results.filter((x) => x.ok)) { const d = rustDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
116
112
|
if (tgt === 'go') for (const r of results.filter((x) => x.ok)) { const d = goDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
113
|
+
// An npm package (Use "<package>" from npm) exists only for the TypeScript target (TC408).
|
|
114
|
+
if (tgt === 'python') for (const r of results.filter((x) => x.ok)) { const d = [...npmRefusals(r.info, 'Python', diag), ...dotnetRefusals(r.info, 'Python', diag)]; if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
117
115
|
// The same for Java: Python modules exist only for the Python target.
|
|
118
116
|
if (tgt === 'java') for (const r of results.filter((x) => x.ok)) { const d = javaDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
119
117
|
const entryPath = single ? resolve(single) : cfg?.entry ? join(cfg.root, cfg.entry) : join(base, cfg?.src ?? '.', 'main.thunder');
|
|
@@ -160,8 +158,10 @@ export function findPython() {
|
|
|
160
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.' };
|
|
161
159
|
}
|
|
162
160
|
|
|
163
|
-
export function runPython(python, outDir, script, cwd) {
|
|
164
|
-
|
|
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);
|
|
165
165
|
}
|
|
166
166
|
|
|
167
167
|
export function newProject(dir, { force = false } = {}) {
|
package/src/core/react-run.mjs
CHANGED
|
@@ -5,15 +5,15 @@
|
|
|
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 } 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 = 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
|
-
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
16
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
17
17
|
const main = result.program.main ?? [];
|
|
18
18
|
if (main.length && hasScreens(result.info)) {
|
|
19
19
|
out.push(diag('TC406', main[0].line, 'A React app shows its screens; the steps outside a screen have nowhere to run.',
|