bonescript-compiler 0.4.0 → 0.5.1

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/src/emitter.ts CHANGED
@@ -1,592 +1,642 @@
1
- /**
2
- * BoneScript Code Emitter — Stage 6 of the compilation pipeline.
3
- * Implements spec/09_CODEGEN.md.
4
- *
5
- * Generates target code from the IR. Every IR node maps to code.
6
- * No orphan logic. No hidden behavior. Deterministic formatting.
7
- */
8
-
9
- import * as IR from "./ir";
10
-
11
- export interface EmittedFile {
12
- path: string;
13
- content: string;
14
- language: "typescript" | "sql" | "yaml" | "json";
15
- source_module: string;
16
- }
17
-
18
- // ─── Type Mapping ────────────────────────────────────────────────────────────
19
-
20
- const TS_TYPE_MAP: Record<string, string> = {
21
- string: "string",
22
- uint: "number",
23
- int: "number",
24
- float: "number",
25
- bool: "boolean",
26
- timestamp: "Date",
27
- uuid: "string",
28
- bytes: "Buffer",
29
- json: "unknown",
30
- };
31
-
32
- const SQL_TYPE_MAP: Record<string, string> = {
33
- string: "VARCHAR",
34
- uint: "BIGINT",
35
- int: "BIGINT",
36
- float: "DOUBLE PRECISION",
37
- bool: "BOOLEAN",
38
- timestamp: "TIMESTAMPTZ",
39
- uuid: "UUID",
40
- bytes: "BYTEA",
41
- json: "JSONB",
42
- };
43
-
44
- function toTsType(irType: string): string {
45
- if (TS_TYPE_MAP[irType]) return TS_TYPE_MAP[irType];
46
- const listMatch = irType.match(/^list<(.+)>$/);
47
- if (listMatch) return `${toTsType(listMatch[1])}[]`;
48
- const setMatch = irType.match(/^set<(.+)>$/);
49
- if (setMatch) return `Set<${toTsType(setMatch[1])}>`;
50
- const mapMatch = irType.match(/^map<(.+),\s*(.+)>$/);
51
- if (mapMatch) return `Map<${toTsType(mapMatch[1])}, ${toTsType(mapMatch[2])}>`;
52
- const optMatch = irType.match(/^optional<(.+)>$/);
53
- if (optMatch) return `${toTsType(optMatch[1])} | null`;
54
- // Entity reference or unknown
55
- return irType;
56
- }
57
-
58
- function toSqlType(irType: string): string {
59
- if (SQL_TYPE_MAP[irType]) return SQL_TYPE_MAP[irType];
60
- if (irType.startsWith("list<") || irType.startsWith("set<") || irType.startsWith("map<")) return "JSONB";
61
- if (irType.startsWith("optional<")) return toSqlType(irType.slice(9, -1));
62
- return "JSONB";
63
- }
64
-
65
- /** Returns an inline SQL CHECK constraint for types that need one, or empty string. */
66
- function sqlCheckConstraint(irType: string): string {
67
- if (irType === "uint") return " CHECK (VALUE >= 0)";
68
- return "";
69
- }
70
-
71
- function toSnakeCase(s: string): string {
72
- return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
73
- }
74
-
75
- // ─── Emitter ─────────────────────────────────────────────────────────────────
76
-
77
- export class Emitter {
78
- emit(system: IR.IRSystem): EmittedFile[] {
79
- const files: EmittedFile[] = [];
80
-
81
- // 1. Schema files (SQL)
82
- for (const mod of system.modules) {
83
- if (mod.kind === "data_store" || mod.kind === "api_service") {
84
- for (const model of mod.models) {
85
- files.push(this.emitSchema(model, mod, system));
86
- }
87
- }
88
- }
89
-
90
- // 2. Type definition files (TypeScript)
91
- files.push(this.emitSharedTypes(system));
92
-
93
- // 3. Event types (TypeScript)
94
- if (system.events.length > 0) {
95
- files.push(this.emitEventTypes(system));
96
- }
97
-
98
- // 4. Service files (TypeScript)
99
- for (const mod of system.modules) {
100
- if (mod.kind === "api_service") {
101
- files.push(this.emitService(mod, system));
102
- }
103
- }
104
-
105
- // 5. State machine files (TypeScript)
106
- for (const mod of system.modules) {
107
- for (const sm of mod.state_machines) {
108
- files.push(this.emitStateMachine(sm, mod, system));
109
- }
110
- }
111
-
112
- // 6. Config files (YAML)
113
- files.push(this.emitServiceConfig(system));
114
-
115
- // 7. Infrastructure config (YAML)
116
- files.push(this.emitInfraConfig(system));
117
-
118
- return files;
119
- }
120
-
121
- // ─── SQL Schema ────────────────────────────────────────────────────────────
122
-
123
- private emitSchema(model: IR.IRModel, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
124
- const tableName = toSnakeCase(model.name) + "s";
125
- const lines: string[] = [];
126
-
127
- lines.push(`-- Generated by BoneScript compiler. DO NOT EDIT.`);
128
- lines.push(`-- Source: ${system.source_hash}`);
129
- lines.push(`-- Module: ${mod.name}`);
130
- lines.push(``);
131
- lines.push(`CREATE TABLE IF NOT EXISTS ${tableName} (`);
132
-
133
- const fieldLines: string[] = [];
134
- for (const field of model.fields) {
135
- let line = ` ${field.name} ${toSqlType(field.type)}${sqlCheckConstraint(field.type)}`;
136
- if (!field.nullable) line += " NOT NULL";
137
- if (field.default_value) {
138
- if (field.default_value === "gen_random_uuid()") line += " DEFAULT gen_random_uuid()";
139
- else if (field.default_value === "now()") line += " DEFAULT NOW()";
140
- else line += ` DEFAULT ${field.default_value}`;
141
- } else if (field.name === "created_at" || field.name === "updated_at") {
142
- // Always add DEFAULT NOW() for timestamp audit fields
143
- line += " DEFAULT NOW()";
144
- } else if (field.name === "id" && field.type === "uuid") {
145
- // Always add DEFAULT gen_random_uuid() for uuid primary keys
146
- line += " DEFAULT gen_random_uuid()";
147
- }
148
- if (field.name === model.primary_key) line += " PRIMARY KEY";
149
- fieldLines.push(line);
150
- }
151
-
152
- // Add unique constraints
153
- for (const c of model.constraints) {
154
- if (c.kind === "unique") {
155
- fieldLines.push(` CONSTRAINT ${tableName}_${c.target}_unique UNIQUE (${c.target})`);
156
- }
157
- }
158
-
159
- // Add foreign key constraints from relations
160
- for (const rel of mod.relations || []) {
161
- if (rel.kind === "belongs_to") {
162
- // belongs_to: FK is on this table
163
- fieldLines.push(` CONSTRAINT fk_${tableName}_${rel.foreign_key} FOREIGN KEY (${rel.foreign_key}) REFERENCES ${rel.to_table}(id) ON DELETE CASCADE`);
164
- }
165
- }
166
-
167
- lines.push(fieldLines.join(",\n"));
168
- lines.push(`);`);
169
- lines.push(``);
170
-
171
- // Indexes
172
- for (const idx of model.indexes) {
173
- const idxName = `idx_${tableName}_${idx.fields.join("_")}`;
174
- const unique = idx.unique ? "UNIQUE " : "";
175
- lines.push(`CREATE ${unique}INDEX IF NOT EXISTS ${idxName} ON ${tableName} (${idx.fields.join(", ")});`);
176
- }
177
-
178
- // FK indexes for belongs_to relations
179
- for (const rel of mod.relations || []) {
180
- if (rel.kind === "belongs_to") {
181
- lines.push(`CREATE INDEX IF NOT EXISTS idx_${tableName}_${rel.foreign_key} ON ${tableName} (${rel.foreign_key});`);
182
- }
183
- }
184
-
185
- // Junction tables for many_to_many
186
- for (const rel of mod.relations || []) {
187
- if (rel.kind === "many_to_many" && rel.junction_table) {
188
- lines.push(``);
189
- lines.push(`CREATE TABLE IF NOT EXISTS ${rel.junction_table} (`);
190
- lines.push(` ${rel.from_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.from_table}(id) ON DELETE CASCADE,`);
191
- lines.push(` ${rel.to_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.to_table}(id) ON DELETE CASCADE,`);
192
- lines.push(` created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),`);
193
- lines.push(` PRIMARY KEY (${rel.from_table.slice(0, -1)}_id, ${rel.to_table.slice(0, -1)}_id)`);
194
- lines.push(`);`);
195
- lines.push(`CREATE INDEX IF NOT EXISTS idx_${rel.junction_table}_${rel.from_table.slice(0, -1)} ON ${rel.junction_table} (${rel.from_table.slice(0, -1)}_id);`);
196
- lines.push(`CREATE INDEX IF NOT EXISTS idx_${rel.junction_table}_${rel.to_table.slice(0, -1)} ON ${rel.junction_table} (${rel.to_table.slice(0, -1)}_id);`);
197
- }
198
- }
199
-
200
- // Updated_at trigger
201
- if (model.fields.some(f => f.name === "updated_at")) {
202
- lines.push(``);
203
- lines.push(`CREATE OR REPLACE FUNCTION update_${tableName}_updated_at()`);
204
- lines.push(`RETURNS TRIGGER AS $$`);
205
- lines.push(`BEGIN`);
206
- lines.push(` NEW.updated_at = NOW();`);
207
- lines.push(` RETURN NEW;`);
208
- lines.push(`END;`);
209
- lines.push(`$$ LANGUAGE plpgsql;`);
210
- lines.push(``);
211
- lines.push(`CREATE TRIGGER trg_${tableName}_updated_at`);
212
- lines.push(` BEFORE UPDATE ON ${tableName}`);
213
- lines.push(` FOR EACH ROW`);
214
- lines.push(` EXECUTE FUNCTION update_${tableName}_updated_at();`);
215
- }
216
-
217
- lines.push(``);
218
-
219
- return {
220
- path: `schema/${toSnakeCase(model.name)}.sql`,
221
- content: lines.join("\n"),
222
- language: "sql",
223
- source_module: mod.id,
224
- };
225
- }
226
-
227
- // ─── Shared Types ──────────────────────────────────────────────────────────
228
-
229
- private emitSharedTypes(system: IR.IRSystem): EmittedFile {
230
- const lines: string[] = [];
231
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
232
- lines.push(`// Source: ${system.source_hash}`);
233
- lines.push(``);
234
-
235
- for (const mod of system.modules) {
236
- for (const model of mod.models) {
237
- lines.push(`export interface ${model.name} {`);
238
- for (const field of model.fields) {
239
- const nullable = field.nullable ? " | null" : "";
240
- lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
241
- }
242
- lines.push(`}`);
243
- lines.push(``);
244
- }
245
- }
246
-
247
- // Common types
248
- lines.push(`export interface ServiceError {`);
249
- lines.push(` code: string;`);
250
- lines.push(` message: string;`);
251
- lines.push(` details?: unknown;`);
252
- lines.push(`}`);
253
- lines.push(``);
254
- lines.push(`export type Result<T, E = ServiceError> =`);
255
- lines.push(` | { ok: true; value: T }`);
256
- lines.push(` | { ok: false; error: E };`);
257
- lines.push(``);
258
- lines.push(`export interface RequestContext {`);
259
- lines.push(` authenticated: boolean;`);
260
- lines.push(` actor_id: string | null;`);
261
- lines.push(` trace_id: string;`);
262
- lines.push(` correlation_id: string;`);
263
- lines.push(`}`);
264
- lines.push(``);
265
- lines.push(`export interface PaginatedResult<T> {`);
266
- lines.push(` items: T[];`);
267
- lines.push(` total: number;`);
268
- lines.push(` page: number;`);
269
- lines.push(` page_size: number;`);
270
- lines.push(`}`);
271
- lines.push(``);
272
-
273
- return {
274
- path: `types/models.ts`,
275
- content: lines.join("\n"),
276
- language: "typescript",
277
- source_module: "shared",
278
- };
279
- }
280
-
281
- // ─── Event Types ───────────────────────────────────────────────────────────
282
-
283
- private emitEventTypes(system: IR.IRSystem): EmittedFile {
284
- const lines: string[] = [];
285
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
286
- lines.push(`// Source: ${system.source_hash}`);
287
- lines.push(``);
288
-
289
- for (const ev of system.events) {
290
- lines.push(`export interface ${ev.name}Event {`);
291
- lines.push(` type: "${ev.name}";`);
292
- lines.push(` payload: {`);
293
- for (const field of ev.payload) {
294
- const nullable = field.nullable ? " | null" : "";
295
- lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
296
- }
297
- lines.push(` };`);
298
- lines.push(` metadata: {`);
299
- lines.push(` source: string;`);
300
- lines.push(` timestamp: Date;`);
301
- lines.push(` correlation_id: string;`);
302
- lines.push(` causation_id: string;`);
303
- lines.push(` };`);
304
- lines.push(`}`);
305
- lines.push(``);
306
- }
307
-
308
- // Union type of all events
309
- const eventNames = system.events.map(e => `${e.name}Event`);
310
- lines.push(`export type SystemEvent = ${eventNames.join(" | ")};`);
311
- lines.push(``);
312
-
313
- // Event bus interface
314
- lines.push(`export interface EventBus {`);
315
- lines.push(` publish(event: SystemEvent): Promise<void>;`);
316
- lines.push(` subscribe(type: string, handler: (event: SystemEvent) => Promise<void>): void;`);
317
- lines.push(`}`);
318
- lines.push(``);
319
-
320
- return {
321
- path: `types/events.ts`,
322
- content: lines.join("\n"),
323
- language: "typescript",
324
- source_module: "shared",
325
- };
326
- }
327
-
328
- // ─── Service Implementation ────────────────────────────────────────────────
329
-
330
- private emitService(mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
331
- const lines: string[] = [];
332
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
333
- lines.push(`// Source: ${system.source_hash}`);
334
- lines.push(`// Module: ${mod.name} (${mod.kind})`);
335
- lines.push(``);
336
- lines.push(`import { Result, RequestContext, ServiceError, PaginatedResult } from "../types/models";`);
337
- lines.push(``);
338
-
339
- for (const iface of mod.interfaces) {
340
- // Interface definition
341
- lines.push(`export interface ${iface.name} {`);
342
- for (const method of iface.methods) {
343
- const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
344
- const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
345
- const allParams = [ctxParam, params].filter(Boolean).join(", ");
346
- lines.push(` ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>>;`);
347
- }
348
- lines.push(`}`);
349
- lines.push(``);
350
-
351
- // Implementation class
352
- lines.push(`export class ${mod.name} implements ${iface.name} {`);
353
- for (const method of iface.methods) {
354
- lines.push(this.emitMethod(method, mod, system));
355
- }
356
- lines.push(`}`);
357
- lines.push(``);
358
- }
359
-
360
- return {
361
- path: `services/${toSnakeCase(mod.name)}.ts`,
362
- content: lines.join("\n"),
363
- language: "typescript",
364
- source_module: mod.id,
365
- };
366
- }
367
-
368
- private emitMethod(method: IR.IRMethod, mod: IR.IRModule, system: IR.IRSystem): string {
369
- const lines: string[] = [];
370
- const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
371
- const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
372
- const allParams = [ctxParam, params].filter(Boolean).join(", ");
373
-
374
- lines.push(` async ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>> {`);
375
-
376
- // Auth check
377
- if (method.authenticated) {
378
- lines.push(` // [Guard] Authentication required`);
379
- lines.push(` if (!ctx.authenticated) {`);
380
- lines.push(` return { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } };`);
381
- lines.push(` }`);
382
- lines.push(``);
383
- }
384
-
385
- // Preconditions
386
- if (method.preconditions.length > 0) {
387
- lines.push(` // [Preconditions]`);
388
- for (const pre of method.preconditions) {
389
- lines.push(` // CHECK: ${pre.description}`);
390
- }
391
- lines.push(``);
392
- }
393
-
394
- // Effects
395
- if (method.effects.length > 0) {
396
- lines.push(` // [Effects] Applied in declaration order (deterministic)`);
397
- for (const eff of method.effects) {
398
- const opSymbol = eff.op === "assign" ? "=" : eff.op === "add" ? "+=" : "-=";
399
- lines.push(` // EFFECT: ${eff.target} ${opSymbol} ${eff.value}`);
400
- }
401
- lines.push(``);
402
- }
403
-
404
- // Emissions
405
- if (method.emissions.length > 0) {
406
- lines.push(` // [Events]`);
407
- for (const ev of method.emissions) {
408
- lines.push(` // EMIT: ${ev}`);
409
- }
410
- lines.push(``);
411
- }
412
-
413
- // Real implementation — delegate to emitCapabilityBody for capabilities,
414
- // or generate CRUD SQL for standard methods
415
- const { emitCapabilityBody } = require("./emit_capability");
416
- const { emitPipelineBody, emitAlgorithmBody } = require("./emit_composition");
417
-
418
- if (method.pipeline) {
419
- lines.push(emitPipelineBody(method, " "));
420
- } else if (method.algorithm) {
421
- lines.push(emitAlgorithmBody(method, " "));
422
- } else if (method.effects.length > 0 || method.preconditions.length > 0) {
423
- // Capability with effects/preconditions — use the full capability body emitter
424
- try {
425
- lines.push(emitCapabilityBody(method, mod, system, " "));
426
- } catch {
427
- // Fallback: emit a descriptive stub if body generation fails
428
- lines.push(` // Effects: ${method.effects.map((e: any) => e.target + " " + e.op + " " + e.value).join("; ")}`);
429
- lines.push(` return { ok: false, error: { code: "NOT_IMPLEMENTED", message: "${method.name} not yet implemented" } };`);
430
- }
431
- } else {
432
- // CRUD or simple method — emit a typed not-implemented stub
433
- lines.push(` return { ok: false, error: { code: "NOT_IMPLEMENTED", message: "${method.name} not yet implemented" } };`);
434
- }
435
- lines.push(` }`);
436
- lines.push(``);
437
-
438
- return lines.join("\n");
439
- }
440
-
441
- // ─── State Machine ─────────────────────────────────────────────────────────
442
-
443
- private emitStateMachine(sm: IR.IRStateMachine, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
444
- const lines: string[] = [];
445
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
446
- lines.push(`// Source: ${system.source_hash}`);
447
- lines.push(`// Entity: ${sm.entity}`);
448
- lines.push(``);
449
-
450
- // State type
451
- const stateUnion = sm.states.map(s => `"${s}"`).join(" | ");
452
- lines.push(`export type ${sm.entity}State = ${stateUnion};`);
453
- lines.push(``);
454
-
455
- // Transition table
456
- lines.push(`export const ${sm.entity.toUpperCase()}_TRANSITIONS: Record<${sm.entity}State, Record<string, ${sm.entity}State>> = {`);
457
- for (const state of sm.states) {
458
- const transitions = sm.transitions.filter(t => t.from === state);
459
- const entries = transitions.map(t => `"${t.trigger}": "${t.to}"`).join(", ");
460
- lines.push(` "${state}": { ${entries} },`);
461
- }
462
- lines.push(`};`);
463
- lines.push(``);
464
-
465
- // Transition function
466
- lines.push(`export interface TransitionError {`);
467
- lines.push(` current: ${sm.entity}State;`);
468
- lines.push(` trigger: string;`);
469
- lines.push(` message: string;`);
470
- lines.push(`}`);
471
- lines.push(``);
472
- lines.push(`export function transition${sm.entity}(`);
473
- lines.push(` current: ${sm.entity}State,`);
474
- lines.push(` trigger: string`);
475
- lines.push(`): { ok: true; state: ${sm.entity}State } | { ok: false; error: TransitionError } {`);
476
- lines.push(` const next = ${sm.entity.toUpperCase()}_TRANSITIONS[current]?.[trigger];`);
477
- lines.push(` if (!next) {`);
478
- lines.push(` return {`);
479
- lines.push(` ok: false,`);
480
- lines.push(` error: {`);
481
- lines.push(` current,`);
482
- lines.push(` trigger,`);
483
- lines.push(` message: \`Invalid transition: \${current} --[\${trigger}]--> ?\``);
484
- lines.push(` }`);
485
- lines.push(` };`);
486
- lines.push(` }`);
487
- lines.push(` return { ok: true, state: next };`);
488
- lines.push(`}`);
489
- lines.push(``);
490
-
491
- // Initial state
492
- lines.push(`export const ${sm.entity.toUpperCase()}_INITIAL: ${sm.entity}State = "${sm.initial}";`);
493
- lines.push(``);
494
-
495
- return {
496
- path: `services/state_machines/${toSnakeCase(sm.entity)}_states.ts`,
497
- content: lines.join("\n"),
498
- language: "typescript",
499
- source_module: mod.id,
500
- };
501
- }
502
-
503
- // ─── Service Config (YAML) ─────────────────────────────────────────────────
504
-
505
- private emitServiceConfig(system: IR.IRSystem): EmittedFile {
506
- const lines: string[] = [];
507
- lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
508
- lines.push(`# Source: ${system.source_hash}`);
509
- lines.push(``);
510
- lines.push(`system:`);
511
- lines.push(` name: ${system.name}`);
512
- lines.push(` version: ${system.version}`);
513
- lines.push(` domain: ${system.domain || "generic"}`);
514
- lines.push(``);
515
- lines.push(`services:`);
516
-
517
- for (const mod of system.modules) {
518
- if (mod.kind === "api_service" || mod.kind === "realtime_service") {
519
- lines.push(` - name: ${toSnakeCase(mod.name)}`);
520
- lines.push(` kind: ${mod.kind}`);
521
- lines.push(` dependencies:`);
522
- for (const dep of mod.dependencies) {
523
- const depMod = system.modules.find(m => m.id === dep);
524
- if (depMod) lines.push(` - ${toSnakeCase(depMod.name)}`);
525
- }
526
- for (const [key, val] of Object.entries(mod.config)) {
527
- lines.push(` ${key}: ${val}`);
528
- }
529
- lines.push(``);
530
- }
531
- }
532
-
533
- return {
534
- path: `config/services.yaml`,
535
- content: lines.join("\n"),
536
- language: "yaml",
537
- source_module: "config",
538
- };
539
- }
540
-
541
- // ─── Infrastructure Config (YAML) ──────────────────────────────────────────
542
-
543
- private emitInfraConfig(system: IR.IRSystem): EmittedFile {
544
- const lines: string[] = [];
545
- lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
546
- lines.push(`# Source: ${system.source_hash}`);
547
- lines.push(``);
548
- lines.push(`infrastructure:`);
549
-
550
- // Data stores
551
- lines.push(` datastores:`);
552
- for (const mod of system.modules) {
553
- if (mod.kind === "data_store") {
554
- lines.push(` - name: ${toSnakeCase(mod.name)}`);
555
- lines.push(` engine: ${mod.config["engine"] || "postgresql"}`);
556
- lines.push(` replicas: ${mod.config["replicas"] || 1}`);
557
- if (mod.config["retention_ms"]) lines.push(` retention_ms: ${mod.config["retention_ms"]}`);
558
- if (mod.config["partition_key"]) lines.push(` partition_key: ${mod.config["partition_key"]}`);
559
- lines.push(``);
560
- }
561
- }
562
-
563
- // Gateway
564
- lines.push(` gateway:`);
565
- const gw = system.modules.find(m => m.kind === "gateway");
566
- if (gw) {
567
- for (const [key, val] of Object.entries(gw.config)) {
568
- lines.push(` ${key}: ${val}`);
569
- }
570
- }
571
- lines.push(``);
572
-
573
- // Events
574
- if (system.events.length > 0) {
575
- lines.push(` events:`);
576
- for (const ev of system.events) {
577
- lines.push(` - name: ${ev.name}`);
578
- lines.push(` delivery: ${ev.delivery}`);
579
- lines.push(` ordering: ${ev.ordering}`);
580
- if (ev.ttl_ms) lines.push(` ttl_ms: ${ev.ttl_ms}`);
581
- lines.push(``);
582
- }
583
- }
584
-
585
- return {
586
- path: `config/infrastructure.yaml`,
587
- content: lines.join("\n"),
588
- language: "yaml",
589
- source_module: "config",
590
- };
591
- }
592
- }
1
+ /**
2
+ * BoneScript Code Emitter — Stage 6 of the compilation pipeline.
3
+ * Implements spec/09_CODEGEN.md.
4
+ *
5
+ * Generates target code from the IR. Every IR node maps to code.
6
+ * No orphan logic. No hidden behavior. Deterministic formatting.
7
+ */
8
+
9
+ import * as IR from "./ir";
10
+
11
+ export interface EmittedFile {
12
+ path: string;
13
+ content: string;
14
+ language: "typescript" | "sql" | "yaml" | "json";
15
+ source_module: string;
16
+ }
17
+
18
+ // ─── Type Mapping ────────────────────────────────────────────────────────────
19
+
20
+ const TS_TYPE_MAP: Record<string, string> = {
21
+ string: "string",
22
+ uint: "number",
23
+ int: "number",
24
+ float: "number",
25
+ bool: "boolean",
26
+ timestamp: "Date",
27
+ uuid: "string",
28
+ bytes: "Buffer",
29
+ json: "unknown",
30
+ };
31
+
32
+ const SQL_TYPE_MAP: Record<string, string> = {
33
+ string: "VARCHAR",
34
+ uint: "BIGINT",
35
+ int: "BIGINT",
36
+ float: "DOUBLE PRECISION",
37
+ bool: "BOOLEAN",
38
+ timestamp: "TIMESTAMPTZ",
39
+ uuid: "UUID",
40
+ bytes: "BYTEA",
41
+ json: "JSONB",
42
+ };
43
+
44
+ function toTsType(irType: string): string {
45
+ if (TS_TYPE_MAP[irType]) return TS_TYPE_MAP[irType];
46
+ const listMatch = irType.match(/^list<(.+)>$/);
47
+ if (listMatch) return `${toTsType(listMatch[1])}[]`;
48
+ const setMatch = irType.match(/^set<(.+)>$/);
49
+ if (setMatch) return `Set<${toTsType(setMatch[1])}>`;
50
+ const mapMatch = irType.match(/^map<(.+),\s*(.+)>$/);
51
+ if (mapMatch) return `Map<${toTsType(mapMatch[1])}, ${toTsType(mapMatch[2])}>`;
52
+ const optMatch = irType.match(/^optional<(.+)>$/);
53
+ if (optMatch) return `${toTsType(optMatch[1])} | null`;
54
+ // Entity reference or unknown
55
+ return irType;
56
+ }
57
+
58
+ function toSqlType(irType: string): string {
59
+ if (SQL_TYPE_MAP[irType]) return SQL_TYPE_MAP[irType];
60
+ if (irType.startsWith("list<") || irType.startsWith("set<") || irType.startsWith("map<")) return "JSONB";
61
+ if (irType.startsWith("optional<")) return toSqlType(irType.slice(9, -1));
62
+ return "JSONB";
63
+ }
64
+
65
+ /** Returns an inline SQL CHECK constraint for types that need one, or empty string. */
66
+ function sqlCheckConstraint(irType: string): string {
67
+ if (irType === "uint") return " CHECK (VALUE >= 0)";
68
+ return "";
69
+ }
70
+
71
+ function toSnakeCase(s: string): string {
72
+ return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
73
+ }
74
+
75
+ // ─── Emitter ─────────────────────────────────────────────────────────────────
76
+
77
+ export class Emitter {
78
+ emit(system: IR.IRSystem): EmittedFile[] {
79
+ const files: EmittedFile[] = [];
80
+
81
+ // 1. Schema files (SQL)
82
+ for (const mod of system.modules) {
83
+ if (mod.kind === "data_store" || mod.kind === "api_service") {
84
+ for (const model of mod.models) {
85
+ files.push(this.emitSchema(model, mod, system));
86
+ }
87
+ }
88
+ }
89
+
90
+ // 2. Type definition files (TypeScript)
91
+ files.push(this.emitSharedTypes(system));
92
+
93
+ // 3. Event types (TypeScript)
94
+ if (system.events.length > 0) {
95
+ files.push(this.emitEventTypes(system));
96
+ }
97
+
98
+ // 4. Service files (TypeScript)
99
+ for (const mod of system.modules) {
100
+ if (mod.kind === "api_service") {
101
+ files.push(this.emitService(mod, system));
102
+ }
103
+ }
104
+
105
+ // 5. State machine files (TypeScript)
106
+ for (const mod of system.modules) {
107
+ for (const sm of mod.state_machines) {
108
+ files.push(this.emitStateMachine(sm, mod, system));
109
+ }
110
+ }
111
+
112
+ // 6. Config files (YAML)
113
+ files.push(this.emitServiceConfig(system));
114
+
115
+ // 7. Infrastructure config (YAML)
116
+ files.push(this.emitInfraConfig(system));
117
+
118
+ return files;
119
+ }
120
+
121
+ // ─── SQL Schema ────────────────────────────────────────────────────────────
122
+
123
+ private emitSchema(model: IR.IRModel, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
124
+ const tableName = toSnakeCase(model.name) + "s";
125
+ const lines: string[] = [];
126
+
127
+ lines.push(`-- Generated by BoneScript compiler. DO NOT EDIT.`);
128
+ lines.push(`-- Source: ${system.source_hash}`);
129
+ lines.push(`-- Module: ${mod.name}`);
130
+ lines.push(``);
131
+ lines.push(`CREATE TABLE IF NOT EXISTS ${tableName} (`);
132
+
133
+ const fieldLines: string[] = [];
134
+ for (const field of model.fields) {
135
+ let line = ` ${field.name} ${toSqlType(field.type)}${sqlCheckConstraint(field.type)}`;
136
+ if (!field.nullable) line += " NOT NULL";
137
+ if (field.default_value) {
138
+ if (field.default_value === "gen_random_uuid()") line += " DEFAULT gen_random_uuid()";
139
+ else if (field.default_value === "now()") line += " DEFAULT NOW()";
140
+ else line += ` DEFAULT ${field.default_value}`;
141
+ } else if (field.name === "created_at" || field.name === "updated_at") {
142
+ // Always add DEFAULT NOW() for timestamp audit fields
143
+ line += " DEFAULT NOW()";
144
+ } else if (field.name === "id" && field.type === "uuid") {
145
+ // Always add DEFAULT gen_random_uuid() for uuid primary keys
146
+ line += " DEFAULT gen_random_uuid()";
147
+ }
148
+ if (field.name === model.primary_key) line += " PRIMARY KEY";
149
+ fieldLines.push(line);
150
+ }
151
+
152
+ // Add unique constraints
153
+ for (const c of model.constraints) {
154
+ if (c.kind === "unique") {
155
+ fieldLines.push(` CONSTRAINT ${tableName}_${c.target}_unique UNIQUE (${c.target})`);
156
+ }
157
+ }
158
+
159
+ // Add foreign key constraints from relations
160
+ for (const rel of mod.relations || []) {
161
+ if (rel.kind === "belongs_to") {
162
+ // belongs_to: FK is on this table
163
+ fieldLines.push(` CONSTRAINT fk_${tableName}_${rel.foreign_key} FOREIGN KEY (${rel.foreign_key}) REFERENCES ${rel.to_table}(id) ON DELETE CASCADE`);
164
+ }
165
+ }
166
+
167
+ // Add cardinality CHECK constraints from relations
168
+ // has_one: enforce at most 1 child row via a partial unique index (emitted below)
169
+ // has_many with explicit max: enforce via CHECK on count (done via trigger — see below)
170
+ for (const rel of (mod as any).relations_with_cardinality || []) {
171
+ if (rel.cardinality && rel.cardinality.max !== "*" && typeof rel.cardinality.max === "number") {
172
+ // Will be enforced via trigger — placeholder comment
173
+ fieldLines.push(` -- cardinality: ${rel.name} max ${rel.cardinality.max} (enforced by trigger)`);
174
+ }
175
+ }
176
+
177
+ lines.push(fieldLines.join(",\n"));
178
+ lines.push(`);`);
179
+ lines.push(``);
180
+
181
+ // Indexes
182
+ for (const idx of model.indexes) {
183
+ const idxName = `idx_${tableName}_${idx.fields.join("_")}`;
184
+ const unique = idx.unique ? "UNIQUE " : "";
185
+ lines.push(`CREATE ${unique}INDEX IF NOT EXISTS ${idxName} ON ${tableName} (${idx.fields.join(", ")});`);
186
+ }
187
+
188
+ // FK indexes for belongs_to relations
189
+ for (const rel of mod.relations || []) {
190
+ if (rel.kind === "belongs_to") {
191
+ lines.push(`CREATE INDEX IF NOT EXISTS idx_${tableName}_${rel.foreign_key} ON ${tableName} (${rel.foreign_key});`);
192
+ }
193
+ }
194
+
195
+ // Cardinality enforcement
196
+ for (const rel of mod.relations || []) {
197
+ // has_one: enforce via unique index on the FK column in the child table
198
+ if (rel.kind === "has_one") {
199
+ const childTable = rel.to_table;
200
+ const fk = rel.foreign_key;
201
+ lines.push(``);
202
+ lines.push(`-- has_one cardinality: each ${tableName.slice(0, -1)} may have at most one ${childTable.slice(0, -1)}`);
203
+ lines.push(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${childTable}_${fk}_unique ON ${childTable} (${fk});`);
204
+ }
205
+
206
+ // has_many with explicit numeric max: enforce via a BEFORE INSERT trigger
207
+ if (rel.kind === "has_many" && rel.cardinality && rel.cardinality.max !== "*") {
208
+ const maxCount = rel.cardinality.max as number;
209
+ const childTable = rel.to_table;
210
+ const fk = rel.foreign_key;
211
+ const fnName = `check_${tableName}_${rel.name}_max`;
212
+ lines.push(``);
213
+ lines.push(`-- has_many cardinality: max ${maxCount} ${childTable} per ${tableName.slice(0, -1)}`);
214
+ lines.push(`CREATE OR REPLACE FUNCTION ${fnName}()`);
215
+ lines.push(`RETURNS TRIGGER AS $$`);
216
+ lines.push(`DECLARE`);
217
+ lines.push(` current_count INTEGER;`);
218
+ lines.push(`BEGIN`);
219
+ lines.push(` SELECT COUNT(*) INTO current_count FROM ${childTable} WHERE ${fk} = NEW.${fk};`);
220
+ lines.push(` IF current_count >= ${maxCount} THEN`);
221
+ lines.push(` RAISE EXCEPTION 'Cardinality violation: ${tableName.slice(0, -1)} already has ${maxCount} ${childTable} (max ${maxCount})';`);
222
+ lines.push(` END IF;`);
223
+ lines.push(` RETURN NEW;`);
224
+ lines.push(`END;`);
225
+ lines.push(`$$ LANGUAGE plpgsql;`);
226
+ lines.push(``);
227
+ lines.push(`DROP TRIGGER IF EXISTS trg_${fnName} ON ${childTable};`);
228
+ lines.push(`CREATE TRIGGER trg_${fnName}`);
229
+ lines.push(` BEFORE INSERT ON ${childTable}`);
230
+ lines.push(` FOR EACH ROW`);
231
+ lines.push(` EXECUTE FUNCTION ${fnName}();`);
232
+ }
233
+ }
234
+
235
+ // Junction tables for many_to_many
236
+ for (const rel of mod.relations || []) {
237
+ if (rel.kind === "many_to_many" && rel.junction_table) {
238
+ lines.push(``);
239
+ lines.push(`CREATE TABLE IF NOT EXISTS ${rel.junction_table} (`);
240
+ lines.push(` ${rel.from_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.from_table}(id) ON DELETE CASCADE,`);
241
+ lines.push(` ${rel.to_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.to_table}(id) ON DELETE CASCADE,`);
242
+ lines.push(` created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),`);
243
+ lines.push(` PRIMARY KEY (${rel.from_table.slice(0, -1)}_id, ${rel.to_table.slice(0, -1)}_id)`);
244
+ lines.push(`);`);
245
+ lines.push(`CREATE INDEX IF NOT EXISTS idx_${rel.junction_table}_${rel.from_table.slice(0, -1)} ON ${rel.junction_table} (${rel.from_table.slice(0, -1)}_id);`);
246
+ lines.push(`CREATE INDEX IF NOT EXISTS idx_${rel.junction_table}_${rel.to_table.slice(0, -1)} ON ${rel.junction_table} (${rel.to_table.slice(0, -1)}_id);`);
247
+ }
248
+ }
249
+
250
+ // Updated_at trigger
251
+ if (model.fields.some(f => f.name === "updated_at")) {
252
+ lines.push(``);
253
+ lines.push(`CREATE OR REPLACE FUNCTION update_${tableName}_updated_at()`);
254
+ lines.push(`RETURNS TRIGGER AS $$`);
255
+ lines.push(`BEGIN`);
256
+ lines.push(` NEW.updated_at = NOW();`);
257
+ lines.push(` RETURN NEW;`);
258
+ lines.push(`END;`);
259
+ lines.push(`$$ LANGUAGE plpgsql;`);
260
+ lines.push(``);
261
+ lines.push(`CREATE TRIGGER trg_${tableName}_updated_at`);
262
+ lines.push(` BEFORE UPDATE ON ${tableName}`);
263
+ lines.push(` FOR EACH ROW`);
264
+ lines.push(` EXECUTE FUNCTION update_${tableName}_updated_at();`);
265
+ }
266
+
267
+ lines.push(``);
268
+
269
+ return {
270
+ path: `schema/${toSnakeCase(model.name)}.sql`,
271
+ content: lines.join("\n"),
272
+ language: "sql",
273
+ source_module: mod.id,
274
+ };
275
+ }
276
+
277
+ // ─── Shared Types ──────────────────────────────────────────────────────────
278
+
279
+ private emitSharedTypes(system: IR.IRSystem): EmittedFile {
280
+ const lines: string[] = [];
281
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
282
+ lines.push(`// Source: ${system.source_hash}`);
283
+ lines.push(``);
284
+
285
+ for (const mod of system.modules) {
286
+ for (const model of mod.models) {
287
+ lines.push(`export interface ${model.name} {`);
288
+ for (const field of model.fields) {
289
+ const nullable = field.nullable ? " | null" : "";
290
+ lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
291
+ }
292
+ lines.push(`}`);
293
+ lines.push(``);
294
+ }
295
+ }
296
+
297
+ // Common types
298
+ lines.push(`export interface ServiceError {`);
299
+ lines.push(` code: string;`);
300
+ lines.push(` message: string;`);
301
+ lines.push(` details?: unknown;`);
302
+ lines.push(`}`);
303
+ lines.push(``);
304
+ lines.push(`export type Result<T, E = ServiceError> =`);
305
+ lines.push(` | { ok: true; value: T }`);
306
+ lines.push(` | { ok: false; error: E };`);
307
+ lines.push(``);
308
+ lines.push(`export interface RequestContext {`);
309
+ lines.push(` authenticated: boolean;`);
310
+ lines.push(` actor_id: string | null;`);
311
+ lines.push(` trace_id: string;`);
312
+ lines.push(` correlation_id: string;`);
313
+ lines.push(`}`);
314
+ lines.push(``);
315
+ lines.push(`export interface PaginatedResult<T> {`);
316
+ lines.push(` items: T[];`);
317
+ lines.push(` total: number;`);
318
+ lines.push(` page: number;`);
319
+ lines.push(` page_size: number;`);
320
+ lines.push(`}`);
321
+ lines.push(``);
322
+
323
+ return {
324
+ path: `types/models.ts`,
325
+ content: lines.join("\n"),
326
+ language: "typescript",
327
+ source_module: "shared",
328
+ };
329
+ }
330
+
331
+ // ─── Event Types ───────────────────────────────────────────────────────────
332
+
333
+ private emitEventTypes(system: IR.IRSystem): EmittedFile {
334
+ const lines: string[] = [];
335
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
336
+ lines.push(`// Source: ${system.source_hash}`);
337
+ lines.push(``);
338
+
339
+ for (const ev of system.events) {
340
+ lines.push(`export interface ${ev.name}Event {`);
341
+ lines.push(` type: "${ev.name}";`);
342
+ lines.push(` payload: {`);
343
+ for (const field of ev.payload) {
344
+ const nullable = field.nullable ? " | null" : "";
345
+ lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
346
+ }
347
+ lines.push(` };`);
348
+ lines.push(` metadata: {`);
349
+ lines.push(` source: string;`);
350
+ lines.push(` timestamp: Date;`);
351
+ lines.push(` correlation_id: string;`);
352
+ lines.push(` causation_id: string;`);
353
+ lines.push(` };`);
354
+ lines.push(`}`);
355
+ lines.push(``);
356
+ }
357
+
358
+ // Union type of all events
359
+ const eventNames = system.events.map(e => `${e.name}Event`);
360
+ lines.push(`export type SystemEvent = ${eventNames.join(" | ")};`);
361
+ lines.push(``);
362
+
363
+ // Event bus interface
364
+ lines.push(`export interface EventBus {`);
365
+ lines.push(` publish(event: SystemEvent): Promise<void>;`);
366
+ lines.push(` subscribe(type: string, handler: (event: SystemEvent) => Promise<void>): void;`);
367
+ lines.push(`}`);
368
+ lines.push(``);
369
+
370
+ return {
371
+ path: `types/events.ts`,
372
+ content: lines.join("\n"),
373
+ language: "typescript",
374
+ source_module: "shared",
375
+ };
376
+ }
377
+
378
+ // ─── Service Implementation ────────────────────────────────────────────────
379
+
380
+ private emitService(mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
381
+ const lines: string[] = [];
382
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
383
+ lines.push(`// Source: ${system.source_hash}`);
384
+ lines.push(`// Module: ${mod.name} (${mod.kind})`);
385
+ lines.push(``);
386
+ lines.push(`import { Result, RequestContext, ServiceError, PaginatedResult } from "../types/models";`);
387
+ lines.push(``);
388
+
389
+ for (const iface of mod.interfaces) {
390
+ // Interface definition
391
+ lines.push(`export interface ${iface.name} {`);
392
+ for (const method of iface.methods) {
393
+ const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
394
+ const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
395
+ const allParams = [ctxParam, params].filter(Boolean).join(", ");
396
+ lines.push(` ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>>;`);
397
+ }
398
+ lines.push(`}`);
399
+ lines.push(``);
400
+
401
+ // Implementation class
402
+ lines.push(`export class ${mod.name} implements ${iface.name} {`);
403
+ for (const method of iface.methods) {
404
+ lines.push(this.emitMethod(method, mod, system));
405
+ }
406
+ lines.push(`}`);
407
+ lines.push(``);
408
+ }
409
+
410
+ return {
411
+ path: `services/${toSnakeCase(mod.name)}.ts`,
412
+ content: lines.join("\n"),
413
+ language: "typescript",
414
+ source_module: mod.id,
415
+ };
416
+ }
417
+
418
+ private emitMethod(method: IR.IRMethod, mod: IR.IRModule, system: IR.IRSystem): string {
419
+ const lines: string[] = [];
420
+ const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
421
+ const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
422
+ const allParams = [ctxParam, params].filter(Boolean).join(", ");
423
+
424
+ lines.push(` async ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>> {`);
425
+
426
+ // Auth check
427
+ if (method.authenticated) {
428
+ lines.push(` // [Guard] Authentication required`);
429
+ lines.push(` if (!ctx.authenticated) {`);
430
+ lines.push(` return { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } };`);
431
+ lines.push(` }`);
432
+ lines.push(``);
433
+ }
434
+
435
+ // Preconditions
436
+ if (method.preconditions.length > 0) {
437
+ lines.push(` // [Preconditions]`);
438
+ for (const pre of method.preconditions) {
439
+ lines.push(` // CHECK: ${pre.description}`);
440
+ }
441
+ lines.push(``);
442
+ }
443
+
444
+ // Effects
445
+ if (method.effects.length > 0) {
446
+ lines.push(` // [Effects] Applied in declaration order (deterministic)`);
447
+ for (const eff of method.effects) {
448
+ const opSymbol = eff.op === "assign" ? "=" : eff.op === "add" ? "+=" : "-=";
449
+ lines.push(` // EFFECT: ${eff.target} ${opSymbol} ${eff.value}`);
450
+ }
451
+ lines.push(``);
452
+ }
453
+
454
+ // Emissions
455
+ if (method.emissions.length > 0) {
456
+ lines.push(` // [Events]`);
457
+ for (const ev of method.emissions) {
458
+ lines.push(` // EMIT: ${ev}`);
459
+ }
460
+ lines.push(``);
461
+ }
462
+
463
+ // Real implementation — delegate to emitCapabilityBody for capabilities,
464
+ // or generate CRUD SQL for standard methods
465
+ const { emitCapabilityBody } = require("./emit_capability");
466
+ const { emitPipelineBody, emitAlgorithmBody } = require("./emit_composition");
467
+
468
+ if (method.pipeline) {
469
+ lines.push(emitPipelineBody(method, " "));
470
+ } else if (method.algorithm) {
471
+ lines.push(emitAlgorithmBody(method, " "));
472
+ } else if (method.effects.length > 0 || method.preconditions.length > 0) {
473
+ // Capability with effects/preconditions — use the full capability body emitter
474
+ try {
475
+ lines.push(emitCapabilityBody(method, mod, system, " "));
476
+ } catch {
477
+ // Fallback: emit a descriptive stub if body generation fails
478
+ lines.push(` // Effects: ${method.effects.map((e: any) => e.target + " " + e.op + " " + e.value).join("; ")}`);
479
+ lines.push(` return { ok: false, error: { code: "NOT_IMPLEMENTED", message: "${method.name} not yet implemented" } };`);
480
+ }
481
+ } else {
482
+ // CRUD or simple method — emit a typed not-implemented stub
483
+ lines.push(` return { ok: false, error: { code: "NOT_IMPLEMENTED", message: "${method.name} not yet implemented" } };`);
484
+ }
485
+ lines.push(` }`);
486
+ lines.push(``);
487
+
488
+ return lines.join("\n");
489
+ }
490
+
491
+ // ─── State Machine ─────────────────────────────────────────────────────────
492
+
493
+ private emitStateMachine(sm: IR.IRStateMachine, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
494
+ const lines: string[] = [];
495
+ lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
496
+ lines.push(`// Source: ${system.source_hash}`);
497
+ lines.push(`// Entity: ${sm.entity}`);
498
+ lines.push(``);
499
+
500
+ // State type
501
+ const stateUnion = sm.states.map(s => `"${s}"`).join(" | ");
502
+ lines.push(`export type ${sm.entity}State = ${stateUnion};`);
503
+ lines.push(``);
504
+
505
+ // Transition table
506
+ lines.push(`export const ${sm.entity.toUpperCase()}_TRANSITIONS: Record<${sm.entity}State, Record<string, ${sm.entity}State>> = {`);
507
+ for (const state of sm.states) {
508
+ const transitions = sm.transitions.filter(t => t.from === state);
509
+ const entries = transitions.map(t => `"${t.trigger}": "${t.to}"`).join(", ");
510
+ lines.push(` "${state}": { ${entries} },`);
511
+ }
512
+ lines.push(`};`);
513
+ lines.push(``);
514
+
515
+ // Transition function
516
+ lines.push(`export interface TransitionError {`);
517
+ lines.push(` current: ${sm.entity}State;`);
518
+ lines.push(` trigger: string;`);
519
+ lines.push(` message: string;`);
520
+ lines.push(`}`);
521
+ lines.push(``);
522
+ lines.push(`export function transition${sm.entity}(`);
523
+ lines.push(` current: ${sm.entity}State,`);
524
+ lines.push(` trigger: string`);
525
+ lines.push(`): { ok: true; state: ${sm.entity}State } | { ok: false; error: TransitionError } {`);
526
+ lines.push(` const next = ${sm.entity.toUpperCase()}_TRANSITIONS[current]?.[trigger];`);
527
+ lines.push(` if (!next) {`);
528
+ lines.push(` return {`);
529
+ lines.push(` ok: false,`);
530
+ lines.push(` error: {`);
531
+ lines.push(` current,`);
532
+ lines.push(` trigger,`);
533
+ lines.push(` message: \`Invalid transition: \${current} --[\${trigger}]--> ?\``);
534
+ lines.push(` }`);
535
+ lines.push(` };`);
536
+ lines.push(` }`);
537
+ lines.push(` return { ok: true, state: next };`);
538
+ lines.push(`}`);
539
+ lines.push(``);
540
+
541
+ // Initial state
542
+ lines.push(`export const ${sm.entity.toUpperCase()}_INITIAL: ${sm.entity}State = "${sm.initial}";`);
543
+ lines.push(``);
544
+
545
+ return {
546
+ path: `services/state_machines/${toSnakeCase(sm.entity)}_states.ts`,
547
+ content: lines.join("\n"),
548
+ language: "typescript",
549
+ source_module: mod.id,
550
+ };
551
+ }
552
+
553
+ // ─── Service Config (YAML) ─────────────────────────────────────────────────
554
+
555
+ private emitServiceConfig(system: IR.IRSystem): EmittedFile {
556
+ const lines: string[] = [];
557
+ lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
558
+ lines.push(`# Source: ${system.source_hash}`);
559
+ lines.push(``);
560
+ lines.push(`system:`);
561
+ lines.push(` name: ${system.name}`);
562
+ lines.push(` version: ${system.version}`);
563
+ lines.push(` domain: ${system.domain || "generic"}`);
564
+ lines.push(``);
565
+ lines.push(`services:`);
566
+
567
+ for (const mod of system.modules) {
568
+ if (mod.kind === "api_service" || mod.kind === "realtime_service") {
569
+ lines.push(` - name: ${toSnakeCase(mod.name)}`);
570
+ lines.push(` kind: ${mod.kind}`);
571
+ lines.push(` dependencies:`);
572
+ for (const dep of mod.dependencies) {
573
+ const depMod = system.modules.find(m => m.id === dep);
574
+ if (depMod) lines.push(` - ${toSnakeCase(depMod.name)}`);
575
+ }
576
+ for (const [key, val] of Object.entries(mod.config)) {
577
+ lines.push(` ${key}: ${val}`);
578
+ }
579
+ lines.push(``);
580
+ }
581
+ }
582
+
583
+ return {
584
+ path: `config/services.yaml`,
585
+ content: lines.join("\n"),
586
+ language: "yaml",
587
+ source_module: "config",
588
+ };
589
+ }
590
+
591
+ // ─── Infrastructure Config (YAML) ──────────────────────────────────────────
592
+
593
+ private emitInfraConfig(system: IR.IRSystem): EmittedFile {
594
+ const lines: string[] = [];
595
+ lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
596
+ lines.push(`# Source: ${system.source_hash}`);
597
+ lines.push(``);
598
+ lines.push(`infrastructure:`);
599
+
600
+ // Data stores
601
+ lines.push(` datastores:`);
602
+ for (const mod of system.modules) {
603
+ if (mod.kind === "data_store") {
604
+ lines.push(` - name: ${toSnakeCase(mod.name)}`);
605
+ lines.push(` engine: ${mod.config["engine"] || "postgresql"}`);
606
+ lines.push(` replicas: ${mod.config["replicas"] || 1}`);
607
+ if (mod.config["retention_ms"]) lines.push(` retention_ms: ${mod.config["retention_ms"]}`);
608
+ if (mod.config["partition_key"]) lines.push(` partition_key: ${mod.config["partition_key"]}`);
609
+ lines.push(``);
610
+ }
611
+ }
612
+
613
+ // Gateway
614
+ lines.push(` gateway:`);
615
+ const gw = system.modules.find(m => m.kind === "gateway");
616
+ if (gw) {
617
+ for (const [key, val] of Object.entries(gw.config)) {
618
+ lines.push(` ${key}: ${val}`);
619
+ }
620
+ }
621
+ lines.push(``);
622
+
623
+ // Events
624
+ if (system.events.length > 0) {
625
+ lines.push(` events:`);
626
+ for (const ev of system.events) {
627
+ lines.push(` - name: ${ev.name}`);
628
+ lines.push(` delivery: ${ev.delivery}`);
629
+ lines.push(` ordering: ${ev.ordering}`);
630
+ if (ev.ttl_ms) lines.push(` ttl_ms: ${ev.ttl_ms}`);
631
+ lines.push(``);
632
+ }
633
+ }
634
+
635
+ return {
636
+ path: `config/infrastructure.yaml`,
637
+ content: lines.join("\n"),
638
+ language: "yaml",
639
+ source_module: "config",
640
+ };
641
+ }
642
+ }