bonescript-compiler 0.5.2 → 0.5.4

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 (187) 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 +543 -75
  5. package/dist/cli.js.map +1 -1
  6. package/dist/emit_capability.d.ts +0 -13
  7. package/dist/emit_capability.js +128 -292
  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 +162 -162
  12. package/dist/emit_events.d.ts +0 -1
  13. package/dist/emit_events.js +275 -342
  14. package/dist/emit_events.js.map +1 -1
  15. package/dist/emit_full.js +106 -268
  16. package/dist/emit_full.js.map +1 -1
  17. package/dist/emit_maintenance.js +249 -249
  18. package/dist/emit_runtime.d.ts +11 -17
  19. package/dist/emit_runtime.js +688 -29
  20. package/dist/emit_runtime.js.map +1 -1
  21. package/dist/emit_sourcemap.js +66 -66
  22. package/dist/emit_tests.js +0 -37
  23. package/dist/emit_tests.js.map +1 -1
  24. package/dist/emitter.js +16 -82
  25. package/dist/emitter.js.map +1 -1
  26. package/dist/extension_manager.d.ts +2 -2
  27. package/dist/extension_manager.js +3 -6
  28. package/dist/extension_manager.js.map +1 -1
  29. package/dist/ir.d.ts +0 -4
  30. package/dist/lowering.d.ts +14 -5
  31. package/dist/lowering.js +417 -66
  32. package/dist/lowering.js.map +1 -1
  33. package/dist/module_loader.d.ts +2 -2
  34. package/dist/module_loader.js +23 -20
  35. package/dist/module_loader.js.map +1 -1
  36. package/dist/optimizer.js +1 -1
  37. package/dist/optimizer.js.map +1 -1
  38. package/dist/scaffold.d.ts +2 -2
  39. package/dist/scaffold.js +319 -315
  40. package/dist/scaffold.js.map +1 -1
  41. package/dist/source_map.js.map +1 -0
  42. package/dist/test.js.map +1 -0
  43. package/dist/test_typechecker.d.ts +5 -0
  44. package/dist/test_typechecker.js +126 -0
  45. package/dist/test_typechecker.js.map +1 -0
  46. package/dist/typechecker.d.ts +0 -5
  47. package/dist/typechecker.js +13 -68
  48. package/dist/typechecker.js.map +1 -1
  49. package/dist/verifier.d.ts +1 -5
  50. package/dist/verifier.js +35 -140
  51. package/dist/verifier.js.map +1 -1
  52. package/package.json +52 -62
  53. package/src/algorithm_catalog.ts +345 -345
  54. package/src/ast.d.ts +244 -0
  55. package/src/ast.ts +334 -334
  56. package/src/cli.ts +624 -98
  57. package/src/emit_batch.ts +140 -140
  58. package/src/emit_capability.ts +436 -617
  59. package/src/emit_composition.ts +196 -229
  60. package/src/emit_deploy.ts +190 -190
  61. package/src/emit_events.ts +307 -377
  62. package/src/emit_extras.ts +240 -240
  63. package/src/emit_full.ts +309 -475
  64. package/src/emit_maintenance.ts +459 -459
  65. package/src/emit_runtime.ts +730 -17
  66. package/src/emit_sourcemap.ts +140 -140
  67. package/src/emit_tests.ts +205 -246
  68. package/src/emit_websocket.ts +229 -229
  69. package/src/emitter.ts +578 -642
  70. package/src/extension_manager.ts +187 -189
  71. package/src/formatter.ts +297 -297
  72. package/src/index.ts +88 -88
  73. package/src/ir.ts +215 -216
  74. package/src/lexer.d.ts +195 -0
  75. package/src/lexer.ts +630 -630
  76. package/src/lowering.ts +556 -168
  77. package/src/module_loader.ts +114 -112
  78. package/src/optimizer.ts +196 -196
  79. package/src/parse_decls.d.ts +13 -0
  80. package/src/parse_decls.ts +409 -409
  81. package/src/parse_decls2.d.ts +13 -0
  82. package/src/parse_decls2.ts +244 -244
  83. package/src/parse_expr.d.ts +7 -0
  84. package/src/parse_expr.ts +197 -197
  85. package/src/parse_types.d.ts +6 -0
  86. package/src/parse_types.ts +54 -54
  87. package/src/parser.d.ts +10 -0
  88. package/src/parser.ts +1 -1
  89. package/src/parser_base.d.ts +19 -0
  90. package/src/parser_base.ts +57 -57
  91. package/src/parser_recovery.ts +153 -153
  92. package/src/scaffold.ts +375 -371
  93. package/src/solver.ts +330 -330
  94. package/src/typechecker.d.ts +52 -0
  95. package/src/typechecker.ts +591 -657
  96. package/src/types.d.ts +38 -0
  97. package/src/types.ts +122 -122
  98. package/src/verifier.ts +46 -152
  99. package/README.md +0 -382
  100. package/dist/commands/check.d.ts +0 -5
  101. package/dist/commands/check.js +0 -34
  102. package/dist/commands/check.js.map +0 -1
  103. package/dist/commands/compile.d.ts +0 -5
  104. package/dist/commands/compile.js +0 -215
  105. package/dist/commands/compile.js.map +0 -1
  106. package/dist/commands/debug.d.ts +0 -5
  107. package/dist/commands/debug.js +0 -59
  108. package/dist/commands/debug.js.map +0 -1
  109. package/dist/commands/diff.d.ts +0 -5
  110. package/dist/commands/diff.js +0 -125
  111. package/dist/commands/diff.js.map +0 -1
  112. package/dist/commands/fmt.d.ts +0 -5
  113. package/dist/commands/fmt.js +0 -49
  114. package/dist/commands/fmt.js.map +0 -1
  115. package/dist/commands/init.d.ts +0 -5
  116. package/dist/commands/init.js +0 -96
  117. package/dist/commands/init.js.map +0 -1
  118. package/dist/commands/ir.d.ts +0 -5
  119. package/dist/commands/ir.js +0 -27
  120. package/dist/commands/ir.js.map +0 -1
  121. package/dist/commands/lex.d.ts +0 -5
  122. package/dist/commands/lex.js +0 -21
  123. package/dist/commands/lex.js.map +0 -1
  124. package/dist/commands/parse.d.ts +0 -5
  125. package/dist/commands/parse.js +0 -30
  126. package/dist/commands/parse.js.map +0 -1
  127. package/dist/commands/test.d.ts +0 -5
  128. package/dist/commands/test.js +0 -61
  129. package/dist/commands/test.js.map +0 -1
  130. package/dist/commands/verify_determinism.d.ts +0 -5
  131. package/dist/commands/verify_determinism.js +0 -64
  132. package/dist/commands/verify_determinism.js.map +0 -1
  133. package/dist/commands/watch.d.ts +0 -5
  134. package/dist/commands/watch.js +0 -50
  135. package/dist/commands/watch.js.map +0 -1
  136. package/dist/emit_auth.d.ts +0 -18
  137. package/dist/emit_auth.js +0 -507
  138. package/dist/emit_auth.js.map +0 -1
  139. package/dist/emit_database.d.ts +0 -7
  140. package/dist/emit_database.js +0 -74
  141. package/dist/emit_database.js.map +0 -1
  142. package/dist/emit_index.d.ts +0 -6
  143. package/dist/emit_index.js +0 -202
  144. package/dist/emit_index.js.map +0 -1
  145. package/dist/emit_models.d.ts +0 -12
  146. package/dist/emit_models.js +0 -171
  147. package/dist/emit_models.js.map +0 -1
  148. package/dist/emit_openapi.d.ts +0 -9
  149. package/dist/emit_openapi.js +0 -308
  150. package/dist/emit_openapi.js.map +0 -1
  151. package/dist/emit_package.d.ts +0 -7
  152. package/dist/emit_package.js +0 -70
  153. package/dist/emit_package.js.map +0 -1
  154. package/dist/emit_router.d.ts +0 -12
  155. package/dist/emit_router.js +0 -390
  156. package/dist/emit_router.js.map +0 -1
  157. package/dist/lowering_channels.d.ts +0 -11
  158. package/dist/lowering_channels.js +0 -103
  159. package/dist/lowering_channels.js.map +0 -1
  160. package/dist/lowering_entities.d.ts +0 -11
  161. package/dist/lowering_entities.js +0 -232
  162. package/dist/lowering_entities.js.map +0 -1
  163. package/dist/lowering_helpers.d.ts +0 -13
  164. package/dist/lowering_helpers.js +0 -76
  165. package/dist/lowering_helpers.js.map +0 -1
  166. package/src/commands/check.ts +0 -33
  167. package/src/commands/compile.ts +0 -191
  168. package/src/commands/debug.ts +0 -33
  169. package/src/commands/diff.ts +0 -108
  170. package/src/commands/fmt.ts +0 -22
  171. package/src/commands/init.ts +0 -72
  172. package/src/commands/ir.ts +0 -23
  173. package/src/commands/lex.ts +0 -17
  174. package/src/commands/parse.ts +0 -24
  175. package/src/commands/test.ts +0 -36
  176. package/src/commands/verify_determinism.ts +0 -66
  177. package/src/commands/watch.ts +0 -25
  178. package/src/emit_auth.ts +0 -513
  179. package/src/emit_database.ts +0 -75
  180. package/src/emit_index.ts +0 -210
  181. package/src/emit_models.ts +0 -176
  182. package/src/emit_openapi.ts +0 -318
  183. package/src/emit_package.ts +0 -69
  184. package/src/emit_router.ts +0 -409
  185. package/src/lowering_channels.ts +0 -108
  186. package/src/lowering_entities.ts +0 -258
  187. package/src/lowering_helpers.ts +0 -75
