bonescript-compiler 0.2.1 → 0.4.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 (167) hide show
  1. package/LICENSE +21 -21
  2. package/dist/algorithm_catalog.js +166 -166
  3. package/dist/cli.d.ts +2 -1
  4. package/dist/cli.js +75 -543
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/check.d.ts +5 -0
  7. package/dist/commands/check.js +34 -0
  8. package/dist/commands/check.js.map +1 -0
  9. package/dist/commands/compile.d.ts +5 -0
  10. package/dist/commands/compile.js +215 -0
  11. package/dist/commands/compile.js.map +1 -0
  12. package/dist/commands/debug.d.ts +5 -0
  13. package/dist/commands/debug.js +59 -0
  14. package/dist/commands/debug.js.map +1 -0
  15. package/dist/commands/diff.d.ts +5 -0
  16. package/dist/commands/diff.js +125 -0
  17. package/dist/commands/diff.js.map +1 -0
  18. package/dist/commands/fmt.d.ts +5 -0
  19. package/dist/commands/fmt.js +49 -0
  20. package/dist/commands/fmt.js.map +1 -0
  21. package/dist/commands/init.d.ts +5 -0
  22. package/dist/commands/init.js +96 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/ir.d.ts +5 -0
  25. package/dist/commands/ir.js +27 -0
  26. package/dist/commands/ir.js.map +1 -0
  27. package/dist/commands/lex.d.ts +5 -0
  28. package/dist/commands/lex.js +21 -0
  29. package/dist/commands/lex.js.map +1 -0
  30. package/dist/commands/parse.d.ts +5 -0
  31. package/dist/commands/parse.js +30 -0
  32. package/dist/commands/parse.js.map +1 -0
  33. package/dist/commands/test.d.ts +5 -0
  34. package/dist/commands/test.js +61 -0
  35. package/dist/commands/test.js.map +1 -0
  36. package/dist/commands/verify_determinism.d.ts +5 -0
  37. package/dist/commands/verify_determinism.js +64 -0
  38. package/dist/commands/verify_determinism.js.map +1 -0
  39. package/dist/commands/watch.d.ts +5 -0
  40. package/dist/commands/watch.js +50 -0
  41. package/dist/commands/watch.js.map +1 -0
  42. package/dist/emit_auth.d.ts +6 -0
  43. package/dist/emit_auth.js +69 -0
  44. package/dist/emit_auth.js.map +1 -0
  45. package/dist/emit_capability.d.ts +13 -0
  46. package/dist/emit_capability.js +292 -128
  47. package/dist/emit_capability.js.map +1 -1
  48. package/dist/emit_composition.js +37 -3
  49. package/dist/emit_composition.js.map +1 -1
  50. package/dist/emit_database.d.ts +7 -0
  51. package/dist/emit_database.js +74 -0
  52. package/dist/emit_database.js.map +1 -0
  53. package/dist/emit_deploy.js +162 -162
  54. package/dist/emit_events.d.ts +1 -0
  55. package/dist/emit_events.js +342 -275
  56. package/dist/emit_events.js.map +1 -1
  57. package/dist/emit_full.js +135 -95
  58. package/dist/emit_full.js.map +1 -1
  59. package/dist/emit_index.d.ts +6 -0
  60. package/dist/emit_index.js +157 -0
  61. package/dist/emit_index.js.map +1 -0
  62. package/dist/emit_maintenance.js +249 -249
  63. package/dist/emit_models.d.ts +12 -0
  64. package/dist/emit_models.js +171 -0
  65. package/dist/emit_models.js.map +1 -0
  66. package/dist/emit_openapi.d.ts +9 -0
  67. package/dist/emit_openapi.js +308 -0
  68. package/dist/emit_openapi.js.map +1 -0
  69. package/dist/emit_package.d.ts +7 -0
  70. package/dist/emit_package.js +70 -0
  71. package/dist/emit_package.js.map +1 -0
  72. package/dist/emit_router.d.ts +12 -0
  73. package/dist/emit_router.js +390 -0
  74. package/dist/emit_router.js.map +1 -0
  75. package/dist/emit_runtime.d.ts +17 -11
  76. package/dist/emit_runtime.js +29 -686
  77. package/dist/emit_runtime.js.map +1 -1
  78. package/dist/emit_sourcemap.js +66 -66
  79. package/dist/emit_tests.js +37 -0
  80. package/dist/emit_tests.js.map +1 -1
  81. package/dist/emitter.js +34 -5
  82. package/dist/emitter.js.map +1 -1
  83. package/dist/extension_manager.d.ts +2 -2
  84. package/dist/extension_manager.js +6 -3
  85. package/dist/extension_manager.js.map +1 -1
  86. package/dist/lowering.d.ts +5 -14
  87. package/dist/lowering.js +47 -417
  88. package/dist/lowering.js.map +1 -1
  89. package/dist/lowering_channels.d.ts +11 -0
  90. package/dist/lowering_channels.js +102 -0
  91. package/dist/lowering_channels.js.map +1 -0
  92. package/dist/lowering_entities.d.ts +11 -0
  93. package/dist/lowering_entities.js +222 -0
  94. package/dist/lowering_entities.js.map +1 -0
  95. package/dist/lowering_helpers.d.ts +13 -0
  96. package/dist/lowering_helpers.js +76 -0
  97. package/dist/lowering_helpers.js.map +1 -0
  98. package/dist/module_loader.d.ts +2 -2
  99. package/dist/module_loader.js +20 -23
  100. package/dist/module_loader.js.map +1 -1
  101. package/dist/scaffold.d.ts +2 -2
  102. package/dist/scaffold.js +316 -319
  103. package/dist/scaffold.js.map +1 -1
  104. package/dist/typechecker.js +32 -13
  105. package/dist/typechecker.js.map +1 -1
  106. package/dist/verifier.d.ts +5 -0
  107. package/dist/verifier.js +140 -2
  108. package/dist/verifier.js.map +1 -1
  109. package/package.json +62 -52
  110. package/src/algorithm_catalog.ts +345 -345
  111. package/src/ast.ts +334 -334
  112. package/src/cli.ts +98 -624
  113. package/src/commands/check.ts +33 -0
  114. package/src/commands/compile.ts +191 -0
  115. package/src/commands/debug.ts +33 -0
  116. package/src/commands/diff.ts +108 -0
  117. package/src/commands/fmt.ts +22 -0
  118. package/src/commands/init.ts +72 -0
  119. package/src/commands/ir.ts +23 -0
  120. package/src/commands/lex.ts +17 -0
  121. package/src/commands/parse.ts +24 -0
  122. package/src/commands/test.ts +36 -0
  123. package/src/commands/verify_determinism.ts +66 -0
  124. package/src/commands/watch.ts +25 -0
  125. package/src/emit_auth.ts +67 -0
  126. package/src/emit_batch.ts +140 -140
  127. package/src/emit_capability.ts +617 -436
  128. package/src/emit_composition.ts +229 -196
  129. package/src/emit_database.ts +75 -0
  130. package/src/emit_deploy.ts +190 -190
  131. package/src/emit_events.ts +377 -307
  132. package/src/emit_extras.ts +240 -240
  133. package/src/emit_full.ts +351 -309
  134. package/src/emit_index.ts +161 -0
  135. package/src/emit_maintenance.ts +459 -459
  136. package/src/emit_models.ts +176 -0
  137. package/src/emit_openapi.ts +318 -0
  138. package/src/emit_package.ts +69 -0
  139. package/src/emit_router.ts +409 -0
  140. package/src/emit_runtime.ts +17 -728
  141. package/src/emit_sourcemap.ts +140 -140
  142. package/src/emit_tests.ts +246 -205
  143. package/src/emit_websocket.ts +229 -229
  144. package/src/emitter.ts +31 -5
  145. package/src/extension_manager.ts +189 -187
  146. package/src/formatter.ts +297 -297
  147. package/src/index.ts +88 -88
  148. package/src/ir.ts +215 -215
  149. package/src/lexer.ts +630 -630
  150. package/src/lowering.ts +142 -556
  151. package/src/lowering_channels.ts +107 -0
  152. package/src/lowering_entities.ts +248 -0
  153. package/src/lowering_helpers.ts +75 -0
  154. package/src/module_loader.ts +112 -114
  155. package/src/optimizer.ts +196 -196
  156. package/src/parse_decls.ts +409 -409
  157. package/src/parse_decls2.ts +244 -244
  158. package/src/parse_expr.ts +197 -197
  159. package/src/parse_types.ts +54 -54
  160. package/src/parser.ts +1 -1
  161. package/src/parser_base.ts +57 -57
  162. package/src/parser_recovery.ts +153 -153
  163. package/src/scaffold.ts +372 -375
  164. package/src/solver.ts +330 -330
  165. package/src/typechecker.ts +30 -15
  166. package/src/types.ts +122 -122
  167. package/src/verifier.ts +151 -4
@@ -0,0 +1,409 @@
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
+ }