bonescript-compiler 0.2.0 → 0.3.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 (146) hide show
  1. package/LICENSE +21 -21
  2. package/dist/algorithm_catalog.js +166 -166
  3. package/dist/cli.d.ts +2 -1
  4. package/dist/cli.js +75 -543
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/check.d.ts +5 -0
  7. package/dist/commands/check.js +34 -0
  8. package/dist/commands/check.js.map +1 -0
  9. package/dist/commands/compile.d.ts +5 -0
  10. package/dist/commands/compile.js +183 -0
  11. package/dist/commands/compile.js.map +1 -0
  12. package/dist/commands/debug.d.ts +5 -0
  13. package/dist/commands/debug.js +59 -0
  14. package/dist/commands/debug.js.map +1 -0
  15. package/dist/commands/diff.d.ts +5 -0
  16. package/dist/commands/diff.js +125 -0
  17. package/dist/commands/diff.js.map +1 -0
  18. package/dist/commands/fmt.d.ts +5 -0
  19. package/dist/commands/fmt.js +49 -0
  20. package/dist/commands/fmt.js.map +1 -0
  21. package/dist/commands/init.d.ts +5 -0
  22. package/dist/commands/init.js +69 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/ir.d.ts +5 -0
  25. package/dist/commands/ir.js +27 -0
  26. package/dist/commands/ir.js.map +1 -0
  27. package/dist/commands/lex.d.ts +5 -0
  28. package/dist/commands/lex.js +21 -0
  29. package/dist/commands/lex.js.map +1 -0
  30. package/dist/commands/parse.d.ts +5 -0
  31. package/dist/commands/parse.js +30 -0
  32. package/dist/commands/parse.js.map +1 -0
  33. package/dist/commands/test.d.ts +5 -0
  34. package/dist/commands/test.js +61 -0
  35. package/dist/commands/test.js.map +1 -0
  36. package/dist/commands/verify_determinism.d.ts +5 -0
  37. package/dist/commands/verify_determinism.js +64 -0
  38. package/dist/commands/verify_determinism.js.map +1 -0
  39. package/dist/commands/watch.d.ts +5 -0
  40. package/dist/commands/watch.js +50 -0
  41. package/dist/commands/watch.js.map +1 -0
  42. package/dist/emit_auth.d.ts +6 -0
  43. package/dist/emit_auth.js +69 -0
  44. package/dist/emit_auth.js.map +1 -0
  45. package/dist/emit_capability.d.ts +13 -0
  46. package/dist/emit_capability.js +235 -125
  47. package/dist/emit_capability.js.map +1 -1
  48. package/dist/emit_database.d.ts +7 -0
  49. package/dist/emit_database.js +74 -0
  50. package/dist/emit_database.js.map +1 -0
  51. package/dist/emit_deploy.js +162 -162
  52. package/dist/emit_events.js +274 -274
  53. package/dist/emit_full.js +102 -95
  54. package/dist/emit_full.js.map +1 -1
  55. package/dist/emit_index.d.ts +6 -0
  56. package/dist/emit_index.js +157 -0
  57. package/dist/emit_index.js.map +1 -0
  58. package/dist/emit_maintenance.js +249 -249
  59. package/dist/emit_package.d.ts +7 -0
  60. package/dist/emit_package.js +70 -0
  61. package/dist/emit_package.js.map +1 -0
  62. package/dist/emit_router.d.ts +12 -0
  63. package/dist/emit_router.js +375 -0
  64. package/dist/emit_router.js.map +1 -0
  65. package/dist/emit_runtime.d.ts +17 -11
  66. package/dist/emit_runtime.js +29 -686
  67. package/dist/emit_runtime.js.map +1 -1
  68. package/dist/emit_sourcemap.js +66 -66
  69. package/dist/extension_manager.d.ts +2 -2
  70. package/dist/extension_manager.js +6 -3
  71. package/dist/extension_manager.js.map +1 -1
  72. package/dist/lowering.d.ts +5 -14
  73. package/dist/lowering.js +32 -417
  74. package/dist/lowering.js.map +1 -1
  75. package/dist/lowering_channels.d.ts +11 -0
  76. package/dist/lowering_channels.js +102 -0
  77. package/dist/lowering_channels.js.map +1 -0
  78. package/dist/lowering_entities.d.ts +11 -0
  79. package/dist/lowering_entities.js +222 -0
  80. package/dist/lowering_entities.js.map +1 -0
  81. package/dist/lowering_helpers.d.ts +13 -0
  82. package/dist/lowering_helpers.js +76 -0
  83. package/dist/lowering_helpers.js.map +1 -0
  84. package/dist/module_loader.d.ts +2 -2
  85. package/dist/module_loader.js +20 -23
  86. package/dist/module_loader.js.map +1 -1
  87. package/dist/scaffold.d.ts +2 -2
  88. package/dist/scaffold.js +316 -319
  89. package/dist/scaffold.js.map +1 -1
  90. package/package.json +62 -52
  91. package/src/algorithm_catalog.ts +345 -345
  92. package/src/ast.ts +334 -334
  93. package/src/cli.ts +98 -624
  94. package/src/commands/check.ts +33 -0
  95. package/src/commands/compile.ts +160 -0
  96. package/src/commands/debug.ts +33 -0
  97. package/src/commands/diff.ts +108 -0
  98. package/src/commands/fmt.ts +22 -0
  99. package/src/commands/init.ts +46 -0
  100. package/src/commands/ir.ts +23 -0
  101. package/src/commands/lex.ts +17 -0
  102. package/src/commands/parse.ts +24 -0
  103. package/src/commands/test.ts +36 -0
  104. package/src/commands/verify_determinism.ts +66 -0
  105. package/src/commands/watch.ts +25 -0
  106. package/src/emit_auth.ts +67 -0
  107. package/src/emit_batch.ts +140 -140
  108. package/src/emit_capability.ts +562 -436
  109. package/src/emit_composition.ts +196 -196
  110. package/src/emit_database.ts +75 -0
  111. package/src/emit_deploy.ts +190 -190
  112. package/src/emit_events.ts +307 -307
  113. package/src/emit_extras.ts +240 -240
  114. package/src/emit_full.ts +316 -309
  115. package/src/emit_index.ts +161 -0
  116. package/src/emit_maintenance.ts +459 -459
  117. package/src/emit_package.ts +69 -0
  118. package/src/emit_router.ts +395 -0
  119. package/src/emit_runtime.ts +17 -728
  120. package/src/emit_sourcemap.ts +140 -140
  121. package/src/emit_tests.ts +205 -205
  122. package/src/emit_websocket.ts +229 -229
  123. package/src/emitter.ts +566 -566
  124. package/src/extension_manager.ts +189 -187
  125. package/src/formatter.ts +297 -297
  126. package/src/index.ts +88 -88
  127. package/src/ir.ts +215 -215
  128. package/src/lexer.ts +630 -630
  129. package/src/lowering.ts +124 -556
  130. package/src/lowering_channels.ts +107 -0
  131. package/src/lowering_entities.ts +248 -0
  132. package/src/lowering_helpers.ts +75 -0
  133. package/src/module_loader.ts +112 -114
  134. package/src/optimizer.ts +196 -196
  135. package/src/parse_decls.ts +409 -409
  136. package/src/parse_decls2.ts +244 -244
  137. package/src/parse_expr.ts +197 -197
  138. package/src/parse_types.ts +54 -54
  139. package/src/parser.ts +1 -1
  140. package/src/parser_base.ts +57 -57
  141. package/src/parser_recovery.ts +153 -153
  142. package/src/scaffold.ts +372 -375
  143. package/src/solver.ts +330 -330
  144. package/src/typechecker.ts +591 -591
  145. package/src/types.ts +122 -122
  146. package/src/verifier.ts +348 -348
