@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,165 @@
|
|
|
1
|
+
function generatePgClient(_context) {
|
|
2
|
+
return `/**
|
|
3
|
+
* Postgres native (pg) \u2014 singleton pool + helpers.
|
|
4
|
+
*
|
|
5
|
+
* Picks up POSTGRES_URL or DATABASE_URL from the environment. The pool is
|
|
6
|
+
* lazily initialised on first use and reused across requests; \`disconnect\`
|
|
7
|
+
* is exposed for graceful-shutdown wiring. \`withTx\` runs a callback in a
|
|
8
|
+
* single connection inside BEGIN/COMMIT (rolled back on throw).
|
|
9
|
+
*/
|
|
10
|
+
import { Pool, type PoolClient, type QueryResult, type QueryResultRow } from 'pg';
|
|
11
|
+
|
|
12
|
+
const connectionString =
|
|
13
|
+
process.env.POSTGRES_URL ||
|
|
14
|
+
process.env.DATABASE_URL ||
|
|
15
|
+
'postgres://postgres:postgres@localhost:5432/specverse';
|
|
16
|
+
|
|
17
|
+
let pool: Pool | null = null;
|
|
18
|
+
|
|
19
|
+
export function getPool(): Pool {
|
|
20
|
+
if (pool) return pool;
|
|
21
|
+
pool = new Pool({ connectionString });
|
|
22
|
+
return pool;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Run a parameterised query against the pool.
|
|
26
|
+
* T defaults to QueryResultRow so callers can pass a row interface. */
|
|
27
|
+
export async function query<T extends QueryResultRow = QueryResultRow>(
|
|
28
|
+
text: string,
|
|
29
|
+
params: ReadonlyArray<unknown> = [],
|
|
30
|
+
): Promise<QueryResult<T>> {
|
|
31
|
+
return getPool().query<T>(text, params as unknown[]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Run a callback inside a transaction. The callback receives a dedicated
|
|
35
|
+
* client; commit on resolve, rollback on throw. */
|
|
36
|
+
export async function withTx<T>(
|
|
37
|
+
fn: (client: PoolClient) => Promise<T>,
|
|
38
|
+
): Promise<T> {
|
|
39
|
+
const client = await getPool().connect();
|
|
40
|
+
try {
|
|
41
|
+
await client.query('BEGIN');
|
|
42
|
+
const result = await fn(client);
|
|
43
|
+
await client.query('COMMIT');
|
|
44
|
+
return result;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
await client.query('ROLLBACK');
|
|
47
|
+
throw err;
|
|
48
|
+
} finally {
|
|
49
|
+
client.release();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Build a comma-separated list of \`"col"\` from an object's keys, plus
|
|
54
|
+
* matching positional placeholders \`$1, $2, ...\`. Quoted to preserve
|
|
55
|
+
* case-sensitive identifiers (camelCase columns work without folding). */
|
|
56
|
+
function buildPositionals(keys: string[], offset = 0): string {
|
|
57
|
+
return keys.map((_k, i) => '$' + (i + 1 + offset)).join(', ');
|
|
58
|
+
}
|
|
59
|
+
function quoteCols(keys: string[]): string {
|
|
60
|
+
return keys.map((k) => '"' + k.replace(/"/g, '""') + '"').join(', ');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** INSERT a record into \`table\` and return the inserted row (with any
|
|
64
|
+
* database-supplied defaults like generated id / createdAt populated). */
|
|
65
|
+
export async function insertOne<T extends QueryResultRow = QueryResultRow>(
|
|
66
|
+
table: string,
|
|
67
|
+
record: Record<string, unknown>,
|
|
68
|
+
): Promise<T> {
|
|
69
|
+
const keys = Object.keys(record);
|
|
70
|
+
const values = keys.map((k) => record[k]);
|
|
71
|
+
const sql = keys.length === 0
|
|
72
|
+
? \`INSERT INTO "\${table}" DEFAULT VALUES RETURNING *\`
|
|
73
|
+
: \`INSERT INTO "\${table}" (\${quoteCols(keys)}) VALUES (\${buildPositionals(keys)}) RETURNING *\`;
|
|
74
|
+
const result = await query<T>(sql, values);
|
|
75
|
+
return result.rows[0] as T;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Bulk-insert many records into \`table\` in one round trip. Returns the
|
|
79
|
+
* inserted rows. All records must share the same shape. */
|
|
80
|
+
export async function insertMany<T extends QueryResultRow = QueryResultRow>(
|
|
81
|
+
table: string,
|
|
82
|
+
records: ReadonlyArray<Record<string, unknown>>,
|
|
83
|
+
): Promise<T[]> {
|
|
84
|
+
if (records.length === 0) return [];
|
|
85
|
+
const firstKeys = Object.keys(records[0]!);
|
|
86
|
+
const valuesClauses: string[] = [];
|
|
87
|
+
const flatValues: unknown[] = [];
|
|
88
|
+
for (let i = 0; i < records.length; i++) {
|
|
89
|
+
const row = records[i] as Record<string, unknown>;
|
|
90
|
+
const placeholders = firstKeys.map((_k, j) => '$' + (i * firstKeys.length + j + 1)).join(', ');
|
|
91
|
+
valuesClauses.push('(' + placeholders + ')');
|
|
92
|
+
for (const k of firstKeys) flatValues.push(row[k]);
|
|
93
|
+
}
|
|
94
|
+
const sql = \`INSERT INTO "\${table}" (\${quoteCols(firstKeys)}) VALUES \${valuesClauses.join(', ')} RETURNING *\`;
|
|
95
|
+
const result = await query<T>(sql, flatValues);
|
|
96
|
+
return result.rows;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** SELECT a single row by a field equality. Returns null if not found. */
|
|
100
|
+
export async function findOneByField<T extends QueryResultRow = QueryResultRow>(
|
|
101
|
+
table: string,
|
|
102
|
+
field: string,
|
|
103
|
+
value: unknown,
|
|
104
|
+
): Promise<T | null> {
|
|
105
|
+
const sql = \`SELECT * FROM "\${table}" WHERE "\${field.replace(/"/g, '""')}" = $1 LIMIT 1\`;
|
|
106
|
+
const result = await query<T>(sql, [value]);
|
|
107
|
+
return result.rows[0] ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** SELECT a single row matching all (field, value) pairs (AND-ed). */
|
|
111
|
+
export async function findOneByFields<T extends QueryResultRow = QueryResultRow>(
|
|
112
|
+
table: string,
|
|
113
|
+
fields: Record<string, unknown>,
|
|
114
|
+
): Promise<T | null> {
|
|
115
|
+
const keys = Object.keys(fields);
|
|
116
|
+
if (keys.length === 0) {
|
|
117
|
+
const result = await query<T>(\`SELECT * FROM "\${table}" LIMIT 1\`);
|
|
118
|
+
return result.rows[0] ?? null;
|
|
119
|
+
}
|
|
120
|
+
const where = keys.map((k, i) => '"' + k.replace(/"/g, '""') + '" = $' + (i + 1)).join(' AND ');
|
|
121
|
+
const sql = \`SELECT * FROM "\${table}" WHERE \${where} LIMIT 1\`;
|
|
122
|
+
const result = await query<T>(sql, keys.map((k) => fields[k]));
|
|
123
|
+
return result.rows[0] ?? null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** SELECT all rows from a table \u2014 equivalent to a Mongo
|
|
127
|
+
* \`collection.find({}).toArray()\` for the bulk-fan-out auto-create
|
|
128
|
+
* convention. */
|
|
129
|
+
export async function findAll<T extends QueryResultRow = QueryResultRow>(
|
|
130
|
+
table: string,
|
|
131
|
+
): Promise<T[]> {
|
|
132
|
+
const result = await query<T>(\`SELECT * FROM "\${table}"\`);
|
|
133
|
+
return result.rows;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** UPDATE columns of the row identified by id. Quotes column names so
|
|
137
|
+
* camelCase identifiers survive postgres' default lower-case folding. */
|
|
138
|
+
export async function updateOneById(
|
|
139
|
+
table: string,
|
|
140
|
+
id: unknown,
|
|
141
|
+
patch: Record<string, unknown>,
|
|
142
|
+
): Promise<void> {
|
|
143
|
+
const keys = Object.keys(patch);
|
|
144
|
+
if (keys.length === 0) return;
|
|
145
|
+
const setClause = keys.map((k, i) => '"' + k.replace(/"/g, '""') + '" = $' + (i + 1)).join(', ');
|
|
146
|
+
const sql = \`UPDATE "\${table}" SET \${setClause} WHERE "id" = $\${keys.length + 1}\`;
|
|
147
|
+
await query(sql, [...keys.map((k) => patch[k]), id]);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** DELETE the row identified by id. */
|
|
151
|
+
export async function deleteOneById(table: string, id: unknown): Promise<void> {
|
|
152
|
+
await query(\`DELETE FROM "\${table}" WHERE "id" = $1\`, [id]);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function disconnect(): Promise<void> {
|
|
156
|
+
if (pool) {
|
|
157
|
+
await pool.end();
|
|
158
|
+
pool = null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
`;
|
|
162
|
+
}
|
|
163
|
+
export {
|
|
164
|
+
generatePgClient as default
|
|
165
|
+
};
|
package/dist/libs/instance-factories/services/templates/postgres-native/controller-generator.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { buildTransitionMap, isAutoField } from "@specverse/types/spec-rules";
|
|
2
|
+
function generatePgNativeController(context) {
|
|
3
|
+
const { controller, model, models } = context;
|
|
4
|
+
if (!controller) throw new Error("Controller is required in template context");
|
|
5
|
+
if (!model) throw new Error("Model is required for controller generation");
|
|
6
|
+
const controllerName = controller.name;
|
|
7
|
+
const modelName = model.name;
|
|
8
|
+
const modelVar = lowerFirst(modelName);
|
|
9
|
+
const table = tableName(model);
|
|
10
|
+
const curedOps = controller.cured || {};
|
|
11
|
+
const modelRegistry = {};
|
|
12
|
+
if (Array.isArray(models)) {
|
|
13
|
+
for (const m of models) if (m?.name) modelRegistry[m.name] = m;
|
|
14
|
+
} else if (models && typeof models === "object") {
|
|
15
|
+
Object.assign(modelRegistry, models);
|
|
16
|
+
}
|
|
17
|
+
const customActions = generateCustomActions(controller, modelRegistry);
|
|
18
|
+
const validate = generateValidateMethod(model, modelName);
|
|
19
|
+
const create = curedOps.create ? generateCreateMethod(modelName, modelVar) : "";
|
|
20
|
+
const retrieve = curedOps.retrieve ? generateRetrieveMethod(modelName, modelVar) : "";
|
|
21
|
+
const update = curedOps.update ? generateUpdateMethod(modelName, modelVar) : "";
|
|
22
|
+
const evolve = curedOps.evolve ? generateEvolveMethod(model, modelName, modelVar) : "";
|
|
23
|
+
const del = curedOps.delete ? generateDeleteMethod(modelName, modelVar) : "";
|
|
24
|
+
const hasEventPublishing = curedOps.create || curedOps.update || curedOps.evolve || curedOps.delete;
|
|
25
|
+
const helperImports = [
|
|
26
|
+
"insertOne",
|
|
27
|
+
"findOneByField",
|
|
28
|
+
"findAll",
|
|
29
|
+
"updateOneById",
|
|
30
|
+
"deleteOneById",
|
|
31
|
+
"query",
|
|
32
|
+
customActions.code.includes("findOneByFields(") ? "findOneByFields" : "",
|
|
33
|
+
customActions.code.includes("insertMany(") ? "insertMany" : ""
|
|
34
|
+
].filter(Boolean).join(", ");
|
|
35
|
+
return `/**
|
|
36
|
+
* ${controllerName}
|
|
37
|
+
* Model-specific business logic for ${modelName} (PostgreSQL native driver)
|
|
38
|
+
* ${controller.description || ""}
|
|
39
|
+
*/
|
|
40
|
+
import { ${helperImports} } from '../db/pgClient.js';
|
|
41
|
+
${hasEventPublishing || customActions.needsAiBehaviors ? `import { eventBus } from '../events/eventBus.js';` : ""}
|
|
42
|
+
${customActions.needsAiBehaviors ? `import * as aiBehaviors from '../behaviors/${controllerName}.ai.js';` : ""}
|
|
43
|
+
|
|
44
|
+
const TABLE_NAME = '${table}';
|
|
45
|
+
|
|
46
|
+
export class ${controllerName} {
|
|
47
|
+
${validate}
|
|
48
|
+
${create}
|
|
49
|
+
${retrieve}
|
|
50
|
+
${update}
|
|
51
|
+
${evolve}
|
|
52
|
+
${del}
|
|
53
|
+
${customActions.code}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const ${modelVar}Controller = new ${controllerName}();
|
|
57
|
+
export default ${modelVar}Controller;
|
|
58
|
+
`;
|
|
59
|
+
}
|
|
60
|
+
function lowerFirst(s) {
|
|
61
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
62
|
+
}
|
|
63
|
+
function tableName(model) {
|
|
64
|
+
if (model?.storage?.table) return String(model.storage.table);
|
|
65
|
+
return model.name.toLowerCase() + "s";
|
|
66
|
+
}
|
|
67
|
+
function generateValidateMethod(model, modelName) {
|
|
68
|
+
return `
|
|
69
|
+
/**
|
|
70
|
+
* Validate ${modelName} data \u2014 runs before create / update / evolve.
|
|
71
|
+
*/
|
|
72
|
+
public validate(
|
|
73
|
+
_data: any,
|
|
74
|
+
_context: { operation: 'create' | 'update' | 'evolve' }
|
|
75
|
+
): { valid: boolean; errors: string[] } {
|
|
76
|
+
const errors: string[] = [];
|
|
77
|
+
${generateValidationLogic(model)}
|
|
78
|
+
return { valid: errors.length === 0, errors };
|
|
79
|
+
}
|
|
80
|
+
`;
|
|
81
|
+
}
|
|
82
|
+
function generateValidationLogic(model) {
|
|
83
|
+
if (!model.attributes) return " // No validation rules defined";
|
|
84
|
+
const attrList = Array.isArray(model.attributes) ? model.attributes.map((a) => [a.name, a]) : Object.entries(model.attributes);
|
|
85
|
+
const out = [];
|
|
86
|
+
attrList.forEach(([name, attr]) => {
|
|
87
|
+
if (attr.required && !isAutoField(name, attr)) {
|
|
88
|
+
out.push(` if (_context.operation === 'create' && !_data.${name}) errors.push('${name} is required');`);
|
|
89
|
+
}
|
|
90
|
+
if (attr.type === "String" || attr.type === "string") {
|
|
91
|
+
if (attr.min) out.push(` if (_data.${name} && _data.${name}.length < ${attr.min}) errors.push('${name} must be at least ${attr.min} characters');`);
|
|
92
|
+
if (attr.max) out.push(` if (_data.${name} && _data.${name}.length > ${attr.max}) errors.push('${name} must be at most ${attr.max} characters');`);
|
|
93
|
+
}
|
|
94
|
+
if (attr.values && Array.isArray(attr.values)) {
|
|
95
|
+
const values = attr.values.map((v) => `'${v}'`).join(", ");
|
|
96
|
+
out.push(` if (_data.${name} && ![${values}].includes(_data.${name})) errors.push('${name} must be one of: ${attr.values.join(", ")}');`);
|
|
97
|
+
}
|
|
98
|
+
if (attr.format === "email") {
|
|
99
|
+
out.push(` if (_data.${name} && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(_data.${name})) errors.push('${name} must be a valid email address');`);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
return out.join("\n") || " // No validation rules defined";
|
|
103
|
+
}
|
|
104
|
+
function generateCreateMethod(modelName, modelVar) {
|
|
105
|
+
return `
|
|
106
|
+
/**
|
|
107
|
+
* Create a new ${modelName}.
|
|
108
|
+
*/
|
|
109
|
+
public async create(data: any): Promise<any> {
|
|
110
|
+
const validation = this.validate(data, { operation: 'create' });
|
|
111
|
+
if (!validation.valid) throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
|
|
112
|
+
|
|
113
|
+
const ${modelVar} = await insertOne(TABLE_NAME, { ...data });
|
|
114
|
+
|
|
115
|
+
await eventBus.publish('${modelName}Created', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
116
|
+
return ${modelVar};
|
|
117
|
+
}
|
|
118
|
+
`;
|
|
119
|
+
}
|
|
120
|
+
function generateRetrieveMethod(modelName, _modelVar) {
|
|
121
|
+
return `
|
|
122
|
+
/**
|
|
123
|
+
* Retrieve ${modelName} by id. Returns null when not found.
|
|
124
|
+
*/
|
|
125
|
+
public async retrieve(id: string): Promise<any | null> {
|
|
126
|
+
return await findOneByField(TABLE_NAME, 'id', id);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Retrieve a page of ${modelName}s.
|
|
131
|
+
*/
|
|
132
|
+
public async retrieveAll(options: { skip?: number; take?: number } = {}): Promise<any[]> {
|
|
133
|
+
if (!options.skip && !options.take) {
|
|
134
|
+
return await findAll(TABLE_NAME);
|
|
135
|
+
}
|
|
136
|
+
const limit = options.take ?? 100;
|
|
137
|
+
const offset = options.skip ?? 0;
|
|
138
|
+
const result = await query(\`SELECT * FROM "\${TABLE_NAME}" LIMIT $1 OFFSET $2\`, [limit, offset]);
|
|
139
|
+
return result.rows;
|
|
140
|
+
}
|
|
141
|
+
`;
|
|
142
|
+
}
|
|
143
|
+
function generateUpdateMethod(modelName, modelVar) {
|
|
144
|
+
return `
|
|
145
|
+
/**
|
|
146
|
+
* Update ${modelName}.
|
|
147
|
+
*/
|
|
148
|
+
public async update(id: string, data: any): Promise<any> {
|
|
149
|
+
const validation = this.validate(data, { operation: 'update' });
|
|
150
|
+
if (!validation.valid) throw new Error(\`Validation failed: \${validation.errors.join(', ')}\`);
|
|
151
|
+
|
|
152
|
+
// Strip nested objects + id \u2014 only scalar fields are written.
|
|
153
|
+
const updateData: Record<string, unknown> = {};
|
|
154
|
+
for (const [key, value] of Object.entries(data)) {
|
|
155
|
+
if (key === 'id') continue;
|
|
156
|
+
if (Array.isArray(value)) continue;
|
|
157
|
+
if (value !== null && typeof value === 'object' && !(value instanceof Date)) continue;
|
|
158
|
+
updateData[key] = value;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
await updateOneById(TABLE_NAME, id, updateData);
|
|
162
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
163
|
+
if (!${modelVar}) throw new Error('${modelName} not found after update');
|
|
164
|
+
|
|
165
|
+
await eventBus.publish('${modelName}Updated', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
166
|
+
return ${modelVar};
|
|
167
|
+
}
|
|
168
|
+
`;
|
|
169
|
+
}
|
|
170
|
+
function generateEvolveMethod(model, modelName, modelVar) {
|
|
171
|
+
const lifecycles = Array.isArray(model.lifecycles) ? model.lifecycles : model.lifecycles ? Object.entries(model.lifecycles).map(([name, lc]) => ({ name, ...lc })) : [];
|
|
172
|
+
const lifecycle = lifecycles[0];
|
|
173
|
+
const lifecycleName = lifecycle?.name || "status";
|
|
174
|
+
const validTransitions = lifecycle ? buildTransitionMap(lifecycle) : {};
|
|
175
|
+
const states = lifecycle?.states && lifecycle.states.length > 0 ? lifecycle.states.map((s) => typeof s === "string" ? s : s.name) : Array.from(/* @__PURE__ */ new Set([
|
|
176
|
+
...Object.keys(validTransitions),
|
|
177
|
+
...Object.values(validTransitions).flat()
|
|
178
|
+
]));
|
|
179
|
+
return `
|
|
180
|
+
/**
|
|
181
|
+
* Evolve ${modelName} through lifecycle "${lifecycleName}"
|
|
182
|
+
* States: ${states.join(" \u2192 ") || "(none declared)"}
|
|
183
|
+
*/
|
|
184
|
+
public async evolve(id: string, data: any): Promise<any> {
|
|
185
|
+
const current = await findOneByField(TABLE_NAME, 'id', id);
|
|
186
|
+
if (!current) throw new Error('${modelName} not found');
|
|
187
|
+
|
|
188
|
+
const targetLifecycle = data?.lifecycleName || '${lifecycleName}';
|
|
189
|
+
const targetState = data?.toState ?? data?.state ?? data?.[targetLifecycle];
|
|
190
|
+
if (!targetState) throw new Error('evolve requires toState (or ${lifecycleName}) in the request body');
|
|
191
|
+
|
|
192
|
+
${states.length > 0 ? `
|
|
193
|
+
const currentState = (current as any)[targetLifecycle];
|
|
194
|
+
const validTransitions: Record<string, string[]> = ${JSON.stringify(validTransitions)};
|
|
195
|
+
const allowed = validTransitions[currentState] || [];
|
|
196
|
+
if (!allowed.includes(targetState)) {
|
|
197
|
+
throw new Error(\`Invalid transition: \${currentState} \u2192 \${targetState}. Allowed: \${allowed.join(', ') || 'none'}\`);
|
|
198
|
+
}
|
|
199
|
+
` : ""}
|
|
200
|
+
|
|
201
|
+
await updateOneById(TABLE_NAME, id, { [targetLifecycle]: targetState });
|
|
202
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
203
|
+
if (!${modelVar}) throw new Error('${modelName} not found after evolve');
|
|
204
|
+
|
|
205
|
+
await eventBus.publish('${modelName}Evolved', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
206
|
+
return ${modelVar};
|
|
207
|
+
}
|
|
208
|
+
`;
|
|
209
|
+
}
|
|
210
|
+
function generateDeleteMethod(modelName, modelVar) {
|
|
211
|
+
return `
|
|
212
|
+
/**
|
|
213
|
+
* Delete ${modelName}.
|
|
214
|
+
*/
|
|
215
|
+
public async delete(id: string): Promise<void> {
|
|
216
|
+
const ${modelVar} = await findOneByField(TABLE_NAME, 'id', id);
|
|
217
|
+
await deleteOneById(TABLE_NAME, id);
|
|
218
|
+
if (${modelVar}) {
|
|
219
|
+
await eventBus.publish('${modelName}Deleted', { ...${modelVar}, timestamp: new Date().toISOString() } as any);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
`;
|
|
223
|
+
}
|
|
224
|
+
import { matchPgStep } from "./step-conventions.js";
|
|
225
|
+
function generateCustomActions(controller, modelRegistry = {}) {
|
|
226
|
+
if (!controller.actions || Object.keys(controller.actions).length === 0) {
|
|
227
|
+
return { code: "", needsAiBehaviors: false };
|
|
228
|
+
}
|
|
229
|
+
const CRUD_NAMES = /* @__PURE__ */ new Set(["create", "retrieve", "retrieveAll", "update", "evolve", "delete", "validate"]);
|
|
230
|
+
const modelName = controller.model || (controller.name || "").replace(/Controller$/, "") || "Model";
|
|
231
|
+
const tableNameLocal = modelName.toLowerCase() + "s";
|
|
232
|
+
const out = [];
|
|
233
|
+
let needsAiBehaviors = false;
|
|
234
|
+
for (const [actionName, action] of Object.entries(controller.actions)) {
|
|
235
|
+
if (CRUD_NAMES.has(actionName)) {
|
|
236
|
+
console.warn(
|
|
237
|
+
`\u26A0\uFE0F ${controller.name || "Controller"}.${actionName} \u2014 behaviour-derived action collides with the auto-generated CURVED \`${actionName}\` op. Dropped to avoid TS2393 duplicate-implementation. Rename the behaviour (e.g. \`${actionName}Soft\` / \`hardDelete\`) if you need the custom logic.`
|
|
238
|
+
);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const steps = Array.isArray(action.steps) ? action.steps : [];
|
|
242
|
+
const stepsHeader = steps.length > 0 ? steps.map((s) => ` * - ${typeof s === "string" ? s : s.action || JSON.stringify(s)}`).join("\n") : " * (no spec steps declared)";
|
|
243
|
+
const declaredVars = /* @__PURE__ */ new Set();
|
|
244
|
+
const stepBodies = [];
|
|
245
|
+
let usesArgs = false;
|
|
246
|
+
let actionRefersToAi = false;
|
|
247
|
+
steps.forEach((rawStep, i) => {
|
|
248
|
+
const stepText = typeof rawStep === "string" ? rawStep : rawStep?.step || rawStep?.action;
|
|
249
|
+
if (typeof stepText !== "string") {
|
|
250
|
+
stepBodies.push(` // Step ${i + 1}: (non-string step ignored)`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const ctx = {
|
|
254
|
+
modelName,
|
|
255
|
+
tableName: tableNameLocal,
|
|
256
|
+
serviceName: controller.name || "Controller",
|
|
257
|
+
operationName: actionName,
|
|
258
|
+
stepNum: i + 1,
|
|
259
|
+
parameterNames: Object.keys(action.parameters || {}),
|
|
260
|
+
declaredVars,
|
|
261
|
+
models: modelRegistry
|
|
262
|
+
};
|
|
263
|
+
const result = matchPgStep(stepText, ctx);
|
|
264
|
+
stepBodies.push(result.call);
|
|
265
|
+
if (/\bargs\./.test(result.call)) usesArgs = true;
|
|
266
|
+
if (!result.matched) actionRefersToAi = true;
|
|
267
|
+
});
|
|
268
|
+
if (actionRefersToAi) needsAiBehaviors = true;
|
|
269
|
+
const argsParam = usesArgs ? "args: any = {}" : "_args: any = {}";
|
|
270
|
+
let combined = stepBodies.join("\n\n");
|
|
271
|
+
const stepResultRe = /const\s+(step\d+Result)\s*=/g;
|
|
272
|
+
let mres;
|
|
273
|
+
const declared = [];
|
|
274
|
+
while ((mres = stepResultRe.exec(combined)) !== null) declared.push(mres[1]);
|
|
275
|
+
for (const name of declared) {
|
|
276
|
+
const refCount = (combined.match(new RegExp(`\\b${name}\\b`, "g")) || []).length;
|
|
277
|
+
if (refCount <= 1) {
|
|
278
|
+
combined = combined.replace(new RegExp(`const\\s+${name}\\s*=\\s*`), "");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const body = steps.length > 0 ? combined + `
|
|
282
|
+
return { success: true };` : ` throw new Error('${controller.name || "Controller"}.${actionName} is not implemented');`;
|
|
283
|
+
out.push(`
|
|
284
|
+
/**
|
|
285
|
+
* ${actionName}
|
|
286
|
+
* ${action.description || ""}
|
|
287
|
+
*
|
|
288
|
+
* Spec steps:
|
|
289
|
+
${stepsHeader}
|
|
290
|
+
*/
|
|
291
|
+
public async ${actionName}(${argsParam}): Promise<any> {
|
|
292
|
+
${body}
|
|
293
|
+
}
|
|
294
|
+
`);
|
|
295
|
+
}
|
|
296
|
+
return { code: out.join("\n"), needsAiBehaviors };
|
|
297
|
+
}
|
|
298
|
+
export {
|
|
299
|
+
generatePgNativeController as default
|
|
300
|
+
};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
function generatePgSchemaSql(context) {
|
|
2
|
+
const { spec, models } = context;
|
|
3
|
+
const allModels = [];
|
|
4
|
+
if (Array.isArray(models) && models.length > 0) {
|
|
5
|
+
for (const m of models) if (m?.name) allModels.push([m.name, m]);
|
|
6
|
+
} else if (spec?.components) {
|
|
7
|
+
const components = Array.isArray(spec.components) ? spec.components : Object.values(spec.components);
|
|
8
|
+
for (const comp of components) {
|
|
9
|
+
const ms = comp?.models;
|
|
10
|
+
if (!ms) continue;
|
|
11
|
+
const entries = Array.isArray(ms) ? ms.map((m) => [m.name, m]) : Object.entries(ms);
|
|
12
|
+
for (const [name, m] of entries) {
|
|
13
|
+
if (name) allModels.push([name, m]);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const banner = `-- ============================================================
|
|
18
|
+
-- ${spec?.metadata?.component || "Application"} \u2014 schema.sql
|
|
19
|
+
-- Generated by @specverse/engines (postgres-native).
|
|
20
|
+
-- Run via: psql "$POSTGRES_URL" -f src/db/schema.sql
|
|
21
|
+
-- Re-runnable: every statement is IF NOT EXISTS / idempotent.
|
|
22
|
+
-- ============================================================
|
|
23
|
+
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- for gen_random_uuid()
|
|
24
|
+
`;
|
|
25
|
+
if (allModels.length === 0) {
|
|
26
|
+
return banner + "\n-- No models declared. (Add one to your spec to populate this file.)\n";
|
|
27
|
+
}
|
|
28
|
+
const tableBlocks = allModels.map(([name, model]) => generateTable(name, model));
|
|
29
|
+
return banner + "\n" + tableBlocks.join("\n\n") + "\n";
|
|
30
|
+
}
|
|
31
|
+
function generateTable(modelName, model) {
|
|
32
|
+
const table = model?.storage?.table || modelName.toLowerCase() + "s";
|
|
33
|
+
const attrs = model.attributes;
|
|
34
|
+
if (!attrs) {
|
|
35
|
+
return `-- ${modelName}
|
|
36
|
+
CREATE TABLE IF NOT EXISTS "${table}" (
|
|
37
|
+
id TEXT PRIMARY KEY
|
|
38
|
+
);`;
|
|
39
|
+
}
|
|
40
|
+
const list = Array.isArray(attrs) ? attrs.map((a) => [a.name, a]) : Object.entries(attrs);
|
|
41
|
+
const columns = [];
|
|
42
|
+
const indexes = [];
|
|
43
|
+
let hasIdColumn = false;
|
|
44
|
+
for (const [colName, attr] of list) {
|
|
45
|
+
if (!colName) continue;
|
|
46
|
+
const { sql, isPk, isUnique } = columnDef(colName, attr, modelName);
|
|
47
|
+
if (isPk) hasIdColumn = true;
|
|
48
|
+
columns.push(" " + sql);
|
|
49
|
+
if (isUnique && !isPk) {
|
|
50
|
+
indexes.push(
|
|
51
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS "${table}_${colName}_uq" ON "${table}" ("${colName}");`
|
|
52
|
+
);
|
|
53
|
+
} else if (colName.endsWith("Id") && colName !== "id") {
|
|
54
|
+
indexes.push(
|
|
55
|
+
`CREATE INDEX IF NOT EXISTS "${table}_${colName}_idx" ON "${table}" ("${colName}");`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!hasIdColumn) {
|
|
60
|
+
columns.unshift(' "id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text');
|
|
61
|
+
}
|
|
62
|
+
const declaredNames = new Set(list.map(([n]) => n));
|
|
63
|
+
if (!declaredNames.has("createdAt")) {
|
|
64
|
+
columns.push(' "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
65
|
+
}
|
|
66
|
+
if (!declaredNames.has("updatedAt")) {
|
|
67
|
+
columns.push(' "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
|
|
68
|
+
}
|
|
69
|
+
const lifecycles = Array.isArray(model.lifecycles) ? model.lifecycles : model.lifecycles ? Object.entries(model.lifecycles).map(([name, lc]) => ({ name, ...lc })) : [];
|
|
70
|
+
for (const lc of lifecycles) {
|
|
71
|
+
const lcName = lc?.name;
|
|
72
|
+
if (!lcName || declaredNames.has(lcName)) continue;
|
|
73
|
+
const initial = deriveInitialState(lc);
|
|
74
|
+
const defaultClause = initial ? ` DEFAULT '${initial.replace(/'/g, "''")}'` : "";
|
|
75
|
+
columns.push(` "${lcName}" TEXT NOT NULL${defaultClause}`);
|
|
76
|
+
}
|
|
77
|
+
const indexBlock = indexes.length > 0 ? "\n\n" + indexes.join("\n") : "";
|
|
78
|
+
return `-- ${modelName}
|
|
79
|
+
CREATE TABLE IF NOT EXISTS "${table}" (
|
|
80
|
+
${columns.join(",\n")}
|
|
81
|
+
);${indexBlock}`;
|
|
82
|
+
}
|
|
83
|
+
function columnDef(name, attr, _modelName) {
|
|
84
|
+
const required = !!attr.required;
|
|
85
|
+
const unique = !!attr.unique;
|
|
86
|
+
const type = (attr.type || "String").toLowerCase();
|
|
87
|
+
const isIdColumn = name === "id";
|
|
88
|
+
if (isIdColumn) {
|
|
89
|
+
if (type === "uuid") {
|
|
90
|
+
return { sql: `"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()`, isPk: true, isUnique: true };
|
|
91
|
+
}
|
|
92
|
+
return { sql: `"id" TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text`, isPk: true, isUnique: true };
|
|
93
|
+
}
|
|
94
|
+
let sqlType;
|
|
95
|
+
switch (type) {
|
|
96
|
+
case "integer":
|
|
97
|
+
case "int":
|
|
98
|
+
sqlType = "INTEGER";
|
|
99
|
+
break;
|
|
100
|
+
case "bigint":
|
|
101
|
+
sqlType = "BIGINT";
|
|
102
|
+
break;
|
|
103
|
+
case "float":
|
|
104
|
+
case "number":
|
|
105
|
+
case "double":
|
|
106
|
+
sqlType = "DOUBLE PRECISION";
|
|
107
|
+
break;
|
|
108
|
+
case "boolean":
|
|
109
|
+
case "bool":
|
|
110
|
+
sqlType = "BOOLEAN";
|
|
111
|
+
break;
|
|
112
|
+
case "datetime":
|
|
113
|
+
case "date":
|
|
114
|
+
case "timestamp":
|
|
115
|
+
sqlType = "TIMESTAMPTZ";
|
|
116
|
+
break;
|
|
117
|
+
case "uuid":
|
|
118
|
+
sqlType = "UUID";
|
|
119
|
+
break;
|
|
120
|
+
case "json":
|
|
121
|
+
case "jsonb":
|
|
122
|
+
sqlType = "JSONB";
|
|
123
|
+
break;
|
|
124
|
+
default:
|
|
125
|
+
sqlType = "TEXT";
|
|
126
|
+
}
|
|
127
|
+
const nullness = required ? " NOT NULL" : "";
|
|
128
|
+
const uniqueClause = unique ? " UNIQUE" : "";
|
|
129
|
+
const defaultClause = formatColumnDefault(attr.default, type);
|
|
130
|
+
return {
|
|
131
|
+
sql: `"${name}" ${sqlType}${nullness}${uniqueClause}${defaultClause}`,
|
|
132
|
+
isPk: false,
|
|
133
|
+
isUnique: unique
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function deriveInitialState(lc) {
|
|
137
|
+
if (!lc) return null;
|
|
138
|
+
if (typeof lc.initial === "string") return lc.initial;
|
|
139
|
+
if (Array.isArray(lc.states) && lc.states.length > 0) {
|
|
140
|
+
const first = lc.states[0];
|
|
141
|
+
return typeof first === "string" ? first : first?.name ?? null;
|
|
142
|
+
}
|
|
143
|
+
if (typeof lc.flow === "string") {
|
|
144
|
+
const head = lc.flow.split(/\s*->\s*/)[0]?.trim();
|
|
145
|
+
return head || null;
|
|
146
|
+
}
|
|
147
|
+
if (lc.transitions && typeof lc.transitions === "object") {
|
|
148
|
+
const first = Object.values(lc.transitions)[0];
|
|
149
|
+
if (typeof first === "string") return first.split(/\s*->\s*/)[0]?.trim() || null;
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
function formatColumnDefault(value, type) {
|
|
154
|
+
if (value === void 0 || value === null) return "";
|
|
155
|
+
if (typeof value === "boolean") return ` DEFAULT ${value}`;
|
|
156
|
+
if (typeof value === "number") return ` DEFAULT ${value}`;
|
|
157
|
+
if (typeof value === "string") {
|
|
158
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return ` DEFAULT ${value}`;
|
|
159
|
+
if (value === "true" || value === "false") return ` DEFAULT ${value}`;
|
|
160
|
+
if (value === "now" && (type === "datetime" || type === "date" || type === "timestamp")) {
|
|
161
|
+
return ` DEFAULT NOW()`;
|
|
162
|
+
}
|
|
163
|
+
return ` DEFAULT '${value.replace(/'/g, "''")}'`;
|
|
164
|
+
}
|
|
165
|
+
return "";
|
|
166
|
+
}
|
|
167
|
+
export {
|
|
168
|
+
generatePgSchemaSql as default
|
|
169
|
+
};
|