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