bonescript-compiler 0.5.3 → 0.5.5

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 (201) hide show
  1. package/LICENSE +21 -21
  2. package/dist/algorithm_catalog.js +166 -166
  3. package/dist/cli.d.ts +1 -2
  4. package/dist/cli.js +617 -75
  5. package/dist/cli.js.map +1 -1
  6. package/dist/emit_capability.d.ts +0 -13
  7. package/dist/emit_capability.js +134 -296
  8. package/dist/emit_capability.js.map +1 -1
  9. package/dist/emit_composition.js +3 -37
  10. package/dist/emit_composition.js.map +1 -1
  11. package/dist/emit_deploy.js +167 -165
  12. package/dist/emit_deploy.js.map +1 -1
  13. package/dist/emit_events.d.ts +0 -1
  14. package/dist/emit_events.js +275 -325
  15. package/dist/emit_events.js.map +1 -1
  16. package/dist/emit_extras.js +5 -3
  17. package/dist/emit_extras.js.map +1 -1
  18. package/dist/emit_full.js +112 -272
  19. package/dist/emit_full.js.map +1 -1
  20. package/dist/emit_maintenance.js +249 -249
  21. package/dist/emit_nakama.d.ts +23 -0
  22. package/dist/emit_nakama.js +510 -0
  23. package/dist/emit_nakama.js.map +1 -0
  24. package/dist/emit_runtime.d.ts +11 -17
  25. package/dist/emit_runtime.js +688 -29
  26. package/dist/emit_runtime.js.map +1 -1
  27. package/dist/emit_sourcemap.js +66 -66
  28. package/dist/emit_tests.js +12 -47
  29. package/dist/emit_tests.js.map +1 -1
  30. package/dist/emit_websocket.js +3 -0
  31. package/dist/emit_websocket.js.map +1 -1
  32. package/dist/emitter.js +49 -94
  33. package/dist/emitter.js.map +1 -1
  34. package/dist/extension_manager.d.ts +2 -2
  35. package/dist/extension_manager.js +20 -9
  36. package/dist/extension_manager.js.map +1 -1
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.js +3 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/ir.d.ts +0 -4
  41. package/dist/lowering.d.ts +14 -5
  42. package/dist/lowering.js +417 -66
  43. package/dist/lowering.js.map +1 -1
  44. package/dist/module_loader.d.ts +2 -2
  45. package/dist/module_loader.js +23 -20
  46. package/dist/module_loader.js.map +1 -1
  47. package/dist/optimizer.js +3 -6
  48. package/dist/optimizer.js.map +1 -1
  49. package/dist/scaffold.d.ts +2 -2
  50. package/dist/scaffold.js +319 -315
  51. package/dist/scaffold.js.map +1 -1
  52. package/dist/solver.js +1 -1
  53. package/dist/solver.js.map +1 -1
  54. package/dist/source_map.js.map +1 -0
  55. package/dist/test.js.map +1 -0
  56. package/dist/test_typechecker.d.ts +5 -0
  57. package/dist/test_typechecker.js +126 -0
  58. package/dist/test_typechecker.js.map +1 -0
  59. package/dist/typechecker.d.ts +0 -7
  60. package/dist/typechecker.js +16 -103
  61. package/dist/typechecker.js.map +1 -1
  62. package/dist/verifier.d.ts +1 -5
  63. package/dist/verifier.js +38 -142
  64. package/dist/verifier.js.map +1 -1
  65. package/package.json +53 -62
  66. package/src/algorithm_catalog.ts +345 -345
  67. package/src/ast.d.ts +244 -0
  68. package/src/ast.ts +334 -334
  69. package/src/cli.ts +704 -98
  70. package/src/emit_batch.ts +140 -140
  71. package/src/emit_capability.ts +436 -613
  72. package/src/emit_composition.ts +196 -229
  73. package/src/emit_deploy.ts +190 -187
  74. package/src/emit_events.ts +307 -362
  75. package/src/emit_extras.ts +240 -237
  76. package/src/emit_full.ts +309 -472
  77. package/src/emit_maintenance.ts +459 -459
  78. package/src/emit_nakama.ts +576 -0
  79. package/src/emit_runtime.ts +730 -17
  80. package/src/emit_sourcemap.ts +140 -140
  81. package/src/emit_tests.ts +205 -243
  82. package/src/emit_websocket.ts +229 -226
  83. package/src/emitter.ts +578 -626
  84. package/src/extension_manager.ts +187 -177
  85. package/src/formatter.ts +297 -297
  86. package/src/index.ts +90 -88
  87. package/src/ir.ts +215 -216
  88. package/src/lexer.d.ts +195 -0
  89. package/src/lexer.ts +630 -630
  90. package/src/lowering.ts +556 -168
  91. package/src/module_loader.ts +114 -112
  92. package/src/optimizer.ts +196 -199
  93. package/src/parse_decls.d.ts +13 -0
  94. package/src/parse_decls.ts +409 -409
  95. package/src/parse_decls2.d.ts +13 -0
  96. package/src/parse_decls2.ts +244 -244
  97. package/src/parse_expr.d.ts +7 -0
  98. package/src/parse_expr.ts +197 -197
  99. package/src/parse_types.d.ts +6 -0
  100. package/src/parse_types.ts +54 -54
  101. package/src/parser.d.ts +10 -0
  102. package/src/parser.ts +1 -1
  103. package/src/parser_base.d.ts +19 -0
  104. package/src/parser_base.ts +57 -57
  105. package/src/parser_recovery.ts +153 -153
  106. package/src/scaffold.ts +375 -371
  107. package/src/solver.ts +330 -330
  108. package/src/typechecker.d.ts +52 -0
  109. package/src/typechecker.ts +591 -700
  110. package/src/types.d.ts +38 -0
  111. package/src/types.ts +122 -122
  112. package/src/verifier.ts +49 -154
  113. package/README.md +0 -382
  114. package/dist/commands/check.d.ts +0 -5
  115. package/dist/commands/check.js +0 -34
  116. package/dist/commands/check.js.map +0 -1
  117. package/dist/commands/compile.d.ts +0 -5
  118. package/dist/commands/compile.js +0 -215
  119. package/dist/commands/compile.js.map +0 -1
  120. package/dist/commands/debug.d.ts +0 -5
  121. package/dist/commands/debug.js +0 -59
  122. package/dist/commands/debug.js.map +0 -1
  123. package/dist/commands/diff.d.ts +0 -5
  124. package/dist/commands/diff.js +0 -123
  125. package/dist/commands/diff.js.map +0 -1
  126. package/dist/commands/fmt.d.ts +0 -5
  127. package/dist/commands/fmt.js +0 -49
  128. package/dist/commands/fmt.js.map +0 -1
  129. package/dist/commands/init.d.ts +0 -5
  130. package/dist/commands/init.js +0 -96
  131. package/dist/commands/init.js.map +0 -1
  132. package/dist/commands/ir.d.ts +0 -5
  133. package/dist/commands/ir.js +0 -27
  134. package/dist/commands/ir.js.map +0 -1
  135. package/dist/commands/lex.d.ts +0 -5
  136. package/dist/commands/lex.js +0 -21
  137. package/dist/commands/lex.js.map +0 -1
  138. package/dist/commands/parse.d.ts +0 -5
  139. package/dist/commands/parse.js +0 -30
  140. package/dist/commands/parse.js.map +0 -1
  141. package/dist/commands/test.d.ts +0 -5
  142. package/dist/commands/test.js +0 -61
  143. package/dist/commands/test.js.map +0 -1
  144. package/dist/commands/verify_determinism.d.ts +0 -5
  145. package/dist/commands/verify_determinism.js +0 -64
  146. package/dist/commands/verify_determinism.js.map +0 -1
  147. package/dist/commands/watch.d.ts +0 -5
  148. package/dist/commands/watch.js +0 -50
  149. package/dist/commands/watch.js.map +0 -1
  150. package/dist/emit_auth.d.ts +0 -18
  151. package/dist/emit_auth.js +0 -507
  152. package/dist/emit_auth.js.map +0 -1
  153. package/dist/emit_database.d.ts +0 -7
  154. package/dist/emit_database.js +0 -72
  155. package/dist/emit_database.js.map +0 -1
  156. package/dist/emit_index.d.ts +0 -6
  157. package/dist/emit_index.js +0 -202
  158. package/dist/emit_index.js.map +0 -1
  159. package/dist/emit_models.d.ts +0 -12
  160. package/dist/emit_models.js +0 -171
  161. package/dist/emit_models.js.map +0 -1
  162. package/dist/emit_openapi.d.ts +0 -9
  163. package/dist/emit_openapi.js +0 -306
  164. package/dist/emit_openapi.js.map +0 -1
  165. package/dist/emit_package.d.ts +0 -7
  166. package/dist/emit_package.js +0 -68
  167. package/dist/emit_package.js.map +0 -1
  168. package/dist/emit_router.d.ts +0 -12
  169. package/dist/emit_router.js +0 -389
  170. package/dist/emit_router.js.map +0 -1
  171. package/dist/lowering_channels.d.ts +0 -11
  172. package/dist/lowering_channels.js +0 -103
  173. package/dist/lowering_channels.js.map +0 -1
  174. package/dist/lowering_entities.d.ts +0 -11
  175. package/dist/lowering_entities.js +0 -232
  176. package/dist/lowering_entities.js.map +0 -1
  177. package/dist/lowering_helpers.d.ts +0 -13
  178. package/dist/lowering_helpers.js +0 -76
  179. package/dist/lowering_helpers.js.map +0 -1
  180. package/src/commands/check.ts +0 -33
  181. package/src/commands/compile.ts +0 -191
  182. package/src/commands/debug.ts +0 -33
  183. package/src/commands/diff.ts +0 -105
  184. package/src/commands/fmt.ts +0 -22
  185. package/src/commands/init.ts +0 -72
  186. package/src/commands/ir.ts +0 -23
  187. package/src/commands/lex.ts +0 -17
  188. package/src/commands/parse.ts +0 -24
  189. package/src/commands/test.ts +0 -36
  190. package/src/commands/verify_determinism.ts +0 -66
  191. package/src/commands/watch.ts +0 -25
  192. package/src/emit_auth.ts +0 -513
  193. package/src/emit_database.ts +0 -72
  194. package/src/emit_index.ts +0 -210
  195. package/src/emit_models.ts +0 -176
  196. package/src/emit_openapi.ts +0 -315
  197. package/src/emit_package.ts +0 -66
  198. package/src/emit_router.ts +0 -408
  199. package/src/lowering_channels.ts +0 -108
  200. package/src/lowering_entities.ts +0 -258
  201. package/src/lowering_helpers.ts +0 -75
