@specverse/engines 6.11.2 → 6.16.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.
- package/dist/ai/behavior-ai-service.js +2 -2
- package/dist/ai/behavior-ai-service.js.map +1 -1
- package/dist/libs/instance-factories/applications/templates/generic/backend-package-json-generator.js +22 -5
- package/dist/libs/instance-factories/services/postgres-native-services.yaml +90 -0
- package/dist/libs/instance-factories/services/templates/_shared/step-matching.js +44 -0
- package/dist/libs/instance-factories/services/templates/mongodb-native/controller-generator.js +18 -6
- package/dist/libs/instance-factories/services/templates/mongodb-native/step-conventions.js +230 -34
- package/dist/libs/instance-factories/services/templates/postgres-native/client-generator.js +165 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/controller-generator.js +300 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/ddl-generator.js +169 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/service-generator.js +65 -0
- package/dist/libs/instance-factories/services/templates/postgres-native/step-conventions.js +433 -0
- package/dist/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.js +1 -1
- package/dist/libs/instance-factories/services/templates/prisma/step-conventions.js +7 -34
- package/dist/realize/index.d.ts.map +1 -1
- package/dist/realize/index.js +8 -0
- package/dist/realize/index.js.map +1 -1
- package/libs/instance-factories/applications/templates/generic/backend-package-json-generator.ts +46 -24
- package/libs/instance-factories/services/postgres-native-services.yaml +90 -0
- package/libs/instance-factories/services/templates/_shared/step-matching.ts +103 -0
- package/libs/instance-factories/services/templates/mongodb-native/controller-generator.ts +25 -5
- package/libs/instance-factories/services/templates/mongodb-native/step-conventions.ts +336 -68
- package/libs/instance-factories/services/templates/postgres-native/__tests__/controller-generator.test.ts +193 -0
- package/libs/instance-factories/services/templates/postgres-native/client-generator.ts +178 -0
- package/libs/instance-factories/services/templates/postgres-native/controller-generator.ts +372 -0
- package/libs/instance-factories/services/templates/postgres-native/ddl-generator.ts +236 -0
- package/libs/instance-factories/services/templates/postgres-native/service-generator.ts +84 -0
- package/libs/instance-factories/services/templates/postgres-native/step-conventions.ts +539 -0
- package/libs/instance-factories/services/templates/prisma/ai-behaviors-generator.ts +1 -1
- package/libs/instance-factories/services/templates/prisma/step-conventions.ts +21 -68
- package/package.json +3 -3
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Postgres native (pg) — schema.sql DDL generator.
|
|
3
|
+
*
|
|
4
|
+
* Emits a single `schema.sql` script with one CREATE TABLE statement per
|
|
5
|
+
* spec model, plus indexes derived from `unique` and FK declarations.
|
|
6
|
+
* Designed to be run via `npm run db:setup` (which pipes the file through
|
|
7
|
+
* `psql "$POSTGRES_URL"`). Idempotent: every CREATE is `IF NOT EXISTS`.
|
|
8
|
+
*
|
|
9
|
+
* Type mapping (best-effort, kept simple):
|
|
10
|
+
* String, UUID, Text, Email → TEXT
|
|
11
|
+
* Integer, Int → INTEGER
|
|
12
|
+
* BigInt → BIGINT
|
|
13
|
+
* Float, Number → DOUBLE PRECISION
|
|
14
|
+
* Boolean → BOOLEAN
|
|
15
|
+
* DateTime, Date → TIMESTAMPTZ
|
|
16
|
+
* Json → JSONB
|
|
17
|
+
*
|
|
18
|
+
* Primary key:
|
|
19
|
+
* - `id UUID required` → id UUID PRIMARY KEY DEFAULT gen_random_uuid()
|
|
20
|
+
* - any other "id" required → id TEXT PRIMARY KEY
|
|
21
|
+
*
|
|
22
|
+
* Out of scope (deferred): partial indexes, RLS policies, check constraints
|
|
23
|
+
* derived from `min/max` ranges, composite keys.
|
|
24
|
+
*/
|
|
25
|
+
import type { TemplateContext } from '@specverse/types';
|
|
26
|
+
|
|
27
|
+
export default function generatePgSchemaSql(context: TemplateContext): string {
|
|
28
|
+
const { spec, models } = context as any;
|
|
29
|
+
|
|
30
|
+
// Pull a flat list of {modelName, model} from the most-likely shapes:
|
|
31
|
+
// 1. Realize passes `models` (array of model specs from the resolved
|
|
32
|
+
// component); use it directly.
|
|
33
|
+
// 2. Otherwise walk spec.components[].models.
|
|
34
|
+
const allModels: Array<[string, any]> = [];
|
|
35
|
+
if (Array.isArray(models) && models.length > 0) {
|
|
36
|
+
for (const m of models) if (m?.name) allModels.push([m.name, m]);
|
|
37
|
+
} else if (spec?.components) {
|
|
38
|
+
const components = Array.isArray(spec.components)
|
|
39
|
+
? spec.components
|
|
40
|
+
: Object.values(spec.components);
|
|
41
|
+
for (const comp of components as any[]) {
|
|
42
|
+
const ms = comp?.models;
|
|
43
|
+
if (!ms) continue;
|
|
44
|
+
const entries: [string, any][] = Array.isArray(ms)
|
|
45
|
+
? ms.map((m: any) => [m.name, m])
|
|
46
|
+
: Object.entries(ms);
|
|
47
|
+
for (const [name, m] of entries) {
|
|
48
|
+
if (name) allModels.push([name, m]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const banner = `-- ============================================================
|
|
54
|
+
-- ${spec?.metadata?.component || 'Application'} — schema.sql
|
|
55
|
+
-- Generated by @specverse/engines (postgres-native).
|
|
56
|
+
-- Run via: psql "$POSTGRES_URL" -f src/db/schema.sql
|
|
57
|
+
-- Re-runnable: every statement is IF NOT EXISTS / idempotent.
|
|
58
|
+
-- ============================================================
|
|
59
|
+
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- for gen_random_uuid()
|
|
60
|
+
`;
|
|
61
|
+
|
|
62
|
+
if (allModels.length === 0) {
|
|
63
|
+
return banner + '\n-- No models declared. (Add one to your spec to populate this file.)\n';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const tableBlocks = allModels.map(([name, model]) => generateTable(name, model));
|
|
67
|
+
return banner + '\n' + tableBlocks.join('\n\n') + '\n';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function generateTable(modelName: string, model: any): string {
|
|
71
|
+
const table = model?.storage?.table || (modelName.toLowerCase() + 's');
|
|
72
|
+
const attrs = model.attributes;
|
|
73
|
+
if (!attrs) {
|
|
74
|
+
return `-- ${modelName}\nCREATE TABLE IF NOT EXISTS "${table}" (\n id TEXT PRIMARY KEY\n);`;
|
|
75
|
+
}
|
|
76
|
+
const list: [string, any][] = Array.isArray(attrs)
|
|
77
|
+
? attrs.map((a: any) => [a.name, a])
|
|
78
|
+
: Object.entries(attrs);
|
|
79
|
+
|
|
80
|
+
const columns: string[] = [];
|
|
81
|
+
const indexes: string[] = [];
|
|
82
|
+
let hasIdColumn = false;
|
|
83
|
+
|
|
84
|
+
for (const [colName, attr] of list) {
|
|
85
|
+
if (!colName) continue;
|
|
86
|
+
const { sql, isPk, isUnique } = columnDef(colName, attr, modelName);
|
|
87
|
+
if (isPk) hasIdColumn = true;
|
|
88
|
+
columns.push(' ' + sql);
|
|
89
|
+
if (isUnique && !isPk) {
|
|
90
|
+
indexes.push(
|
|
91
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS "${table}_${colName}_uq" ON "${table}" ("${colName}");`,
|
|
92
|
+
);
|
|
93
|
+
} else if (colName.endsWith('Id') && colName !== 'id') {
|
|
94
|
+
// FK columns — index for join performance.
|
|
95
|
+
indexes.push(
|
|
96
|
+
`CREATE INDEX IF NOT EXISTS "${table}_${colName}_idx" ON "${table}" ("${colName}");`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// No id declared in spec — synthesise one so the table is keyed.
|
|
102
|
+
if (!hasIdColumn) {
|
|
103
|
+
columns.unshift(' "id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// createdAt / updatedAt — provide defaults if not declared.
|
|
107
|
+
const declaredNames = new Set(list.map(([n]) => n));
|
|
108
|
+
if (!declaredNames.has('createdAt')) {
|
|
109
|
+
columns.push(' "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
110
|
+
}
|
|
111
|
+
if (!declaredNames.has('updatedAt')) {
|
|
112
|
+
columns.push(' "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Lifecycle columns — for every declared lifecycle, add a TEXT column
|
|
116
|
+
// (named after the lifecycle, defaulting to its first state) so
|
|
117
|
+
// controller.evolve has somewhere to write the transitioned state.
|
|
118
|
+
// Mongo is schemaless so this happens implicitly there; in postgres we
|
|
119
|
+
// need an explicit column.
|
|
120
|
+
const lifecycles = Array.isArray(model.lifecycles)
|
|
121
|
+
? model.lifecycles
|
|
122
|
+
: (model.lifecycles ? Object.entries(model.lifecycles).map(([name, lc]: [string, any]) => ({ name, ...lc })) : []);
|
|
123
|
+
for (const lc of lifecycles) {
|
|
124
|
+
const lcName = lc?.name;
|
|
125
|
+
if (!lcName || declaredNames.has(lcName)) continue;
|
|
126
|
+
const initial = deriveInitialState(lc);
|
|
127
|
+
const defaultClause = initial ? ` DEFAULT '${initial.replace(/'/g, "''")}'` : '';
|
|
128
|
+
columns.push(` "${lcName}" TEXT NOT NULL${defaultClause}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const indexBlock = indexes.length > 0 ? '\n\n' + indexes.join('\n') : '';
|
|
132
|
+
return `-- ${modelName}\nCREATE TABLE IF NOT EXISTS "${table}" (\n${columns.join(',\n')}\n);${indexBlock}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
interface ColumnDefResult {
|
|
136
|
+
sql: string;
|
|
137
|
+
isPk: boolean;
|
|
138
|
+
isUnique: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function columnDef(name: string, attr: any, _modelName: string): ColumnDefResult {
|
|
142
|
+
const required = !!attr.required;
|
|
143
|
+
const unique = !!attr.unique;
|
|
144
|
+
const type = (attr.type || 'String').toLowerCase();
|
|
145
|
+
const isIdColumn = name === 'id';
|
|
146
|
+
|
|
147
|
+
if (isIdColumn) {
|
|
148
|
+
if (type === 'uuid') {
|
|
149
|
+
return { sql: `"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()`, isPk: true, isUnique: true };
|
|
150
|
+
}
|
|
151
|
+
return { sql: `"id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text`, isPk: true, isUnique: true };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let sqlType: string;
|
|
155
|
+
switch (type) {
|
|
156
|
+
case 'integer':
|
|
157
|
+
case 'int':
|
|
158
|
+
sqlType = 'INTEGER';
|
|
159
|
+
break;
|
|
160
|
+
case 'bigint':
|
|
161
|
+
sqlType = 'BIGINT';
|
|
162
|
+
break;
|
|
163
|
+
case 'float':
|
|
164
|
+
case 'number':
|
|
165
|
+
case 'double':
|
|
166
|
+
sqlType = 'DOUBLE PRECISION';
|
|
167
|
+
break;
|
|
168
|
+
case 'boolean':
|
|
169
|
+
case 'bool':
|
|
170
|
+
sqlType = 'BOOLEAN';
|
|
171
|
+
break;
|
|
172
|
+
case 'datetime':
|
|
173
|
+
case 'date':
|
|
174
|
+
case 'timestamp':
|
|
175
|
+
sqlType = 'TIMESTAMPTZ';
|
|
176
|
+
break;
|
|
177
|
+
case 'uuid':
|
|
178
|
+
sqlType = 'UUID';
|
|
179
|
+
break;
|
|
180
|
+
case 'json':
|
|
181
|
+
case 'jsonb':
|
|
182
|
+
sqlType = 'JSONB';
|
|
183
|
+
break;
|
|
184
|
+
default:
|
|
185
|
+
sqlType = 'TEXT';
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const nullness = required ? ' NOT NULL' : '';
|
|
189
|
+
const uniqueClause = unique ? ' UNIQUE' : '';
|
|
190
|
+
const defaultClause = formatColumnDefault(attr.default, type);
|
|
191
|
+
return {
|
|
192
|
+
sql: `"${name}" ${sqlType}${nullness}${uniqueClause}${defaultClause}`,
|
|
193
|
+
isPk: false,
|
|
194
|
+
isUnique: unique,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Derive the initial state from a lifecycle declaration. Handles:
|
|
199
|
+
* - explicit `initial: stateName`
|
|
200
|
+
* - explicit states[] array — first entry
|
|
201
|
+
* - `flow: "a -> b -> c"` shorthand — first arrow-source
|
|
202
|
+
*/
|
|
203
|
+
function deriveInitialState(lc: any): string | null {
|
|
204
|
+
if (!lc) return null;
|
|
205
|
+
if (typeof lc.initial === 'string') return lc.initial;
|
|
206
|
+
if (Array.isArray(lc.states) && lc.states.length > 0) {
|
|
207
|
+
const first = lc.states[0];
|
|
208
|
+
return typeof first === 'string' ? first : (first?.name ?? null);
|
|
209
|
+
}
|
|
210
|
+
if (typeof lc.flow === 'string') {
|
|
211
|
+
const head = lc.flow.split(/\s*->\s*/)[0]?.trim();
|
|
212
|
+
return head || null;
|
|
213
|
+
}
|
|
214
|
+
if (lc.transitions && typeof lc.transitions === 'object') {
|
|
215
|
+
// Pick the source side of the first transition.
|
|
216
|
+
const first = Object.values(lc.transitions)[0];
|
|
217
|
+
if (typeof first === 'string') return first.split(/\s*->\s*/)[0]?.trim() || null;
|
|
218
|
+
}
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function formatColumnDefault(value: any, type: string): string {
|
|
223
|
+
if (value === undefined || value === null) return '';
|
|
224
|
+
if (typeof value === 'boolean') return ` DEFAULT ${value}`;
|
|
225
|
+
if (typeof value === 'number') return ` DEFAULT ${value}`;
|
|
226
|
+
if (typeof value === 'string') {
|
|
227
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return ` DEFAULT ${value}`;
|
|
228
|
+
if (value === 'true' || value === 'false') return ` DEFAULT ${value}`;
|
|
229
|
+
if (value === 'now' && (type === 'datetime' || type === 'date' || type === 'timestamp')) {
|
|
230
|
+
return ` DEFAULT NOW()`;
|
|
231
|
+
}
|
|
232
|
+
// Quoted SQL string literal — escape single quotes.
|
|
233
|
+
return ` DEFAULT '${value.replace(/'/g, "''")}'`;
|
|
234
|
+
}
|
|
235
|
+
return '';
|
|
236
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL Native (pg) — Service Generator
|
|
3
|
+
*
|
|
4
|
+
* Generates abstract business-logic services that use the pgClient
|
|
5
|
+
* helpers directly. The service body is intentionally skeletal: each
|
|
6
|
+
* declared operation gets a typed method, but the body is a TODO stub
|
|
7
|
+
* containing the spec steps as comments. The behavior-step → SQL
|
|
8
|
+
* conventions for service bodies are a follow-up; controllers already
|
|
9
|
+
* inline conventions today.
|
|
10
|
+
*/
|
|
11
|
+
import type { TemplateContext } from '@specverse/types';
|
|
12
|
+
|
|
13
|
+
export default function generatePgNativeService(context: TemplateContext): string {
|
|
14
|
+
const { service } = context;
|
|
15
|
+
if (!service) throw new Error('Service is required in template context');
|
|
16
|
+
|
|
17
|
+
const serviceName = service.name;
|
|
18
|
+
const operationsCode = generateOperations(service);
|
|
19
|
+
const usesDb = /\bquery\b|\bgetPool\b/.test(operationsCode);
|
|
20
|
+
const hasEvents = (service.publishes && service.publishes.length > 0) ||
|
|
21
|
+
(service.subscribes && service.subscribes.length > 0);
|
|
22
|
+
|
|
23
|
+
return `/**
|
|
24
|
+
* ${serviceName}
|
|
25
|
+
* Abstract business logic service (PostgreSQL native driver)
|
|
26
|
+
* ${service.description || ''}
|
|
27
|
+
*/
|
|
28
|
+
${usesDb ? `import { query, getPool } from '../db/pgClient.js';` : ''}
|
|
29
|
+
${hasEvents ? `import { eventBus } from '../events/eventBus.js';` : ''}
|
|
30
|
+
|
|
31
|
+
export class ${serviceName} {
|
|
32
|
+
${operationsCode}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ${lowerFirst(serviceName)} = new ${serviceName}();
|
|
36
|
+
export const ${lowerFirst(serviceName)}Instance = ${lowerFirst(serviceName)};
|
|
37
|
+
export default ${lowerFirst(serviceName)};
|
|
38
|
+
`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function lowerFirst(s: string): string {
|
|
42
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function generateOperations(service: any): string {
|
|
46
|
+
const ops = service.operations;
|
|
47
|
+
if (!ops || (Array.isArray(ops) && ops.length === 0) || (!Array.isArray(ops) && Object.keys(ops).length === 0)) {
|
|
48
|
+
return `
|
|
49
|
+
/**
|
|
50
|
+
* Default service entrypoint — replace with real operations once declared
|
|
51
|
+
* on the service's spec.
|
|
52
|
+
*/
|
|
53
|
+
public async execute(_params: any = {}): Promise<any> {
|
|
54
|
+
throw new Error('${service.name}.execute is not implemented');
|
|
55
|
+
}
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
const entries: [string, any][] = Array.isArray(ops)
|
|
59
|
+
? ops.map((op: any) => [op.name, op])
|
|
60
|
+
: Object.entries(ops);
|
|
61
|
+
return entries.map(([name, op]) => generateOperation(name, op, service.name)).join('\n');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function generateOperation(operationName: string, operation: any, serviceName: string): string {
|
|
65
|
+
const stepsHeader = (operation.steps && operation.steps.length > 0)
|
|
66
|
+
? operation.steps.map((s: any) => ` * - ${typeof s === 'string' ? s : (s.action || JSON.stringify(s))}`).join('\n')
|
|
67
|
+
: ' * (no spec steps declared)';
|
|
68
|
+
return `
|
|
69
|
+
/**
|
|
70
|
+
* ${operationName}
|
|
71
|
+
* ${operation.description || ''}
|
|
72
|
+
*
|
|
73
|
+
* Spec steps:
|
|
74
|
+
${stepsHeader}
|
|
75
|
+
*/
|
|
76
|
+
public async ${operationName}(_args: any = {}): Promise<any> {
|
|
77
|
+
// TODO: translate spec steps into pg-native SQL calls. Controllers
|
|
78
|
+
// already inline conventions today; service-side parity is a
|
|
79
|
+
// follow-up. For now this stub keeps realize completing and the
|
|
80
|
+
// service surface callable.
|
|
81
|
+
throw new Error('${serviceName}.${operationName} is not implemented');
|
|
82
|
+
}
|
|
83
|
+
`;
|
|
84
|
+
}
|