package/src/emit_full.ts CHANGED
@@ -1,309 +1,316 @@
1
- /**
2
- * BoneScript Full Emitter — Produces a complete, runnable project.
3
- * Combines schema generation with runtime service code.
4
- */
5
-
6
- import * as IR from "./ir";
7
- import { Emitter, EmittedFile } from "./emitter";
8
- import {
9
- emitPackageJson,
10
- emitTsConfig,
11
- emitDbClient,
12
- emitAuthMiddleware,
13
- emitEntityRouter,
14
- emitStateMachineRuntime,
15
- emitIndex,
16
- emitMigration,
17
- } from "./emit_runtime";
18
- import { emitWebSocketServer } from "./emit_websocket";
19
- import {
20
- emitLogger,
21
- emitMetrics,
22
- emitHealthChecks,
23
- emitFailureRules,
24
- emitMigrationDiff,
25
- } from "./emit_maintenance";
26
- import { emitFlowRuntime } from "./emit_extras";
27
- import { emitAlgorithmsFile, collectUsedAlgorithms } from "./emit_composition";
28
- import { emitExtensionPointStub } from "./extension_manager";
29
- import * as AST from "./ast";
30
- import { emitDurableEventBus, emitOutboxSchema } from "./emit_events";
31
- import { emitBatchExecutor } from "./emit_batch";
32
- import { emitSourceMapFile, emitDebugHandler } from "./emit_sourcemap";
33
- import { emitTestSuite } from "./emit_tests";
34
- import { emitDockerfile, emitDockerignore, emitK8sDeployment, emitGithubActions } from "./emit_deploy";
35
-
36
- function toSnakeCase(s: string): string {
37
- return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
38
- }
39
-
40
- export class FullEmitter {
41
- private schemaEmitter = new Emitter();
42
-
43
- emit(system: IR.IRSystem): EmittedFile[] {
44
- const files: EmittedFile[] = [];
45
-
46
- // 1. Package files
47
- files.push({ path: "package.json", content: emitPackageJson(system), language: "json", source_module: "root" });
48
- files.push({ path: "tsconfig.json", content: emitTsConfig(), language: "json", source_module: "root" });
49
- files.push({ path: ".env.example", content: this.emitEnvExample(system), language: "yaml", source_module: "root" });
50
-
51
- // 2. Source: infrastructure
52
- files.push({ path: "src/db.ts", content: emitDbClient(system), language: "typescript", source_module: "infra" });
53
- // Durable event bus replaces the old in-process stub
54
- files.push({ path: "src/events.ts", content: emitDurableEventBus(system), language: "typescript", source_module: "infra" });
55
- // Outbox SQL schema
56
- files.push({ path: "migrations/event_outbox.sql", content: emitOutboxSchema(), language: "sql", source_module: "infra" });
57
- files.push({ path: "src/auth.ts", content: emitAuthMiddleware(system), language: "typescript", source_module: "infra" });
58
- files.push({ path: "src/logger.ts", content: emitLogger(system), language: "typescript", source_module: "infra" });
59
- files.push({ path: "src/metrics.ts", content: emitMetrics(), language: "typescript", source_module: "infra" });
60
- files.push({ path: "src/health.ts", content: emitHealthChecks(system), language: "typescript", source_module: "infra" });
61
- files.push({ path: "src/failure_rules.ts", content: emitFailureRules(system), language: "typescript", source_module: "infra" });
62
-
63
- // 2a. WebSocket server (only if there are realtime channels)
64
- const wsContent = emitWebSocketServer(system);
65
- if (wsContent) {
66
- files.push({ path: "src/websocket.ts", content: wsContent, language: "typescript", source_module: "infra" });
67
- }
68
-
69
- // 2b. Flow saga runtime (only if there are flows)
70
- const flowContent = emitFlowRuntime(system);
71
- if (flowContent) {
72
- files.push({ path: "src/flows.ts", content: flowContent, language: "typescript", source_module: "infra" });
73
- }
74
-
75
- // 2b2. Batch executor (only if there are batch capabilities)
76
- const batchContent = emitBatchExecutor(system);
77
- if (batchContent) {
78
- files.push({ path: "src/batch.ts", content: batchContent, language: "typescript", source_module: "infra" });
79
- }
80
-
81
- // 2c. Migration diff utility (always emitted)
82
- files.push({ path: "src/migration_diff.ts", content: emitMigrationDiff(), language: "typescript", source_module: "infra" });
83
-
84
- // 2d. Algorithm implementations (only what's used)
85
- const usedAlgorithms = collectUsedAlgorithms(system);
86
- if (usedAlgorithms.size > 0) {
87
- const algoContent = emitAlgorithmsFile(usedAlgorithms);
88
- files.push({ path: "src/algorithms.ts", content: algoContent, language: "typescript", source_module: "algorithms" });
89
- } else {
90
- files.push({
91
- path: "src/algorithms.ts",
92
- content: "// No algorithms used in this system.\nexport {};\n",
93
- language: "typescript",
94
- source_module: "algorithms",
95
- });
96
- }
97
-
98
- // 2e. Extension points (escape hatches — preserved across recompilation)
99
- if (system.extension_points && system.extension_points.length > 0) {
100
- const extLines: string[] = [
101
- "// Generated by BoneScript compiler.",
102
- "// Extension points: implement the functions below.",
103
- "// Code between sentinel comments is preserved on recompile.",
104
- "// DO NOT remove the sentinel comments.",
105
- "",
106
- ];
107
- for (const ep of system.extension_points) {
108
- const params = ep.params.map((p: { name: string; type: string }) => `${p.name}: ${p.type}`).join(", ");
109
- const returnType = ep.returns || "void";
110
- extLines.push(`/**`);
111
- extLines.push(` * Extension point: ${ep.name}`);
112
- extLines.push(` * ${ep.stable ? "STABLE: implementation required." : "Optional."}`);
113
- extLines.push(` */`);
114
- extLines.push(`export function ${ep.name}(${params}): ${returnType} {`);
115
- extLines.push(` // <bonescript:ext:${ep.name}:begin>`);
116
- extLines.push(` throw new Error("Not implemented: ${ep.name}");`);
117
- extLines.push(` // <bonescript:ext:${ep.name}:end>`);
118
- extLines.push(`}`);
119
- extLines.push("");
120
- }
121
- files.push({
122
- path: "src/extensions.ts",
123
- content: extLines.join("\n"),
124
- language: "typescript",
125
- source_module: "extensions",
126
- });
127
- }
128
-
129
- // 3. Source: state machines
130
- for (const mod of system.modules) {
131
- for (const sm of mod.state_machines) {
132
- files.push({
133
- path: `src/state_machines/${toSnakeCase(sm.entity)}.ts`,
134
- content: emitStateMachineRuntime(sm),
135
- language: "typescript",
136
- source_module: mod.id,
137
- });
138
- }
139
- }
140
-
141
- // 4. Source: route files (CRUD + capabilities)
142
- for (const mod of system.modules) {
143
- if (mod.kind === "api_service" && mod.models.length > 0) {
144
- const content = emitEntityRouter(mod, system);
145
- if (content) {
146
- files.push({
147
- path: `src/routes/${toSnakeCase(mod.models[0].name)}.ts`,
148
- content,
149
- language: "typescript",
150
- source_module: mod.id,
151
- });
152
- }
153
- }
154
- }
155
-
156
- // 5. Source: main entry point
157
- files.push({ path: "src/index.ts", content: emitIndex(system), language: "typescript", source_module: "root" });
158
-
159
- // 6. SQL migrations — run schema emitter ONCE, then match by model name
160
- const schemas: string[] = [];
161
- const allSchemaFiles = this.schemaEmitter.emit(system);
162
- for (const mod of system.modules) {
163
- if (mod.kind === "data_store" || mod.kind === "api_service") {
164
- for (const model of mod.models) {
165
- const schemaFile = allSchemaFiles.find(f => f.path.includes(toSnakeCase(model.name)) && f.language === "sql");
166
- if (schemaFile) {
167
- files.push({ ...schemaFile, path: `migrations/${schemaFile.path.replace("schema/", "")}` });
168
- schemas.push(schemaFile.content);
169
- }
170
- }
171
- }
172
- }
173
-
174
- // 7. Migration runner
175
- files.push({ path: "src/migrate.ts", content: emitMigration(system, schemas), language: "typescript", source_module: "infra" });
176
-
177
- // 8. Docker compose for local dev
178
- files.push({ path: "docker-compose.yaml", content: this.emitDockerCompose(system), language: "yaml", source_module: "infra" });
179
-
180
- // 9. README
181
- files.push({ path: "README.md", content: this.emitReadme(system), language: "yaml", source_module: "root" });
182
-
183
- // 10. Source map + debug handler
184
- files.push({ path: `${system.name}.bone.map`, content: emitSourceMapFile(system, `${system.name}.bone`), language: "json", source_module: "root" });
185
- files.push({ path: "src/debug.ts", content: emitDebugHandler(system), language: "typescript", source_module: "infra" });
186
- files.push({ path: "src/tests.ts", content: emitTestSuite(system), language: "typescript", source_module: "tests" });
187
-
188
- // 11. Deploy targets
189
- files.push({ path: "Dockerfile", content: emitDockerfile(system), language: "yaml", source_module: "deploy" });
190
- files.push({ path: ".dockerignore", content: emitDockerignore(), language: "yaml", source_module: "deploy" });
191
- files.push({ path: "k8s/deployment.yaml", content: emitK8sDeployment(system), language: "yaml", source_module: "deploy" });
192
- files.push({ path: ".github/workflows/ci.yaml", content: emitGithubActions(system), language: "yaml", source_module: "deploy" });
193
-
194
- return files;
195
- }
196
-
197
- private emitEnvExample(system: IR.IRSystem): string {
198
- return `# ${system.name} Environment Variables
199
- # Copy this file to .env and fill in real values. Never commit .env to source control.
200
-
201
- # --- Required in production ---
202
- # Generate with: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
203
- JWT_SECRET=
204
-
205
- # --- Database ---
206
- DATABASE_URL=postgresql://postgres:postgres@localhost:5432/${toSnakeCase(system.name)}
207
-
208
- # --- Redis (optional, used by some domain templates) ---
209
- REDIS_URL=redis://localhost:6379
210
-
211
- # --- Server ---
212
- PORT=3000
213
- NODE_ENV=development
214
-
215
- # --- CORS ---
216
- # Comma-separated list of allowed origins. Leave empty to disallow all cross-origin requests.
217
- # Example: ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
218
- ALLOWED_ORIGINS=
219
-
220
- # --- Event delivery mode ---
221
- # in_process: in-memory, fast, no durability guarantees (default for development)
222
- # durable: Postgres-backed transactional outbox (recommended for production)
223
- EVENT_MODE=in_process
224
- EVENT_WORKER_INTERVAL_MS=1000
225
-
226
- # --- Request timeout ---
227
- REQUEST_TIMEOUT_MS=30000
228
- `;
229
- }
230
-
231
- private emitDockerCompose(system: IR.IRSystem): string {
232
- return `# Generated by BoneScript compiler.
233
- version: "3.8"
234
-
235
- services:
236
- postgres:
237
- image: postgres:16-alpine
238
- environment:
239
- POSTGRES_DB: ${toSnakeCase(system.name)}
240
- POSTGRES_USER: postgres
241
- POSTGRES_PASSWORD: postgres
242
- ports:
243
- - "5432:5432"
244
- volumes:
245
- - pgdata:/var/lib/postgresql/data
246
-
247
- redis:
248
- image: redis:7-alpine
249
- ports:
250
- - "6379:6379"
251
-
252
- volumes:
253
- pgdata:
254
- `;
255
- }
256
-
257
- private emitReadme(system: IR.IRSystem): string {
258
- const apiModules = system.modules.filter(m => m.kind === "api_service");
259
- const routes = apiModules
260
- .filter(m => m.models.length > 0)
261
- .map(m => `- \`/${toSnakeCase(m.models[0].name)}s\` — ${m.name}`)
262
- .join("\n");
263
-
264
- return `# ${system.name}
265
-
266
- Generated by BoneScript compiler. Source hash: ${system.source_hash}
267
-
268
- ## Quick Start
269
-
270
- \`\`\`bash
271
- # Start dependencies
272
- docker compose up -d
273
-
274
- # Install
275
- npm install
276
-
277
- # Run migrations
278
- npm run migrate
279
-
280
- # Start server
281
- npm run dev
282
- \`\`\`
283
-
284
- ## API Routes
285
-
286
- ${routes}
287
-
288
- Each route supports:
289
- - \`GET /\` — List (paginated)
290
- - \`GET /:id\` — Read
291
- - \`POST /\` — Create
292
- - \`PUT /:id\` — Update
293
- - \`DELETE /:id\` — Delete
294
-
295
- Plus capability-specific endpoints.
296
-
297
- ## Auth
298
-
299
- Send a Bearer token in the Authorization header:
300
- \`\`\`
301
- Authorization: Bearer <jwt-token>
302
- \`\`\`
303
-
304
- ## Environment
305
-
306
- Copy \`.env.example\` to \`.env\` and configure.
307
- `;
308
- }
309
- }
1
+ /**
2
+ * BoneScript Full Emitter — Produces a complete, runnable project.
3
+ * Combines schema generation with runtime service code.
4
+ */
5
+
6
+ import * as IR from "./ir";
7
+ import { Emitter, EmittedFile } from "./emitter";
8
+ import {
9
+ emitPackageJson,
10
+ emitTsConfig,
11
+ emitDbClient,
12
+ emitAuthMiddleware,
13
+ emitEntityRouter,
14
+ emitStateMachineRuntime,
15
+ emitIndex,
16
+ emitMigration,
17
+ } from "./emit_runtime";
18
+ import { emitWebSocketServer } from "./emit_websocket";
19
+ import {
20
+ emitLogger,
21
+ emitMetrics,
22
+ emitHealthChecks,
23
+ emitFailureRules,
24
+ emitMigrationDiff,
25
+ } from "./emit_maintenance";
26
+ import { emitFlowRuntime } from "./emit_extras";
27
+ import { emitAlgorithmsFile, collectUsedAlgorithms } from "./emit_composition";
28
+ import { emitExtensionPointStub } from "./extension_manager";
29
+ import * as AST from "./ast";
30
+ import { emitDurableEventBus, emitOutboxSchema } from "./emit_events";
31
+ import { emitBatchExecutor } from "./emit_batch";
32
+ import { emitSourceMapFile, emitDebugHandler } from "./emit_sourcemap";
33
+ import { emitTestSuite } from "./emit_tests";
34
+ import { emitDockerfile, emitDockerignore, emitK8sDeployment, emitGithubActions } from "./emit_deploy";
35
+
36
+ function toSnakeCase(s: string): string {
37
+ return s.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
38
+ }
39
+
40
+ export class FullEmitter {
41
+ private schemaEmitter = new Emitter();
42
+
43
+ emit(system: IR.IRSystem): EmittedFile[] {
44
+ const files: EmittedFile[] = [];
45
+
46
+ // 1. Package files
47
+ files.push({ path: "package.json", content: emitPackageJson(system), language: "json", source_module: "root" });
48
+ files.push({ path: "tsconfig.json", content: emitTsConfig(), language: "json", source_module: "root" });
49
+ files.push({ path: ".env.example", content: this.emitEnvExample(system), language: "yaml", source_module: "root" });
50
+
51
+ // 2. Source: infrastructure
52
+ files.push({ path: "src/db.ts", content: emitDbClient(system), language: "typescript", source_module: "infra" });
53
+ // Durable event bus replaces the old in-process stub
54
+ files.push({ path: "src/events.ts", content: emitDurableEventBus(system), language: "typescript", source_module: "infra" });
55
+ // Outbox SQL schema
56
+ files.push({ path: "migrations/event_outbox.sql", content: emitOutboxSchema(), language: "sql", source_module: "infra" });
57
+ files.push({ path: "src/auth.ts", content: emitAuthMiddleware(system), language: "typescript", source_module: "infra" });
58
+ files.push({ path: "src/logger.ts", content: emitLogger(system), language: "typescript", source_module: "infra" });
59
+ files.push({ path: "src/metrics.ts", content: emitMetrics(), language: "typescript", source_module: "infra" });
60
+ files.push({ path: "src/health.ts", content: emitHealthChecks(system), language: "typescript", source_module: "infra" });
61
+ files.push({ path: "src/failure_rules.ts", content: emitFailureRules(system), language: "typescript", source_module: "infra" });
62
+
63
+ // 2a. WebSocket server (only if there are realtime channels)
64
+ const wsContent = emitWebSocketServer(system);
65
+ if (wsContent) {
66
+ files.push({ path: "src/websocket.ts", content: wsContent, language: "typescript", source_module: "infra" });
67
+ }
68
+
69
+ // 2b. Flow saga runtime (only if there are flows)
70
+ const flowContent = emitFlowRuntime(system);
71
+ if (flowContent) {
72
+ files.push({ path: "src/flows.ts", content: flowContent, language: "typescript", source_module: "infra" });
73
+ }
74
+
75
+ // 2b2. Batch executor (only if there are batch capabilities)
76
+ const batchContent = emitBatchExecutor(system);
77
+ if (batchContent) {
78
+ files.push({ path: "src/batch.ts", content: batchContent, language: "typescript", source_module: "infra" });
79
+ }
80
+
81
+ // 2c. Migration diff utility (always emitted)
82
+ files.push({ path: "src/migration_diff.ts", content: emitMigrationDiff(), language: "typescript", source_module: "infra" });
83
+
84
+ // 2d. Algorithm implementations (only what's used)
85
+ const usedAlgorithms = collectUsedAlgorithms(system);
86
+ if (usedAlgorithms.size > 0) {
87
+ const algoContent = emitAlgorithmsFile(usedAlgorithms);
88
+ files.push({ path: "src/algorithms.ts", content: algoContent, language: "typescript", source_module: "algorithms" });
89
+ } else {
90
+ files.push({
91
+ path: "src/algorithms.ts",
92
+ content: "// No algorithms used in this system.\nexport {};\n",
93
+ language: "typescript",
94
+ source_module: "algorithms",
95
+ });
96
+ }
97
+
98
+ // 2e. Extension points (escape hatches — preserved across recompilation)
99
+ if (system.extension_points && system.extension_points.length > 0) {
100
+ const extLines: string[] = [
101
+ "// Generated by BoneScript compiler.",
102
+ "// Extension points: implement the functions below.",
103
+ "// Code between sentinel comments is preserved on recompile.",
104
+ "// DO NOT remove the sentinel comments.",
105
+ "",
106
+ ];
107
+ for (const ep of system.extension_points) {
108
+ const params = ep.params.map((p: { name: string; type: string }) => `${p.name}: ${p.type}`).join(", ");
109
+ const returnType = ep.returns || "void";
110
+ extLines.push(`/**`);
111
+ extLines.push(` * Extension point: ${ep.name}`);
112
+ extLines.push(` * ${ep.stable ? "STABLE: implementation required." : "Optional."}`);
113
+ extLines.push(` */`);
114
+ extLines.push(`export function ${ep.name}(${params}): ${returnType} {`);
115
+ extLines.push(` // <bonescript:ext:${ep.name}:begin>`);
116
+ extLines.push(` throw new Error("Not implemented: ${ep.name}");`);
117
+ extLines.push(` // <bonescript:ext:${ep.name}:end>`);
118
+ extLines.push(`}`);
119
+ extLines.push("");
120
+ }
121
+ files.push({
122
+ path: "src/extensions.ts",
123
+ content: extLines.join("\n"),
124
+ language: "typescript",
125
+ source_module: "extensions",
126
+ });
127
+ }
128
+
129
+ // 3. Source: state machines
130
+ for (const mod of system.modules) {
131
+ for (const sm of mod.state_machines) {
132
+ files.push({
133
+ path: `src/state_machines/${toSnakeCase(sm.entity)}.ts`,
134
+ content: emitStateMachineRuntime(sm),
135
+ language: "typescript",
136
+ source_module: mod.id,
137
+ });
138
+ }
139
+ }
140
+
141
+ // 4. Source: route files (CRUD + capabilities)
142
+ for (const mod of system.modules) {
143
+ if (mod.kind === "api_service" && mod.models.length > 0) {
144
+ const content = emitEntityRouter(mod, system);
145
+ if (content) {
146
+ files.push({
147
+ path: `src/routes/${toSnakeCase(mod.models[0].name)}.ts`,
148
+ content,
149
+ language: "typescript",
150
+ source_module: mod.id,
151
+ });
152
+ }
153
+ }
154
+ }
155
+
156
+ // 5. Source: main entry point
157
+ files.push({ path: "src/index.ts", content: emitIndex(system), language: "typescript", source_module: "root" });
158
+
159
+ // 6. SQL migrations — run schema emitter ONCE, then match by model name
160
+ const schemas: string[] = [];
161
+ const allSchemaFiles = this.schemaEmitter.emit(system);
162
+ for (const mod of system.modules) {
163
+ if (mod.kind === "data_store" || mod.kind === "api_service") {
164
+ for (const model of mod.models) {
165
+ const schemaFile = allSchemaFiles.find(f => f.path.includes(toSnakeCase(model.name)) && f.language === "sql");
166
+ if (schemaFile) {
167
+ files.push({ ...schemaFile, path: `migrations/${schemaFile.path.replace("schema/", "")}` });
168
+ schemas.push(schemaFile.content);
169
+ }
170
+ }
171
+ }
172
+ }
173
+
174
+ // 7. Migration runner
175
+ files.push({ path: "src/migrate.ts", content: emitMigration(system, schemas), language: "typescript", source_module: "infra" });
176
+
177
+ // 8. Docker compose for local dev
178
+ files.push({ path: "docker-compose.yaml", content: this.emitDockerCompose(system), language: "yaml", source_module: "infra" });
179
+
180
+ // 9. README
181
+ files.push({ path: "README.md", content: this.emitReadme(system), language: "yaml", source_module: "root" });
182
+
183
+ // 10. Source map + debug handler
184
+ files.push({ path: `${system.name}.bone.map`, content: emitSourceMapFile(system, `${system.name}.bone`), language: "json", source_module: "root" });
185
+ files.push({ path: "src/debug.ts", content: emitDebugHandler(system), language: "typescript", source_module: "infra" });
186
+ files.push({ path: "src/tests.ts", content: emitTestSuite(system), language: "typescript", source_module: "tests" });
187
+
188
+ // 11. Deploy targets
189
+ files.push({ path: "Dockerfile", content: emitDockerfile(system), language: "yaml", source_module: "deploy" });
190
+ files.push({ path: ".dockerignore", content: emitDockerignore(), language: "yaml", source_module: "deploy" });
191
+ files.push({ path: "k8s/deployment.yaml", content: emitK8sDeployment(system), language: "yaml", source_module: "deploy" });
192
+ files.push({ path: ".github/workflows/ci.yaml", content: emitGithubActions(system), language: "yaml", source_module: "deploy" });
193
+
194
+ return files;
195
+ }
196
+
197
+ private emitEnvExample(system: IR.IRSystem): string {
198
+ return `# ${system.name} Environment Variables
199
+ # Copy this file to .env and fill in real values. Never commit .env to source control.
200
+
201
+ # --- Required in production ---
202
+ # Generate with: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
203
+ JWT_SECRET=
204
+
205
+ # --- Database ---
206
+ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/${toSnakeCase(system.name)}
207
+
208
+ # --- Redis (optional, used by some domain templates) ---
209
+ REDIS_URL=redis://localhost:6379
210
+
211
+ # --- Server ---
212
+ PORT=3000
213
+ NODE_ENV=development
214
+
215
+ # --- CORS ---
216
+ # Comma-separated list of allowed origins. Leave empty to disallow all cross-origin requests.
217
+ # Example: ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
218
+ ALLOWED_ORIGINS=
219
+
220
+ # --- Rate limiting ---
221
+ # Global limit: requests per window per IP (default 300/min)
222
+ RATE_LIMIT_MAX=300
223
+ RATE_LIMIT_WINDOW_MS=60000
224
+ # Auth endpoints (login/register) limit per IP (default 20/min — brute-force protection)
225
+ AUTH_RATE_LIMIT_MAX=20
226
+
227
+ # --- Event delivery mode ---
228
+ # in_process: in-memory, fast, no durability guarantees (default for development)
229
+ # durable: Postgres-backed transactional outbox (recommended for production)
230
+ EVENT_MODE=in_process
231
+ EVENT_WORKER_INTERVAL_MS=1000
232
+
233
+ # --- Request timeout ---
234
+ REQUEST_TIMEOUT_MS=30000
235
+ `;
236
+ }
237
+
238
+ private emitDockerCompose(system: IR.IRSystem): string {
239
+ return `# Generated by BoneScript compiler.
240
+ version: "3.8"
241
+
242
+ services:
243
+ postgres:
244
+ image: postgres:16-alpine
245
+ environment:
246
+ POSTGRES_DB: ${toSnakeCase(system.name)}
247
+ POSTGRES_USER: postgres
248
+ POSTGRES_PASSWORD: postgres
249
+ ports:
250
+ - "5432:5432"
251
+ volumes:
252
+ - pgdata:/var/lib/postgresql/data
253
+
254
+ redis:
255
+ image: redis:7-alpine
256
+ ports:
257
+ - "6379:6379"
258
+
259
+ volumes:
260
+ pgdata:
261
+ `;
262
+ }
263
+
264
+ private emitReadme(system: IR.IRSystem): string {
265
+ const apiModules = system.modules.filter(m => m.kind === "api_service");
266
+ const routes = apiModules
267
+ .filter(m => m.models.length > 0)
268
+ .map(m => `- \`/${toSnakeCase(m.models[0].name)}s\` — ${m.name}`)
269
+ .join("\n");
270
+
271
+ return `# ${system.name}
272
+
273
+ Generated by BoneScript compiler. Source hash: ${system.source_hash}
274
+
275
+ ## Quick Start
276
+
277
+ \`\`\`bash
278
+ # Start dependencies
279
+ docker compose up -d
280
+
281
+ # Install
282
+ npm install
283
+
284
+ # Run migrations
285
+ npm run migrate
286
+
287
+ # Start server
288
+ npm run dev
289
+ \`\`\`
290
+
291
+ ## API Routes
292
+
293
+ ${routes}
294
+
295
+ Each route supports:
296
+ - \`GET /\` — List (paginated)
297
+ - \`GET /:id\` — Read
298
+ - \`POST /\` — Create
299
+ - \`PUT /:id\` — Update
300
+ - \`DELETE /:id\` — Delete
301
+
302
+ Plus capability-specific endpoints.
303
+
304
+ ## Auth
305
+
306
+ Send a Bearer token in the Authorization header:
307
+ \`\`\`
308
+ Authorization: Bearer <jwt-token>
309
+ \`\`\`
310
+
311
+ ## Environment
312
+
313
+ Copy \`.env.example\` to \`.env\` and configure.
314
+ `;
315
+ }
316
+ }