@ingenyus/swarm-wasp 0.1.0 → 0.2.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/README.md +229 -21
- package/dist/.tsbuildinfo +1 -1
- package/dist/common/filesystem.d.ts +0 -14
- package/dist/common/filesystem.d.ts.map +1 -1
- package/dist/common/filesystem.js +123 -0
- package/dist/common/index.js +391 -0
- package/dist/common/plugin.js +41 -0
- package/dist/common/prisma.js +140 -0
- package/dist/common/schemas.d.ts +8 -42
- package/dist/common/schemas.d.ts.map +1 -1
- package/dist/common/schemas.js +54 -0
- package/dist/common/templates.js +52 -0
- package/dist/generators/action/action-generator.d.ts +16 -29
- package/dist/generators/action/action-generator.d.ts.map +1 -1
- package/dist/generators/action/action-generator.js +1429 -0
- package/dist/generators/action/index.js +1429 -0
- package/dist/generators/action/schema.d.ts +11 -23
- package/dist/generators/action/schema.d.ts.map +1 -1
- package/dist/generators/action/schema.js +119 -0
- package/dist/generators/api/api-generator.d.ts +19 -26
- package/dist/generators/api/api-generator.d.ts.map +1 -1
- package/dist/generators/api/api-generator.js +1108 -0
- package/dist/generators/api/index.js +1108 -0
- package/dist/generators/api/schema.d.ts +13 -21
- package/dist/generators/api/schema.d.ts.map +1 -1
- package/dist/generators/api/schema.js +121 -0
- package/dist/generators/api-namespace/api-namespace-generator.d.ts +10 -17
- package/dist/generators/api-namespace/api-namespace-generator.d.ts.map +1 -1
- package/dist/generators/api-namespace/api-namespace-generator.js +1032 -0
- package/dist/generators/api-namespace/index.js +1032 -0
- package/dist/generators/api-namespace/schema.d.ts +4 -12
- package/dist/generators/api-namespace/schema.d.ts.map +1 -1
- package/dist/generators/api-namespace/schema.js +93 -0
- package/dist/generators/base/{entity-generator.base.d.ts → component-generator.base.d.ts} +9 -9
- package/dist/generators/base/component-generator.base.d.ts.map +1 -0
- package/dist/generators/base/component-generator.base.js +935 -0
- package/dist/generators/base/index.d.ts +1 -1
- package/dist/generators/base/index.d.ts.map +1 -1
- package/dist/generators/base/index.js +1334 -0
- package/dist/generators/base/operation-generator.base.d.ts +12 -3
- package/dist/generators/base/operation-generator.base.d.ts.map +1 -1
- package/dist/generators/base/operation-generator.base.js +1335 -0
- package/dist/generators/base/wasp-generator.base.d.ts +2 -1
- package/dist/generators/base/wasp-generator.base.d.ts.map +1 -1
- package/dist/generators/base/wasp-generator.base.js +710 -0
- package/dist/generators/config/config-generator.d.ts +7 -4
- package/dist/generators/config/config-generator.d.ts.map +1 -1
- package/dist/generators/config/config-generator.js +0 -0
- package/dist/generators/config/index.js +600 -0
- package/dist/generators/config/wasp-config-generator.d.ts +1 -1
- package/dist/generators/config/wasp-config-generator.d.ts.map +1 -1
- package/dist/generators/config/wasp-config-generator.js +600 -0
- package/dist/generators/crud/crud-generator.d.ts +34 -22
- package/dist/generators/crud/crud-generator.d.ts.map +1 -1
- package/dist/generators/crud/crud-generator.js +1554 -0
- package/dist/generators/crud/index.js +1554 -0
- package/dist/generators/crud/schema.d.ts +25 -18
- package/dist/generators/crud/schema.d.ts.map +1 -1
- package/dist/generators/crud/schema.js +137 -0
- package/dist/generators/feature/feature-generator.d.ts +20 -0
- package/dist/generators/feature/feature-generator.d.ts.map +1 -0
- package/dist/generators/feature/feature-generator.js +769 -0
- package/dist/generators/feature/index.d.ts +2 -0
- package/dist/generators/feature/index.d.ts.map +1 -0
- package/dist/generators/feature/index.js +769 -0
- package/dist/generators/feature/schema.d.ts +5 -0
- package/dist/generators/feature/schema.d.ts.map +1 -0
- package/dist/generators/feature/schema.js +90 -0
- package/dist/generators/index.d.ts +1 -1
- package/dist/generators/index.d.ts.map +1 -1
- package/dist/generators/index.js +2215 -0
- package/dist/generators/job/index.js +1103 -0
- package/dist/generators/job/job-generator.d.ts +12 -23
- package/dist/generators/job/job-generator.d.ts.map +1 -1
- package/dist/generators/job/job-generator.js +1103 -0
- package/dist/generators/job/schema.d.ts +6 -18
- package/dist/generators/job/schema.d.ts.map +1 -1
- package/dist/generators/job/schema.js +156 -0
- package/dist/generators/query/index.js +1429 -0
- package/dist/generators/query/query-generator.d.ts +16 -29
- package/dist/generators/query/query-generator.d.ts.map +1 -1
- package/dist/generators/query/query-generator.js +1429 -0
- package/dist/generators/query/schema.d.ts +11 -23
- package/dist/generators/query/schema.d.ts.map +1 -1
- package/dist/generators/query/schema.js +119 -0
- package/dist/generators/route/index.js +1042 -0
- package/dist/generators/route/route-generator.d.ts +11 -20
- package/dist/generators/route/route-generator.d.ts.map +1 -1
- package/dist/generators/route/route-generator.js +1042 -0
- package/dist/generators/route/schema.d.ts +5 -15
- package/dist/generators/route/schema.d.ts.map +1 -1
- package/dist/generators/route/schema.js +94 -0
- package/dist/index.d.ts +2 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1730 -1839
- package/dist/plugins/index.d.ts +2 -0
- package/dist/plugins/index.d.ts.map +1 -0
- package/dist/plugins/wasp.d.ts +3 -0
- package/dist/plugins/wasp.d.ts.map +1 -0
- package/dist/types/constants.d.ts +4 -22
- package/dist/types/constants.d.ts.map +1 -1
- package/dist/types/constants.js +8 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +8 -2
- package/dist/wasp-config/app.d.ts +2 -1
- package/dist/wasp-config/app.d.ts.map +1 -1
- package/dist/wasp-config/app.js +357 -0
- package/dist/wasp-config/index.js +357 -0
- package/dist/wasp-config/stubs/index.js +48 -0
- package/package.json +5 -14
- package/dist/generators/args.types.d.ts +0 -85
- package/dist/generators/args.types.d.ts.map +0 -1
- package/dist/generators/base/entity-generator.base.d.ts.map +0 -1
- package/dist/generators/feature-directory/feature-directory-generator.d.ts +0 -18
- package/dist/generators/feature-directory/feature-directory-generator.d.ts.map +0 -1
- package/dist/generators/feature-directory/index.d.ts +0 -2
- package/dist/generators/feature-directory/index.d.ts.map +0 -1
- package/dist/generators/feature-directory/schema.d.ts +0 -8
- package/dist/generators/feature-directory/schema.d.ts.map +0 -1
- package/dist/plugin.d.ts +0 -6
- package/dist/plugin.d.ts.map +0 -1
- /package/dist/generators/{feature-directory → feature}/templates/feature.wasp.eta +0 -0
|
@@ -0,0 +1,1334 @@
|
|
|
1
|
+
// src/generators/base/component-generator.base.ts
|
|
2
|
+
import {
|
|
3
|
+
hasHelperMethodCall,
|
|
4
|
+
logger as singletonLogger4,
|
|
5
|
+
toCamelCase,
|
|
6
|
+
toKebabCase as toKebabCase2,
|
|
7
|
+
validateFeaturePath as validateFeaturePath3
|
|
8
|
+
} from "@ingenyus/swarm";
|
|
9
|
+
import path7 from "path";
|
|
10
|
+
|
|
11
|
+
// src/common/filesystem.ts
|
|
12
|
+
import { toPascalCase, validateFeaturePath } from "@ingenyus/swarm";
|
|
13
|
+
import fs from "fs";
|
|
14
|
+
import path from "path";
|
|
15
|
+
|
|
16
|
+
// src/types/constants.ts
|
|
17
|
+
var PLUGIN_NAME = "wasp";
|
|
18
|
+
var OPERATION_TYPES = ["query", "action"];
|
|
19
|
+
var OPERATIONS = {
|
|
20
|
+
CREATE: "create",
|
|
21
|
+
UPDATE: "update",
|
|
22
|
+
DELETE: "delete",
|
|
23
|
+
GET: "get",
|
|
24
|
+
GETALL: "getAll",
|
|
25
|
+
GETFILTERED: "getFiltered"
|
|
26
|
+
};
|
|
27
|
+
var TYPE_DIRECTORIES = {
|
|
28
|
+
component: "client/components",
|
|
29
|
+
hook: "client/hooks",
|
|
30
|
+
layout: "client/layouts",
|
|
31
|
+
page: "client/pages",
|
|
32
|
+
util: "client/utils",
|
|
33
|
+
action: "server/actions",
|
|
34
|
+
query: "server/queries",
|
|
35
|
+
middleware: "server/middleware",
|
|
36
|
+
job: "server/jobs",
|
|
37
|
+
api: "server/apis",
|
|
38
|
+
crud: "server/cruds",
|
|
39
|
+
type: "types"
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// src/common/filesystem.ts
|
|
43
|
+
var realFileSystem = {
|
|
44
|
+
readFileSync: fs.readFileSync,
|
|
45
|
+
writeFileSync: fs.writeFileSync,
|
|
46
|
+
existsSync: fs.existsSync,
|
|
47
|
+
copyFileSync: fs.copyFileSync,
|
|
48
|
+
mkdirSync: fs.mkdirSync,
|
|
49
|
+
readdirSync: fs.readdirSync,
|
|
50
|
+
statSync: fs.statSync
|
|
51
|
+
};
|
|
52
|
+
function findWaspRoot(fileSystem, startDir = process.cwd()) {
|
|
53
|
+
const startDirPath = path.resolve(startDir);
|
|
54
|
+
let currentDirPath = startDirPath;
|
|
55
|
+
const root = path.parse(currentDirPath).root;
|
|
56
|
+
while (currentDirPath !== root) {
|
|
57
|
+
const waspRootPath = path.join(currentDirPath, ".wasproot");
|
|
58
|
+
if (fileSystem.existsSync(waspRootPath)) {
|
|
59
|
+
return currentDirPath;
|
|
60
|
+
}
|
|
61
|
+
currentDirPath = path.dirname(currentDirPath);
|
|
62
|
+
}
|
|
63
|
+
throw new Error(
|
|
64
|
+
`Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
function copyDirectory(fileSystem, src, dest) {
|
|
68
|
+
if (!fileSystem.existsSync(dest)) {
|
|
69
|
+
fileSystem.mkdirSync(dest, { recursive: true });
|
|
70
|
+
}
|
|
71
|
+
const entries = fileSystem.readdirSync(src, { withFileTypes: true });
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
const srcPath = path.join(src, entry.name);
|
|
74
|
+
const destPath = path.join(dest, entry.name);
|
|
75
|
+
if (entry.isDirectory()) {
|
|
76
|
+
copyDirectory(fileSystem, srcPath, destPath);
|
|
77
|
+
} else {
|
|
78
|
+
fileSystem.copyFileSync(srcPath, destPath);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function ensureDirectoryExists(fileSystem, dir) {
|
|
83
|
+
if (!fileSystem.existsSync(dir)) {
|
|
84
|
+
fileSystem.mkdirSync(dir, { recursive: true });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function normaliseFeaturePath(featurePath) {
|
|
88
|
+
const segments = validateFeaturePath(featurePath);
|
|
89
|
+
const normalisedSegments = [];
|
|
90
|
+
for (let i = 0; i < segments.length; i++) {
|
|
91
|
+
const segment = segments[i];
|
|
92
|
+
const previousSegment = normalisedSegments[normalisedSegments.length - 1];
|
|
93
|
+
if (previousSegment !== "features" && segment !== "features") {
|
|
94
|
+
normalisedSegments.push("features");
|
|
95
|
+
}
|
|
96
|
+
normalisedSegments.push(segment);
|
|
97
|
+
}
|
|
98
|
+
return normalisedSegments.join("/");
|
|
99
|
+
}
|
|
100
|
+
function getFeatureDir(fileSystem, featureName) {
|
|
101
|
+
const waspRoot = findWaspRoot(fileSystem);
|
|
102
|
+
const normalisedPath = normaliseFeaturePath(featureName);
|
|
103
|
+
return path.join(waspRoot, "src", normalisedPath);
|
|
104
|
+
}
|
|
105
|
+
function getFeatureImportPath(featurePath) {
|
|
106
|
+
const segments = validateFeaturePath(featurePath);
|
|
107
|
+
return segments.join("/");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/common/plugin.ts
|
|
111
|
+
import path2 from "path";
|
|
112
|
+
import { fileURLToPath } from "url";
|
|
113
|
+
|
|
114
|
+
// src/common/prisma.ts
|
|
115
|
+
import {
|
|
116
|
+
getSchema
|
|
117
|
+
} from "@mrleebo/prisma-ast";
|
|
118
|
+
import fs2 from "fs";
|
|
119
|
+
import path3 from "path";
|
|
120
|
+
async function getEntityMetadata(modelName) {
|
|
121
|
+
try {
|
|
122
|
+
const schemaPath = path3.join(process.cwd(), "schema.prisma");
|
|
123
|
+
const schemaContent = fs2.readFileSync(schemaPath, "utf8");
|
|
124
|
+
const schema2 = getSchema(schemaContent);
|
|
125
|
+
const model = schema2.list?.find(
|
|
126
|
+
(m) => m.type === "model" && m.name === modelName
|
|
127
|
+
);
|
|
128
|
+
if (!model || model.type !== "model") {
|
|
129
|
+
throw new Error(`Model ${modelName} not found in schema`);
|
|
130
|
+
}
|
|
131
|
+
const compositeIdAttr = (model.properties || []).find(
|
|
132
|
+
(item) => item.type === "attribute" && item.kind === "object" && item.name === "id"
|
|
133
|
+
);
|
|
134
|
+
let compositeIdFields = [];
|
|
135
|
+
if (compositeIdAttr?.args?.[0]) {
|
|
136
|
+
const arg = compositeIdAttr.args[0];
|
|
137
|
+
if (typeof arg.value === "object" && arg.value !== null && "type" in arg.value && arg.value.type === "array" && "args" in arg.value) {
|
|
138
|
+
compositeIdFields = arg.value.args;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const fields = (model.properties || []).filter(
|
|
142
|
+
(item) => item.type === "field" && !item.array && !item.attributes?.some((attr) => attr.name === "relation")
|
|
143
|
+
).map((field) => {
|
|
144
|
+
const fieldType = typeof field.fieldType === "string" ? field.fieldType : field.fieldType.name;
|
|
145
|
+
const tsType = getPrismaToTsType(fieldType);
|
|
146
|
+
const isRequired = !field.optional;
|
|
147
|
+
const isId = field.attributes?.some((attr) => attr.name === "id") || compositeIdFields.includes(field.name);
|
|
148
|
+
const isUnique = field.attributes?.some((attr) => attr.name === "unique") || false;
|
|
149
|
+
const hasDefaultValue = field.attributes?.some((attr) => attr.name === "default") || false;
|
|
150
|
+
const isUpdatedAt = field.attributes?.some((attr) => attr.name === "updatedAt") || false;
|
|
151
|
+
const isGenerated = field.attributes?.some((attr) => attr.name === "map") || false;
|
|
152
|
+
return {
|
|
153
|
+
name: field.name,
|
|
154
|
+
type: fieldType,
|
|
155
|
+
tsType,
|
|
156
|
+
isRequired,
|
|
157
|
+
isId,
|
|
158
|
+
isUnique,
|
|
159
|
+
hasDefaultValue,
|
|
160
|
+
isGenerated,
|
|
161
|
+
isUpdatedAt
|
|
162
|
+
};
|
|
163
|
+
});
|
|
164
|
+
return {
|
|
165
|
+
name: modelName,
|
|
166
|
+
fields
|
|
167
|
+
};
|
|
168
|
+
} catch (error) {
|
|
169
|
+
throw new Error(
|
|
170
|
+
`Failed to get entity metadata for ${modelName}: ${error instanceof Error ? error.message : String(error)}`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function getIdFields(model) {
|
|
175
|
+
const idFields = model.fields.filter((f) => f.isId).map((f) => f.name);
|
|
176
|
+
if (idFields.length === 0) {
|
|
177
|
+
throw new Error(`No ID field found for model ${model.name}`);
|
|
178
|
+
}
|
|
179
|
+
return idFields;
|
|
180
|
+
}
|
|
181
|
+
function getRequiredFields(model) {
|
|
182
|
+
return model.fields.filter(
|
|
183
|
+
(f) => f.isRequired && !f.hasDefaultValue && !f.isGenerated && !f.isUpdatedAt
|
|
184
|
+
).map((f) => f.name);
|
|
185
|
+
}
|
|
186
|
+
function getOptionalFields(model) {
|
|
187
|
+
return model.fields.filter(
|
|
188
|
+
(field) => (field.hasDefaultValue && field.type !== "DateTime" || !field.isRequired) && !field.isId && !field.isGenerated && !field.isUpdatedAt
|
|
189
|
+
).map((field) => field.name);
|
|
190
|
+
}
|
|
191
|
+
function getJsonFields(model) {
|
|
192
|
+
return model.fields.filter((f) => f.type === "Json").map((f) => f.name);
|
|
193
|
+
}
|
|
194
|
+
function generateJsonTypeHandling(jsonFields) {
|
|
195
|
+
if (jsonFields.length === 0) return "";
|
|
196
|
+
const assignments = jsonFields.map(
|
|
197
|
+
(field) => ` ${field}: (data.${field} as Prisma.JsonValue) || Prisma.JsonNull`
|
|
198
|
+
).join(",\n");
|
|
199
|
+
return `,
|
|
200
|
+
${assignments}`;
|
|
201
|
+
}
|
|
202
|
+
function needsPrismaImport(model) {
|
|
203
|
+
return model.fields.some((f) => f.type === "Json" || f.type === "Decimal");
|
|
204
|
+
}
|
|
205
|
+
function generatePickType(modelName, fields, allFields) {
|
|
206
|
+
if (fields.length === 0) return "";
|
|
207
|
+
if (fields.length === allFields.length) return modelName;
|
|
208
|
+
const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
|
|
209
|
+
return `Pick<${modelName}, ${fieldUnion}>`;
|
|
210
|
+
}
|
|
211
|
+
function generateOmitType(modelName, fields, allFields) {
|
|
212
|
+
if (fields.length === 0) return modelName;
|
|
213
|
+
if (fields.length === allFields.length) return "";
|
|
214
|
+
const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
|
|
215
|
+
return `Omit<${modelName}, ${fieldUnion}>`;
|
|
216
|
+
}
|
|
217
|
+
function generatePartialType(typeString) {
|
|
218
|
+
if (!typeString) return "";
|
|
219
|
+
return `Partial<${typeString}>`;
|
|
220
|
+
}
|
|
221
|
+
function generateIntersectionType(type1, type2) {
|
|
222
|
+
if (!type1 && !type2) return "";
|
|
223
|
+
if (!type1) return type2;
|
|
224
|
+
if (!type2) return type1;
|
|
225
|
+
return `${type1} & ${type2}`;
|
|
226
|
+
}
|
|
227
|
+
function getPrismaToTsType(type) {
|
|
228
|
+
const typeMap = {
|
|
229
|
+
String: "string",
|
|
230
|
+
Int: "number",
|
|
231
|
+
Float: "number",
|
|
232
|
+
Boolean: "boolean",
|
|
233
|
+
DateTime: "Date",
|
|
234
|
+
Json: "Prisma.JsonValue",
|
|
235
|
+
BigInt: "bigint",
|
|
236
|
+
Decimal: "Prisma.Decimal",
|
|
237
|
+
Bytes: "Buffer"
|
|
238
|
+
};
|
|
239
|
+
return typeMap[type] || type;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// src/common/schemas.ts
|
|
243
|
+
import { commandRegistry } from "@ingenyus/swarm";
|
|
244
|
+
import { z } from "zod";
|
|
245
|
+
var commonSchemas = {
|
|
246
|
+
feature: z.string().min(1, "Feature is required").meta({
|
|
247
|
+
description: "The feature directory this component will be generated in"
|
|
248
|
+
}).register(commandRegistry, {
|
|
249
|
+
shortName: "f",
|
|
250
|
+
examples: ["root", "auth", "dashboard/users"],
|
|
251
|
+
helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
|
|
252
|
+
}),
|
|
253
|
+
name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
|
|
254
|
+
shortName: "n",
|
|
255
|
+
examples: ["users", "task"],
|
|
256
|
+
helpText: "Will be used for generated files and configuration entries"
|
|
257
|
+
}),
|
|
258
|
+
target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
|
|
259
|
+
shortName: "t",
|
|
260
|
+
examples: ["dashboard/users", "features/dashboard/features/users"],
|
|
261
|
+
helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
|
|
262
|
+
}),
|
|
263
|
+
path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
|
|
264
|
+
shortName: "p",
|
|
265
|
+
examples: ["/api/users/:id", "/api/products"],
|
|
266
|
+
helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
|
|
267
|
+
}),
|
|
268
|
+
dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
|
|
269
|
+
shortName: "d",
|
|
270
|
+
examples: ["User", "Product", "Task"],
|
|
271
|
+
helpText: "The Wasp entity or model name this operation will interact with"
|
|
272
|
+
}),
|
|
273
|
+
entities: z.array(z.string()).optional().meta({
|
|
274
|
+
description: "The Wasp entities that will be available to this component (optional)"
|
|
275
|
+
}).register(commandRegistry, {
|
|
276
|
+
shortName: "e",
|
|
277
|
+
examples: ["User", "User Task"],
|
|
278
|
+
helpText: "An array of Wasp entity names"
|
|
279
|
+
}),
|
|
280
|
+
force: z.boolean().optional().meta({
|
|
281
|
+
description: "Force overwrite of existing files and configuration entries (optional)"
|
|
282
|
+
}).register(commandRegistry, {
|
|
283
|
+
shortName: "F",
|
|
284
|
+
helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
|
|
285
|
+
}),
|
|
286
|
+
auth: z.boolean().optional().meta({
|
|
287
|
+
description: "Require authentication for this component (optional)"
|
|
288
|
+
}).register(commandRegistry, {
|
|
289
|
+
shortName: "a",
|
|
290
|
+
helpText: "Will generate authentication checks"
|
|
291
|
+
})
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
// src/common/templates.ts
|
|
295
|
+
import { toKebabCase } from "@ingenyus/swarm";
|
|
296
|
+
import { Eta } from "eta";
|
|
297
|
+
import path4 from "path";
|
|
298
|
+
var TemplateUtility = class {
|
|
299
|
+
constructor(fileSystem) {
|
|
300
|
+
this.fileSystem = fileSystem;
|
|
301
|
+
}
|
|
302
|
+
processTemplate(templatePath, replacements) {
|
|
303
|
+
const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
|
|
304
|
+
const functionHeader = declarations ? `const ${declarations};` : void 0;
|
|
305
|
+
const templateDir = path4.dirname(templatePath);
|
|
306
|
+
const eta = new Eta({
|
|
307
|
+
autoTrim: false,
|
|
308
|
+
autoEscape: false,
|
|
309
|
+
views: templateDir,
|
|
310
|
+
functionHeader
|
|
311
|
+
});
|
|
312
|
+
const templateName = path4.basename(templatePath).replace(/\.eta$/, "");
|
|
313
|
+
if (this.fileSystem.existsSync(templatePath)) {
|
|
314
|
+
return eta.render(templateName, replacements);
|
|
315
|
+
} else {
|
|
316
|
+
const template = this.fileSystem.readFileSync(templatePath, "utf8");
|
|
317
|
+
return eta.renderString(template, replacements);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Helper method to resolve template paths for concrete generators
|
|
322
|
+
* @param relativePath - The relative path to the template file
|
|
323
|
+
* @param generatorName - The name of the generator (e.g., 'api', 'job')
|
|
324
|
+
* @param currentFileUrl - The import.meta.url from the concrete generator class
|
|
325
|
+
* @returns The full path to the template file
|
|
326
|
+
*/
|
|
327
|
+
resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
|
|
328
|
+
const generatorDirName = toKebabCase(generatorName);
|
|
329
|
+
const currentFilePath = new URL(currentFileUrl).pathname;
|
|
330
|
+
const currentFileDir = path4.dirname(currentFilePath);
|
|
331
|
+
const currentFileName = path4.basename(currentFilePath);
|
|
332
|
+
const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
|
|
333
|
+
const startDir = isInstalledPackage ? currentFileDir : path4.dirname(path4.dirname(currentFileDir));
|
|
334
|
+
return path4.join(
|
|
335
|
+
startDir,
|
|
336
|
+
"generators",
|
|
337
|
+
generatorDirName,
|
|
338
|
+
"templates",
|
|
339
|
+
relativePath
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// src/generators/feature/feature-generator.ts
|
|
345
|
+
import {
|
|
346
|
+
handleFatalError as handleFatalError2,
|
|
347
|
+
logger as singletonLogger3,
|
|
348
|
+
validateFeaturePath as validateFeaturePath2
|
|
349
|
+
} from "@ingenyus/swarm";
|
|
350
|
+
import path6 from "path";
|
|
351
|
+
|
|
352
|
+
// src/generators/base/wasp-generator.base.ts
|
|
353
|
+
import {
|
|
354
|
+
GeneratorBase,
|
|
355
|
+
logger as singletonLogger2,
|
|
356
|
+
SwarmConfigManager,
|
|
357
|
+
TemplateResolver
|
|
358
|
+
} from "@ingenyus/swarm";
|
|
359
|
+
|
|
360
|
+
// src/generators/config/wasp-config-generator.ts
|
|
361
|
+
import {
|
|
362
|
+
handleFatalError,
|
|
363
|
+
parseHelperMethodDefinition,
|
|
364
|
+
logger as singletonLogger
|
|
365
|
+
} from "@ingenyus/swarm";
|
|
366
|
+
import path5 from "path";
|
|
367
|
+
var WaspConfigGenerator = class {
|
|
368
|
+
constructor(logger = singletonLogger, fileSystem = realFileSystem) {
|
|
369
|
+
this.logger = logger;
|
|
370
|
+
this.fileSystem = fileSystem;
|
|
371
|
+
this.templateUtility = new TemplateUtility(fileSystem);
|
|
372
|
+
}
|
|
373
|
+
path = path5;
|
|
374
|
+
templateUtility;
|
|
375
|
+
/**
|
|
376
|
+
* Gets the template path for feature config templates.
|
|
377
|
+
* Feature config templates are located in the feature generator's templates directory.
|
|
378
|
+
* @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
|
|
379
|
+
* @returns The full path to the template file
|
|
380
|
+
*/
|
|
381
|
+
getTemplatePath(templateName) {
|
|
382
|
+
return this.templateUtility.resolveTemplatePath(
|
|
383
|
+
templateName,
|
|
384
|
+
"feature",
|
|
385
|
+
import.meta.url
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Generate a TypeScript Wasp config file in a feature directory
|
|
390
|
+
* @param featurePath - The feature directory path
|
|
391
|
+
*/
|
|
392
|
+
generate(featurePath) {
|
|
393
|
+
const featureDir = getFeatureDir(this.fileSystem, featurePath);
|
|
394
|
+
if (!this.fileSystem.existsSync(featureDir)) {
|
|
395
|
+
this.fileSystem.mkdirSync(featureDir, { recursive: true });
|
|
396
|
+
}
|
|
397
|
+
const templatePath = this.getTemplatePath("feature.wasp.eta");
|
|
398
|
+
if (!this.fileSystem.existsSync(templatePath)) {
|
|
399
|
+
this.logger.error(`Template not found: ${templatePath}`);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const configFilePath = path5.join(featureDir, `feature.wasp.ts`);
|
|
403
|
+
if (this.fileSystem.existsSync(configFilePath)) {
|
|
404
|
+
this.logger.warn(`Feature config already exists: ${configFilePath}`);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
this.fileSystem.copyFileSync(templatePath, configFilePath);
|
|
408
|
+
this.logger.success(`Generated feature config: ${configFilePath}`);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Updates or creates a feature configuration file with a pre-built declaration.
|
|
412
|
+
* @param featurePath - The path to the feature
|
|
413
|
+
* @param declaration - The pre-built declaration string to add or update
|
|
414
|
+
* @returns The updated feature configuration file
|
|
415
|
+
*/
|
|
416
|
+
update(featurePath, declaration) {
|
|
417
|
+
const configDir = getFeatureDir(this.fileSystem, featurePath);
|
|
418
|
+
const configFilePath = path5.join(configDir, `feature.wasp.ts`);
|
|
419
|
+
if (!this.fileSystem.existsSync(configFilePath)) {
|
|
420
|
+
const templatePath = this.getTemplatePath("feature.wasp.eta");
|
|
421
|
+
if (!this.fileSystem.existsSync(templatePath)) {
|
|
422
|
+
handleFatalError(`Feature config template not found: ${templatePath}`);
|
|
423
|
+
}
|
|
424
|
+
this.fileSystem.copyFileSync(templatePath, configFilePath);
|
|
425
|
+
}
|
|
426
|
+
let content = this.fileSystem.readFileSync(configFilePath, "utf8");
|
|
427
|
+
content = this.normaliseSemicolons(content);
|
|
428
|
+
const parsed = parseHelperMethodDefinition(declaration);
|
|
429
|
+
if (!parsed) {
|
|
430
|
+
handleFatalError(`Could not parse definition: ${declaration}`);
|
|
431
|
+
return content;
|
|
432
|
+
}
|
|
433
|
+
const { methodName } = parsed;
|
|
434
|
+
const hadExistingDefinitions = this.hasExistingDefinitions(
|
|
435
|
+
content,
|
|
436
|
+
methodName
|
|
437
|
+
);
|
|
438
|
+
content = this.removeExistingDefinition(content, declaration);
|
|
439
|
+
const hasExistingDefinitions = this.hasExistingDefinitions(
|
|
440
|
+
content,
|
|
441
|
+
methodName
|
|
442
|
+
);
|
|
443
|
+
const lines = content.split("\n");
|
|
444
|
+
const configureFunctionStart = lines.findIndex(
|
|
445
|
+
(line) => line.trim().startsWith("export default function")
|
|
446
|
+
);
|
|
447
|
+
if (configureFunctionStart === -1) {
|
|
448
|
+
handleFatalError("Could not find configure function in feature config");
|
|
449
|
+
}
|
|
450
|
+
const appLineIndex = lines.findIndex(
|
|
451
|
+
(line, index) => index > configureFunctionStart && line.trim() === "app"
|
|
452
|
+
);
|
|
453
|
+
if (appLineIndex === -1) {
|
|
454
|
+
const insertIndex = configureFunctionStart + 1;
|
|
455
|
+
const itemsToInsert = [" app"];
|
|
456
|
+
const comment = this.getMethodComment(methodName);
|
|
457
|
+
itemsToInsert.push(` ${comment}`);
|
|
458
|
+
itemsToInsert.push(declaration.trimEnd());
|
|
459
|
+
lines.splice(insertIndex, 0, ...itemsToInsert);
|
|
460
|
+
} else {
|
|
461
|
+
const { insertIndex, addComment } = this.findGroupInsertionPoint(
|
|
462
|
+
lines,
|
|
463
|
+
methodName,
|
|
464
|
+
declaration,
|
|
465
|
+
hadExistingDefinitions || hasExistingDefinitions
|
|
466
|
+
);
|
|
467
|
+
const newLines = this.insertWithSpacing(
|
|
468
|
+
lines,
|
|
469
|
+
declaration,
|
|
470
|
+
insertIndex,
|
|
471
|
+
methodName,
|
|
472
|
+
addComment
|
|
473
|
+
);
|
|
474
|
+
const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
|
|
475
|
+
this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
|
|
476
|
+
return configFilePath;
|
|
477
|
+
}
|
|
478
|
+
const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
|
|
479
|
+
this.fileSystem.writeFileSync(configFilePath, normalisedContent);
|
|
480
|
+
return configFilePath;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Determines the insertion index for a method name based on alphabetical ordering
|
|
484
|
+
* of existing groups in the configuration file.
|
|
485
|
+
* @param groups - Object containing existing method groups
|
|
486
|
+
* @param methodName - The method name to find insertion index for
|
|
487
|
+
* @returns The insertion index for the method name
|
|
488
|
+
*/
|
|
489
|
+
getInsertionIndexForMethod(groups, methodName) {
|
|
490
|
+
const existingMethods = Object.keys(groups).filter(
|
|
491
|
+
(method) => groups[method].length > 0
|
|
492
|
+
);
|
|
493
|
+
const allMethods = [...existingMethods, methodName].sort();
|
|
494
|
+
return allMethods.indexOf(methodName);
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Gets the comment text for a method type.
|
|
498
|
+
* @param methodName The method name (e.g., 'addApi')
|
|
499
|
+
* @returns The comment text for the method type
|
|
500
|
+
*/
|
|
501
|
+
getMethodComment(methodName) {
|
|
502
|
+
const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
|
|
503
|
+
return `// ${entityName} definitions`;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Finds the correct insertion point for a new configuration item.
|
|
507
|
+
* @param lines - Array of file lines
|
|
508
|
+
* @param methodName - The method name (e.g., 'addApi')
|
|
509
|
+
* @param definition - The definition string to parse for item name
|
|
510
|
+
* @returns Object with insertion index and whether to add a comment
|
|
511
|
+
*/
|
|
512
|
+
findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
|
|
513
|
+
const appLineIndex = lines.findIndex((line) => line.trim() === "app");
|
|
514
|
+
if (appLineIndex === -1) {
|
|
515
|
+
return { insertIndex: appLineIndex + 1, addComment: false };
|
|
516
|
+
}
|
|
517
|
+
const methodCalls = [];
|
|
518
|
+
for (let i = appLineIndex + 1; i < lines.length; i++) {
|
|
519
|
+
const line = lines[i].trim();
|
|
520
|
+
if (line.startsWith(".") && line.includes("(")) {
|
|
521
|
+
let methodCallContent = line;
|
|
522
|
+
let j = i;
|
|
523
|
+
let closingParenCount = 0;
|
|
524
|
+
let foundClosingParen = false;
|
|
525
|
+
for (let k = 0; k < methodCallContent.length; k++) {
|
|
526
|
+
if (methodCallContent[k] === "(") closingParenCount++;
|
|
527
|
+
if (methodCallContent[k] === ")") closingParenCount--;
|
|
528
|
+
if (closingParenCount === 0 && methodCallContent[k] === ")") {
|
|
529
|
+
foundClosingParen = true;
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
while (!foundClosingParen && j < lines.length - 1) {
|
|
534
|
+
j++;
|
|
535
|
+
methodCallContent += " " + lines[j].trim();
|
|
536
|
+
for (let k = 0; k < lines[j].length; k++) {
|
|
537
|
+
if (lines[j][k] === "(") closingParenCount++;
|
|
538
|
+
if (lines[j][k] === ")") closingParenCount--;
|
|
539
|
+
if (closingParenCount === 0 && lines[j][k] === ")") {
|
|
540
|
+
foundClosingParen = true;
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const match = methodCallContent.match(
|
|
546
|
+
/\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
|
|
547
|
+
);
|
|
548
|
+
if (match) {
|
|
549
|
+
methodCalls.push({
|
|
550
|
+
lineIndex: i,
|
|
551
|
+
endLineIndex: j,
|
|
552
|
+
methodName: match[1],
|
|
553
|
+
itemName: match[2]
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const groups = {};
|
|
559
|
+
methodCalls.forEach((call) => {
|
|
560
|
+
if (!groups[call.methodName]) {
|
|
561
|
+
groups[call.methodName] = [];
|
|
562
|
+
}
|
|
563
|
+
groups[call.methodName].push({
|
|
564
|
+
lineIndex: call.lineIndex,
|
|
565
|
+
endLineIndex: call.endLineIndex,
|
|
566
|
+
itemName: call.itemName
|
|
567
|
+
});
|
|
568
|
+
});
|
|
569
|
+
const targetGroup = groups[methodName] || [];
|
|
570
|
+
if (targetGroup.length === 0) {
|
|
571
|
+
const targetGroupIndex = this.getInsertionIndexForMethod(
|
|
572
|
+
groups,
|
|
573
|
+
methodName
|
|
574
|
+
);
|
|
575
|
+
const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
|
|
576
|
+
for (let i = targetGroupIndex; i < existingMethods.length; i++) {
|
|
577
|
+
const groupMethod = existingMethods[i];
|
|
578
|
+
if (groups[groupMethod] && groups[groupMethod].length > 0) {
|
|
579
|
+
const firstItem = groups[groupMethod][0];
|
|
580
|
+
let insertIndex = firstItem.lineIndex;
|
|
581
|
+
for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
|
|
582
|
+
const line = lines[j].trim();
|
|
583
|
+
if (line.startsWith("//") && line.includes("definitions")) {
|
|
584
|
+
insertIndex = j;
|
|
585
|
+
break;
|
|
586
|
+
} else if (line.startsWith(".") || line === "") {
|
|
587
|
+
continue;
|
|
588
|
+
} else {
|
|
589
|
+
break;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return { insertIndex, addComment: !hasExistingDefinitionsOfType };
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
for (let i = targetGroupIndex - 1; i >= 0; i--) {
|
|
596
|
+
const groupMethod = existingMethods[i];
|
|
597
|
+
if (groups[groupMethod] && groups[groupMethod].length > 0) {
|
|
598
|
+
const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
|
|
599
|
+
return {
|
|
600
|
+
insertIndex: lastItem2.endLineIndex + 1,
|
|
601
|
+
addComment: !hasExistingDefinitionsOfType
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
insertIndex: appLineIndex + 1,
|
|
607
|
+
addComment: !hasExistingDefinitionsOfType
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
const parsed = parseHelperMethodDefinition(definition);
|
|
611
|
+
if (!parsed) {
|
|
612
|
+
return { insertIndex: appLineIndex + 1, addComment: false };
|
|
613
|
+
}
|
|
614
|
+
const { firstParam: itemName } = parsed;
|
|
615
|
+
for (let i = 0; i < targetGroup.length; i++) {
|
|
616
|
+
if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
|
|
617
|
+
return { insertIndex: targetGroup[i].lineIndex, addComment: false };
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const lastItem = targetGroup[targetGroup.length - 1];
|
|
621
|
+
return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Inserts a definition with optional comment header.
|
|
625
|
+
* @param lines - Array of file lines
|
|
626
|
+
* @param declaration - The declaration to insert
|
|
627
|
+
* @param insertIndex - The index where to insert
|
|
628
|
+
* @param methodName - The method name for comment generation
|
|
629
|
+
* @param addComment - Whether to add a comment before the declaration
|
|
630
|
+
* @returns The modified lines array
|
|
631
|
+
*/
|
|
632
|
+
insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
|
|
633
|
+
const newLines = [...lines];
|
|
634
|
+
if (addComment) {
|
|
635
|
+
const comment = this.getMethodComment(methodName);
|
|
636
|
+
newLines.splice(insertIndex, 0, ` ${comment}`);
|
|
637
|
+
insertIndex += 1;
|
|
638
|
+
}
|
|
639
|
+
newLines.splice(insertIndex, 0, declaration.trimEnd());
|
|
640
|
+
return newLines;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Checks if there are any existing definitions of a specific type in the content.
|
|
644
|
+
* @param content - The file content to search
|
|
645
|
+
* @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
|
|
646
|
+
* @returns true if there are existing definitions of this type, false otherwise
|
|
647
|
+
*/
|
|
648
|
+
hasExistingDefinitions(content, methodName) {
|
|
649
|
+
const lines = content.split("\n");
|
|
650
|
+
for (const line of lines) {
|
|
651
|
+
if (line.trim().startsWith(`.${methodName}(`)) {
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Removes an existing definition from the content by finding the helper method call
|
|
659
|
+
* and removing the entire method call block.
|
|
660
|
+
* @param content - The file content
|
|
661
|
+
* @param definition - The new definition to find the existing one from
|
|
662
|
+
* @returns The content with the existing definition removed
|
|
663
|
+
*/
|
|
664
|
+
removeExistingDefinition(content, definition) {
|
|
665
|
+
const parsed = parseHelperMethodDefinition(definition);
|
|
666
|
+
if (!parsed) {
|
|
667
|
+
return content;
|
|
668
|
+
}
|
|
669
|
+
const { methodName, firstParam } = parsed;
|
|
670
|
+
let contentLines = content.split("\n");
|
|
671
|
+
let openingLineIndex = -1;
|
|
672
|
+
for (let i = 0; i < contentLines.length; i++) {
|
|
673
|
+
const line = contentLines[i];
|
|
674
|
+
if (line.trim().startsWith(`.${methodName}(`)) {
|
|
675
|
+
if (firstParam && line.includes(firstParam)) {
|
|
676
|
+
openingLineIndex = i;
|
|
677
|
+
break;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (openingLineIndex === -1) {
|
|
682
|
+
return content;
|
|
683
|
+
}
|
|
684
|
+
let closingLineIndex = -1;
|
|
685
|
+
let parenCount = 0;
|
|
686
|
+
let braceCount = 0;
|
|
687
|
+
let foundOpening = false;
|
|
688
|
+
for (let i = openingLineIndex; i < contentLines.length; i++) {
|
|
689
|
+
const line = contentLines[i];
|
|
690
|
+
for (const char of line) {
|
|
691
|
+
if (char === "(") {
|
|
692
|
+
parenCount++;
|
|
693
|
+
foundOpening = true;
|
|
694
|
+
} else if (char === ")") {
|
|
695
|
+
parenCount--;
|
|
696
|
+
if (foundOpening && parenCount === 0 && braceCount === 0) {
|
|
697
|
+
closingLineIndex = i;
|
|
698
|
+
break;
|
|
699
|
+
}
|
|
700
|
+
} else if (char === "{") {
|
|
701
|
+
braceCount++;
|
|
702
|
+
} else if (char === "}") {
|
|
703
|
+
braceCount--;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (closingLineIndex !== -1) {
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (closingLineIndex === -1) {
|
|
711
|
+
this.logger.warn(
|
|
712
|
+
"Could not find closing parenthesis for existing definition"
|
|
713
|
+
);
|
|
714
|
+
return content;
|
|
715
|
+
}
|
|
716
|
+
contentLines.splice(
|
|
717
|
+
openingLineIndex,
|
|
718
|
+
closingLineIndex - openingLineIndex + 1
|
|
719
|
+
);
|
|
720
|
+
return contentLines.join("\n");
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Adds a definition to the content by finding the appropriate place to insert it.
|
|
724
|
+
* @param content - The current file content
|
|
725
|
+
* @param definition - The definition to add
|
|
726
|
+
* @returns The updated content with the new definition
|
|
727
|
+
*/
|
|
728
|
+
addDefinitionToContent(content, definition) {
|
|
729
|
+
const lines = content.split("\n");
|
|
730
|
+
const lastLineIndex = lines.length - 1;
|
|
731
|
+
let insertIndex = lastLineIndex;
|
|
732
|
+
for (let i = lastLineIndex; i >= 0; i--) {
|
|
733
|
+
const line = lines[i].trim();
|
|
734
|
+
if (line && !line.startsWith("}")) {
|
|
735
|
+
insertIndex = i;
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
lines.splice(insertIndex + 1, 0, ` ${definition}`);
|
|
740
|
+
return lines.join("\n");
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Normalises semicolons in the config file by removing them from method chain calls
|
|
744
|
+
* while preserving them in other contexts (imports, declarations, etc.).
|
|
745
|
+
* @param content - The file content to normalise
|
|
746
|
+
* @returns The normalised content
|
|
747
|
+
*/
|
|
748
|
+
normaliseSemicolons(content) {
|
|
749
|
+
const lines = content.split("\n");
|
|
750
|
+
const configureFunctionStart = lines.findIndex(
|
|
751
|
+
(line) => line.trim().startsWith("export default function")
|
|
752
|
+
);
|
|
753
|
+
if (configureFunctionStart === -1) {
|
|
754
|
+
return content;
|
|
755
|
+
}
|
|
756
|
+
const appLineIndex = lines.findIndex(
|
|
757
|
+
(line, index) => index > configureFunctionStart && line.trim().startsWith("app")
|
|
758
|
+
);
|
|
759
|
+
if (appLineIndex === -1) {
|
|
760
|
+
return content;
|
|
761
|
+
}
|
|
762
|
+
let braceCount = 0;
|
|
763
|
+
let functionEndIndex = lines.length - 1;
|
|
764
|
+
for (let i = configureFunctionStart; i < lines.length; i++) {
|
|
765
|
+
const line = lines[i];
|
|
766
|
+
for (const char of line) {
|
|
767
|
+
if (char === "{") braceCount++;
|
|
768
|
+
if (char === "}") {
|
|
769
|
+
braceCount--;
|
|
770
|
+
if (braceCount === 0) {
|
|
771
|
+
functionEndIndex = i;
|
|
772
|
+
break;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (braceCount === 0 && i > configureFunctionStart) {
|
|
777
|
+
break;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
let lastMethodCallIndex = -1;
|
|
781
|
+
for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
|
|
782
|
+
const line = lines[i];
|
|
783
|
+
const trimmed = line.trim();
|
|
784
|
+
if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
|
|
785
|
+
lines[i] = line.replace(/;\s*$/, "");
|
|
786
|
+
lastMethodCallIndex = i;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
|
|
790
|
+
lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
|
|
791
|
+
}
|
|
792
|
+
return lines.join("\n");
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
|
|
796
|
+
// src/generators/base/wasp-generator.base.ts
|
|
797
|
+
var WaspGeneratorBase = class extends GeneratorBase {
|
|
798
|
+
constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
|
|
799
|
+
super(fileSystem, logger);
|
|
800
|
+
this.fileSystem = fileSystem;
|
|
801
|
+
this.logger = logger;
|
|
802
|
+
this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
|
|
803
|
+
this.templateUtility = new TemplateUtility(fileSystem);
|
|
804
|
+
this.templateResolver = new TemplateResolver(fileSystem);
|
|
805
|
+
}
|
|
806
|
+
configGenerator;
|
|
807
|
+
templateUtility;
|
|
808
|
+
templateResolver;
|
|
809
|
+
swarmConfig;
|
|
810
|
+
configLoaded = false;
|
|
811
|
+
// Plugin name from swarm.config.json
|
|
812
|
+
pluginName = PLUGIN_NAME;
|
|
813
|
+
async loadSwarmConfig() {
|
|
814
|
+
if (this.configLoaded) return;
|
|
815
|
+
const configManager = new SwarmConfigManager();
|
|
816
|
+
this.swarmConfig = await configManager.loadConfig();
|
|
817
|
+
this.configLoaded = true;
|
|
818
|
+
}
|
|
819
|
+
async getCustomTemplateDir() {
|
|
820
|
+
await this.loadSwarmConfig();
|
|
821
|
+
return this.swarmConfig?.templateDirectory;
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Resolves template path with override support
|
|
825
|
+
*/
|
|
826
|
+
async getTemplatePath(templateName) {
|
|
827
|
+
const defaultPath = this.getDefaultTemplatePath(templateName);
|
|
828
|
+
const customPath = await this.getCustomTemplateDir();
|
|
829
|
+
if (!customPath) {
|
|
830
|
+
return defaultPath;
|
|
831
|
+
}
|
|
832
|
+
const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
|
|
833
|
+
this.pluginName,
|
|
834
|
+
this.name,
|
|
835
|
+
templateName,
|
|
836
|
+
defaultPath,
|
|
837
|
+
customPath
|
|
838
|
+
);
|
|
839
|
+
if (isCustom) {
|
|
840
|
+
this.logger.info(`Using custom template: ${resolvedPath}`);
|
|
841
|
+
}
|
|
842
|
+
return resolvedPath;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Processes a template and writes the result to a file
|
|
846
|
+
*/
|
|
847
|
+
async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
|
|
848
|
+
const templatePath = await this.getTemplatePath(templateName);
|
|
849
|
+
const fileExists = this.checkFileExists(
|
|
850
|
+
outputPath,
|
|
851
|
+
force,
|
|
852
|
+
readableFileType
|
|
853
|
+
);
|
|
854
|
+
const content = this.templateUtility.processTemplate(
|
|
855
|
+
templatePath,
|
|
856
|
+
replacements
|
|
857
|
+
);
|
|
858
|
+
this.writeFile(outputPath, content, readableFileType, fileExists);
|
|
859
|
+
return fileExists;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Generic existence check with force flag handling
|
|
863
|
+
* Consolidates the pattern used in both file and config checks
|
|
864
|
+
*/
|
|
865
|
+
checkExistence(exists, itemDescription, force, errorMessage) {
|
|
866
|
+
if (exists && !force) {
|
|
867
|
+
this.logger.error(`${itemDescription}. Use --force to overwrite`);
|
|
868
|
+
throw new Error(errorMessage || itemDescription);
|
|
869
|
+
}
|
|
870
|
+
return exists;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Checks if a file exists and handles force flag logic
|
|
874
|
+
*/
|
|
875
|
+
checkFileExists(filePath, force, fileType) {
|
|
876
|
+
const fileExists = this.fileSystem.existsSync(filePath);
|
|
877
|
+
return this.checkExistence(
|
|
878
|
+
fileExists,
|
|
879
|
+
`${fileType} already exists: ${filePath}`,
|
|
880
|
+
force,
|
|
881
|
+
`${fileType} already exists`
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Safely writes a file with proper error handling and logging
|
|
886
|
+
*/
|
|
887
|
+
writeFile(filePath, content, fileType, fileExists) {
|
|
888
|
+
this.fileSystem.writeFileSync(filePath, content);
|
|
889
|
+
this.logger.success(
|
|
890
|
+
`${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
// src/generators/feature/schema.ts
|
|
896
|
+
import { z as z2 } from "zod";
|
|
897
|
+
var schema = z2.object({
|
|
898
|
+
target: commonSchemas.target
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
// src/generators/feature/feature-generator.ts
|
|
902
|
+
var FeatureGenerator = class extends WaspGeneratorBase {
|
|
903
|
+
constructor(logger = singletonLogger3, fileSystem = realFileSystem) {
|
|
904
|
+
super(fileSystem, logger);
|
|
905
|
+
this.logger = logger;
|
|
906
|
+
this.fileSystem = fileSystem;
|
|
907
|
+
this.name = "feature";
|
|
908
|
+
this.description = "Generates a feature directory containing a Wasp configuration file";
|
|
909
|
+
}
|
|
910
|
+
name;
|
|
911
|
+
description;
|
|
912
|
+
schema = schema;
|
|
913
|
+
getDefaultTemplatePath(templateName) {
|
|
914
|
+
return this.templateUtility.resolveTemplatePath(
|
|
915
|
+
templateName,
|
|
916
|
+
this.name,
|
|
917
|
+
import.meta.url
|
|
918
|
+
);
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Generates a feature directory containing a Wasp configuration file
|
|
922
|
+
* @param target - The target path of the generated directory
|
|
923
|
+
*/
|
|
924
|
+
async generate(args) {
|
|
925
|
+
const { target } = args;
|
|
926
|
+
const segments = validateFeaturePath2(target);
|
|
927
|
+
const normalisedPath = normaliseFeaturePath(target);
|
|
928
|
+
const sourceRoot = path6.join(findWaspRoot(this.fileSystem), "src");
|
|
929
|
+
if (segments.length > 1) {
|
|
930
|
+
const parentPath = segments.slice(0, -1).join("/");
|
|
931
|
+
const parentNormalisedPath = normaliseFeaturePath(parentPath);
|
|
932
|
+
const parentFeatureDir = path6.join(sourceRoot, parentNormalisedPath);
|
|
933
|
+
if (!this.fileSystem.existsSync(parentFeatureDir)) {
|
|
934
|
+
handleFatalError2(
|
|
935
|
+
`Parent feature '${parentPath}' does not exist. Please create it first.`
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
const featureDir = path6.join(sourceRoot, normalisedPath);
|
|
940
|
+
this.fileSystem.mkdirSync(featureDir, { recursive: true });
|
|
941
|
+
this.configGenerator.generate(normalisedPath);
|
|
942
|
+
this.logger.success(`Generated feature: ${normalisedPath}`);
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
// src/generators/base/component-generator.base.ts
|
|
947
|
+
var ComponentGeneratorBase = class extends WaspGeneratorBase {
|
|
948
|
+
constructor(logger = singletonLogger4, fileSystem = realFileSystem, featureDirectoryGenerator = new FeatureGenerator(logger, fileSystem)) {
|
|
949
|
+
super(fileSystem, logger);
|
|
950
|
+
this.logger = logger;
|
|
951
|
+
this.fileSystem = fileSystem;
|
|
952
|
+
this.featureDirectoryGenerator = featureDirectoryGenerator;
|
|
953
|
+
this.featureDirectoryGenerator = featureDirectoryGenerator;
|
|
954
|
+
}
|
|
955
|
+
getDefaultTemplatePath(templateName) {
|
|
956
|
+
return this.templateUtility.resolveTemplatePath(
|
|
957
|
+
templateName,
|
|
958
|
+
this.name,
|
|
959
|
+
import.meta.url
|
|
960
|
+
);
|
|
961
|
+
}
|
|
962
|
+
get name() {
|
|
963
|
+
return toKebabCase2(this.componentType);
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* Validates that the feature config file exists in the target or ancestor directories
|
|
967
|
+
*/
|
|
968
|
+
validateFeatureConfig(featurePath) {
|
|
969
|
+
const normalisedPath = normaliseFeaturePath(featurePath);
|
|
970
|
+
const segments = normalisedPath.split("/");
|
|
971
|
+
for (let i = segments.length; i > 0; i--) {
|
|
972
|
+
const pathSegments = segments.slice(0, i);
|
|
973
|
+
const currentPath = pathSegments.join("/");
|
|
974
|
+
const featureName = pathSegments[pathSegments.length - 1];
|
|
975
|
+
const featureDir = getFeatureDir(this.fileSystem, currentPath);
|
|
976
|
+
const configPath = path7.join(featureDir, `feature.wasp.ts`);
|
|
977
|
+
if (this.fileSystem.existsSync(configPath)) {
|
|
978
|
+
return configPath;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
this.logger.error(
|
|
982
|
+
`Feature config file not found in '${normalisedPath}' or any ancestor directories`
|
|
983
|
+
);
|
|
984
|
+
this.logger.error(
|
|
985
|
+
`Expected to find a feature.wasp.ts config file in one of the feature directories`
|
|
986
|
+
);
|
|
987
|
+
throw new Error("Feature config file not found");
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Checks if a config item already exists in the feature config
|
|
991
|
+
*/
|
|
992
|
+
checkConfigExists(configPath, methodName, itemName, force) {
|
|
993
|
+
const configContent = this.fileSystem.readFileSync(configPath, "utf8");
|
|
994
|
+
const configExists = hasHelperMethodCall(
|
|
995
|
+
configContent,
|
|
996
|
+
methodName,
|
|
997
|
+
itemName
|
|
998
|
+
);
|
|
999
|
+
return this.checkExistence(
|
|
1000
|
+
configExists,
|
|
1001
|
+
`${methodName} config already exists in ${configPath}`,
|
|
1002
|
+
force,
|
|
1003
|
+
`${methodName} config already exists`
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Updates the feature config with a new definition
|
|
1008
|
+
*/
|
|
1009
|
+
updateFeatureConfig(featurePath, definition, configPath, configExists, methodName) {
|
|
1010
|
+
this.configGenerator.update(featurePath, definition);
|
|
1011
|
+
this.logger.success(
|
|
1012
|
+
`${configExists ? "Updated" : "Added"} ${methodName} config in: ${configPath}`
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Consolidated helper for updating config files with existence check
|
|
1017
|
+
* This replaces the duplicated updateConfigFile pattern in concrete generators
|
|
1018
|
+
*/
|
|
1019
|
+
updateConfigWithCheck(configPath, methodName, entityName, definition, featurePath, force) {
|
|
1020
|
+
const configExists = this.checkConfigExists(
|
|
1021
|
+
configPath,
|
|
1022
|
+
methodName,
|
|
1023
|
+
entityName,
|
|
1024
|
+
force
|
|
1025
|
+
);
|
|
1026
|
+
if (!configExists || force) {
|
|
1027
|
+
this.updateFeatureConfig(
|
|
1028
|
+
featurePath,
|
|
1029
|
+
definition,
|
|
1030
|
+
configPath,
|
|
1031
|
+
configExists,
|
|
1032
|
+
methodName
|
|
1033
|
+
);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Gets the appropriate directory for a feature based on its path.
|
|
1038
|
+
* @param fileSystem - The filesystem abstraction
|
|
1039
|
+
* @param featurePath - The full feature path
|
|
1040
|
+
* @param type - The type of file being generated
|
|
1041
|
+
* @returns The target directory and import path
|
|
1042
|
+
*/
|
|
1043
|
+
getFeatureTargetDir(fileSystem, featurePath, type) {
|
|
1044
|
+
validateFeaturePath3(featurePath);
|
|
1045
|
+
const normalisedPath = normaliseFeaturePath(featurePath);
|
|
1046
|
+
const featureDir = getFeatureDir(fileSystem, normalisedPath);
|
|
1047
|
+
const typeKey = type.toLowerCase();
|
|
1048
|
+
const typeDirectory = TYPE_DIRECTORIES[typeKey];
|
|
1049
|
+
const targetDirectory = path7.join(featureDir, typeDirectory);
|
|
1050
|
+
const importDirectory = `@src/${normalisedPath}/${typeDirectory}`;
|
|
1051
|
+
return { targetDirectory, importDirectory };
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Ensures a target directory exists and returns its path
|
|
1055
|
+
*/
|
|
1056
|
+
ensureTargetDirectory(featurePath, type) {
|
|
1057
|
+
const { targetDirectory, importDirectory } = this.getFeatureTargetDir(
|
|
1058
|
+
this.fileSystem,
|
|
1059
|
+
featurePath,
|
|
1060
|
+
type
|
|
1061
|
+
);
|
|
1062
|
+
ensureDirectoryExists(this.fileSystem, targetDirectory);
|
|
1063
|
+
return { targetDirectory, importDirectory };
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Generate middleware file for API or API namespace
|
|
1067
|
+
*/
|
|
1068
|
+
async generateMiddlewareFile(targetFile, name, force) {
|
|
1069
|
+
const replacements = {
|
|
1070
|
+
name,
|
|
1071
|
+
middlewareType: toCamelCase(this.componentType || "")
|
|
1072
|
+
};
|
|
1073
|
+
await this.renderTemplateToFile(
|
|
1074
|
+
"middleware.eta",
|
|
1075
|
+
replacements,
|
|
1076
|
+
targetFile,
|
|
1077
|
+
"Middleware file",
|
|
1078
|
+
force
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
// src/generators/base/operation-generator.base.ts
|
|
1084
|
+
import {
|
|
1085
|
+
capitalise,
|
|
1086
|
+
getPlural,
|
|
1087
|
+
handleFatalError as handleFatalError3,
|
|
1088
|
+
toPascalCase as toPascalCase2
|
|
1089
|
+
} from "@ingenyus/swarm";
|
|
1090
|
+
var OperationGeneratorBase = class extends ComponentGeneratorBase {
|
|
1091
|
+
/**
|
|
1092
|
+
* Gets the operation name based on operation type and model name.
|
|
1093
|
+
*/
|
|
1094
|
+
getOperationName(operation, modelName, customName) {
|
|
1095
|
+
if (customName) {
|
|
1096
|
+
return customName;
|
|
1097
|
+
}
|
|
1098
|
+
switch (operation) {
|
|
1099
|
+
case OPERATIONS.GETALL:
|
|
1100
|
+
return `getAll${getPlural(modelName)}`;
|
|
1101
|
+
case OPERATIONS.GETFILTERED:
|
|
1102
|
+
return `getFiltered${getPlural(modelName)}`;
|
|
1103
|
+
default:
|
|
1104
|
+
return `${operation}${modelName}`;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Gets the template path for operation templates.
|
|
1109
|
+
* This method resolves operation templates to the operation generator's directory
|
|
1110
|
+
* instead of the current generator's directory.
|
|
1111
|
+
*/
|
|
1112
|
+
getOperationTemplatePath(templateName) {
|
|
1113
|
+
return this.templateUtility.resolveTemplatePath(
|
|
1114
|
+
templateName,
|
|
1115
|
+
"operation",
|
|
1116
|
+
import.meta.url
|
|
1117
|
+
);
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Gets the TypeScript type name for an operation.
|
|
1121
|
+
*/
|
|
1122
|
+
getOperationTypeName(operation, modelName) {
|
|
1123
|
+
return toPascalCase2(this.getOperationName(operation, modelName));
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Generates import statements for an operation.
|
|
1127
|
+
*/
|
|
1128
|
+
generateImports(model, modelName, operation) {
|
|
1129
|
+
const imports = [];
|
|
1130
|
+
if (operation !== OPERATIONS.GETALL) {
|
|
1131
|
+
if (needsPrismaImport(model)) {
|
|
1132
|
+
imports.push('import { Prisma } from "@prisma/client";');
|
|
1133
|
+
}
|
|
1134
|
+
imports.push(`import { ${modelName} } from "wasp/entities";`);
|
|
1135
|
+
}
|
|
1136
|
+
imports.push('import { HttpError } from "wasp/server";');
|
|
1137
|
+
imports.push(
|
|
1138
|
+
`import type { ${this.getOperationTypeName(
|
|
1139
|
+
operation,
|
|
1140
|
+
modelName
|
|
1141
|
+
)} } from "wasp/server/operations";`
|
|
1142
|
+
);
|
|
1143
|
+
return imports.join("\n");
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Gets the operation type ("query" or "action") for a given operation.
|
|
1147
|
+
*/
|
|
1148
|
+
getOperationType(operation) {
|
|
1149
|
+
return operation === OPERATIONS.GETALL || operation === OPERATIONS.GET || operation === OPERATIONS.GETFILTERED ? "query" : "action";
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Generates the operation components needed for file and config generation.
|
|
1153
|
+
*/
|
|
1154
|
+
async generateOperationComponents(modelName, operation, auth = false, entities = [modelName], isCrudOverride = false, crudName = null, customName) {
|
|
1155
|
+
const model = await getEntityMetadata(modelName);
|
|
1156
|
+
const operationType = this.getOperationType(operation);
|
|
1157
|
+
const operationName = this.getOperationName(
|
|
1158
|
+
operation,
|
|
1159
|
+
modelName,
|
|
1160
|
+
customName
|
|
1161
|
+
);
|
|
1162
|
+
const operationCode = await this.generateOperationCode(
|
|
1163
|
+
model,
|
|
1164
|
+
operation,
|
|
1165
|
+
auth,
|
|
1166
|
+
isCrudOverride,
|
|
1167
|
+
crudName
|
|
1168
|
+
);
|
|
1169
|
+
const configEntry = {
|
|
1170
|
+
operationName,
|
|
1171
|
+
entities,
|
|
1172
|
+
authRequired: auth
|
|
1173
|
+
};
|
|
1174
|
+
return {
|
|
1175
|
+
operationCode,
|
|
1176
|
+
configEntry,
|
|
1177
|
+
operationType,
|
|
1178
|
+
operationName
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Generates the code for an operation.
|
|
1183
|
+
*/
|
|
1184
|
+
async generateOperationCode(model, operation, auth = false, isCrudOverride = false, crudName = null) {
|
|
1185
|
+
const operationType = this.getOperationType(operation);
|
|
1186
|
+
const templatePath = this.getOperationTemplatePath(`${operation}.eta`);
|
|
1187
|
+
const allFieldNames = model.fields.map((f) => f.name);
|
|
1188
|
+
const idFields = getIdFields(model);
|
|
1189
|
+
const requiredFields = getRequiredFields(model);
|
|
1190
|
+
const optionalFields = getOptionalFields(model);
|
|
1191
|
+
const jsonFields = getJsonFields(model);
|
|
1192
|
+
const pluralModelName = getPlural(model.name);
|
|
1193
|
+
const pluralModelNameLower = pluralModelName.toLowerCase();
|
|
1194
|
+
const modelNameLower = model.name.toLowerCase();
|
|
1195
|
+
const operationName = this.getOperationName(operation, model.name);
|
|
1196
|
+
const imports = isCrudOverride ? "" : this.generateImports(model, model.name, operation);
|
|
1197
|
+
const jsonTypeHandling = generateJsonTypeHandling(jsonFields);
|
|
1198
|
+
let typeParams = "";
|
|
1199
|
+
switch (operation) {
|
|
1200
|
+
case "create": {
|
|
1201
|
+
const pickRequired = generatePickType(
|
|
1202
|
+
model.name,
|
|
1203
|
+
requiredFields,
|
|
1204
|
+
allFieldNames
|
|
1205
|
+
);
|
|
1206
|
+
const partialOptional = generatePartialType(
|
|
1207
|
+
generatePickType(model.name, optionalFields, allFieldNames)
|
|
1208
|
+
);
|
|
1209
|
+
typeParams = `<${generateIntersectionType(pickRequired, partialOptional)}>`;
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
case "update": {
|
|
1213
|
+
const pickId = generatePickType(model.name, idFields, allFieldNames);
|
|
1214
|
+
const omitId = generateOmitType(model.name, idFields, allFieldNames);
|
|
1215
|
+
const partialRest = generatePartialType(omitId);
|
|
1216
|
+
typeParams = `<${generateIntersectionType(pickId, partialRest)}>`;
|
|
1217
|
+
break;
|
|
1218
|
+
}
|
|
1219
|
+
case "delete":
|
|
1220
|
+
case "get":
|
|
1221
|
+
typeParams = `<${generatePickType(model.name, idFields, allFieldNames)}>`;
|
|
1222
|
+
break;
|
|
1223
|
+
case "getAll":
|
|
1224
|
+
typeParams = `<void>`;
|
|
1225
|
+
break;
|
|
1226
|
+
case "getFiltered":
|
|
1227
|
+
typeParams = `<${generatePartialType(model.name)}>`;
|
|
1228
|
+
break;
|
|
1229
|
+
}
|
|
1230
|
+
const authCheck = auth ? ` if (!context.user) {
|
|
1231
|
+
throw new HttpError(401);
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
` : "";
|
|
1235
|
+
let typeAnnotation = "";
|
|
1236
|
+
let satisfiesType = "";
|
|
1237
|
+
if (isCrudOverride && crudName) {
|
|
1238
|
+
const opCap = capitalise(operation);
|
|
1239
|
+
if (operationType === "action") {
|
|
1240
|
+
typeAnnotation = `: ${crudName}.${opCap}Action${typeParams}`;
|
|
1241
|
+
} else {
|
|
1242
|
+
typeAnnotation = "";
|
|
1243
|
+
}
|
|
1244
|
+
if (operationType === "query") {
|
|
1245
|
+
satisfiesType = `satisfies ${crudName}.${opCap}Query${typeParams}`;
|
|
1246
|
+
} else {
|
|
1247
|
+
satisfiesType = "";
|
|
1248
|
+
}
|
|
1249
|
+
} else {
|
|
1250
|
+
if (operationType === "action") {
|
|
1251
|
+
typeAnnotation = `: ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
|
|
1252
|
+
} else {
|
|
1253
|
+
typeAnnotation = "";
|
|
1254
|
+
}
|
|
1255
|
+
if (operationType === "query") {
|
|
1256
|
+
satisfiesType = `satisfies ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
|
|
1257
|
+
} else {
|
|
1258
|
+
satisfiesType = "";
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
const isCompositeKey = idFields.length > 1;
|
|
1262
|
+
const compositeKeyName = isCompositeKey ? idFields.join("_") : "";
|
|
1263
|
+
const idFieldParams = isCompositeKey ? idFields.join(", ") : idFields[0];
|
|
1264
|
+
const whereClause = isCompositeKey ? `${compositeKeyName}: { ${idFields.map((f) => `${f}`).join(", ")} }` : idFields[0];
|
|
1265
|
+
const replacements = {
|
|
1266
|
+
operationName,
|
|
1267
|
+
modelName: model.name,
|
|
1268
|
+
authCheck,
|
|
1269
|
+
imports,
|
|
1270
|
+
idField: idFields[0],
|
|
1271
|
+
idFieldParams,
|
|
1272
|
+
whereClause,
|
|
1273
|
+
isCompositeKey: String(isCompositeKey),
|
|
1274
|
+
compositeKeyName,
|
|
1275
|
+
jsonTypeHandling,
|
|
1276
|
+
typeAnnotation,
|
|
1277
|
+
satisfiesType,
|
|
1278
|
+
modelNameLower,
|
|
1279
|
+
pluralModelNameLower
|
|
1280
|
+
};
|
|
1281
|
+
return this.templateUtility.processTemplate(templatePath, replacements);
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Generates an operation file for a given operation.
|
|
1285
|
+
*/
|
|
1286
|
+
generateOperationFile(operationsDir, operationName, operationCode, force = false) {
|
|
1287
|
+
const operationFile = `${operationsDir}/${operationName}.ts`;
|
|
1288
|
+
const fileExists = this.checkFileExists(
|
|
1289
|
+
operationFile,
|
|
1290
|
+
force,
|
|
1291
|
+
"Operation file"
|
|
1292
|
+
);
|
|
1293
|
+
this.writeFile(operationFile, operationCode, "operation file", fileExists);
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Copies a directory of operation templates to the target feature directory.
|
|
1297
|
+
* @param templateDir - The source template directory
|
|
1298
|
+
* @param targetDir - The target feature directory
|
|
1299
|
+
*/
|
|
1300
|
+
copyOperationTemplates(templateDir, targetDir) {
|
|
1301
|
+
copyDirectory(this.fileSystem, templateDir, targetDir);
|
|
1302
|
+
this.logger.debug(
|
|
1303
|
+
`Copied operation templates from ${templateDir} to ${targetDir}`
|
|
1304
|
+
);
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Generates an operation definition for the feature configuration.
|
|
1308
|
+
*/
|
|
1309
|
+
getDefinition(operationName, featurePath, entities, operationType, importPath, auth = false) {
|
|
1310
|
+
if (!OPERATION_TYPES.includes(operationType)) {
|
|
1311
|
+
handleFatalError3(`Unknown operation type: ${operationType}`);
|
|
1312
|
+
}
|
|
1313
|
+
const directory = TYPE_DIRECTORIES[operationType];
|
|
1314
|
+
const featureDir = getFeatureImportPath(featurePath);
|
|
1315
|
+
const templatePath = this.templateUtility.resolveTemplatePath(
|
|
1316
|
+
"operation.eta",
|
|
1317
|
+
"config",
|
|
1318
|
+
import.meta.url
|
|
1319
|
+
);
|
|
1320
|
+
return this.templateUtility.processTemplate(templatePath, {
|
|
1321
|
+
operationType: capitalise(operationType),
|
|
1322
|
+
operationName,
|
|
1323
|
+
featureDir,
|
|
1324
|
+
directory,
|
|
1325
|
+
entities: entities.map((e) => `"${e}"`).join(", "),
|
|
1326
|
+
importPath,
|
|
1327
|
+
auth: String(auth)
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
};
|
|
1331
|
+
export {
|
|
1332
|
+
ComponentGeneratorBase,
|
|
1333
|
+
OperationGeneratorBase
|
|
1334
|
+
};
|