package/src/cli.ts CHANGED
@@ -1,98 +1,704 @@
1
- /**
2
- * BoneScript compiler CLI — dispatcher
3
- * Each command lives in its own file under commands/.
4
- */
5
-
6
- import * as fs from "fs";
7
- import * as path from "path";
8
- import { runCompile } from "./commands/compile";
9
- import { runCheck } from "./commands/check";
10
- import { runLex } from "./commands/lex";
11
- import { runParse } from "./commands/parse";
12
- import { runIR } from "./commands/ir";
13
- import { runFormat } from "./commands/fmt";
14
- import { runWatch } from "./commands/watch";
15
- import { runInit } from "./commands/init";
16
- import { runDiff } from "./commands/diff";
17
- import { runDebug } from "./commands/debug";
18
- import { runTest } from "./commands/test";
19
- import { runVerifyDeterminism } from "./commands/verify_determinism";
20
-
21
- // ─── Helpers ──────────────────────────────────────────────────────────────────
22
-
23
- /** Read a file and pass its contents to an async action. */
24
- async function requireFile(
25
- filePath: string | undefined,
26
- action: (source: string, resolved: string) => Promise<void> | void,
27
- ): Promise<void> {
28
- if (!filePath) {
29
- console.error("Error: No input file specified.");
30
- process.exit(1);
31
- }
32
- const resolved = path.resolve(filePath);
33
- try {
34
- await fs.promises.access(resolved);
35
- } catch {
36
- console.error(`Error: File not found: ${resolved}`);
37
- process.exit(1);
38
- }
39
- const source = await fs.promises.readFile(resolved, "utf-8");
40
- await action(source, resolved);
41
- }
42
-
43
- function showHelp(): void {
44
- console.log("BoneScript compiler v0.3.0");
45
- console.log("");
46
- console.log("Usage:");
47
- console.log(" bonec compile <file> Compile to runnable project");
48
- console.log(" bonec check <file> Lex + parse + type check (no codegen)");
49
- console.log(" bonec lex <file> Show token stream");
50
- console.log(" bonec parse <file> Show AST");
51
- console.log(" bonec ir <file> Show IR (JSON)");
52
- console.log(" bonec fmt <file> Format file in place");
53
- console.log(" bonec watch <file> Recompile on change");
54
- console.log(" bonec diff <old.bone> <new.bone> Show schema migration diff");
55
- console.log(" bonec init <name> --domain <domain> Scaffold from a domain template");
56
- console.log(" bonec test [output-dir] Run generated regression tests");
57
- console.log(" bonec debug <file> Generate source maps");
58
- console.log(" bonec verify-determinism <file> Confirm two compilations are identical");
59
- console.log("");
60
- console.log("Domain options: multiplayer_game, saas_platform, iot_system,");
61
- console.log(" social_network, marketplace, realtime_collaboration");
62
- console.log(" --out <dir> Output directory for init (default: ./<name>)");
63
- }
64
-
65
- // ─── Dispatch ─────────────────────────────────────────────────────────────────
66
-
67
- async function main(): Promise<void> {
68
- const args = process.argv.slice(2);
69
-
70
- if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
71
- showHelp();
72
- return;
73
- }
74
-
75
- switch (args[0]) {
76
- case "compile": await requireFile(args[1], runCompile); break;
77
- case "check": await requireFile(args[1], (src) => runCheck(src)); break;
78
- case "lex": await requireFile(args[1], (src) => runLex(src)); break;
79
- case "parse": await requireFile(args[1], (src) => runParse(src)); break;
80
- case "ir": await requireFile(args[1], (src) => runIR(src)); break;
81
- case "fmt": await requireFile(args[1], runFormat); break;
82
- case "watch": await requireFile(args[1], runWatch); break;
83
- case "init": await runInit(args.slice(1)); break;
84
- case "diff": await runDiff(args.slice(1)); break;
85
- case "debug": await requireFile(args[1], runDebug); break;
86
- case "test": await runTest(args.slice(1)); break;
87
- case "verify-determinism": await requireFile(args[1], (src) => runVerifyDeterminism(src)); break;
88
- default:
89
- console.error(`Unknown command: ${args[0]}`);
90
- showHelp();
91
- process.exit(1);
92
- }
93
- }
94
-
95
- main().catch(e => {
96
- console.error(`x Fatal: ${e.message}`);
97
- process.exit(1);
98
- });
1
+ /**
2
+ * BoneScript compiler CLI
3
+ */
4
+
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+ import { createHash } from "crypto";
8
+ import { Lexer } from "./lexer";
9
+ import { Parser } from "./parser";
10
+ import { RecoveringParser } from "./parser_recovery";
11
+ import { TypeChecker } from "./typechecker";
12
+ import { Lowering } from "./lowering";
13
+ import { ConstraintSolver } from "./solver";
14
+ import { FullEmitter } from "./emit_full";
15
+ import { NakamaEmitter } from "./emit_nakama";
16
+ import { Verifier } from "./verifier";
17
+ import { ModuleLoader } from "./module_loader";
18
+ import { Formatter } from "./formatter";
19
+ import { scaffold, ScaffoldDomain } from "./scaffold";
20
+ import { mergeWithExisting } from "./extension_manager";
21
+ import { optimize } from "./optimizer";
22
+
23
+ function main() {
24
+ const args = process.argv.slice(2);
25
+
26
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
27
+ showHelp();
28
+ return;
29
+ }
30
+
31
+ const command = args[0];
32
+
33
+ switch (command) {
34
+ case "compile":
35
+ requireFile(args[1], (src, res) => runCompile(src, res, args.slice(2)));
36
+ break;
37
+ case "lex":
38
+ requireFile(args[1], runLex);
39
+ break;
40
+ case "parse":
41
+ requireFile(args[1], runParse);
42
+ break;
43
+ case "ir":
44
+ requireFile(args[1], runIR);
45
+ break;
46
+ case "check":
47
+ requireFile(args[1], runCheck);
48
+ break;
49
+ case "fmt":
50
+ requireFile(args[1], runFormat);
51
+ break;
52
+ case "watch":
53
+ requireFile(args[1], runWatch);
54
+ break;
55
+ case "init":
56
+ runInit(args.slice(1));
57
+ break;
58
+ case "diff":
59
+ runDiff(args.slice(1));
60
+ break;
61
+ case "debug":
62
+ requireFile(args[1], runDebug);
63
+ break;
64
+ case "test":
65
+ runTest(args.slice(1));
66
+ break;
67
+ case "verify-determinism":
68
+ requireFile(args[1], runVerifyDeterminism);
69
+ break;
70
+ default:
71
+ console.error(`Unknown command: ${command}`);
72
+ showHelp();
73
+ process.exit(1);
74
+ }
75
+ }
76
+
77
+ function showHelp() {
78
+ console.log("BoneScript compiler v0.5.4");
79
+ console.log("");
80
+ console.log("Usage:");
81
+ console.log(" bonec compile <file> [--target <target>] Compile to runnable project");
82
+ console.log(" bonec check <file> Lex + parse + type check (no codegen)");
83
+ console.log(" bonec lex <file> Show token stream");
84
+ console.log(" bonec parse <file> Show AST");
85
+ console.log(" bonec ir <file> Show IR (JSON)");
86
+ console.log(" bonec fmt <file> Format file in place");
87
+ console.log(" bonec watch <file> Recompile on change");
88
+ console.log(" bonec diff <old.bone> <new.bone> Show schema migration diff");
89
+ console.log("");
90
+ console.log("compile options:");
91
+ console.log(" --target <name> Output target (default: express)");
92
+ console.log(" Options: express, nakama");
93
+ console.log("");
94
+ console.log("init options:");
95
+ console.log(" bonec init <name> --domain <name> Scaffold from a domain template");
96
+ console.log(" --domain <name> Domain template (default: saas_platform)");
97
+ console.log(" Options: multiplayer_game, saas_platform, iot_system,");
98
+ console.log(" social_network, marketplace, realtime_collaboration");
99
+ console.log(" --out <dir> Output directory (default: current dir)");
100
+ }
101
+
102
+ function requireFile(filePath: string | undefined, action: (source: string, resolved: string) => void) {
103
+ if (!filePath) {
104
+ console.error("Error: No input file specified.");
105
+ process.exit(1);
106
+ }
107
+
108
+ const resolved = path.resolve(filePath);
109
+ if (!fs.existsSync(resolved)) {
110
+ console.error(`Error: File not found: ${resolved}`);
111
+ process.exit(1);
112
+ }
113
+
114
+ const source = fs.readFileSync(resolved, "utf-8");
115
+ action(source, resolved);
116
+ }
117
+
118
+ // ─── Lex ─────────────────────────────────────────────────────────────────────
119
+
120
+ function runLex(source: string) {
121
+ try {
122
+ const tokens = new Lexer(source).tokenize();
123
+ console.log(JSON.stringify(tokens, null, 2));
124
+ console.log(`\nv ${tokens.length} tokens produced.`);
125
+ } catch (e: any) {
126
+ console.error(`x ${e.message}`);
127
+ process.exit(1);
128
+ }
129
+ }
130
+
131
+ // ─── Parse ───────────────────────────────────────────────────────────────────
132
+
133
+ function runParse(source: string) {
134
+ try {
135
+ const tokens = new Lexer(source).tokenize();
136
+ const result = new RecoveringParser(tokens).parse();
137
+ if (result.errors.length > 0) {
138
+ console.error(`x ${result.errors.length} parse error(s):`);
139
+ for (const e of result.errors) console.error(` ${e.message}`);
140
+ if (!result.ast) process.exit(1);
141
+ }
142
+ console.log(JSON.stringify(result.ast, null, 2));
143
+ console.log(`\nv Parsed ${result.ast?.systems.length || 0} system(s).`);
144
+ } catch (e: any) {
145
+ console.error(`x ${e.message}`);
146
+ process.exit(1);
147
+ }
148
+ }
149
+
150
+ // ─── IR ──────────────────────────────────────────────────────────────────────
151
+
152
+ function runIR(source: string) {
153
+ try {
154
+ const tokens = new Lexer(source).tokenize();
155
+ const ast = new Parser(tokens).parse();
156
+ const sourceHash = createHash("sha256").update(source).digest("hex").slice(0, 16);
157
+ const irSystems = new Lowering().lower(ast, sourceHash);
158
+ console.log(JSON.stringify(irSystems, null, 2));
159
+ console.log(`\nv Lowered to ${irSystems.length} IR system(s).`);
160
+ } catch (e: any) {
161
+ console.error(`x ${e.message}`);
162
+ process.exit(1);
163
+ }
164
+ }
165
+
166
+ // ─── Check ───────────────────────────────────────────────────────────────────
167
+
168
+ function runCheck(source: string) {
169
+ const tokens = new Lexer(source).tokenize();
170
+ const result = new RecoveringParser(tokens).parse();
171
+
172
+ let totalErrors = 0;
173
+
174
+ if (result.errors.length > 0) {
175
+ for (const e of result.errors) {
176
+ console.error(` parse: ${e.message}`);
177
+ totalErrors++;
178
+ }
179
+ }
180
+
181
+ if (result.ast) {
182
+ const typeErrors = new TypeChecker().check(result.ast);
183
+ for (const err of typeErrors) {
184
+ console.error(` type: ${err.code} at ${err.loc.line}:${err.loc.column}: ${err.message}`);
185
+ totalErrors++;
186
+ }
187
+ }
188
+
189
+ if (totalErrors === 0) {
190
+ console.log("v Check passed (0 errors)");
191
+ } else {
192
+ console.log(`x ${totalErrors} error(s) found.`);
193
+ process.exit(1);
194
+ }
195
+ }
196
+
197
+ // ─── Format ──────────────────────────────────────────────────────────────────
198
+
199
+ function runFormat(source: string, resolved: string) {
200
+ try {
201
+ const tokens = new Lexer(source).tokenize();
202
+ const ast = new Parser(tokens).parse();
203
+ const formatted = new Formatter().format(ast);
204
+ fs.writeFileSync(resolved, formatted, "utf-8");
205
+ console.log(`v Formatted ${resolved}`);
206
+ } catch (e: any) {
207
+ console.error(`x ${e.message}`);
208
+ process.exit(1);
209
+ }
210
+ }
211
+
212
+ // ─── Watch ───────────────────────────────────────────────────────────────────
213
+
214
+ function runWatch(_source: string, resolved: string) {
215
+ console.log(`Watching ${resolved}...`);
216
+
217
+ const compile = () => {
218
+ try {
219
+ const fresh = fs.readFileSync(resolved, "utf-8");
220
+ console.log(`\n[${new Date().toLocaleTimeString()}] Compiling...`);
221
+ runCompile(fresh, resolved);
222
+ } catch (e: any) {
223
+ console.error(`x ${e.message}`);
224
+ }
225
+ };
226
+
227
+ compile();
228
+ fs.watchFile(resolved, { interval: 500 }, (curr, prev) => {
229
+ if (curr.mtimeMs !== prev.mtimeMs) compile();
230
+ });
231
+ }
232
+
233
+ // ─── Init ────────────────────────────────────────────────────────────────────
234
+
235
+ function runInit(args: string[]) {
236
+ if (args.length === 0) {
237
+ console.error("Error: bone init requires a project name.");
238
+ console.error("Example: bone init my-project --domain saas_platform");
239
+ process.exit(1);
240
+ }
241
+
242
+ const name = args[0];
243
+ let domain: ScaffoldDomain = "saas_platform";
244
+ let outDir = path.resolve(name);
245
+
246
+ for (let i = 1; i < args.length; i++) {
247
+ if (args[i] === "--domain" && args[i + 1]) {
248
+ domain = args[i + 1] as ScaffoldDomain;
249
+ i++;
250
+ } else if (args[i] === "--out" && args[i + 1]) {
251
+ outDir = path.resolve(args[i + 1]);
252
+ i++;
253
+ }
254
+ }
255
+
256
+ const validDomains: ScaffoldDomain[] = [
257
+ "multiplayer_game", "saas_platform", "iot_system",
258
+ "social_network", "marketplace", "realtime_collaboration",
259
+ ];
260
+ if (!validDomains.includes(domain)) {
261
+ console.error(`Error: Invalid domain '${domain}'. Valid: ${validDomains.join(", ")}`);
262
+ process.exit(1);
263
+ }
264
+
265
+ const result = scaffold({ name, domain, outDir });
266
+ console.log(`v Created ${result.created.length} file(s):`);
267
+ for (const f of result.created) console.log(` ${f}`);
268
+ console.log(`\nNext steps:`);
269
+ console.log(` cd ${outDir}`);
270
+ console.log(` bone compile ${name}.bone`);
271
+ }
272
+
273
+ // ─── Compile (full pipeline) ─────────────────────────────────────────────────
274
+
275
+ function runCompile(source: string, resolved: string, extraArgs: string[] = []) {
276
+ // Parse --target flag (default: express)
277
+ let target: "express" | "nakama" = "express";
278
+ for (let i = 0; i < extraArgs.length; i++) {
279
+ if (extraArgs[i] === "--target" && extraArgs[i + 1]) {
280
+ const t = extraArgs[i + 1];
281
+ if (t !== "express" && t !== "nakama") {
282
+ console.error(`Unknown target '${t}'. Valid targets: express, nakama`);
283
+ process.exit(1);
284
+ }
285
+ target = t;
286
+ i++;
287
+ }
288
+ }
289
+
290
+ if (target === "nakama") {
291
+ runCompileNakama(source, resolved);
292
+ return;
293
+ }
294
+
295
+ try {
296
+ const tokens = new Lexer(source).tokenize();
297
+ console.log(` [1/7] Lexed: ${tokens.length} tokens`);
298
+
299
+ // Use module loader to handle imports
300
+ const loader = new ModuleLoader();
301
+ const loadResult = loader.load(resolved);
302
+
303
+ if (loadResult.errors.length > 0) {
304
+ console.log(` [2/7] Parse: ${loadResult.errors.length} error(s)`);
305
+ for (const e of loadResult.errors.slice(0, 10)) {
306
+ console.log(` ${path.basename(e.file)}: ${e.error.message}`);
307
+ }
308
+ if (!loadResult.ast) process.exit(1);
309
+ } else {
310
+ const sysCount = loadResult.ast?.systems.length || 0;
311
+ console.log(` [2/7] Parsed: ${sysCount} system(s) from ${loadResult.loadedFiles.length} file(s)`);
312
+ }
313
+
314
+ const ast = loadResult.ast!;
315
+
316
+ for (const sys of ast.systems) {
317
+ console.log(` System '${sys.name}':`);
318
+ const counts: Record<string, number> = {};
319
+ for (const d of sys.declarations) counts[d.kind] = (counts[d.kind] || 0) + 1;
320
+ for (const [kind, count] of Object.entries(counts)) {
321
+ console.log(` ${kind}: ${count}`);
322
+ }
323
+ }
324
+
325
+ // Stage 3: Type Check
326
+ const checker = new TypeChecker();
327
+ const typeErrors = checker.check(ast);
328
+ if (typeErrors.length > 0) {
329
+ console.log(` [3/7] Type check: ${typeErrors.length} error(s)`);
330
+ for (const err of typeErrors) {
331
+ console.log(` ${err.code} at ${err.loc.line}:${err.loc.column}: ${err.message}`);
332
+ }
333
+ } else {
334
+ console.log(` [3/7] Type check: v (0 errors)`);
335
+ }
336
+
337
+ // Stage 4: Lower to IR
338
+ const sourceHash = createHash("sha256").update(source).digest("hex").slice(0, 16);
339
+ const lowering = new Lowering();
340
+ const irSystems = lowering.lower(ast, sourceHash);
341
+ const totalModules = irSystems.reduce((sum, s) => sum + s.modules.length, 0);
342
+ const totalEvents = irSystems.reduce((sum, s) => sum + s.events.length, 0);
343
+ const totalFlows = irSystems.reduce((sum, s) => sum + s.flows.length, 0);
344
+ console.log(` [4/7] Lower to IR: ${totalModules} modules, ${totalEvents} events, ${totalFlows} flows`);
345
+ for (const sys of irSystems) {
346
+ for (const mod of sys.modules) {
347
+ const methodCount = mod.interfaces.reduce((s, i) => s + i.methods.length, 0);
348
+ console.log(` ${mod.kind.padEnd(16)} ${mod.name.padEnd(24)} (${methodCount} methods, ${mod.models.length} models)`);
349
+ }
350
+ }
351
+
352
+ // Stage 4.5: IR Optimization
353
+ for (let i = 0; i < irSystems.length; i++) {
354
+ const result = optimize(irSystems[i]);
355
+ irSystems[i] = result.system;
356
+ if (result.log.length > 0) {
357
+ console.log(` [4.5] IR optimize: ${result.modulesRemoved} modules removed, ${result.eventsDeduped} events deduped, ${result.depsRemoved} deps minimized`);
358
+ }
359
+ }
360
+
361
+ // Stage 5: Constraint Solve
362
+ const solver = new ConstraintSolver();
363
+ let totalResolved = 0;
364
+ for (const sys of irSystems) {
365
+ const result = solver.solve(sys);
366
+ sys.resolution = result.resolution;
367
+ totalResolved += Object.keys(result.resolution).length;
368
+ if (result.errors.length > 0) {
369
+ console.log(` [5/7] Constraint solve: ${result.errors.length} error(s)`);
370
+ for (const err of result.errors) console.log(` x ${err}`);
371
+ } else {
372
+ console.log(` [5/7] Constraint solve: v (${totalResolved} resolved, ${result.assumptions.length} assumptions)`);
373
+ for (const a of result.assumptions.slice(0, 5)) console.log(` ${a}`);
374
+ if (result.assumptions.length > 5) console.log(` ... and ${result.assumptions.length - 5} more`);
375
+ }
376
+ }
377
+
378
+ // Stage 6: Code Emit
379
+ const emitter = new FullEmitter();
380
+ const allFiles: ReturnType<typeof emitter.emit> = [];
381
+ for (const sys of irSystems) {
382
+ const files = emitter.emit(sys);
383
+ allFiles.push(...files);
384
+ }
385
+ console.log(` [6/7] Code emit: ${allFiles.length} files generated`);
386
+ const byLang: Record<string, number> = {};
387
+ for (const f of allFiles) byLang[f.language] = (byLang[f.language] || 0) + 1;
388
+ for (const [lang, count] of Object.entries(byLang)) {
389
+ console.log(` ${lang}: ${count} file(s)`);
390
+ }
391
+
392
+ // Stage 7: Verify
393
+ const verifier = new Verifier();
394
+ const verifyResult = verifier.verify(irSystems[0], allFiles);
395
+ const errCount = verifyResult.issues.filter(i => i.severity === "error").length;
396
+ const warnCount = verifyResult.issues.filter(i => i.severity === "warning").length;
397
+ if (verifyResult.passed) {
398
+ console.log(` [7/7] Verify: v (${allFiles.length} files, ${warnCount} warnings)`);
399
+ } else {
400
+ console.log(` [7/7] Verify: FAILED (${errCount} errors, ${warnCount} warnings)`);
401
+ }
402
+ for (const issue of verifyResult.issues.slice(0, 10)) {
403
+ const icon = issue.severity === "error" ? "x" : "!";
404
+ console.log(` ${icon} ${issue.code}: ${issue.message}`);
405
+ }
406
+
407
+ // Write output — merge extension point implementations from existing files
408
+ const outputDir = path.resolve(path.dirname(resolved), "output");
409
+ const allExtensions = irSystems.flatMap(s => s.extension_points || []);
410
+ let extensionErrors: string[] = [];
411
+
412
+ for (const f of allFiles) {
413
+ const outPath = path.join(outputDir, f.path);
414
+ const dir = path.dirname(outPath);
415
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
416
+
417
+ // For extensions.ts: merge preserved implementations
418
+ if (f.path === "src/extensions.ts" && allExtensions.length > 0) {
419
+ const astExtensions = ast.systems.flatMap(s =>
420
+ s.declarations.filter((d): d is any => d.kind === "ExtensionPointDecl")
421
+ );
422
+ const { content, validationErrors } = mergeWithExisting(f.content, outPath, astExtensions);
423
+ for (const e of validationErrors) extensionErrors.push(e.message);
424
+ fs.writeFileSync(outPath, content, "utf-8");
425
+ } else {
426
+ fs.writeFileSync(outPath, f.content, "utf-8");
427
+ }
428
+ }
429
+
430
+ if (extensionErrors.length > 0) {
431
+ console.log(`\n Extension point errors:`);
432
+ for (const e of extensionErrors) console.log(` x ${e}`);
433
+ process.exit(1);
434
+ }
435
+
436
+ console.log(`\nv Compilation complete. ${allFiles.length} files written to output/`);
437
+ } catch (e: any) {
438
+ console.error(`x ${e.message}`);
439
+ process.exit(1);
440
+ }
441
+ }
442
+
443
+ main();
444
+
445
+ // ─── Compile (Nakama target) ──────────────────────────────────────────────────
446
+
447
+ function runCompileNakama(source: string, resolved: string) {
448
+ try {
449
+ const tokens = new Lexer(source).tokenize();
450
+ console.log(` [1/5] Lexed: ${tokens.length} tokens`);
451
+
452
+ const loader = new ModuleLoader();
453
+ const loadResult = loader.load(resolved);
454
+ if (loadResult.errors.length > 0) {
455
+ for (const e of loadResult.errors.slice(0, 10)) {
456
+ console.log(` ${path.basename(e.file)}: ${e.error.message}`);
457
+ }
458
+ if (!loadResult.ast) process.exit(1);
459
+ }
460
+ const ast = loadResult.ast!;
461
+ console.log(` [2/5] Parsed: ${ast.systems.length} system(s)`);
462
+
463
+ const typeErrors = new TypeChecker().check(ast);
464
+ if (typeErrors.length > 0) {
465
+ for (const err of typeErrors) {
466
+ console.log(` ${err.code} at ${err.loc.line}:${err.loc.column}: ${err.message}`);
467
+ }
468
+ } else {
469
+ console.log(` [3/5] Type check: v (0 errors)`);
470
+ }
471
+
472
+ const sourceHash = createHash("sha256").update(source).digest("hex").slice(0, 16);
473
+ const irSystems = new Lowering().lower(ast, sourceHash);
474
+ console.log(` [4/5] Lowered to IR: ${irSystems.reduce((s, sys) => s + sys.modules.length, 0)} modules`);
475
+
476
+ const emitter = new NakamaEmitter();
477
+ const allFiles: ReturnType<typeof emitter.emit> = [];
478
+ for (const sys of irSystems) {
479
+ allFiles.push(...emitter.emit(sys));
480
+ }
481
+ console.log(` [5/5] Nakama emit: ${allFiles.length} files`);
482
+
483
+ const outputDir = path.resolve(path.dirname(resolved), "output-nakama");
484
+ for (const f of allFiles) {
485
+ const outPath = path.join(outputDir, f.path);
486
+ const dir = path.dirname(outPath);
487
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
488
+ fs.writeFileSync(outPath, f.content, "utf-8");
489
+ }
490
+
491
+ console.log(`\nv Nakama compilation complete. ${allFiles.length} files written to output-nakama/`);
492
+ console.log(`\nNext steps:`);
493
+ console.log(` cd output-nakama && npm install && npm run build`);
494
+ console.log(` # Copy build/ to your Nakama runtime path`);
495
+ } catch (e: any) {
496
+ console.error(`x ${e.message}`);
497
+ process.exit(1);
498
+ }
499
+ }
500
+
501
+ // ─── Diff ─────────────────────────────────────────────────────────────────────
502
+
503
+ function runDiff(args: string[]) {
504
+ if (args.length < 2) {
505
+ console.error("Usage: bone diff <old.bone> <new.bone>");
506
+ process.exit(1);
507
+ }
508
+
509
+ const [oldFile, newFile] = args;
510
+
511
+ const compileToIR = (filePath: string) => {
512
+ const resolved = path.resolve(filePath);
513
+ if (!fs.existsSync(resolved)) {
514
+ console.error(`File not found: ${resolved}`);
515
+ process.exit(1);
516
+ }
517
+ const source = fs.readFileSync(resolved, "utf-8");
518
+ const tokens = new Lexer(source).tokenize();
519
+ const ast = new Parser(tokens).parse();
520
+ const hash = createHash("sha256").update(source).digest("hex").slice(0, 16);
521
+ return new Lowering().lower(ast, hash);
522
+ };
523
+
524
+ const oldIR = compileToIR(oldFile);
525
+ const newIR = compileToIR(newFile);
526
+
527
+ const oldModels: any[] = [];
528
+ const newModels: any[] = [];
529
+ for (const sys of oldIR) for (const mod of sys.modules) for (const m of mod.models) oldModels.push(m);
530
+ for (const sys of newIR) for (const mod of sys.modules) for (const m of mod.models) newModels.push(m);
531
+
532
+ const oldByName = new Map(oldModels.map(m => [m.name, m]));
533
+ const newByName = new Map(newModels.map(m => [m.name, m]));
534
+ const statements: string[] = [];
535
+
536
+ // New tables
537
+ for (const [name, model] of newByName) {
538
+ if (!oldByName.has(name)) {
539
+ statements.push(`-- NEW TABLE: ${name}`);
540
+ statements.push(`-- Run: bone compile ${newFile} (generates full migration)`);
541
+ }
542
+ }
543
+
544
+ // Removed tables
545
+ for (const [name] of oldByName) {
546
+ if (!newByName.has(name)) {
547
+ const table = name.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase() + "s";
548
+ statements.push(`-- WARNING: Table '${table}' removed from schema`);
549
+ statements.push(`-- Manual: ALTER TABLE ${table} ... (or DROP TABLE ${table})`);
550
+ }
551
+ }
552
+
553
+ // Modified tables
554
+ for (const [name, newModel] of newByName) {
555
+ const oldModel = oldByName.get(name);
556
+ if (!oldModel) continue;
557
+
558
+ const table = name.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase() + "s";
559
+ const oldFields = new Map(oldModel.fields.map((f: any) => [f.name, f]));
560
+ const newFields = new Map(newModel.fields.map((f: any) => [f.name, f]));
561
+
562
+ const sqlTypeMap: Record<string, string> = {
563
+ string: "VARCHAR", uint: "BIGINT", int: "BIGINT", float: "DOUBLE PRECISION",
564
+ bool: "BOOLEAN", timestamp: "TIMESTAMPTZ", uuid: "UUID", bytes: "BYTEA", json: "JSONB",
565
+ };
566
+
567
+ for (const [fname, field] of newFields) {
568
+ if (!oldFields.has(fname)) {
569
+ const sqlType = sqlTypeMap[(field as any).type] || "JSONB";
570
+ statements.push(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fname} ${sqlType};`);
571
+ }
572
+ }
573
+
574
+ for (const [fname] of oldFields) {
575
+ if (!newFields.has(fname)) {
576
+ statements.push(`-- WARNING: Column '${table}.${fname}' removed`);
577
+ statements.push(`-- Manual: ALTER TABLE ${table} DROP COLUMN ${fname};`);
578
+ }
579
+ }
580
+ }
581
+
582
+ if (statements.length === 0) {
583
+ console.log("No schema changes detected.");
584
+ } else {
585
+ console.log(`-- BoneScript schema diff: ${path.basename(oldFile)} → ${path.basename(newFile)}`);
586
+ console.log(`-- Generated: ${new Date().toISOString()}`);
587
+ console.log(``);
588
+ console.log(statements.join("\n"));
589
+ }
590
+ }
591
+
592
+ // ─── Debug ────────────────────────────────────────────────────────────────────
593
+
594
+ function runDebug(source: string, resolved: string) {
595
+ try {
596
+ const tokens = new Lexer(source).tokenize();
597
+ const ast = new Parser(tokens).parse();
598
+ const sourceHash = createHash("sha256").update(source).digest("hex").slice(0, 16);
599
+ const irSystems = new Lowering().lower(ast, sourceHash);
600
+
601
+ const { emitSourceMapFile } = require("./emit_sourcemap");
602
+ for (const sys of irSystems) {
603
+ const mapContent = emitSourceMapFile(sys, path.basename(resolved));
604
+ const mapPath = path.join(path.dirname(resolved), `${sys.name}.bone.map`);
605
+ fs.writeFileSync(mapPath, mapContent, "utf-8");
606
+ console.log(`v Source map written: ${mapPath}`);
607
+ console.log(` ${sys.modules.length} modules mapped`);
608
+ console.log(` Use output/src/debug.ts to get annotated runtime errors`);
609
+ }
610
+ } catch (e: any) {
611
+ console.error(`x ${e.message}`);
612
+ process.exit(1);
613
+ }
614
+ }
615
+
616
+ // ─── Test ─────────────────────────────────────────────────────────────────────
617
+
618
+ function runTest(args: string[]) {
619
+ const outputDir = args[0] ? path.resolve(args[0]) : path.resolve("output");
620
+ const testFile = path.join(outputDir, "src", "tests.ts");
621
+
622
+ if (!fs.existsSync(testFile)) {
623
+ console.error(`No test file found at ${testFile}`);
624
+ console.error("Run 'bone compile <file>' first to generate tests.");
625
+ process.exit(1);
626
+ }
627
+
628
+ console.log(`Running BoneScript regression tests...`);
629
+ console.log(`Test file: ${testFile}`);
630
+ console.log(`Target: ${process.env.TEST_BASE_URL || "http://localhost:3000"}`);
631
+ console.log(``);
632
+
633
+ // Run the generated test file using ts-node
634
+ const { execSync } = require("child_process");
635
+ try {
636
+ execSync(`npx ts-node ${testFile}`, {
637
+ cwd: outputDir,
638
+ stdio: "inherit",
639
+ env: { ...process.env },
640
+ });
641
+ } catch {
642
+ process.exit(1);
643
+ }
644
+ }
645
+
646
+ // ─── Verify Determinism ───────────────────────────────────────────────────────
647
+
648
+ function runVerifyDeterminism(source: string, resolved: string) {
649
+ console.log("Verifying compilation determinism...");
650
+
651
+ const compile = () => {
652
+ const tokens = new Lexer(source).tokenize();
653
+ const ast = new Parser(tokens).parse();
654
+ const hash = createHash("sha256").update(source).digest("hex").slice(0, 16);
655
+ const ir = new Lowering().lower(ast, hash);
656
+ const emitter = new FullEmitter();
657
+ const files: { path: string; content: string }[] = [];
658
+ for (const sys of ir) {
659
+ for (const f of emitter.emit(sys)) {
660
+ files.push({ path: f.path, content: f.content });
661
+ }
662
+ }
663
+ // Sort for canonical comparison
664
+ files.sort((a, b) => a.path.localeCompare(b.path));
665
+ return JSON.stringify(files);
666
+ };
667
+
668
+ const run1 = compile();
669
+ const run2 = compile();
670
+
671
+ if (run1 === run2) {
672
+ const hash = createHash("sha256").update(run1).digest("hex").slice(0, 16);
673
+ console.log(`v Deterministic. Both runs produced identical output.`);
674
+ console.log(` Output hash: ${hash}`);
675
+ } else {
676
+ // Find first divergence
677
+ const files1: { path: string; content: string }[] = JSON.parse(run1);
678
+ const files2: { path: string; content: string }[] = JSON.parse(run2);
679
+
680
+ for (let i = 0; i < Math.max(files1.length, files2.length); i++) {
681
+ const f1 = files1[i];
682
+ const f2 = files2[i];
683
+ if (!f1 || !f2 || f1.path !== f2.path || f1.content !== f2.content) {
684
+ console.error(`x NON-DETERMINISTIC: First divergence at file ${i}`);
685
+ console.error(` Run 1: ${f1?.path || "(missing)"}`);
686
+ console.error(` Run 2: ${f2?.path || "(missing)"}`);
687
+ if (f1 && f2 && f1.path === f2.path) {
688
+ // Find first differing line
689
+ const lines1 = f1.content.split("\n");
690
+ const lines2 = f2.content.split("\n");
691
+ for (let j = 0; j < Math.max(lines1.length, lines2.length); j++) {
692
+ if (lines1[j] !== lines2[j]) {
693
+ console.error(` First differing line ${j + 1}:`);
694
+ console.error(` Run 1: ${lines1[j]}`);
695
+ console.error(` Run 2: ${lines2[j]}`);
696
+ break;
697
+ }
698
+ }
699
+ }
700
+ process.exit(1);
701
+ }
702
+ }
703
+ }
704
+ }