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