@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,2215 @@
1
+ // src/types/constants.ts
2
+ var PLUGIN_NAME = "wasp";
3
+ var OPERATION_TYPES = ["query", "action"];
4
+ var API_HTTP_METHODS = [
5
+ "ALL",
6
+ "GET",
7
+ "POST",
8
+ "PUT",
9
+ "DELETE"
10
+ ];
11
+ var OPERATIONS = {
12
+ CREATE: "create",
13
+ UPDATE: "update",
14
+ DELETE: "delete",
15
+ GET: "get",
16
+ GETALL: "getAll",
17
+ GETFILTERED: "getFiltered"
18
+ };
19
+ var CRUD_OPERATIONS = {
20
+ CREATE: "create",
21
+ GET: "get",
22
+ GETALL: "getAll",
23
+ UPDATE: "update",
24
+ DELETE: "delete"
25
+ };
26
+ var ACTION_OPERATIONS = {
27
+ CREATE: "create",
28
+ UPDATE: "update",
29
+ DELETE: "delete"
30
+ };
31
+ var QUERY_OPERATIONS = {
32
+ GET: "get",
33
+ GETALL: "getAll",
34
+ GETFILTERED: "getFiltered"
35
+ };
36
+ var TYPE_DIRECTORIES = {
37
+ component: "client/components",
38
+ hook: "client/hooks",
39
+ layout: "client/layouts",
40
+ page: "client/pages",
41
+ util: "client/utils",
42
+ action: "server/actions",
43
+ query: "server/queries",
44
+ middleware: "server/middleware",
45
+ job: "server/jobs",
46
+ api: "server/apis",
47
+ crud: "server/cruds",
48
+ type: "types"
49
+ };
50
+ var CONFIG_TYPES = {
51
+ ROUTE: "Route",
52
+ QUERY: "Query",
53
+ ACTION: "Action",
54
+ JOB: "Job",
55
+ API: "Api",
56
+ API_NAMESPACE: "ApiNamespace",
57
+ CRUD: "Crud"
58
+ };
59
+
60
+ // src/generators/base/component-generator.base.ts
61
+ import {
62
+ hasHelperMethodCall,
63
+ logger as singletonLogger4,
64
+ toCamelCase,
65
+ toKebabCase as toKebabCase2,
66
+ validateFeaturePath as validateFeaturePath3
67
+ } from "@ingenyus/swarm";
68
+ import path7 from "path";
69
+
70
+ // src/common/filesystem.ts
71
+ import { toPascalCase, validateFeaturePath } from "@ingenyus/swarm";
72
+ import fs from "fs";
73
+ import path from "path";
74
+ var realFileSystem = {
75
+ readFileSync: fs.readFileSync,
76
+ writeFileSync: fs.writeFileSync,
77
+ existsSync: fs.existsSync,
78
+ copyFileSync: fs.copyFileSync,
79
+ mkdirSync: fs.mkdirSync,
80
+ readdirSync: fs.readdirSync,
81
+ statSync: fs.statSync
82
+ };
83
+ function findWaspRoot(fileSystem, startDir = process.cwd()) {
84
+ const startDirPath = path.resolve(startDir);
85
+ let currentDirPath = startDirPath;
86
+ const root = path.parse(currentDirPath).root;
87
+ while (currentDirPath !== root) {
88
+ const waspRootPath = path.join(currentDirPath, ".wasproot");
89
+ if (fileSystem.existsSync(waspRootPath)) {
90
+ return currentDirPath;
91
+ }
92
+ currentDirPath = path.dirname(currentDirPath);
93
+ }
94
+ throw new Error(
95
+ `Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
96
+ );
97
+ }
98
+ function copyDirectory(fileSystem, src, dest) {
99
+ if (!fileSystem.existsSync(dest)) {
100
+ fileSystem.mkdirSync(dest, { recursive: true });
101
+ }
102
+ const entries = fileSystem.readdirSync(src, { withFileTypes: true });
103
+ for (const entry of entries) {
104
+ const srcPath = path.join(src, entry.name);
105
+ const destPath = path.join(dest, entry.name);
106
+ if (entry.isDirectory()) {
107
+ copyDirectory(fileSystem, srcPath, destPath);
108
+ } else {
109
+ fileSystem.copyFileSync(srcPath, destPath);
110
+ }
111
+ }
112
+ }
113
+ function ensureDirectoryExists(fileSystem, dir) {
114
+ if (!fileSystem.existsSync(dir)) {
115
+ fileSystem.mkdirSync(dir, { recursive: true });
116
+ }
117
+ }
118
+ function normaliseFeaturePath(featurePath) {
119
+ const segments = validateFeaturePath(featurePath);
120
+ const normalisedSegments = [];
121
+ for (let i = 0; i < segments.length; i++) {
122
+ const segment = segments[i];
123
+ const previousSegment = normalisedSegments[normalisedSegments.length - 1];
124
+ if (previousSegment !== "features" && segment !== "features") {
125
+ normalisedSegments.push("features");
126
+ }
127
+ normalisedSegments.push(segment);
128
+ }
129
+ return normalisedSegments.join("/");
130
+ }
131
+ function getFeatureDir(fileSystem, featureName) {
132
+ const waspRoot = findWaspRoot(fileSystem);
133
+ const normalisedPath = normaliseFeaturePath(featureName);
134
+ return path.join(waspRoot, "src", normalisedPath);
135
+ }
136
+ function getFeatureImportPath(featurePath) {
137
+ const segments = validateFeaturePath(featurePath);
138
+ return segments.join("/");
139
+ }
140
+ function getRouteNameFromPath(routePath) {
141
+ const lastSegment = routePath.split("/").filter(Boolean).pop() || "index";
142
+ const cleanSegment = lastSegment.replace(/[:*]/g, "");
143
+ return `${toPascalCase(cleanSegment)}Page`;
144
+ }
145
+
146
+ // src/common/plugin.ts
147
+ import path2 from "path";
148
+ import { fileURLToPath } from "url";
149
+
150
+ // src/common/prisma.ts
151
+ import {
152
+ getSchema
153
+ } from "@mrleebo/prisma-ast";
154
+ import fs2 from "fs";
155
+ import path3 from "path";
156
+ async function getEntityMetadata(modelName) {
157
+ try {
158
+ const schemaPath = path3.join(process.cwd(), "schema.prisma");
159
+ const schemaContent = fs2.readFileSync(schemaPath, "utf8");
160
+ const schema9 = getSchema(schemaContent);
161
+ const model = schema9.list?.find(
162
+ (m) => m.type === "model" && m.name === modelName
163
+ );
164
+ if (!model || model.type !== "model") {
165
+ throw new Error(`Model ${modelName} not found in schema`);
166
+ }
167
+ const compositeIdAttr = (model.properties || []).find(
168
+ (item) => item.type === "attribute" && item.kind === "object" && item.name === "id"
169
+ );
170
+ let compositeIdFields = [];
171
+ if (compositeIdAttr?.args?.[0]) {
172
+ const arg = compositeIdAttr.args[0];
173
+ if (typeof arg.value === "object" && arg.value !== null && "type" in arg.value && arg.value.type === "array" && "args" in arg.value) {
174
+ compositeIdFields = arg.value.args;
175
+ }
176
+ }
177
+ const fields = (model.properties || []).filter(
178
+ (item) => item.type === "field" && !item.array && !item.attributes?.some((attr) => attr.name === "relation")
179
+ ).map((field) => {
180
+ const fieldType = typeof field.fieldType === "string" ? field.fieldType : field.fieldType.name;
181
+ const tsType = getPrismaToTsType(fieldType);
182
+ const isRequired = !field.optional;
183
+ const isId = field.attributes?.some((attr) => attr.name === "id") || compositeIdFields.includes(field.name);
184
+ const isUnique = field.attributes?.some((attr) => attr.name === "unique") || false;
185
+ const hasDefaultValue = field.attributes?.some((attr) => attr.name === "default") || false;
186
+ const isUpdatedAt = field.attributes?.some((attr) => attr.name === "updatedAt") || false;
187
+ const isGenerated = field.attributes?.some((attr) => attr.name === "map") || false;
188
+ return {
189
+ name: field.name,
190
+ type: fieldType,
191
+ tsType,
192
+ isRequired,
193
+ isId,
194
+ isUnique,
195
+ hasDefaultValue,
196
+ isGenerated,
197
+ isUpdatedAt
198
+ };
199
+ });
200
+ return {
201
+ name: modelName,
202
+ fields
203
+ };
204
+ } catch (error) {
205
+ throw new Error(
206
+ `Failed to get entity metadata for ${modelName}: ${error instanceof Error ? error.message : String(error)}`
207
+ );
208
+ }
209
+ }
210
+ function getIdFields(model) {
211
+ const idFields = model.fields.filter((f) => f.isId).map((f) => f.name);
212
+ if (idFields.length === 0) {
213
+ throw new Error(`No ID field found for model ${model.name}`);
214
+ }
215
+ return idFields;
216
+ }
217
+ function getRequiredFields(model) {
218
+ return model.fields.filter(
219
+ (f) => f.isRequired && !f.hasDefaultValue && !f.isGenerated && !f.isUpdatedAt
220
+ ).map((f) => f.name);
221
+ }
222
+ function getOptionalFields(model) {
223
+ return model.fields.filter(
224
+ (field) => (field.hasDefaultValue && field.type !== "DateTime" || !field.isRequired) && !field.isId && !field.isGenerated && !field.isUpdatedAt
225
+ ).map((field) => field.name);
226
+ }
227
+ function getJsonFields(model) {
228
+ return model.fields.filter((f) => f.type === "Json").map((f) => f.name);
229
+ }
230
+ function generateJsonTypeHandling(jsonFields) {
231
+ if (jsonFields.length === 0) return "";
232
+ const assignments = jsonFields.map(
233
+ (field) => ` ${field}: (data.${field} as Prisma.JsonValue) || Prisma.JsonNull`
234
+ ).join(",\n");
235
+ return `,
236
+ ${assignments}`;
237
+ }
238
+ function needsPrismaImport(model) {
239
+ return model.fields.some((f) => f.type === "Json" || f.type === "Decimal");
240
+ }
241
+ function generatePickType(modelName, fields, allFields) {
242
+ if (fields.length === 0) return "";
243
+ if (fields.length === allFields.length) return modelName;
244
+ const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
245
+ return `Pick<${modelName}, ${fieldUnion}>`;
246
+ }
247
+ function generateOmitType(modelName, fields, allFields) {
248
+ if (fields.length === 0) return modelName;
249
+ if (fields.length === allFields.length) return "";
250
+ const fieldUnion = fields.map((f) => `"${f}"`).join(" | ");
251
+ return `Omit<${modelName}, ${fieldUnion}>`;
252
+ }
253
+ function generatePartialType(typeString) {
254
+ if (!typeString) return "";
255
+ return `Partial<${typeString}>`;
256
+ }
257
+ function generateIntersectionType(type1, type2) {
258
+ if (!type1 && !type2) return "";
259
+ if (!type1) return type2;
260
+ if (!type2) return type1;
261
+ return `${type1} & ${type2}`;
262
+ }
263
+ function getPrismaToTsType(type) {
264
+ const typeMap = {
265
+ String: "string",
266
+ Int: "number",
267
+ Float: "number",
268
+ Boolean: "boolean",
269
+ DateTime: "Date",
270
+ Json: "Prisma.JsonValue",
271
+ BigInt: "bigint",
272
+ Decimal: "Prisma.Decimal",
273
+ Bytes: "Buffer"
274
+ };
275
+ return typeMap[type] || type;
276
+ }
277
+
278
+ // src/common/schemas.ts
279
+ import { commandRegistry } from "@ingenyus/swarm";
280
+ import { z } from "zod";
281
+ var commonSchemas = {
282
+ feature: z.string().min(1, "Feature is required").meta({
283
+ description: "The feature directory this component will be generated in"
284
+ }).register(commandRegistry, {
285
+ shortName: "f",
286
+ examples: ["root", "auth", "dashboard/users"],
287
+ helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
288
+ }),
289
+ name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
290
+ shortName: "n",
291
+ examples: ["users", "task"],
292
+ helpText: "Will be used for generated files and configuration entries"
293
+ }),
294
+ target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
295
+ shortName: "t",
296
+ examples: ["dashboard/users", "features/dashboard/features/users"],
297
+ helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
298
+ }),
299
+ path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
300
+ shortName: "p",
301
+ examples: ["/api/users/:id", "/api/products"],
302
+ helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
303
+ }),
304
+ dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
305
+ shortName: "d",
306
+ examples: ["User", "Product", "Task"],
307
+ helpText: "The Wasp entity or model name this operation will interact with"
308
+ }),
309
+ entities: z.array(z.string()).optional().meta({
310
+ description: "The Wasp entities that will be available to this component (optional)"
311
+ }).register(commandRegistry, {
312
+ shortName: "e",
313
+ examples: ["User", "User Task"],
314
+ helpText: "An array of Wasp entity names"
315
+ }),
316
+ force: z.boolean().optional().meta({
317
+ description: "Force overwrite of existing files and configuration entries (optional)"
318
+ }).register(commandRegistry, {
319
+ shortName: "F",
320
+ helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
321
+ }),
322
+ auth: z.boolean().optional().meta({
323
+ description: "Require authentication for this component (optional)"
324
+ }).register(commandRegistry, {
325
+ shortName: "a",
326
+ helpText: "Will generate authentication checks"
327
+ })
328
+ };
329
+
330
+ // src/common/templates.ts
331
+ import { toKebabCase } from "@ingenyus/swarm";
332
+ import { Eta } from "eta";
333
+ import path4 from "path";
334
+ var TemplateUtility = class {
335
+ constructor(fileSystem) {
336
+ this.fileSystem = fileSystem;
337
+ }
338
+ processTemplate(templatePath, replacements) {
339
+ const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
340
+ const functionHeader = declarations ? `const ${declarations};` : void 0;
341
+ const templateDir = path4.dirname(templatePath);
342
+ const eta = new Eta({
343
+ autoTrim: false,
344
+ autoEscape: false,
345
+ views: templateDir,
346
+ functionHeader
347
+ });
348
+ const templateName = path4.basename(templatePath).replace(/\.eta$/, "");
349
+ if (this.fileSystem.existsSync(templatePath)) {
350
+ return eta.render(templateName, replacements);
351
+ } else {
352
+ const template = this.fileSystem.readFileSync(templatePath, "utf8");
353
+ return eta.renderString(template, replacements);
354
+ }
355
+ }
356
+ /**
357
+ * Helper method to resolve template paths for concrete generators
358
+ * @param relativePath - The relative path to the template file
359
+ * @param generatorName - The name of the generator (e.g., 'api', 'job')
360
+ * @param currentFileUrl - The import.meta.url from the concrete generator class
361
+ * @returns The full path to the template file
362
+ */
363
+ resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
364
+ const generatorDirName = toKebabCase(generatorName);
365
+ const currentFilePath = new URL(currentFileUrl).pathname;
366
+ const currentFileDir = path4.dirname(currentFilePath);
367
+ const currentFileName = path4.basename(currentFilePath);
368
+ const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
369
+ const startDir = isInstalledPackage ? currentFileDir : path4.dirname(path4.dirname(currentFileDir));
370
+ return path4.join(
371
+ startDir,
372
+ "generators",
373
+ generatorDirName,
374
+ "templates",
375
+ relativePath
376
+ );
377
+ }
378
+ };
379
+
380
+ // src/generators/feature/feature-generator.ts
381
+ import {
382
+ handleFatalError as handleFatalError2,
383
+ logger as singletonLogger3,
384
+ validateFeaturePath as validateFeaturePath2
385
+ } from "@ingenyus/swarm";
386
+ import path6 from "path";
387
+
388
+ // src/generators/base/wasp-generator.base.ts
389
+ import {
390
+ GeneratorBase,
391
+ logger as singletonLogger2,
392
+ SwarmConfigManager,
393
+ TemplateResolver
394
+ } from "@ingenyus/swarm";
395
+
396
+ // src/generators/config/wasp-config-generator.ts
397
+ import {
398
+ handleFatalError,
399
+ parseHelperMethodDefinition,
400
+ logger as singletonLogger
401
+ } from "@ingenyus/swarm";
402
+ import path5 from "path";
403
+ var WaspConfigGenerator = class {
404
+ constructor(logger = singletonLogger, fileSystem = realFileSystem) {
405
+ this.logger = logger;
406
+ this.fileSystem = fileSystem;
407
+ this.templateUtility = new TemplateUtility(fileSystem);
408
+ }
409
+ path = path5;
410
+ templateUtility;
411
+ /**
412
+ * Gets the template path for feature config templates.
413
+ * Feature config templates are located in the feature generator's templates directory.
414
+ * @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
415
+ * @returns The full path to the template file
416
+ */
417
+ getTemplatePath(templateName) {
418
+ return this.templateUtility.resolveTemplatePath(
419
+ templateName,
420
+ "feature",
421
+ import.meta.url
422
+ );
423
+ }
424
+ /**
425
+ * Generate a TypeScript Wasp config file in a feature directory
426
+ * @param featurePath - The feature directory path
427
+ */
428
+ generate(featurePath) {
429
+ const featureDir = getFeatureDir(this.fileSystem, featurePath);
430
+ if (!this.fileSystem.existsSync(featureDir)) {
431
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
432
+ }
433
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
434
+ if (!this.fileSystem.existsSync(templatePath)) {
435
+ this.logger.error(`Template not found: ${templatePath}`);
436
+ return;
437
+ }
438
+ const configFilePath = path5.join(featureDir, `feature.wasp.ts`);
439
+ if (this.fileSystem.existsSync(configFilePath)) {
440
+ this.logger.warn(`Feature config already exists: ${configFilePath}`);
441
+ return;
442
+ }
443
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
444
+ this.logger.success(`Generated feature config: ${configFilePath}`);
445
+ }
446
+ /**
447
+ * Updates or creates a feature configuration file with a pre-built declaration.
448
+ * @param featurePath - The path to the feature
449
+ * @param declaration - The pre-built declaration string to add or update
450
+ * @returns The updated feature configuration file
451
+ */
452
+ update(featurePath, declaration) {
453
+ const configDir = getFeatureDir(this.fileSystem, featurePath);
454
+ const configFilePath = path5.join(configDir, `feature.wasp.ts`);
455
+ if (!this.fileSystem.existsSync(configFilePath)) {
456
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
457
+ if (!this.fileSystem.existsSync(templatePath)) {
458
+ handleFatalError(`Feature config template not found: ${templatePath}`);
459
+ }
460
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
461
+ }
462
+ let content = this.fileSystem.readFileSync(configFilePath, "utf8");
463
+ content = this.normaliseSemicolons(content);
464
+ const parsed = parseHelperMethodDefinition(declaration);
465
+ if (!parsed) {
466
+ handleFatalError(`Could not parse definition: ${declaration}`);
467
+ return content;
468
+ }
469
+ const { methodName } = parsed;
470
+ const hadExistingDefinitions = this.hasExistingDefinitions(
471
+ content,
472
+ methodName
473
+ );
474
+ content = this.removeExistingDefinition(content, declaration);
475
+ const hasExistingDefinitions = this.hasExistingDefinitions(
476
+ content,
477
+ methodName
478
+ );
479
+ const lines = content.split("\n");
480
+ const configureFunctionStart = lines.findIndex(
481
+ (line) => line.trim().startsWith("export default function")
482
+ );
483
+ if (configureFunctionStart === -1) {
484
+ handleFatalError("Could not find configure function in feature config");
485
+ }
486
+ const appLineIndex = lines.findIndex(
487
+ (line, index) => index > configureFunctionStart && line.trim() === "app"
488
+ );
489
+ if (appLineIndex === -1) {
490
+ const insertIndex = configureFunctionStart + 1;
491
+ const itemsToInsert = [" app"];
492
+ const comment = this.getMethodComment(methodName);
493
+ itemsToInsert.push(` ${comment}`);
494
+ itemsToInsert.push(declaration.trimEnd());
495
+ lines.splice(insertIndex, 0, ...itemsToInsert);
496
+ } else {
497
+ const { insertIndex, addComment } = this.findGroupInsertionPoint(
498
+ lines,
499
+ methodName,
500
+ declaration,
501
+ hadExistingDefinitions || hasExistingDefinitions
502
+ );
503
+ const newLines = this.insertWithSpacing(
504
+ lines,
505
+ declaration,
506
+ insertIndex,
507
+ methodName,
508
+ addComment
509
+ );
510
+ const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
511
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
512
+ return configFilePath;
513
+ }
514
+ const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
515
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent);
516
+ return configFilePath;
517
+ }
518
+ /**
519
+ * Determines the insertion index for a method name based on alphabetical ordering
520
+ * of existing groups in the configuration file.
521
+ * @param groups - Object containing existing method groups
522
+ * @param methodName - The method name to find insertion index for
523
+ * @returns The insertion index for the method name
524
+ */
525
+ getInsertionIndexForMethod(groups, methodName) {
526
+ const existingMethods = Object.keys(groups).filter(
527
+ (method) => groups[method].length > 0
528
+ );
529
+ const allMethods = [...existingMethods, methodName].sort();
530
+ return allMethods.indexOf(methodName);
531
+ }
532
+ /**
533
+ * Gets the comment text for a method type.
534
+ * @param methodName The method name (e.g., 'addApi')
535
+ * @returns The comment text for the method type
536
+ */
537
+ getMethodComment(methodName) {
538
+ const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
539
+ return `// ${entityName} definitions`;
540
+ }
541
+ /**
542
+ * Finds the correct insertion point for a new configuration item.
543
+ * @param lines - Array of file lines
544
+ * @param methodName - The method name (e.g., 'addApi')
545
+ * @param definition - The definition string to parse for item name
546
+ * @returns Object with insertion index and whether to add a comment
547
+ */
548
+ findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
549
+ const appLineIndex = lines.findIndex((line) => line.trim() === "app");
550
+ if (appLineIndex === -1) {
551
+ return { insertIndex: appLineIndex + 1, addComment: false };
552
+ }
553
+ const methodCalls = [];
554
+ for (let i = appLineIndex + 1; i < lines.length; i++) {
555
+ const line = lines[i].trim();
556
+ if (line.startsWith(".") && line.includes("(")) {
557
+ let methodCallContent = line;
558
+ let j = i;
559
+ let closingParenCount = 0;
560
+ let foundClosingParen = false;
561
+ for (let k = 0; k < methodCallContent.length; k++) {
562
+ if (methodCallContent[k] === "(") closingParenCount++;
563
+ if (methodCallContent[k] === ")") closingParenCount--;
564
+ if (closingParenCount === 0 && methodCallContent[k] === ")") {
565
+ foundClosingParen = true;
566
+ break;
567
+ }
568
+ }
569
+ while (!foundClosingParen && j < lines.length - 1) {
570
+ j++;
571
+ methodCallContent += " " + lines[j].trim();
572
+ for (let k = 0; k < lines[j].length; k++) {
573
+ if (lines[j][k] === "(") closingParenCount++;
574
+ if (lines[j][k] === ")") closingParenCount--;
575
+ if (closingParenCount === 0 && lines[j][k] === ")") {
576
+ foundClosingParen = true;
577
+ break;
578
+ }
579
+ }
580
+ }
581
+ const match = methodCallContent.match(
582
+ /\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
583
+ );
584
+ if (match) {
585
+ methodCalls.push({
586
+ lineIndex: i,
587
+ endLineIndex: j,
588
+ methodName: match[1],
589
+ itemName: match[2]
590
+ });
591
+ }
592
+ }
593
+ }
594
+ const groups = {};
595
+ methodCalls.forEach((call) => {
596
+ if (!groups[call.methodName]) {
597
+ groups[call.methodName] = [];
598
+ }
599
+ groups[call.methodName].push({
600
+ lineIndex: call.lineIndex,
601
+ endLineIndex: call.endLineIndex,
602
+ itemName: call.itemName
603
+ });
604
+ });
605
+ const targetGroup = groups[methodName] || [];
606
+ if (targetGroup.length === 0) {
607
+ const targetGroupIndex = this.getInsertionIndexForMethod(
608
+ groups,
609
+ methodName
610
+ );
611
+ const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
612
+ for (let i = targetGroupIndex; i < existingMethods.length; i++) {
613
+ const groupMethod = existingMethods[i];
614
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
615
+ const firstItem = groups[groupMethod][0];
616
+ let insertIndex = firstItem.lineIndex;
617
+ for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
618
+ const line = lines[j].trim();
619
+ if (line.startsWith("//") && line.includes("definitions")) {
620
+ insertIndex = j;
621
+ break;
622
+ } else if (line.startsWith(".") || line === "") {
623
+ continue;
624
+ } else {
625
+ break;
626
+ }
627
+ }
628
+ return { insertIndex, addComment: !hasExistingDefinitionsOfType };
629
+ }
630
+ }
631
+ for (let i = targetGroupIndex - 1; i >= 0; i--) {
632
+ const groupMethod = existingMethods[i];
633
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
634
+ const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
635
+ return {
636
+ insertIndex: lastItem2.endLineIndex + 1,
637
+ addComment: !hasExistingDefinitionsOfType
638
+ };
639
+ }
640
+ }
641
+ return {
642
+ insertIndex: appLineIndex + 1,
643
+ addComment: !hasExistingDefinitionsOfType
644
+ };
645
+ }
646
+ const parsed = parseHelperMethodDefinition(definition);
647
+ if (!parsed) {
648
+ return { insertIndex: appLineIndex + 1, addComment: false };
649
+ }
650
+ const { firstParam: itemName } = parsed;
651
+ for (let i = 0; i < targetGroup.length; i++) {
652
+ if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
653
+ return { insertIndex: targetGroup[i].lineIndex, addComment: false };
654
+ }
655
+ }
656
+ const lastItem = targetGroup[targetGroup.length - 1];
657
+ return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
658
+ }
659
+ /**
660
+ * Inserts a definition with optional comment header.
661
+ * @param lines - Array of file lines
662
+ * @param declaration - The declaration to insert
663
+ * @param insertIndex - The index where to insert
664
+ * @param methodName - The method name for comment generation
665
+ * @param addComment - Whether to add a comment before the declaration
666
+ * @returns The modified lines array
667
+ */
668
+ insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
669
+ const newLines = [...lines];
670
+ if (addComment) {
671
+ const comment = this.getMethodComment(methodName);
672
+ newLines.splice(insertIndex, 0, ` ${comment}`);
673
+ insertIndex += 1;
674
+ }
675
+ newLines.splice(insertIndex, 0, declaration.trimEnd());
676
+ return newLines;
677
+ }
678
+ /**
679
+ * Checks if there are any existing definitions of a specific type in the content.
680
+ * @param content - The file content to search
681
+ * @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
682
+ * @returns true if there are existing definitions of this type, false otherwise
683
+ */
684
+ hasExistingDefinitions(content, methodName) {
685
+ const lines = content.split("\n");
686
+ for (const line of lines) {
687
+ if (line.trim().startsWith(`.${methodName}(`)) {
688
+ return true;
689
+ }
690
+ }
691
+ return false;
692
+ }
693
+ /**
694
+ * Removes an existing definition from the content by finding the helper method call
695
+ * and removing the entire method call block.
696
+ * @param content - The file content
697
+ * @param definition - The new definition to find the existing one from
698
+ * @returns The content with the existing definition removed
699
+ */
700
+ removeExistingDefinition(content, definition) {
701
+ const parsed = parseHelperMethodDefinition(definition);
702
+ if (!parsed) {
703
+ return content;
704
+ }
705
+ const { methodName, firstParam } = parsed;
706
+ let contentLines = content.split("\n");
707
+ let openingLineIndex = -1;
708
+ for (let i = 0; i < contentLines.length; i++) {
709
+ const line = contentLines[i];
710
+ if (line.trim().startsWith(`.${methodName}(`)) {
711
+ if (firstParam && line.includes(firstParam)) {
712
+ openingLineIndex = i;
713
+ break;
714
+ }
715
+ }
716
+ }
717
+ if (openingLineIndex === -1) {
718
+ return content;
719
+ }
720
+ let closingLineIndex = -1;
721
+ let parenCount = 0;
722
+ let braceCount = 0;
723
+ let foundOpening = false;
724
+ for (let i = openingLineIndex; i < contentLines.length; i++) {
725
+ const line = contentLines[i];
726
+ for (const char of line) {
727
+ if (char === "(") {
728
+ parenCount++;
729
+ foundOpening = true;
730
+ } else if (char === ")") {
731
+ parenCount--;
732
+ if (foundOpening && parenCount === 0 && braceCount === 0) {
733
+ closingLineIndex = i;
734
+ break;
735
+ }
736
+ } else if (char === "{") {
737
+ braceCount++;
738
+ } else if (char === "}") {
739
+ braceCount--;
740
+ }
741
+ }
742
+ if (closingLineIndex !== -1) {
743
+ break;
744
+ }
745
+ }
746
+ if (closingLineIndex === -1) {
747
+ this.logger.warn(
748
+ "Could not find closing parenthesis for existing definition"
749
+ );
750
+ return content;
751
+ }
752
+ contentLines.splice(
753
+ openingLineIndex,
754
+ closingLineIndex - openingLineIndex + 1
755
+ );
756
+ return contentLines.join("\n");
757
+ }
758
+ /**
759
+ * Adds a definition to the content by finding the appropriate place to insert it.
760
+ * @param content - The current file content
761
+ * @param definition - The definition to add
762
+ * @returns The updated content with the new definition
763
+ */
764
+ addDefinitionToContent(content, definition) {
765
+ const lines = content.split("\n");
766
+ const lastLineIndex = lines.length - 1;
767
+ let insertIndex = lastLineIndex;
768
+ for (let i = lastLineIndex; i >= 0; i--) {
769
+ const line = lines[i].trim();
770
+ if (line && !line.startsWith("}")) {
771
+ insertIndex = i;
772
+ break;
773
+ }
774
+ }
775
+ lines.splice(insertIndex + 1, 0, ` ${definition}`);
776
+ return lines.join("\n");
777
+ }
778
+ /**
779
+ * Normalises semicolons in the config file by removing them from method chain calls
780
+ * while preserving them in other contexts (imports, declarations, etc.).
781
+ * @param content - The file content to normalise
782
+ * @returns The normalised content
783
+ */
784
+ normaliseSemicolons(content) {
785
+ const lines = content.split("\n");
786
+ const configureFunctionStart = lines.findIndex(
787
+ (line) => line.trim().startsWith("export default function")
788
+ );
789
+ if (configureFunctionStart === -1) {
790
+ return content;
791
+ }
792
+ const appLineIndex = lines.findIndex(
793
+ (line, index) => index > configureFunctionStart && line.trim().startsWith("app")
794
+ );
795
+ if (appLineIndex === -1) {
796
+ return content;
797
+ }
798
+ let braceCount = 0;
799
+ let functionEndIndex = lines.length - 1;
800
+ for (let i = configureFunctionStart; i < lines.length; i++) {
801
+ const line = lines[i];
802
+ for (const char of line) {
803
+ if (char === "{") braceCount++;
804
+ if (char === "}") {
805
+ braceCount--;
806
+ if (braceCount === 0) {
807
+ functionEndIndex = i;
808
+ break;
809
+ }
810
+ }
811
+ }
812
+ if (braceCount === 0 && i > configureFunctionStart) {
813
+ break;
814
+ }
815
+ }
816
+ let lastMethodCallIndex = -1;
817
+ for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
818
+ const line = lines[i];
819
+ const trimmed = line.trim();
820
+ if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
821
+ lines[i] = line.replace(/;\s*$/, "");
822
+ lastMethodCallIndex = i;
823
+ }
824
+ }
825
+ if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
826
+ lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
827
+ }
828
+ return lines.join("\n");
829
+ }
830
+ };
831
+
832
+ // src/generators/base/wasp-generator.base.ts
833
+ var WaspGeneratorBase = class extends GeneratorBase {
834
+ constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
835
+ super(fileSystem, logger);
836
+ this.fileSystem = fileSystem;
837
+ this.logger = logger;
838
+ this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
839
+ this.templateUtility = new TemplateUtility(fileSystem);
840
+ this.templateResolver = new TemplateResolver(fileSystem);
841
+ }
842
+ configGenerator;
843
+ templateUtility;
844
+ templateResolver;
845
+ swarmConfig;
846
+ configLoaded = false;
847
+ // Plugin name from swarm.config.json
848
+ pluginName = PLUGIN_NAME;
849
+ async loadSwarmConfig() {
850
+ if (this.configLoaded) return;
851
+ const configManager = new SwarmConfigManager();
852
+ this.swarmConfig = await configManager.loadConfig();
853
+ this.configLoaded = true;
854
+ }
855
+ async getCustomTemplateDir() {
856
+ await this.loadSwarmConfig();
857
+ return this.swarmConfig?.templateDirectory;
858
+ }
859
+ /**
860
+ * Resolves template path with override support
861
+ */
862
+ async getTemplatePath(templateName) {
863
+ const defaultPath = this.getDefaultTemplatePath(templateName);
864
+ const customPath = await this.getCustomTemplateDir();
865
+ if (!customPath) {
866
+ return defaultPath;
867
+ }
868
+ const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
869
+ this.pluginName,
870
+ this.name,
871
+ templateName,
872
+ defaultPath,
873
+ customPath
874
+ );
875
+ if (isCustom) {
876
+ this.logger.info(`Using custom template: ${resolvedPath}`);
877
+ }
878
+ return resolvedPath;
879
+ }
880
+ /**
881
+ * Processes a template and writes the result to a file
882
+ */
883
+ async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
884
+ const templatePath = await this.getTemplatePath(templateName);
885
+ const fileExists = this.checkFileExists(
886
+ outputPath,
887
+ force,
888
+ readableFileType
889
+ );
890
+ const content = this.templateUtility.processTemplate(
891
+ templatePath,
892
+ replacements
893
+ );
894
+ this.writeFile(outputPath, content, readableFileType, fileExists);
895
+ return fileExists;
896
+ }
897
+ /**
898
+ * Generic existence check with force flag handling
899
+ * Consolidates the pattern used in both file and config checks
900
+ */
901
+ checkExistence(exists, itemDescription, force, errorMessage) {
902
+ if (exists && !force) {
903
+ this.logger.error(`${itemDescription}. Use --force to overwrite`);
904
+ throw new Error(errorMessage || itemDescription);
905
+ }
906
+ return exists;
907
+ }
908
+ /**
909
+ * Checks if a file exists and handles force flag logic
910
+ */
911
+ checkFileExists(filePath, force, fileType) {
912
+ const fileExists = this.fileSystem.existsSync(filePath);
913
+ return this.checkExistence(
914
+ fileExists,
915
+ `${fileType} already exists: ${filePath}`,
916
+ force,
917
+ `${fileType} already exists`
918
+ );
919
+ }
920
+ /**
921
+ * Safely writes a file with proper error handling and logging
922
+ */
923
+ writeFile(filePath, content, fileType, fileExists) {
924
+ this.fileSystem.writeFileSync(filePath, content);
925
+ this.logger.success(
926
+ `${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
927
+ );
928
+ }
929
+ };
930
+
931
+ // src/generators/feature/schema.ts
932
+ import { z as z2 } from "zod";
933
+ var schema = z2.object({
934
+ target: commonSchemas.target
935
+ });
936
+
937
+ // src/generators/feature/feature-generator.ts
938
+ var FeatureGenerator = class extends WaspGeneratorBase {
939
+ constructor(logger = singletonLogger3, fileSystem = realFileSystem) {
940
+ super(fileSystem, logger);
941
+ this.logger = logger;
942
+ this.fileSystem = fileSystem;
943
+ this.name = "feature";
944
+ this.description = "Generates a feature directory containing a Wasp configuration file";
945
+ }
946
+ name;
947
+ description;
948
+ schema = schema;
949
+ getDefaultTemplatePath(templateName) {
950
+ return this.templateUtility.resolveTemplatePath(
951
+ templateName,
952
+ this.name,
953
+ import.meta.url
954
+ );
955
+ }
956
+ /**
957
+ * Generates a feature directory containing a Wasp configuration file
958
+ * @param target - The target path of the generated directory
959
+ */
960
+ async generate(args) {
961
+ const { target } = args;
962
+ const segments = validateFeaturePath2(target);
963
+ const normalisedPath = normaliseFeaturePath(target);
964
+ const sourceRoot = path6.join(findWaspRoot(this.fileSystem), "src");
965
+ if (segments.length > 1) {
966
+ const parentPath = segments.slice(0, -1).join("/");
967
+ const parentNormalisedPath = normaliseFeaturePath(parentPath);
968
+ const parentFeatureDir = path6.join(sourceRoot, parentNormalisedPath);
969
+ if (!this.fileSystem.existsSync(parentFeatureDir)) {
970
+ handleFatalError2(
971
+ `Parent feature '${parentPath}' does not exist. Please create it first.`
972
+ );
973
+ }
974
+ }
975
+ const featureDir = path6.join(sourceRoot, normalisedPath);
976
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
977
+ this.configGenerator.generate(normalisedPath);
978
+ this.logger.success(`Generated feature: ${normalisedPath}`);
979
+ }
980
+ };
981
+
982
+ // src/generators/base/component-generator.base.ts
983
+ var ComponentGeneratorBase = class extends WaspGeneratorBase {
984
+ constructor(logger = singletonLogger4, fileSystem = realFileSystem, featureDirectoryGenerator = new FeatureGenerator(logger, fileSystem)) {
985
+ super(fileSystem, logger);
986
+ this.logger = logger;
987
+ this.fileSystem = fileSystem;
988
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
989
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
990
+ }
991
+ getDefaultTemplatePath(templateName) {
992
+ return this.templateUtility.resolveTemplatePath(
993
+ templateName,
994
+ this.name,
995
+ import.meta.url
996
+ );
997
+ }
998
+ get name() {
999
+ return toKebabCase2(this.componentType);
1000
+ }
1001
+ /**
1002
+ * Validates that the feature config file exists in the target or ancestor directories
1003
+ */
1004
+ validateFeatureConfig(featurePath) {
1005
+ const normalisedPath = normaliseFeaturePath(featurePath);
1006
+ const segments = normalisedPath.split("/");
1007
+ for (let i = segments.length; i > 0; i--) {
1008
+ const pathSegments = segments.slice(0, i);
1009
+ const currentPath = pathSegments.join("/");
1010
+ const featureName = pathSegments[pathSegments.length - 1];
1011
+ const featureDir = getFeatureDir(this.fileSystem, currentPath);
1012
+ const configPath = path7.join(featureDir, `feature.wasp.ts`);
1013
+ if (this.fileSystem.existsSync(configPath)) {
1014
+ return configPath;
1015
+ }
1016
+ }
1017
+ this.logger.error(
1018
+ `Feature config file not found in '${normalisedPath}' or any ancestor directories`
1019
+ );
1020
+ this.logger.error(
1021
+ `Expected to find a feature.wasp.ts config file in one of the feature directories`
1022
+ );
1023
+ throw new Error("Feature config file not found");
1024
+ }
1025
+ /**
1026
+ * Checks if a config item already exists in the feature config
1027
+ */
1028
+ checkConfigExists(configPath, methodName, itemName, force) {
1029
+ const configContent = this.fileSystem.readFileSync(configPath, "utf8");
1030
+ const configExists = hasHelperMethodCall(
1031
+ configContent,
1032
+ methodName,
1033
+ itemName
1034
+ );
1035
+ return this.checkExistence(
1036
+ configExists,
1037
+ `${methodName} config already exists in ${configPath}`,
1038
+ force,
1039
+ `${methodName} config already exists`
1040
+ );
1041
+ }
1042
+ /**
1043
+ * Updates the feature config with a new definition
1044
+ */
1045
+ updateFeatureConfig(featurePath, definition, configPath, configExists, methodName) {
1046
+ this.configGenerator.update(featurePath, definition);
1047
+ this.logger.success(
1048
+ `${configExists ? "Updated" : "Added"} ${methodName} config in: ${configPath}`
1049
+ );
1050
+ }
1051
+ /**
1052
+ * Consolidated helper for updating config files with existence check
1053
+ * This replaces the duplicated updateConfigFile pattern in concrete generators
1054
+ */
1055
+ updateConfigWithCheck(configPath, methodName, entityName, definition, featurePath, force) {
1056
+ const configExists = this.checkConfigExists(
1057
+ configPath,
1058
+ methodName,
1059
+ entityName,
1060
+ force
1061
+ );
1062
+ if (!configExists || force) {
1063
+ this.updateFeatureConfig(
1064
+ featurePath,
1065
+ definition,
1066
+ configPath,
1067
+ configExists,
1068
+ methodName
1069
+ );
1070
+ }
1071
+ }
1072
+ /**
1073
+ * Gets the appropriate directory for a feature based on its path.
1074
+ * @param fileSystem - The filesystem abstraction
1075
+ * @param featurePath - The full feature path
1076
+ * @param type - The type of file being generated
1077
+ * @returns The target directory and import path
1078
+ */
1079
+ getFeatureTargetDir(fileSystem, featurePath, type) {
1080
+ validateFeaturePath3(featurePath);
1081
+ const normalisedPath = normaliseFeaturePath(featurePath);
1082
+ const featureDir = getFeatureDir(fileSystem, normalisedPath);
1083
+ const typeKey = type.toLowerCase();
1084
+ const typeDirectory = TYPE_DIRECTORIES[typeKey];
1085
+ const targetDirectory = path7.join(featureDir, typeDirectory);
1086
+ const importDirectory = `@src/${normalisedPath}/${typeDirectory}`;
1087
+ return { targetDirectory, importDirectory };
1088
+ }
1089
+ /**
1090
+ * Ensures a target directory exists and returns its path
1091
+ */
1092
+ ensureTargetDirectory(featurePath, type) {
1093
+ const { targetDirectory, importDirectory } = this.getFeatureTargetDir(
1094
+ this.fileSystem,
1095
+ featurePath,
1096
+ type
1097
+ );
1098
+ ensureDirectoryExists(this.fileSystem, targetDirectory);
1099
+ return { targetDirectory, importDirectory };
1100
+ }
1101
+ /**
1102
+ * Generate middleware file for API or API namespace
1103
+ */
1104
+ async generateMiddlewareFile(targetFile, name, force) {
1105
+ const replacements = {
1106
+ name,
1107
+ middlewareType: toCamelCase(this.componentType || "")
1108
+ };
1109
+ await this.renderTemplateToFile(
1110
+ "middleware.eta",
1111
+ replacements,
1112
+ targetFile,
1113
+ "Middleware file",
1114
+ force
1115
+ );
1116
+ }
1117
+ };
1118
+
1119
+ // src/generators/base/operation-generator.base.ts
1120
+ import {
1121
+ capitalise,
1122
+ getPlural,
1123
+ handleFatalError as handleFatalError3,
1124
+ toPascalCase as toPascalCase2
1125
+ } from "@ingenyus/swarm";
1126
+ var OperationGeneratorBase = class extends ComponentGeneratorBase {
1127
+ /**
1128
+ * Gets the operation name based on operation type and model name.
1129
+ */
1130
+ getOperationName(operation, modelName, customName) {
1131
+ if (customName) {
1132
+ return customName;
1133
+ }
1134
+ switch (operation) {
1135
+ case OPERATIONS.GETALL:
1136
+ return `getAll${getPlural(modelName)}`;
1137
+ case OPERATIONS.GETFILTERED:
1138
+ return `getFiltered${getPlural(modelName)}`;
1139
+ default:
1140
+ return `${operation}${modelName}`;
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Gets the template path for operation templates.
1145
+ * This method resolves operation templates to the operation generator's directory
1146
+ * instead of the current generator's directory.
1147
+ */
1148
+ getOperationTemplatePath(templateName) {
1149
+ return this.templateUtility.resolveTemplatePath(
1150
+ templateName,
1151
+ "operation",
1152
+ import.meta.url
1153
+ );
1154
+ }
1155
+ /**
1156
+ * Gets the TypeScript type name for an operation.
1157
+ */
1158
+ getOperationTypeName(operation, modelName) {
1159
+ return toPascalCase2(this.getOperationName(operation, modelName));
1160
+ }
1161
+ /**
1162
+ * Generates import statements for an operation.
1163
+ */
1164
+ generateImports(model, modelName, operation) {
1165
+ const imports = [];
1166
+ if (operation !== OPERATIONS.GETALL) {
1167
+ if (needsPrismaImport(model)) {
1168
+ imports.push('import { Prisma } from "@prisma/client";');
1169
+ }
1170
+ imports.push(`import { ${modelName} } from "wasp/entities";`);
1171
+ }
1172
+ imports.push('import { HttpError } from "wasp/server";');
1173
+ imports.push(
1174
+ `import type { ${this.getOperationTypeName(
1175
+ operation,
1176
+ modelName
1177
+ )} } from "wasp/server/operations";`
1178
+ );
1179
+ return imports.join("\n");
1180
+ }
1181
+ /**
1182
+ * Gets the operation type ("query" or "action") for a given operation.
1183
+ */
1184
+ getOperationType(operation) {
1185
+ return operation === OPERATIONS.GETALL || operation === OPERATIONS.GET || operation === OPERATIONS.GETFILTERED ? "query" : "action";
1186
+ }
1187
+ /**
1188
+ * Generates the operation components needed for file and config generation.
1189
+ */
1190
+ async generateOperationComponents(modelName, operation, auth = false, entities = [modelName], isCrudOverride = false, crudName = null, customName) {
1191
+ const model = await getEntityMetadata(modelName);
1192
+ const operationType = this.getOperationType(operation);
1193
+ const operationName = this.getOperationName(
1194
+ operation,
1195
+ modelName,
1196
+ customName
1197
+ );
1198
+ const operationCode = await this.generateOperationCode(
1199
+ model,
1200
+ operation,
1201
+ auth,
1202
+ isCrudOverride,
1203
+ crudName
1204
+ );
1205
+ const configEntry = {
1206
+ operationName,
1207
+ entities,
1208
+ authRequired: auth
1209
+ };
1210
+ return {
1211
+ operationCode,
1212
+ configEntry,
1213
+ operationType,
1214
+ operationName
1215
+ };
1216
+ }
1217
+ /**
1218
+ * Generates the code for an operation.
1219
+ */
1220
+ async generateOperationCode(model, operation, auth = false, isCrudOverride = false, crudName = null) {
1221
+ const operationType = this.getOperationType(operation);
1222
+ const templatePath = this.getOperationTemplatePath(`${operation}.eta`);
1223
+ const allFieldNames = model.fields.map((f) => f.name);
1224
+ const idFields = getIdFields(model);
1225
+ const requiredFields = getRequiredFields(model);
1226
+ const optionalFields = getOptionalFields(model);
1227
+ const jsonFields = getJsonFields(model);
1228
+ const pluralModelName = getPlural(model.name);
1229
+ const pluralModelNameLower = pluralModelName.toLowerCase();
1230
+ const modelNameLower = model.name.toLowerCase();
1231
+ const operationName = this.getOperationName(operation, model.name);
1232
+ const imports = isCrudOverride ? "" : this.generateImports(model, model.name, operation);
1233
+ const jsonTypeHandling = generateJsonTypeHandling(jsonFields);
1234
+ let typeParams = "";
1235
+ switch (operation) {
1236
+ case "create": {
1237
+ const pickRequired = generatePickType(
1238
+ model.name,
1239
+ requiredFields,
1240
+ allFieldNames
1241
+ );
1242
+ const partialOptional = generatePartialType(
1243
+ generatePickType(model.name, optionalFields, allFieldNames)
1244
+ );
1245
+ typeParams = `<${generateIntersectionType(pickRequired, partialOptional)}>`;
1246
+ break;
1247
+ }
1248
+ case "update": {
1249
+ const pickId = generatePickType(model.name, idFields, allFieldNames);
1250
+ const omitId = generateOmitType(model.name, idFields, allFieldNames);
1251
+ const partialRest = generatePartialType(omitId);
1252
+ typeParams = `<${generateIntersectionType(pickId, partialRest)}>`;
1253
+ break;
1254
+ }
1255
+ case "delete":
1256
+ case "get":
1257
+ typeParams = `<${generatePickType(model.name, idFields, allFieldNames)}>`;
1258
+ break;
1259
+ case "getAll":
1260
+ typeParams = `<void>`;
1261
+ break;
1262
+ case "getFiltered":
1263
+ typeParams = `<${generatePartialType(model.name)}>`;
1264
+ break;
1265
+ }
1266
+ const authCheck = auth ? ` if (!context.user) {
1267
+ throw new HttpError(401);
1268
+ }
1269
+
1270
+ ` : "";
1271
+ let typeAnnotation = "";
1272
+ let satisfiesType = "";
1273
+ if (isCrudOverride && crudName) {
1274
+ const opCap = capitalise(operation);
1275
+ if (operationType === "action") {
1276
+ typeAnnotation = `: ${crudName}.${opCap}Action${typeParams}`;
1277
+ } else {
1278
+ typeAnnotation = "";
1279
+ }
1280
+ if (operationType === "query") {
1281
+ satisfiesType = `satisfies ${crudName}.${opCap}Query${typeParams}`;
1282
+ } else {
1283
+ satisfiesType = "";
1284
+ }
1285
+ } else {
1286
+ if (operationType === "action") {
1287
+ typeAnnotation = `: ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
1288
+ } else {
1289
+ typeAnnotation = "";
1290
+ }
1291
+ if (operationType === "query") {
1292
+ satisfiesType = `satisfies ${this.getOperationTypeName(operation, model.name)}${typeParams}`;
1293
+ } else {
1294
+ satisfiesType = "";
1295
+ }
1296
+ }
1297
+ const isCompositeKey = idFields.length > 1;
1298
+ const compositeKeyName = isCompositeKey ? idFields.join("_") : "";
1299
+ const idFieldParams = isCompositeKey ? idFields.join(", ") : idFields[0];
1300
+ const whereClause = isCompositeKey ? `${compositeKeyName}: { ${idFields.map((f) => `${f}`).join(", ")} }` : idFields[0];
1301
+ const replacements = {
1302
+ operationName,
1303
+ modelName: model.name,
1304
+ authCheck,
1305
+ imports,
1306
+ idField: idFields[0],
1307
+ idFieldParams,
1308
+ whereClause,
1309
+ isCompositeKey: String(isCompositeKey),
1310
+ compositeKeyName,
1311
+ jsonTypeHandling,
1312
+ typeAnnotation,
1313
+ satisfiesType,
1314
+ modelNameLower,
1315
+ pluralModelNameLower
1316
+ };
1317
+ return this.templateUtility.processTemplate(templatePath, replacements);
1318
+ }
1319
+ /**
1320
+ * Generates an operation file for a given operation.
1321
+ */
1322
+ generateOperationFile(operationsDir, operationName, operationCode, force = false) {
1323
+ const operationFile = `${operationsDir}/${operationName}.ts`;
1324
+ const fileExists = this.checkFileExists(
1325
+ operationFile,
1326
+ force,
1327
+ "Operation file"
1328
+ );
1329
+ this.writeFile(operationFile, operationCode, "operation file", fileExists);
1330
+ }
1331
+ /**
1332
+ * Copies a directory of operation templates to the target feature directory.
1333
+ * @param templateDir - The source template directory
1334
+ * @param targetDir - The target feature directory
1335
+ */
1336
+ copyOperationTemplates(templateDir, targetDir) {
1337
+ copyDirectory(this.fileSystem, templateDir, targetDir);
1338
+ this.logger.debug(
1339
+ `Copied operation templates from ${templateDir} to ${targetDir}`
1340
+ );
1341
+ }
1342
+ /**
1343
+ * Generates an operation definition for the feature configuration.
1344
+ */
1345
+ getDefinition(operationName, featurePath, entities, operationType, importPath, auth = false) {
1346
+ if (!OPERATION_TYPES.includes(operationType)) {
1347
+ handleFatalError3(`Unknown operation type: ${operationType}`);
1348
+ }
1349
+ const directory = TYPE_DIRECTORIES[operationType];
1350
+ const featureDir = getFeatureImportPath(featurePath);
1351
+ const templatePath = this.templateUtility.resolveTemplatePath(
1352
+ "operation.eta",
1353
+ "config",
1354
+ import.meta.url
1355
+ );
1356
+ return this.templateUtility.processTemplate(templatePath, {
1357
+ operationType: capitalise(operationType),
1358
+ operationName,
1359
+ featureDir,
1360
+ directory,
1361
+ entities: entities.map((e) => `"${e}"`).join(", "),
1362
+ importPath,
1363
+ auth: String(auth)
1364
+ });
1365
+ }
1366
+ };
1367
+
1368
+ // src/generators/action/schema.ts
1369
+ import { SchemaManager, commandRegistry as commandRegistry2 } from "@ingenyus/swarm";
1370
+ import { z as z3 } from "zod";
1371
+ var validActions = Object.values(ACTION_OPERATIONS);
1372
+ var actionSchema = z3.string().min(1, "Action type is required").transform((val) => SchemaManager.findEnumValue(ACTION_OPERATIONS, val)).pipe(
1373
+ z3.enum(ACTION_OPERATIONS, {
1374
+ message: `Invalid action. Must be one of: ${validActions.join(", ")}`
1375
+ })
1376
+ ).meta({ description: "The action operation to generate" }).register(commandRegistry2, {
1377
+ shortName: "o",
1378
+ examples: validActions,
1379
+ helpText: `Available actions: ${validActions.join(", ")}`
1380
+ });
1381
+ var schema2 = z3.object({
1382
+ feature: commonSchemas.feature,
1383
+ operation: actionSchema,
1384
+ dataType: commonSchemas.dataType,
1385
+ name: commonSchemas.name.optional().meta({
1386
+ ...commonSchemas.name.meta() ?? {},
1387
+ description: `${commonSchemas.name.meta()?.description ?? ""} (optional)`
1388
+ }).register(commandRegistry2, commandRegistry2.get(commonSchemas.name) ?? {}),
1389
+ entities: commonSchemas.entities,
1390
+ force: commonSchemas.force,
1391
+ auth: commonSchemas.auth
1392
+ });
1393
+
1394
+ // src/generators/action/action-generator.ts
1395
+ var ActionGenerator = class extends OperationGeneratorBase {
1396
+ get componentType() {
1397
+ return CONFIG_TYPES.ACTION;
1398
+ }
1399
+ description = "Generates a Wasp Action";
1400
+ schema = schema2;
1401
+ async generate(args) {
1402
+ const { dataType, feature, name } = args;
1403
+ const operation = args.operation;
1404
+ const operationType = "action";
1405
+ const entities = args.entities ?? [];
1406
+ if (dataType && !entities.includes(dataType)) {
1407
+ entities.unshift(dataType);
1408
+ }
1409
+ const { operationCode, operationName } = await this.generateOperationComponents(
1410
+ dataType,
1411
+ operation,
1412
+ args.auth,
1413
+ entities,
1414
+ false,
1415
+ null,
1416
+ name
1417
+ );
1418
+ return this.handleGeneratorError(
1419
+ this.componentType,
1420
+ operationName,
1421
+ async () => {
1422
+ const configPath = this.validateFeatureConfig(feature);
1423
+ const { targetDirectory: operationsDir, importDirectory } = this.ensureTargetDirectory(feature, operationType);
1424
+ const importPath = `${importDirectory}/${operationName}`;
1425
+ this.generateOperationFile(
1426
+ operationsDir,
1427
+ operationName,
1428
+ operationCode,
1429
+ args.force || false
1430
+ );
1431
+ const definition = this.getDefinition(
1432
+ operationName,
1433
+ feature,
1434
+ entities,
1435
+ "action",
1436
+ importPath,
1437
+ args.auth
1438
+ );
1439
+ this.updateConfigWithCheck(
1440
+ configPath,
1441
+ "addAction",
1442
+ operationName,
1443
+ definition,
1444
+ feature,
1445
+ args.force || false
1446
+ );
1447
+ }
1448
+ );
1449
+ }
1450
+ };
1451
+
1452
+ // src/generators/api/api-generator.ts
1453
+ import { toCamelCase as toCamelCase2, toPascalCase as toPascalCase3 } from "@ingenyus/swarm";
1454
+
1455
+ // src/generators/api/schema.ts
1456
+ import { commandRegistry as commandRegistry3 } from "@ingenyus/swarm";
1457
+ import { z as z4 } from "zod";
1458
+ var validHttpMethods = API_HTTP_METHODS.map((method) => `${method}`);
1459
+ var schema3 = z4.object({
1460
+ method: z4.string().min(1, "HTTP method is required").transform((val) => val.toUpperCase()).pipe(
1461
+ z4.enum(API_HTTP_METHODS, {
1462
+ message: `Invalid HTTP method. Must be one of: ${validHttpMethods.join(", ")}`
1463
+ })
1464
+ ).meta({ description: "The HTTP method used for this API Endpoint" }).register(commandRegistry3, {
1465
+ shortName: "m",
1466
+ examples: validHttpMethods,
1467
+ helpText: `Must be one of: ${validHttpMethods.join(", ")}`
1468
+ }),
1469
+ feature: commonSchemas.feature,
1470
+ name: commonSchemas.name,
1471
+ path: commonSchemas.path,
1472
+ entities: commonSchemas.entities,
1473
+ auth: commonSchemas.auth,
1474
+ force: commonSchemas.force,
1475
+ customMiddleware: z4.boolean().meta({ description: "Enable custom middleware for this API Endpoint" }).optional().register(commandRegistry3, {
1476
+ shortName: "c",
1477
+ helpText: "Will generate custom middleware file"
1478
+ })
1479
+ });
1480
+
1481
+ // src/generators/api/api-generator.ts
1482
+ var ApiGenerator = class extends ComponentGeneratorBase {
1483
+ get componentType() {
1484
+ return CONFIG_TYPES.API;
1485
+ }
1486
+ description = "Generates a Wasp API Endpoint";
1487
+ schema = schema3;
1488
+ async generate(args) {
1489
+ const apiName = toCamelCase2(args.name);
1490
+ return this.handleGeneratorError(this.componentType, apiName, async () => {
1491
+ const configPath = this.validateFeatureConfig(args.feature);
1492
+ const {
1493
+ targetDirectory: apiTargetDirectory,
1494
+ importDirectory: apiImportDirectory
1495
+ } = this.ensureTargetDirectory(args.feature, this.name);
1496
+ const fileName = `${apiName}.ts`;
1497
+ const targetFile = `${apiTargetDirectory}/${fileName}`;
1498
+ await this.generateApiFile(targetFile, apiName, args);
1499
+ if (args.customMiddleware) {
1500
+ const { targetDirectory: middlewareTargetDirectory } = this.ensureTargetDirectory(args.feature, "middleware");
1501
+ const middlewareFile = `${middlewareTargetDirectory}/${apiName}.ts`;
1502
+ this.generateMiddlewareFile(
1503
+ middlewareFile,
1504
+ apiName,
1505
+ args.force || false
1506
+ );
1507
+ }
1508
+ await this.updateConfigFile(
1509
+ apiName,
1510
+ fileName,
1511
+ apiImportDirectory,
1512
+ args,
1513
+ configPath
1514
+ );
1515
+ });
1516
+ }
1517
+ async generateApiFile(targetFile, apiName, { method, auth = false, force = false }) {
1518
+ const replacements = this.buildTemplateData(apiName, method, auth);
1519
+ await this.renderTemplateToFile(
1520
+ "api.eta",
1521
+ replacements,
1522
+ targetFile,
1523
+ "API Endpoint file",
1524
+ force
1525
+ );
1526
+ }
1527
+ async updateConfigFile(apiName, apiFile, importDirectory, args, configFilePath) {
1528
+ const {
1529
+ feature,
1530
+ force = false,
1531
+ entities,
1532
+ method,
1533
+ path: path9,
1534
+ auth,
1535
+ customMiddleware
1536
+ } = args;
1537
+ const importPath = this.path.join(importDirectory, apiFile);
1538
+ const definition = await this.getConfigDefinition(
1539
+ apiName,
1540
+ feature,
1541
+ Array.isArray(entities) ? entities : entities ? [entities] : [],
1542
+ method,
1543
+ path9,
1544
+ apiFile,
1545
+ auth,
1546
+ importPath,
1547
+ customMiddleware || false
1548
+ );
1549
+ this.updateConfigWithCheck(
1550
+ configFilePath,
1551
+ "addApi",
1552
+ apiName,
1553
+ definition,
1554
+ feature,
1555
+ force
1556
+ );
1557
+ }
1558
+ async getConfigDefinition(apiName, featurePath, entities, method, route, apiFile, auth = false, importPath, customMiddleware = false) {
1559
+ const featureDir = getFeatureImportPath(featurePath);
1560
+ const configTemplatePath = await this.getTemplatePath("config/api.eta");
1561
+ return this.templateUtility.processTemplate(configTemplatePath, {
1562
+ apiName,
1563
+ featureDir,
1564
+ entities: entities.map((e) => `"${e}"`).join(", "),
1565
+ method,
1566
+ route,
1567
+ apiFile,
1568
+ auth: String(auth),
1569
+ importPath,
1570
+ customMiddleware: String(customMiddleware)
1571
+ });
1572
+ }
1573
+ buildTemplateData(apiName, method, auth) {
1574
+ const apiType = toPascalCase3(apiName);
1575
+ const authCheck = auth ? ` if (!context.user) {
1576
+ throw new HttpError(401);
1577
+ }
1578
+
1579
+ ` : "";
1580
+ const methodCheck = method !== "ALL" ? ` if (req.method !== '${method}') {
1581
+ throw new HttpError(405);
1582
+ }
1583
+
1584
+ ` : "";
1585
+ const errorImport = auth || method !== "ALL" ? 'import { HttpError } from "wasp/server";\n' : "";
1586
+ const imports = `${errorImport}import type { ${apiType} } from "wasp/server/api";`;
1587
+ return {
1588
+ imports,
1589
+ apiType,
1590
+ apiName,
1591
+ methodCheck,
1592
+ authCheck
1593
+ };
1594
+ }
1595
+ };
1596
+
1597
+ // src/generators/api-namespace/api-namespace-generator.ts
1598
+ import { toCamelCase as toCamelCase3 } from "@ingenyus/swarm";
1599
+ import path8 from "path";
1600
+
1601
+ // src/generators/api-namespace/schema.ts
1602
+ import { z as z5 } from "zod";
1603
+ var schema4 = z5.object({
1604
+ feature: commonSchemas.feature,
1605
+ name: commonSchemas.name,
1606
+ path: commonSchemas.path,
1607
+ force: commonSchemas.force
1608
+ });
1609
+
1610
+ // src/generators/api-namespace/api-namespace-generator.ts
1611
+ var ApiNamespaceGenerator = class extends ComponentGeneratorBase {
1612
+ get componentType() {
1613
+ return CONFIG_TYPES.API_NAMESPACE;
1614
+ }
1615
+ description = "Generates a Wasp API Namespace";
1616
+ schema = schema4;
1617
+ async generate(args) {
1618
+ const { name, path: namespacePath, feature } = args;
1619
+ const namespaceName = toCamelCase3(name);
1620
+ return this.handleGeneratorError(
1621
+ this.componentType,
1622
+ namespaceName,
1623
+ async () => {
1624
+ const configPath = this.validateFeatureConfig(feature);
1625
+ const { targetDirectory, importDirectory } = this.ensureTargetDirectory(
1626
+ feature,
1627
+ "middleware"
1628
+ );
1629
+ const targetFile = `${targetDirectory}/${namespaceName}.ts`;
1630
+ await this.generateMiddlewareFile(
1631
+ targetFile,
1632
+ namespaceName,
1633
+ args.force || false
1634
+ );
1635
+ await this.updateConfigFile(
1636
+ namespaceName,
1637
+ importDirectory,
1638
+ namespacePath,
1639
+ args,
1640
+ configPath
1641
+ );
1642
+ }
1643
+ );
1644
+ }
1645
+ async updateConfigFile(namespaceName, importDirectory, namespacePath, args, configFilePath) {
1646
+ const { force = false } = args;
1647
+ const importPath = path8.join(importDirectory, namespaceName);
1648
+ const definition = await this.getDefinition(
1649
+ namespaceName,
1650
+ importPath,
1651
+ namespacePath
1652
+ );
1653
+ this.updateConfigWithCheck(
1654
+ configFilePath,
1655
+ "addApiNamespace",
1656
+ namespaceName,
1657
+ definition,
1658
+ args.feature,
1659
+ force
1660
+ );
1661
+ }
1662
+ /**
1663
+ * Generates an apiNamespace definition for the feature configuration.
1664
+ */
1665
+ async getDefinition(namespaceName, middlewareImportPath, pathValue) {
1666
+ const templatePath = this.templateUtility.resolveTemplatePath(
1667
+ "config/api-namespace.eta",
1668
+ "api-namespace",
1669
+ import.meta.url
1670
+ );
1671
+ return this.templateUtility.processTemplate(templatePath, {
1672
+ namespaceName,
1673
+ middlewareImportPath,
1674
+ pathValue
1675
+ });
1676
+ }
1677
+ };
1678
+
1679
+ // src/generators/crud/crud-generator.ts
1680
+ import { getPlural as getPlural2, toCamelCase as toCamelCase4, toPascalCase as toPascalCase4 } from "@ingenyus/swarm";
1681
+
1682
+ // src/generators/crud/schema.ts
1683
+ import { SchemaManager as SchemaManager2, commandRegistry as commandRegistry4 } from "@ingenyus/swarm";
1684
+ import { z as z6 } from "zod";
1685
+ var validCrudOperations = Object.values(CRUD_OPERATIONS);
1686
+ var publicOperations = getCrudOperationsArray();
1687
+ var overrideOperations = getCrudOperationsArray();
1688
+ var excludeOperations = getCrudOperationsArray();
1689
+ var schema5 = z6.object({
1690
+ feature: commonSchemas.feature,
1691
+ name: commonSchemas.name,
1692
+ dataType: commonSchemas.dataType,
1693
+ public: publicOperations.meta({
1694
+ description: "Public CRUD operations (accessible without authentication)"
1695
+ }).register(commandRegistry4, {
1696
+ shortName: "b",
1697
+ examples: ["'get'", "'get' 'getAll'"],
1698
+ helpText: "Operations that can be accessed without authentication."
1699
+ }),
1700
+ override: overrideOperations.meta({ description: "Override existing CRUD operations" }).register(commandRegistry4, {
1701
+ shortName: "v",
1702
+ examples: ["'create'", "'create' 'update'"],
1703
+ helpText: "Operations that will have overriden implementations"
1704
+ }),
1705
+ exclude: excludeOperations.meta({ description: "Exclude specific CRUD operations from generation" }).register(commandRegistry4, {
1706
+ shortName: "x",
1707
+ examples: ["'delete'", "'delete' 'update'"],
1708
+ helpText: "Operations to exclude from generation"
1709
+ }),
1710
+ force: commonSchemas.force
1711
+ });
1712
+ function getCrudOperationsArray() {
1713
+ return z6.array(
1714
+ z6.string().transform((val) => {
1715
+ return SchemaManager2.findEnumValue(CRUD_OPERATIONS, val);
1716
+ }).pipe(
1717
+ z6.enum(CRUD_OPERATIONS, {
1718
+ message: `Must be one or more of: ${validCrudOperations.join(", ")}`
1719
+ })
1720
+ )
1721
+ ).optional();
1722
+ }
1723
+
1724
+ // src/generators/crud/crud-generator.ts
1725
+ var CRUD_OPERATIONS_LIST = [
1726
+ "get",
1727
+ "getAll",
1728
+ "create",
1729
+ "update",
1730
+ "delete"
1731
+ ];
1732
+ var CrudGenerator = class extends OperationGeneratorBase {
1733
+ get componentType() {
1734
+ return CONFIG_TYPES.CRUD;
1735
+ }
1736
+ description = "Generates a Wasp CRUD operation";
1737
+ schema = schema5;
1738
+ async generate(args) {
1739
+ const { dataType, feature } = args;
1740
+ const crudName = toCamelCase4(getPlural2(dataType));
1741
+ const crudType = toPascalCase4(crudName);
1742
+ return this.handleGeneratorError(this.componentType, crudName, async () => {
1743
+ const configPath = this.validateFeatureConfig(feature);
1744
+ const { targetDirectory } = this.ensureTargetDirectory(
1745
+ feature,
1746
+ this.componentType.toLowerCase()
1747
+ );
1748
+ if ((args.override?.length ?? 0) > 0) {
1749
+ const targetFile = `${targetDirectory}/${crudName}.ts`;
1750
+ const operations = await this.getOperationsCode(
1751
+ dataType,
1752
+ crudName,
1753
+ args
1754
+ );
1755
+ await this.generateCrudFile(
1756
+ targetFile,
1757
+ dataType,
1758
+ operations,
1759
+ crudType,
1760
+ args
1761
+ );
1762
+ }
1763
+ await this.updateConfigFile(
1764
+ feature,
1765
+ crudName,
1766
+ dataType,
1767
+ args,
1768
+ configPath
1769
+ );
1770
+ });
1771
+ }
1772
+ async generateCrudFile(targetFile, dataType, operations, crudName, args) {
1773
+ const { override = [], force = false } = args;
1774
+ const model = await getEntityMetadata(dataType);
1775
+ const imports = this.generateCrudImports(
1776
+ model,
1777
+ dataType,
1778
+ crudName,
1779
+ override
1780
+ );
1781
+ const replacements = {
1782
+ imports,
1783
+ operations
1784
+ };
1785
+ await this.renderTemplateToFile(
1786
+ "crud.eta",
1787
+ replacements,
1788
+ targetFile,
1789
+ "CRUD file",
1790
+ force
1791
+ );
1792
+ }
1793
+ /**
1794
+ * Generates import statements for an operation.
1795
+ */
1796
+ generateCrudImports(model, modelName, crudName, operations) {
1797
+ const imports = [];
1798
+ if (operations.some((operation) => operation !== "getAll")) {
1799
+ if (needsPrismaImport(model)) {
1800
+ imports.push('import { Prisma } from "@prisma/client";');
1801
+ }
1802
+ imports.push(`import { type ${modelName} } from "wasp/entities";`);
1803
+ }
1804
+ imports.push('import { HttpError } from "wasp/server";');
1805
+ imports.push(`import { type ${crudName} } from "wasp/server/crud";`);
1806
+ return imports.join("\n");
1807
+ }
1808
+ async updateConfigFile(feature, crudName, dataType, args, configPath) {
1809
+ const operations = this.buildOperations(args);
1810
+ const definition = this.getDefinition(crudName, dataType, operations);
1811
+ this.updateConfigWithCheck(
1812
+ configPath,
1813
+ "addCrud",
1814
+ crudName,
1815
+ definition,
1816
+ feature,
1817
+ args.force || false
1818
+ );
1819
+ }
1820
+ buildOperations(args) {
1821
+ const {
1822
+ public: publicOps = [],
1823
+ override: overrideOps = [],
1824
+ exclude: excludeOps = []
1825
+ } = args;
1826
+ return CRUD_OPERATIONS_LIST.reduce(
1827
+ (acc, operation) => {
1828
+ if (excludeOps.includes(operation)) {
1829
+ return acc;
1830
+ }
1831
+ const operationConfig = {};
1832
+ if (publicOps.includes(operation)) {
1833
+ operationConfig.isPublic = true;
1834
+ }
1835
+ if (overrideOps.includes(operation)) {
1836
+ operationConfig.override = true;
1837
+ }
1838
+ acc[operation] = operationConfig;
1839
+ return acc;
1840
+ },
1841
+ {}
1842
+ );
1843
+ }
1844
+ /**
1845
+ * Generates operation code for overridden CRUD operations and returns as a single string.
1846
+ */
1847
+ async getOperationsCode(dataType, crudName, args) {
1848
+ const { override = [], public: publicOps = [] } = args;
1849
+ if (override.length === 0) {
1850
+ return "";
1851
+ }
1852
+ const operationCodes = [];
1853
+ for (const operation of override) {
1854
+ const { operationCode } = await this.generateOperationComponents(
1855
+ dataType,
1856
+ operation,
1857
+ !publicOps.includes(operation),
1858
+ [dataType],
1859
+ true,
1860
+ toPascalCase4(crudName)
1861
+ );
1862
+ operationCodes.push(operationCode.replace(/^[\r\n]/, ""));
1863
+ }
1864
+ return operationCodes.join("");
1865
+ }
1866
+ /**
1867
+ * Generates a CRUD definition for the feature configuration.
1868
+ */
1869
+ getDefinition(crudName, dataType, operations) {
1870
+ const templatePath = this.templateUtility.resolveTemplatePath(
1871
+ "config/crud.eta",
1872
+ "crud",
1873
+ import.meta.url
1874
+ );
1875
+ 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");
1876
+ return this.templateUtility.processTemplate(templatePath, {
1877
+ crudName: toPascalCase4(crudName),
1878
+ dataType,
1879
+ operations: operationsStr
1880
+ });
1881
+ }
1882
+ };
1883
+
1884
+ // src/generators/job/job-generator.ts
1885
+ import { capitalise as capitalise2, toCamelCase as toCamelCase5 } from "@ingenyus/swarm";
1886
+
1887
+ // src/generators/job/schema.ts
1888
+ import { commandRegistry as commandRegistry5 } from "@ingenyus/swarm";
1889
+ import { z as z7 } from "zod";
1890
+ var cronSchema = z7.string().optional().refine(
1891
+ (val) => {
1892
+ if (!val) return true;
1893
+ const parts = val.trim().split(/\s+/);
1894
+ if (parts.length !== 5) return false;
1895
+ const [minute, hour, day, month, weekday] = parts;
1896
+ const validateCronField = (field, min, max) => {
1897
+ if (field === "*") return true;
1898
+ const rangeRegex = /^(\d+)(-(\d+))?(,(\d+)(-(\d+))?)*(\/(\d+))?$/;
1899
+ if (!rangeRegex.test(field)) return false;
1900
+ const items = field.split(",");
1901
+ for (const item of items) {
1902
+ if (item.includes("/")) {
1903
+ const [base, step] = item.split("/");
1904
+ const stepNum = parseInt(step, 10);
1905
+ if (isNaN(stepNum) || stepNum <= 0) return false;
1906
+ if (base === "*") continue;
1907
+ const baseNum = parseInt(base, 10);
1908
+ if (isNaN(baseNum) || baseNum < min || baseNum > max) return false;
1909
+ } else if (item.includes("-")) {
1910
+ const [start, end] = item.split("-");
1911
+ const startNum = parseInt(start, 10);
1912
+ const endNum = parseInt(end, 10);
1913
+ if (isNaN(startNum) || isNaN(endNum) || startNum < min || endNum > max || startNum > endNum)
1914
+ return false;
1915
+ } else {
1916
+ const num = parseInt(item, 10);
1917
+ if (isNaN(num) || num < min || num > max) return false;
1918
+ }
1919
+ }
1920
+ return true;
1921
+ };
1922
+ return validateCronField(minute, 0, 59) && validateCronField(hour, 0, 23) && validateCronField(day, 1, 31) && validateCronField(month, 1, 12) && validateCronField(weekday, 0, 6);
1923
+ },
1924
+ {
1925
+ message: 'Cron expression must be a valid five-field format: (minute hour day month weekday), e.g. "0 9 * * *"'
1926
+ }
1927
+ ).meta({ description: "Cron schedule expression for the job" }).register(commandRegistry5, {
1928
+ shortName: "c",
1929
+ examples: ["0 9 * * *", "*/15 * * * *", "0 0 1 * *"],
1930
+ helpText: "Five-field cron expression: minute hour day month weekday"
1931
+ });
1932
+ var argsSchema = z7.string().optional().refine(
1933
+ (val) => {
1934
+ if (!val) return true;
1935
+ try {
1936
+ const parsed = JSON.parse(val);
1937
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
1938
+ } catch {
1939
+ return false;
1940
+ }
1941
+ },
1942
+ {
1943
+ message: "Args must be a valid JSON object string"
1944
+ }
1945
+ ).meta({ description: "Arguments to pass to the job function when executed" }).register(commandRegistry5, {
1946
+ shortName: "a",
1947
+ examples: ['{"userId": 123}', '{"type": "cleanup", "batchSize": 100}'],
1948
+ helpText: "JSON object string that will be passed to the job function"
1949
+ });
1950
+ var schema6 = z7.object({
1951
+ feature: commonSchemas.feature,
1952
+ name: commonSchemas.name,
1953
+ entities: commonSchemas.entities,
1954
+ cron: cronSchema,
1955
+ args: argsSchema,
1956
+ force: commonSchemas.force
1957
+ });
1958
+
1959
+ // src/generators/job/job-generator.ts
1960
+ var JobGenerator = class extends ComponentGeneratorBase {
1961
+ get componentType() {
1962
+ return CONFIG_TYPES.JOB;
1963
+ }
1964
+ description = "Generates a Wasp Job";
1965
+ schema = schema6;
1966
+ async generate(args) {
1967
+ const jobName = toCamelCase5(args.name);
1968
+ return this.handleGeneratorError(this.componentType, jobName, async () => {
1969
+ const configPath = this.validateFeatureConfig(args.feature);
1970
+ const { targetDirectory } = this.ensureTargetDirectory(
1971
+ args.feature,
1972
+ this.componentType.toLowerCase()
1973
+ );
1974
+ const targetFile = `${targetDirectory}/${jobName}.ts`;
1975
+ await this.generateJobFile(targetFile, jobName, args);
1976
+ this.updateConfigFile(args.feature, jobName, args, configPath);
1977
+ });
1978
+ }
1979
+ async generateJobFile(targetFile, jobName, args) {
1980
+ const jobType = capitalise2(jobName);
1981
+ const entities = args.entities ?? [];
1982
+ let imports = `import type { ${jobType} } from 'wasp/server/jobs';
1983
+ `;
1984
+ if (entities.length > 0) {
1985
+ imports += `import { ${entities.join(", ")} } from 'wasp/entities';
1986
+ `;
1987
+ }
1988
+ const replacements = {
1989
+ imports,
1990
+ jobType,
1991
+ jobName
1992
+ };
1993
+ await this.renderTemplateToFile(
1994
+ "job.eta",
1995
+ replacements,
1996
+ targetFile,
1997
+ "job worker",
1998
+ args.force || false
1999
+ );
2000
+ }
2001
+ updateConfigFile(featurePath, jobName, args, configPath) {
2002
+ const {
2003
+ entities = [],
2004
+ cron = "0 0 * * *",
2005
+ args: executionArgs = "{}",
2006
+ force = false
2007
+ } = args;
2008
+ const definition = this.getDefinition(
2009
+ jobName,
2010
+ entities,
2011
+ cron,
2012
+ executionArgs
2013
+ );
2014
+ this.updateConfigWithCheck(
2015
+ configPath,
2016
+ "job",
2017
+ jobName,
2018
+ definition,
2019
+ featurePath,
2020
+ force
2021
+ );
2022
+ }
2023
+ /**
2024
+ * Generates a job definition for the feature configuration.
2025
+ */
2026
+ getDefinition(jobName, entities, cron, args) {
2027
+ const templatePath = this.getDefaultTemplatePath("config/job.eta");
2028
+ return this.templateUtility.processTemplate(templatePath, {
2029
+ jobName,
2030
+ entities: entities.map((e) => `"${e}"`).join(", "),
2031
+ cron,
2032
+ args
2033
+ });
2034
+ }
2035
+ };
2036
+
2037
+ // src/generators/query/schema.ts
2038
+ import { SchemaManager as SchemaManager3, commandRegistry as commandRegistry6 } from "@ingenyus/swarm";
2039
+ import { z as z8 } from "zod";
2040
+ var validQueries = Object.values(QUERY_OPERATIONS);
2041
+ var querySchema = z8.string().min(1, "Query type is required").transform((val) => SchemaManager3.findEnumValue(QUERY_OPERATIONS, val)).pipe(
2042
+ z8.enum(QUERY_OPERATIONS, {
2043
+ message: `Invalid query. Must be one of: ${validQueries.join(", ")}`
2044
+ })
2045
+ ).meta({ description: "The query operation to generate" }).register(commandRegistry6, {
2046
+ shortName: "o",
2047
+ examples: validQueries,
2048
+ helpText: `Available queries: ${validQueries.join(", ")}`
2049
+ });
2050
+ var schema7 = z8.object({
2051
+ feature: commonSchemas.feature,
2052
+ operation: querySchema,
2053
+ dataType: commonSchemas.dataType,
2054
+ name: commonSchemas.name.optional().meta({
2055
+ ...commonSchemas.name.meta() ?? {},
2056
+ description: `${commonSchemas.name.meta()?.description ?? ""} (optional)`
2057
+ }).register(commandRegistry6, commandRegistry6.get(commonSchemas.name) ?? {}),
2058
+ entities: commonSchemas.entities,
2059
+ force: commonSchemas.force,
2060
+ auth: commonSchemas.auth
2061
+ });
2062
+
2063
+ // src/generators/query/query-generator.ts
2064
+ var QueryGenerator = class extends OperationGeneratorBase {
2065
+ get componentType() {
2066
+ return CONFIG_TYPES.QUERY;
2067
+ }
2068
+ description = "Generates a Wasp Query";
2069
+ schema = schema7;
2070
+ async generate(args) {
2071
+ const { dataType, feature, name } = args;
2072
+ const operation = args.operation;
2073
+ const operationType = "query";
2074
+ const entities = args.entities ?? [];
2075
+ if (dataType && !entities.includes(dataType)) {
2076
+ entities.unshift(dataType);
2077
+ }
2078
+ const { operationCode, operationName } = await this.generateOperationComponents(
2079
+ dataType,
2080
+ operation,
2081
+ args.auth,
2082
+ entities,
2083
+ false,
2084
+ null,
2085
+ name
2086
+ );
2087
+ return this.handleGeneratorError(
2088
+ this.componentType,
2089
+ operationName,
2090
+ async () => {
2091
+ const configPath = this.validateFeatureConfig(feature);
2092
+ const { targetDirectory: operationsDir, importDirectory } = this.ensureTargetDirectory(feature, operationType);
2093
+ const importPath = `${importDirectory}/${operationName}`;
2094
+ this.generateOperationFile(
2095
+ operationsDir,
2096
+ operationName,
2097
+ operationCode,
2098
+ args.force || false
2099
+ );
2100
+ const definition = this.getDefinition(
2101
+ operationName,
2102
+ feature,
2103
+ entities,
2104
+ "query",
2105
+ importPath,
2106
+ args.auth
2107
+ );
2108
+ this.updateConfigWithCheck(
2109
+ configPath,
2110
+ "addQuery",
2111
+ operationName,
2112
+ definition,
2113
+ feature,
2114
+ args.force || false
2115
+ );
2116
+ }
2117
+ );
2118
+ }
2119
+ };
2120
+
2121
+ // src/generators/route/route-generator.ts
2122
+ import {
2123
+ formatDisplayName,
2124
+ toCamelCase as toCamelCase6,
2125
+ toPascalCase as toPascalCase5
2126
+ } from "@ingenyus/swarm";
2127
+
2128
+ // src/generators/route/schema.ts
2129
+ import { z as z9 } from "zod";
2130
+ var schema8 = z9.object({
2131
+ feature: commonSchemas.feature,
2132
+ name: commonSchemas.name,
2133
+ path: commonSchemas.path,
2134
+ auth: commonSchemas.auth,
2135
+ force: commonSchemas.force
2136
+ });
2137
+
2138
+ // src/generators/route/route-generator.ts
2139
+ var RouteGenerator = class extends ComponentGeneratorBase {
2140
+ get componentType() {
2141
+ return CONFIG_TYPES.ROUTE;
2142
+ }
2143
+ description = "Generates a Wasp Page and Route";
2144
+ schema = schema8;
2145
+ async generate(args) {
2146
+ const { path: routePath, name, feature } = args;
2147
+ const routeName = toCamelCase6(name || getRouteNameFromPath(routePath));
2148
+ const componentName = toPascalCase5(routeName);
2149
+ const fileName = `${componentName}.tsx`;
2150
+ return this.handleGeneratorError(
2151
+ this.componentType,
2152
+ routeName,
2153
+ async () => {
2154
+ const configPath = this.validateFeatureConfig(feature);
2155
+ const { targetDirectory } = this.ensureTargetDirectory(feature, "page");
2156
+ const targetFile = `${targetDirectory}/${fileName}`;
2157
+ await this.generatePageFile(targetFile, componentName, args);
2158
+ this.updateConfigFile(feature, routeName, routePath, args, configPath);
2159
+ }
2160
+ );
2161
+ }
2162
+ async generatePageFile(targetFile, componentName, args) {
2163
+ const templatePath = "files/client/page.eta";
2164
+ const replacements = {
2165
+ componentName,
2166
+ displayName: formatDisplayName(componentName)
2167
+ };
2168
+ await this.renderTemplateToFile(
2169
+ "page.eta",
2170
+ replacements,
2171
+ targetFile,
2172
+ "Page file",
2173
+ args.force || false
2174
+ );
2175
+ }
2176
+ updateConfigFile(featurePath, routeName, routePath, args, configPath) {
2177
+ const definition = this.getDefinition(
2178
+ routeName,
2179
+ routePath,
2180
+ featurePath,
2181
+ args.auth
2182
+ );
2183
+ this.updateConfigWithCheck(
2184
+ configPath,
2185
+ "addRoute",
2186
+ routeName,
2187
+ definition,
2188
+ featurePath,
2189
+ args.force || false
2190
+ );
2191
+ }
2192
+ /**
2193
+ * Generates a route definition for the feature configuration.
2194
+ */
2195
+ getDefinition(routeName, routePath, featurePath, auth = false) {
2196
+ const templatePath = this.getDefaultTemplatePath("config/route.eta");
2197
+ return this.templateUtility.processTemplate(templatePath, {
2198
+ featureName: featurePath.split("/").pop() || featurePath,
2199
+ routeName,
2200
+ routePath,
2201
+ auth: String(auth)
2202
+ });
2203
+ }
2204
+ };
2205
+ export {
2206
+ ActionGenerator,
2207
+ ApiGenerator,
2208
+ ApiNamespaceGenerator,
2209
+ CrudGenerator,
2210
+ FeatureGenerator,
2211
+ JobGenerator,
2212
+ QueryGenerator,
2213
+ RouteGenerator,
2214
+ WaspConfigGenerator
2215
+ };