bonescript-compiler 0.3.0 → 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 (52) hide show
  1. package/dist/commands/compile.js +42 -10
  2. package/dist/commands/compile.js.map +1 -1
  3. package/dist/commands/init.d.ts +1 -1
  4. package/dist/commands/init.js +29 -2
  5. package/dist/commands/init.js.map +1 -1
  6. package/dist/emit_capability.js +61 -7
  7. package/dist/emit_capability.js.map +1 -1
  8. package/dist/emit_composition.js +37 -3
  9. package/dist/emit_composition.js.map +1 -1
  10. package/dist/emit_events.d.ts +1 -0
  11. package/dist/emit_events.js +68 -1
  12. package/dist/emit_events.js.map +1 -1
  13. package/dist/emit_full.js +33 -0
  14. package/dist/emit_full.js.map +1 -1
  15. package/dist/emit_models.d.ts +12 -0
  16. package/dist/emit_models.js +171 -0
  17. package/dist/emit_models.js.map +1 -0
  18. package/dist/emit_openapi.d.ts +9 -0
  19. package/dist/emit_openapi.js +308 -0
  20. package/dist/emit_openapi.js.map +1 -0
  21. package/dist/emit_router.js +19 -4
  22. package/dist/emit_router.js.map +1 -1
  23. package/dist/emit_tests.js +37 -0
  24. package/dist/emit_tests.js.map +1 -1
  25. package/dist/emitter.js +34 -5
  26. package/dist/emitter.js.map +1 -1
  27. package/dist/lowering.js +16 -1
  28. package/dist/lowering.js.map +1 -1
  29. package/dist/lowering_channels.d.ts +1 -1
  30. package/dist/lowering_channels.js +2 -2
  31. package/dist/lowering_channels.js.map +1 -1
  32. package/dist/typechecker.js +32 -13
  33. package/dist/typechecker.js.map +1 -1
  34. package/dist/verifier.d.ts +5 -0
  35. package/dist/verifier.js +140 -2
  36. package/dist/verifier.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/commands/compile.ts +41 -10
  39. package/src/commands/init.ts +28 -2
  40. package/src/emit_capability.ts +61 -6
  41. package/src/emit_composition.ts +36 -3
  42. package/src/emit_events.ts +70 -0
  43. package/src/emit_full.ts +36 -1
  44. package/src/emit_models.ts +176 -0
  45. package/src/emit_openapi.ts +318 -0
  46. package/src/emit_router.ts +18 -4
  47. package/src/emit_tests.ts +41 -0
  48. package/src/emitter.ts +592 -566
  49. package/src/lowering.ts +19 -1
  50. package/src/lowering_channels.ts +2 -2
  51. package/src/typechecker.ts +606 -591
  52. package/src/verifier.ts +495 -348
