@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,65 @@
|
|
|
1
|
+
function generatePgNativeService(context) {
|
|
2
|
+
const { service } = context;
|
|
3
|
+
if (!service) throw new Error("Service is required in template context");
|
|
4
|
+
const serviceName = service.name;
|
|
5
|
+
const operationsCode = generateOperations(service);
|
|
6
|
+
const usesDb = /\bquery\b|\bgetPool\b/.test(operationsCode);
|
|
7
|
+
const hasEvents = service.publishes && service.publishes.length > 0 || service.subscribes && service.subscribes.length > 0;
|
|
8
|
+
return `/**
|
|
9
|
+
* ${serviceName}
|
|
10
|
+
* Abstract business logic service (PostgreSQL native driver)
|
|
11
|
+
* ${service.description || ""}
|
|
12
|
+
*/
|
|
13
|
+
${usesDb ? `import { query, getPool } from '../db/pgClient.js';` : ""}
|
|
14
|
+
${hasEvents ? `import { eventBus } from '../events/eventBus.js';` : ""}
|
|
15
|
+
|
|
16
|
+
export class ${serviceName} {
|
|
17
|
+
${operationsCode}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ${lowerFirst(serviceName)} = new ${serviceName}();
|
|
21
|
+
export const ${lowerFirst(serviceName)}Instance = ${lowerFirst(serviceName)};
|
|
22
|
+
export default ${lowerFirst(serviceName)};
|
|
23
|
+
`;
|
|
24
|
+
}
|
|
25
|
+
function lowerFirst(s) {
|
|
26
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
27
|
+
}
|
|
28
|
+
function generateOperations(service) {
|
|
29
|
+
const ops = service.operations;
|
|
30
|
+
if (!ops || Array.isArray(ops) && ops.length === 0 || !Array.isArray(ops) && Object.keys(ops).length === 0) {
|
|
31
|
+
return `
|
|
32
|
+
/**
|
|
33
|
+
* Default service entrypoint \u2014 replace with real operations once declared
|
|
34
|
+
* on the service's spec.
|
|
35
|
+
*/
|
|
36
|
+
public async execute(_params: any = {}): Promise<any> {
|
|
37
|
+
throw new Error('${service.name}.execute is not implemented');
|
|
38
|
+
}
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
const entries = Array.isArray(ops) ? ops.map((op) => [op.name, op]) : Object.entries(ops);
|
|
42
|
+
return entries.map(([name, op]) => generateOperation(name, op, service.name)).join("\n");
|
|
43
|
+
}
|
|
44
|
+
function generateOperation(operationName, operation, serviceName) {
|
|
45
|
+
const stepsHeader = operation.steps && operation.steps.length > 0 ? operation.steps.map((s) => ` * - ${typeof s === "string" ? s : s.action || JSON.stringify(s)}`).join("\n") : " * (no spec steps declared)";
|
|
46
|
+
return `
|
|
47
|
+
/**
|
|
48
|
+
* ${operationName}
|
|
49
|
+
* ${operation.description || ""}
|
|
50
|
+
*
|
|
51
|
+
* Spec steps:
|
|
52
|
+
${stepsHeader}
|
|
53
|
+
*/
|
|
54
|
+
public async ${operationName}(_args: any = {}): Promise<any> {
|
|
55
|
+
// TODO: translate spec steps into pg-native SQL calls. Controllers
|
|
56
|
+
// already inline conventions today; service-side parity is a
|
|
57
|
+
// follow-up. For now this stub keeps realize completing and the
|
|
58
|
+
// service surface callable.
|
|
59
|
+
throw new Error('${serviceName}.${operationName} is not implemented');
|
|
60
|
+
}
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
export {
|
|
64
|
+
generatePgNativeService as default
|
|
65
|
+
};
|
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import {
|
|
2
|
+
toVar,
|
|
3
|
+
matchAgainstConventions
|
|
4
|
+
} from "../_shared/step-matching.js";
|
|
5
|
+
function deriveModelDefaults(modelName, ctx) {
|
|
6
|
+
if (!ctx.models) return [];
|
|
7
|
+
const model = ctx.models[modelName] || ctx.models[modelName.charAt(0).toUpperCase() + modelName.slice(1)];
|
|
8
|
+
if (!model) return [];
|
|
9
|
+
const attrs = model.attributes;
|
|
10
|
+
if (!attrs) return [];
|
|
11
|
+
const list = Array.isArray(attrs) ? attrs.map((a) => [a.name, a]) : Object.entries(attrs);
|
|
12
|
+
const declaredVars = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
13
|
+
const out = [];
|
|
14
|
+
const conventionManaged = /* @__PURE__ */ new Set(["createdAt", "updatedAt", "id"]);
|
|
15
|
+
for (const [name, attr] of list) {
|
|
16
|
+
if (!name) continue;
|
|
17
|
+
if (conventionManaged.has(name)) continue;
|
|
18
|
+
const required = !!attr.required;
|
|
19
|
+
const hasDefault = attr.default !== void 0;
|
|
20
|
+
if (!required && !hasDefault) continue;
|
|
21
|
+
if (hasDefault) {
|
|
22
|
+
out.push(`${name}: ${formatDefault(attr.default, attr.type)}`);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const type = (attr.type || "String").toLowerCase();
|
|
26
|
+
if (type === "integer" || type === "int" || type === "number" || type === "float") {
|
|
27
|
+
const min = attr.min ?? 0;
|
|
28
|
+
out.push(`${name}: ${min}`);
|
|
29
|
+
} else if (type === "boolean") {
|
|
30
|
+
out.push(`${name}: false`);
|
|
31
|
+
} else if (type === "datetime" || type === "date") {
|
|
32
|
+
out.push(`${name}: new Date().toISOString()`);
|
|
33
|
+
} else {
|
|
34
|
+
const selfVar = modelName.charAt(0).toLowerCase() + modelName.slice(1);
|
|
35
|
+
const fkMatch = name.match(/^(.+)Id$/);
|
|
36
|
+
if (fkMatch && fkMatch[1] !== selfVar && declaredVars.has(fkMatch[1])) {
|
|
37
|
+
out.push(`${name}: (${fkMatch[1]} as any)?.id`);
|
|
38
|
+
} else {
|
|
39
|
+
out.push(`${name}: ''`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
function formatDefault(value, type) {
|
|
46
|
+
if (value === null || value === void 0) return "null";
|
|
47
|
+
if (typeof value === "boolean") return String(value);
|
|
48
|
+
if (typeof value === "number") return String(value);
|
|
49
|
+
if (typeof value === "string") {
|
|
50
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return value;
|
|
51
|
+
if (value === "true" || value === "false") return value;
|
|
52
|
+
if (value === "now" && (type === "DateTime" || type === "Date")) {
|
|
53
|
+
return "new Date().toISOString()";
|
|
54
|
+
}
|
|
55
|
+
return JSON.stringify(value);
|
|
56
|
+
}
|
|
57
|
+
return JSON.stringify(value);
|
|
58
|
+
}
|
|
59
|
+
function toTable(modelName) {
|
|
60
|
+
return modelName.toLowerCase() + "s";
|
|
61
|
+
}
|
|
62
|
+
function resolveValue(rawValue, ctx) {
|
|
63
|
+
const value = rawValue.trim().replace(/^['"]|['"]$/g, "");
|
|
64
|
+
if (/^(current\s*time|now|timestamp)$/i.test(value)) return "new Date().toISOString()";
|
|
65
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return value;
|
|
66
|
+
if (value === "true" || value === "false") return value;
|
|
67
|
+
if (value === "null") return "null";
|
|
68
|
+
const declared = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
69
|
+
const params = ctx.parameterNames || [];
|
|
70
|
+
const head = value.split(".")[0];
|
|
71
|
+
if (declared.has(head)) return value;
|
|
72
|
+
if (params.includes(head)) return `args.${value}`;
|
|
73
|
+
return `'${value.replace(/'/g, "\\'")}'`;
|
|
74
|
+
}
|
|
75
|
+
function mostRecentStepResult(ctx) {
|
|
76
|
+
const declared = Array.from(ctx.declaredVars || []);
|
|
77
|
+
const stepResults = declared.filter((v) => /^step\d+Result$/.test(v)).sort((a, b) => parseInt(b.slice(4), 10) - parseInt(a.slice(4), 10));
|
|
78
|
+
return stepResults[0] ?? null;
|
|
79
|
+
}
|
|
80
|
+
function pascal(model) {
|
|
81
|
+
return model.charAt(0).toUpperCase() + model.slice(1);
|
|
82
|
+
}
|
|
83
|
+
const PG_STEP_CONVENTIONS = [
|
|
84
|
+
// --- Find / Lookup by single field ---
|
|
85
|
+
{
|
|
86
|
+
name: "find-by-field",
|
|
87
|
+
pattern: /^(?:look\s+up|find|fetch|get)\s+(\w+)\s+by\s+(\w+)(?:\s+or\s+fail.*)?$/i,
|
|
88
|
+
generateCall: (m, ctx) => {
|
|
89
|
+
const model = m[1];
|
|
90
|
+
const field = m[2];
|
|
91
|
+
const modelVar = toVar(model);
|
|
92
|
+
const table = toTable(model);
|
|
93
|
+
const params = ctx.parameterNames || [];
|
|
94
|
+
const declared = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
95
|
+
const idVal = field === "id" ? params.includes(`${modelVar}Id`) ? `args.${modelVar}Id` : "args.id" : `args.${field}`;
|
|
96
|
+
if (declared.has(modelVar)) {
|
|
97
|
+
return ` // Step ${ctx.stepNum}: Find ${model} by ${field} (already loaded)`;
|
|
98
|
+
}
|
|
99
|
+
declared.add(modelVar);
|
|
100
|
+
const failOnMissing = /or\s+fail/i.test(m[0]);
|
|
101
|
+
return ` // Step ${ctx.stepNum}: Find ${model} by ${field}
|
|
102
|
+
let ${modelVar} = await findOneByField('${table}', '${field}', ${idVal}) as any;${failOnMissing ? `
|
|
103
|
+
if (!${modelVar}) throw new Error('${model} not found');` : ""}`;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
// --- Find by composite (two fields) ---
|
|
107
|
+
{
|
|
108
|
+
name: "find-by-composite",
|
|
109
|
+
pattern: /^(?:look\s+up|find|fetch|get)(?:\s+existing)?\s+(\w+)\s+by\s+(\w+)\s+and\s+(\w+)$/i,
|
|
110
|
+
generateCall: (m, ctx) => {
|
|
111
|
+
const model = m[1];
|
|
112
|
+
const f1 = m[2];
|
|
113
|
+
const f2 = m[3];
|
|
114
|
+
const modelVar = toVar(model);
|
|
115
|
+
const table = toTable(model);
|
|
116
|
+
const declared = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
117
|
+
if (declared.has(modelVar)) {
|
|
118
|
+
return ` // Step ${ctx.stepNum}: Find ${model} by ${f1} and ${f2} (already loaded)`;
|
|
119
|
+
}
|
|
120
|
+
declared.add(modelVar);
|
|
121
|
+
const resolveFieldSource = (f) => {
|
|
122
|
+
const stripIdMatch = f.match(/^(.+)Id$/);
|
|
123
|
+
if (stripIdMatch) {
|
|
124
|
+
const candidate = stripIdMatch[1];
|
|
125
|
+
if (candidate !== modelVar && declared.has(candidate)) {
|
|
126
|
+
return `(${candidate} as any)?.id`;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return `args.${f}`;
|
|
130
|
+
};
|
|
131
|
+
const f1Src = resolveFieldSource(f1);
|
|
132
|
+
const f2Src = resolveFieldSource(f2);
|
|
133
|
+
return ` // Step ${ctx.stepNum}: Find ${model} by ${f1} and ${f2}
|
|
134
|
+
let ${modelVar} = await findOneByFields('${table}', { ${f1}: ${f1Src}, ${f2}: ${f2Src} }) as any;`;
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
// --- Create model record ---
|
|
138
|
+
{
|
|
139
|
+
name: "create",
|
|
140
|
+
pattern: /^create\s+(?:new\s+)?(\w+)(?:\s+(?:with\s+)?(.+))?/i,
|
|
141
|
+
generateCall: (m, ctx) => {
|
|
142
|
+
const model = m[1];
|
|
143
|
+
const modelVar = toVar(model);
|
|
144
|
+
const table = toTable(model);
|
|
145
|
+
const params = ctx.parameterNames || [];
|
|
146
|
+
const declared = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
147
|
+
declared.add(modelVar);
|
|
148
|
+
const dataExpr = params.length > 0 ? `{ ${params.join(", ")} }` : "args";
|
|
149
|
+
return ` // Step ${ctx.stepNum}: Create ${model}
|
|
150
|
+
const ${modelVar} = await insertOne('${table}', ${dataExpr}) as any;`;
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
// --- Update specific field on previously-loaded model ---
|
|
154
|
+
{
|
|
155
|
+
name: "update-field",
|
|
156
|
+
pattern: /^update\s+(\w+)\s+(\w+)\s+to\s+(.+)/i,
|
|
157
|
+
generateCall: (m, ctx) => {
|
|
158
|
+
const model = m[1];
|
|
159
|
+
const field = m[2];
|
|
160
|
+
const rawValue = m[3];
|
|
161
|
+
const modelVar = toVar(model);
|
|
162
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
163
|
+
const table = toTable(model);
|
|
164
|
+
const val = resolveValue(rawValue, ctx);
|
|
165
|
+
return ` // Step ${ctx.stepNum}: Update ${model}.${field} to ${rawValue.trim()}
|
|
166
|
+
await updateOneById('${table}', ${modelVar}.id, { ${field}: ${val} });`;
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
// --- Update field timestamp ---
|
|
170
|
+
{
|
|
171
|
+
name: "update-field-timestamp",
|
|
172
|
+
pattern: /^update\s+(\w+)\s+(\w+)\s+timestamp$/i,
|
|
173
|
+
generateCall: (m, ctx) => {
|
|
174
|
+
const model = m[1];
|
|
175
|
+
const field = m[2];
|
|
176
|
+
const modelVar = toVar(model);
|
|
177
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
178
|
+
const table = toTable(model);
|
|
179
|
+
return ` // Step ${ctx.stepNum}: Update ${model}.${field} timestamp
|
|
180
|
+
await updateOneById('${table}', ${modelVar}.id, { ${field}: new Date().toISOString() });`;
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
// --- Generic "Update X" (writes args back) ---
|
|
184
|
+
{
|
|
185
|
+
name: "update",
|
|
186
|
+
pattern: /^update\s+(\w+)(?:\s+(.+))?$/i,
|
|
187
|
+
generateCall: (m, ctx) => {
|
|
188
|
+
const model = m[1];
|
|
189
|
+
const modelVar = toVar(model);
|
|
190
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
191
|
+
const table = toTable(model);
|
|
192
|
+
return ` // Step ${ctx.stepNum}: Update ${model}
|
|
193
|
+
await updateOneById('${table}', ${modelVar}.id, args);`;
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
// --- Delete model record ---
|
|
197
|
+
{
|
|
198
|
+
name: "delete",
|
|
199
|
+
pattern: /^delete\s+(\w+)/i,
|
|
200
|
+
generateCall: (m, ctx) => {
|
|
201
|
+
const model = m[1];
|
|
202
|
+
const modelVar = toVar(model);
|
|
203
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
204
|
+
const table = toTable(model);
|
|
205
|
+
return ` // Step ${ctx.stepNum}: Delete ${model}
|
|
206
|
+
await deleteOneById('${table}', ${modelVar}.id);`;
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
// --- Transition to lifecycle state ---
|
|
210
|
+
{
|
|
211
|
+
name: "transition",
|
|
212
|
+
pattern: /^transition\s+(\w+)\s+to\s+(\w+)/i,
|
|
213
|
+
generateCall: (m, ctx) => {
|
|
214
|
+
const model = m[1];
|
|
215
|
+
const state = m[2];
|
|
216
|
+
const modelVar = toVar(model);
|
|
217
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
218
|
+
const table = toTable(model);
|
|
219
|
+
return ` // Step ${ctx.stepNum}: Transition ${model} to ${state}
|
|
220
|
+
if ((${modelVar} as any).status === '${state}') throw new Error('${model} is already ${state}');
|
|
221
|
+
await updateOneById('${table}', ${modelVar}.id, { status: '${state}' });`;
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
// --- Set field to value (on the controller's primary model) ---
|
|
225
|
+
{
|
|
226
|
+
name: "set",
|
|
227
|
+
pattern: /^set\s+(\w+)\s+to\s+(.+)/i,
|
|
228
|
+
generateCall: (m, ctx) => {
|
|
229
|
+
const field = m[1];
|
|
230
|
+
const rawValue = m[2];
|
|
231
|
+
const modelVar = toVar(ctx.modelName);
|
|
232
|
+
const val = resolveValue(rawValue, ctx);
|
|
233
|
+
return ` // Step ${ctx.stepNum}: Set ${field} to ${rawValue.trim()}
|
|
234
|
+
await updateOneById(TABLE_NAME, (${modelVar} as any).id, { ${field}: ${val} });`;
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
// --- Increment / Decrement ---
|
|
238
|
+
// Postgres has no Mongo $inc; emit a column = column +/- N update. The
|
|
239
|
+
// helper updateOneById doesn't support raw SQL fragments, so emit query
|
|
240
|
+
// directly here.
|
|
241
|
+
{
|
|
242
|
+
name: "increment",
|
|
243
|
+
pattern: /^increment\s+(\w+)\s+by\s+(\w+)/i,
|
|
244
|
+
generateCall: (m, ctx) => {
|
|
245
|
+
const field = m[1];
|
|
246
|
+
const amount = m[2];
|
|
247
|
+
const modelVar = toVar(ctx.modelName);
|
|
248
|
+
return ` // Step ${ctx.stepNum}: Increment ${field} by ${amount}
|
|
249
|
+
await query(\`UPDATE "\${TABLE_NAME}" SET "${field}" = "${field}" + $1 WHERE "id" = $2\`, [${amount}, (${modelVar} as any).id]);`;
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
name: "decrement",
|
|
254
|
+
pattern: /^decrement\s+(\w+)\s+by\s+(\w+)/i,
|
|
255
|
+
generateCall: (m, ctx) => {
|
|
256
|
+
const field = m[1];
|
|
257
|
+
const amount = m[2];
|
|
258
|
+
const modelVar = toVar(ctx.modelName);
|
|
259
|
+
return ` // Step ${ctx.stepNum}: Decrement ${field} by ${amount}
|
|
260
|
+
await query(\`UPDATE "\${TABLE_NAME}" SET "${field}" = "${field}" - $1 WHERE "id" = $2\`, [${amount}, (${modelVar} as any).id]);`;
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
// --- Persist / Save / Store ---
|
|
264
|
+
{
|
|
265
|
+
name: "persist",
|
|
266
|
+
pattern: /^(?:persist|save|store)\s+(\w+(?:\s+\w+)?)(?:\s+(?:for|to|record).*)?$/i,
|
|
267
|
+
generateCall: (m, ctx) => {
|
|
268
|
+
const target = toVar(m[1].replace(/\s+(.)/g, (_, c) => c.toUpperCase()));
|
|
269
|
+
const table = toTable(target);
|
|
270
|
+
const recordSrc = mostRecentStepResult(ctx) ?? "args";
|
|
271
|
+
return ` // Step ${ctx.stepNum}: Persist ${m[1]}
|
|
272
|
+
{
|
|
273
|
+
const _rec: any = ${recordSrc} && typeof ${recordSrc} === 'object' && !Array.isArray(${recordSrc})
|
|
274
|
+
? ${recordSrc} : { value: ${recordSrc} };
|
|
275
|
+
await insertOne('${table}', _rec);
|
|
276
|
+
}`;
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
// --- Conditional create ---
|
|
280
|
+
{
|
|
281
|
+
name: "conditional-create",
|
|
282
|
+
pattern: /^if\s+(\w+)\s+does\s+not\s+exist,?\s+create\s+new\s+(\w+)(?:\s+with\s+.+)?$/i,
|
|
283
|
+
generateCall: (m, ctx) => {
|
|
284
|
+
const modelVar = toVar(m[1]);
|
|
285
|
+
const Model = pascal(m[2]);
|
|
286
|
+
const table = toTable(Model);
|
|
287
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
288
|
+
const defaults = deriveModelDefaults(Model, ctx);
|
|
289
|
+
const defaultsBlock = defaults.length > 0 ? defaults.join(", ") + "," : "";
|
|
290
|
+
return ` // Step ${ctx.stepNum}: If ${modelVar} does not exist, create new ${Model}
|
|
291
|
+
if (!${modelVar}) {
|
|
292
|
+
const _newRecord = { ${defaultsBlock} ...args, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
|
|
293
|
+
${modelVar} = await insertOne('${table}', _newRecord) as any;
|
|
294
|
+
}`;
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
// --- Conditional update ---
|
|
298
|
+
{
|
|
299
|
+
name: "conditional-update",
|
|
300
|
+
pattern: /^if\s+(\w+)\s+exists,?\s+update\s+(\w+)(?:\s+(.+))?$/i,
|
|
301
|
+
generateCall: (m, ctx) => {
|
|
302
|
+
const modelVar = toVar(m[1]);
|
|
303
|
+
const field = m[2];
|
|
304
|
+
const table = toTable(m[1]);
|
|
305
|
+
if (!ctx.declaredVars?.has(modelVar)) return "";
|
|
306
|
+
return ` // Step ${ctx.stepNum}: If ${modelVar} exists, update ${field}
|
|
307
|
+
if (${modelVar}) {
|
|
308
|
+
await updateOneById('${table}', (${modelVar} as any).id, { ${field}: new Date().toISOString() });
|
|
309
|
+
}`;
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
// --- Auto-create / Bulk fan-out ---
|
|
313
|
+
{
|
|
314
|
+
name: "auto-create-loop",
|
|
315
|
+
pattern: /^(?:auto-create|bulk\s+create)\s+(\w+)\s+(?:profile|record|entry|entries)?s?\s+for\s+(?:all\s+)?(?:available\s+)?(\w+)$/i,
|
|
316
|
+
generateCall: (m, ctx) => {
|
|
317
|
+
const Model = pascal(m[1]);
|
|
318
|
+
const targetTable = toTable(Model);
|
|
319
|
+
const sourceTable = m[2].toLowerCase();
|
|
320
|
+
const declared = Array.from(ctx.declaredVars || []);
|
|
321
|
+
const ownerVar = declared.find((v) => !/^step\d+Result$/.test(v) && v !== "args");
|
|
322
|
+
const sourceSingular = sourceTable.replace(/s$/, "");
|
|
323
|
+
const linkField = sourceSingular + "Id";
|
|
324
|
+
const ownerLinkField = ownerVar ? ownerVar + "Id" : "ownerId";
|
|
325
|
+
const modelDefaults = deriveModelDefaults(Model, ctx);
|
|
326
|
+
const defaultsBlock = modelDefaults.length > 0 ? modelDefaults.filter((d) => !d.startsWith(`${ownerLinkField}:`) && !d.startsWith(`${linkField}:`)).join(", ") : "";
|
|
327
|
+
return ` // Step ${ctx.stepNum}: Auto-create ${m[1]} ${m[2]} for all ${m[2]}
|
|
328
|
+
{
|
|
329
|
+
const _allItems = await findAll('${sourceTable}');
|
|
330
|
+
const _ownerId = ${ownerVar ? `(${ownerVar} as any)?.id` : "null"};
|
|
331
|
+
const _records = _allItems.map((_item: any) => ({
|
|
332
|
+
${defaultsBlock ? defaultsBlock + "," : ""}
|
|
333
|
+
${ownerLinkField}: _ownerId,
|
|
334
|
+
${linkField}: (_item as any).${sourceSingular}Id ?? (_item as any).id,
|
|
335
|
+
createdAt: new Date().toISOString(),
|
|
336
|
+
updatedAt: new Date().toISOString(),
|
|
337
|
+
}));
|
|
338
|
+
if (_records.length > 0) {
|
|
339
|
+
await insertMany('${targetTable}', _records);
|
|
340
|
+
}
|
|
341
|
+
}`;
|
|
342
|
+
}
|
|
343
|
+
},
|
|
344
|
+
// --- "Otherwise create new X record" ---
|
|
345
|
+
{
|
|
346
|
+
name: "otherwise-create",
|
|
347
|
+
pattern: /^otherwise\s+create\s+(?:new\s+)?(\w+)\s+record$/i,
|
|
348
|
+
generateCall: (m, ctx) => {
|
|
349
|
+
const Model = pascal(m[1]);
|
|
350
|
+
const modelVar = toVar(Model);
|
|
351
|
+
const table = toTable(Model);
|
|
352
|
+
const wasDeclared = ctx.declaredVars?.has(modelVar);
|
|
353
|
+
const declared = Array.from(ctx.declaredVars || []);
|
|
354
|
+
const defaults = deriveModelDefaults(Model, ctx);
|
|
355
|
+
const supplied = /* @__PURE__ */ new Set();
|
|
356
|
+
for (const entry of defaults) {
|
|
357
|
+
const colonIdx = entry.indexOf(":");
|
|
358
|
+
if (colonIdx > 0) supplied.add(entry.slice(0, colonIdx).trim());
|
|
359
|
+
}
|
|
360
|
+
const fkAssignments = declared.filter((v) => v !== modelVar && !/^step\d+Result$/.test(v) && v !== "args").filter((v) => !supplied.has(v + "Id")).map((v) => {
|
|
361
|
+
supplied.add(v + "Id");
|
|
362
|
+
return `${v}Id: (${v} as any)?.id`;
|
|
363
|
+
}).join(", ");
|
|
364
|
+
const defaultsBlock = defaults.length > 0 ? defaults.join(", ") + "," : "";
|
|
365
|
+
ctx.declaredVars?.add(modelVar);
|
|
366
|
+
return ` // Step ${ctx.stepNum}: Otherwise create new ${Model} record
|
|
367
|
+
else {
|
|
368
|
+
const _newRecord = { ${defaultsBlock} ${fkAssignments ? fkAssignments + "," : ""} ...args, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
|
|
369
|
+
${wasDeclared ? `${modelVar} = await insertOne('${table}', _newRecord) as any;` : `const ${modelVar} = await insertOne('${table}', _newRecord) as any;
|
|
370
|
+
void ${modelVar};`}
|
|
371
|
+
}`;
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
// --- Send/Emit/Publish event ---
|
|
375
|
+
{
|
|
376
|
+
name: "send-event",
|
|
377
|
+
pattern: /^(?:send|emit|publish)\s+(\w+)\s+event/i,
|
|
378
|
+
generateCall: (m, ctx) => {
|
|
379
|
+
const event = m[1];
|
|
380
|
+
const modelVar = toVar(ctx.modelName);
|
|
381
|
+
const hasModelVar = ctx.declaredVars?.has(modelVar);
|
|
382
|
+
const payload = hasModelVar ? `{ ${modelVar}Id: (${modelVar} as any)?.id, operation: '${ctx.operationName}', timestamp: new Date().toISOString() }` : `{ operation: '${ctx.operationName}', timestamp: new Date().toISOString() }`;
|
|
383
|
+
return ` // Step ${ctx.stepNum}: Emit ${event} event
|
|
384
|
+
await eventBus.publish('${event}', ${payload} as any);`;
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
// --- Call service ---
|
|
388
|
+
{
|
|
389
|
+
name: "call-service",
|
|
390
|
+
pattern: /^call\s+(\w+)\.(\w+)/i,
|
|
391
|
+
generateCall: (m, ctx) => {
|
|
392
|
+
const service = m[1];
|
|
393
|
+
const method = m[2];
|
|
394
|
+
const args = (ctx.parameterNames || []).join(", ");
|
|
395
|
+
return ` // Step ${ctx.stepNum}: Call ${service}.${method}
|
|
396
|
+
await (${toVar(service)} as any).${method}({ ${args} });`;
|
|
397
|
+
}
|
|
398
|
+
},
|
|
399
|
+
// --- Return ---
|
|
400
|
+
{
|
|
401
|
+
name: "return-model",
|
|
402
|
+
pattern: /^return\s+(?:the\s+|updated\s+|created\s+)?(\w+)\s*$/i,
|
|
403
|
+
generateCall: (m, ctx) => {
|
|
404
|
+
const valueRaw = m[1].trim();
|
|
405
|
+
const declared = ctx.declaredVars || /* @__PURE__ */ new Set();
|
|
406
|
+
const params = ctx.parameterNames || [];
|
|
407
|
+
const modelVar = toVar(ctx.modelName);
|
|
408
|
+
if (valueRaw.toLowerCase() === ctx.modelName.toLowerCase() || valueRaw === modelVar) {
|
|
409
|
+
return ` // Step ${ctx.stepNum}: Return ${ctx.modelName}
|
|
410
|
+
return ${modelVar};`;
|
|
411
|
+
}
|
|
412
|
+
if (declared.has(valueRaw)) {
|
|
413
|
+
return ` // Step ${ctx.stepNum}: Return ${valueRaw}
|
|
414
|
+
return ${valueRaw};`;
|
|
415
|
+
}
|
|
416
|
+
if (params.includes(valueRaw)) {
|
|
417
|
+
return ` // Step ${ctx.stepNum}: Return ${valueRaw}
|
|
418
|
+
return args.${valueRaw};`;
|
|
419
|
+
}
|
|
420
|
+
return ` // Step ${ctx.stepNum}: Return ${valueRaw} \u2014 TODO: resolve binding
|
|
421
|
+
return null;`;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
];
|
|
425
|
+
function matchPgStep(step, ctx) {
|
|
426
|
+
const aiArgsExpr = (inputs, paramNames) => inputs.length > 0 ? `{ ${inputs.map((n) => paramNames.includes(n) ? `${n}: args.${n}` : n).join(", ")} }` : "{}";
|
|
427
|
+
return matchAgainstConventions(step, ctx, PG_STEP_CONVENTIONS, aiArgsExpr);
|
|
428
|
+
}
|
|
429
|
+
export {
|
|
430
|
+
PG_STEP_CONVENTIONS,
|
|
431
|
+
deriveModelDefaults,
|
|
432
|
+
matchPgStep
|
|
433
|
+
};
|
|
@@ -75,7 +75,7 @@ async function validateTypeScriptTypes(code) {
|
|
|
75
75
|
return null;
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
-
const PROMPT_VERSION = "9.
|
|
78
|
+
const PROMPT_VERSION = "9.7.0";
|
|
79
79
|
function cacheKey(step, modelName, operationName, functionName, inputs) {
|
|
80
80
|
const payload = JSON.stringify({ step, modelName, operationName, functionName, inputs: [...inputs].sort(), v: PROMPT_VERSION });
|
|
81
81
|
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const camel = cleaned.replace(/\s+(.)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toLowerCase());
|
|
7
|
-
const safe = camel.replace(/[^A-Za-z0-9_$]/g, "");
|
|
8
|
-
return safe || "unnamedStep";
|
|
9
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
toMethod,
|
|
3
|
+
toVar,
|
|
4
|
+
matchAgainstConventions
|
|
5
|
+
} from "../_shared/step-matching.js";
|
|
10
6
|
function resolveValue(rawValue, ctx) {
|
|
11
7
|
const value = rawValue.trim().replace(/^['"]|['"]$/g, "");
|
|
12
8
|
if (/^(current\s*time|now|timestamp)$/i.test(value)) {
|
|
@@ -252,31 +248,8 @@ const STEP_CONVENTIONS = [
|
|
|
252
248
|
}
|
|
253
249
|
];
|
|
254
250
|
function matchStep(step, ctx) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (match) {
|
|
258
|
-
return {
|
|
259
|
-
call: convention.generateCall(match, ctx),
|
|
260
|
-
helperMethod: convention.generateMethod?.(match, ctx),
|
|
261
|
-
matched: true
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
const functionName = toMethod(step);
|
|
266
|
-
const declared = Array.from(ctx.declaredVars || []);
|
|
267
|
-
const paramNames = ctx.parameterNames || [];
|
|
268
|
-
const inputs = [...paramNames, ...declared];
|
|
269
|
-
const resultVar = ctx.resultName || `step${ctx.stepNum}Result`;
|
|
270
|
-
const inputObj = inputs.length > 0 ? `{ ${inputs.join(", ")} }` : "{}";
|
|
271
|
-
if (ctx.declaredVars) ctx.declaredVars.add(resultVar);
|
|
272
|
-
return {
|
|
273
|
-
call: ` // Step ${ctx.stepNum}: ${step} [AI-generated \u2014 pure function]
|
|
274
|
-
const ${resultVar} = await aiBehaviors.${functionName}(${inputObj});`,
|
|
275
|
-
matched: false,
|
|
276
|
-
functionName,
|
|
277
|
-
inputs,
|
|
278
|
-
resultVar
|
|
279
|
-
};
|
|
251
|
+
const aiArgsExpr = (inputs, _paramNames) => inputs.length > 0 ? `{ ${inputs.join(", ")} }` : "{}";
|
|
252
|
+
return matchAgainstConventions(step, ctx, STEP_CONVENTIONS, aiArgsExpr);
|
|
280
253
|
}
|
|
281
254
|
export {
|
|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U;IA8DxB,OAAO,CAAC,oBAAoB;CAuB7B;AAED,eAAO,MAAM,MAAM,wBAA+B,CAAC;AACnD,eAAe,MAAM,CAAC;AACtB,OAAO,EAAE,sBAAsB,EAAE,CAAC"}
|
package/dist/realize/index.js
CHANGED
|
@@ -286,6 +286,14 @@ class SpecVerseRealizeEngine {
|
|
|
286
286
|
matcher = matchMongoStep;
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
|
+
else if (ormFactoryName === 'PostgresNativeDriver') {
|
|
290
|
+
const pgMatcherPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'libs', 'instance-factories', 'services', 'templates', 'postgres-native', 'step-conventions.ts');
|
|
291
|
+
const pgMatcherSrc = resolveGenPath(pgMatcherPath);
|
|
292
|
+
if (pgMatcherSrc) {
|
|
293
|
+
const { matchPgStep } = await import(pgMatcherSrc);
|
|
294
|
+
matcher = matchPgStep;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
289
297
|
let aiBehaviorCount = 0;
|
|
290
298
|
for (const model of allModels) {
|
|
291
299
|
const ctrlName = `${model.name}Controller`;
|