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