package/src/emitter.ts CHANGED
@@ -1,566 +1,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
- function toSnakeCase(s: string): string {
66
- return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
67
- }
68
-
69
- // ─── Emitter ─────────────────────────────────────────────────────────────────
70
-
71
- export class Emitter {
72
- emit(system: IR.IRSystem): EmittedFile[] {
73
- const files: EmittedFile[] = [];
74
-
75
- // 1. Schema files (SQL)
76
- for (const mod of system.modules) {
77
- if (mod.kind === "data_store" || mod.kind === "api_service") {
78
- for (const model of mod.models) {
79
- files.push(this.emitSchema(model, mod, system));
80
- }
81
- }
82
- }
83
-
84
- // 2. Type definition files (TypeScript)
85
- files.push(this.emitSharedTypes(system));
86
-
87
- // 3. Event types (TypeScript)
88
- if (system.events.length > 0) {
89
- files.push(this.emitEventTypes(system));
90
- }
91
-
92
- // 4. Service files (TypeScript)
93
- for (const mod of system.modules) {
94
- if (mod.kind === "api_service") {
95
- files.push(this.emitService(mod, system));
96
- }
97
- }
98
-
99
- // 5. State machine files (TypeScript)
100
- for (const mod of system.modules) {
101
- for (const sm of mod.state_machines) {
102
- files.push(this.emitStateMachine(sm, mod, system));
103
- }
104
- }
105
-
106
- // 6. Config files (YAML)
107
- files.push(this.emitServiceConfig(system));
108
-
109
- // 7. Infrastructure config (YAML)
110
- files.push(this.emitInfraConfig(system));
111
-
112
- return files;
113
- }
114
-
115
- // ─── SQL Schema ────────────────────────────────────────────────────────────
116
-
117
- private emitSchema(model: IR.IRModel, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
118
- const tableName = toSnakeCase(model.name) + "s";
119
- const lines: string[] = [];
120
-
121
- lines.push(`-- Generated by BoneScript compiler. DO NOT EDIT.`);
122
- lines.push(`-- Source: ${system.source_hash}`);
123
- lines.push(`-- Module: ${mod.name}`);
124
- lines.push(``);
125
- lines.push(`CREATE TABLE IF NOT EXISTS ${tableName} (`);
126
-
127
- const fieldLines: string[] = [];
128
- for (const field of model.fields) {
129
- let line = ` ${field.name} ${toSqlType(field.type)}`;
130
- if (!field.nullable) line += " NOT NULL";
131
- if (field.default_value) {
132
- if (field.default_value === "gen_random_uuid()") line += " DEFAULT gen_random_uuid()";
133
- else if (field.default_value === "now()") line += " DEFAULT NOW()";
134
- else line += ` DEFAULT ${field.default_value}`;
135
- } else if (field.name === "created_at" || field.name === "updated_at") {
136
- // Always add DEFAULT NOW() for timestamp audit fields
137
- line += " DEFAULT NOW()";
138
- } else if (field.name === "id" && field.type === "uuid") {
139
- // Always add DEFAULT gen_random_uuid() for uuid primary keys
140
- line += " DEFAULT gen_random_uuid()";
141
- }
142
- if (field.name === model.primary_key) line += " PRIMARY KEY";
143
- fieldLines.push(line);
144
- }
145
-
146
- // Add unique constraints
147
- for (const c of model.constraints) {
148
- if (c.kind === "unique") {
149
- fieldLines.push(` CONSTRAINT ${tableName}_${c.target}_unique UNIQUE (${c.target})`);
150
- }
151
- }
152
-
153
- // Add foreign key constraints from relations
154
- for (const rel of mod.relations || []) {
155
- if (rel.kind === "belongs_to") {
156
- // belongs_to: FK is on this table
157
- fieldLines.push(` CONSTRAINT fk_${tableName}_${rel.foreign_key} FOREIGN KEY (${rel.foreign_key}) REFERENCES ${rel.to_table}(id) ON DELETE CASCADE`);
158
- }
159
- }
160
-
161
- lines.push(fieldLines.join(",\n"));
162
- lines.push(`);`);
163
- lines.push(``);
164
-
165
- // Indexes
166
- for (const idx of model.indexes) {
167
- const idxName = `idx_${tableName}_${idx.fields.join("_")}`;
168
- const unique = idx.unique ? "UNIQUE " : "";
169
- lines.push(`CREATE ${unique}INDEX IF NOT EXISTS ${idxName} ON ${tableName} (${idx.fields.join(", ")});`);
170
- }
171
-
172
- // FK indexes for belongs_to relations
173
- for (const rel of mod.relations || []) {
174
- if (rel.kind === "belongs_to") {
175
- lines.push(`CREATE INDEX IF NOT EXISTS idx_${tableName}_${rel.foreign_key} ON ${tableName} (${rel.foreign_key});`);
176
- }
177
- }
178
-
179
- // Junction tables for many_to_many
180
- for (const rel of mod.relations || []) {
181
- if (rel.kind === "many_to_many" && rel.junction_table) {
182
- lines.push(``);
183
- lines.push(`CREATE TABLE IF NOT EXISTS ${rel.junction_table} (`);
184
- lines.push(` ${rel.from_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.from_table}(id) ON DELETE CASCADE,`);
185
- lines.push(` ${rel.to_table.slice(0, -1)}_id UUID NOT NULL REFERENCES ${rel.to_table}(id) ON DELETE CASCADE,`);
186
- lines.push(` created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),`);
187
- lines.push(` PRIMARY KEY (${rel.from_table.slice(0, -1)}_id, ${rel.to_table.slice(0, -1)}_id)`);
188
- lines.push(`);`);
189
- 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);`);
190
- 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);`);
191
- }
192
- }
193
-
194
- // Updated_at trigger
195
- if (model.fields.some(f => f.name === "updated_at")) {
196
- lines.push(``);
197
- lines.push(`CREATE OR REPLACE FUNCTION update_${tableName}_updated_at()`);
198
- lines.push(`RETURNS TRIGGER AS $$`);
199
- lines.push(`BEGIN`);
200
- lines.push(` NEW.updated_at = NOW();`);
201
- lines.push(` RETURN NEW;`);
202
- lines.push(`END;`);
203
- lines.push(`$$ LANGUAGE plpgsql;`);
204
- lines.push(``);
205
- lines.push(`CREATE TRIGGER trg_${tableName}_updated_at`);
206
- lines.push(` BEFORE UPDATE ON ${tableName}`);
207
- lines.push(` FOR EACH ROW`);
208
- lines.push(` EXECUTE FUNCTION update_${tableName}_updated_at();`);
209
- }
210
-
211
- lines.push(``);
212
-
213
- return {
214
- path: `schema/${toSnakeCase(model.name)}.sql`,
215
- content: lines.join("\n"),
216
- language: "sql",
217
- source_module: mod.id,
218
- };
219
- }
220
-
221
- // ─── Shared Types ──────────────────────────────────────────────────────────
222
-
223
- private emitSharedTypes(system: IR.IRSystem): EmittedFile {
224
- const lines: string[] = [];
225
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
226
- lines.push(`// Source: ${system.source_hash}`);
227
- lines.push(``);
228
-
229
- for (const mod of system.modules) {
230
- for (const model of mod.models) {
231
- lines.push(`export interface ${model.name} {`);
232
- for (const field of model.fields) {
233
- const nullable = field.nullable ? " | null" : "";
234
- lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
235
- }
236
- lines.push(`}`);
237
- lines.push(``);
238
- }
239
- }
240
-
241
- // Common types
242
- lines.push(`export interface ServiceError {`);
243
- lines.push(` code: string;`);
244
- lines.push(` message: string;`);
245
- lines.push(` details?: unknown;`);
246
- lines.push(`}`);
247
- lines.push(``);
248
- lines.push(`export type Result<T, E = ServiceError> =`);
249
- lines.push(` | { ok: true; value: T }`);
250
- lines.push(` | { ok: false; error: E };`);
251
- lines.push(``);
252
- lines.push(`export interface RequestContext {`);
253
- lines.push(` authenticated: boolean;`);
254
- lines.push(` actor_id: string | null;`);
255
- lines.push(` trace_id: string;`);
256
- lines.push(` correlation_id: string;`);
257
- lines.push(`}`);
258
- lines.push(``);
259
- lines.push(`export interface PaginatedResult<T> {`);
260
- lines.push(` items: T[];`);
261
- lines.push(` total: number;`);
262
- lines.push(` page: number;`);
263
- lines.push(` page_size: number;`);
264
- lines.push(`}`);
265
- lines.push(``);
266
-
267
- return {
268
- path: `types/models.ts`,
269
- content: lines.join("\n"),
270
- language: "typescript",
271
- source_module: "shared",
272
- };
273
- }
274
-
275
- // ─── Event Types ───────────────────────────────────────────────────────────
276
-
277
- private emitEventTypes(system: IR.IRSystem): EmittedFile {
278
- const lines: string[] = [];
279
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
280
- lines.push(`// Source: ${system.source_hash}`);
281
- lines.push(``);
282
-
283
- for (const ev of system.events) {
284
- lines.push(`export interface ${ev.name}Event {`);
285
- lines.push(` type: "${ev.name}";`);
286
- lines.push(` payload: {`);
287
- for (const field of ev.payload) {
288
- const nullable = field.nullable ? " | null" : "";
289
- lines.push(` ${field.name}: ${toTsType(field.type)}${nullable};`);
290
- }
291
- lines.push(` };`);
292
- lines.push(` metadata: {`);
293
- lines.push(` source: string;`);
294
- lines.push(` timestamp: Date;`);
295
- lines.push(` correlation_id: string;`);
296
- lines.push(` causation_id: string;`);
297
- lines.push(` };`);
298
- lines.push(`}`);
299
- lines.push(``);
300
- }
301
-
302
- // Union type of all events
303
- const eventNames = system.events.map(e => `${e.name}Event`);
304
- lines.push(`export type SystemEvent = ${eventNames.join(" | ")};`);
305
- lines.push(``);
306
-
307
- // Event bus interface
308
- lines.push(`export interface EventBus {`);
309
- lines.push(` publish(event: SystemEvent): Promise<void>;`);
310
- lines.push(` subscribe(type: string, handler: (event: SystemEvent) => Promise<void>): void;`);
311
- lines.push(`}`);
312
- lines.push(``);
313
-
314
- return {
315
- path: `types/events.ts`,
316
- content: lines.join("\n"),
317
- language: "typescript",
318
- source_module: "shared",
319
- };
320
- }
321
-
322
- // ─── Service Implementation ────────────────────────────────────────────────
323
-
324
- private emitService(mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
325
- const lines: string[] = [];
326
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
327
- lines.push(`// Source: ${system.source_hash}`);
328
- lines.push(`// Module: ${mod.name} (${mod.kind})`);
329
- lines.push(``);
330
- lines.push(`import { Result, RequestContext, ServiceError, PaginatedResult } from "../types/models";`);
331
- lines.push(``);
332
-
333
- for (const iface of mod.interfaces) {
334
- // Interface definition
335
- lines.push(`export interface ${iface.name} {`);
336
- for (const method of iface.methods) {
337
- const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
338
- const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
339
- const allParams = [ctxParam, params].filter(Boolean).join(", ");
340
- lines.push(` ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>>;`);
341
- }
342
- lines.push(`}`);
343
- lines.push(``);
344
-
345
- // Implementation class
346
- lines.push(`export class ${mod.name} implements ${iface.name} {`);
347
- for (const method of iface.methods) {
348
- lines.push(this.emitMethod(method));
349
- }
350
- lines.push(`}`);
351
- lines.push(``);
352
- }
353
-
354
- return {
355
- path: `services/${toSnakeCase(mod.name)}.ts`,
356
- content: lines.join("\n"),
357
- language: "typescript",
358
- source_module: mod.id,
359
- };
360
- }
361
-
362
- private emitMethod(method: IR.IRMethod): string {
363
- const lines: string[] = [];
364
- const params = method.input.map(f => `${f.name}: ${toTsType(f.type)}`).join(", ");
365
- const ctxParam = method.authenticated ? "ctx: RequestContext" : "";
366
- const allParams = [ctxParam, params].filter(Boolean).join(", ");
367
-
368
- lines.push(` async ${method.name}(${allParams}): Promise<Result<${toTsType(method.output)}>> {`);
369
-
370
- // Auth check
371
- if (method.authenticated) {
372
- lines.push(` // [Guard] Authentication required`);
373
- lines.push(` if (!ctx.authenticated) {`);
374
- lines.push(` return { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } };`);
375
- lines.push(` }`);
376
- lines.push(``);
377
- }
378
-
379
- // Preconditions
380
- if (method.preconditions.length > 0) {
381
- lines.push(` // [Preconditions]`);
382
- for (const pre of method.preconditions) {
383
- lines.push(` // CHECK: ${pre.description}`);
384
- }
385
- lines.push(``);
386
- }
387
-
388
- // Effects
389
- if (method.effects.length > 0) {
390
- lines.push(` // [Effects] Applied in declaration order (deterministic)`);
391
- for (const eff of method.effects) {
392
- const opSymbol = eff.op === "assign" ? "=" : eff.op === "add" ? "+=" : "-=";
393
- lines.push(` // EFFECT: ${eff.target} ${opSymbol} ${eff.value}`);
394
- }
395
- lines.push(``);
396
- }
397
-
398
- // Emissions
399
- if (method.emissions.length > 0) {
400
- lines.push(` // [Events]`);
401
- for (const ev of method.emissions) {
402
- lines.push(` // EMIT: ${ev}`);
403
- }
404
- lines.push(``);
405
- }
406
-
407
- lines.push(` // TODO: Implementation`);
408
- lines.push(` throw new Error("Not implemented: ${method.name}");`);
409
- lines.push(` }`);
410
- lines.push(``);
411
-
412
- return lines.join("\n");
413
- }
414
-
415
- // ─── State Machine ─────────────────────────────────────────────────────────
416
-
417
- private emitStateMachine(sm: IR.IRStateMachine, mod: IR.IRModule, system: IR.IRSystem): EmittedFile {
418
- const lines: string[] = [];
419
- lines.push(`// Generated by BoneScript compiler. DO NOT EDIT.`);
420
- lines.push(`// Source: ${system.source_hash}`);
421
- lines.push(`// Entity: ${sm.entity}`);
422
- lines.push(``);
423
-
424
- // State type
425
- const stateUnion = sm.states.map(s => `"${s}"`).join(" | ");
426
- lines.push(`export type ${sm.entity}State = ${stateUnion};`);
427
- lines.push(``);
428
-
429
- // Transition table
430
- lines.push(`export const ${sm.entity.toUpperCase()}_TRANSITIONS: Record<${sm.entity}State, Record<string, ${sm.entity}State>> = {`);
431
- for (const state of sm.states) {
432
- const transitions = sm.transitions.filter(t => t.from === state);
433
- const entries = transitions.map(t => `"${t.trigger}": "${t.to}"`).join(", ");
434
- lines.push(` "${state}": { ${entries} },`);
435
- }
436
- lines.push(`};`);
437
- lines.push(``);
438
-
439
- // Transition function
440
- lines.push(`export interface TransitionError {`);
441
- lines.push(` current: ${sm.entity}State;`);
442
- lines.push(` trigger: string;`);
443
- lines.push(` message: string;`);
444
- lines.push(`}`);
445
- lines.push(``);
446
- lines.push(`export function transition${sm.entity}(`);
447
- lines.push(` current: ${sm.entity}State,`);
448
- lines.push(` trigger: string`);
449
- lines.push(`): { ok: true; state: ${sm.entity}State } | { ok: false; error: TransitionError } {`);
450
- lines.push(` const next = ${sm.entity.toUpperCase()}_TRANSITIONS[current]?.[trigger];`);
451
- lines.push(` if (!next) {`);
452
- lines.push(` return {`);
453
- lines.push(` ok: false,`);
454
- lines.push(` error: {`);
455
- lines.push(` current,`);
456
- lines.push(` trigger,`);
457
- lines.push(` message: \`Invalid transition: \${current} --[\${trigger}]--> ?\``);
458
- lines.push(` }`);
459
- lines.push(` };`);
460
- lines.push(` }`);
461
- lines.push(` return { ok: true, state: next };`);
462
- lines.push(`}`);
463
- lines.push(``);
464
-
465
- // Initial state
466
- lines.push(`export const ${sm.entity.toUpperCase()}_INITIAL: ${sm.entity}State = "${sm.initial}";`);
467
- lines.push(``);
468
-
469
- return {
470
- path: `services/state_machines/${toSnakeCase(sm.entity)}_states.ts`,
471
- content: lines.join("\n"),
472
- language: "typescript",
473
- source_module: mod.id,
474
- };
475
- }
476
-
477
- // ─── Service Config (YAML) ─────────────────────────────────────────────────
478
-
479
- private emitServiceConfig(system: IR.IRSystem): EmittedFile {
480
- const lines: string[] = [];
481
- lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
482
- lines.push(`# Source: ${system.source_hash}`);
483
- lines.push(``);
484
- lines.push(`system:`);
485
- lines.push(` name: ${system.name}`);
486
- lines.push(` version: ${system.version}`);
487
- lines.push(` domain: ${system.domain || "generic"}`);
488
- lines.push(``);
489
- lines.push(`services:`);
490
-
491
- for (const mod of system.modules) {
492
- if (mod.kind === "api_service" || mod.kind === "realtime_service") {
493
- lines.push(` - name: ${toSnakeCase(mod.name)}`);
494
- lines.push(` kind: ${mod.kind}`);
495
- lines.push(` dependencies:`);
496
- for (const dep of mod.dependencies) {
497
- const depMod = system.modules.find(m => m.id === dep);
498
- if (depMod) lines.push(` - ${toSnakeCase(depMod.name)}`);
499
- }
500
- for (const [key, val] of Object.entries(mod.config)) {
501
- lines.push(` ${key}: ${val}`);
502
- }
503
- lines.push(``);
504
- }
505
- }
506
-
507
- return {
508
- path: `config/services.yaml`,
509
- content: lines.join("\n"),
510
- language: "yaml",
511
- source_module: "config",
512
- };
513
- }
514
-
515
- // ─── Infrastructure Config (YAML) ──────────────────────────────────────────
516
-
517
- private emitInfraConfig(system: IR.IRSystem): EmittedFile {
518
- const lines: string[] = [];
519
- lines.push(`# Generated by BoneScript compiler. DO NOT EDIT.`);
520
- lines.push(`# Source: ${system.source_hash}`);
521
- lines.push(``);
522
- lines.push(`infrastructure:`);
523
-
524
- // Data stores
525
- lines.push(` datastores:`);
526
- for (const mod of system.modules) {
527
- if (mod.kind === "data_store") {
528
- lines.push(` - name: ${toSnakeCase(mod.name)}`);
529
- lines.push(` engine: ${mod.config["engine"] || "postgresql"}`);
530
- lines.push(` replicas: ${mod.config["replicas"] || 1}`);
531
- if (mod.config["retention_ms"]) lines.push(` retention_ms: ${mod.config["retention_ms"]}`);
532
- if (mod.config["partition_key"]) lines.push(` partition_key: ${mod.config["partition_key"]}`);
533
- lines.push(``);
534
- }
535
- }
536
-
537
- // Gateway
538
- lines.push(` gateway:`);
539
- const gw = system.modules.find(m => m.kind === "gateway");
540
- if (gw) {
541
- for (const [key, val] of Object.entries(gw.config)) {
542
- lines.push(` ${key}: ${val}`);
543
- }
544
- }
545
- lines.push(``);
546
-
547
- // Events
548
- if (system.events.length > 0) {
549
- lines.push(` events:`);
550
- for (const ev of system.events) {
551
- lines.push(` - name: ${ev.name}`);
552
- lines.push(` delivery: ${ev.delivery}`);
553
- lines.push(` ordering: ${ev.ordering}`);
554
- if (ev.ttl_ms) lines.push(` ttl_ms: ${ev.ttl_ms}`);
555
- lines.push(``);
556
- }
557
- }
558
-
559
- return {
560
- path: `config/infrastructure.yaml`,
561
- content: lines.join("\n"),
562
- language: "yaml",
563
- source_module: "config",
564
- };
565
- }
566
- }
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
+ }