@ingenyus/swarm-wasp 0.1.0 → 0.2.1

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