@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.
Files changed (81) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +10 -3
  3. package/dist/core.cjs +264 -47
  4. package/dist/index.cjs +9118 -1077
  5. package/dist/learn.cjs +1419 -90
  6. package/package.json +1 -1
  7. package/src/ai.mjs +2 -1
  8. package/src/atlas.mjs +2 -1
  9. package/src/behaviour.mjs +246 -0
  10. package/src/cli-main.mjs +3015 -0
  11. package/src/cli.mjs +9 -2799
  12. package/src/conflict.mjs +0 -0
  13. package/src/core/ThunderDotnet.cs +195 -0
  14. package/src/core/check.mjs +316 -10
  15. package/src/core/cli.mjs +67 -10
  16. package/src/core/csharp-run.mjs +29 -8
  17. package/src/core/diagnostics.mjs +12 -1
  18. package/src/core/engine-core.mjs +161 -20
  19. package/src/core/engine-values.mjs +1 -0
  20. package/src/core/engine.mjs +131 -7
  21. package/src/core/go-run.mjs +3 -2
  22. package/src/core/index.mjs +6 -2
  23. package/src/core/java-run.mjs +3 -3
  24. package/src/core/kind.mjs +45 -0
  25. package/src/core/lexer.mjs +16 -2
  26. package/src/core/parser.mjs +254 -22
  27. package/src/core/project-root.mjs +18 -0
  28. package/src/core/project.mjs +18 -18
  29. package/src/core/react-run.mjs +3 -3
  30. package/src/core/runtime-go/thunder_runtime.go +269 -1
  31. package/src/core/runtime-npm.mjs +79 -0
  32. package/src/core/runtime-python.mjs +365 -3
  33. package/src/core/runtime-react.mjs +2 -1
  34. package/src/core/runtime-typescript.mjs +155 -6
  35. package/src/core/rust-run.mjs +3 -2
  36. package/src/core/serving.mjs +12 -0
  37. package/src/core/store-format.mjs +110 -0
  38. package/src/core/target-csharp.mjs +5 -1
  39. package/src/core/target-go.mjs +11 -4
  40. package/src/core/target-python.mjs +39 -6
  41. package/src/core/target-rust.mjs +1 -1
  42. package/src/core/target-typescript.mjs +95 -7
  43. package/src/core/typescript-run.mjs +14 -7
  44. package/src/core-changes-fs.mjs +28 -0
  45. package/src/core-changes.d.mts +67 -0
  46. package/src/core-changes.mjs +603 -0
  47. package/src/core-rules.mjs +146 -0
  48. package/src/core-services.d.mts +4 -0
  49. package/src/core-services.mjs +49 -0
  50. package/src/decision.mjs +2 -1
  51. package/src/distributed.mjs +2 -1
  52. package/src/emit.mjs +2 -2
  53. package/src/evidence.mjs +28 -0
  54. package/src/examples.d.mts +21 -0
  55. package/src/examples.mjs +175 -0
  56. package/src/focus.mjs +2 -1
  57. package/src/index.d.ts +4 -0
  58. package/src/index.mjs +4 -0
  59. package/src/intent-atlas.mjs +4 -3
  60. package/src/mcp.mjs +52 -6
  61. package/src/passport-fs.mjs +2 -1
  62. package/src/passport.mjs +2 -1
  63. package/src/privacy.mjs +2 -1
  64. package/src/program.d.mts +4 -0
  65. package/src/program.mjs +4 -0
  66. package/src/read-repo-fs.mjs +2 -1
  67. package/src/read-repo.mjs +3 -2
  68. package/src/report.mjs +3 -2
  69. package/src/review.mjs +71 -4
  70. package/src/select.mjs +2 -1
  71. package/src/semantic-diff.mjs +7 -6
  72. package/src/system.mjs +3 -2
  73. package/src/text-order.mjs +6 -0
  74. package/src/thunderize.mjs +2 -1
  75. package/src/trace-cli.mjs +8 -3
  76. package/src/trace-data.mjs +3 -2
  77. package/src/trace-fs.mjs +29 -3
  78. package/src/trace.mjs +27 -10
  79. package/src/write-across-cli.mjs +22 -4
  80. package/src/write-across.mjs +2 -1
  81. package/syntaxes/thunder.tmLanguage.json +196 -0