@@ -1,409 +0,0 @@
1
- /**
2
- * BoneScript Router Emitter
3
- * Generates Express route files (CRUD + capability endpoints) and
4
- * state machine runtime files for each entity.
5
- */
6
-
7
- import * as IR from "./ir";
8
- import { emitCapabilityBody } from "./emit_capability";
9
-
10
- // ─── Shared helpers ───────────────────────────────────────────────────────────
11
-
12
- export function toSnakeCase(s: string): string {
13
- return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
14
- }
15
-
16
- export function toCamelCase(s: string): string {
17
- return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
18
- }
19
-
20
- const TS_TYPE_MAP: Record<string, string> = {
21
- string: "string", uint: "number", int: "number", float: "number",
22
- bool: "boolean", timestamp: "Date", uuid: "string", bytes: "Buffer", json: "unknown",
23
- };
24
-
25
- export function toTsType(irType: string): string {
26
- if (TS_TYPE_MAP[irType]) return TS_TYPE_MAP[irType];
27
- const m = irType.match(/^(list|set)<(.+)>$/);
28
- if (m) return `${toTsType(m[2])}[]`;
29
- const om = irType.match(/^optional<(.+)>$/);
30
- if (om) return `${toTsType(om[1])} | null`;
31
- return irType;
32
- }
33
-
34
- // ─── Unknown function collector ───────────────────────────────────────────────
35
-
36
- const KNOWN_FUNCTIONS = new Set([
37
- "now", "count", "sum", "min", "max", "avg", "length", "size",
38
- "shortestPath", "topologicalSort", "binarySearch", "bipartiteMatching",
39
- "roundRobin", "weightedAverage", "percentile", "rankBy", "consistentHash",
40
- ]);
41
-
42
- function collectUnknownFunctions(mod: IR.IRModule): Set<string> {
43
- const found = new Set<string>();
44
- for (const iface of mod.interfaces) {
45
- for (const method of iface.methods) {
46
- for (const effect of method.effects) extractFunctionCalls(effect.value, found);
47
- for (const pre of method.preconditions) extractFunctionCalls(pre.expression, found);
48
- }
49
- }
50
- return found;
51
- }
52
-
53
- function extractFunctionCalls(expr: string, found: Set<string>): void {
54
- const pattern = /\b([a-zA-Z_]\w*)\s*\(/g;
55
- let match: RegExpExecArray | null;
56
- while ((match = pattern.exec(expr)) !== null) {
57
- const name = match[1];
58
- if (!KNOWN_FUNCTIONS.has(name)) found.add(name);
59
- }
60
- }
61
-
62
- // ─── State Machine Runtime ────────────────────────────────────────────────────
63
-
64
- export function emitStateMachineRuntime(sm: IR.IRStateMachine): string {
65
- const lines: string[] = [];
66
- const stateUnion = sm.states.map(s => `"${s}"`).join(" | ");
67
-
68
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
69
- lines.push(``);
70
- lines.push(`export type ${sm.entity}State = ${stateUnion};`);
71
- lines.push(``);
72
- lines.push(`export const ${sm.entity.toUpperCase()}_INITIAL: ${sm.entity}State = "${sm.initial}";`);
73
- lines.push(``);
74
- lines.push(`const TRANSITIONS: Record<${sm.entity}State, Record<string, ${sm.entity}State>> = {`);
75
- for (const state of sm.states) {
76
- const trans = sm.transitions.filter(t => t.from === state);
77
- const entries = trans.map(t => `"${t.trigger}": "${t.to}"`).join(", ");
78
- lines.push(` "${state}": { ${entries} },`);
79
- }
80
- lines.push(`};`);
81
- lines.push(``);
82
- lines.push(`export function transition${sm.entity}(`);
83
- lines.push(` current: ${sm.entity}State,`);
84
- lines.push(` trigger: string,`);
85
- lines.push(` guard?: () => boolean`);
86
- lines.push(`): { ok: true; next: ${sm.entity}State } | { ok: false; error: string } {`);
87
- lines.push(` const next = TRANSITIONS[current]?.[trigger];`);
88
- lines.push(` if (!next) return { ok: false, error: \`Invalid transition: \${current} --[\${trigger}]--> ?\` };`);
89
- lines.push(` if (guard && !guard()) return { ok: false, error: \`Guard failed for transition: \${current} --[\${trigger}]--> \${next}\` };`);
90
- lines.push(` return { ok: true, next };`);
91
- lines.push(`}`);
92
- lines.push(``);
93
-
94
- return lines.join("\n");
95
- }
96
-
97
- // ─── Entity Router ────────────────────────────────────────────────────────────
98
-
99
- export function emitEntityRouter(mod: IR.IRModule, system: IR.IRSystem): string {
100
- const entityModel = mod.models[0];
101
- if (!entityModel) return "";
102
-
103
- const tableName = toSnakeCase(entityModel.name) + "s";
104
- const routeBase = toSnakeCase(entityModel.name) + "s";
105
- const lines: string[] = [];
106
-
107
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
108
- lines.push(`// Service: ${mod.name}`);
109
- lines.push(`import { Router, Request, Response } from "express";`);
110
- lines.push(`import { v4 as uuid } from "uuid";`);
111
- lines.push(`import { query, queryOne, execute, pool } from "../db";`);
112
- lines.push(`import { eventBus } from "../events";`);
113
- lines.push(`import { requireAuth, AuthContext } from "../auth";`);
114
- lines.push(`import { logger } from "../logger";`);
115
- lines.push(`import { counter } from "../metrics";`);
116
- lines.push(`import * as __algorithms from "../algorithms";`);
117
- lines.push(`const { shortestPath, topologicalSort, binarySearch, bipartiteMatching, roundRobin, weightedAverage, percentile, rankBy, consistentHash } = __algorithms as any;`);
118
- lines.push(``);
119
-
120
- // Import broadcastToChannel if any capability uses sync: realtime
121
- const hasRealtime = mod.interfaces.some(i => i.methods.some(m => m.sync === "realtime"));
122
- if (hasRealtime) {
123
- // Only import if websocket.ts will be generated (system has realtime_service modules)
124
- const hasWebSocket = system.modules.some(m => m.kind === "realtime_service");
125
- if (hasWebSocket) {
126
- lines.push(`import { broadcastToChannel } from "../websocket";`);
127
- } else {
128
- // No WebSocket server — define a no-op stub so the route file still compiles
129
- lines.push(`// No realtime_service declared — broadcastToChannel is a no-op`);
130
- lines.push(`function broadcastToChannel(_channel: string, _msg: unknown, _exclude?: unknown): void {}`);
131
- }
132
- lines.push(``);
133
- }
134
- const unknownFunctions = collectUnknownFunctions(mod);
135
- if (unknownFunctions.size > 0) {
136
- lines.push(`// User-defined functions referenced in effects — implement these or use extension_point`);
137
- for (const fn of unknownFunctions) lines.push(`declare function ${fn}(...args: any[]): any;`);
138
- lines.push(``);
139
- }
140
-
141
- if (mod.state_machines.length > 0) {
142
- const sm = mod.state_machines[0];
143
- lines.push(`import { transition${sm.entity}, ${sm.entity.toUpperCase()}_INITIAL } from "../state_machines/${toSnakeCase(sm.entity)}";`);
144
- lines.push(``);
145
- }
146
-
147
- lines.push(`export const ${toCamelCase(routeBase)}Router = Router();`);
148
- lines.push(``);
149
-
150
- // CREATE
151
- const insertFields = entityModel.fields.filter(f =>
152
- f.name !== "id" && f.name !== "created_at" && f.name !== "updated_at"
153
- );
154
- lines.push(`// CREATE`);
155
- lines.push(`${toCamelCase(routeBase)}Router.post("/", requireAuth, async (req: Request, res: Response) => {`);
156
- lines.push(` try {`);
157
- lines.push(` const id = uuid();`);
158
- lines.push(` const { ${insertFields.map(f => f.name).join(", ")} } = req.body;`);
159
- if (mod.state_machines.length > 0) {
160
- lines.push(` const state = ${mod.state_machines[0].entity.toUpperCase()}_INITIAL;`);
161
- }
162
- const allInsertFields = ["id", ...insertFields.map(f => f.name)];
163
- if (mod.state_machines.length > 0 && !insertFields.find(f => f.name === "state")) {
164
- allInsertFields.push("state");
165
- }
166
- const placeholders = allInsertFields.map((_, i) => `$${i + 1}`).join(", ");
167
- const values = allInsertFields.map(f => f === "id" ? "id" : f === "state" ? "state" : f).join(", ");
168
- lines.push(` const sql = \`INSERT INTO ${tableName} (${allInsertFields.join(", ")}) VALUES (${placeholders}) RETURNING *\`;`);
169
- lines.push(` const rows = await query(sql, [${values}]);`);
170
- lines.push(` counter("entity.created", { entity: "${entityModel.name}" });`);
171
- lines.push(` res.status(201).json(rows[0]);`);
172
- lines.push(` } catch (e: any) {`);
173
- lines.push(` res.status(400).json({ error: { code: "CREATE_FAILED", message: e.message } });`);
174
- lines.push(` }`);
175
- lines.push(`});`);
176
- lines.push(``);
177
-
178
- // READ
179
- lines.push(`// READ`);
180
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id", requireAuth, async (req: Request, res: Response) => {`);
181
- lines.push(` try {`);
182
- lines.push(` const row = await queryOne(\`SELECT * FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
183
- lines.push(` if (!row) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
184
- lines.push(` res.json(row);`);
185
- lines.push(` } catch (e: any) {`);
186
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
187
- lines.push(` }`);
188
- lines.push(`});`);
189
- lines.push(``);
190
-
191
- // LIST — COUNT(*) OVER() window function avoids a separate COUNT round-trip
192
- const joinRelations = mod.relations.filter(r => r.kind === "has_one" || r.kind === "belongs_to");
193
- lines.push(`// LIST`);
194
- lines.push(`${toCamelCase(routeBase)}Router.get("/", requireAuth, async (req: Request, res: Response) => {`);
195
- lines.push(` try {`);
196
- lines.push(` const page = parseInt(req.query.page as string) || 1;`);
197
- lines.push(` const pageSize = Math.min(parseInt(req.query.page_size as string) || 50, 100);`);
198
- lines.push(` const offset = (page - 1) * pageSize;`);
199
- if (joinRelations.length > 0) {
200
- const joinClauses = joinRelations.map(r => {
201
- const alias = r.to_table.slice(0, -1);
202
- return r.kind === "belongs_to"
203
- ? `LEFT JOIN ${r.to_table} ${alias} ON ${tableName}.${r.foreign_key} = ${alias}.id`
204
- : `LEFT JOIN ${r.to_table} ${alias} ON ${alias}.${r.foreign_key} = ${tableName}.id`;
205
- }).join(" ");
206
- const relCols = joinRelations.map(r => `row_to_json(${r.to_table.slice(0, -1)}.*) as ${r.name}`).join(", ");
207
- lines.push(` const rows = await query(\`SELECT ${tableName}.*, ${relCols}, COUNT(*) OVER() AS __total FROM ${tableName} ${joinClauses} ORDER BY ${tableName}.created_at DESC LIMIT $1 OFFSET $2\`, [pageSize, offset]);`);
208
- } else {
209
- lines.push(` const rows = await query(\`SELECT *, COUNT(*) OVER() AS __total FROM ${tableName} ORDER BY created_at DESC LIMIT $1 OFFSET $2\`, [pageSize, offset]);`);
210
- }
211
- lines.push(` const total = rows.length > 0 ? parseInt((rows[0] as any).__total) : 0;`);
212
- lines.push(` const items = rows.map((r: any) => { const { __total, ...rest } = r; return rest; });`);
213
- lines.push(` res.json({ items, total, page, page_size: pageSize });`);
214
- lines.push(` } catch (e: any) {`);
215
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
216
- lines.push(` }`);
217
- lines.push(`});`);
218
- lines.push(``);
219
-
220
- // UPDATE — column allowlist prevents SQL injection via field name interpolation
221
- const updatableFields = entityModel.fields.filter(f =>
222
- f.name !== "id" && f.name !== "created_at" && f.name !== "updated_at"
223
- );
224
- const allowedCols = updatableFields.map(f => `"${f.name}"`).join(", ");
225
- lines.push(`// UPDATE`);
226
- lines.push(`${toCamelCase(routeBase)}Router.put("/:id", requireAuth, async (req: Request, res: Response) => {`);
227
- lines.push(` // Only allow known columns — prevents SQL injection via field name interpolation`);
228
- lines.push(` const ALLOWED_COLUMNS = new Set([${allowedCols}]);`);
229
- lines.push(` const rawFields = { ...req.body };`);
230
- lines.push(` const fields: Record<string, unknown> = {};`);
231
- lines.push(` for (const key of Object.keys(rawFields)) {`);
232
- lines.push(` if (ALLOWED_COLUMNS.has(key)) fields[key] = rawFields[key];`);
233
- lines.push(` }`);
234
- lines.push(` if (Object.keys(fields).length === 0) {`);
235
- lines.push(` return res.status(400).json({ error: { code: "NO_VALID_FIELDS", message: "No valid fields to update" } });`);
236
- lines.push(` }`);
237
- if (mod.state_machines.length > 0) {
238
- const sm = mod.state_machines[0];
239
- lines.push(` if (fields.state !== undefined) {`);
240
- lines.push(` const current = await queryOne<{ state: string }>(\`SELECT state FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
241
- lines.push(` if (!current) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
242
- lines.push(` const trigger = \`\${current.state}_to_\${fields.state}\`;`);
243
- lines.push(` const tr = transition${sm.entity}(current.state as any, trigger);`);
244
- lines.push(` if (!tr.ok) return res.status(422).json({ error: { code: "INVALID_TRANSITION", message: \`Cannot transition from \${current.state} to \${fields.state}\` } });`);
245
- lines.push(` }`);
246
- }
247
- lines.push(` const sets = Object.keys(fields).map((k, i) => \`\${k} = $\${i + 2}\`).join(", ");`);
248
- lines.push(` const values = Object.values(fields);`);
249
- lines.push(` const sql = \`UPDATE ${tableName} SET \${sets}, updated_at = NOW() WHERE id = $1 RETURNING *\`;`);
250
- lines.push(` const rows = await query(sql, [req.params.id, ...values]);`);
251
- lines.push(` if (rows.length === 0) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
252
- lines.push(` res.json(rows[0]);`);
253
- lines.push(`});`);
254
- lines.push(``);
255
-
256
- // DELETE
257
- lines.push(`// DELETE`);
258
- lines.push(`${toCamelCase(routeBase)}Router.delete("/:id", requireAuth, async (req: Request, res: Response) => {`);
259
- lines.push(` try {`);
260
- lines.push(` const count = await execute(\`DELETE FROM ${tableName} WHERE id = $1\`, [req.params.id]);`);
261
- lines.push(` if (count === 0) return res.status(404).json({ error: { code: "NOT_FOUND", message: "Not found" } });`);
262
- lines.push(` res.status(204).send();`);
263
- lines.push(` } catch (e: any) {`);
264
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
265
- lines.push(` }`);
266
- lines.push(`});`);
267
- lines.push(``);
268
-
269
- // Capability endpoints
270
- for (const iface of mod.interfaces) {
271
- for (const method of iface.methods) {
272
- if (["create", "read", "update", "delete", "list"].includes(method.name)) continue;
273
- lines.push(emitCapabilityEndpoint(method, mod, tableName, system));
274
- }
275
- }
276
-
277
- // Relation endpoints
278
- for (const rel of mod.relations) {
279
- if (rel.kind === "has_many") {
280
- lines.push(`// RELATION: ${rel.name} (has_many ${rel.to_entity})`);
281
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id/${rel.name}", requireAuth, async (req: Request, res: Response) => {`);
282
- lines.push(` try {`);
283
- lines.push(` const page = parseInt(req.query.page as string) || 1;`);
284
- lines.push(` const pageSize = Math.min(parseInt(req.query.page_size as string) || 50, 100);`);
285
- lines.push(` const offset = (page - 1) * pageSize;`);
286
- lines.push(` // COUNT(*) OVER() avoids a separate COUNT round-trip`);
287
- lines.push(` const rows = await query(\`SELECT *, COUNT(*) OVER() AS __total FROM ${rel.to_table} WHERE ${rel.foreign_key} = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3\`, [req.params.id, pageSize, offset]);`);
288
- lines.push(` const total = rows.length > 0 ? parseInt((rows[0] as any).__total) : 0;`);
289
- lines.push(` const items = rows.map((r: any) => { const { __total, ...rest } = r; return rest; });`);
290
- lines.push(` res.json({ items, total, page, page_size: pageSize });`);
291
- lines.push(` } catch (e: any) {`);
292
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
293
- lines.push(` }`);
294
- lines.push(`});`);
295
- lines.push(``);
296
- }
297
- if (rel.kind === "many_to_many" && rel.junction_table) {
298
- lines.push(`// RELATION: ${rel.name} (many_to_many ${rel.to_entity})`);
299
- lines.push(`${toCamelCase(routeBase)}Router.get("/:id/${rel.name}", requireAuth, async (req: Request, res: Response) => {`);
300
- lines.push(` try {`);
301
- lines.push(` const rows = await query(\`SELECT ${rel.to_table}.* FROM ${rel.to_table} INNER JOIN ${rel.junction_table} ON ${rel.junction_table}.${rel.to_table.slice(0, -1)}_id = ${rel.to_table}.id WHERE ${rel.junction_table}.${rel.from_table.slice(0, -1)}_id = $1\`, [req.params.id]);`);
302
- lines.push(` res.json({ items: rows, total: rows.length });`);
303
- lines.push(` } catch (e: any) {`);
304
- lines.push(` res.status(500).json({ error: { code: "DB_ERROR", message: e.message } });`);
305
- lines.push(` }`);
306
- lines.push(`});`);
307
- lines.push(``);
308
- }
309
- }
310
-
311
- return lines.join("\n");
312
- }
313
-
314
- // ─── Capability Endpoint ──────────────────────────────────────────────────────
315
-
316
- export function emitCapabilityEndpoint(
317
- method: IR.IRMethod,
318
- mod: IR.IRModule,
319
- tableName: string,
320
- system: IR.IRSystem,
321
- ): string {
322
- const lines: string[] = [];
323
- const routerName = toCamelCase(toSnakeCase(mod.models[0]?.name || mod.name) + "s") + "Router";
324
- const endpoint = `/${method.name.replace(/_/g, "-")}`;
325
- const isTransactional = method.sync === "transactional";
326
-
327
- lines.push(`// CAPABILITY: ${method.name}${isTransactional ? " [transactional]" : ""}${method.retry ? ` [retry: ${method.retry.max_attempts}x ${method.retry.backoff}]` : ""}`);
328
- lines.push(`${routerName}.post("${endpoint}", requireAuth, async (req: Request, res: Response) => {`);
329
- lines.push(` const auth: AuthContext = (req as any).auth;`);
330
-
331
- if (method.retry) {
332
- const { max_attempts, backoff, interval_ms } = method.retry;
333
- lines.push(` let __attempt = 0;`);
334
- lines.push(` const __maxAttempts = ${max_attempts};`);
335
- lines.push(` const __intervalMs = ${interval_ms};`);
336
- lines.push(` const __backoff = "${backoff}";`);
337
- lines.push(` while (__attempt < __maxAttempts) {`);
338
- lines.push(` __attempt++;`);
339
- lines.push(` try {`);
340
- }
341
-
342
- if (isTransactional) {
343
- lines.push(` const __client = await pool.connect();`);
344
- lines.push(` try {`);
345
- lines.push(` await __client.query("BEGIN");`);
346
- } else if (method.sync === "realtime") {
347
- lines.push(` try {`);
348
- lines.push(` // sync: realtime — execute then broadcast to WebSocket channel`);
349
- } else if (method.sync === "eventual") {
350
- lines.push(` try {`);
351
- lines.push(` // sync: eventual — effects applied, events queued via outbox`);
352
- } else if (method.sync === "batch") {
353
- lines.push(` try {`);
354
- lines.push(` // sync: batch — enqueued for batch processing`);
355
- lines.push(` const { enqueueBatch } = require("../batch");`);
356
- lines.push(` const result = await enqueueBatch("${mod.name}.${method.name}", req.body);`);
357
- lines.push(` res.json({ ok: true, action: "${method.name}", queued: true, result });`);
358
- lines.push(` return;`);
359
- } else {
360
- lines.push(` try {`);
361
- }
362
-
363
- if (method.pipeline) {
364
- const { emitPipelineBody } = require("./emit_composition");
365
- lines.push(emitPipelineBody(method, " "));
366
- } else if (method.algorithm) {
367
- const { emitAlgorithmBody } = require("./emit_composition");
368
- lines.push(emitAlgorithmBody(method, " "));
369
- } else {
370
- lines.push(emitCapabilityBody(method, mod, system, " "));
371
- }
372
-
373
- if (isTransactional) {
374
- lines.push(` await __client.query("COMMIT");`);
375
- lines.push(` } catch (e: any) {`);
376
- lines.push(` await __client.query("ROLLBACK");`);
377
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
378
- lines.push(` } finally {`);
379
- lines.push(` __client.release();`);
380
- lines.push(` }`);
381
- } else if (method.sync === "realtime") {
382
- lines.push(` broadcastToChannel("${mod.name}", { type: "${method.name}", payload: req.body, actor: auth.actor_id });`);
383
- lines.push(` } catch (e: any) {`);
384
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
385
- lines.push(` }`);
386
- } else {
387
- lines.push(` } catch (e: any) {`);
388
- lines.push(` res.status(400).json({ error: { code: "CAPABILITY_FAILED", message: e.message } });`);
389
- lines.push(` }`);
390
- }
391
-
392
- if (method.retry) {
393
- lines.push(` } catch (e: any) {`);
394
- lines.push(` if (__attempt >= __maxAttempts) {`);
395
- lines.push(` res.status(503).json({ error: { code: "MAX_RETRIES_EXCEEDED", message: e.message, attempts: __attempt } });`);
396
- lines.push(` return;`);
397
- lines.push(` }`);
398
- lines.push(` const delay = __backoff === "exponential" ? __intervalMs * Math.pow(2, __attempt - 1)`);
399
- lines.push(` : __backoff === "linear" ? __intervalMs * __attempt`);
400
- lines.push(` : __intervalMs;`);
401
- lines.push(` await new Promise(r => setTimeout(r, delay));`);
402
- lines.push(` }`);
403
- lines.push(` } // end retry loop`);
404
- }
405
-
406
- lines.push(`});`);
407
- lines.push(``);
408
- return lines.join("\n");
409
- }
@@ -1,108 +0,0 @@
1
- /**
2
- * BoneScript Channel / Event / Flow / Store Lowering
3
- * Converts ChannelDecl, EventDecl, FlowDecl, and StoreDecl AST nodes into IR.
4
- */
5
-
6
- import * as AST from "./ast";
7
- import * as IR from "./ir";
8
- import { makeId, parseDurationMs, serializeExpr } from "./lowering_helpers";
9
- import { lowerField as lowerFieldHelper } from "./lowering_entities";
10
-
11
- // Re-export lowerField so lowering.ts can use a single import
12
- export { lowerField } from "./lowering_entities";
13
-
14
- // ─── Store Lowering ───────────────────────────────────────────────────────────
15
-
16
- export function lowerStore(systemName: string, store: AST.StoreDeclNode): IR.IRModule {
17
- const entityName = store.name.replace(/Store$/, "") || store.name;
18
- const model: IR.IRModel = {
19
- name: entityName,
20
- fields: store.schema.map(lowerFieldHelper),
21
- primary_key: "id",
22
- indexes: [],
23
- constraints: [],
24
- };
25
-
26
- if (!model.fields.find(f => f.name === "id")) {
27
- model.fields.unshift({
28
- name: "id", type: "uuid", nullable: false, unique: true, indexed: true, default_value: "gen_random_uuid()",
29
- });
30
- }
31
-
32
- return {
33
- id: makeId(systemName, "data_store", store.name),
34
- kind: "data_store",
35
- name: store.name,
36
- interfaces: [],
37
- models: [model],
38
- events: [],
39
- state_machines: [],
40
- relations: [],
41
- dependencies: [],
42
- config: {
43
- engine: store.engine || "postgresql",
44
- replicas: store.replicas || 1,
45
- ...(store.retention ? { retention_ms: parseDurationMs(store.retention) || 0 } : {}),
46
- ...(store.partition ? { partition_key: store.partition } : {}),
47
- },
48
- };
49
- }
50
-
51
- // ─── Channel Lowering ─────────────────────────────────────────────────────────
52
-
53
- export function lowerChannel(systemName: string, channel: AST.ChannelDeclNode): IR.IRModule {
54
- return {
55
- id: makeId(systemName, "realtime_service", channel.name),
56
- kind: "realtime_service",
57
- name: channel.name,
58
- interfaces: [{
59
- name: `I${channel.name}Channel`,
60
- methods: [
61
- { name: "connect", input: [], output: "connection", preconditions: [], effects: [], emissions: [], idempotent: false, authenticated: true, timeout_ms: 5000, retry: null, pipeline: null, algorithm: null, sync: null },
62
- { name: "subscribe", input: [{ name: "topic", type: "string", nullable: false, unique: false, indexed: false, default_value: null }], output: "subscription", preconditions: [], effects: [], emissions: [], idempotent: true, authenticated: true, timeout_ms: 5000, retry: null, pipeline: null, algorithm: null, sync: null },
63
- { name: "publish", input: [{ name: "message", type: "json", nullable: false, unique: false, indexed: false, default_value: null }], output: "void", preconditions: [], effects: [], emissions: [], idempotent: false, authenticated: true, timeout_ms: 5000, retry: null, pipeline: null, algorithm: null, sync: null },
64
- ],
65
- }],
66
- models: [],
67
- events: [],
68
- state_machines: [],
69
- relations: [],
70
- dependencies: [],
71
- config: {
72
- transport: channel.transport || "websocket",
73
- ordering: channel.ordering || "fifo",
74
- persistence: channel.persistence || "none",
75
- max_size: channel.maxSize || 10000,
76
- ...(channel.filter ? { filter: serializeExpr(channel.filter) } : {}),
77
- },
78
- };
79
- }
80
-
81
- // ─── Event Lowering ───────────────────────────────────────────────────────────
82
-
83
- export function lowerEvent(systemName: string, ev: AST.EventDeclNode, source: string): IR.IREvent {
84
- return {
85
- id: makeId(systemName, "event", ev.name),
86
- name: ev.name,
87
- payload: ev.payload.map(lowerFieldHelper),
88
- source,
89
- delivery: (ev.delivery as IR.IRDeliveryMode) || "at_least_once",
90
- ordering: "fifo",
91
- ttl_ms: parseDurationMs(ev.ttl),
92
- };
93
- }
94
-
95
- // ─── Flow Lowering ────────────────────────────────────────────────────────────
96
-
97
- export function lowerFlow(_systemName: string, flow: AST.FlowDeclNode): IR.IRFlow {
98
- return {
99
- name: flow.name,
100
- steps: flow.steps.map(s => ({
101
- name: s.name,
102
- action: `${s.action.name}(${s.action.args.map(serializeExpr).join(", ")})`,
103
- compensation: s.compensate
104
- ? `${s.compensate.name}(${s.compensate.args.map(serializeExpr).join(", ")})`
105
- : null,
106
- })),
107
- };
108
- }