@@ -754,7 +754,8 @@ def _callers(tb):
754
754
 
755
755
 
756
756
  def describe_error(error):
757
- src, line, from_python = thunder_place(error.__traceback__)
757
+ placed = getattr(error, "thunder_where", None) # a stored list's file: its Store line
758
+ src, line, from_python = (*placed, False) if placed else thunder_place(error.__traceback__)
758
759
  message = explain(error)
759
760
  code = _code(error)
760
761
  # Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
@@ -769,15 +770,376 @@ def describe_error(error):
769
770
  return "%s: %s [%s]" % (where, message, code)
770
771
 
771
772
 
772
- def run(main, file=None):
773
- """Runs a generated program; an error is reported against the Thunder line, then the program exits with 1."""
773
+ # ── Stored lists (Store habits as a list of Habit): data/<name>.json, the format of store-format.mjs ─────────────
774
+ _STORES = []
775
+ _STORE_KINDS = {"whole": "a whole number", "number": "a number", "money": "money", "text": "text", "bool": "yes or no", "date": "a date"}
776
+
777
+
778
+ def new_store(source, line, name, cls, kinds):
779
+ """A stored list: empty until the program starts (run fills it), saved when the program finishes well.
780
+ A file it can't read is reported at its Store line (source, line), as on the Thunder engine and TypeScript."""
781
+ items = []
782
+ _STORES.append((source, line, name, cls, kinds, items))
783
+ return items
784
+
785
+
786
+ def _store_encode(v, kind):
787
+ if kind.startswith("?"):
788
+ return None if v is None else _store_encode(v, kind[1:])
789
+ if v is None:
790
+ return None
791
+ if kind == "whole":
792
+ return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
793
+ if kind == "number":
794
+ return str(v)
795
+ if kind == "money":
796
+ return str(v).replace("$", "")
797
+ if kind == "date":
798
+ return v.isoformat()
799
+ return v
800
+
801
+
802
+ def _store_decode(x, kind, where, has="the file has"):
803
+ if kind.startswith("?"):
804
+ return None if x is None else _store_decode(x, kind[1:], where, has)
805
+ def bad():
806
+ return ConversionFailed("%s should be %s, but %s %s." % (where, _STORE_KINDS.get(kind, "a value"), has, json.dumps(x)))
807
+ if kind == "whole":
808
+ if isinstance(x, int) and not isinstance(x, bool):
809
+ return x
810
+ if isinstance(x, str) and re.fullmatch(r"-?\d+", x):
811
+ return int(x)
812
+ raise bad()
813
+ if kind == "number":
814
+ if isinstance(x, int) and not isinstance(x, bool):
815
+ return x
816
+ if isinstance(x, str):
817
+ if re.fullmatch(r"-?\d+", x):
818
+ return int(x)
819
+ try:
820
+ return Decimal(x)
821
+ except InvalidOperation:
822
+ raise bad()
823
+ raise bad()
824
+ if kind == "money":
825
+ try:
826
+ return Money(Decimal(str(x)))
827
+ except (InvalidOperation, ValueError):
828
+ raise bad()
829
+ if kind == "text":
830
+ if isinstance(x, str):
831
+ return x
832
+ raise bad()
833
+ if kind == "bool":
834
+ if isinstance(x, bool):
835
+ return x
836
+ raise bad()
837
+ if kind == "date":
838
+ try:
839
+ return date.fromisoformat(x)
840
+ except (TypeError, ValueError):
841
+ raise bad()
842
+ return x
843
+
844
+
845
+ def _store_file(name):
846
+ return "data/%s.json" % name
847
+
848
+
849
+ def _fill_stores():
850
+ import os
851
+ for source, line, name, cls, kinds, items in _STORES:
852
+ path = _store_file(name)
853
+ if not os.path.exists(path):
854
+ continue
855
+ try:
856
+ items[:] = _read_store(path, cls, kinds)
857
+ except Exception as error: # noqa: BLE001 - reported at the Store line
858
+ error.thunder_where = (source, line)
859
+ raise
860
+
861
+
862
+ def _read_store(path, cls, kinds):
863
+ """The records in a store's file; a problem names the item and field."""
864
+ with open(path, encoding="utf-8") as fh:
865
+ text = fh.read()
866
+ try:
867
+ rows = json.loads(text)
868
+ except ValueError as error:
869
+ raise ConversionFailed("%s is not a list Thunder can read (%s)." % (path, error))
870
+ if not isinstance(rows, list):
871
+ raise ConversionFailed("%s should hold a list, written [ … ]." % path)
872
+ return [_record_from(row, cls, kinds, "%s, item %d" % (path, i + 1)) for i, row in enumerate(rows)]
873
+
874
+
875
+ def _record_from(row, cls, kinds, where, has="the file has"):
876
+ """A record from a JSON object, each field read by its kind; a problem names where it is and the field."""
877
+ if not isinstance(row, dict):
878
+ raise ConversionFailed("%s should be a record, written { … }." % where)
879
+ given = {}
880
+ for field_name, kind in kinds.items():
881
+ if field_name not in row:
882
+ if kind.startswith("?"):
883
+ given[field_name] = None
884
+ continue
885
+ raise ConversionFailed('%s has no "%s".' % (where, field_name))
886
+ given[field_name] = _store_decode(row[field_name], kind, '%s, "%s"' % (where, field_name), has)
887
+ return cls(**given)
888
+
889
+
890
+ def _save_stores():
891
+ import os
892
+ for source, line, name, cls, kinds, items in _STORES:
893
+ path = _store_file(name)
894
+ rows = [{f: _store_encode(getattr(item, f), kind) for f, kind in kinds.items()} for item in items]
895
+ os.makedirs(os.path.dirname(path), exist_ok=True)
896
+ with open(path + ".saving", "w", encoding="utf-8") as fh:
897
+ fh.write(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
898
+ os.replace(path + ".saving", path)
899
+
900
+
901
+ # ── HTTP (When someone calls GET /habits: and the answer from GET "…"): data in the stored-list format ──────────
902
+ class CallFailed(ThunderError):
903
+ code = "TC510"
904
+
905
+
906
+ _ANSWER_STATUS = [None]
907
+
908
+
909
+ def answer_status(status):
910
+ """Give … with status 201: the status this request answers with (a direct call in a test ignores it)."""
911
+ _ANSWER_STATUS[0] = status
912
+
913
+
914
+ def stop_with(message, status):
915
+ """Stop with "…" and status 404: a Stop that an endpoint answers with that status."""
916
+ error = Stop(message)
917
+ error.status = status
918
+ return error
919
+
920
+
921
+ def _data_ready(v):
922
+ """A value as JSON data, written by its kind: whole numbers as numbers (text when too large), numbers and money as
923
+ exact text, dates as "2026-11-28", records as objects. The same on every target."""
924
+ if v is None or isinstance(v, (bool, str)):
925
+ return v
926
+ if isinstance(v, int):
927
+ return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
928
+ if isinstance(v, Decimal):
929
+ return str(v)
930
+ if isinstance(v, Money):
931
+ return str(v).replace("$", "", 1)
932
+ if isinstance(v, date):
933
+ return v.isoformat()
934
+ if isinstance(v, (list, tuple)):
935
+ return [_data_ready(x) for x in v]
936
+ if isinstance(v, dict):
937
+ out = {}
938
+ for k, x in v.items():
939
+ if not isinstance(k, str):
940
+ raise KindMismatch("A JSON object's keys are text, but one is %s." % show(k))
941
+ out[k] = _data_ready(x)
942
+ return out
943
+ if is_dataclass(v):
944
+ alts = getattr(type(v), "__thunder_alts__", None)
945
+ if alts is not None: # an alternative of a data type: "which" and the fields it has
946
+ keep = ("which",) + tuple(alts.get(v.which, ()))
947
+ return {name: _data_ready(getattr(v, name)) for name in keep}
948
+ return {f.name: _data_ready(getattr(v, f.name)) for f in fields(v)}
949
+ raise KindMismatch("%s can't be sent as JSON." % show(v))
950
+
951
+
952
+ def data_json(v):
953
+ return json.dumps(_data_ready(v), ensure_ascii=False, separators=(",", ":"))
954
+
955
+
956
+ def _unreachable_reason(error):
957
+ """Why a service could not be reached, in words that are the same on every target."""
958
+ import socket
959
+ reason = getattr(error, "reason", error)
960
+ if isinstance(reason, (TimeoutError, socket.timeout)):
961
+ return "no answer within 30 seconds"
962
+ if isinstance(reason, ConnectionRefusedError):
963
+ return "nothing is answering there"
964
+ if isinstance(reason, socket.gaierror):
965
+ return "the address could not be found"
966
+ return str(reason)
967
+
968
+
969
+ def http_call(method, url, body, read_as):
970
+ """the answer from GET "…": the answer's text, or records read from it (read_as = (record, kinds, many))."""
971
+ import urllib.error
972
+ import urllib.request
973
+ where = "The answer from %s %s" % (method, url)
974
+ data = data_json(body).encode("utf-8") if body is not None else None
975
+ headers = {"Accept": "application/json"}
976
+ if data is not None:
977
+ headers["Content-Type"] = "application/json"
978
+ request = urllib.request.Request(url, data=data, method=method, headers=headers)
979
+ try:
980
+ with urllib.request.urlopen(request, timeout=30) as reply:
981
+ text = reply.read().decode("utf-8")
982
+ except urllib.error.HTTPError as error:
983
+ raise CallFailed("%s %s answered %d: %s" % (method, url, error.code, error.read().decode("utf-8", "replace").strip()[:300]))
984
+ except (urllib.error.URLError, OSError, ValueError) as error:
985
+ raise CallFailed("%s %s could not be reached (%s)." % (method, url, _unreachable_reason(error)))
986
+ if read_as is None:
987
+ return text
988
+ cls, kinds, many = read_as
989
+ try:
990
+ answer = json.loads(text)
991
+ except ValueError:
992
+ raise ConversionFailed("%s is not JSON Thunder can read." % where)
993
+ if many:
994
+ if not isinstance(answer, list):
995
+ raise ConversionFailed("%s should be a list, written [ … ]." % where)
996
+ return [_record_from(row, cls, kinds, "%s, item %d" % (where, i + 1), "it has") for i, row in enumerate(answer)]
997
+ return _record_from(answer, cls, kinds, where, "it has")
998
+
999
+
1000
+ def _input_value(raw, kind, where, from_text):
1001
+ """A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false."""
1002
+ plain = kind.lstrip("?")
1003
+ if from_text and plain == "bool" and isinstance(raw, str) and raw.lower() in ("yes", "no", "true", "false"):
1004
+ raw = raw.lower() in ("yes", "true")
1005
+ return _store_decode(raw, kind, where, "the request has")
1006
+
1007
+
1008
+ def _serve(routes):
1009
+ """Answer requests on this machine, one at a time, until stopped (Ctrl+C). Stored lists are saved after each
1010
+ request that finishes well."""
1011
+ import os
1012
+ import urllib.parse
1013
+ from http.server import BaseHTTPRequestHandler, HTTPServer
1014
+
1015
+ host = os.environ.get("THUNDER_HOST", "127.0.0.1")
1016
+ port = int(os.environ.get("THUNDER_PORT", "8080"))
1017
+ table = []
1018
+ for method, path, handler, inputs in routes:
1019
+ parts = [p for p in path.split("/") if p]
1020
+ table.append((method, path, parts, handler, inputs))
1021
+
1022
+ def match(parts, request_parts):
1023
+ if len(parts) != len(request_parts):
1024
+ return None
1025
+ found = {}
1026
+ for want, got in zip(parts, request_parts):
1027
+ if want.startswith("{") and want.endswith("}"):
1028
+ found[want[1:-1].strip().lower()] = urllib.parse.unquote(got)
1029
+ elif want != got:
1030
+ return None
1031
+ return found
1032
+
1033
+ class Handler(BaseHTTPRequestHandler):
1034
+ server_version = "Thunder"
1035
+
1036
+ def answer(self, status, value):
1037
+ data = data_json(value).encode("utf-8")
1038
+ self.send_response(status)
1039
+ self.send_header("Content-Type", "application/json; charset=utf-8")
1040
+ self.send_header("Content-Length", str(len(data)))
1041
+ self.end_headers()
1042
+ self.wfile.write(data)
1043
+ print("%s %s -> %d" % (self.command, self.path, status), flush=True)
1044
+
1045
+ def handle_any(self):
1046
+ url = urllib.parse.urlsplit(self.path)
1047
+ request_parts = [p for p in url.path.split("/") if p]
1048
+ query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()}
1049
+ chosen, methods = None, []
1050
+ for method, path, parts, handler, inputs in table:
1051
+ found = match(parts, request_parts)
1052
+ if found is None:
1053
+ continue
1054
+ methods.append(method)
1055
+ if method == self.command:
1056
+ chosen = (method, path, handler, inputs, found)
1057
+ if chosen is None:
1058
+ if methods:
1059
+ return self.answer(405, {"problem": "%s answers only %s." % (url.path, ", ".join(methods))})
1060
+ return self.answer(404, {"problem": "Nothing here answers %s %s." % (self.command, url.path)})
1061
+ method, path, handler, inputs, found = chosen
1062
+ body = {}
1063
+ length = int(self.headers.get("Content-Length") or 0)
1064
+ if length:
1065
+ try:
1066
+ body = json.loads(self.rfile.read(length).decode("utf-8"))
1067
+ except ValueError:
1068
+ return self.answer(400, {"problem": "The request's body is not JSON Thunder can read."})
1069
+ if not isinstance(body, dict):
1070
+ return self.answer(400, {"problem": "The request's body should be a JSON object, written { … }."})
1071
+ args = {}
1072
+ try:
1073
+ for text, py_name, kind, source, has_default in inputs:
1074
+ key = text.lower()
1075
+ if source == "path":
1076
+ args[py_name] = _input_value(found[key], kind, '"%s"' % text, True)
1077
+ elif key in query:
1078
+ args[py_name] = _input_value(query[key], kind, '"%s"' % text, True)
1079
+ elif py_name in query:
1080
+ args[py_name] = _input_value(query[py_name], kind, '"%s"' % text, True)
1081
+ elif text in body or key in body or py_name in body:
1082
+ raw = body[text] if text in body else body[key] if key in body else body[py_name]
1083
+ args[py_name] = _input_value(raw, kind, '"%s"' % text, False)
1084
+ elif not has_default:
1085
+ if kind.startswith("?"):
1086
+ args[py_name] = None
1087
+ else:
1088
+ return self.answer(400, {"problem": "%s %s needs %s (%s)." % (method, path, text, _STORE_KINDS.get(kind, kind))})
1089
+ except ThunderError as error:
1090
+ return self.answer(400, {"problem": explain(error)})
1091
+ _ANSWER_STATUS[0] = None
1092
+ try:
1093
+ value = handler(**args)
1094
+ except Stop as error:
1095
+ return self.answer(getattr(error, "status", 400), {"problem": explain(error)})
1096
+ except RuleBroken as error:
1097
+ return self.answer(422, {"problem": explain(error)})
1098
+ except Exception as error: # noqa: BLE001 - reported in Thunder words, the server keeps answering
1099
+ print(describe_error(error), file=sys.stderr, flush=True)
1100
+ return self.answer(500, {"problem": explain(error)})
1101
+ status = _ANSWER_STATUS[0] or 200
1102
+ try:
1103
+ _save_stores()
1104
+ data = data_json(value)
1105
+ except Exception as error: # noqa: BLE001
1106
+ print(describe_error(error), file=sys.stderr, flush=True)
1107
+ return self.answer(500, {"problem": explain(error)})
1108
+ self.answer(status, json.loads(data) if data != "null" else None)
1109
+
1110
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
1111
+
1112
+ def log_message(self, *args):
1113
+ pass
1114
+
1115
+ server = HTTPServer((host, port), Handler)
1116
+ print("Thunder is answering on http://%s:%d" % (host, port), flush=True)
1117
+ for method, path, handler, inputs in routes:
1118
+ print(" %s %s" % (method, path), flush=True)
1119
+ print("Press Ctrl+C to stop.", flush=True)
1120
+ try:
1121
+ server.serve_forever()
1122
+ except KeyboardInterrupt:
1123
+ print("Stopped answering.", flush=True)
1124
+ finally:
1125
+ server.server_close()
1126
+
1127
+
1128
+ def run(main, file=None, routes=None):
1129
+ """Runs a generated program; an error is reported against the Thunder line, then the program exits with 1.
1130
+ Stored lists are filled first and saved only when the program finishes well. With endpoints, it then answers
1131
+ requests until stopped."""
774
1132
  try:
1133
+ _fill_stores()
775
1134
  main()
1135
+ _save_stores()
776
1136
  except KeyboardInterrupt:
777
1137
  raise
778
1138
  except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
779
1139
  print(describe_error(error), file=sys.stderr)
780
1140
  sys.exit(1)
1141
+ if routes:
1142
+ _serve(routes)
781
1143
 
782
1144
 
783
1145
  def run_tests(modules):
@@ -6,6 +6,7 @@
6
6
  import { readFileSync } from 'node:fs';
7
7
  import * as VALUES from './engine-values.mjs';
8
8
  import * as SCREEN from './screen-values.mjs';
9
+ import { byText } from '../text-order.mjs';
9
10
 
10
11
  const VALUES_SOURCE = readFileSync(new URL('./engine-values.mjs', import.meta.url), 'utf8');
11
12
  // (Its import line names what engine-values.mjs already defined above it.)
@@ -120,7 +121,7 @@ const isClass = (v) => typeof v === 'function' && /^class\b/.test(Function.proto
120
121
 
121
122
  function declarations() {
122
123
  const L = ['// thunder_runtime.d.mts: types for thunder_runtime.mjs (written by the Thunder compiler).', '// Thunder values are checked when the program runs; to TypeScript they are of any kind.', ''];
123
- for (const [name, v] of Object.entries({ ...VALUES, ...SCREEN }).sort(([a], [b]) => a.localeCompare(b))) {
124
+ for (const [name, v] of Object.entries({ ...VALUES, ...SCREEN }).sort(([a], [b]) => byText(a, b))) {
124
125
  if (isClass(v)) L.push(`export declare class ${name} { constructor(...args: any[]); [key: string]: any; static [key: string]: any; }`);
125
126
  else if (typeof v === 'function') L.push(`export declare function ${name}(...args: any[]): any;`);
126
127
  else L.push(`export declare const ${name}: any;`);
@@ -6,14 +6,25 @@
6
6
  // Thunder engine, and compiled TypeScript, and requires the same output from all three.
7
7
  import { readFileSync } from 'node:fs';
8
8
  import * as VALUES from './engine-values.mjs';
9
+ import { byText } from '../text-order.mjs';
9
10
 
10
11
  const VALUES_SOURCE = readFileSync(new URL('./engine-values.mjs', import.meta.url), 'utf8');
12
+ // npm packages (Use "<package>" from npm): the boundary between Thunder values and JavaScript values. Its import
13
+ // line is dropped: in thunder_runtime.mjs the names it uses are the runtime's own.
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, '');
11
20
 
12
21
  /** The Node part: everything here is about running, not about what a value means. */
13
22
  const NODE_PART = `
14
23
  // ── Running compiled TypeScript: frames (for error lines), output, files, and the program or its tests ───────────
15
- import { readFileSync as nodeReadFile, realpathSync as nodeRealpath } from 'node:fs';
16
- 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';
17
28
 
18
29
  const frames = [];
19
30
  let aborted = false;
@@ -76,7 +87,145 @@ export function isEntry(url) {
76
87
  const strip = (p) => real(p).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');
77
88
  return strip(decodeURIComponent(new URL(url).pathname)) === strip(nodeResolve(arg));
78
89
  }
79
- 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
+ }
80
229
  /** Every Test block, the way run_tests.py runs them: one line per test, then the totals. */
81
230
  export function runTests(modules) {
82
231
  if (aborted) return;
@@ -93,21 +242,21 @@ export function runTests(modules) {
93
242
  }
94
243
  `;
95
244
 
96
- const NODE_EXPORTS = { functions: ['enterFrame', 'enterCall', 'leave', 'topFrame', 'fail', 'keyAt', 'say', 'readText', 'recordKind', 'setAttr', 'setField', 'newRecord', 'init', 'isEntry', 'run', 'runTests'] };
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'] };
97
246
 
98
247
  const HEADER = `// thunder_runtime.mjs: written by the Thunder compiler next to compiled TypeScript. Standard library only.
99
248
  // The values and rules here are the Thunder engine's own (engine-values.mjs), so compiled TypeScript, the Thunder
100
249
  // engine, and compiled Python say the same thing for the same program.
101
250
  `;
102
251
 
103
- export const TS_RUNTIME = `${HEADER}\n${VALUES_SOURCE.trimEnd()}\n${NODE_PART}`;
252
+ export const TS_RUNTIME = `${HEADER}\n${VALUES_SOURCE.trimEnd()}\n${STORE_SOURCE.trimEnd()}\n${NODE_PART}\n${NPM_SOURCE}`;
104
253
 
105
254
  const isClass = (v) => typeof v === 'function' && /^class\b/.test(Function.prototype.toString.call(v));
106
255
 
107
256
  /** Declarations for the runtime, made from its exports: every function takes and gives values of any kind. */
108
257
  function declarations() {
109
258
  const L = ['// thunder_runtime.d.mts: types for thunder_runtime.mjs (written by the Thunder compiler).', '// Thunder values are checked when the program runs; to TypeScript they are of any kind.', ''];
110
- for (const [name, v] of Object.entries(VALUES).sort(([a], [b]) => a.localeCompare(b))) {
259
+ for (const [name, v] of Object.entries(VALUES).sort(([a], [b]) => byText(a, b))) {
111
260
  if (isClass(v)) L.push(`export declare class ${name} { constructor(...args: any[]); [key: string]: any; static [key: string]: any; }`);
112
261
  else if (typeof v === 'function') L.push(`export declare function ${name}(...args: any[]): any;`);
113
262
  else L.push(`export declare const ${name}: any;`);
@@ -10,6 +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, storeRefusals, httpRefusals } from './target-typescript.mjs';
13
14
  import { diag } from './diagnostics.mjs';
14
15
 
15
16
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -21,9 +22,9 @@ export const rustModule = (m) => `m_${m}`;
21
22
 
22
23
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
23
24
  export function rustDiagnostics(result) {
24
- return 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,
25
26
  `"${u.module}" is a Python module, and this program is compiled to Rust, which cannot use it.`,
26
- 'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
27
+ 'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
27
28
  }
28
29
 
29
30
  /** Compile checked results to Rust: { [rustModule]: text }. Test modules see every src module's names. */
@@ -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
+ }